diff --git a/.circleci/config.yml b/.circleci/config.yml index 12a5e1bb7..e0aa3d850 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -29,15 +29,14 @@ jobs: - run: git config --global user.email "circle@circleci.com" - run: git config --global user.name "CircleCI" - run: chmod -Rv +x scripts/ - - run: ./scripts/build.sh - - run: ./scripts/inst.sh --setup --remote + - run: ./akarin build # Save dependency cache - save_cache: key: v1-dep-{{ .Branch }}-{{ epoch }} paths: - ~/.m2 # Test - - run: yes|cp -rf ./akarin-*.jar $CIRCLE_ARTIFACTS + - run: cp akarin-paperclip.jar $CIRCLE_ARTIFACTS # Teardown # Save test results - store_test_results: diff --git a/.gitignore b/.gitignore index 574c43345..0d7180e46 100644 --- a/.gitignore +++ b/.gitignore @@ -1,57 +1,43 @@ -# Eclipse stuff -.classpath -.project -.settings/ -.factorypath -.externalToolBuilders/ +# Akarin +Akarin-Server +Akarin-API +mc-dev +.idea +testserver +run +/akarin-paperclip.jar -# netbeans -nbproject/ -nbactions.xml +# Compiled class file +*.class -# we use maven! -build.xml +# Log file +*.log -# maven -target/ -dependency-reduced-pom.xml +# BlueJ files +*.ctxt -# vim -.*.sw[a-p] +# Mobile Tools for Java (J2ME) +.mtj.tmp/ -# various other potential build files -build/ -bin/ -dist/ -manifest.mf - -work/1.* -work/Minecraft -work/BuildData -work/Bukkit -work/CraftBukkit -work/Paperclip -work/Spigot -work/Spigot-Server -work/Spigot-API -work/*.jar -work/test-server - -# Mac filesystem dust -.DS_Store/ -.DS_Store - -# intellij +# IntelliJ *.iml *.ipr *.iws .idea/ out/ -# Linux temp files -*~ +# Maven +target/ -# other stuff -run/ +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* -akarin-*.jar \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index 6bf17fdbc..76ec94597 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,4 @@ -[submodule "work/Paper"] - path = work/Paper +[submodule "Paper"] + path = Paper url = https://github.com/PaperMC/Paper.git branch = master diff --git a/.gradle/6.2.2/executionHistory/executionHistory.bin b/.gradle/6.2.2/executionHistory/executionHistory.bin deleted file mode 100644 index 7c2e6cd73..000000000 Binary files a/.gradle/6.2.2/executionHistory/executionHistory.bin and /dev/null differ diff --git a/.gradle/6.2.2/executionHistory/executionHistory.lock b/.gradle/6.2.2/executionHistory/executionHistory.lock deleted file mode 100644 index 78eb4dc14..000000000 Binary files a/.gradle/6.2.2/executionHistory/executionHistory.lock and /dev/null differ diff --git a/.gradle/6.2.2/fileChanges/last-build.bin b/.gradle/6.2.2/fileChanges/last-build.bin deleted file mode 100644 index f76dd238a..000000000 Binary files a/.gradle/6.2.2/fileChanges/last-build.bin and /dev/null differ diff --git a/.gradle/6.2.2/fileContent/fileContent.lock b/.gradle/6.2.2/fileContent/fileContent.lock deleted file mode 100644 index c232dcf05..000000000 Binary files a/.gradle/6.2.2/fileContent/fileContent.lock and /dev/null differ diff --git a/.gradle/6.2.2/fileHashes/fileHashes.lock b/.gradle/6.2.2/fileHashes/fileHashes.lock deleted file mode 100644 index 76bca900f..000000000 Binary files a/.gradle/6.2.2/fileHashes/fileHashes.lock and /dev/null differ diff --git a/.gradle/6.2.2/gc.properties b/.gradle/6.2.2/gc.properties deleted file mode 100644 index e69de29bb..000000000 diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock deleted file mode 100644 index 920ecad05..000000000 Binary files a/.gradle/buildOutputCleanup/buildOutputCleanup.lock and /dev/null differ diff --git a/.gradle/buildOutputCleanup/cache.properties b/.gradle/buildOutputCleanup/cache.properties deleted file mode 100644 index ee5484781..000000000 --- a/.gradle/buildOutputCleanup/cache.properties +++ /dev/null @@ -1,2 +0,0 @@ -#Sat Mar 28 16:11:26 MST 2020 -gradle.version=6.2.2 diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin deleted file mode 100644 index 7c2e6cd73..000000000 Binary files a/.gradle/buildOutputCleanup/outputFiles.bin and /dev/null differ diff --git a/.gradle/checksums/checksums.lock b/.gradle/checksums/checksums.lock deleted file mode 100644 index a4f8f7ea7..000000000 Binary files a/.gradle/checksums/checksums.lock and /dev/null differ diff --git a/.gradle/checksums/md5-checksums.bin b/.gradle/checksums/md5-checksums.bin deleted file mode 100644 index b25f88d85..000000000 Binary files a/.gradle/checksums/md5-checksums.bin and /dev/null differ diff --git a/.gradle/checksums/sha1-checksums.bin b/.gradle/checksums/sha1-checksums.bin deleted file mode 100644 index b86a85540..000000000 Binary files a/.gradle/checksums/sha1-checksums.bin and /dev/null differ diff --git a/.gradle/vcs-1/gc.properties b/.gradle/vcs-1/gc.properties deleted file mode 100644 index e69de29bb..000000000 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 49eecfa0e..000000000 --- a/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -language: java -dist: trusty -jdk: - - oraclejdk8 -install: true -script: - - git config --global user.email "circle@circleci.com" - - git config --global user.name "CircleCI" - - chmod -Rv +x scripts/ - - ./scripts/build.sh - - ./scripts/inst.sh --setup --remote -after_success: - - rm -rf push - - mkdir push - - cp ./target/*.jar ./push/ -deploy: - skip_cleanup: true - provider: releases - api_key: - secure: $Github_token - file: - - ./push/* - file_glob: true - on: - tags: true diff --git a/work/Paper b/Paper similarity index 100% rename from work/Paper rename to Paper diff --git a/akarin b/akarin new file mode 100755 index 000000000..6255e9f4f --- /dev/null +++ b/akarin @@ -0,0 +1,133 @@ +#!/usr/bin/env bash + +# exit immediately if a command exits with a non-zero status +set -e +# get base dir regardless of execution location +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +SOURCE=$([[ "$SOURCE" = /* ]] && echo "$SOURCE" || echo "$PWD/${SOURCE#./}") +basedir=$(dirname "$SOURCE") +. "$basedir"/scripts/init.sh + +paperstash() { + STASHED=$(git stash) +} + +paperunstash() { + if [[ "$STASHED" != "No local changes to save" ]] ; then + git stash pop + fi +} + +case "$1" in + "rb" | "rbp" | "rebuild") + ( + set -e + cd "$basedir" + scripts/rebuildpatches.sh "$basedir" + ) + ;; + "p" | "patch" | "apply") + ( + set -e + cd "$basedir" + if [ "$2" != "fast" ]; then + scripts/upstream.sh + fi + scripts/apply.sh "$basedir" + ) + ;; + "b" | "bu" | "build") + ( + basedir + mvn -N install + cd ${FORK_NAME}-API + mvn -e clean install && cd ../${FORK_NAME}-Server && mvn -e clean install + ) + ;; + "jar" | "paperclip") + ( + basedir + cd "$basedir" + if [ "$2" != "fast" ]; then + scripts/upstream.sh + fi + ./scripts/apply.sh "$basedir" + cd "$basedir" + mvn -N install + cd ${FORK_NAME}-API + mvn -e clean install && cd ../${FORK_NAME}-Server && mvn -e clean install + cd "$basedir" + ./scripts/paperclip.sh + ) + ;; + "d" | "de" | "deploy") + ( + basedir + mvn -N install + cd ${FORK_NAME}-API + mvn clean deploy && cd ../${FORK_NAME}-Server && mvn clean install + ) + ;; + "up" | "upstream") + ( + cd "$basedir" + scripts/upstream.sh "$2" + ) + ;; + "r" | "root") + cd "$basedir" + ;; + "a" | "api") + cd "$basedir/Akarin-API" + ;; + "s" | "server") + cd "$basedir/Akarin-Server" + ;; + "setup") + if [[ -f ~/.bashrc ]] ; then + NAME="ec" + if [[ ! -z "${2+x}" ]] ; then + NAME="$2" + fi + (grep "alias $NAME=" ~/.bashrc > /dev/null) && (sed -i "s|alias $NAME=.*|alias $NAME='. $SOURCE'|g" ~/.bashrc) || (echo "alias $NAME='. $SOURCE'" >> ~/.bashrc) + alias "$NAME=. $SOURCE" + echo "You can now just type '$NAME' at any time to access the paper tool." + fi + ;; + *) + echo "Akarin build tool command. This provides a variety of commands to build and manage the PaperMC build" + echo "environment. For all of the functionality of this command to be available, you must first run the" + echo "'setup' command. View below for details. For essential building and patching, you do not need to do the setup." + echo "" + echo " Normal commands:" + echo " * rb, rebuild | Rebuild patches, can be called from anywhere." + echo " * p, patch | Apply all patches to top of Paper without building it. Can be run from anywhere." + echo " * up, upstream | Build Paper upstream, pass arg up to update paper. Can be run from anywhere." + echo " * b, build | Build API and Server but no deploy. Can be ran anywhere." + echo " * d, deploy | Build and Deploy API jar and build Server. Can be ran anywhere." + echo "" + echo " These commands require the setup command before use:" + echo " * r, root | Change directory to the root of the project." + echo " * a. api | Move to the Paper-API directory." + echo " * s, server | Move to the Paper-Server directory." + echo " * e, edit | Use to edit a specific patch, give it the argument \"server\" or \"api\"" + echo " | respectively to edit the correct project. Use the argument \"continue\" after" + echo " | the changes have been made to finish and rebuild patches. Can be called from anywhere." + echo "" + echo " * setup | Add an alias to .bashrc to allow full functionality of this script. Run as:" + echo " | . ./akarin setup" + echo " | After you run this command you'll be able to just run 'akarin' from anywhere." + echo " | The default name for the resulting alias is 'akarin', you can give an argument to override" + echo " | this default, such as:" + echo " | . ./akarin setup example" + echo " | Which will allow you to run 'example' instead." + ;; +esac + +unset -f paperstash +unset -f paperunstash diff --git a/api/pom.xml b/api/pom.xml deleted file mode 100644 index 55afe1747..000000000 --- a/api/pom.xml +++ /dev/null @@ -1,245 +0,0 @@ - - - 4.0.0 - - akarin-api - 1.15.2-R0.1-SNAPSHOT - jar - - - com.destroystokyo.paper - paper-parent - dev-SNAPSHOT - - - Akarin-API - https://github.com/Akarin-project/Akarin - An enhanced plugin API for Minecraft servers. - - - - - 1.8 - 1.8 - UTF-8 - - - - - - spigotmc-public - https://hub.spigotmc.org/nexus/content/groups/public/ - - - sonatype - https://oss.sonatype.org/content/groups/public/ - - - - - - spigotmc-public - https://hub.spigotmc.org/nexus/content/groups/public/ - - - - - - it.unimi.dsi - fastutil - 8.2.2 - provided - - - commons-lang - commons-lang - 2.6 - compile - - - com.googlecode.json-simple - json-simple - 1.1.1 - compile - - - - com.google.code.findbugs - jsr305 - 1.3.9 - compile - - - - com.google.guava - guava - 21.0 - compile - - - - com.google.code.gson - gson - 2.8.0 - compile - - - net.md-5 - bungeecord-chat - 1.13-SNAPSHOT - jar - compile - - - org.yaml - snakeyaml - 1.23 - compile - - - - org.jetbrains - annotations-java5 - 17.0.0 - provided - - - - org.slf4j - slf4j-api - 1.7.25 - compile - - - - junit - junit - 4.12 - test - - - org.hamcrest - hamcrest-library - 1.3 - test - - - org.ow2.asm - asm-tree - 7.1 - test - - - - org.ow2.asm - asm - 7.1 - - - org.ow2.asm - asm-commons - 7.1 - - - - com.koloboke - koloboke-api-jdk8 - 1.0.0 - provided - - - com.koloboke - koloboke-impl-jdk8 - 1.0.0 - runtime - - - - - clean install - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - - - org.codehaus.plexus - plexus-compiler-eclipse - 2.8.5-spigotmc - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - - org.bukkit - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.1.1 - - - package - - shade - - - - - ${project.build.directory}/dependency-reduced-pom.xml - - true - - - - - - - - development - - false - - - - - org.codehaus.mojo - animal-sniffer-maven-plugin - 1.17 - - - process-classes - - check - - - - - - org.codehaus.mojo.signature - java17 - 1.0 - - - - - - - - diff --git a/api/src/main/java/co/aikar/timings/FullServerTickHandler.java b/api/src/main/java/co/aikar/timings/FullServerTickHandler.java deleted file mode 100644 index 64531fcce..000000000 --- a/api/src/main/java/co/aikar/timings/FullServerTickHandler.java +++ /dev/null @@ -1,84 +0,0 @@ -package co.aikar.timings; - -import static co.aikar.timings.TimingsManager.*; - -import org.jetbrains.annotations.NotNull; - -public class FullServerTickHandler extends TimingHandler { - private static final TimingIdentifier IDENTITY = new TimingIdentifier("Minecraft", "Full Server Tick", null); - final TimingData minuteData; - double avgFreeMemory = -1D; - double avgUsedMemory = -1D; - FullServerTickHandler() { - super(IDENTITY); - minuteData = new TimingData(id); - - TIMING_MAP.put(IDENTITY, this); - } - - @NotNull - @Override - public Timing startTiming() { - if (TimingsManager.needsFullReset) { - TimingsManager.resetTimings(); - } else if (TimingsManager.needsRecheckEnabled) { - TimingsManager.recheckEnabled(); - } - return super.startTiming(); - } - - @Override - public void stopTiming() { - super.stopTiming(); - if (!isEnabled()) { - return; - } - if (TimingHistory.timedTicks % 20 == 0) { - final Runtime runtime = Runtime.getRuntime(); - double usedMemory = runtime.totalMemory() - runtime.freeMemory(); - double freeMemory = runtime.maxMemory() - usedMemory; - if (this.avgFreeMemory == -1) { - this.avgFreeMemory = freeMemory; - } else { - this.avgFreeMemory = (this.avgFreeMemory * (59 / 60D)) + (freeMemory * (1 / 60D)); - } - - if (this.avgUsedMemory == -1) { - this.avgUsedMemory = usedMemory; - } else { - this.avgUsedMemory = (this.avgUsedMemory * (59 / 60D)) + (usedMemory * (1 / 60D)); - } - } - - long start = System.nanoTime(); - TimingsManager.tick(); - long diff = System.nanoTime() - start; - TIMINGS_TICK.addDiff(diff, null); - // addDiff for TIMINGS_TICK incremented this, bring it back down to 1 per tick. - record.setCurTickCount(record.getCurTickCount()-1); - - minuteData.setCurTickTotal(record.getCurTickTotal()); - minuteData.setCurTickCount(1); - - boolean violated = isViolated(); - minuteData.processTick(violated); - TIMINGS_TICK.processTick(violated); - processTick(violated); - - - if (TimingHistory.timedTicks % 1200 == 0) { - MINUTE_REPORTS.add(new TimingHistory.MinuteReport()); - TimingHistory.resetTicks(false); - minuteData.reset(); - } - if (TimingHistory.timedTicks % Timings.getHistoryInterval() == 0) { - TimingsManager.HISTORY.add(new TimingHistory()); - TimingsManager.resetTimings(); - } - TimingsExport.reportTimings(); - } - - boolean isViolated() { - return record.getCurTickTotal() > 50000000; - } -} diff --git a/api/src/main/java/co/aikar/timings/NullTimingHandler.java b/api/src/main/java/co/aikar/timings/NullTimingHandler.java deleted file mode 100644 index 9b45ce887..000000000 --- a/api/src/main/java/co/aikar/timings/NullTimingHandler.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public final class NullTimingHandler implements Timing { - public static final Timing NULL = new NullTimingHandler(); - @NotNull - @Override - public Timing startTiming() { - return this; - } - - @Override - public void stopTiming() { - - } - - @NotNull - @Override - public Timing startTimingIfSync() { - return this; - } - - @Override - public void stopTimingIfSync() { - - } - - @Override - public void abort() { - - } - - @Nullable - @Override - public TimingHandler getTimingHandler() { - return null; - } - - @Override - public void close() { - - } -} diff --git a/api/src/main/java/co/aikar/timings/TimedEventExecutor.java b/api/src/main/java/co/aikar/timings/TimedEventExecutor.java deleted file mode 100644 index 933ecf9bd..000000000 --- a/api/src/main/java/co/aikar/timings/TimedEventExecutor.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -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.bukkit.plugin.Plugin; - -import java.lang.reflect.Method; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class TimedEventExecutor implements EventExecutor { - - private final EventExecutor executor; - private final Timing timings; - - /** - * Wraps an event executor and associates a timing handler to it. - * - * @param executor Executor to wrap - * @param plugin Owning plugin - * @param method EventHandler method - * @param eventClass Owning class - */ - public TimedEventExecutor(@NotNull EventExecutor executor, @NotNull Plugin plugin, @Nullable Method method, @NotNull Class eventClass) { - this.executor = executor; - String id; - - if (method == null) { - if (executor.getClass().getEnclosingClass() != null) { // Oh Skript, how we love you - method = executor.getClass().getEnclosingMethod(); - } - } - - if (method != null) { - id = method.getDeclaringClass().getName(); - } else { - id = executor.getClass().getName(); - } - - - final String eventName = eventClass.getSimpleName(); - boolean verbose = "BlockPhysicsEvent".equals(eventName); - this.timings = Timings.ofSafe(plugin.getName(), (verbose ? "## " : "") + - "Event: " + id + " (" + eventName + ")", null); - } - - @Override - public void execute(@NotNull Listener listener, @NotNull Event event) throws EventException { - if (event.isAsynchronous() || !Timings.timingsEnabled || !Bukkit.isPrimaryThread()) { - executor.execute(listener, event); - return; - } - try (Timing ignored = timings.startTiming()){ - executor.execute(listener, event); - } - } -} diff --git a/api/src/main/java/co/aikar/timings/Timing.java b/api/src/main/java/co/aikar/timings/Timing.java deleted file mode 100644 index a21e5ead5..000000000 --- a/api/src/main/java/co/aikar/timings/Timing.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Provides an ability to time sections of code within the Minecraft Server - */ -public interface Timing extends AutoCloseable { - /** - * Starts timing the execution until {@link #stopTiming()} is called. - * - * @return Timing - */ - @NotNull - Timing startTiming(); - - /** - *

Stops timing and records the data. Propagates the data up to group handlers.

- * - * Will automatically be called when this Timing is used with try-with-resources - */ - void stopTiming(); - - /** - * Starts timing the execution until {@link #stopTiming()} is called. - * - * But only if we are on the primary thread. - * - * @return Timing - */ - @NotNull - Timing startTimingIfSync(); - - /** - *

Stops timing and records the data. Propagates the data up to group handlers.

- * - *

Will automatically be called when this Timing is used with try-with-resources

- * - * But only if we are on the primary thread. - */ - void stopTimingIfSync(); - - /** - * @deprecated Doesn't do anything - Removed - */ - @Deprecated - void abort(); - - /** - * Used internally to get the actual backing Handler in the case of delegated Handlers - * - * @return TimingHandler - */ - @Nullable - TimingHandler getTimingHandler(); - - @Override - void close(); -} diff --git a/api/src/main/java/co/aikar/timings/TimingData.java b/api/src/main/java/co/aikar/timings/TimingData.java deleted file mode 100644 index a5d13a1e4..000000000 --- a/api/src/main/java/co/aikar/timings/TimingData.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import java.util.List; -import org.jetbrains.annotations.NotNull; - -import static co.aikar.util.JSONUtil.toArray; - -/** - *

Lightweight object for tracking timing data

- * - * This is broken out to reduce memory usage - */ -class TimingData { - private final int id; - private int count = 0; - private int lagCount = 0; - private long totalTime = 0; - private long lagTotalTime = 0; - private int curTickCount = 0; - private long curTickTotal = 0; - - TimingData(int id) { - this.id = id; - } - - private TimingData(TimingData data) { - this.id = data.id; - this.totalTime = data.totalTime; - this.lagTotalTime = data.lagTotalTime; - this.count = data.count; - this.lagCount = data.lagCount; - } - - void add(long diff) { - ++curTickCount; - curTickTotal += diff; - } - - void processTick(boolean violated) { - totalTime += curTickTotal; - count += curTickCount; - if (violated) { - lagTotalTime += curTickTotal; - lagCount += curTickCount; - } - curTickTotal = 0; - curTickCount = 0; - } - - void reset() { - count = 0; - lagCount = 0; - curTickTotal = 0; - curTickCount = 0; - totalTime = 0; - lagTotalTime = 0; - } - - protected TimingData clone() { - return new TimingData(this); - } - - @NotNull - List export() { - List list = toArray( - id, - count, - totalTime); - if (lagCount > 0) { - list.add(lagCount); - list.add(lagTotalTime); - } - return list; - } - - boolean hasData() { - return count > 0; - } - - long getTotalTime() { - return totalTime; - } - - int getCurTickCount() { - return curTickCount; - } - - void setCurTickCount(int curTickCount) { - this.curTickCount = curTickCount; - } - - long getCurTickTotal() { - return curTickTotal; - } - - void setCurTickTotal(long curTickTotal) { - this.curTickTotal = curTickTotal; - } -} diff --git a/api/src/main/java/co/aikar/timings/TimingHandler.java b/api/src/main/java/co/aikar/timings/TimingHandler.java deleted file mode 100644 index cc0390c06..000000000 --- a/api/src/main/java/co/aikar/timings/TimingHandler.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import co.aikar.util.LoadingIntMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; - -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.bukkit.Bukkit; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -class TimingHandler implements Timing { - - private static AtomicInteger idPool = new AtomicInteger(1); - private static Deque TIMING_STACK = new ArrayDeque<>(); - final int id = idPool.getAndIncrement(); - - final TimingIdentifier identifier; - private final boolean verbose; - - private final Int2ObjectOpenHashMap children = new LoadingIntMap<>(TimingData::new); - - final TimingData record; - private TimingHandler startParent; - private final TimingHandler groupHandler; - - private long start = 0; - private int timingDepth = 0; - private boolean added; - private boolean timed; - private boolean enabled; - - TimingHandler(@NotNull TimingIdentifier id) { - this.identifier = id; - this.verbose = id.name.startsWith("##"); - this.record = new TimingData(this.id); - this.groupHandler = id.groupHandler; - - TimingIdentifier.getGroup(id.group).handlers.add(this); - checkEnabled(); - } - - final void checkEnabled() { - enabled = Timings.timingsEnabled && (!verbose || Timings.verboseEnabled); - } - - void processTick(boolean violated) { - if (timingDepth != 0 || record.getCurTickCount() == 0) { - timingDepth = 0; - start = 0; - return; - } - - record.processTick(violated); - for (TimingData handler : children.values()) { - handler.processTick(violated); - } - } - - @NotNull - @Override - public Timing startTimingIfSync() { - startTiming(); - return this; - } - - @Override - public void stopTimingIfSync() { - stopTiming(); - } - - @NotNull - public Timing startTiming() { - if (!enabled || !Bukkit.isPrimaryThread()) { - return this; - } - if (++timingDepth == 1) { - startParent = TIMING_STACK.peekLast(); - start = System.nanoTime(); - } - TIMING_STACK.addLast(this); - return this; - } - - public void stopTiming() { - if (!enabled || timingDepth <= 0 || start == 0 || !Bukkit.isPrimaryThread()) { - return; - } - - popTimingStack(); - if (--timingDepth == 0) { - addDiff(System.nanoTime() - start, startParent); - startParent = null; - start = 0; - } - } - - private void popTimingStack() { - TimingHandler last; - while ((last = TIMING_STACK.removeLast()) != this) { - last.timingDepth = 0; - String reportTo; - if ("Minecraft".equalsIgnoreCase(last.identifier.group)) { - reportTo = "Paper! This is a potential bug in Paper"; - } else { - reportTo = "the plugin " + last.identifier.group + "(Look for errors above this in the logs)"; - } - Logger.getGlobal().log(Level.SEVERE, "TIMING_STACK_CORRUPTION - Report this to " + reportTo + " (" + last.identifier + " did not stopTiming)", new Throwable()); - boolean found = TIMING_STACK.contains(this); - if (!found) { - // We aren't even in the stack... Don't pop everything - TIMING_STACK.addLast(last); - break; - } - } - } - - @Override - public final void abort() { - - } - - void addDiff(long diff, @Nullable TimingHandler parent) { - if (parent != null) { - parent.children.get(id).add(diff); - } - - record.add(diff); - if (!added) { - added = true; - timed = true; - TimingsManager.HANDLERS.add(this); - } - if (groupHandler != null) { - groupHandler.addDiff(diff, parent); - groupHandler.children.get(id).add(diff); - } - } - - /** - * Reset this timer, setting all values to zero. - */ - void reset(boolean full) { - record.reset(); - if (full) { - timed = false; - } - start = 0; - timingDepth = 0; - added = false; - children.clear(); - checkEnabled(); - } - - @NotNull - @Override - public TimingHandler getTimingHandler() { - return this; - } - - @Override - public boolean equals(Object o) { - return (this == o); - } - - @Override - public int hashCode() { - return id; - } - - /** - * This is simply for the Closeable interface so it can be used with try-with-resources () - */ - @Override - public void close() { - stopTimingIfSync(); - } - - public boolean isSpecial() { - return this == TimingsManager.FULL_SERVER_TICK || this == TimingsManager.TIMINGS_TICK; - } - - boolean isTimed() { - return timed; - } - - public boolean isEnabled() { - return enabled; - } - - @NotNull - TimingData[] cloneChildren() { - final TimingData[] clonedChildren = new TimingData[children.size()]; - int i = 0; - for (TimingData child : children.values()) { - clonedChildren[i++] = child.clone(); - } - return clonedChildren; - } -} diff --git a/api/src/main/java/co/aikar/timings/TimingHistory.java b/api/src/main/java/co/aikar/timings/TimingHistory.java deleted file mode 100644 index 203cda0f9..000000000 --- a/api/src/main/java/co/aikar/timings/TimingHistory.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import co.aikar.timings.TimingHistory.RegionData.RegionId; -import com.google.common.base.Function; -import com.google.common.collect.Sets; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import co.aikar.util.LoadingMap; -import co.aikar.util.MRUMapCache; - -import java.lang.management.ManagementFactory; -import java.util.Collection; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import static co.aikar.timings.TimingsManager.FULL_SERVER_TICK; -import static co.aikar.timings.TimingsManager.MINUTE_REPORTS; -import static co.aikar.util.JSONUtil.*; - -@SuppressWarnings({"deprecation", "SuppressionAnnotation", "Convert2Lambda", "Anonymous2MethodRef"}) -public class TimingHistory { - public static long lastMinuteTime; - public static long timedTicks; - public static long playerTicks; - public static long entityTicks; - public static long tileEntityTicks; - public static long activatedEntityTicks; - private static int worldIdPool = 1; - static Map worldMap = LoadingMap.newHashMap(new Function() { - @NotNull - @Override - public Integer apply(@Nullable String input) { - return worldIdPool++; - } - }); - private final long endTime; - private final long startTime; - private final long totalTicks; - private final long totalTime; // Represents all time spent running the server this history - private final MinuteReport[] minuteReports; - - private final TimingHistoryEntry[] entries; - final Set tileEntityTypeSet = Sets.newHashSet(); - final Set entityTypeSet = Sets.newHashSet(); - private final Map worlds; - - TimingHistory() { - this.endTime = System.currentTimeMillis() / 1000; - this.startTime = TimingsManager.historyStart / 1000; - if (timedTicks % 1200 != 0 || MINUTE_REPORTS.isEmpty()) { - this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size() + 1]); - this.minuteReports[this.minuteReports.length - 1] = new MinuteReport(); - } else { - this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size()]); - } - long ticks = 0; - for (MinuteReport mp : this.minuteReports) { - ticks += mp.ticksRecord.timed; - } - this.totalTicks = ticks; - this.totalTime = FULL_SERVER_TICK.record.getTotalTime(); - this.entries = new TimingHistoryEntry[TimingsManager.HANDLERS.size()]; - - int i = 0; - for (TimingHandler handler : TimingsManager.HANDLERS) { - entries[i++] = new TimingHistoryEntry(handler); - } - - // Information about all loaded chunks/entities - //noinspection unchecked - this.worlds = toObjectMapper(Bukkit.getWorlds(), new Function() { - @NotNull - @Override - public JSONPair apply(World world) { - Map regions = LoadingMap.newHashMap(RegionData.LOADER); - - for (Chunk chunk : world.getLoadedChunks()) { - RegionData data = regions.get(new RegionId(chunk.getX(), chunk.getZ())); - - for (Entity entity : chunk.getEntities()) { - if (entity == null) { - Bukkit.getLogger().warning("Null entity detected in chunk at position x: " + chunk.getX() + ", z: " + chunk.getZ()); - continue; - } - - data.entityCounts.get(entity.getType()).increment(); - } - - for (BlockState tileEntity : chunk.getTileEntities(false)) { - if (tileEntity == null) { - Bukkit.getLogger().warning("Null tileentity detected in chunk at position x: " + chunk.getX() + ", z: " + chunk.getZ()); - continue; - } - - data.tileEntityCounts.get(tileEntity.getBlock().getType()).increment(); - } - } - return pair( - worldMap.get(world.getName()), - toArrayMapper(regions.values(),new Function() { - @NotNull - @Override - public Object apply(RegionData input) { - return toArray( - input.regionId.x, - input.regionId.z, - toObjectMapper(input.entityCounts.entrySet(), - new Function, JSONPair>() { - @NotNull - @Override - public JSONPair apply(Map.Entry entry) { - entityTypeSet.add(entry.getKey()); - return pair( - String.valueOf(entry.getKey().ordinal()), - entry.getValue().count() - ); - } - } - ), - toObjectMapper(input.tileEntityCounts.entrySet(), - new Function, JSONPair>() { - @NotNull - @Override - public JSONPair apply(Map.Entry entry) { - tileEntityTypeSet.add(entry.getKey()); - return pair( - String.valueOf(entry.getKey().ordinal()), - entry.getValue().count() - ); - } - } - ) - ); - } - }) - ); - } - }); - } - static class RegionData { - final RegionId regionId; - @SuppressWarnings("Guava") - static Function LOADER = new Function() { - @NotNull - @Override - public RegionData apply(@NotNull RegionId id) { - return new RegionData(id); - } - }; - RegionData(@NotNull RegionId id) { - this.regionId = id; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - RegionData that = (RegionData) o; - - return regionId.equals(that.regionId); - - } - - @Override - public int hashCode() { - return regionId.hashCode(); - } - - @SuppressWarnings("unchecked") - final Map entityCounts = MRUMapCache.of(LoadingMap.of( - new EnumMap(EntityType.class), k -> new Counter() - )); - @SuppressWarnings("unchecked") - final Map tileEntityCounts = MRUMapCache.of(LoadingMap.of( - new EnumMap(Material.class), k -> new Counter() - )); - - static class RegionId { - final int x, z; - final long regionId; - RegionId(int x, int z) { - this.x = x >> 5 << 5; - this.z = z >> 5 << 5; - this.regionId = ((long) (this.x) << 32) + (this.z >> 5 << 5) - Integer.MIN_VALUE; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - RegionId regionId1 = (RegionId) o; - - return regionId == regionId1.regionId; - - } - - @Override - public int hashCode() { - return (int) (regionId ^ (regionId >>> 32)); - } - } - } - static void resetTicks(boolean fullReset) { - if (fullReset) { - // Non full is simply for 1 minute reports - timedTicks = 0; - } - lastMinuteTime = System.nanoTime(); - playerTicks = 0; - tileEntityTicks = 0; - entityTicks = 0; - activatedEntityTicks = 0; - } - - @NotNull - Object export() { - return createObject( - pair("s", startTime), - pair("e", endTime), - pair("tk", totalTicks), - pair("tm", totalTime), - pair("w", worlds), - pair("h", toArrayMapper(entries, new Function() { - @Nullable - @Override - public Object apply(TimingHistoryEntry entry) { - TimingData record = entry.data; - if (!record.hasData()) { - return null; - } - return entry.export(); - } - })), - pair("mp", toArrayMapper(minuteReports, new Function() { - @NotNull - @Override - public Object apply(MinuteReport input) { - return input.export(); - } - })) - ); - } - - static class MinuteReport { - final long time = System.currentTimeMillis() / 1000; - - final TicksRecord ticksRecord = new TicksRecord(); - final PingRecord pingRecord = new PingRecord(); - final TimingData fst = TimingsManager.FULL_SERVER_TICK.minuteData.clone(); - final double tps = 1E9 / ( System.nanoTime() - lastMinuteTime ) * ticksRecord.timed; - final double usedMemory = TimingsManager.FULL_SERVER_TICK.avgUsedMemory; - final double freeMemory = TimingsManager.FULL_SERVER_TICK.avgFreeMemory; - final double loadAvg = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage(); - - @NotNull - List export() { - return toArray( - time, - Math.round(tps * 100D) / 100D, - Math.round(pingRecord.avg * 100D) / 100D, - fst.export(), - toArray(ticksRecord.timed, - ticksRecord.player, - ticksRecord.entity, - ticksRecord.activatedEntity, - ticksRecord.tileEntity - ), - usedMemory, - freeMemory, - loadAvg - ); - } - } - - private static class TicksRecord { - final long timed; - final long player; - final long entity; - final long tileEntity; - final long activatedEntity; - - TicksRecord() { - timed = timedTicks - (TimingsManager.MINUTE_REPORTS.size() * 1200); - player = playerTicks; - entity = entityTicks; - tileEntity = tileEntityTicks; - activatedEntity = activatedEntityTicks; - } - - } - - private static class PingRecord { - final double avg; - - PingRecord() { - final Collection onlinePlayers = Bukkit.getOnlinePlayers(); - int totalPing = 0; - for (Player player : onlinePlayers) { - totalPing += player.spigot().getPing(); - } - avg = onlinePlayers.isEmpty() ? 0 : totalPing / onlinePlayers.size(); - } - } - - - private static class Counter { - private int count = 0; - public int increment() { - return ++count; - } - public int count() { - return count; - } - } -} diff --git a/api/src/main/java/co/aikar/timings/TimingHistoryEntry.java b/api/src/main/java/co/aikar/timings/TimingHistoryEntry.java deleted file mode 100644 index 86d5ac6bd..000000000 --- a/api/src/main/java/co/aikar/timings/TimingHistoryEntry.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import com.google.common.base.Function; - -import java.util.List; -import org.jetbrains.annotations.NotNull; - -import static co.aikar.util.JSONUtil.toArrayMapper; - -class TimingHistoryEntry { - final TimingData data; - private final TimingData[] children; - - TimingHistoryEntry(@NotNull TimingHandler handler) { - this.data = handler.record.clone(); - children = handler.cloneChildren(); - } - - @NotNull - List export() { - List result = data.export(); - if (children.length > 0) { - result.add( - toArrayMapper(children, new Function() { - @NotNull - @Override - public Object apply(TimingData child) { - return child.export(); - } - }) - ); - } - return result; - } -} diff --git a/api/src/main/java/co/aikar/timings/TimingIdentifier.java b/api/src/main/java/co/aikar/timings/TimingIdentifier.java deleted file mode 100644 index df142a89b..000000000 --- a/api/src/main/java/co/aikar/timings/TimingIdentifier.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import co.aikar.util.LoadingMap; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - *

Used as a basis for fast HashMap key comparisons for the Timing Map.

- * - * This class uses interned strings giving us the ability to do an identity check instead of equals() on the strings - */ -final class TimingIdentifier { - /** - * Holds all groups. Autoloads on request for a group by name. - */ - static final Map GROUP_MAP = LoadingMap.of(new ConcurrentHashMap<>(64, .5F), TimingGroup::new); - private static final TimingGroup DEFAULT_GROUP = getGroup("Minecraft"); - final String group; - final String name; - final TimingHandler groupHandler; - private final int hashCode; - - TimingIdentifier(@Nullable String group, @NotNull String name, @Nullable Timing groupHandler) { - this.group = group != null ? group: DEFAULT_GROUP.name; - this.name = name; - this.groupHandler = groupHandler != null ? groupHandler.getTimingHandler() : null; - this.hashCode = (31 * this.group.hashCode()) + this.name.hashCode(); - } - - @NotNull - static TimingGroup getGroup(@Nullable String groupName) { - if (groupName == null) { - //noinspection ConstantConditions - return DEFAULT_GROUP; - } - - return GROUP_MAP.get(groupName); - } - - @Override - public boolean equals(Object o) { - if (o == null) { - return false; - } - - TimingIdentifier that = (TimingIdentifier) o; - return Objects.equals(group, that.group) && Objects.equals(name, that.name); - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public String toString() { - return "TimingIdentifier{id=" + group + ":" + name +'}'; - } - - static class TimingGroup { - - private static AtomicInteger idPool = new AtomicInteger(1); - final int id = idPool.getAndIncrement(); - - final String name; - final List handlers = Collections.synchronizedList(new ArrayList<>(64)); - - private TimingGroup(String name) { - this.name = name; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - TimingGroup that = (TimingGroup) o; - return id == that.id; - } - - @Override - public int hashCode() { - return id; - } - } -} diff --git a/api/src/main/java/co/aikar/timings/Timings.java b/api/src/main/java/co/aikar/timings/Timings.java deleted file mode 100644 index 0b34e0d01..000000000 --- a/api/src/main/java/co/aikar/timings/Timings.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import com.google.common.base.Preconditions; -import com.google.common.collect.EvictingQueue; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.Plugin; - -import java.util.Queue; -import java.util.logging.Level; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -@SuppressWarnings({"UnusedDeclaration", "WeakerAccess", "SameParameterValue"}) -public final class Timings { - - private static final int MAX_HISTORY_FRAMES = 12; - public static final Timing NULL_HANDLER = new NullTimingHandler(); - static boolean timingsEnabled = false; - static boolean verboseEnabled = false; - private static int historyInterval = -1; - private static int historyLength = -1; - - private Timings() {} - - /** - * Returns a Timing for a plugin corresponding to a name. - * - * @param plugin Plugin to own the Timing - * @param name Name of Timing - * @return Handler - */ - @NotNull - public static Timing of(@NotNull Plugin plugin, @NotNull String name) { - Timing pluginHandler = null; - if (plugin != null) { - pluginHandler = ofSafe(plugin.getName(), "Combined Total", TimingsManager.PLUGIN_GROUP_HANDLER); - } - return of(plugin, name, pluginHandler); - } - - /** - *

Returns a handler that has a groupHandler timer handler. Parent timers should not have their - * start/stop methods called directly, as the children will call it for you.

- * - * Parent Timers are used to group multiple subsections together and get a summary of them combined - * Parent Handler can not be changed after first call - * - * @param plugin Plugin to own the Timing - * @param name Name of Timing - * @param groupHandler Parent handler to mirror .start/stop calls to - * @return Timing Handler - */ - @NotNull - public static Timing of(@NotNull Plugin plugin, @NotNull String name, @Nullable Timing groupHandler) { - Preconditions.checkNotNull(plugin, "Plugin can not be null"); - return TimingsManager.getHandler(plugin.getName(), name, groupHandler); - } - - /** - * Returns a Timing object after starting it, useful for Java7 try-with-resources. - * - * try (Timing ignored = Timings.ofStart(plugin, someName)) { - * // timed section - * } - * - * @param plugin Plugin to own the Timing - * @param name Name of Timing - * @return Timing Handler - */ - @NotNull - public static Timing ofStart(@NotNull Plugin plugin, @NotNull String name) { - return ofStart(plugin, name, null); - } - - /** - * Returns a Timing object after starting it, useful for Java7 try-with-resources. - * - * try (Timing ignored = Timings.ofStart(plugin, someName, groupHandler)) { - * // timed section - * } - * - * @param plugin Plugin to own the Timing - * @param name Name of Timing - * @param groupHandler Parent handler to mirror .start/stop calls to - * @return Timing Handler - */ - @NotNull - public static Timing ofStart(@NotNull Plugin plugin, @NotNull String name, @Nullable Timing groupHandler) { - Timing timing = of(plugin, name, groupHandler); - timing.startTiming(); - return timing; - } - - /** - * Gets whether or not the Spigot Timings system is enabled - * - * @return Enabled or not - */ - public static boolean isTimingsEnabled() { - return timingsEnabled; - } - - /** - *

Sets whether or not the Spigot Timings system should be enabled

- * - * Calling this will reset timing data. - * - * @param enabled Should timings be reported - */ - public static void setTimingsEnabled(boolean enabled) { - timingsEnabled = enabled; - reset(); - } - - /** - *

Sets whether or not the Timings should monitor at Verbose level.

- * - *

When Verbose is disabled, high-frequency timings will not be available.

- * - * @return Enabled or not - */ - public static boolean isVerboseTimingsEnabled() { - return verboseEnabled; - } - - /** - *

Sets whether or not the Timings should monitor at Verbose level.

- * - * When Verbose is disabled, high-frequency timings will not be available. - * Calling this will reset timing data. - * - * @param enabled Should high-frequency timings be reported - */ - public static void setVerboseTimingsEnabled(boolean enabled) { - verboseEnabled = enabled; - TimingsManager.needsRecheckEnabled = true; - } - - /** - *

Gets the interval between Timing History report generation.

- * - * Defaults to 5 minutes (6000 ticks) - * - * @return Interval in ticks - */ - public static int getHistoryInterval() { - return historyInterval; - } - - /** - *

Sets the interval between Timing History report generations.

- * - *

Defaults to 5 minutes (6000 ticks)

- * - * This will recheck your history length, so lowering this value will lower your - * history length if you need more than 60 history windows. - * - * @param interval Interval in ticks - */ - public static void setHistoryInterval(int interval) { - historyInterval = Math.max(20*60, interval); - // Recheck the history length with the new Interval - if (historyLength != -1) { - setHistoryLength(historyLength); - } - } - - /** - * Gets how long in ticks Timings history is kept for the server. - * - * Defaults to 1 hour (72000 ticks) - * - * @return Duration in Ticks - */ - public static int getHistoryLength() { - return historyLength; - } - - /** - * Sets how long Timing History reports are kept for the server. - * - * Defaults to 1 hours(72000 ticks) - * - * This value is capped at a maximum of getHistoryInterval() * MAX_HISTORY_FRAMES (12) - * - * Will not reset Timing Data but may truncate old history if the new length is less than old length. - * - * @param length Duration in ticks - */ - public static void setHistoryLength(int length) { - // Cap at 12 History Frames, 1 hour at 5 minute frames. - int maxLength = historyInterval * MAX_HISTORY_FRAMES; - // For special cases of servers with special permission to bypass the max. - // This max helps keep data file sizes reasonable for processing on Aikar's Timing parser side. - // Setting this will not help you bypass the max unless Aikar has added an exception on the API side. - if (System.getProperty("timings.bypassMax") != null) { - maxLength = Integer.MAX_VALUE; - } - historyLength = Math.max(Math.min(maxLength, length), historyInterval); - Queue oldQueue = TimingsManager.HISTORY; - int frames = (getHistoryLength() / getHistoryInterval()); - if (length > maxLength) { - Bukkit.getLogger().log(Level.WARNING, "Timings Length too high. Requested " + length + ", max is " + maxLength + ". To get longer history, you must increase your interval. Set Interval to " + Math.ceil(length / MAX_HISTORY_FRAMES) + " to achieve this length."); - } - TimingsManager.HISTORY = EvictingQueue.create(frames); - TimingsManager.HISTORY.addAll(oldQueue); - } - - /** - * Resets all Timing Data - */ - public static void reset() { - TimingsManager.reset(); - } - - /** - * Generates a report and sends it to the specified command sender. - * - * If sender is null, ConsoleCommandSender will be used. - * @param sender The sender to send to, or null to use the ConsoleCommandSender - */ - public static void generateReport(@Nullable CommandSender sender) { - if (sender == null) { - sender = Bukkit.getConsoleSender(); - } - TimingsExport.requestingReport.add(sender); - } - - /** - * Generates a report and sends it to the specified listener. - * Use with {@link org.bukkit.command.BufferedCommandSender} to get full response when done! - * @param sender The listener to send responses too. - */ - public static void generateReport(@NotNull TimingsReportListener sender) { - Validate.notNull(sender); - TimingsExport.requestingReport.add(sender); - } - - /* - ================= - Protected API: These are for internal use only in Bukkit/CraftBukkit - These do not have isPrimaryThread() checks in the startTiming/stopTiming - ================= - */ - @NotNull - static TimingHandler ofSafe(@NotNull String name) { - return ofSafe(null, name, null); - } - - @NotNull - static Timing ofSafe(@Nullable Plugin plugin, @NotNull String name) { - Timing pluginHandler = null; - if (plugin != null) { - pluginHandler = ofSafe(plugin.getName(), "Combined Total", TimingsManager.PLUGIN_GROUP_HANDLER); - } - return ofSafe(plugin != null ? plugin.getName() : "Minecraft - Invalid Plugin", name, pluginHandler); - } - - @NotNull - static TimingHandler ofSafe(@NotNull String name, @Nullable Timing groupHandler) { - return ofSafe(null, name, groupHandler); - } - - @NotNull - static TimingHandler ofSafe(@Nullable String groupName, @NotNull String name, @Nullable Timing groupHandler) { - return TimingsManager.getHandler(groupName, name, groupHandler); - } -} diff --git a/api/src/main/java/co/aikar/timings/TimingsCommand.java b/api/src/main/java/co/aikar/timings/TimingsCommand.java deleted file mode 100644 index c0d8f2016..000000000 --- a/api/src/main/java/co/aikar/timings/TimingsCommand.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import com.google.common.collect.ImmutableList; -import org.apache.commons.lang.Validate; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.defaults.BukkitCommand; -import org.bukkit.util.StringUtil; - -import java.util.ArrayList; -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - - -public class TimingsCommand extends BukkitCommand { - private static final List TIMINGS_SUBCOMMANDS = ImmutableList.of("report", "reset", "on", "off", "paste", "verbon", "verboff"); - private long lastResetAttempt = 0; - - public TimingsCommand(@NotNull String name) { - super(name); - this.description = "Manages Spigot Timings data to see performance of the server."; - this.usageMessage = "/timings "; - this.setPermission("bukkit.command.timings"); - } - - @Override - public boolean execute(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull String[] args) { - if (!testPermission(sender)) { - return true; - } - if (args.length < 1) { - sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); - return true; - } - final String arg = args[0]; - if ("on".equalsIgnoreCase(arg)) { - Timings.setTimingsEnabled(true); - sender.sendMessage("Enabled Timings & Reset"); - return true; - } else if ("off".equalsIgnoreCase(arg)) { - Timings.setTimingsEnabled(false); - sender.sendMessage("Disabled Timings"); - return true; - } - - if (!Timings.isTimingsEnabled()) { - sender.sendMessage("Please enable timings by typing /timings on"); - return true; - } - - long now = System.currentTimeMillis(); - if ("verbon".equalsIgnoreCase(arg)) { - Timings.setVerboseTimingsEnabled(true); - sender.sendMessage("Enabled Verbose Timings"); - return true; - } else if ("verboff".equalsIgnoreCase(arg)) { - Timings.setVerboseTimingsEnabled(false); - sender.sendMessage("Disabled Verbose Timings"); - return true; - } else if ("reset".equalsIgnoreCase(arg)) { - if (now - lastResetAttempt < 30000) { - TimingsManager.reset(); - sender.sendMessage(ChatColor.RED + "Timings reset. Please wait 5-10 minutes before using /timings report."); - } else { - lastResetAttempt = now; - sender.sendMessage(ChatColor.RED + "WARNING: Timings v2 should not be reset. If you are encountering lag, please wait 3 minutes and then issue a report. The best timings will include 10+ minutes, with data before and after your lag period. If you really want to reset, run this command again within 30 seconds."); - } - - } else if ("cost".equals(arg)) { - sender.sendMessage("Timings cost: " + TimingsExport.getCost()); - } else if ( - "paste".equalsIgnoreCase(arg) || - "report".equalsIgnoreCase(arg) || - "get".equalsIgnoreCase(arg) || - "merged".equalsIgnoreCase(arg) || - "separate".equalsIgnoreCase(arg) - ) { - Timings.generateReport(sender); - } else { - sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); - } - return true; - } - - @NotNull - @Override - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull 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], TIMINGS_SUBCOMMANDS, - new ArrayList(TIMINGS_SUBCOMMANDS.size())); - } - return ImmutableList.of(); - } -} diff --git a/api/src/main/java/co/aikar/timings/TimingsExport.java b/api/src/main/java/co/aikar/timings/TimingsExport.java deleted file mode 100644 index 23eb8c65c..000000000 --- a/api/src/main/java/co/aikar/timings/TimingsExport.java +++ /dev/null @@ -1,355 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.MemorySection; -import org.bukkit.entity.EntityType; -import org.json.simple.JSONObject; -import org.json.simple.JSONValue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.net.HttpURLConnection; -import java.net.InetAddress; -import java.net.URL; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -import static co.aikar.timings.TimingsManager.HISTORY; -import static co.aikar.util.JSONUtil.appendObjectData; -import static co.aikar.util.JSONUtil.createObject; -import static co.aikar.util.JSONUtil.pair; -import static co.aikar.util.JSONUtil.toArray; -import static co.aikar.util.JSONUtil.toArrayMapper; -import static co.aikar.util.JSONUtil.toObjectMapper; - -@SuppressWarnings({"rawtypes", "SuppressionAnnotation"}) -class TimingsExport extends Thread { - - private final TimingsReportListener listeners; - private final Map out; - private final TimingHistory[] history; - private static long lastReport = 0; - final static List requestingReport = Lists.newArrayList(); - - private TimingsExport(TimingsReportListener listeners, Map out, TimingHistory[] history) { - super("Timings paste thread"); - this.listeners = listeners; - this.out = out; - this.history = history; - } - - /** - * Checks if any pending reports are being requested, and builds one if needed. - */ - static void reportTimings() { - if (requestingReport.isEmpty()) { - return; - } - TimingsReportListener listeners = new TimingsReportListener(requestingReport); - listeners.addConsoleIfNeeded(); - - requestingReport.clear(); - long now = System.currentTimeMillis(); - final long lastReportDiff = now - lastReport; - if (lastReportDiff < 60000) { - listeners.sendMessage(ChatColor.RED + "Please wait at least 1 minute in between Timings reports. (" + (int)((60000 - lastReportDiff) / 1000) + " seconds)"); - listeners.done(); - return; - } - final long lastStartDiff = now - TimingsManager.timingStart; - if (lastStartDiff < 180000) { - listeners.sendMessage(ChatColor.RED + "Please wait at least 3 minutes before generating a Timings report. Unlike Timings v1, v2 benefits from longer timings and is not as useful with short timings. (" + (int)((180000 - lastStartDiff) / 1000) + " seconds)"); - listeners.done(); - return; - } - listeners.sendMessage(ChatColor.GREEN + "Preparing Timings Report..."); - lastReport = now; - Map parent = createObject( - // Get some basic system details about the server - pair("version", Bukkit.getVersion()), - pair("maxplayers", Bukkit.getMaxPlayers()), - pair("start", TimingsManager.timingStart / 1000), - pair("end", System.currentTimeMillis() / 1000), - pair("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000) - ); - if (!TimingsManager.privacy) { - appendObjectData(parent, - pair("server", Bukkit.getUnsafe().getTimingsServerName()), - pair("motd", Bukkit.getServer().getMotd()), - pair("online-mode", Bukkit.getServer().getOnlineMode()), - pair("icon", Bukkit.getServer().getServerIcon().getData()) - ); - } - - final Runtime runtime = Runtime.getRuntime(); - RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); - - parent.put("system", createObject( - pair("timingcost", getCost()), - pair("name", System.getProperty("os.name")), - pair("version", System.getProperty("os.version")), - pair("jvmversion", System.getProperty("java.version")), - pair("arch", System.getProperty("os.arch")), - pair("maxmem", runtime.maxMemory()), - pair("cpu", runtime.availableProcessors()), - pair("runtime", ManagementFactory.getRuntimeMXBean().getUptime()), - pair("flags", StringUtils.join(runtimeBean.getInputArguments(), " ")), - pair("gc", toObjectMapper(ManagementFactory.getGarbageCollectorMXBeans(), input -> pair(input.getName(), toArray(input.getCollectionCount(), input.getCollectionTime())))) - ) - ); - - Set tileEntityTypeSet = Sets.newHashSet(); - Set entityTypeSet = Sets.newHashSet(); - - int size = HISTORY.size(); - TimingHistory[] history = new TimingHistory[size + 1]; - int i = 0; - for (TimingHistory timingHistory : HISTORY) { - tileEntityTypeSet.addAll(timingHistory.tileEntityTypeSet); - entityTypeSet.addAll(timingHistory.entityTypeSet); - history[i++] = timingHistory; - } - - history[i] = new TimingHistory(); // Current snapshot - tileEntityTypeSet.addAll(history[i].tileEntityTypeSet); - entityTypeSet.addAll(history[i].entityTypeSet); - - - Map handlers = createObject(); - Map groupData; - synchronized (TimingIdentifier.GROUP_MAP) { - for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) { - synchronized (group.handlers) { - for (TimingHandler id : group.handlers) { - - if (!id.isTimed() && !id.isSpecial()) { - continue; - } - - String name = id.identifier.name; - if (name.startsWith("##")) { - name = name.substring(3); - } - handlers.put(id.id, toArray( - group.id, - name - )); - } - } - } - - groupData = toObjectMapper( - TimingIdentifier.GROUP_MAP.values(), group -> pair(group.id, group.name)); - } - - parent.put("idmap", createObject( - pair("groups", groupData), - pair("handlers", handlers), - pair("worlds", toObjectMapper(TimingHistory.worldMap.entrySet(), input -> pair(input.getValue(), input.getKey()))), - pair("tileentity", - toObjectMapper(tileEntityTypeSet, input -> pair(input.ordinal(), input.name()))), - pair("entity", - toObjectMapper(entityTypeSet, input -> pair(input.ordinal(), input.name()))) - )); - - // Information about loaded plugins - - parent.put("plugins", toObjectMapper(Bukkit.getPluginManager().getPlugins(), - plugin -> pair(plugin.getName(), createObject( - pair("version", plugin.getDescription().getVersion()), - pair("description", String.valueOf(plugin.getDescription().getDescription()).trim()), - pair("website", plugin.getDescription().getWebsite()), - pair("authors", StringUtils.join(plugin.getDescription().getAuthors(), ", ")) - )))); - - - - // Information on the users Config - - parent.put("config", createObject( - pair("spigot", mapAsJSON(Bukkit.spigot().getSpigotConfig(), null)), - pair("bukkit", mapAsJSON(Bukkit.spigot().getBukkitConfig(), null)), - pair("paper", mapAsJSON(Bukkit.spigot().getPaperConfig(), null)) - )); - - new TimingsExport(listeners, parent, history).start(); - } - - static long getCost() { - // Benchmark the users System.nanotime() for cost basis - int passes = 100; - TimingHandler SAMPLER1 = Timings.ofSafe("Timings Sampler 1"); - TimingHandler SAMPLER2 = Timings.ofSafe("Timings Sampler 2"); - TimingHandler SAMPLER3 = Timings.ofSafe("Timings Sampler 3"); - TimingHandler SAMPLER4 = Timings.ofSafe("Timings Sampler 4"); - TimingHandler SAMPLER5 = Timings.ofSafe("Timings Sampler 5"); - TimingHandler SAMPLER6 = Timings.ofSafe("Timings Sampler 6"); - - long start = System.nanoTime(); - for (int i = 0; i < passes; i++) { - SAMPLER1.startTiming(); - SAMPLER2.startTiming(); - SAMPLER3.startTiming(); - SAMPLER3.stopTiming(); - SAMPLER4.startTiming(); - SAMPLER5.startTiming(); - SAMPLER6.startTiming(); - SAMPLER6.stopTiming(); - SAMPLER5.stopTiming(); - SAMPLER4.stopTiming(); - SAMPLER2.stopTiming(); - SAMPLER1.stopTiming(); - } - long timingsCost = (System.nanoTime() - start) / passes / 6; - SAMPLER1.reset(true); - SAMPLER2.reset(true); - SAMPLER3.reset(true); - SAMPLER4.reset(true); - SAMPLER5.reset(true); - SAMPLER6.reset(true); - return timingsCost; - } - - private static JSONObject mapAsJSON(ConfigurationSection config, String parentKey) { - - JSONObject object = new JSONObject(); - for (String key : config.getKeys(false)) { - String fullKey = (parentKey != null ? parentKey + "." + key : key); - if (fullKey.equals("database") || fullKey.equals("settings.bungeecord-addresses") || TimingsManager.hiddenConfigs.contains(fullKey)) { - continue; - } - final Object val = config.get(key); - - object.put(key, valAsJSON(val, fullKey)); - } - return object; - } - - private static Object valAsJSON(Object val, final String parentKey) { - if (!(val instanceof MemorySection)) { - if (val instanceof List) { - Iterable v = (Iterable) val; - return toArrayMapper(v, input -> valAsJSON(input, parentKey)); - } else { - return val.toString(); - } - } else { - return mapAsJSON((ConfigurationSection) val, parentKey); - } - } - - @Override - public void run() { - out.put("data", toArrayMapper(history, TimingHistory::export)); - - - String response = null; - String timingsURL = null; - try { - HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection(); - con.setDoOutput(true); - String hostName = "BrokenHost"; - try { - hostName = InetAddress.getLocalHost().getHostName(); - } catch (Exception ignored) {} - con.setRequestProperty("User-Agent", "Paper/" + Bukkit.getUnsafe().getTimingsServerName() + "/" + hostName); - con.setRequestMethod("POST"); - con.setInstanceFollowRedirects(false); - - OutputStream request = new GZIPOutputStream(con.getOutputStream()) {{ - this.def.setLevel(7); - }}; - - request.write(JSONValue.toJSONString(out).getBytes("UTF-8")); - request.close(); - - response = getResponse(con); - - if (con.getResponseCode() != 302) { - listeners.sendMessage( - ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage()); - listeners.sendMessage(ChatColor.RED + "Check your logs for more information"); - if (response != null) { - Bukkit.getLogger().log(Level.SEVERE, response); - } - return; - } - - timingsURL = con.getHeaderField("Location"); - listeners.sendMessage(ChatColor.GREEN + "View Timings Report: " + timingsURL); - - if (response != null && !response.isEmpty()) { - Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response); - } - } catch (IOException ex) { - listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information"); - if (response != null) { - Bukkit.getLogger().log(Level.SEVERE, response); - } - Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex); - } finally { - this.listeners.done(timingsURL); - } - } - - private String getResponse(HttpURLConnection con) throws IOException { - InputStream is = null; - try { - is = con.getInputStream(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - byte[] b = new byte[1024]; - int bytesRead; - while ((bytesRead = is.read(b)) != -1) { - bos.write(b, 0, bytesRead); - } - return bos.toString(); - - } catch (IOException ex) { - listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information"); - Bukkit.getLogger().log(Level.WARNING, con.getResponseMessage(), ex); - return null; - } finally { - if (is != null) { - is.close(); - } - } - } -} diff --git a/api/src/main/java/co/aikar/timings/TimingsManager.java b/api/src/main/java/co/aikar/timings/TimingsManager.java deleted file mode 100644 index ef824d701..000000000 --- a/api/src/main/java/co/aikar/timings/TimingsManager.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import co.aikar.util.LoadingMap; -import com.google.common.collect.EvictingQueue; -import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.command.Command; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.PluginClassLoader; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public final class TimingsManager { - static final Map TIMING_MAP = LoadingMap.of( - new ConcurrentHashMap<>(4096, .5F), TimingHandler::new - ); - public static final FullServerTickHandler FULL_SERVER_TICK = new FullServerTickHandler(); - public static final TimingHandler TIMINGS_TICK = Timings.ofSafe("Timings Tick", FULL_SERVER_TICK); - public static final Timing PLUGIN_GROUP_HANDLER = Timings.ofSafe("Plugins"); - public static List hiddenConfigs = new ArrayList(); - public static boolean privacy = false; - - static final List HANDLERS = new ArrayList<>(1024); - static final List MINUTE_REPORTS = new ArrayList<>(64); - - static EvictingQueue HISTORY = EvictingQueue.create(12); - static long timingStart = 0; - static long historyStart = 0; - static boolean needsFullReset = false; - static boolean needsRecheckEnabled = false; - - private TimingsManager() {} - - /** - * Resets all timing data on the next tick - */ - static void reset() { - needsFullReset = true; - } - - /** - * Ticked every tick by CraftBukkit to count the number of times a timer - * caused TPS loss. - */ - static void tick() { - if (Timings.timingsEnabled) { - boolean violated = FULL_SERVER_TICK.isViolated(); - - for (TimingHandler handler : HANDLERS) { - if (handler.isSpecial()) { - // We manually call this - continue; - } - handler.processTick(violated); - } - - TimingHistory.playerTicks += Bukkit.getOnlinePlayers().size(); - TimingHistory.timedTicks++; - // Generate TPS/Ping/Tick reports every minute - } - } - static void stopServer() { - Timings.timingsEnabled = false; - recheckEnabled(); - } - static void recheckEnabled() { - synchronized (TIMING_MAP) { - for (TimingHandler timings : TIMING_MAP.values()) { - timings.checkEnabled(); - } - } - needsRecheckEnabled = false; - } - static void resetTimings() { - if (needsFullReset) { - // Full resets need to re-check every handlers enabled state - // Timing map can be modified from async so we must sync on it. - synchronized (TIMING_MAP) { - for (TimingHandler timings : TIMING_MAP.values()) { - timings.reset(true); - } - } - Bukkit.getLogger().log(Level.INFO, "Timings Reset"); - HISTORY.clear(); - needsFullReset = false; - needsRecheckEnabled = false; - timingStart = System.currentTimeMillis(); - } else { - // Soft resets only need to act on timings that have done something - // Handlers can only be modified on main thread. - for (TimingHandler timings : HANDLERS) { - timings.reset(false); - } - } - - HANDLERS.clear(); - MINUTE_REPORTS.clear(); - - TimingHistory.resetTicks(true); - historyStart = System.currentTimeMillis(); - } - - @NotNull - static TimingHandler getHandler(@Nullable String group, @NotNull String name, @Nullable Timing parent) { - return TIMING_MAP.get(new TimingIdentifier(group, name, parent)); - } - - - /** - *

Due to access restrictions, we need a helper method to get a Command TimingHandler with String group

- * - * Plugins should never call this - * - * @param pluginName Plugin this command is associated with - * @param command Command to get timings for - * @return TimingHandler - */ - @NotNull - public static Timing getCommandTiming(@Nullable String pluginName, @NotNull Command command) { - Plugin plugin = null; - final Server server = Bukkit.getServer(); - if (!( server == null || pluginName == null || - "minecraft".equals(pluginName) || "bukkit".equals(pluginName) || - "spigot".equalsIgnoreCase(pluginName) || "paper".equals(pluginName) - )) { - plugin = server.getPluginManager().getPlugin(pluginName); - } - if (plugin == null) { - // Plugin is passing custom fallback prefix, try to look up by class loader - plugin = getPluginByClassloader(command.getClass()); - } - if (plugin == null) { - return Timings.ofSafe("Command: " + pluginName + ":" + command.getTimingName()); - } - - return Timings.ofSafe(plugin, "Command: " + pluginName + ":" + command.getTimingName()); - } - - /** - * Looks up the class loader for the specified class, and if it is a PluginClassLoader, return the - * Plugin that created this class. - * - * @param clazz Class to check - * @return Plugin if created by a plugin - */ - @Nullable - public static Plugin getPluginByClassloader(@Nullable Class clazz) { - if (clazz == null) { - return null; - } - final ClassLoader classLoader = clazz.getClassLoader(); - if (classLoader instanceof PluginClassLoader) { - PluginClassLoader pluginClassLoader = (PluginClassLoader) classLoader; - return pluginClassLoader.getPlugin(); - } - return null; - } -} diff --git a/api/src/main/java/co/aikar/timings/TimingsReportListener.java b/api/src/main/java/co/aikar/timings/TimingsReportListener.java deleted file mode 100644 index bf3e059fe..000000000 --- a/api/src/main/java/co/aikar/timings/TimingsReportListener.java +++ /dev/null @@ -1,75 +0,0 @@ -package co.aikar.timings; - -import com.google.common.collect.Lists; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.command.MessageCommandSender; -import org.bukkit.command.RemoteConsoleCommandSender; - -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -@SuppressWarnings("WeakerAccess") -public class TimingsReportListener implements MessageCommandSender { - private final List senders; - private final Runnable onDone; - private String timingsURL; - - public TimingsReportListener(@NotNull CommandSender senders) { - this(senders, null); - } - public TimingsReportListener(@NotNull CommandSender sender, @Nullable Runnable onDone) { - this(Lists.newArrayList(sender), onDone); - } - public TimingsReportListener(@NotNull List senders) { - this(senders, null); - } - public TimingsReportListener(@NotNull List senders, @Nullable Runnable onDone) { - Validate.notNull(senders); - Validate.notEmpty(senders); - - this.senders = Lists.newArrayList(senders); - this.onDone = onDone; - } - - @Nullable - public String getTimingsURL() { - return timingsURL; - } - - public void done() { - done(null); - } - - public void done(@Nullable String url) { - this.timingsURL = url; - if (onDone != null) { - onDone.run(); - } - for (CommandSender sender : senders) { - if (sender instanceof TimingsReportListener) { - ((TimingsReportListener) sender).done(); - } - } - } - - @Override - public void sendMessage(@NotNull String message) { - senders.forEach((sender) -> sender.sendMessage(message)); - } - - public void addConsoleIfNeeded() { - boolean hasConsole = false; - for (CommandSender sender : this.senders) { - if (sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender) { - hasConsole = true; - } - } - if (!hasConsole) { - this.senders.add(Bukkit.getConsoleSender()); - } - } -} diff --git a/api/src/main/java/co/aikar/timings/UnsafeTimingHandler.java b/api/src/main/java/co/aikar/timings/UnsafeTimingHandler.java deleted file mode 100644 index 632c49615..000000000 --- a/api/src/main/java/co/aikar/timings/UnsafeTimingHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.timings; - -import org.bukkit.Bukkit; -import org.jetbrains.annotations.NotNull; - -class UnsafeTimingHandler extends TimingHandler { - - UnsafeTimingHandler(@NotNull TimingIdentifier id) { - super(id); - } - - private static void checkThread() { - if (!Bukkit.isPrimaryThread()) { - throw new IllegalStateException("Calling Timings from Async Operation"); - } - } - - @NotNull - @Override - public Timing startTiming() { - checkThread(); - return super.startTiming(); - } - - @Override - public void stopTiming() { - checkThread(); - super.stopTiming(); - } -} diff --git a/api/src/main/java/co/aikar/util/Counter.java b/api/src/main/java/co/aikar/util/Counter.java deleted file mode 100644 index 80155072d..000000000 --- a/api/src/main/java/co/aikar/util/Counter.java +++ /dev/null @@ -1,38 +0,0 @@ -package co.aikar.util; - -import com.google.common.collect.ForwardingMap; - -import java.util.HashMap; -import java.util.Map; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class Counter extends ForwardingMap { - private final Map counts = new HashMap<>(); - - public long decrement(@Nullable T key) { - return increment(key, -1); - } - public long increment(@Nullable T key) { - return increment(key, 1); - } - public long decrement(@Nullable T key, long amount) { - return decrement(key, -amount); - } - public long increment(@Nullable T key, long amount) { - Long count = this.getCount(key); - count += amount; - this.counts.put(key, count); - return count; - } - - public long getCount(@Nullable T key) { - return this.counts.getOrDefault(key, 0L); - } - - @NotNull - @Override - protected Map delegate() { - return this.counts; - } -} diff --git a/api/src/main/java/co/aikar/util/JSONUtil.java b/api/src/main/java/co/aikar/util/JSONUtil.java deleted file mode 100644 index 190bf0598..000000000 --- a/api/src/main/java/co/aikar/util/JSONUtil.java +++ /dev/null @@ -1,140 +0,0 @@ -package co.aikar.util; - -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Provides Utility methods that assist with generating JSON Objects - */ -@SuppressWarnings({"rawtypes", "SuppressionAnnotation"}) -public final class JSONUtil { - private JSONUtil() {} - - /** - * Creates a key/value "JSONPair" object - * - * @param key Key to use - * @param obj Value to use - * @return JSONPair - */ - @NotNull - public static JSONPair pair(@NotNull String key, @Nullable Object obj) { - return new JSONPair(key, obj); - } - - @NotNull - public static JSONPair pair(long key, @Nullable Object obj) { - return new JSONPair(String.valueOf(key), obj); - } - - /** - * Creates a new JSON object from multiple JSONPair key/value pairs - * - * @param data JSONPairs - * @return Map - */ - @NotNull - public static Map createObject(@NotNull JSONPair... data) { - return appendObjectData(new LinkedHashMap(), data); - } - - /** - * This appends multiple key/value Obj pairs into a JSON Object - * - * @param parent Map to be appended to - * @param data Data to append - * @return Map - */ - @NotNull - public static Map appendObjectData(@NotNull Map parent, @NotNull JSONPair... data) { - for (JSONPair JSONPair : data) { - parent.put(JSONPair.key, JSONPair.val); - } - return parent; - } - - /** - * This builds a JSON array from a set of data - * - * @param data Data to build JSON array from - * @return List - */ - @NotNull - public static List toArray(@NotNull Object... data) { - return Lists.newArrayList(data); - } - - /** - * These help build a single JSON array using a mapper function - * - * @param collection Collection to apply to - * @param mapper Mapper to apply - * @param Element Type - * @return List - */ - @NotNull - public static List toArrayMapper(@NotNull E[] collection, @NotNull Function mapper) { - return toArrayMapper(Lists.newArrayList(collection), mapper); - } - - @NotNull - public static List toArrayMapper(@NotNull Iterable collection, @NotNull Function mapper) { - List array = Lists.newArrayList(); - for (E e : collection) { - Object object = mapper.apply(e); - if (object != null) { - array.add(object); - } - } - return array; - } - - /** - * These help build a single JSON Object from a collection, using a mapper function - * - * @param collection Collection to apply to - * @param mapper Mapper to apply - * @param Element Type - * @return Map - */ - @NotNull - public static Map toObjectMapper(@NotNull E[] collection, @NotNull Function mapper) { - return toObjectMapper(Lists.newArrayList(collection), mapper); - } - - @NotNull - public static Map toObjectMapper(@NotNull Iterable collection, @NotNull Function mapper) { - Map object = Maps.newLinkedHashMap(); - for (E e : collection) { - JSONPair JSONPair = mapper.apply(e); - if (JSONPair != null) { - object.put(JSONPair.key, JSONPair.val); - } - } - return object; - } - - /** - * Simply stores a key and a value, used internally by many methods below. - */ - @SuppressWarnings("PublicInnerClass") - public static class JSONPair { - final String key; - final Object val; - - JSONPair(@NotNull String key, @NotNull Object val) { - this.key = key; - this.val = val; - } - } -} diff --git a/api/src/main/java/co/aikar/util/LoadingIntMap.java b/api/src/main/java/co/aikar/util/LoadingIntMap.java deleted file mode 100644 index 63a899c7d..000000000 --- a/api/src/main/java/co/aikar/util/LoadingIntMap.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2015. Starlis LLC / dba Empire Minecraft - * - * This source code is proprietary software and must not be redistributed without Starlis LLC's approval - * - */ -package co.aikar.util; - - -import com.google.common.base.Function; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Allows you to pass a Loader function that when a key is accessed that doesn't exist, - * automatically loads the entry into the map by calling the loader Function. - * - * .get() Will only return null if the Loader can return null. - * - * You may pass any backing Map to use. - * - * This class is not thread safe and should be wrapped with Collections.synchronizedMap on the OUTSIDE of the LoadingMap if needed. - * - * Do not wrap the backing map with Collections.synchronizedMap. - * - * @param Value - */ -public class LoadingIntMap extends Int2ObjectOpenHashMap { - private final Function loader; - - public LoadingIntMap(@NotNull Function loader) { - super(); - this.loader = loader; - } - - public LoadingIntMap(int expectedSize, @NotNull Function loader) { - super(expectedSize); - this.loader = loader; - } - - public LoadingIntMap(int expectedSize, float loadFactor, @NotNull Function loader) { - super(expectedSize, loadFactor); - this.loader = loader; - } - - - @Nullable - @Override - public V get(int key) { - V res = super.get(key); - if (res == null) { - res = loader.apply(key); - if (res != null) { - put(key, res); - } - } - return res; - } - - /** - * Due to java stuff, you will need to cast it to (Function) for some cases - * - * @param Type - */ - public abstract static class Feeder implements Function { - @Nullable - @Override - public T apply(@Nullable Object input) { - return apply(); - } - - @Nullable - public abstract T apply(); - } -} diff --git a/api/src/main/java/co/aikar/util/LoadingMap.java b/api/src/main/java/co/aikar/util/LoadingMap.java deleted file mode 100644 index aedbb0332..000000000 --- a/api/src/main/java/co/aikar/util/LoadingMap.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.util; - -import com.google.common.base.Preconditions; -import java.lang.reflect.Constructor; -import java.util.AbstractMap; -import java.util.Collection; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Allows you to pass a Loader function that when a key is accessed that doesn't exists, - * automatically loads the entry into the map by calling the loader Function. - * - * .get() Will only return null if the Loader can return null. - * - * You may pass any backing Map to use. - * - * This class is not thread safe and should be wrapped with Collections.synchronizedMap on the OUTSIDE of the LoadingMap if needed. - * - * Do not wrap the backing map with Collections.synchronizedMap. - * - * @param Key - * @param Value - */ -public class LoadingMap extends AbstractMap { - private final Map backingMap; - private final java.util.function.Function loader; - - /** - * Initializes an auto loading map using specified loader and backing map - * @param backingMap Map to wrap - * @param loader Loader - */ - public LoadingMap(@NotNull Map backingMap, @NotNull java.util.function.Function loader) { - this.backingMap = backingMap; - this.loader = loader; - } - - /** - * Creates a new LoadingMap with the specified map and loader - * - * @param backingMap Actual map being used. - * @param loader Loader to use - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map - */ - @NotNull - public static Map of(@NotNull Map backingMap, @NotNull Function loader) { - return new LoadingMap<>(backingMap, loader); - } - - /** - * Creates a LoadingMap with an auto instantiating loader. - * - * Will auto construct class of of Value when not found - * - * Since this uses Reflection, It is more effecient to define your own static loader - * than using this helper, but if performance is not critical, this is easier. - * - * @param backingMap Actual map being used. - * @param keyClass Class used for the K generic - * @param valueClass Class used for the V generic - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map that auto instantiates on .get() - */ - @NotNull - public static Map newAutoMap(@NotNull Map backingMap, @Nullable final Class keyClass, - @NotNull final Class valueClass) { - return new LoadingMap<>(backingMap, new AutoInstantiatingLoader<>(keyClass, valueClass)); - } - /** - * Creates a LoadingMap with an auto instantiating loader. - * - * Will auto construct class of of Value when not found - * - * Since this uses Reflection, It is more effecient to define your own static loader - * than using this helper, but if performance is not critical, this is easier. - * - * @param backingMap Actual map being used. - * @param valueClass Class used for the V generic - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map that auto instantiates on .get() - */ - @NotNull - public static Map newAutoMap(@NotNull Map backingMap, - @NotNull final Class valueClass) { - return newAutoMap(backingMap, null, valueClass); - } - - /** - * @see #newAutoMap - * - * new Auto initializing map using a HashMap. - * - * @param keyClass Class used for the K generic - * @param valueClass Class used for the V generic - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map that auto instantiates on .get() - */ - @NotNull - public static Map newHashAutoMap(@Nullable final Class keyClass, @NotNull final Class valueClass) { - return newAutoMap(new HashMap<>(), keyClass, valueClass); - } - - /** - * @see #newAutoMap - * - * new Auto initializing map using a HashMap. - * - * @param valueClass Class used for the V generic - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map that auto instantiates on .get() - */ - @NotNull - public static Map newHashAutoMap(@NotNull final Class valueClass) { - return newHashAutoMap(null, valueClass); - } - - /** - * @see #newAutoMap - * - * new Auto initializing map using a HashMap. - * - * @param keyClass Class used for the K generic - * @param valueClass Class used for the V generic - * @param initialCapacity Initial capacity to use - * @param loadFactor Load factor to use - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map that auto instantiates on .get() - */ - @NotNull - public static Map newHashAutoMap(@Nullable final Class keyClass, @NotNull final Class valueClass, int initialCapacity, float loadFactor) { - return newAutoMap(new HashMap<>(initialCapacity, loadFactor), keyClass, valueClass); - } - - /** - * @see #newAutoMap - * - * new Auto initializing map using a HashMap. - * - * @param valueClass Class used for the V generic - * @param initialCapacity Initial capacity to use - * @param loadFactor Load factor to use - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map that auto instantiates on .get() - */ - @NotNull - public static Map newHashAutoMap(@NotNull final Class valueClass, int initialCapacity, float loadFactor) { - return newHashAutoMap(null, valueClass, initialCapacity, loadFactor); - } - - /** - * Initializes an auto loading map using a HashMap - * - * @param loader Loader to use - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map - */ - @NotNull - public static Map newHashMap(@NotNull Function loader) { - return new LoadingMap<>(new HashMap<>(), loader); - } - - /** - * Initializes an auto loading map using a HashMap - * - * @param loader Loader to use - * @param initialCapacity Initial capacity to use - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map - */ - @NotNull - public static Map newHashMap(@NotNull Function loader, int initialCapacity) { - return new LoadingMap<>(new HashMap<>(initialCapacity), loader); - } - /** - * Initializes an auto loading map using a HashMap - * - * @param loader Loader to use - * @param initialCapacity Initial capacity to use - * @param loadFactor Load factor to use - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map - */ - @NotNull - public static Map newHashMap(@NotNull Function loader, int initialCapacity, float loadFactor) { - return new LoadingMap<>(new HashMap<>(initialCapacity, loadFactor), loader); - } - - /** - * Initializes an auto loading map using an Identity HashMap - * - * @param loader Loader to use - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map - */ - @NotNull - public static Map newIdentityHashMap(@NotNull Function loader) { - return new LoadingMap<>(new IdentityHashMap<>(), loader); - } - - /** - * Initializes an auto loading map using an Identity HashMap - * - * @param loader Loader to use - * @param initialCapacity Initial capacity to use - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map - */ - @NotNull - public static Map newIdentityHashMap(@NotNull Function loader, int initialCapacity) { - return new LoadingMap<>(new IdentityHashMap<>(initialCapacity), loader); - } - - @Override - public int size() {return backingMap.size();} - - @Override - public boolean isEmpty() {return backingMap.isEmpty();} - - @Override - public boolean containsKey(@Nullable Object key) {return backingMap.containsKey(key);} - - @Override - public boolean containsValue(@Nullable Object value) {return backingMap.containsValue(value);} - - @Nullable - @Override - public V get(@Nullable Object key) { - V v = backingMap.get(key); - if (v != null) { - return v; - } - return backingMap.computeIfAbsent((K) key, loader); - } - - @Nullable - public V put(@Nullable K key, @Nullable V value) {return backingMap.put(key, value);} - - @Nullable - @Override - public V remove(@Nullable Object key) {return backingMap.remove(key);} - - public void putAll(@NotNull Map m) {backingMap.putAll(m);} - - @Override - public void clear() {backingMap.clear();} - - @NotNull - @Override - public Set keySet() {return backingMap.keySet();} - - @NotNull - @Override - public Collection values() {return backingMap.values();} - - @Override - public boolean equals(@Nullable Object o) {return backingMap.equals(o);} - - @Override - public int hashCode() {return backingMap.hashCode();} - - @NotNull - @Override - public Set> entrySet() { - return backingMap.entrySet(); - } - - @NotNull - public LoadingMap clone() { - return new LoadingMap<>(backingMap, loader); - } - - private static class AutoInstantiatingLoader implements Function { - final Constructor constructor; - private final Class valueClass; - - AutoInstantiatingLoader(@Nullable Class keyClass, @NotNull Class valueClass) { - try { - this.valueClass = valueClass; - if (keyClass != null) { - constructor = valueClass.getConstructor(keyClass); - } else { - constructor = null; - } - } catch (NoSuchMethodException e) { - throw new IllegalStateException( - valueClass.getName() + " does not have a constructor for " + (keyClass != null ? keyClass.getName() : null)); - } - } - - @NotNull - @Override - public V apply(@Nullable K input) { - try { - return (constructor != null ? constructor.newInstance(input) : valueClass.newInstance()); - } catch (Exception e) { - throw new ExceptionInInitializerError(e); - } - } - - @Override - public int hashCode() { - return super.hashCode(); - } - - @Override - public boolean equals(Object object) { - return false; - } - } - - /** - * Due to java stuff, you will need to cast it to (Function) for some cases - * - * @param Type - */ - public abstract static class Feeder implements Function { - @Nullable - @Override - public T apply(@Nullable Object input) { - return apply(); - } - - @Nullable - public abstract T apply(); - } -} diff --git a/api/src/main/java/co/aikar/util/MRUMapCache.java b/api/src/main/java/co/aikar/util/MRUMapCache.java deleted file mode 100644 index 5989ee212..000000000 --- a/api/src/main/java/co/aikar/util/MRUMapCache.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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 co.aikar.util; - -import java.util.AbstractMap; -import java.util.Collection; -import java.util.Map; -import java.util.Set; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Implements a Most Recently Used cache in front of a backing map, to quickly access the last accessed result. - * - * @param Key Type of the Map - * @param Value Type of the Map - */ -public class MRUMapCache extends AbstractMap { - final Map backingMap; - Object cacheKey; - V cacheValue; - public MRUMapCache(@NotNull final Map backingMap) { - this.backingMap = backingMap; - } - - public int size() {return backingMap.size();} - - public boolean isEmpty() {return backingMap.isEmpty();} - - public boolean containsKey(@Nullable Object key) { - return key != null && key.equals(cacheKey) || backingMap.containsKey(key); - } - - public boolean containsValue(@Nullable Object value) { - return value != null && value == cacheValue || backingMap.containsValue(value); - } - - @Nullable - public V get(@Nullable Object key) { - if (cacheKey != null && cacheKey.equals(key)) { - return cacheValue; - } - cacheKey = key; - return cacheValue = backingMap.get(key); - } - - @Nullable - public V put(@Nullable K key, @Nullable V value) { - cacheKey = key; - return cacheValue = backingMap.put(key, value); - } - - @Nullable - public V remove(@Nullable Object key) { - if (key != null && key.equals(cacheKey)) { - cacheKey = null; - } - return backingMap.remove(key); - } - - public void putAll(@NotNull Map m) {backingMap.putAll(m);} - - public void clear() { - cacheKey = null; - cacheValue = null; - backingMap.clear(); - } - - @NotNull - public Set keySet() {return backingMap.keySet();} - - @NotNull - public Collection values() {return backingMap.values();} - - @NotNull - public Set> entrySet() {return backingMap.entrySet();} - - /** - * Wraps the specified map with a most recently used cache - * - * @param map Map to be wrapped - * @param Key Type of the Map - * @param Value Type of the Map - * @return Map - */ - @NotNull - public static Map of(@NotNull Map map) { - return new MRUMapCache(map); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/HeightmapType.java b/api/src/main/java/com/destroystokyo/paper/HeightmapType.java deleted file mode 100644 index 4cd9b5ed0..000000000 --- a/api/src/main/java/com/destroystokyo/paper/HeightmapType.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.destroystokyo.paper; - -import org.bukkit.World; - -/** - * Enumeration of different heightmap types maintained by the server. Generally using these maps is much faster - * than using an iterative search for a block in a given x, z coordinate. - */ -public enum HeightmapType { - - /** - * The highest block used for lighting in the world. Also the block returned by {@link World#getHighestBlockYAt(int, int)}} - */ - LIGHT_BLOCKING, - - /** - * References the highest block in the world. - */ - ANY, - - /** - * References the highest solid block in a world. - */ - SOLID, - - /** - * References the highest solid or liquid block in a world. - */ - SOLID_OR_LIQUID, - - /** - * References the highest solid or liquid block in a world, excluding leaves. - */ - SOLID_OR_LIQUID_NO_LEAVES; -} diff --git a/api/src/main/java/com/destroystokyo/paper/MaterialSetTag.java b/api/src/main/java/com/destroystokyo/paper/MaterialSetTag.java deleted file mode 100644 index c91ea2a06..000000000 --- a/api/src/main/java/com/destroystokyo/paper/MaterialSetTag.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2018 Daniel Ennis (Aikar) MIT License - */ - -package com.destroystokyo.paper; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.Tag; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; - -import java.util.Collection; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class MaterialSetTag implements Tag { - - private final NamespacedKey key; - private final Set materials; - - /** - * @deprecated Use NamespacedKey version of constructor - */ - @Deprecated - public MaterialSetTag(@NotNull Predicate filter) { - this(null, Stream.of(Material.values()).filter(filter).collect(Collectors.toList())); - } - - /** - * @deprecated Use NamespacedKey version of constructor - */ - @Deprecated - public MaterialSetTag(@NotNull Collection materials) { - this(null, materials); - } - - /** - * @deprecated Use NamespacedKey version of constructor - */ - @Deprecated - public MaterialSetTag(@NotNull Material... materials) { - this(null, materials); - } - - public MaterialSetTag(@Nullable NamespacedKey key, @NotNull Predicate filter) { - this(key, Stream.of(Material.values()).filter(filter).collect(Collectors.toList())); - } - - public MaterialSetTag(@Nullable NamespacedKey key, @NotNull Material... materials) { - this(key, Lists.newArrayList(materials)); - } - - public MaterialSetTag(@Nullable NamespacedKey key, @NotNull Collection materials) { - this.key = key != null ? key : NamespacedKey.randomKey(); - this.materials = Sets.newEnumSet(materials, Material.class); - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - - @NotNull - public MaterialSetTag add(@NotNull Tag... tags) { - for (Tag tag : tags) { - add(tag.getValues()); - } - return this; - } - - @NotNull - public MaterialSetTag add(@NotNull MaterialSetTag... tags) { - for (Tag tag : tags) { - add(tag.getValues()); - } - return this; - } - - @NotNull - public MaterialSetTag add(@NotNull Material... material) { - this.materials.addAll(Lists.newArrayList(material)); - return this; - } - - @NotNull - public MaterialSetTag add(@NotNull Collection materials) { - this.materials.addAll(materials); - return this; - } - - @NotNull - public MaterialSetTag contains(@NotNull String with) { - return add(mat -> mat.name().contains(with)); - } - - @NotNull - public MaterialSetTag endsWith(@NotNull String with) { - return add(mat -> mat.name().endsWith(with)); - } - - - @NotNull - public MaterialSetTag startsWith(@NotNull String with) { - return add(mat -> mat.name().startsWith(with)); - } - @NotNull - public MaterialSetTag add(@NotNull Predicate filter) { - add(Stream.of(Material.values()).filter(((Predicate) Material::isLegacy).negate()).filter(filter).collect(Collectors.toList())); - return this; - } - - @NotNull - public MaterialSetTag not(@NotNull MaterialSetTag tags) { - not(tags.getValues()); - return this; - } - - @NotNull - public MaterialSetTag not(@NotNull Material... material) { - this.materials.removeAll(Lists.newArrayList(material)); - return this; - } - - @NotNull - public MaterialSetTag not(@NotNull Collection materials) { - this.materials.removeAll(materials); - return this; - } - - @NotNull - public MaterialSetTag not(@NotNull Predicate filter) { - not(Stream.of(Material.values()).filter(((Predicate) Material::isLegacy).negate()).filter(filter).collect(Collectors.toList())); - return this; - } - - @NotNull - public MaterialSetTag notEndsWith(@NotNull String with) { - return not(mat -> mat.name().endsWith(with)); - } - - - @NotNull - public MaterialSetTag notStartsWith(@NotNull String with) { - return not(mat -> mat.name().startsWith(with)); - } - - @NotNull - public Set getValues() { - return this.materials; - } - - public boolean isTagged(@NotNull BlockData block) { - return isTagged(block.getMaterial()); - } - - public boolean isTagged(@NotNull BlockState block) { - return isTagged(block.getType()); - } - - public boolean isTagged(@NotNull Block block) { - return isTagged(block.getType()); - } - - public boolean isTagged(@NotNull ItemStack item) { - return isTagged(item.getType()); - } - - public boolean isTagged(@NotNull Material material) { - return this.materials.contains(material); - } - - @NotNull - public MaterialSetTag ensureSize(@NotNull String label, int size) { - long actual = this.materials.stream().filter(((Predicate) Material::isLegacy).negate()).count(); - if (size != actual) { - throw new IllegalStateException(label + " - Expected " + size + " materials, got " + actual); - } - return this; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/MaterialTags.java b/api/src/main/java/com/destroystokyo/paper/MaterialTags.java deleted file mode 100644 index ef1e2c191..000000000 --- a/api/src/main/java/com/destroystokyo/paper/MaterialTags.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * 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 com.destroystokyo.paper; - -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.Tag; - -/** - * Represents a collection tags to identify materials that share common properties. - * Will map to minecraft for missing tags, as well as custom ones that may be useful. - */ -@SuppressWarnings({"NonFinalUtilityClass", "unused", "WeakerAccess"}) -public class MaterialTags { - - private static NamespacedKey keyFor(String key) { - //noinspection deprecation - return new NamespacedKey("paper", key + "_settag"); - } - public static final MaterialSetTag ARROWS = new MaterialSetTag(keyFor("arrows")) - .endsWith("ARROW") - .ensureSize("ARROWS", 3); - - /** - * Cover all 16 colors of beds. - */ - public static final MaterialSetTag BEDS = new MaterialSetTag(keyFor("beds")) - .endsWith("_BED") - .ensureSize("BEDS", 16); - - /** - * Covers all bucket items. - */ - public static final MaterialSetTag BUCKETS = new MaterialSetTag(keyFor("buckets")) - .endsWith("BUCKET") - .ensureSize("BUCKETS", 8); - - /** - * Covers coal and charcoal. - */ - public static final MaterialSetTag COALS = new MaterialSetTag(keyFor("coals")) - .add(Material.COAL, Material.CHARCOAL); - - /** - * Covers both cobblestone wall variants. - */ - public static final MaterialSetTag COBBLESTONE_WALLS = new MaterialSetTag(keyFor("cobblestone_walls")) - .endsWith("COBBLESTONE_WALL") - .ensureSize("COBBLESTONE_WALLS", 2); - - /** - * Covers both cobblestone and mossy Cobblestone. - */ - public static final MaterialSetTag COBBLESTONES = new MaterialSetTag(keyFor("cobblestones")) - .add(Material.COBBLESTONE, Material.MOSSY_COBBLESTONE); - - /** - * Covers all 16 colors of concrete. - */ - public static final MaterialSetTag CONCRETES = new MaterialSetTag(keyFor("concretes")) - .endsWith("_CONCRETE") - .ensureSize("CONCRETES", 16); - - /** - * Covers all 16 colors of concrete powder. - */ - public static final MaterialSetTag CONCRETE_POWDER = new MaterialSetTag(keyFor("concrete_powder")) - .endsWith("_CONCRETE_POWDER") - .ensureSize("CONCRETE_POWDER", 16); - - /** - * Covers the two types of cooked fish. - */ - public static final MaterialSetTag COOKED_FISH = new MaterialSetTag(keyFor("cooked_fish")) - .add(Material.COOKED_COD, Material.COOKED_SALMON); - - /** - * Covers all 16 dyes. - */ - public static final MaterialSetTag DYES = new MaterialSetTag(keyFor("dyes")) - .endsWith("_DYE") - .ensureSize("DYES", 16); - - /** - * Covers all 6 wood variants of gates. - */ - public static final MaterialSetTag FENCE_GATES = new MaterialSetTag(keyFor("fence_gates")) - .endsWith("_GATE") - .ensureSize("FENCE_GATES", 6); - - /** - * Covers all 6 wood variants and nether brick fence. - */ - public static final MaterialSetTag FENCES = new MaterialSetTag(keyFor("fences")) - .endsWith("_FENCE") - .ensureSize("FENCES", 7); - - /** - * Covers all 4 variants of fish buckets. - */ - public static final MaterialSetTag FISH_BUCKETS = new MaterialSetTag(keyFor("fish_buckets")) - .add(Material.COD_BUCKET, Material.PUFFERFISH_BUCKET, Material.SALMON_BUCKET, Material.TROPICAL_FISH_BUCKET); - - /** - * Covers the non-colored glass and 16 stained glass (not panes). - */ - public static final MaterialSetTag GLASS = new MaterialSetTag(keyFor("glass")) - .endsWith("_GLASS") - .add(Material.GLASS) - .ensureSize("GLASS", 17); - - /** - * Covers the non-colored glass panes and 16 stained glass panes (panes only). - */ - public static final MaterialSetTag GLASS_PANES = new MaterialSetTag(keyFor("glass_panes")) - .endsWith("GLASS_PANE") - .ensureSize("GLASS_PANES", 17); - - /** - * Covers all 16 glazed terracotta blocks. - */ - public static final MaterialSetTag GLAZED_TERRACOTTA = new MaterialSetTag(keyFor("glazed_terracotta")) - .endsWith("GLAZED_TERRACOTTA") - .ensureSize("GLAZED_TERRACOTTA", 16); - - /** - * Covers the 16 colors of stained terracotta. - */ - public static final MaterialSetTag STAINED_TERRACOTTA = new MaterialSetTag(keyFor("stained_terracotta")) - .endsWith("TERRACOTTA") - .not(Material.TERRACOTTA) - .notEndsWith("GLAZED_TERRACOTTA") - .ensureSize("STAINED_TERRACOTTA", 16); - - /** - * Covers terracotta along with the 16 stained variants. - */ - public static final MaterialSetTag TERRACOTTA = new MaterialSetTag(keyFor("terracotta")) - .endsWith("TERRACOTTA") - .ensureSize("TERRACOTTA", 33); - - - /** - * Covers both golden apples. - */ - public static final MaterialSetTag GOLDEN_APPLES = new MaterialSetTag(keyFor("golden_apples")) - .endsWith("GOLDEN_APPLE") - .ensureSize("GOLDEN_APPLES", 2); - - /** - * Covers the 3 variants of horse armor. - */ - public static final MaterialSetTag HORSE_ARMORS = new MaterialSetTag(keyFor("horse_armors")) - .endsWith("_HORSE_ARMOR") - .ensureSize("HORSE_ARMORS", 4); - - /** - * Covers the 6 variants of infested blocks. - */ - public static final MaterialSetTag INFESTED_BLOCKS = new MaterialSetTag(keyFor("infested_blocks")) - .startsWith("INFESTED_") - .ensureSize("INFESTED_BLOCKS", 6); - - /** - * Covers the 3 variants of mushroom blocks. - */ - public static final MaterialSetTag MUSHROOM_BLOCKS = new MaterialSetTag(keyFor("mushroom_blocks")) - .endsWith("MUSHROOM_BLOCK") - .add(Material.MUSHROOM_STEM) - .ensureSize("MUSHROOM_BLOCKS", 3); - - /** - * Covers both mushrooms. - */ - public static final MaterialSetTag MUSHROOMS = new MaterialSetTag(keyFor("mushrooms")) - .add(Material.BROWN_MUSHROOM, Material.RED_MUSHROOM); - - /** - * Covers all 12 music disc items. - */ - public static final MaterialSetTag MUSIC_DISCS = new MaterialSetTag(keyFor("music_discs")) - .startsWith("MUSIC_DISC_") - .ensureSize("MUSIC_DISCS", 12); - - /** - * Covers all 8 ores. - */ - public static final MaterialSetTag ORES = new MaterialSetTag(keyFor("ores")) - .endsWith("_ORE") - .ensureSize("ORES", 8); - - /** - * Covers all piston typed items and blocks including the piston head and moving piston. - */ - public static final MaterialSetTag PISTONS = new MaterialSetTag(keyFor("pistons")) - .contains("PISTON") - .ensureSize("PISTONS", 4); - - /** - * Covers all potato items. - */ - public static final MaterialSetTag POTATOES = new MaterialSetTag(keyFor("potatoes")) - .endsWith("POTATO") - .ensureSize("POTATOES", 3); - - /** - * Covers all 6 wooden pressure plates and the 2 weighted pressure plates and 1 stone pressure plate. - */ - public static final MaterialSetTag PRESSURE_PLATES = new MaterialSetTag(keyFor("pressure_plates")) - .endsWith("_PRESSURE_PLATE") - .ensureSize("PRESSURE_PLATES", 9); - - /** - * Covers the 3 variants of prismarine blocks. - */ - public static final MaterialSetTag PRISMARINE = new MaterialSetTag(keyFor("prismarine")) - .add(Material.PRISMARINE, Material.PRISMARINE_BRICKS, Material.DARK_PRISMARINE); - - /** - * Covers the 3 variants of prismarine slabs. - */ - public static final MaterialSetTag PRISMARINE_SLABS = new MaterialSetTag(keyFor("prismarine_slabs")) - .add(Material.PRISMARINE_SLAB, Material.PRISMARINE_BRICK_SLAB, Material.DARK_PRISMARINE_SLAB); - - /** - * Covers the 3 variants of prismarine stairs. - */ - public static final MaterialSetTag PRISMARINE_STAIRS = new MaterialSetTag(keyFor("prismarine_stairs")) - .add(Material.PRISMARINE_STAIRS, Material.PRISMARINE_BRICK_STAIRS, Material.DARK_PRISMARINE_STAIRS); - - /** - * Covers the 3 variants of pumpkins. - */ - public static final MaterialSetTag PUMPKINS = new MaterialSetTag(keyFor("pumpkins")) - .add(Material.CARVED_PUMPKIN, Material.JACK_O_LANTERN, Material.PUMPKIN); - - /** - * Covers the 4 variants of quartz blocks. - */ - public static final MaterialSetTag QUARTZ_BLOCKS = new MaterialSetTag(keyFor("quartz_blocks")) - .add(Material.QUARTZ_BLOCK, Material.QUARTZ_PILLAR, Material.CHISELED_QUARTZ_BLOCK, Material.SMOOTH_QUARTZ); - - /** - * Covers all uncooked fish items. - */ - public static final MaterialSetTag RAW_FISH = new MaterialSetTag(keyFor("raw_fish")) - .add(Material.COD, Material.PUFFERFISH, Material.SALMON, Material.TROPICAL_FISH); - - /** - * Covers the 4 variants of red sandstone blocks. - */ - public static final MaterialSetTag RED_SANDSTONES = new MaterialSetTag(keyFor("red_sandstones")) - .endsWith("RED_SANDSTONE") - .ensureSize("RED_SANDSTONES", 4); - - /** - * Covers the 4 variants of sandstone blocks. - */ - public static final MaterialSetTag SANDSTONES = new MaterialSetTag(keyFor("sandstones")) - .add(Material.SANDSTONE, Material.CHISELED_SANDSTONE, Material.CUT_SANDSTONE, Material.SMOOTH_SANDSTONE); - - /** - * Covers sponge and wet sponge. - */ - public static final MaterialSetTag SPONGES = new MaterialSetTag(keyFor("sponges")) - .endsWith("SPONGE") - .ensureSize("SPONGES", 2); - - /** - * Covers the non-colored and 16 colored shulker boxes. - */ - public static final MaterialSetTag SHULKER_BOXES = new MaterialSetTag(keyFor("shulker_boxes")) - .endsWith("SHULKER_BOX") - .ensureSize("SHULKER_BOXES", 17); - - /** - * Covers zombie, creeper, skeleton, dragon, and player heads. - */ - public static final MaterialSetTag SKULLS = new MaterialSetTag(keyFor("skulls")) - .endsWith("_HEAD") - .endsWith("_SKULL") - .not(Material.PISTON_HEAD) - .ensureSize("SKULLS", 12); - - /** - * Covers all spawn egg items. - */ - public static final MaterialSetTag SPAWN_EGGS = new MaterialSetTag(keyFor("spawn_eggs")) - .endsWith("_SPAWN_EGG") - .ensureSize("SPAWN_EGGS", 58); - - /** - * Covers all 16 colors of stained glass. - */ - public static final MaterialSetTag STAINED_GLASS = new MaterialSetTag(keyFor("stained_glass")) - .endsWith("_STAINED_GLASS") - .ensureSize("STAINED_GLASS", 16); - - /** - * Covers all 16 colors of stained glass panes. - */ - public static final MaterialSetTag STAINED_GLASS_PANES = new MaterialSetTag(keyFor("stained_glass_panes")) - .endsWith("STAINED_GLASS_PANE") - .ensureSize("STAINED_GLASS_PANES", 16); - - /** - * Covers all 7 variants of trapdoors. - */ - public static final MaterialSetTag TRAPDOORS = new MaterialSetTag(keyFor("trapdoors")) - .endsWith("_TRAPDOOR") - .ensureSize("TRAPDOORS", 7); - - /** - * Covers all 6 wood variants of fences. - */ - public static final MaterialSetTag WOODEN_FENCES = new MaterialSetTag(keyFor("wooden_fences")) - .endsWith("_FENCE") - .not(Material.NETHER_BRICK_FENCE) - .ensureSize("WOODEN_FENCES", 6); - - /** - * Covers all 6 wood variants of trapdoors. - */ - public static final MaterialSetTag WOODEN_TRAPDOORS = new MaterialSetTag(keyFor("wooden_trapdoors")) - .endsWith("_TRAPDOOR") - .not(Material.IRON_TRAPDOOR) - .ensureSize("WOODEN_TRAPDOORS", 6); - - public static final MaterialSetTag WOODEN_GATES = new MaterialSetTag(keyFor("wooden_gates")) - .endsWith("_GATE") - .ensureSize("WOODEN_GATES", 6); - - public static final MaterialSetTag PURPUR = new MaterialSetTag(keyFor("purpur")) - .startsWith("PURPUR_") - .ensureSize("PURPUR", 4); - - public static final MaterialSetTag SIGNS = new MaterialSetTag(keyFor("signs")) - .endsWith("_SIGN") - .ensureSize("SIGNS", 12); - - public static final MaterialSetTag TORCH = new MaterialSetTag(keyFor("torch")) - .add(Material.TORCH, Material.WALL_TORCH) - .ensureSize("TORCH", 2); - - public static final MaterialSetTag REDSTONE_TORCH = new MaterialSetTag(keyFor("restone_torch")) - .add(Material.REDSTONE_TORCH, Material.REDSTONE_WALL_TORCH) - .ensureSize("REDSTONE_TORCH", 2); - - @SuppressWarnings("unchecked") - public static final MaterialSetTag COLORABLE = new MaterialSetTag(keyFor("colorable")) - .add(Tag.WOOL, Tag.CARPETS).add(SHULKER_BOXES, STAINED_GLASS, STAINED_GLASS_PANES, CONCRETES, BEDS); - //.ensureSize("COLORABLE", 81); unit test don't have the vanilla item tags, so counts don't line up for real -} diff --git a/api/src/main/java/com/destroystokyo/paper/Namespaced.java b/api/src/main/java/com/destroystokyo/paper/Namespaced.java deleted file mode 100644 index cd1a34b82..000000000 --- a/api/src/main/java/com/destroystokyo/paper/Namespaced.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.destroystokyo.paper; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents a namespaced resource, see {@link org.bukkit.NamespacedKey} for single elements - * or {@link com.destroystokyo.paper.NamespacedTag} for a collection of elements - * - * Namespaces may only contain lowercase alphanumeric characters, periods, - * underscores, and hyphens. - *

- * Keys may only contain lowercase alphanumeric characters, periods, - * underscores, hyphens, and forward slashes. - *

- * You should not be implementing this interface yourself, use {@link org.bukkit.NamespacedKey} - * or {@link com.destroystokyo.paper.NamespacedTag} as needed instead. - */ -public interface Namespaced { - /** - * Gets the namespace this resource is a part of - *

- * This is contractually obligated to only contain lowercase alphanumeric characters, - * periods, underscores, and hyphens. - * - * @return resource namespace - */ - @NotNull - String getNamespace(); - - /** - * Gets the key corresponding to this resource - *

- * This is contractually obligated to only contain lowercase alphanumeric characters, - * periods, underscores, hyphens, and forward slashes. - * - * @return resource key - */ - @NotNull - String getKey(); -} diff --git a/api/src/main/java/com/destroystokyo/paper/NamespacedTag.java b/api/src/main/java/com/destroystokyo/paper/NamespacedTag.java deleted file mode 100644 index 28f3fda95..000000000 --- a/api/src/main/java/com/destroystokyo/paper/NamespacedTag.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.destroystokyo.paper; - -import com.google.common.base.Preconditions; -import java.util.Locale; -import java.util.UUID; -import java.util.regex.Pattern; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a String based key pertaining to a tagged entry. Consists of two components - a namespace - * and a key. - *

- * Namespaces may only contain lowercase alphanumeric characters, periods, - * underscores, and hyphens. - *

- * Keys may only contain lowercase alphanumeric characters, periods, - * underscores, hyphens, and forward slashes. - * - */ -// Paper - entire class, based on org.bukkit.NamespacedKey -public final class NamespacedTag implements com.destroystokyo.paper.Namespaced { - - /** - * The namespace representing all inbuilt keys. - */ - public static final String MINECRAFT = "minecraft"; - /** - * The namespace representing all keys generated by Bukkit for backwards - * compatibility measures. - */ - public static final String BUKKIT = "bukkit"; - // - private static final Pattern VALID_NAMESPACE = Pattern.compile("[a-z0-9._-]+"); - private static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); - // - private final String namespace; - private final String key; - - /** - * Create a key in a specific namespace. - * - * @param namespace String representing a grouping of keys - * @param key Name for this specific key - * @deprecated should never be used by plugins, for internal use only!! - */ - @Deprecated - public NamespacedTag(@NotNull String namespace, @NotNull String key) { - Preconditions.checkArgument(namespace != null && VALID_NAMESPACE.matcher(namespace).matches(), "Invalid namespace. Must be [a-z0-9._-]: %s", namespace); - Preconditions.checkArgument(key != null && VALID_KEY.matcher(key).matches(), "Invalid key. Must be [a-z0-9/._-]: %s", key); - - this.namespace = namespace; - this.key = key; - - String string = toString(); - Preconditions.checkArgument(string.length() < 256, "NamespacedTag must be less than 256 characters", string); - } - - /** - * Create a key in the plugin's namespace. - *

- * Namespaces may only contain lowercase alphanumeric characters, periods, - * underscores, and hyphens. - *

- * Keys may only contain lowercase alphanumeric characters, periods, - * underscores, hyphens, and forward slashes. - * - * @param plugin the plugin to use for the namespace - * @param key the key to create - */ - public NamespacedTag(@NotNull Plugin plugin, @NotNull String key) { - Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); - Preconditions.checkArgument(key != null, "Key cannot be null"); - - this.namespace = plugin.getName().toLowerCase(Locale.ROOT); - this.key = key.toLowerCase().toLowerCase(Locale.ROOT); - - // Check validity after normalization - Preconditions.checkArgument(VALID_NAMESPACE.matcher(this.namespace).matches(), "Invalid namespace. Must be [a-z0-9._-]: %s", this.namespace); - Preconditions.checkArgument(VALID_KEY.matcher(this.key).matches(), "Invalid key. Must be [a-z0-9/._-]: %s", this.key); - - String string = toString(); - Preconditions.checkArgument(string.length() < 256, "NamespacedTag must be less than 256 characters (%s)", string); - } - - @NotNull - public String getNamespace() { - return namespace; - } - - @NotNull - public String getKey() { - return key; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 47 * hash + this.namespace.hashCode(); - hash = 47 * hash + this.key.hashCode(); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final NamespacedTag other = (NamespacedTag) obj; - return this.namespace.equals(other.namespace) && this.key.equals(other.key); - } - - @Override - public String toString() { - return "#" + this.namespace + ":" + this.key; - } - - /** - * Return a new random key in the {@link #BUKKIT} namespace. - * - * @return new key - * @deprecated should never be used by plugins, for internal use only!! - */ - @Deprecated - public static NamespacedTag randomKey() { - return new NamespacedTag(BUKKIT, UUID.randomUUID().toString()); - } - - /** - * Get a key in the Minecraft namespace. - * - * @param key the key to use - * @return new key in the Minecraft namespace - */ - @NotNull - public static NamespacedTag minecraft(@NotNull String key) { - return new NamespacedTag(MINECRAFT, key); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/ParticleBuilder.java b/api/src/main/java/com/destroystokyo/paper/ParticleBuilder.java deleted file mode 100644 index 06f1602f5..000000000 --- a/api/src/main/java/com/destroystokyo/paper/ParticleBuilder.java +++ /dev/null @@ -1,478 +0,0 @@ -package com.destroystokyo.paper; - -import com.google.common.collect.Lists; -import org.bukkit.Color; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.util.NumberConversions; - -import java.util.Collection; -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Helps prepare a particle to be sent to players. - * - * Usage of the builder is preferred over the super long {@link World#spawnParticle(Particle, Location, int, double, double, double, double, Object)} API - */ -public class ParticleBuilder { - - private Particle particle; - private List receivers; - private Player source; - private Location location; - private int count = 1; - private double offsetX = 0, offsetY = 0, offsetZ = 0; - private double extra = 1; - private Object data; - private boolean force = true; - - public ParticleBuilder(@NotNull Particle particle) { - this.particle = particle; - } - - /** - * Sends the particle to all receiving players (or all). This method is safe to use - * Asynchronously - * - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder spawn() { - if (this.location == null) { - throw new IllegalStateException("Please specify location for this particle"); - } - location.getWorld().spawnParticle(particle, receivers, source, - location.getX(), location.getY(), location.getZ(), - count, offsetX, offsetY, offsetZ, extra, data, force - ); - return this; - } - - /** - * @return The particle going to be sent - */ - @NotNull - public Particle particle() { - return particle; - } - - /** - * Changes what particle will be sent - * - * @param particle The particle - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder particle(@NotNull Particle particle) { - this.particle = particle; - return this; - } - - /** - * @return List of players who will receive the particle, or null for all in world - */ - @Nullable - public List receivers() { - return receivers; - } - - /** - * Example use: - * - * builder.receivers(16); if (builder.hasReceivers()) { sendParticleAsync(builder); } - * - * @return If this particle is going to be sent to someone - */ - public boolean hasReceivers() { - return (receivers == null && !location.getWorld().getPlayers().isEmpty()) || ( - receivers != null && !receivers.isEmpty()); - } - - /** - * Sends this particle to all players in the world. This is rather silly and you should likely not - * be doing this. - * - * Just be a logical person and use receivers by radius or collection. - * - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder allPlayers() { - this.receivers = null; - return this; - } - - /** - * @param receivers List of players to receive this particle, or null for all players in the - * world - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder receivers(@Nullable List receivers) { - // Had to keep this as we first made API List<> and not Collection, but removing this may break plugins compiled on older jars - // TODO: deprecate? - this.receivers = receivers != null ? Lists.newArrayList(receivers) : null; - return this; - } - - /** - * @param receivers List of players to receive this particle, or null for all players in the - * world - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder receivers(@Nullable Collection receivers) { - this.receivers = receivers != null ? Lists.newArrayList(receivers) : null; - return this; - } - - /** - * @param receivers List of players to be receive this particle, or null for all players in the - * world - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder receivers(@Nullable Player... receivers) { - this.receivers = receivers != null ? Lists.newArrayList(receivers) : null; - return this; - } - - /** - * Selects all players within a cuboid selection around the particle location, within the - * specified bounding box. If you want a more spherical check, see {@link #receivers(int, - * boolean)} - * - * @param radius amount to add on all axis - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder receivers(int radius) { - return receivers(radius, radius); - } - - /** - * Selects all players within the specified radius around the particle location. If byDistance is - * false, behavior uses cuboid selection the same as {@link #receivers(int, int)} If byDistance is - * true, radius is tested by distance in a spherical shape - * - * @param radius amount to add on each axis - * @param byDistance true to use a spherical radius, false to use a cuboid - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder receivers(int radius, boolean byDistance) { - if (!byDistance) { - return receivers(radius, radius, radius); - } else { - this.receivers = Lists.newArrayList(); - for (Player nearbyPlayer : location.getWorld() - .getNearbyPlayers(location, radius, radius, radius)) { - Location loc = nearbyPlayer.getLocation(); - double x = NumberConversions.square(location.getX() - loc.getX()); - double y = NumberConversions.square(location.getY() - loc.getY()); - double z = NumberConversions.square(location.getZ() - loc.getZ()); - if (Math.sqrt(x + y + z) > radius) { - continue; - } - this.receivers.add(nearbyPlayer); - } - return this; - } - } - - /** - * Selects all players within a cuboid selection around the particle location, within the - * specified bounding box. Allows specifying a different Y size than X and Z If you want a more - * cylinder check, see {@link #receivers(int, int, boolean)} If you want a more spherical check, - * see {@link #receivers(int, boolean)} - * - * @param xzRadius amount to add on the x/z axis - * @param yRadius amount to add on the y axis - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder receivers(int xzRadius, int yRadius) { - return receivers(xzRadius, yRadius, xzRadius); - } - - /** - * Selects all players within the specified radius around the particle location. If byDistance is - * false, behavior uses cuboid selection the same as {@link #receivers(int, int)} If byDistance is - * true, radius is tested by distance on the y plane and on the x/z plane, in a cylinder shape. - * - * @param xzRadius amount to add on the x/z axis - * @param yRadius amount to add on the y axis - * @param byDistance true to use a cylinder shape, false to use cuboid - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder receivers(int xzRadius, int yRadius, boolean byDistance) { - if (!byDistance) { - return receivers(xzRadius, yRadius, xzRadius); - } else { - this.receivers = Lists.newArrayList(); - for (Player nearbyPlayer : location.getWorld() - .getNearbyPlayers(location, xzRadius, yRadius, xzRadius)) { - Location loc = nearbyPlayer.getLocation(); - if (Math.abs(loc.getY() - this.location.getY()) > yRadius) { - continue; - } - double x = NumberConversions.square(location.getX() - loc.getX()); - double z = NumberConversions.square(location.getZ() - loc.getZ()); - if (x + z > NumberConversions.square(xzRadius)) { - continue; - } - this.receivers.add(nearbyPlayer); - } - return this; - } - } - - /** - * Selects all players within a cuboid selection around the particle location, within the - * specified bounding box. If you want a more cylinder check, see {@link #receivers(int, int, - * boolean)} If you want a more spherical check, see {@link #receivers(int, boolean)} - * - * @param xRadius amount to add on the x axis - * @param yRadius amount to add on the y axis - * @param zRadius amount to add on the z axis - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder receivers(int xRadius, int yRadius, int zRadius) { - if (location == null) { - throw new IllegalStateException("Please set location first"); - } - return receivers(location.getWorld().getNearbyPlayers(location, xRadius, yRadius, zRadius)); - } - - /** - * @return The player considered the source of this particle (for Visibility concerns), or null - */ - @Nullable - public Player source() { - return source; - } - - /** - * Sets the source of this particle for visibility concerns (Vanish API) - * - * @param source The player who is considered the source - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder source(@Nullable Player source) { - this.source = source; - return this; - } - - /** - * @return Location of where the particle will spawn - */ - @Nullable - public Location location() { - return location; - } - - /** - * Sets the location of where to spawn the particle - * - * @param location The location of the particle - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder location(@NotNull Location location) { - this.location = location.clone(); - return this; - } - - /** - * Sets the location of where to spawn the particle - * - * @param world World to spawn particle in - * @param x X location - * @param y Y location - * @param z Z location - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder location(@NotNull World world, double x, double y, double z) { - this.location = new Location(world, x, y, z); - return this; - } - - /** - * @return Number of particles to spawn - */ - public int count() { - return count; - } - - /** - * Sets the number of particles to spawn - * - * @param count Number of particles - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder count(int count) { - this.count = count; - return this; - } - - /** - * Particle offset X. Varies by particle on how this is used - * - * @return Particle offset X. - */ - public double offsetX() { - return offsetX; - } - - /** - * Particle offset Y. Varies by particle on how this is used - * - * @return Particle offset Y. - */ - public double offsetY() { - return offsetY; - } - - /** - * Particle offset Z. Varies by particle on how this is used - * - * @return Particle offset Z. - */ - public double offsetZ() { - return offsetZ; - } - - /** - * Sets the particle offset. Varies by particle on how this is used - * - * @param offsetX Particle offset X - * @param offsetY Particle offset Y - * @param offsetZ Particle offset Z - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder offset(double offsetX, double offsetY, double offsetZ) { - this.offsetX = offsetX; - this.offsetY = offsetY; - this.offsetZ = offsetZ; - return this; - } - - /** - * Gets the Particle extra data. Varies by particle on how this is used - * - * @return the extra particle data - */ - public double extra() { - return extra; - } - - /** - * Sets the particle extra data. Varies by particle on how this is used - * - * @param extra the extra particle data - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder extra(double extra) { - this.extra = extra; - return this; - } - - /** - * Gets the particle custom data. Varies by particle on how this is used - * - * @param The Particle data type - * @return the ParticleData for this particle - */ - @Nullable - public T data() { - //noinspection unchecked - return (T) data; - } - - /** - * Sets the particle custom data. Varies by particle on how this is used - * - * @param data The new particle data - * @param The Particle data type - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder data(@Nullable T data) { - this.data = data; - return this; - } - - /** - * Sets whether the particle is forcefully shown to the player. If forced, the particle will show - * faraway, as far as the player's view distance allows. If false, the particle will show - * according to the client's particle settings. - * - * @param force true to force, false for normal - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder force(boolean force) { - this.force = force; - return this; - } - - /** - * Sets the particle Color. Only valid for REDSTONE. - * - * @param color the new particle color - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder color(@Nullable Color color) { - return color(color, 1); - } - - /** - * Sets the particle Color and size. Only valid for REDSTONE. - * - * @param color the new particle color - * @param size the size of the particle - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder color(@Nullable Color color, float size) { - if (particle != Particle.REDSTONE && color != null) { - throw new IllegalStateException("Color may only be set on REDSTONE"); - } - - // We don't officially support reusing these objects, but here we go - if (color == null) { - if (data instanceof Particle.DustOptions) { - return data(null); - } else { - return this; - } - } - - return data(new Particle.DustOptions(color, size)); - } - - /** - * Sets the particle Color. - * Only valid for REDSTONE. - * @param r red color component - * @param g green color component - * @param b blue color component - * @return a reference to this object. - */ - @NotNull - public ParticleBuilder color(int r, int g, int b) { - return color(Color.fromRGB(r, g, b)); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/Title.java b/api/src/main/java/com/destroystokyo/paper/Title.java deleted file mode 100644 index 4fe18540f..000000000 --- a/api/src/main/java/com/destroystokyo/paper/Title.java +++ /dev/null @@ -1,373 +0,0 @@ -package com.destroystokyo.paper; - -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; - -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -/** - * 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull BaseComponent title, @Nullable 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(@NotNull BaseComponent[] title, @Nullable 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(@NotNull String title, @Nullable 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(@NotNull BaseComponent title, @Nullable 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(@Nullable BaseComponent[] title, @NotNull 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(@NotNull String title, @Nullable 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 - */ - @NotNull - public BaseComponent[] getTitle() { - return this.title; - } - - /** - * Gets the text of this title's subtitle - * - * @return the text - */ - @Nullable - 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; - } - - @NotNull - 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 - */ - @NotNull - public Builder title(@NotNull 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 - */ - @NotNull - public Builder title(@NotNull 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 - */ - @NotNull - public Builder title(@NotNull 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 - */ - @NotNull - public Builder subtitle(@Nullable 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 - */ - @NotNull - public Builder subtitle(@Nullable 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 - */ - @NotNull - public Builder subtitle(@Nullable 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - public Title build() { - checkState(title != null, "Title not specified"); - return new Title(this.title, this.subtitle, this.fadeIn, this.stay, this.fadeOut); - } - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/block/BlockSoundGroup.java b/api/src/main/java/com/destroystokyo/paper/block/BlockSoundGroup.java deleted file mode 100644 index 8cf87d228..000000000 --- a/api/src/main/java/com/destroystokyo/paper/block/BlockSoundGroup.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.destroystokyo.paper.block; - -import org.bukkit.Sound; -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; - -/** - * Represents the sounds that a {@link Block} makes in certain situations - *

- * The sound group includes break, step, place, hit, and fall sounds. - */ -public interface BlockSoundGroup { - /** - * Gets the sound that plays when breaking this block - * - * @return The break sound - */ - @NotNull - Sound getBreakSound(); - - /** - * Gets the sound that plays when stepping on this block - * - * @return The step sound - */ - @NotNull - Sound getStepSound(); - - /** - * Gets the sound that plays when placing this block - * - * @return The place sound - */ - @NotNull - Sound getPlaceSound(); - - /** - * Gets the sound that plays when hitting this block - * - * @return The hit sound - */ - @NotNull - Sound getHitSound(); - - /** - * Gets the sound that plays when this block falls - * - * @return The fall sound - */ - @NotNull - Sound getFallSound(); -} diff --git a/api/src/main/java/com/destroystokyo/paper/block/TargetBlockInfo.java b/api/src/main/java/com/destroystokyo/paper/block/TargetBlockInfo.java deleted file mode 100644 index 18a96dbb0..000000000 --- a/api/src/main/java/com/destroystokyo/paper/block/TargetBlockInfo.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.destroystokyo.paper.block; - -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.jetbrains.annotations.NotNull; - -/** - * Represents information about a targeted block - */ -public class TargetBlockInfo { - private final Block block; - private final BlockFace blockFace; - - public TargetBlockInfo(@NotNull Block block, @NotNull BlockFace blockFace) { - this.block = block; - this.blockFace = blockFace; - } - - /** - * Get the block that is targeted - * - * @return Targeted block - */ - @NotNull - public Block getBlock() { - return block; - } - - /** - * Get the targeted BlockFace - * - * @return Targeted blockface - */ - @NotNull - public BlockFace getBlockFace() { - return blockFace; - } - - /** - * Get the relative Block to the targeted block on the side it is targeted at - * - * @return Block relative to targeted block - */ - @NotNull - public Block getRelativeBlock() { - return block.getRelative(blockFace); - } - - public enum FluidMode { - NEVER, - SOURCE_ONLY, - ALWAYS - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/entity/Pathfinder.java b/api/src/main/java/com/destroystokyo/paper/entity/Pathfinder.java deleted file mode 100644 index 8b90a9053..000000000 --- a/api/src/main/java/com/destroystokyo/paper/entity/Pathfinder.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.destroystokyo.paper.entity; - -import org.bukkit.Location; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Mob; - -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Handles pathfinding operations for an Entity - */ -public interface Pathfinder { - - /** - * - * @return The entity that is controlled by this pathfinder - */ - @NotNull - Mob getEntity(); - - /** - * Instructs the Entity to stop trying to navigate to its current desired location - */ - void stopPathfinding(); - - /** - * If the entity is currently trying to navigate to a destination, this will return true - * @return true if the entity is navigating to a destination - */ - boolean hasPath(); - - /** - * @return The location the entity is trying to navigate to, or null if there is no destination - */ - @Nullable - PathResult getCurrentPath(); - - /** - * Calculates a destination for the Entity to navigate to, but does not set it - * as the current target. Useful for calculating what would happen before setting it. - * @param loc Location to navigate to - * @return The closest Location the Entity can get to for this navigation, or null if no path could be calculated - */ - @Nullable PathResult findPath(@NotNull Location loc); - - /** - * Calculates a destination for the Entity to navigate to to reach the target entity, - * but does not set it as the current target. - * Useful for calculating what would happen before setting it. - * - * The behavior of this PathResult is subject to the games pathfinding rules, and may - * result in the pathfinding automatically updating to follow the target Entity. - * - * However, this behavior is not guaranteed, and is subject to the games behavior. - * - * @param target the Entity to navigate to - * @return The closest Location the Entity can get to for this navigation, or null if no path could be calculated - */ - @Nullable PathResult findPath(@NotNull LivingEntity target); - - /** - * Calculates a destination for the Entity to navigate to, and sets it with default speed - * as the current target. - * @param loc Location to navigate to - * @return If the pathfinding was successfully started - */ - default boolean moveTo(@NotNull Location loc) { - return moveTo(loc, 1); - } - - /** - * Calculates a destination for the Entity to navigate to, with desired speed - * as the current target. - * @param loc Location to navigate to - * @param speed Speed multiplier to navigate at, where 1 is 'normal' - * @return If the pathfinding was successfully started - */ - default boolean moveTo(@NotNull Location loc, double speed) { - PathResult path = findPath(loc); - return path != null && moveTo(path, speed); - } - - /** - * Calculates a destination for the Entity to navigate to to reach the target entity, - * and sets it with default speed. - * - * The behavior of this PathResult is subject to the games pathfinding rules, and may - * result in the pathfinding automatically updating to follow the target Entity. - * - * However, this behavior is not guaranteed, and is subject to the games behavior. - * - * @param target the Entity to navigate to - * @return If the pathfinding was successfully started - */ - default boolean moveTo(@NotNull LivingEntity target) { - return moveTo(target, 1); - } - - /** - * Calculates a destination for the Entity to navigate to to reach the target entity, - * and sets it with specified speed. - * - * The behavior of this PathResult is subject to the games pathfinding rules, and may - * result in the pathfinding automatically updating to follow the target Entity. - * - * However, this behavior is not guaranteed, and is subject to the games behavior. - * - * @param target the Entity to navigate to - * @param speed Speed multiplier to navigate at, where 1 is 'normal' - * @return If the pathfinding was successfully started - */ - default boolean moveTo(@NotNull LivingEntity target, double speed) { - PathResult path = findPath(target); - return path != null && moveTo(path, speed); - } - - /** - * Takes the result of a previous pathfinding calculation and sets it - * as the active pathfinding with default speed. - * - * @param path The Path to start following - * @return If the pathfinding was successfully started - */ - default boolean moveTo(@NotNull PathResult path) { - return moveTo(path, 1); - } - - /** - * Takes the result of a previous pathfinding calculation and sets it - * as the active pathfinding, - * - * @param path The Path to start following - * @param speed Speed multiplier to navigate at, where 1 is 'normal' - * @return If the pathfinding was successfully started - */ - boolean moveTo(@NotNull PathResult path, double speed); - - /** - * Represents the result of a pathfinding calculation - */ - interface PathResult { - - /** - * All currently calculated points to follow along the path to reach the destination location - * - * Will return points the entity has already moved past, see {@link #getNextPointIndex()} - * @return List of points - */ - @NotNull - List getPoints(); - - /** - * @return Returns the index of the current point along the points returned in {@link #getPoints()} the entity - * is trying to reach, or null if we are done with this pathfinding. - */ - int getNextPointIndex(); - - /** - * @return The next location in the path points the entity is trying to reach, or null if there is no next point - */ - @Nullable Location getNextPoint(); - - /** - * @return The closest point the path can get to the target location - */ - @Nullable Location getFinalPoint(); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/entity/RangedEntity.java b/api/src/main/java/com/destroystokyo/paper/entity/RangedEntity.java deleted file mode 100644 index f2e3233a3..000000000 --- a/api/src/main/java/com/destroystokyo/paper/entity/RangedEntity.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.destroystokyo.paper.entity; - -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Mob; -import org.jetbrains.annotations.NotNull; - -public interface RangedEntity extends Mob { - /** - * Attack the specified entity using a ranged attack. - * - * @param target the entity to target - * @param charge How "charged" the attack is (how far back the bow was pulled for Bow attacks). - * This should be a value between 0 and 1, represented as targetDistance/maxDistance. - */ - void rangedAttack(@NotNull LivingEntity target, float charge); - - /** - * Sets that the Entity is "charging" up an attack, by raising its hands - * - * @param raiseHands Whether the entities hands are raised to charge attack - */ - void setChargingAttack(boolean raiseHands); - - /** - * Alias to {@link LivingEntity#isHandRaised()}, if the entity is charging an attack - * @return If entities hands are raised - */ - default boolean isChargingAttack() { - return isHandRaised(); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/entity/TargetEntityInfo.java b/api/src/main/java/com/destroystokyo/paper/entity/TargetEntityInfo.java deleted file mode 100644 index f52644fab..000000000 --- a/api/src/main/java/com/destroystokyo/paper/entity/TargetEntityInfo.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.destroystokyo.paper.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; - -/** - * Represents information about a targeted entity - */ -public class TargetEntityInfo { - private final Entity entity; - private final Vector hitVec; - - public TargetEntityInfo(@NotNull Entity entity, @NotNull Vector hitVec) { - this.entity = entity; - this.hitVec = hitVec; - } - - /** - * Get the entity that is targeted - * - * @return Targeted entity - */ - @NotNull - public Entity getEntity() { - return entity; - } - - /** - * Get the position the entity is targeted at - * - * @return Targeted position - */ - @NotNull - public Vector getHitVector() { - return hitVec; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/block/AnvilDamagedEvent.java b/api/src/main/java/com/destroystokyo/paper/event/block/AnvilDamagedEvent.java deleted file mode 100644 index a83c286c1..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/block/AnvilDamagedEvent.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.destroystokyo.paper.event.block; - -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.inventory.InventoryEvent; -import org.bukkit.inventory.AnvilInventory; -import org.bukkit.inventory.InventoryView; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when an anvil is damaged from being used - */ -public class AnvilDamagedEvent extends InventoryEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancel; - private DamageState damageState; - - public AnvilDamagedEvent(@NotNull InventoryView inventory, @NotNull BlockData blockData) { - super(inventory); - this.damageState = DamageState.getState(blockData); - } - - @NotNull - @Override - public AnvilInventory getInventory() { - return (AnvilInventory) super.getInventory(); - } - - /** - * Gets the new state of damage on the anvil - * - * @return Damage state - */ - @NotNull - public DamageState getDamageState() { - return damageState; - } - - /** - * Sets the new state of damage on the anvil - * - * @param damageState Damage state - */ - public void setDamageState(@NotNull DamageState damageState) { - this.damageState = damageState; - } - - /** - * Gets if anvil is breaking on this use - * - * @return True if breaking - */ - public boolean isBreaking() { - return damageState == DamageState.BROKEN; - } - - /** - * Sets if anvil is breaking on this use - * - * @param breaking True if breaking - */ - public void setBreaking(boolean breaking) { - if (breaking) { - damageState = DamageState.BROKEN; - } else if (damageState == DamageState.BROKEN) { - damageState = DamageState.DAMAGED; - } - } - - public boolean isCancelled() { - return cancel; - } - - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Represents the amount of damage on an anvil block - */ - public enum DamageState { - FULL(Material.ANVIL), - CHIPPED(Material.CHIPPED_ANVIL), - DAMAGED(Material.DAMAGED_ANVIL), - BROKEN(Material.AIR); - - private Material material; - - DamageState(@NotNull Material material) { - this.material = material; - } - - /** - * Get block material of this state - * - * @return Material - */ - @NotNull - public Material getMaterial() { - return material; - } - - /** - * Get damaged state by block data - * - * @param blockData Block data - * @return DamageState - * @throws IllegalArgumentException If non anvil block data is given - */ - @NotNull - public static DamageState getState(@Nullable BlockData blockData) { - return blockData == null ? BROKEN : getState(blockData.getMaterial()); - } - - /** - * Get damaged state by block material - * - * @param material Block material - * @return DamageState - * @throws IllegalArgumentException If non anvil material is given - */ - @NotNull - public static DamageState getState(@Nullable Material material) { - if (material == null) { - return BROKEN; - } - for (DamageState state : values()) { - if (state.material == material) { - return state; - } - } - throw new IllegalArgumentException("Material not an anvil"); - } - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/block/BeaconEffectEvent.java b/api/src/main/java/com/destroystokyo/paper/event/block/BeaconEffectEvent.java deleted file mode 100644 index 978813b94..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/block/BeaconEffectEvent.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.destroystokyo.paper.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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Block block, @NotNull PotionEffect effect, @NotNull 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 - */ - @NotNull - public PotionEffect getEffect() { - return effect; - } - - /** - * Sets the potion effect that will be applied. - * - * @param effect Potion effect - */ - public void setEffect(@NotNull PotionEffect effect) { - this.effect = effect; - } - - /** - * Gets the player who the potion effect is being applied to. - * - * @return Affected player - */ - @NotNull - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/block/BlockDestroyEvent.java b/api/src/main/java/com/destroystokyo/paper/event/block/BlockDestroyEvent.java deleted file mode 100644 index 3aee12f1c..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/block/BlockDestroyEvent.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.destroystokyo.paper.event.block; - -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.block.BlockEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired anytime the server intends to 'destroy' a block through some triggering reason. - * This does not fire anytime a block is set to air, but only with more direct triggers such - * as physics updates, pistons, Entities changing blocks, commands set to "Destroy". - * - * This event is associated with the game playing a sound effect at the block in question, when - * something can be described as "intend to destroy what is there", - * - * Events such as leaves decaying, pistons retracting (where the block is moving), does NOT fire this event. - * - */ -public class BlockDestroyEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - - @NotNull private final BlockData newState; - private final boolean willDrop; - private boolean playEffect; - - private boolean cancelled = false; - - public BlockDestroyEvent(@NotNull Block block, @NotNull BlockData newState, boolean willDrop) { - super(block); - this.newState = newState; - this.willDrop = willDrop; - } - - /** - * @return The new state of this block (Air, or a Fluid type) - */ - @NotNull - public BlockData getNewState() { - return newState; - } - - /** - * @return If the server is going to drop the block in question with this destroy event - */ - public boolean willDrop() { - return this.willDrop; - } - - /** - * @return If the server is going to play the sound effect for this destruction - */ - public boolean playEffect() { - return this.playEffect; - } - - /** - * @param playEffect If the server should play the sound effect for this destruction - */ - public void setPlayEffect(boolean playEffect) { - this.playEffect = playEffect; - } - - /** - * @return If the event is cancelled, meaning the block will not be destroyed - */ - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * If the event is cancelled, the block will remain in its previous state. - * @param cancel true if you wish to cancel this event - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/block/TNTPrimeEvent.java b/api/src/main/java/com/destroystokyo/paper/event/block/TNTPrimeEvent.java deleted file mode 100644 index 73dabb82c..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/block/TNTPrimeEvent.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.destroystokyo.paper.event.block; - -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.block.BlockEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when TNT block is about to turn into {@link org.bukkit.entity.TNTPrimed} - *

- * Cancelling it won't turn TNT into {@link org.bukkit.entity.TNTPrimed} and leaves - * the TNT block as-is - * - * @author Mark Vainomaa - */ -public class TNTPrimeEvent extends BlockEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - @NotNull private PrimeReason reason; - @Nullable private Entity primerEntity; - - public TNTPrimeEvent(@NotNull Block theBlock, @NotNull PrimeReason reason, @Nullable Entity primerEntity) { - super(theBlock); - this.reason = reason; - this.primerEntity = primerEntity; - } - - /** - * Gets the TNT prime reason - * - * @return Prime reason - */ - @NotNull - public PrimeReason getReason() { - return this.reason; - } - - /** - * Gets the TNT primer {@link Entity}. - * - * It's null if {@link #getReason()} is {@link PrimeReason#REDSTONE} or {@link PrimeReason#FIRE}. - * It's not null if {@link #getReason()} is {@link PrimeReason#ITEM} or {@link PrimeReason#PROJECTILE} - * It might be null if {@link #getReason()} is {@link PrimeReason#EXPLOSION} - * - * @return The {@link Entity} who primed the TNT - */ - @Nullable - public Entity getPrimerEntity() { - return this.primerEntity; - } - - /** - * Gets whether spawning {@link org.bukkit.entity.TNTPrimed} should be cancelled or not - * - * @return Whether spawning {@link org.bukkit.entity.TNTPrimed} should be cancelled or not - */ - @Override - public boolean isCancelled() { - return this.cancelled; - } - - /** - * Sets whether to cancel spawning {@link org.bukkit.entity.TNTPrimed} or not - * - * @param cancel whether spawning {@link org.bukkit.entity.TNTPrimed} should be cancelled or not - */ - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @Nullable - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Nullable - public static HandlerList getHandlerList() { - return handlers; - } - - public enum PrimeReason { - /** - * When TNT prime was caused by other explosion (chain reaction) - */ - EXPLOSION, - - /** - * When TNT prime was caused by fire - */ - FIRE, - - /** - * When {@link org.bukkit.entity.Player} used {@link org.bukkit.Material#FLINT_AND_STEEL} or - * {@link org.bukkit.Material#FIRE_CHARGE} on given TNT block - */ - ITEM, - - /** - * When TNT prime was caused by an {@link Entity} shooting TNT - * using a bow with {@link org.bukkit.enchantments.Enchantment#ARROW_FIRE} enchantment - */ - PROJECTILE, - - /** - * When redstone power triggered the TNT prime - */ - REDSTONE - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/CreeperIgniteEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/CreeperIgniteEvent.java deleted file mode 100644 index ff10251b6..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/CreeperIgniteEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Creeper; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a Creeper is ignite flag is changed (armed/disarmed to explode). - */ -public class CreeperIgniteEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean canceled; - private boolean ignited; - - public CreeperIgniteEvent(@NotNull Creeper creeper, boolean ignited) { - super(creeper); - this.ignited = ignited; - } - - @NotNull - @Override - public Creeper getEntity() { - return (Creeper) entity; - } - - public boolean isIgnited() { - return ignited; - } - - public void setIgnited(boolean ignited) { - this.ignited = ignited; - } - - public boolean isCancelled() { - return canceled; - } - - public void setCancelled(boolean cancel) { - canceled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonFireballHitEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonFireballHitEvent.java deleted file mode 100644 index 118c7b677..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonFireballHitEvent.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.AreaEffectCloud; -import org.bukkit.entity.DragonFireball; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; - -import java.util.Collection; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Fired when a DragonFireball collides with a block/entity and spawns an AreaEffectCloud - */ -public class EnderDragonFireballHitEvent extends EntityEvent implements Cancellable { - @Nullable private final Collection targets; - @NotNull private final AreaEffectCloud areaEffectCloud; - - public EnderDragonFireballHitEvent(@NotNull DragonFireball fireball, @Nullable Collection targets, @NotNull AreaEffectCloud areaEffectCloud) { - super(fireball); - this.targets = targets; - this.areaEffectCloud = areaEffectCloud; - } - - /** - * The fireball involved in this event - */ - @NotNull - @Override - public DragonFireball getEntity() { - return (DragonFireball) super.getEntity(); - } - - /** - * The living entities hit by fireball - * - * May be null if no entities were hit - * - * @return the targets - */ - @Nullable - public Collection getTargets() { - return targets; - } - - /** - * @return The area effect cloud spawned in this collision - */ - @NotNull - public AreaEffectCloud getAreaEffectCloud() { - return areaEffectCloud; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonFlameEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonFlameEvent.java deleted file mode 100644 index 1915177f4..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonFlameEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.AreaEffectCloud; -import org.bukkit.entity.EnderDragon; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when an EnderDragon spawns an AreaEffectCloud by shooting flames - */ -public class EnderDragonFlameEvent extends EntityEvent implements Cancellable { - @NotNull private final AreaEffectCloud areaEffectCloud; - - public EnderDragonFlameEvent(@NotNull EnderDragon enderDragon, @NotNull AreaEffectCloud areaEffectCloud) { - super(enderDragon); - this.areaEffectCloud = areaEffectCloud; - } - - /** - * The enderdragon involved in this event - */ - @NotNull - @Override - public EnderDragon getEntity() { - return (EnderDragon) super.getEntity(); - } - - /** - * @return The area effect cloud spawned in this collision - */ - @NotNull - public AreaEffectCloud getAreaEffectCloud() { - return areaEffectCloud; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonShootFireballEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonShootFireballEvent.java deleted file mode 100644 index 8414bd805..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EnderDragonShootFireballEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.DragonFireball; -import org.bukkit.entity.EnderDragon; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when an EnderDragon shoots a fireball - */ -public class EnderDragonShootFireballEvent extends EntityEvent implements Cancellable { - @NotNull private final DragonFireball fireball; - - public EnderDragonShootFireballEvent(@NotNull EnderDragon entity, @NotNull DragonFireball fireball) { - super(entity); - this.fireball = fireball; - } - - /** - * The enderdragon shooting the fireball - */ - @NotNull - @Override - public EnderDragon getEntity() { - return (EnderDragon) super.getEntity(); - } - - /** - * @return The fireball being shot - */ - @NotNull - public DragonFireball getFireball() { - return fireball; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EndermanAttackPlayerEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EndermanAttackPlayerEvent.java deleted file mode 100644 index f530a3d93..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EndermanAttackPlayerEvent.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * 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 com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Enderman; -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; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when an Enderman determines if it should attack a player or not. - * Starts off cancelled if the player is wearing a pumpkin head or is not looking - * at the Enderman, according to Vanilla rules. - * - */ -public class EndermanAttackPlayerEvent extends EntityEvent implements Cancellable { - @NotNull private final Player player; - - public EndermanAttackPlayerEvent(@NotNull Enderman entity, @NotNull Player player) { - super(entity); - this.player = player; - } - - /** - * The enderman considering attacking - * - * @return The enderman considering attacking - */ - @NotNull - @Override - public Enderman getEntity() { - return (Enderman) super.getEntity(); - } - - /** - * The player the Enderman is considering attacking - * - * @return The player the Enderman is considering attacking - */ - @NotNull - public Player getPlayer() { - return player; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - /** - * - * @return If cancelled, the enderman will not attack - */ - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * Cancels if the Enderman will attack this player - * @param cancel true if you wish to cancel this event - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EndermanEscapeEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EndermanEscapeEvent.java deleted file mode 100644 index 806112a8b..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EndermanEscapeEvent.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Enderman; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -public class EndermanEscapeEvent extends EntityEvent implements Cancellable { - @NotNull private final Reason reason; - - public EndermanEscapeEvent(@NotNull Enderman entity, @NotNull Reason reason) { - super(entity); - this.reason = reason; - } - - @NotNull - @Override - public Enderman getEntity() { - return (Enderman) super.getEntity(); - } - - /** - * @return The reason the enderman is trying to escape - */ - @NotNull - public Reason getReason() { - return reason; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * Cancels the escape. - * - * If this escape normally would of resulted in damage avoidance such as indirect, - * the enderman will now take damage. - * - * @param cancel true if you wish to cancel this event - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - public enum Reason { - /** - * The enderman has stopped attacking and ran away - */ - RUNAWAY, - /** - * The enderman has teleported away due to indirect damage (ranged) - */ - INDIRECT, - /** - * The enderman has teleported away due to a critical hit - */ - CRITICAL_HIT, - /** - * The enderman has teleported away due to the player staring at it during combat - */ - STARE, - /** - * Specific case for CRITICAL_HIT where the enderman is taking rain damage - */ - DROWN - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityAddToWorldEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EntityAddToWorldEvent.java deleted file mode 100644 index 07660202e..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityAddToWorldEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired any time an entity is being added to the world for any reason. - * - * Not to be confused with {@link org.bukkit.event.entity.CreatureSpawnEvent} - * This will fire anytime a chunk is reloaded too. - */ -public class EntityAddToWorldEvent extends EntityEvent { - - public EntityAddToWorldEvent(@NotNull Entity entity) { - super(entity); - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityKnockbackByEntityEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EntityKnockbackByEntityEvent.java deleted file mode 100644 index 9efecabab..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityKnockbackByEntityEvent.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when an Entity is knocked back by the hit of another Entity. The acceleration - * vector can be modified. If this event is cancelled, the entity is not knocked back. - * - */ -public class EntityKnockbackByEntityEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - @NotNull private final Entity hitBy; - private final float knockbackStrength; - @NotNull private final Vector acceleration; - private boolean cancelled = false; - - public EntityKnockbackByEntityEvent(@NotNull LivingEntity entity, @NotNull Entity hitBy, float knockbackStrength, @NotNull Vector acceleration) { - super(entity); - this.hitBy = hitBy; - this.knockbackStrength = knockbackStrength; - this.acceleration = acceleration; - } - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - /** - * @return the entity which was knocked back - */ - @NotNull - @Override - public LivingEntity getEntity() { - return (LivingEntity) super.getEntity(); - } - - /** - * @return the original knockback strength. - */ - public float getKnockbackStrength() { - return knockbackStrength; - } - - /** - * @return the Entity which hit - */ - @NotNull - public Entity getHitBy() { - return hitBy; - } - - /** - * @return the acceleration that will be applied - */ - @NotNull - public Vector getAcceleration() { - return acceleration; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityPathfindEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EntityPathfindEvent.java deleted file mode 100644 index 63e46b2fb..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityPathfindEvent.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Fired when an Entity decides to start moving towards a location. - * - * This event does not fire for the entities actual movement. Only when it - * is choosing to start moving to a location. - */ -public class EntityPathfindEvent extends EntityEvent implements Cancellable { - @Nullable private final Entity targetEntity; - @NotNull private final Location loc; - - public EntityPathfindEvent(@NotNull Entity entity, @NotNull Location loc, @Nullable Entity targetEntity) { - super(entity); - this.targetEntity = targetEntity; - this.loc = loc; - } - - /** - * The Entity that is pathfinding. - * @return The Entity that is pathfinding. - */ - @NotNull - public Entity getEntity() { - return entity; - } - - /** - * If the Entity is trying to pathfind to an entity, this is the entity in relation. - * - * Otherwise this will return null. - * - * @return The entity target or null - */ - @Nullable - public Entity getTargetEntity() { - return targetEntity; - } - - /** - * The Location of where the entity is about to move to. - * - * Note that if the target happened to of been an entity - * @return Location of where the entity is trying to pathfind to. - */ - @NotNull - public Location getLoc() { - return loc; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityRemoveFromWorldEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EntityRemoveFromWorldEvent.java deleted file mode 100644 index e5dbbd660..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityRemoveFromWorldEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired any time an entity is being removed from a world for any reason - */ -public class EntityRemoveFromWorldEvent extends EntityEvent { - - public EntityRemoveFromWorldEvent(@NotNull Entity entity) { - super(entity); - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityTeleportEndGatewayEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EntityTeleportEndGatewayEvent.java deleted file mode 100644 index bfc69a43c..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityTeleportEndGatewayEvent.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.Location; -import org.bukkit.block.EndGateway; -import org.bukkit.entity.Entity; -import org.bukkit.event.entity.EntityTeleportEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired any time an entity attempts to teleport in an end gateway - */ -public class EntityTeleportEndGatewayEvent extends EntityTeleportEvent { - - @NotNull private final EndGateway gateway; - - public EntityTeleportEndGatewayEvent(@NotNull Entity what, @NotNull Location from, @NotNull Location to, @NotNull EndGateway gateway) { - super(what, from, to); - this.gateway = gateway; - } - - /** - * The gateway triggering the teleport - * - * @return EndGateway used - */ - @NotNull - public EndGateway getGateway() { - return gateway; - } - -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityTransformedEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EntityTransformedEvent.java deleted file mode 100644 index 12194f1fc..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityTransformedEvent.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.destroystokyo.paper.event.entity; - - -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.bukkit.event.entity.EntityTransformEvent; - -/** - * Fired when an entity transforms into another entity - *

- * If the event is cancelled, the entity will not transform - * @deprecated Bukkit has added {@link EntityTransformEvent}, you should start using that - */ -@Deprecated -public class EntityTransformedEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final Entity transformed; - private final TransformedReason reason; - - public EntityTransformedEvent(Entity entity, Entity transformed, TransformedReason reason) { - super(entity); - this.transformed = transformed; - this.reason = reason; - } - - /** - * The entity after it has transformed - * - * @return Transformed entity - * @deprecated see {@link EntityTransformEvent#getTransformedEntity()} - */ - @Deprecated - public Entity getTransformed() { - return transformed; - } - - /** - * @return The reason for the transformation - * @deprecated see {@link EntityTransformEvent#getTransformReason()} - */ - @Deprecated - public TransformedReason getReason() { - return reason; - } - - - @Override - public HandlerList getHandlers(){ - return handlers; - } - - public static HandlerList getHandlerList(){ - return handlers; - } - - @Override - public boolean isCancelled(){ - return cancelled; - } - - @Override - public void setCancelled(boolean cancel){ - cancelled = cancel; - } - - public enum TransformedReason { - /** - * When a zombie drowns - */ - DROWNED, - /** - * When a zombie villager is cured - */ - CURED, - /** - * When a villager turns to a zombie villager - */ - INFECTED, - /** - * When a mooshroom turns to a cow - */ - SHEARED, - /** - * When a pig turns to a zombiepigman - */ - LIGHTNING - - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityZapEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/EntityZapEvent.java deleted file mode 100644 index 3b725a489..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/EntityZapEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.apache.commons.lang.Validate; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LightningStrike; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.bukkit.event.entity.EntityTransformEvent; - -import java.util.Collections; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when lightning strikes an entity - */ -public class EntityZapEvent extends EntityTransformEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - @NotNull private final LightningStrike bolt; - - public EntityZapEvent(@NotNull final Entity entity, @NotNull final LightningStrike bolt, @NotNull final Entity replacementEntity) { - super(entity, Collections.singletonList(replacementEntity), TransformReason.LIGHTNING); - Validate.notNull(bolt); - Validate.notNull(replacementEntity); - this.bolt = bolt; - } - - public boolean isCancelled() { - return cancelled; - } - - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - /** - * Gets the lightning bolt that is striking the entity. - * @return The lightning bolt responsible for this event - */ - @NotNull - public LightningStrike getBolt() { - return bolt; - } - - /** - * Gets the entity that will replace the struck entity. - * @return The entity that will replace the struck entity - */ - @NotNull - public Entity getReplacementEntity() { - return getTransformedEntity(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/ExperienceOrbMergeEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/ExperienceOrbMergeEvent.java deleted file mode 100644 index 0ce3e3977..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/ExperienceOrbMergeEvent.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2017 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 com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.ExperienceOrb; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired anytime the server is about to merge 2 experience orbs into one - */ -public class ExperienceOrbMergeEvent extends EntityEvent implements Cancellable { - @NotNull private final ExperienceOrb mergeTarget; - @NotNull private final ExperienceOrb mergeSource; - - public ExperienceOrbMergeEvent(@NotNull ExperienceOrb mergeTarget, @NotNull ExperienceOrb mergeSource) { - super(mergeTarget); - this.mergeTarget = mergeTarget; - this.mergeSource = mergeSource; - } - - /** - * @return The orb that will absorb the other experience orb - */ - @NotNull - public ExperienceOrb getMergeTarget() { - return mergeTarget; - } - - /** - * @return The orb that is subject to being removed and merged into the target orb - */ - @NotNull - public ExperienceOrb getMergeSource() { - return mergeSource; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * @param cancel true if you wish to cancel this event, and prevent the orbs from merging - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/PhantomPreSpawnEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/PhantomPreSpawnEvent.java deleted file mode 100644 index 9022f697a..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/PhantomPreSpawnEvent.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - - -/** - * Called when a phantom is spawned for an exhausted player - */ -public class PhantomPreSpawnEvent extends PreCreatureSpawnEvent { - @NotNull private final Entity entity; - - public PhantomPreSpawnEvent(@NotNull Location location, @NotNull Entity entity, @NotNull CreatureSpawnEvent.SpawnReason reason) { - super(location, EntityType.PHANTOM, reason); - this.entity = entity; - } - - /** - * Get the entity this phantom is spawning for - * - * @return Entity - */ - @Nullable - public Entity getSpawningEntity() { - return entity; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/PlayerNaturallySpawnCreaturesEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/PlayerNaturallySpawnCreaturesEvent.java deleted file mode 100644 index 112a0dbf5..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/PlayerNaturallySpawnCreaturesEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when the server is calculating what chunks to try to spawn monsters in every Monster Spawn Tick event - */ -public class PlayerNaturallySpawnCreaturesEvent extends PlayerEvent implements Cancellable { - private byte radius; - - public PlayerNaturallySpawnCreaturesEvent(@NotNull Player player, byte radius) { - super(player); - this.radius = radius; - } - - /** - * @return The radius of chunks around this player to be included in natural spawn selection - */ - public byte getSpawnRadius() { - return radius; - } - - /** - * @param radius The radius of chunks around this player to be included in natural spawn selection - */ - public void setSpawnRadius(byte radius) { - this.radius = radius; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - /** - * @return If this players chunks will be excluded from natural spawns - */ - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * @param cancel true if you wish to cancel this event, and not include this players chunks for natural spawning - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/PreCreatureSpawnEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/PreCreatureSpawnEvent.java deleted file mode 100644 index d5edde9cd..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/PreCreatureSpawnEvent.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import com.google.common.base.Preconditions; -import org.bukkit.Location; -import org.bukkit.entity.EntityType; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.jetbrains.annotations.NotNull; - -/** - * WARNING: This event only fires for a limited number of cases, and not for every case that CreatureSpawnEvent does. - * - * You should still listen to CreatureSpawnEvent as a backup, and only use this event as an "enhancement". - * The intent of this event is to improve server performance, so limited use cases. - * - * Currently: NATURAL and SPAWNER based reasons. Please submit a Pull Request for future additions. - * Also, Plugins that replace Entity Registrations with their own custom entities might not fire this event. - */ -public class PreCreatureSpawnEvent extends Event implements Cancellable { - @NotNull private final Location location; - @NotNull private final EntityType type; - @NotNull private final CreatureSpawnEvent.SpawnReason reason; - private boolean shouldAbortSpawn; - - public PreCreatureSpawnEvent(@NotNull Location location, @NotNull EntityType type, @NotNull CreatureSpawnEvent.SpawnReason reason) { - this.location = Preconditions.checkNotNull(location, "Location may not be null").clone(); - this.type = Preconditions.checkNotNull(type, "Type may not be null"); - this.reason = Preconditions.checkNotNull(reason, "Reason may not be null"); - } - - /** - * @return The location this creature is being spawned at - */ - @NotNull - public Location getSpawnLocation() { - return location; - } - - /** - * @return The type of creature being spawned - */ - @NotNull - public EntityType getType() { - return type; - } - - /** - * @return Reason this creature is spawning (ie, NATURAL vs SPAWNER) - */ - @NotNull - public CreatureSpawnEvent.SpawnReason getReason() { - return reason; - } - - /** - * @return If the spawn process should be aborted vs trying more attempts - */ - public boolean shouldAbortSpawn() { - return shouldAbortSpawn; - } - - /** - * Set this if you are more blanket blocking all types of these spawns, and wish to abort the spawn process from - * trying more attempts after this cancellation. - * - * @param shouldAbortSpawn Set if the spawn process should be aborted vs trying more attempts - */ - public void setShouldAbortSpawn(boolean shouldAbortSpawn) { - this.shouldAbortSpawn = shouldAbortSpawn; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - /** - * @return If the spawn of this creature is cancelled or not - */ - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * Cancelling this event is more effecient than cancelling CreatureSpawnEvent - * @param cancel true if you wish to cancel this event, and abort the spawn of this creature - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/PreSpawnerSpawnEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/PreSpawnerSpawnEvent.java deleted file mode 100644 index 48cff0635..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/PreSpawnerSpawnEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.destroystokyo.paper.event.entity; - - -import com.google.common.base.Preconditions; -import org.bukkit.Location; -import org.bukkit.entity.EntityType; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Called before an entity is spawned into a world by a spawner. - * - * This only includes the spawner's location and not the full BlockState snapshot for performance reasons. - * If you really need it you have to get the spawner yourself. - */ - -public class PreSpawnerSpawnEvent extends PreCreatureSpawnEvent { - @NotNull private final Location spawnerLocation; - - public PreSpawnerSpawnEvent(@NotNull Location location, @NotNull EntityType type, @NotNull Location spawnerLocation) { - super(location, type, CreatureSpawnEvent.SpawnReason.SPAWNER); - this.spawnerLocation = Preconditions.checkNotNull(spawnerLocation, "Spawner location may not be null"); - } - - @NotNull - public Location getSpawnerLocation() { - return spawnerLocation; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/ProjectileCollideEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/ProjectileCollideEvent.java deleted file mode 100644 index 453663893..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/ProjectileCollideEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Projectile; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an projectile collides with an entity - *

- * This event is called before {@link org.bukkit.event.entity.EntityDamageByEntityEvent}, and cancelling it will allow the projectile to continue flying - */ -public class ProjectileCollideEvent extends EntityEvent implements Cancellable { - @NotNull private final Entity collidedWith; - - /** - * Get the entity the projectile collided with - * - * @return the entity collided with - */ - @NotNull - public Entity getCollidedWith() { - return collidedWith; - } - - public ProjectileCollideEvent(@NotNull Projectile what, @NotNull Entity collidedWith) { - super(what); - this.collidedWith = collidedWith; - } - - /** - * Get the projectile that collided - * - * @return the projectile that collided - */ - @NotNull - public Projectile getEntity() { - return (Projectile) super.getEntity(); - } - - private static final HandlerList handlerList = new HandlerList(); - - @NotNull - public static HandlerList getHandlerList() { - return handlerList; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlerList; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/SkeletonHorseTrapEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/SkeletonHorseTrapEvent.java deleted file mode 100644 index d79dbcd68..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/SkeletonHorseTrapEvent.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.SkeletonHorse; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Event called when a player gets close to a skeleton horse and triggers the lightning trap - */ -public class SkeletonHorseTrapEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - - public SkeletonHorseTrapEvent(@NotNull SkeletonHorse horse) { - super(horse); - } - - @NotNull - @Override - public SkeletonHorse getEntity() { - return (SkeletonHorse) super.getEntity(); - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} - diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeChangeDirectionEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeChangeDirectionEvent.java deleted file mode 100644 index 2638bbd3e..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeChangeDirectionEvent.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Slime; -import org.bukkit.event.Cancellable; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a Slime decides to change it's facing direction. - *

- * This event does not fire for the entity's actual movement. Only when it - * is choosing to change direction. - */ -public class SlimeChangeDirectionEvent extends SlimePathfindEvent implements Cancellable { - private float yaw; - - public SlimeChangeDirectionEvent(@NotNull Slime slime, float yaw) { - super(slime); - this.yaw = yaw; - } - - /** - * Get the new chosen yaw - * - * @return Chosen yaw - */ - public float getNewYaw() { - return yaw; - } - - /** - * Set the new chosen yaw - * - * @param yaw Chosen yaw - */ - public void setNewYaw(float yaw) { - this.yaw = yaw; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimePathfindEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/SlimePathfindEvent.java deleted file mode 100644 index 14b67da10..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimePathfindEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Slime; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a Slime decides to start pathfinding. - *

- * This event does not fire for the entity's actual movement. Only when it - * is choosing to start moving. - */ -public class SlimePathfindEvent extends EntityEvent implements Cancellable { - public SlimePathfindEvent(@NotNull Slime slime) { - super(slime); - } - - /** - * The Slime that is pathfinding. - * - * @return The Slime that is pathfinding. - */ - @NotNull - public Slime getEntity() { - return (Slime) entity; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeSwimEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeSwimEvent.java deleted file mode 100644 index c8dd49d11..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeSwimEvent.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Slime; -import org.bukkit.event.Cancellable; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a Slime decides to start jumping while swimming in water/lava. - *

- * This event does not fire for the entity's actual movement. Only when it - * is choosing to start jumping. - */ -public class SlimeSwimEvent extends SlimeWanderEvent implements Cancellable { - public SlimeSwimEvent(@NotNull Slime slime) { - super(slime); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeTargetLivingEntityEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeTargetLivingEntityEvent.java deleted file mode 100644 index e9ba32799..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeTargetLivingEntityEvent.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Slime; -import org.bukkit.event.Cancellable; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a Slime decides to change direction to target a LivingEntity. - *

- * This event does not fire for the entity's actual movement. Only when it - * is choosing to start moving. - */ -public class SlimeTargetLivingEntityEvent extends SlimePathfindEvent implements Cancellable { - @NotNull private final LivingEntity target; - - public SlimeTargetLivingEntityEvent(@NotNull Slime slime, @NotNull LivingEntity target) { - super(slime); - this.target = target; - } - - /** - * Get the targeted entity - * - * @return Targeted entity - */ - @NotNull - public LivingEntity getTarget() { - return target; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeWanderEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeWanderEvent.java deleted file mode 100644 index 4683a7237..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/SlimeWanderEvent.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Slime; -import org.bukkit.event.Cancellable; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a Slime decides to start wandering. - *

- * This event does not fire for the entity's actual movement. Only when it - * is choosing to start moving. - */ -public class SlimeWanderEvent extends SlimePathfindEvent implements Cancellable { - public SlimeWanderEvent(@NotNull Slime slime) { - super(slime); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleGoHomeEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleGoHomeEvent.java deleted file mode 100644 index 021356d15..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleGoHomeEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Turtle; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a Turtle decides to go home - */ -public class TurtleGoHomeEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled = false; - - public TurtleGoHomeEvent(@NotNull Turtle turtle) { - super(turtle); - } - - /** - * The turtle going home - * - * @return The turtle - */ - @NotNull - public Turtle getEntity() { - return (Turtle) entity; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleLayEggEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleLayEggEvent.java deleted file mode 100644 index a315c5185..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleLayEggEvent.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Turtle; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a Turtle lays eggs - */ -public class TurtleLayEggEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled = false; - @NotNull - private final Location location; - private int eggCount; - - public TurtleLayEggEvent(@NotNull Turtle turtle, @NotNull Location location, int eggCount) { - super(turtle); - this.location = location; - this.eggCount = eggCount; - } - - /** - * The turtle laying the eggs - * - * @return The turtle - */ - @NotNull - public Turtle getEntity() { - return (Turtle) entity; - } - - /** - * Get the location where the eggs are being laid - * - * @return Location of eggs - */ - @NotNull - public Location getLocation() { - return location; - } - - /** - * Get the number of eggs being laid - * - * @return Number of eggs - */ - public int getEggCount() { - return eggCount; - } - - /** - * Set the number of eggs being laid - * - * @param eggCount Number of eggs - */ - public void setEggCount(int eggCount) { - if (eggCount < 1) { - cancelled = true; - return; - } - eggCount = Math.min(eggCount, 4); - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleStartDiggingEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleStartDiggingEvent.java deleted file mode 100644 index abeb24fcc..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/TurtleStartDiggingEvent.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Turtle; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a Turtle starts digging to lay eggs - */ -public class TurtleStartDiggingEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled = false; - @NotNull private final Location location; - - public TurtleStartDiggingEvent(@NotNull Turtle turtle, @NotNull Location location) { - super(turtle); - this.location = location; - } - - /** - * The turtle digging - * - * @return The turtle - */ - @NotNull - public Turtle getEntity() { - return (Turtle) entity; - } - - /** - * Get the location where the turtle is digging - * - * @return Location where digging - */ - @NotNull - public Location getLocation() { - return location; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/WitchConsumePotionEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/WitchConsumePotionEvent.java deleted file mode 100644 index fbbace36d..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/WitchConsumePotionEvent.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.Witch; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Fired when a witch consumes the potion in their hand to buff themselves. - */ -public class WitchConsumePotionEvent extends EntityEvent implements Cancellable { - @Nullable private ItemStack potion; - - public WitchConsumePotionEvent(@NotNull Witch witch, @Nullable ItemStack potion) { - super(witch); - this.potion = potion; - } - - @NotNull - @Override - public Witch getEntity() { - return (Witch) super.getEntity(); - } - - /** - * @return the potion the witch will consume and have the effects applied. - */ - @Nullable - public ItemStack getPotion() { - return potion; - } - - /** - * Sets the potion to be consumed and applied to the witch. - * @param potion The potion - */ - public void setPotion(@Nullable ItemStack potion) { - this.potion = potion != null ? potion.clone() : null; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - /** - * @return Event was cancelled or potion was null - */ - @Override - public boolean isCancelled() { - return cancelled || potion == null; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/WitchReadyPotionEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/WitchReadyPotionEvent.java deleted file mode 100644 index 5351b523d..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/WitchReadyPotionEvent.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.Material; -import org.bukkit.entity.Witch; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class WitchReadyPotionEvent extends EntityEvent implements Cancellable { - private ItemStack potion; - - public WitchReadyPotionEvent(@NotNull Witch witch, @Nullable ItemStack potion) { - super(witch); - this.potion = potion; - } - - /** - * Fires thee event, returning the desired potion, or air of cancelled - * @param witch the witch whom is readying to use a potion - * @param potion the potion to be used - * @return The ItemStack to be used - */ - @Nullable - public static ItemStack process(@NotNull Witch witch, @Nullable ItemStack potion) { - WitchReadyPotionEvent event = new WitchReadyPotionEvent(witch, potion); - if (!event.callEvent() || event.getPotion() == null) { - return new ItemStack(Material.AIR); - } - return event.getPotion(); - } - - @NotNull - @Override - public Witch getEntity() { - return (Witch) super.getEntity(); - } - - /** - * @return the potion the witch is readying to use - */ - @Nullable - public ItemStack getPotion() { - return potion; - } - - /** - * Sets the potion the which is going to hold and use - * @param potion The potion - */ - public void setPotion(@Nullable ItemStack potion) { - this.potion = potion != null ? potion.clone() : null; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/entity/WitchThrowPotionEvent.java b/api/src/main/java/com/destroystokyo/paper/event/entity/WitchThrowPotionEvent.java deleted file mode 100644 index 688a596aa..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/entity/WitchThrowPotionEvent.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.destroystokyo.paper.event.entity; - -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Witch; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Fired when a witch throws a potion at a player - */ -public class WitchThrowPotionEvent extends EntityEvent implements Cancellable { - @NotNull private final LivingEntity target; - @Nullable private ItemStack potion; - - public WitchThrowPotionEvent(@NotNull Witch witch, @NotNull LivingEntity target, @Nullable ItemStack potion) { - super(witch); - this.target = target; - this.potion = potion; - } - - @NotNull - @Override - public Witch getEntity() { - return (Witch) super.getEntity(); - } - - /** - * @return The target of the potion - */ - @NotNull - public LivingEntity getTarget() { - return target; - } - - /** - * @return The potion the witch will throw at a player - */ - @Nullable - public ItemStack getPotion() { - return potion; - } - - /** - * Sets the potion to be thrown at a player - * @param potion The potion - */ - public void setPotion(@Nullable ItemStack potion) { - this.potion = potion != null ? potion.clone() : null; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - /** - * @return Event was cancelled or potion was null - */ - @Override - public boolean isCancelled() { - return cancelled || potion == null; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java b/api/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java deleted file mode 100644 index 5b28e9b1d..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java +++ /dev/null @@ -1,42 +0,0 @@ -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/api/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java b/api/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java deleted file mode 100644 index c83672427..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java +++ /dev/null @@ -1,43 +0,0 @@ -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(eventClass != null, "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/api/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java b/api/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java deleted file mode 100644 index b6e7d8ee8..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java +++ /dev/null @@ -1,47 +0,0 @@ -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.jetbrains.annotations.NotNull; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Type; -import org.objectweb.asm.commons.GeneratorAdapter; - -import static org.objectweb.asm.Opcodes.*; - -public class ASMEventExecutorGenerator { - @NotNull - public static byte[] generateEventExecutor(@NotNull Method m, @NotNull String name) { - 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", "(Lorg/bukkit/event/Listener;Lorg/bukkit/event/Event;)V", null, null), ACC_PUBLIC, "execute", "(Lorg/bukkit/event/Listener;Lorg/bukkit/event/Listener;)V");; - 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()); - if (m.getReturnType() != void.class) { - methodGenerator.pop(); - } - methodGenerator.returnValue(); - methodGenerator.endMethod(); - writer.visitEnd(); - return writer.toByteArray(); - } - - public static AtomicInteger NEXT_ID = new AtomicInteger(1); - @NotNull - public static String generateName() { - int id = NEXT_ID.getAndIncrement(); - return "com.destroystokyo.paper.event.executor.asm.generated.GeneratedEventExecutor" + id; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java b/api/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java deleted file mode 100644 index beed9e6e0..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.destroystokyo.paper.event.executor.asm; - -import com.destroystokyo.paper.utils.UnsafeUtils; -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/api/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java b/api/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java deleted file mode 100644 index ac99477e9..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java +++ /dev/null @@ -1,66 +0,0 @@ -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/api/src/main/java/com/destroystokyo/paper/event/player/IllegalPacketEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/IllegalPacketEvent.java deleted file mode 100644 index 37a17f0bb..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/IllegalPacketEvent.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class IllegalPacketEvent extends PlayerEvent { - @Nullable private final String type; - @Nullable private final String ex; - @Nullable private String kickMessage; - private boolean shouldKick = true; - - public IllegalPacketEvent(@NotNull Player player, @Nullable String type, @Nullable String kickMessage, @NotNull Exception e) { - super(player); - this.type = type; - this.kickMessage = kickMessage; - this.ex = e.getMessage(); - } - - public boolean isShouldKick() { - return shouldKick; - } - - public void setShouldKick(boolean shouldKick) { - this.shouldKick = shouldKick; - } - - @Nullable - public String getKickMessage() { - return kickMessage; - } - - public void setKickMessage(@Nullable String kickMessage) { - this.kickMessage = kickMessage; - } - - @Nullable - public String getType() { - return type; - } - - @Nullable - public String getExceptionMessage() { - return ex; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - public static void process(@NotNull Player player, @Nullable String type, @Nullable String kickMessage, @NotNull Exception exception) { - IllegalPacketEvent event = new IllegalPacketEvent(player, type, kickMessage, exception); - event.callEvent(); - if (event.shouldKick) { - player.kickPlayer(kickMessage); - } - Bukkit.getLogger().severe(player.getName() + "/" + type + ": " + exception.getMessage()); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerAdvancementCriterionGrantEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerAdvancementCriterionGrantEvent.java deleted file mode 100644 index bb8d7c959..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerAdvancementCriterionGrantEvent.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.advancement.Advancement; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player is granted a criteria in an advancement. - */ -public class PlayerAdvancementCriterionGrantEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - @NotNull private final Advancement advancement; - @NotNull private final String criterion; - private boolean cancel = false; - - public PlayerAdvancementCriterionGrantEvent(@NotNull Player who, @NotNull Advancement advancement, @NotNull String criterion) { - super(who); - this.advancement = advancement; - this.criterion = criterion; - } - - /** - * Get the advancement which has been affected. - * - * @return affected advancement - */ - @NotNull - public Advancement getAdvancement() { - return advancement; - } - - /** - * Get the criterion which has been granted. - * - * @return granted criterion - */ - @NotNull - public String getCriterion() { - return criterion; - } - - 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/api/src/main/java/com/destroystokyo/paper/event/player/PlayerArmorChangeEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerArmorChangeEvent.java deleted file mode 100644 index 2827a1002..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerArmorChangeEvent.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.ItemStack; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import static org.bukkit.Material.*; - -/** - * Called when the player themselves change their armor items - *

- * Not currently called for environmental factors though it MAY BE IN THE FUTURE - */ -public class PlayerArmorChangeEvent extends PlayerEvent { - private static final HandlerList HANDLERS = new HandlerList(); - - @NotNull private final SlotType slotType; - @Nullable private final ItemStack oldItem; - @Nullable private final ItemStack newItem; - - public PlayerArmorChangeEvent(@NotNull Player player, @NotNull SlotType slotType, @Nullable ItemStack oldItem, @Nullable ItemStack newItem) { - super(player); - this.slotType = slotType; - this.oldItem = oldItem; - this.newItem = newItem; - } - - /** - * Gets the type of slot being altered. - * - * @return type of slot being altered - */ - @NotNull - public SlotType getSlotType() { - return this.slotType; - } - - /** - * Gets the existing item that's being replaced - * - * @return old item - */ - @Nullable - public ItemStack getOldItem() { - return this.oldItem; - } - - /** - * Gets the new item that's replacing the old - * - * @return new item - */ - @Nullable - public ItemStack getNewItem() { - return this.newItem; - } - - @Override - public String toString() { - return "ArmorChangeEvent{" + "player=" + player + ", slotType=" + slotType + ", oldItem=" + oldItem + ", newItem=" + newItem + '}'; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } - - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } - - public enum SlotType { - HEAD(DIAMOND_HELMET, GOLDEN_HELMET, IRON_HELMET, CHAINMAIL_HELMET, LEATHER_HELMET, PUMPKIN, JACK_O_LANTERN), - CHEST(DIAMOND_CHESTPLATE, GOLDEN_CHESTPLATE, IRON_CHESTPLATE, CHAINMAIL_CHESTPLATE, LEATHER_CHESTPLATE, ELYTRA), - LEGS(DIAMOND_LEGGINGS, GOLDEN_LEGGINGS, IRON_LEGGINGS, CHAINMAIL_LEGGINGS, LEATHER_LEGGINGS), - FEET(DIAMOND_BOOTS, GOLDEN_BOOTS, IRON_BOOTS, CHAINMAIL_BOOTS, LEATHER_BOOTS); - - private final Set mutableTypes = new HashSet<>(); - private Set immutableTypes; - - SlotType(Material... types) { - this.mutableTypes.addAll(Arrays.asList(types)); - } - - /** - * Gets an immutable set of all allowed material types that can be placed in an - * armor slot. - * - * @return immutable set of material types - */ - @NotNull - public Set getTypes() { - if (immutableTypes == null) { - immutableTypes = Collections.unmodifiableSet(mutableTypes); - } - - return immutableTypes; - } - - /** - * Gets the type of slot via the specified material - * - * @param material material to get slot by - * @return slot type the material will go in, or null if it won't - */ - @Nullable - public static SlotType getByMaterial(@NotNull Material material) { - for (SlotType slotType : values()) { - if (slotType.getTypes().contains(material)) { - return slotType; - } - } - return null; - } - - /** - * Gets whether or not this material can be equipped to a slot - * - * @param material material to check - * @return whether or not this material can be equipped - */ - public static boolean isEquipable(@NotNull Material material) { - return getByMaterial(material) != null; - } - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerConnectionCloseEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerConnectionCloseEvent.java deleted file mode 100644 index 12c1c6fe9..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerConnectionCloseEvent.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.net.InetAddress; -import java.util.UUID; -import org.jetbrains.annotations.NotNull; - -/** - *

- * This event is invoked when a player has disconnected. It is guaranteed that, - * if the server is in online-mode, that the provided uuid and username have been - * validated. - *

- * - *

- * The event is invoked for players who have not yet logged into the world, whereas - * {@link org.bukkit.event.player.PlayerQuitEvent} is only invoked on players who have logged into the world. - *

- * - *

- * The event is invoked for players who have already logged into the world, - * although whether or not the player exists in the world at the time of - * firing is undefined. (That is, whether the plugin can retrieve a Player object - * using the event parameters is undefined). However, it is guaranteed that this - * event is invoked AFTER {@link org.bukkit.event.player.PlayerQuitEvent}, if the player has already logged into the world. - *

- * - *

- * This event is guaranteed to never fire unless {@link org.bukkit.event.player.AsyncPlayerPreLoginEvent} has - * been fired beforehand, and this event may not be called in parallel with - * {@link org.bukkit.event.player.AsyncPlayerPreLoginEvent} for the same connection. - *

- * - *

- * Cancelling the {@link org.bukkit.event.player.AsyncPlayerPreLoginEvent} guarantees the corresponding - * {@code PlayerConnectionCloseEvent} is never called. - *

- * - *

- * The event may be invoked asynchronously or synchronously. Plugins should check - * {@link Event#isAsynchronous()} and handle accordingly. - *

- */ -public class PlayerConnectionCloseEvent extends Event { - - private static final HandlerList HANDLERS = new HandlerList(); - - @NotNull private final UUID playerUniqueId; - @NotNull private final String playerName; - @NotNull private final InetAddress ipAddress; - - public PlayerConnectionCloseEvent(@NotNull final UUID playerUniqueId, @NotNull final String playerName, @NotNull final InetAddress ipAddress, final boolean async) { - super(async); - this.playerUniqueId = playerUniqueId; - this.playerName = playerName; - this.ipAddress = ipAddress; - } - - /** - * Returns the {@code UUID} of the player disconnecting. - */ - @NotNull - public UUID getPlayerUniqueId() { - return this.playerUniqueId; - } - - /** - * Returns the name of the player disconnecting. - */ - @NotNull - public String getPlayerName() { - return this.playerName; - } - - /** - * Returns the player's IP address. - */ - @NotNull - public InetAddress getIpAddress() { - return this.ipAddress; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } - - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerElytraBoostEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerElytraBoostEvent.java deleted file mode 100644 index e9a76a25f..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerElytraBoostEvent.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.entity.Firework; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a player boosts elytra flight with a firework - */ -public class PlayerElytraBoostEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled = false; - @NotNull private final ItemStack itemStack; - @NotNull private Firework firework; - private boolean consume = true; - - public PlayerElytraBoostEvent(@NotNull Player player, @NotNull ItemStack itemStack, @NotNull Firework firework) { - super(player); - this.itemStack = itemStack; - this.firework = firework; - } - - /** - * Get the firework itemstack used - * - * @return ItemStack of firework - */ - @NotNull - public ItemStack getItemStack() { - return itemStack; - } - - /** - * Get the firework entity that was spawned - * - * @return Firework entity - */ - @NotNull - public Firework getFirework() { - return firework; - } - - /** - * Get whether to consume the firework or not - * - * @return True to consume - */ - public boolean shouldConsume() { - return consume; - } - - /** - * Set whether to consume the firework or not - * - * @param consume True to consume - */ - public void setShouldConsume(boolean consume) { - this.consume = consume; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerHandshakeEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerHandshakeEvent.java deleted file mode 100644 index f0bb4e31c..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerHandshakeEvent.java +++ /dev/null @@ -1,222 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.apache.commons.lang.Validate; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.util.UUID; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * This event is fired during a player handshake. - * - *

If there are no listeners listening to this event, the logic default - * to your server platform will be ran.

- * - *

WARNING: TAMPERING WITH THIS EVENT CAN BE DANGEROUS

- */ -public class PlayerHandshakeEvent extends Event implements Cancellable { - - private static final HandlerList HANDLERS = new HandlerList(); - @NotNull private final String originalHandshake; - private boolean cancelled; - @Nullable private String serverHostname; - @Nullable private String socketAddressHostname; - @Nullable private UUID uniqueId; - @Nullable private String propertiesJson; - private boolean failed; - private String failMessage = "If you wish to use IP forwarding, please enable it in your BungeeCord config as well!"; - - /** - * Creates a new {@link PlayerHandshakeEvent}. - * - * @param originalHandshake the original handshake string - * @param cancelled if this event is enabled - */ - public PlayerHandshakeEvent(@NotNull String originalHandshake, boolean cancelled) { - super(true); - this.originalHandshake = originalHandshake; - this.cancelled = cancelled; - } - - /** - * Determines if this event is cancelled. - * - *

When this event is cancelled, custom handshake logic will not - * be processed.

- * - * @return {@code true} if this event is cancelled, {@code false} otherwise - */ - @Override - public boolean isCancelled() { - return this.cancelled; - } - - /** - * Sets if this event is cancelled. - * - *

When this event is cancelled, custom handshake logic will not - * be processed.

- * - * @param cancelled {@code true} if this event is cancelled, {@code false} otherwise - */ - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - /** - * Gets the original handshake string. - * - * @return the original handshake string - */ - @NotNull - public String getOriginalHandshake() { - return this.originalHandshake; - } - - /** - * Gets the server hostname string. - * - *

This should not include the port.

- * - * @return the server hostname string - */ - @Nullable - public String getServerHostname() { - return this.serverHostname; - } - - /** - * Sets the server hostname string. - * - *

This should not include the port.

- * - * @param serverHostname the server hostname string - */ - public void setServerHostname(@NotNull String serverHostname) { - this.serverHostname = serverHostname; - } - - /** - * Gets the socket address hostname string. - * - *

This should not include the port.

- * - * @return the socket address hostname string - */ - @Nullable - public String getSocketAddressHostname() { - return this.socketAddressHostname; - } - - /** - * Sets the socket address hostname string. - * - *

This should not include the port.

- * - * @param socketAddressHostname the socket address hostname string - */ - public void setSocketAddressHostname(@NotNull String socketAddressHostname) { - this.socketAddressHostname = socketAddressHostname; - } - - /** - * Gets the unique id. - * - * @return the unique id - */ - @Nullable - public UUID getUniqueId() { - return this.uniqueId; - } - - /** - * Sets the unique id. - * - * @param uniqueId the unique id - */ - public void setUniqueId(@NotNull UUID uniqueId) { - this.uniqueId = uniqueId; - } - - /** - * Gets the profile properties. - * - *

This should be a valid JSON string.

- * - * @return the profile properties, as JSON - */ - @Nullable - public String getPropertiesJson() { - return this.propertiesJson; - } - - /** - * Determines if authentication failed. - * - *

When {@code true}, the client connecting will be disconnected - * with the {@link #getFailMessage() fail message}.

- * - * @return {@code true} if authentication failed, {@code false} otherwise - */ - public boolean isFailed() { - return this.failed; - } - - /** - * Sets if authentication failed and the client should be disconnected. - * - *

When {@code true}, the client connecting will be disconnected - * with the {@link #getFailMessage() fail message}.

- * - * @param failed {@code true} if authentication failed, {@code false} otherwise - */ - public void setFailed(boolean failed) { - this.failed = failed; - } - - /** - * Sets the profile properties. - * - *

This should be a valid JSON string.

- * - * @param propertiesJson the profile properties, as JSON - */ - public void setPropertiesJson(@NotNull String propertiesJson) { - this.propertiesJson = propertiesJson; - } - - /** - * Gets the message to display to the client when authentication fails. - * - * @return the message to display to the client - */ - @NotNull - public String getFailMessage() { - return this.failMessage; - } - - /** - * Sets the message to display to the client when authentication fails. - * - * @param failMessage the message to display to the client - */ - public void setFailMessage(@NotNull String failMessage) { - Validate.notEmpty(failMessage, "fail message cannot be null or empty"); - this.failMessage = failMessage; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } - - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerInitialSpawnEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerInitialSpawnEvent.java deleted file mode 100644 index 8e407eff1..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerInitialSpawnEvent.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public class PlayerInitialSpawnEvent extends PlayerEvent { - private static final HandlerList handlers = new HandlerList(); - @NotNull private Location spawnLocation; - - public PlayerInitialSpawnEvent(@NotNull final Player player, @NotNull final Location spawnLocation) { - super(player); - this.spawnLocation = spawnLocation; - } - - /** - * Gets the current spawn location - * - * @return Location current spawn location - */ - @NotNull - public Location getSpawnLocation() { - return this.spawnLocation; - } - - /** - * Sets the new spawn location - * - * @param spawnLocation new location for the spawn - */ - public void setSpawnLocation(@NotNull Location spawnLocation) { - this.spawnLocation = spawnLocation; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerJumpEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerJumpEvent.java deleted file mode 100644 index 289a0d784..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerJumpEvent.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.destroystokyo.paper.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; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Called when the server detects the player is jumping. - *

- * Added to avoid the overhead and special case logic that many plugins use - * when checking for jumps via PlayerMoveEvent, this event is fired whenever - * the server detects that the player is jumping. - */ -public class PlayerJumpEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancel = false; - @NotNull private Location from; - @NotNull private Location to; - - public PlayerJumpEvent(@NotNull final Player player, @NotNull final Location from, @NotNull 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 jump 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 jump 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 jumped from - * - * @return Location the player jumped from - */ - @NotNull - public Location getFrom() { - return from; - } - - /** - * Sets the location to mark as where the player jumped from - * - * @param from New location to mark as the players previous location - */ - public void setFrom(@NotNull Location from) { - validateLocation(from); - this.from = from; - } - - /** - * Gets the location this player jumped to - * - * This information is based on what the client sends, it typically - * has little relation to the arc of the jump at any given point. - * - * @return Location the player jumped to - */ - @NotNull - public Location getTo() { - return to; - } - - private void validateLocation(Location loc) { - Preconditions.checkArgument(loc != null, "Cannot use null location!"); - Preconditions.checkArgument(loc.getWorld() != null, "Cannot use location with null world!"); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerLaunchProjectileEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerLaunchProjectileEvent.java deleted file mode 100644 index 9074b2ede..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerLaunchProjectileEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player shoots a projectile - */ -public class PlayerLaunchProjectileEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - @NotNull private final Projectile projectile; - @NotNull private final ItemStack itemStack; - private boolean consumeItem = true; - private boolean cancelled; - - public PlayerLaunchProjectileEvent(@NotNull Player shooter, @NotNull ItemStack itemStack, @NotNull Projectile projectile) { - super(shooter); - this.itemStack = itemStack; - this.projectile = projectile; - } - - /** - * Gets the projectile which will be launched by this event - * - * @return the launched projectile - */ - @NotNull - public Projectile getProjectile() { - return projectile; - } - - /** - * Get the ItemStack used to fire the projectile - * - * @return The ItemStack used - */ - @NotNull - public ItemStack getItemStack() { - return itemStack; - } - - /** - * Get whether to consume the ItemStack or not - * - * @return True to consume - */ - public boolean shouldConsume() { - return consumeItem; - } - - /** - * Set whether to consume the ItemStack or not - * - * @param consumeItem True to consume - */ - public void setShouldConsume(boolean consumeItem) { - this.consumeItem = consumeItem; - } - - public boolean isCancelled() { - return cancelled; - } - - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerLocaleChangeEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerLocaleChangeEvent.java deleted file mode 100644 index 29dd763a9..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerLocaleChangeEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; - -/** - * Called when the locale of the player is changed. - * - * @deprecated Replaced by {@link org.bukkit.event.player.PlayerLocaleChangeEvent} upstream - */ -@Deprecated -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; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerPickupExperienceEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerPickupExperienceEvent.java deleted file mode 100644 index f7beb22d5..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerPickupExperienceEvent.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2017 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 com.destroystokyo.paper.event.player; - -import org.bukkit.entity.ExperienceOrb; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a player is attempting to pick up an experience orb - */ -public class PlayerPickupExperienceEvent extends PlayerEvent implements Cancellable { - @NotNull private final ExperienceOrb experienceOrb; - - public PlayerPickupExperienceEvent(@NotNull Player player, @NotNull ExperienceOrb experienceOrb) { - super(player); - this.experienceOrb = experienceOrb; - } - - /** - * @return Returns the Orb that the player is picking up - */ - @NotNull - public ExperienceOrb getExperienceOrb() { - return experienceOrb; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * If true, Cancels picking up the experience orb, leaving it in the world - * @param cancel true if you wish to cancel this event - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerPostRespawnEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerPostRespawnEvent.java deleted file mode 100644 index 31f34b548..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerPostRespawnEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired after a player has respawned - */ -public class PlayerPostRespawnEvent extends PlayerEvent { - private final static HandlerList handlers = new HandlerList(); - private final Location respawnedLocation; - private final boolean isBedSpawn; - - public PlayerPostRespawnEvent(@NotNull final Player respawnPlayer, @NotNull final Location respawnedLocation, final boolean isBedSpawn) { - super(respawnPlayer); - this.respawnedLocation = respawnedLocation; - this.isBedSpawn = isBedSpawn; - } - - /** - * Returns the location of the respawned player - * - * @return location of the respawned player - */ - @NotNull - public Location getRespawnedLocation() { - return respawnedLocation.clone(); - } - - /** - * Checks if the player respawned to their bed - * - * @return whether the player respawned to their bed - */ - public boolean isBedSpawn() { - return isBedSpawn; - } - - @Override - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerReadyArrowEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerReadyArrowEvent.java deleted file mode 100644 index 5d04a22fd..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerReadyArrowEvent.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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 com.destroystokyo.paper.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player is firing a bow and the server is choosing an arrow to use. - */ -public class PlayerReadyArrowEvent extends PlayerEvent implements Cancellable { - @NotNull private final ItemStack bow; - @NotNull private final ItemStack arrow; - - public PlayerReadyArrowEvent(@NotNull Player player, @NotNull ItemStack bow, @NotNull ItemStack arrow) { - super(player); - this.bow = bow; - this.arrow = arrow; - } - - /** - * @return the player is using to fire the arrow - */ - @NotNull - public ItemStack getBow() { - return bow; - } - - /** - * @return the arrow that is attempting to be used - */ - @NotNull - public ItemStack getArrow() { - return arrow; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - /** - * Whether or not use of this arrow is cancelled. On cancel, the server will try the next arrow available and fire another event. - */ - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * Cancel use of this arrow. On cancel, the server will try the next arrow available and fire another event. - * @param cancel true if you wish to cancel this event - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerStartSpectatingEntityEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerStartSpectatingEntityEvent.java deleted file mode 100644 index b8ec7ef2d..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerStartSpectatingEntityEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.destroystokyo.paper.event.player; - -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; -import org.jetbrains.annotations.NotNull; - -/** - * Triggered when a player starts spectating an entity in spectator mode. - */ -public class PlayerStartSpectatingEntityEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - @NotNull private final Entity currentSpectatorTarget; - @NotNull private final Entity newSpectatorTarget; - - public PlayerStartSpectatingEntityEvent(@NotNull Player player, @NotNull Entity currentSpectatorTarget, @NotNull Entity newSpectatorTarget) { - super(player); - this.currentSpectatorTarget = currentSpectatorTarget; - this.newSpectatorTarget = newSpectatorTarget; - } - - /** - * Gets the entity that the player is currently spectating or themselves if they weren't spectating anything - * - * @return The entity the player is currently spectating (before they start spectating the new target). - */ - @NotNull - public Entity getCurrentSpectatorTarget() { - return currentSpectatorTarget; - } - - /** - * Gets the new entity that the player will now be spectating - * - * @return The entity the player is now going to be spectating. - */ - @NotNull - public Entity getNewSpectatorTarget() { - return newSpectatorTarget; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} - diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerStopSpectatingEntityEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerStopSpectatingEntityEvent.java deleted file mode 100644 index 693d119ab..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerStopSpectatingEntityEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.destroystokyo.paper.event.player; - -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; -import org.jetbrains.annotations.NotNull; - -/** - * Triggered when a player stops spectating an entity in spectator mode. - */ -public class PlayerStopSpectatingEntityEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - @NotNull private final Entity spectatorTarget; - - public PlayerStopSpectatingEntityEvent(@NotNull Player player, @NotNull Entity spectatorTarget) { - super(player); - this.spectatorTarget = spectatorTarget; - } - - /** - * Gets the entity that the player is spectating - * - * @return The entity the player is currently spectating (before they will stop). - */ - @NotNull - public Entity getSpectatorTarget() { - return spectatorTarget; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerTeleportEndGatewayEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerTeleportEndGatewayEvent.java deleted file mode 100644 index b64ab6eec..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerTeleportEndGatewayEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.Location; -import org.bukkit.block.EndGateway; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when a teleport is triggered for an End Gateway - */ -public class PlayerTeleportEndGatewayEvent extends PlayerTeleportEvent { - @NotNull private final EndGateway gateway; - - public PlayerTeleportEndGatewayEvent(@NotNull Player player, @NotNull Location from, @NotNull Location to, @NotNull EndGateway gateway) { - super(player, from, to, PlayerTeleportEvent.TeleportCause.END_GATEWAY); - this.gateway = gateway; - } - - /** - * The gateway triggering the teleport - * - * @return EndGateway used - */ - @NotNull - public EndGateway getGateway() { - return gateway; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerUseUnknownEntityEvent.java b/api/src/main/java/com/destroystokyo/paper/event/player/PlayerUseUnknownEntityEvent.java deleted file mode 100644 index 09cfdf48e..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/player/PlayerUseUnknownEntityEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.destroystokyo.paper.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.jetbrains.annotations.NotNull; - -public class PlayerUseUnknownEntityEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - private final int entityId; - private final boolean attack; - @NotNull private final EquipmentSlot hand; - - public PlayerUseUnknownEntityEvent(@NotNull Player who, int entityId, boolean attack, @NotNull EquipmentSlot hand) { - super(who); - this.entityId = entityId; - this.attack = attack; - this.hand = hand; - } - - public int getEntityId() { - return this.entityId; - } - - public boolean isAttack() { - return this.attack; - } - - @NotNull - public EquipmentSlot getHand() { - return this.hand; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/profile/FillProfileEvent.java b/api/src/main/java/com/destroystokyo/paper/event/profile/FillProfileEvent.java deleted file mode 100644 index 71f36e9ca..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/profile/FillProfileEvent.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 com.destroystokyo.paper.event.profile; - -import com.destroystokyo.paper.profile.PlayerProfile; -import com.destroystokyo.paper.profile.ProfileProperty; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.util.Set; -import org.jetbrains.annotations.NotNull; - -/** - * Fired once a profiles additional properties (such as textures) has been filled - */ -public class FillProfileEvent extends Event { - @NotNull private final PlayerProfile profile; - - public FillProfileEvent(@NotNull PlayerProfile profile) { - super(!org.bukkit.Bukkit.isPrimaryThread()); - this.profile = profile; - } - - /** - * @return The Profile that had properties filled - */ - @NotNull - public PlayerProfile getPlayerProfile() { - return profile; - } - - /** - * Same as .getPlayerProfile().getProperties() - * - * @see PlayerProfile#getProperties() - * @return The new properties on the profile. - */ - @NotNull - public Set getProperties() { - return profile.getProperties(); - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/profile/LookupProfileEvent.java b/api/src/main/java/com/destroystokyo/paper/event/profile/LookupProfileEvent.java deleted file mode 100644 index 8df37c07c..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/profile/LookupProfileEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.destroystokyo.paper.event.profile; - -import com.destroystokyo.paper.profile.PlayerProfile; -import org.bukkit.Bukkit; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import org.jetbrains.annotations.NotNull; - -/** - * Allows a plugin to be notified anytime AFTER a Profile has been looked up from the Mojang API - * This is an opportunity to view the response and potentially cache things. - * - * No guarantees are made about thread execution context for this event. If you need to know, check - * event.isAsync() - */ -public class LookupProfileEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - - @NotNull private final PlayerProfile profile; - - public LookupProfileEvent(@NotNull PlayerProfile profile) { - super(!Bukkit.isPrimaryThread()); - this.profile = profile; - } - - /** - * @return The profile that was recently looked up. This profile can be mutated - */ - @NotNull - public PlayerProfile getPlayerProfile() { - return profile; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/profile/PreFillProfileEvent.java b/api/src/main/java/com/destroystokyo/paper/event/profile/PreFillProfileEvent.java deleted file mode 100644 index 021bc8631..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/profile/PreFillProfileEvent.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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 com.destroystokyo.paper.event.profile; - -import com.destroystokyo.paper.profile.PlayerProfile; -import com.destroystokyo.paper.profile.ProfileProperty; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.util.Collection; -import org.jetbrains.annotations.NotNull; - -/** - * Fired when the server is requesting to fill in properties of an incomplete profile, such as textures. - * - * Allows plugins to pre populate cached properties and avoid a call to the Mojang API - */ -public class PreFillProfileEvent extends Event { - @NotNull private final PlayerProfile profile; - - public PreFillProfileEvent(@NotNull PlayerProfile profile) { - super(!org.bukkit.Bukkit.isPrimaryThread()); - this.profile = profile; - } - - /** - * @return The profile that needs its properties filled - */ - @NotNull - public PlayerProfile getPlayerProfile() { - return profile; - } - - /** - * Sets the properties on the profile, avoiding the call to the Mojang API - * Same as .getPlayerProfile().setProperties(properties); - * - * @see PlayerProfile#setProperties(Collection) - * @param properties The properties to set/append - */ - public void setProperties(@NotNull Collection properties) { - profile.setProperties(properties); - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/profile/PreLookupProfileEvent.java b/api/src/main/java/com/destroystokyo/paper/event/profile/PreLookupProfileEvent.java deleted file mode 100644 index 4dcf6242c..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/profile/PreLookupProfileEvent.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.destroystokyo.paper.event.profile; - -import com.destroystokyo.paper.profile.PlayerProfile; -import com.destroystokyo.paper.profile.ProfileProperty; -import com.google.common.collect.ArrayListMultimap; -import org.bukkit.Bukkit; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Allows a plugin to intercept a Profile Lookup for a Profile by name - * - * At the point of event fire, the UUID and properties are unset. - * - * If a plugin sets the UUID, and optionally the properties, the API call to look up the profile may be skipped. - * - * No guarantees are made about thread execution context for this event. If you need to know, check - * event.isAsync() - */ -public class PreLookupProfileEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - @NotNull private final String name; - private UUID uuid; - @NotNull private Set properties = new HashSet<>(); - - public PreLookupProfileEvent(@NotNull String name) { - super(!Bukkit.isPrimaryThread()); - this.name = name; - } - - /** - * @return Name of the profile - */ - @NotNull - public String getName() { - return name; - } - - /** - * If this value is left null by the completion of the event call, then the server will - * trigger a call to the Mojang API to look up the UUID (Network Request), and subsequently, fire a - * {@link LookupProfileEvent} - * - * @return The UUID of the profile if it has already been provided by a plugin - */ - @Nullable - public UUID getUUID() { - return uuid; - } - - /** - * Sets the UUID for this player name. This will skip the initial API call to find the players UUID. - * - * However, if Profile Properties are needed by the server, you must also set them or else an API call might still be made. - * - * @param uuid the UUID to set for the profile or null to reset - */ - public void setUUID(@Nullable UUID uuid) { - this.uuid = uuid; - } - - /** - * @return The currently pending prepopulated properties. - * Any property in this Set will be automatically prefilled on this Profile - */ - @NotNull - public Set getProfileProperties() { - return this.properties; - } - - /** - * Clears any existing prepopulated properties and uses the supplied properties - * Any property in this Set will be automatically prefilled on this Profile - * @param properties The properties to add - */ - public void setProfileProperties(@NotNull Set properties) { - this.properties = new HashSet<>(); - this.properties.addAll(properties); - } - - /** - * Adds any properties currently missing to the prepopulated properties set, replacing any that already were set. - * Any property in this Set will be automatically prefilled on this Profile - * @param properties The properties to add - */ - public void addProfileProperties(@NotNull Set properties) { - this.properties.addAll(properties); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/profile/ProfileWhitelistVerifyEvent.java b/api/src/main/java/com/destroystokyo/paper/event/profile/ProfileWhitelistVerifyEvent.java deleted file mode 100644 index b10176289..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/profile/ProfileWhitelistVerifyEvent.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2017 - 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 com.destroystokyo.paper.event.profile; - -import com.destroystokyo.paper.profile.PlayerProfile; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Fires when the server needs to verify if a player is whitelisted. - * - * Plugins may override/control the servers whitelist with this event, - * and dynamically change the kick message. - * - */ -public class ProfileWhitelistVerifyEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - @NotNull private final PlayerProfile profile; - private final boolean whitelistEnabled; - private boolean whitelisted; - private final boolean isOp; - @Nullable private String kickMessage; - - public ProfileWhitelistVerifyEvent(@NotNull final PlayerProfile profile, boolean whitelistEnabled, boolean whitelisted, boolean isOp, @Nullable String kickMessage) { - this.profile = profile; - this.whitelistEnabled = whitelistEnabled; - this.whitelisted = whitelisted; - this.isOp = isOp; - this.kickMessage = kickMessage; - } - - /** - * @return the currently planned message to send to the user if they are not whitelisted - */ - @Nullable - public String getKickMessage() { - return kickMessage; - } - - /** - * @param kickMessage The message to send to the player on kick if not whitelisted. May set to null to use the server configured default - */ - public void setKickMessage(@Nullable String kickMessage) { - this.kickMessage = kickMessage; - } - - /** - * @return The profile of the player trying to connect - */ - @NotNull - public PlayerProfile getPlayerProfile() { - return profile; - } - - /** - * @return Whether the player is whitelisted to play on this server (whitelist may be off is why its true) - */ - public boolean isWhitelisted() { - return whitelisted; - } - - /** - * Changes the players whitelisted state. false will deny the login - * @param whitelisted The new whitelisted state - */ - public void setWhitelisted(boolean whitelisted) { - this.whitelisted = whitelisted; - } - - /** - * @return if the player obtained whitelist status by having op - */ - public boolean isOp() { - return isOp; - } - - /** - * @return if the server even has whitelist on - */ - public boolean isWhitelistEnabled() { - return whitelistEnabled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/server/AsyncTabCompleteEvent.java b/api/src/main/java/com/destroystokyo/paper/event/server/AsyncTabCompleteEvent.java deleted file mode 100644 index 619ed3716..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/server/AsyncTabCompleteEvent.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2017 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 com.destroystokyo.paper.event.server; - -import com.google.common.collect.ImmutableList; -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.util.ArrayList; -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Allows plugins to compute tab completion results asynchronously. If this event provides completions, then the standard synchronous process will not be fired to populate the results. However, the synchronous TabCompleteEvent will fire with the Async results. - * - * Only 1 process will be allowed to provide completions, the Async Event, or the standard process. - */ -public class AsyncTabCompleteEvent extends Event implements Cancellable { - @NotNull private final CommandSender sender; - @NotNull private final String buffer; - private final boolean isCommand; - @Nullable - private final Location loc; - @NotNull private List completions; - private boolean cancelled; - private boolean handled = false; - private boolean fireSyncHandler = true; - - public AsyncTabCompleteEvent(@NotNull CommandSender sender, @NotNull List completions, @NotNull String buffer, boolean isCommand, @Nullable Location loc) { - super(true); - this.sender = sender; - this.completions = completions; - this.buffer = buffer; - this.isCommand = isCommand; - this.loc = loc; - } - - /** - * Get the sender completing this command. - * - * @return the {@link CommandSender} instance - */ - @NotNull - public CommandSender getSender() { - return sender; - } - - /** - * The list of completions which will be offered to the sender, in order. - * This list is mutable and reflects what will be offered. - * - * If this collection is not empty after the event is fired, then - * the standard process of calling {@link Command#tabComplete(CommandSender, String, String[])} - * or current player names will not be called. - * - * @return a list of offered completions - */ - @NotNull - public List getCompletions() { - return completions; - } - - /** - * Set the completions offered, overriding any already set. - * If this collection is not empty after the event is fired, then - * the standard process of calling {@link Command#tabComplete(CommandSender, String, String[])} - * or current player names will not be called. - * - * The passed collection will be cloned to a new List. You must call {{@link #getCompletions()}} to mutate from here - * - * @param completions the new completions - */ - public void setCompletions(@NotNull List completions) { - Validate.notNull(completions); - this.completions = new ArrayList<>(completions); - } - - /** - * Return the entire buffer which formed the basis of this completion. - * - * @return command buffer, as entered - */ - @NotNull - public String getBuffer() { - return buffer; - } - - /** - * @return True if it is a command being tab completed, false if it is a chat message. - */ - public boolean isCommand() { - return isCommand; - } - - /** - * @return The position looked at by the sender, or null if none - */ - @Nullable - public Location getLocation() { - return loc; - } - - /** - * If true, the standard process of calling {@link Command#tabComplete(CommandSender, String, String[])} - * or current player names will not be called. - * - * @return Is completions considered handled. Always true if completions is not empty. - */ - public boolean isHandled() { - return !completions.isEmpty() || handled; - } - - /** - * Sets whether or not to consider the completion request handled. - * If true, the standard process of calling {@link Command#tabComplete(CommandSender, String, String[])} - * or current player names will not be called. - * - * @param handled if this completion should be marked as being handled - */ - public void setHandled(boolean handled) { - this.handled = handled; - } - - private static final HandlerList handlers = new HandlerList(); - - - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * Will provide no completions, and will not fire the synchronous process - * @param cancelled true if you wish to cancel this event - */ - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/server/GS4QueryEvent.java b/api/src/main/java/com/destroystokyo/paper/event/server/GS4QueryEvent.java deleted file mode 100644 index 77a19995f..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/server/GS4QueryEvent.java +++ /dev/null @@ -1,412 +0,0 @@ -package com.destroystokyo.paper.event.server; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -/** - * This event is fired if server is getting queried over GS4 Query protocol - * - * Adapted from Velocity's ProxyQueryEvent - * - * @author Mark Vainomaa - */ -public final class GS4QueryEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - - private final QueryType queryType; - private final InetAddress querierAddress; - private QueryResponse response; - - public GS4QueryEvent(@NotNull QueryType queryType, @NotNull InetAddress querierAddress, @NotNull QueryResponse response) { - super(true); // should always be called async - this.queryType = Preconditions.checkNotNull(queryType, "queryType"); - this.querierAddress = Preconditions.checkNotNull(querierAddress, "querierAddress"); - this.response = Preconditions.checkNotNull(response, "response"); - } - - /** - * Get query type - * @return query type - */ - @NotNull - public QueryType getQueryType() { - return queryType; - } - - /** - * Get querier address - * @return querier address - */ - @NotNull - public InetAddress getQuerierAddress() { - return querierAddress; - } - - /** - * Get query response - * @return query response - */ - @NotNull - public QueryResponse getResponse() { - return response; - } - - /** - * Set query response - * @param response query response - */ - public void setResponse(@NotNull QueryResponse response) { - this.response = Preconditions.checkNotNull(response, "response"); - } - - @Override - public String toString() { - return "GS4QueryEvent{" + - "queryType=" + queryType + - ", querierAddress=" + querierAddress + - ", response=" + response + - '}'; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * The type of query - */ - public enum QueryType { - /** - * Basic query asks only a subset of information, such as motd, game type (hardcoded to

MINECRAFT
), map, - * current players, max players, server port and server motd - */ - BASIC, - - /** - * Full query asks pretty much everything present on this event (only hardcoded values cannot be modified here). - */ - FULL - ; - } - - public final static class QueryResponse { - private final String motd; - private final String gameVersion; - private final String map; - private final int currentPlayers; - private final int maxPlayers; - private final String hostname; - private final int port; - private final Collection players; - private final String serverVersion; - private final Collection plugins; - - private QueryResponse(String motd, String gameVersion, String map, int currentPlayers, int maxPlayers, String hostname, int port, Collection players, String serverVersion, Collection plugins) { - this.motd = motd; - this.gameVersion = gameVersion; - this.map = map; - this.currentPlayers = currentPlayers; - this.maxPlayers = maxPlayers; - this.hostname = hostname; - this.port = port; - this.players = players; - this.serverVersion = serverVersion; - this.plugins = plugins; - } - - /** - * Get motd which will be used to reply to the query. By default it is {@link org.bukkit.Server#getMotd()}. - * @return motd - */ - @NotNull - public String getMotd() { - return motd; - } - - /** - * Get game version which will be used to reply to the query. By default supported Minecraft versions range is sent. - * @return game version - */ - @NotNull - public String getGameVersion() { - return gameVersion; - } - - /** - * Get map name which will be used to reply to the query. By default {@code world} is sent. - * @return map name - */ - @NotNull - public String getMap() { - return map; - } - - /** - * Get current online player count which will be used to reply to the query. - * @return online player count - */ - public int getCurrentPlayers() { - return currentPlayers; - } - - /** - * Get max player count which will be used to reply to the query. - * @return max player count - */ - public int getMaxPlayers() { - return maxPlayers; - } - - /** - * Get server (public facing) hostname - * @return server hostname - */ - @NotNull - public String getHostname() { - return hostname; - } - - /** - * Get server (public facing) port - * @return server port - */ - public int getPort() { - return port; - } - - /** - * Get collection of players which will be used to reply to the query. - * @return collection of players - */ - @NotNull - public Collection getPlayers() { - return players; - } - - /** - * Get server software (name and version) which will be used to reply to the query. - * @return server software - */ - @NotNull - public String getServerVersion() { - return serverVersion; - } - - /** - * Get list of plugins which will be used to reply to the query. - * @return collection of plugins - */ - @NotNull - public Collection getPlugins() { - return plugins; - } - - - /** - * Creates a new {@link Builder} instance from data represented by this response - * @return {@link QueryResponse} builder - */ - @NotNull - public Builder toBuilder() { - return QueryResponse.builder() - .motd(getMotd()) - .gameVersion(getGameVersion()) - .map(getMap()) - .currentPlayers(getCurrentPlayers()) - .maxPlayers(getMaxPlayers()) - .hostname(getHostname()) - .port(getPort()) - .players(getPlayers()) - .serverVersion(getServerVersion()) - .plugins(getPlugins()); - } - - /** - * Creates a new {@link Builder} instance - * @return {@link QueryResponse} builder - */ - @NotNull - public static Builder builder() { - return new Builder(); - } - - /** - * A builder for {@link QueryResponse} objects. - */ - public static final class Builder { - private String motd; - private String gameVersion; - private String map; - private String hostname; - private String serverVersion; - - private int currentPlayers; - private int maxPlayers; - private int port; - - private List players = new ArrayList<>(); - private List plugins = new ArrayList<>(); - - private Builder() {} - - @NotNull - public Builder motd(@NotNull String motd) { - this.motd = Preconditions.checkNotNull(motd, "motd"); - return this; - } - - @NotNull - public Builder gameVersion(@NotNull String gameVersion) { - this.gameVersion = Preconditions.checkNotNull(gameVersion, "gameVersion"); - return this; - } - - @NotNull - public Builder map(@NotNull String map) { - this.map = Preconditions.checkNotNull(map, "map"); - return this; - } - - @NotNull - public Builder currentPlayers(int currentPlayers) { - Preconditions.checkArgument(currentPlayers >= 0, "currentPlayers cannot be negative"); - this.currentPlayers = currentPlayers; - return this; - } - - @NotNull - public Builder maxPlayers(int maxPlayers) { - Preconditions.checkArgument(maxPlayers >= 0, "maxPlayers cannot be negative"); - this.maxPlayers = maxPlayers; - return this; - } - - @NotNull - public Builder hostname(@NotNull String hostname) { - this.hostname = Preconditions.checkNotNull(hostname, "hostname"); - return this; - } - - @NotNull - public Builder port(int port) { - Preconditions.checkArgument(port >= 1 && port <= 65535, "port must be between 1-65535"); - this.port = port; - return this; - } - - @NotNull - public Builder players(@NotNull Collection players) { - this.players.addAll(Preconditions.checkNotNull(players, "players")); - return this; - } - - @NotNull - public Builder players(@NotNull String... players) { - this.players.addAll(Arrays.asList(Preconditions.checkNotNull(players, "players"))); - return this; - } - - @NotNull - public Builder clearPlayers() { - this.players.clear(); - return this; - } - - @NotNull - public Builder serverVersion(@NotNull String serverVersion) { - this.serverVersion = Preconditions.checkNotNull(serverVersion, "serverVersion"); - return this; - } - - @NotNull - public Builder plugins(@NotNull Collection plugins) { - this.plugins.addAll(Preconditions.checkNotNull(plugins, "plugins")); - return this; - } - - @NotNull - public Builder plugins(@NotNull PluginInformation... plugins) { - this.plugins.addAll(Arrays.asList(Preconditions.checkNotNull(plugins, "plugins"))); - return this; - } - - @NotNull - public Builder clearPlugins() { - this.plugins.clear(); - return this; - } - - /** - * Builds new {@link QueryResponse} with supplied data - * @return response - */ - @NotNull - public QueryResponse build() { - return new QueryResponse( - Preconditions.checkNotNull(motd, "motd"), - Preconditions.checkNotNull(gameVersion, "gameVersion"), - Preconditions.checkNotNull(map, "map"), - currentPlayers, - maxPlayers, - Preconditions.checkNotNull(hostname, "hostname"), - port, - ImmutableList.copyOf(players), - Preconditions.checkNotNull(serverVersion, "serverVersion"), - ImmutableList.copyOf(plugins) - ); - } - } - - /** - * Plugin information - */ - public static class PluginInformation { - private String name; - private String version; - - public PluginInformation(@NotNull String name, @NotNull String version) { - this.name = Preconditions.checkNotNull(name, "name"); - this.version = Preconditions.checkNotNull(version, "version"); - } - - @NotNull - public String getName() { - return name; - } - - public void setName(@NotNull String name) { - this.name = name; - } - - public void setVersion(@NotNull String version) { - this.version = version; - } - - @NotNull - public String getVersion() { - return version; - } - - @NotNull - public static PluginInformation of(@NotNull String name, @NotNull String version) { - return new PluginInformation(name, version); - } - } - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/server/PaperServerListPingEvent.java b/api/src/main/java/com/destroystokyo/paper/event/server/PaperServerListPingEvent.java deleted file mode 100644 index 0cc5dd573..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/server/PaperServerListPingEvent.java +++ /dev/null @@ -1,323 +0,0 @@ -package com.destroystokyo.paper.event.server; - -import static java.util.Objects.requireNonNull; - -import com.destroystokyo.paper.network.StatusClient; -import com.destroystokyo.paper.profile.PlayerProfile; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.server.ServerListPingEvent; -import org.bukkit.util.CachedServerIcon; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.UUID; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Extended version of {@link ServerListPingEvent} that allows full control - * of the response sent to the client. - */ -public class PaperServerListPingEvent extends ServerListPingEvent implements Cancellable { - - @NotNull private final StatusClient client; - - private int numPlayers; - private boolean hidePlayers; - @NotNull private final List playerSample = new ArrayList<>(); - - @NotNull private String version; - private int protocolVersion; - - @Nullable private CachedServerIcon favicon; - - private boolean cancelled; - - private boolean originalPlayerCount = true; - private Object[] players; - - public PaperServerListPingEvent(@NotNull StatusClient client, @NotNull String motd, int numPlayers, int maxPlayers, - @NotNull String version, int protocolVersion, @Nullable CachedServerIcon favicon) { - super(client.getAddress().getAddress(), motd, numPlayers, maxPlayers); - this.client = client; - this.numPlayers = numPlayers; - this.version = version; - this.protocolVersion = protocolVersion; - setServerIcon(favicon); - } - - /** - * Returns the {@link StatusClient} pinging the server. - * - * @return The client - */ - @NotNull - public StatusClient getClient() { - return this.client; - } - - /** - * {@inheritDoc} - * - *

Returns {@code -1} if players are hidden using - * {@link #shouldHidePlayers()}.

- */ - @Override - public int getNumPlayers() { - if (this.hidePlayers) { - return -1; - } - - return this.numPlayers; - } - - /** - * Sets the number of players displayed in the server list. - * - *

Note that this won't have any effect if {@link #shouldHidePlayers()} - * is enabled.

- * - * @param numPlayers The number of online players - */ - public void setNumPlayers(int numPlayers) { - if (this.numPlayers != numPlayers) { - this.numPlayers = numPlayers; - this.originalPlayerCount = false; - } - } - - /** - * {@inheritDoc} - * - *

Returns {@code -1} if players are hidden using - * {@link #shouldHidePlayers()}.

- */ - @Override - public int getMaxPlayers() { - if (this.hidePlayers) { - return -1; - } - - return super.getMaxPlayers(); - } - - /** - * Returns whether all player related information is hidden in the server - * list. This will cause {@link #getNumPlayers()}, {@link #getMaxPlayers()} - * and {@link #getPlayerSample()} to be skipped in the response. - * - *

The Vanilla Minecraft client will display the player count as {@code ???} - * when this option is enabled.

- * - * @return {@code true} if the player count is hidden - */ - public boolean shouldHidePlayers() { - return hidePlayers; - } - - /** - * Sets whether all player related information is hidden in the server - * list. This will cause {@link #getNumPlayers()}, {@link #getMaxPlayers()} - * and {@link #getPlayerSample()} to be skipped in the response. - * - *

The Vanilla Minecraft client will display the player count as {@code ???} - * when this option is enabled.

- * - * @param hidePlayers {@code true} if the player count should be hidden - */ - public void setHidePlayers(boolean hidePlayers) { - this.hidePlayers = hidePlayers; - } - - /** - * Returns a mutable list of {@link PlayerProfile} that will be displayed - * as online players on the client. - * - *

The Vanilla Minecraft client will display them when hovering the - * player count with the mouse.

- * - * @return The mutable player sample list - */ - @NotNull - public List getPlayerSample() { - return this.playerSample; - } - - /** - * Returns the version that will be sent as server version on the client. - * - * @return The server version - */ - @NotNull - public String getVersion() { - return version; - } - - /** - * Sets the version that will be sent as server version to the client. - * - * @param version The server version - */ - public void setVersion(@NotNull String version) { - this.version = requireNonNull(version, "version"); - } - - /** - * Returns the protocol version that will be sent as the protocol version - * of the server to the client. - * - * @return The protocol version of the server, or {@code -1} if the server - * has not finished initialization yet - */ - public int getProtocolVersion() { - return protocolVersion; - } - - /** - * Sets the protocol version that will be sent as the protocol version - * of the server to the client. - * - * @param protocolVersion The protocol version of the server - */ - public void setProtocolVersion(int protocolVersion) { - this.protocolVersion = protocolVersion; - } - - /** - * Gets the server icon sent to the client. - * - * @return The icon to send to the client, or {@code null} for none - */ - @Nullable - public CachedServerIcon getServerIcon() { - return this.favicon; - } - - /** - * Sets the server icon sent to the client. - * - * @param icon The icon to send to the client, or {@code null} for none - */ - @Override - public void setServerIcon(@Nullable CachedServerIcon icon) { - if (icon != null && icon.isEmpty()) { - // Represent empty icons as null - icon = null; - } - - this.favicon = icon; - } - - /** - * {@inheritDoc} - * - *

Cancelling this event will cause the connection to be closed immediately, - * without sending a response to the client.

- */ - @Override - public boolean isCancelled() { - return this.cancelled; - } - - /** - * {@inheritDoc} - * - *

Cancelling this event will cause the connection to be closed immediately, - * without sending a response to the client.

- */ - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - /** - * {@inheritDoc} - * - *

Note: For compatibility reasons, this method will return all - * online players, not just the ones referenced in {@link #getPlayerSample()}. - * Removing a player will:

- * - *
    - *
  • Decrement the online player count (if and only if) the player - * count wasn't changed by another plugin before.
  • - *
  • Remove all entries from {@link #getPlayerSample()} that refer to - * the removed player (based on their {@link UUID}).
  • - *
- */ - @NotNull - @Override - public Iterator iterator() { - if (this.players == null) { - this.players = getOnlinePlayers(); - } - - return new PlayerIterator(); - } - - @NotNull - protected Object[] getOnlinePlayers() { - return Bukkit.getOnlinePlayers().toArray(); - } - - @NotNull - protected Player getBukkitPlayer(@NotNull Object player) { - return (Player) player; - } - - private final class PlayerIterator implements Iterator { - - private int next; - private int current; - @Nullable private Player player; - - @Override - public boolean hasNext() { - for (; this.next < players.length; this.next++) { - if (players[this.next] != null) { - return true; - } - } - - return false; - } - - @NotNull - @Override - public Player next() { - if (!hasNext()) { - this.player = null; - throw new NoSuchElementException(); - } - - this.current = this.next++; - return this.player = getBukkitPlayer(players[this.current]); - } - - @Override - public void remove() { - if (this.player == null) { - throw new IllegalStateException(); - } - - UUID uniqueId = this.player.getUniqueId(); - this.player = null; - - // Remove player from iterator - players[this.current] = null; - - // Remove player from sample - getPlayerSample().removeIf(p -> uniqueId.equals(p.getId())); - - // Decrement player count - if (originalPlayerCount) { - numPlayers--; - } - } - } - -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/server/ServerExceptionEvent.java b/api/src/main/java/com/destroystokyo/paper/event/server/ServerExceptionEvent.java deleted file mode 100644 index 2f573299a..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/server/ServerExceptionEvent.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.destroystokyo.paper.event.server; - -import com.google.common.base.Preconditions; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import com.destroystokyo.paper.exception.ServerException; -import org.jetbrains.annotations.NotNull; - -/** - * 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(); - @NotNull private ServerException exception; - - public ServerExceptionEvent(@NotNull ServerException exception) { - super(!Bukkit.isPrimaryThread()); - this.exception = Preconditions.checkNotNull(exception, "exception"); - } - - /** - * Gets the wrapped exception that was thrown. - * - * @return Exception thrown - */ - @NotNull - public ServerException getException() { - return exception; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/event/server/ServerTickEndEvent.java b/api/src/main/java/com/destroystokyo/paper/event/server/ServerTickEndEvent.java deleted file mode 100644 index 9fd28e036..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/server/ServerTickEndEvent.java +++ /dev/null @@ -1,59 +0,0 @@ -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/api/src/main/java/com/destroystokyo/paper/event/server/ServerTickStartEvent.java b/api/src/main/java/com/destroystokyo/paper/event/server/ServerTickStartEvent.java deleted file mode 100644 index eac85f1f4..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/server/ServerTickStartEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -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/api/src/main/java/com/destroystokyo/paper/event/server/WhitelistToggleEvent.java b/api/src/main/java/com/destroystokyo/paper/event/server/WhitelistToggleEvent.java deleted file mode 100644 index fdd5eedb2..000000000 --- a/api/src/main/java/com/destroystokyo/paper/event/server/WhitelistToggleEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.destroystokyo.paper.event.server; - -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * This event is fired when whitelist is toggled - * - * @author Mark Vainomaa - */ -public class WhitelistToggleEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - - private boolean enabled; - - public WhitelistToggleEvent(boolean enabled) { - this.enabled = enabled; - } - - /** - * Gets whether whitelist is going to be enabled or not - * - * @return Whether whitelist is going to be enabled or not - */ - public boolean isEnabled() { - return enabled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/exception/ServerCommandException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerCommandException.java deleted file mode 100644 index 6fb39af04..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerCommandException.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.destroystokyo.paper.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/api/src/main/java/com/destroystokyo/paper/exception/ServerEventException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerEventException.java deleted file mode 100644 index 410b24139..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerEventException.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.destroystokyo.paper.exception; - -import org.bukkit.event.Event; -import org.bukkit.event.Listener; -import org.bukkit.plugin.Plugin; - -import static com.google.common.base.Preconditions.*; - -/** - * 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/api/src/main/java/com/destroystokyo/paper/exception/ServerException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerException.java deleted file mode 100644 index c06ea3942..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerException.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.destroystokyo.paper.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/api/src/main/java/com/destroystokyo/paper/exception/ServerInternalException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerInternalException.java deleted file mode 100644 index e762ed0db..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerInternalException.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.destroystokyo.paper.exception; - -import org.bukkit.Bukkit; -import com.destroystokyo.paper.event.server.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/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginEnableDisableException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginEnableDisableException.java deleted file mode 100644 index f016ba3b1..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginEnableDisableException.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.destroystokyo.paper.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); - } -} \ No newline at end of file diff --git a/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginException.java deleted file mode 100644 index 6defac287..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginException.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.destroystokyo.paper.exception; - -import com.google.common.base.Preconditions; -import org.apache.commons.lang.Validate; -import org.bukkit.plugin.Plugin; - -import static com.google.common.base.Preconditions.*; - -/** - * 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/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginMessageException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginMessageException.java deleted file mode 100644 index 89e132525..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerPluginMessageException.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.destroystokyo.paper.exception; - -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -import static com.google.common.base.Preconditions.*; - -/** - * 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/api/src/main/java/com/destroystokyo/paper/exception/ServerSchedulerException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerSchedulerException.java deleted file mode 100644 index 2d0b2d4a9..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerSchedulerException.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.destroystokyo.paper.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/api/src/main/java/com/destroystokyo/paper/exception/ServerTabCompleteException.java b/api/src/main/java/com/destroystokyo/paper/exception/ServerTabCompleteException.java deleted file mode 100644 index 5582999fe..000000000 --- a/api/src/main/java/com/destroystokyo/paper/exception/ServerTabCompleteException.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.destroystokyo.paper.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/api/src/main/java/com/destroystokyo/paper/inventory/ItemStackRecipeChoice.java b/api/src/main/java/com/destroystokyo/paper/inventory/ItemStackRecipeChoice.java deleted file mode 100644 index 43e6576b1..000000000 --- a/api/src/main/java/com/destroystokyo/paper/inventory/ItemStackRecipeChoice.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.destroystokyo.paper.inventory; - -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; - -import java.util.ArrayList; -import java.util.List; - -/** - * Allows crafting Items that require full matching itemstacks to complete the recipe for custom items - * @deprecated Draft API - */ -@Deprecated -public class ItemStackRecipeChoice implements RecipeChoice { - - protected final List choices = new ArrayList<>(); - - public ItemStackRecipeChoice(ItemStack choices) { - this.choices.add(choices); - } - - public ItemStackRecipeChoice(List choices) { - this.choices.addAll(choices); - } - - @Override - public ItemStack getItemStack() { - return choices.isEmpty() ? null : choices.get(0); - } - - @Override - public RecipeChoice clone() { - try { - ItemStackRecipeChoice clone = (ItemStackRecipeChoice) super.clone(); - clone.choices.addAll(this.choices); - return clone; - } catch (CloneNotSupportedException ex) { - throw new AssertionError(ex); - } - } - - @Override - public boolean test(ItemStack itemStack) { - for (ItemStack stack : choices) { - if (stack.isSimilar(itemStack)) { - return true; - } - } - return false; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/inventory/meta/ArmorStandMeta.java b/api/src/main/java/com/destroystokyo/paper/inventory/meta/ArmorStandMeta.java deleted file mode 100644 index 7e4acfff1..000000000 --- a/api/src/main/java/com/destroystokyo/paper/inventory/meta/ArmorStandMeta.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.destroystokyo.paper.inventory.meta; - -import org.bukkit.inventory.meta.ItemMeta; - -public interface ArmorStandMeta extends ItemMeta { - - /** - * Gets whether the ArmorStand should be invisible when spawned - * - * @return true if this should be invisible - */ - boolean isInvisible(); - - /** - * Gets whether this ArmorStand should have no base plate when spawned - * - * @return true if it will not have a base plate - */ - boolean hasNoBasePlate(); - - /** - * Gets whether this ArmorStand should show arms when spawned - * - * @return true if it will show arms - */ - boolean shouldShowArms(); - - /** - * Gets whether this ArmorStand will be small when spawned - * - * @return true if it will be small - */ - boolean isSmall(); - - /** - * Gets whether this ArmorStand will be a marker when spawned - * The exact details of this flag are an implementation detail - * - * @return true if it will be a marker - */ - boolean isMarker(); - - /** - * Sets that this ArmorStand should be invisible when spawned - * - * @param invisible true if set invisible - */ - void setInvisible(boolean invisible); - - /** - * Sets that this ArmorStand should have no base plate when spawned - * - * @param noBasePlate true if no base plate - */ - void setNoBasePlate(boolean noBasePlate); - - /** - * Sets that this ArmorStand should show arms when spawned - * - * @param showArms true if show arms - */ - void setShowArms(boolean showArms); - - /** - * Sets that this ArmorStand should be small when spawned - * - * @param small true if small - */ - void setSmall(boolean small); - - /** - * Sets that this ArmorStand should be a marker when spawned - * The exact details of this flag are an implementation detail - * - * @param marker true if a marker - */ - void setMarker(boolean marker); -} diff --git a/api/src/main/java/com/destroystokyo/paper/loottable/LootableBlockInventory.java b/api/src/main/java/com/destroystokyo/paper/loottable/LootableBlockInventory.java deleted file mode 100644 index 92d7b853a..000000000 --- a/api/src/main/java/com/destroystokyo/paper/loottable/LootableBlockInventory.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; - -/** - * Represents an Inventory that can generate loot, such as Chests inside of Fortresses and Mineshafts - */ -public interface LootableBlockInventory extends LootableInventory { - - /** - * Gets the block that is lootable - * @return The Block - */ - @NotNull - Block getBlock(); -} diff --git a/api/src/main/java/com/destroystokyo/paper/loottable/LootableEntityInventory.java b/api/src/main/java/com/destroystokyo/paper/loottable/LootableEntityInventory.java deleted file mode 100644 index b387894fe..000000000 --- a/api/src/main/java/com/destroystokyo/paper/loottable/LootableEntityInventory.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; - -/** - * Represents an Inventory that can generate loot, such as Minecarts inside of Mineshafts - */ -public interface LootableEntityInventory extends LootableInventory { - - /** - * Gets the entity that is lootable - * @return The Entity - */ - @NotNull - Entity getEntity(); -} diff --git a/api/src/main/java/com/destroystokyo/paper/loottable/LootableInventory.java b/api/src/main/java/com/destroystokyo/paper/loottable/LootableInventory.java deleted file mode 100644 index 97815eeb2..000000000 --- a/api/src/main/java/com/destroystokyo/paper/loottable/LootableInventory.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import org.bukkit.entity.Player; -import org.bukkit.loot.Lootable; - -import java.util.UUID; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents an Inventory that contains a Loot Table associated to it that will - * automatically fill on first open. - * - * A new feature and API is provided to support automatically refreshing the contents - * of the inventory based on that Loot Table after a configurable amount of time has passed. - * - * The behavior of how the Inventory is filled based on the loot table may vary based - * on Minecraft versions and the Loot Table feature. - */ -public interface LootableInventory extends Lootable { - - /** - * Server owners have to enable whether or not an object in a world should refill - * - * @return If the world this inventory is currently in has Replenishable Lootables enabled - */ - boolean isRefillEnabled(); - - /** - * Whether or not this object has ever been filled - * @return Has ever been filled - */ - boolean hasBeenFilled(); - - /** - * Has this player ever looted this block - * @param player The player to check - * @return Whether or not this player has looted this block - */ - default boolean hasPlayerLooted(@NotNull Player player) { - return hasPlayerLooted(player.getUniqueId()); - } - - /** - * Has this player ever looted this block - * @param player The player to check - * @return Whether or not this player has looted this block - */ - boolean hasPlayerLooted(@NotNull UUID player); - - /** - * Gets the timestamp, in milliseconds, of when the player last looted this object - * - * @param player The player to check - * @return Timestamp last looted, or null if player has not looted this object - */ - @Nullable - default Long getLastLooted(@NotNull Player player) { - return getLastLooted(player.getUniqueId()); - } - - /** - * Gets the timestamp, in milliseconds, of when the player last looted this object - * - * @param player The player to check - * @return Timestamp last looted, or null if player has not looted this object - */ - @Nullable - Long getLastLooted(@NotNull UUID player); - - /** - * Change the state of whether or not a player has looted this block - * @param player The player to change state for - * @param looted true to add player to looted list, false to remove - * @return The previous state of whether the player had looted this or not - */ - default boolean setHasPlayerLooted(@NotNull Player player, boolean looted) { - return setHasPlayerLooted(player.getUniqueId(), looted); - } - - /** - * Change the state of whether or not a player has looted this block - * @param player The player to change state for - * @param looted true to add player to looted list, false to remove - * @return The previous state of whether the player had looted this or not - */ - boolean setHasPlayerLooted(@NotNull UUID player, boolean looted); - - /** - * Returns Whether or not this object has been filled and now has a pending refill - * @return Has pending refill - */ - boolean hasPendingRefill(); - - /** - * Gets the timestamp in milliseconds that the Lootable object was last refilled - * - * @return -1 if it was never refilled, or timestamp in milliseconds - */ - long getLastFilled(); - - /** - * Gets the timestamp in milliseconds that the Lootable object will refill - * - * @return -1 if it is not scheduled for refill, or timestamp in milliseconds - */ - long getNextRefill(); - - /** - * Sets the timestamp in milliseconds of the next refill for this object - * - * @param refillAt timestamp in milliseconds. -1 to clear next refill - * @return The previous scheduled time to refill, or -1 if was not scheduled - */ - long setNextRefill(long refillAt); -} diff --git a/api/src/main/java/com/destroystokyo/paper/loottable/LootableInventoryReplenishEvent.java b/api/src/main/java/com/destroystokyo/paper/loottable/LootableInventoryReplenishEvent.java deleted file mode 100644 index fd184f13f..000000000 --- a/api/src/main/java/com/destroystokyo/paper/loottable/LootableInventoryReplenishEvent.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public class LootableInventoryReplenishEvent extends PlayerEvent implements Cancellable { - @NotNull private final LootableInventory inventory; - - public LootableInventoryReplenishEvent(@NotNull Player player, @NotNull LootableInventory inventory) { - super(player); - this.inventory = inventory; - } - - @NotNull - public LootableInventory getInventory() { - return inventory; - } - - private static final HandlerList handlers = new HandlerList(); - - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - private boolean cancelled = false; - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/network/NetworkClient.java b/api/src/main/java/com/destroystokyo/paper/network/NetworkClient.java deleted file mode 100644 index 7b2af1bd7..000000000 --- a/api/src/main/java/com/destroystokyo/paper/network/NetworkClient.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.destroystokyo.paper.network; - -import java.net.InetSocketAddress; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a client connected to the server. - */ -public interface NetworkClient { - - /** - * Returns the socket address of the client. - * - * @return The client's socket address - */ - @NotNull - InetSocketAddress getAddress(); - - /** - * Returns the protocol version of the client. - * - * @return The client's protocol version, or {@code -1} if unknown - * @see List of protocol - * version numbers - */ - int getProtocolVersion(); - - /** - * Returns the virtual host the client is connected to. - * - *

The virtual host refers to the hostname/port the client used to - * connect to the server.

- * - * @return The client's virtual host, or {@code null} if unknown - */ - @Nullable - InetSocketAddress getVirtualHost(); - -} diff --git a/api/src/main/java/com/destroystokyo/paper/network/StatusClient.java b/api/src/main/java/com/destroystokyo/paper/network/StatusClient.java deleted file mode 100644 index ffda9f6a8..000000000 --- a/api/src/main/java/com/destroystokyo/paper/network/StatusClient.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.destroystokyo.paper.network; - -import com.destroystokyo.paper.event.server.PaperServerListPingEvent; - -/** - * Represents a client requesting the current status from the server (e.g. from - * the server list). - * - * @see PaperServerListPingEvent - */ -public interface StatusClient extends NetworkClient { - - /** - * Returns whether the client is using an older version that doesn't - * support all of the features in {@link PaperServerListPingEvent}. - * - *

For Vanilla, this returns {@code true} for all clients older than 1.7.

- * - * @return {@code true} if the client is using legacy ping - */ - default boolean isLegacy() { - return false; - } - -} diff --git a/api/src/main/java/com/destroystokyo/paper/profile/PlayerProfile.java b/api/src/main/java/com/destroystokyo/paper/profile/PlayerProfile.java deleted file mode 100644 index 476151d2a..000000000 --- a/api/src/main/java/com/destroystokyo/paper/profile/PlayerProfile.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.destroystokyo.paper.profile; - -import java.util.Collection; -import java.util.Set; -import java.util.UUID; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a players profile for the game, such as UUID, Name, and textures. - */ -public interface PlayerProfile { - - /** - * @return The players name, if set - */ - @Nullable - String getName(); - - /** - * Sets this profiles Name - * - * @param name The new Name - * @return The previous Name - */ - @NotNull - String setName(@Nullable String name); - - /** - * @return The players unique identifier, if set - */ - @Nullable UUID getId(); - - /** - * Sets this profiles UUID - * - * @param uuid The new UUID - * @return The previous UUID - */ - @Nullable - UUID setId(@Nullable UUID uuid); - - /** - * @return A Mutable set of this players properties, such as textures. - * Values specified here are subject to implementation details. - */ - @NotNull Set getProperties(); - - /** - * Check if the Profile has the specified property - * @param property Property name to check - * @return If the property is set - */ - boolean hasProperty(@Nullable String property); - - /** - * Sets a property. If the property already exists, the previous one will be replaced - * @param property Property to set. - */ - void setProperty(@NotNull ProfileProperty property); - - /** - * Sets multiple properties. If any of the set properties already exist, it will be replaced - * @param properties The properties to set - */ - void setProperties(@NotNull Collection properties); - - /** - * Removes a specific property from this profile - * @param property The property to remove - * @return If a property was removed - */ - boolean removeProperty(@Nullable String property); - - /** - * Removes a specific property from this profile - * @param property The property to remove - * @return If a property was removed - */ - default boolean removeProperty(@NotNull ProfileProperty property) { - return removeProperty(property.getName()); - } - - /** - * Removes all properties in the collection - * @param properties The properties to remove - * @return If any property was removed - */ - default boolean removeProperties(@NotNull Collection properties) { - boolean removed = false; - for (ProfileProperty property : properties) { - if (removeProperty(property)) { - removed = true; - } - } - return removed; - } - - /** - * Clears all properties on this profile - */ - void clearProperties(); - - /** - * @return If the profile is now complete (has UUID and Name) - */ - boolean isComplete(); - - /** - * Like {@link #complete(boolean)} but will try only from cache, and not make network calls - * Does not account for textures. - * - * @return If the profile is now complete (has UUID and Name) - */ - boolean completeFromCache(); - - /** - * If this profile is not complete, then make the API call to complete it. - * This is a blocking operation and should be done asynchronously. - * - * This will also complete textures. If you do not want to load textures, use {{@link #complete(boolean)}} - * @return If the profile is now complete (has UUID and Name) (if you get rate limited, this operation may fail) - */ - default boolean complete() { - return complete(true); - } - - /** - * If this profile is not complete, then make the API call to complete it. - * This is a blocking operation and should be done asynchronously. - * - * Optionally will also fill textures. - * @param textures controls if we should fill the profile with texture properties - * @return If the profile is now complete (has UUID and Name) (if you get rate limited, this operation may fail) - */ - boolean complete(boolean textures); - - /** - * Whether or not this Profile has textures associated to it - * @return If has a textures property - */ - default boolean hasTextures() { - return hasProperty("textures"); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/profile/ProfileProperty.java b/api/src/main/java/com/destroystokyo/paper/profile/ProfileProperty.java deleted file mode 100644 index 7b3b6ef53..000000000 --- a/api/src/main/java/com/destroystokyo/paper/profile/ProfileProperty.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.destroystokyo.paper.profile; - -import com.google.common.base.Preconditions; - -import java.util.Objects; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a property on a {@link PlayerProfile} - */ -public class ProfileProperty { - private final String name; - private final String value; - private final String signature; - - public ProfileProperty(@NotNull String name, @NotNull String value) { - this(name, value, null); - } - - public ProfileProperty(@NotNull String name, @NotNull String value, @Nullable String signature) { - this.name = Preconditions.checkNotNull(name, "ProfileProperty name can not be null"); - this.value = Preconditions.checkNotNull(value, "ProfileProperty value can not be null"); - this.signature = signature; - } - - /** - * @return The property name, ie "textures" - */ - @NotNull - public String getName() { - return name; - } - - /** - * @return The property value, likely to be base64 encoded - */ - @NotNull - public String getValue() { - return value; - } - - /** - * @return A signature from Mojang for signed properties - */ - @Nullable - public String getSignature() { - return signature; - } - - /** - * @return If this property has a signature or not - */ - public boolean isSigned() { - return this.signature != null; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ProfileProperty that = (ProfileProperty) o; - return Objects.equals(name, that.name) && - Objects.equals(value, that.value) && - Objects.equals(signature, that.signature); - } - - @Override - public int hashCode() { - return Objects.hash(name); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/util/SneakyThrow.java b/api/src/main/java/com/destroystokyo/paper/util/SneakyThrow.java deleted file mode 100644 index 9db0056ab..000000000 --- a/api/src/main/java/com/destroystokyo/paper/util/SneakyThrow.java +++ /dev/null @@ -1,16 +0,0 @@ -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/api/src/main/java/com/destroystokyo/paper/util/VersionFetcher.java b/api/src/main/java/com/destroystokyo/paper/util/VersionFetcher.java deleted file mode 100644 index 2a2651299..000000000 --- a/api/src/main/java/com/destroystokyo/paper/util/VersionFetcher.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.destroystokyo.paper.util; - -import org.bukkit.Bukkit; -import org.jetbrains.annotations.NotNull; - -public interface VersionFetcher { - /** - * Amount of time to cache results for in milliseconds - *

- * Negative values will never cache. - * - * @return cache time - */ - long getCacheTime(); - - /** - * Gets the version message to cache and show to command senders. Multiple messages can be sent using newlines (\n) - * in the string. The string will be split on these newlines and sent as individual messages. - *

- * NOTE: This is run in a new thread separate from that of the command processing thread - * - * @param serverVersion the current version of the server (will match {@link Bukkit#getVersion()}) - * @return the message to show when requesting a version - */ - @NotNull - String getVersionMessage(@NotNull String serverVersion); - - class DummyVersionFetcher implements VersionFetcher { - - @Override - public long getCacheTime() { - return -1; - } - - @NotNull - @Override - public String getVersionMessage(@NotNull String serverVersion) { - Bukkit.getLogger().warning("Version provider has not been set, cannot check for updates!"); - Bukkit.getLogger().info("Override the default implementation of org.bukkit.UnsafeValues#getVersionFetcher()"); - new Throwable().printStackTrace(); - return "Unable to check for updates. No version provider set."; - } - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/utils/CachedSizeConcurrentLinkedQueue.java b/api/src/main/java/com/destroystokyo/paper/utils/CachedSizeConcurrentLinkedQueue.java deleted file mode 100644 index 5bb677ce5..000000000 --- a/api/src/main/java/com/destroystokyo/paper/utils/CachedSizeConcurrentLinkedQueue.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.destroystokyo.paper.utils; - -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.LongAdder; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class CachedSizeConcurrentLinkedQueue extends ConcurrentLinkedQueue { - private final LongAdder cachedSize = new LongAdder(); - - @Override - public boolean add(@NotNull E e) { - boolean result = super.add(e); - if (result) { - cachedSize.increment(); - } - return result; - } - - @Nullable - @Override - public E poll() { - E result = super.poll(); - if (result != null) { - cachedSize.decrement(); - } - return result; - } - - @Override - public int size() { - return cachedSize.intValue(); - } -} diff --git a/api/src/main/java/com/destroystokyo/paper/utils/PaperPluginLogger.java b/api/src/main/java/com/destroystokyo/paper/utils/PaperPluginLogger.java deleted file mode 100644 index 76f2cb9cd..000000000 --- a/api/src/main/java/com/destroystokyo/paper/utils/PaperPluginLogger.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.destroystokyo.paper.utils; - -import org.bukkit.plugin.PluginDescriptionFile; - -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.Logger; -import org.jetbrains.annotations.NotNull; - -/** - * Prevents plugins (e.g. Essentials) from changing the parent of the plugin logger. - */ -public class PaperPluginLogger extends Logger { - - @NotNull - public static Logger getLogger(@NotNull PluginDescriptionFile description) { - Logger logger = new PaperPluginLogger(description); - if (!LogManager.getLogManager().addLogger(logger)) { - // Disable this if it's going to happen across reloads anyways... - //logger.log(Level.WARNING, "Could not insert plugin logger - one was already found: {}", LogManager.getLogManager().getLogger(this.getName())); - logger = LogManager.getLogManager().getLogger(description.getPrefix() != null ? description.getPrefix() : description.getName()); - } - - return logger; - } - - private PaperPluginLogger(@NotNull PluginDescriptionFile description) { - super(description.getPrefix() != null ? description.getPrefix() : description.getName(), null); - } - - @Override - public void setParent(@NotNull Logger parent) { - if (getParent() != null) { - warning("Ignoring attempt to change parent of plugin logger"); - } else { - this.log(Level.FINE, "Setting plugin logger parent to {0}", parent); - super.setParent(parent); - } - } - -} diff --git a/api/src/main/java/com/destroystokyo/paper/utils/UnsafeUtils.java b/api/src/main/java/com/destroystokyo/paper/utils/UnsafeUtils.java deleted file mode 100644 index 72e48e8ef..000000000 --- a/api/src/main/java/com/destroystokyo/paper/utils/UnsafeUtils.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.destroystokyo.paper.utils; - -import org.jetbrains.annotations.Nullable; -import sun.misc.Unsafe; - -import java.lang.reflect.Field; - -public class UnsafeUtils { - private UnsafeUtils() {} - - private static final Unsafe UNSAFE; - static { - Unsafe unsafe; - try { - Class c = Class.forName("sun.misc.Unsafe"); - Field f = c.getDeclaredField("theUnsafe"); - f.setAccessible(true); - unsafe = (Unsafe) f.get(null); - } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) { - unsafe = null; - } catch (IllegalAccessException e) { - throw new AssertionError(e); - } - UNSAFE = unsafe; - } - - public static boolean isUnsafeSupported() { - return UNSAFE != null; - } - - @Nullable - public static Unsafe getUnsafe() { - return UNSAFE; - } -} diff --git a/api/src/main/java/org/bukkit/Achievement.java b/api/src/main/java/org/bukkit/Achievement.java deleted file mode 100644 index 0080e0fea..000000000 --- a/api/src/main/java/org/bukkit/Achievement.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.bukkit; - -import org.jetbrains.annotations.Nullable; - -/** - * Represents an achievement, which may be given to players. - * @deprecated future versions of Minecraft do not have achievements - */ -@Deprecated -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; - - private Achievement() { - parent = null; - } - - private Achievement(/*@Nullable*/ 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 - */ - @Nullable - public Achievement getParent() { - return parent; - } -} diff --git a/api/src/main/java/org/bukkit/Art.java b/api/src/main/java/org/bukkit/Art.java deleted file mode 100644 index e7563acf4..000000000 --- a/api/src/main/java/org/bukkit/Art.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.HashMap; -import org.apache.commons.lang.Validate; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents the art on a painting - */ -public enum Art implements Keyed { - 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), - BURNING_SKULL(23, 4, 4), - SKELETON(24, 4, 3), - DONKEY_KONG(25, 4, 3); - - private final int id, width, height; - private final NamespacedKey key; - private static final HashMap BY_NAME = Maps.newHashMap(); - private static final HashMap BY_ID = Maps.newHashMap(); - - private Art(int id, int width, int height) { - this.id = id; - this.width = width; - this.height = height; - this.key = NamespacedKey.minecraft(name().toLowerCase(java.util.Locale.ENGLISH)); - } - - /** - * 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; - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - - /** - * Get a painting by its numeric ID - * - * @param id The ID - * @return The painting - * @deprecated Magic value - */ - @Deprecated - @Nullable - 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 - */ - @Nullable - public static Art getByName(@NotNull String name) { - Validate.notNull(name, "Name cannot be null"); - - return BY_NAME.get(name.toLowerCase(java.util.Locale.ENGLISH)); - } - - static { - for (Art art : values()) { - BY_ID.put(art.id, art); - BY_NAME.put(art.toString().toLowerCase(java.util.Locale.ENGLISH), art); - } - } -} diff --git a/api/src/main/java/org/bukkit/Axis.java b/api/src/main/java/org/bukkit/Axis.java deleted file mode 100644 index fd86d68d1..000000000 --- a/api/src/main/java/org/bukkit/Axis.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit; - -/** - * Represents a mutually perpendicular axis in 3D Cartesian coordinates. In - * Minecraft the x, z axes lie in the horizontal plane, whilst the y axis points - * upwards. - */ -public enum Axis { - /** - * The x axis. - */ - X, - /** - * The y axis. - */ - Y, - /** - * The z axis. - */ - Z; -} diff --git a/api/src/main/java/org/bukkit/BanEntry.java b/api/src/main/java/org/bukkit/BanEntry.java deleted file mode 100644 index 2cf11ca4f..000000000 --- a/api/src/main/java/org/bukkit/BanEntry.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.bukkit; - -import java.util.Date; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @NotNull - public String getTarget(); - - /** - * Gets the date this ban entry was created. - * - * @return the creation date - */ - @NotNull - public Date getCreated(); - - /** - * Sets the date this ban entry was created. - * - * @param created the new created date, cannot be null - * @see #save() saving changes - */ - public void setCreated(@NotNull 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 - */ - @NotNull - public 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 - */ - public void setSource(@NotNull String source); - - /** - * Gets the date this ban expires on, or null for no defined end date. - * - * @return the expiration date - */ - @Nullable - public 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 - */ - public void setExpiration(@Nullable Date expiration); - - /** - * Gets the reason for this ban. - * - * @return the ban reason, or null if not set - */ - @Nullable - public 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 - */ - public void setReason(@Nullable 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. - */ - public void save(); -} diff --git a/api/src/main/java/org/bukkit/BanList.java b/api/src/main/java/org/bukkit/BanList.java deleted file mode 100644 index 96ef22fe8..000000000 --- a/api/src/main/java/org/bukkit/BanList.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bukkit; - -import java.util.Date; -import java.util.Set; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * A ban list, containing bans of some {@link Type}. - */ -public interface BanList { - - /** - * Represents a ban-type that a {@link BanList} may track. - */ - public 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 - */ - @Nullable - public BanEntry getBanEntry(@NotNull 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 - */ - @Nullable - public BanEntry addBan(@NotNull String target, @Nullable String reason, @Nullable Date expires, @Nullable String source); - - /** - * Gets a set containing every {@link BanEntry} in this list. - * - * @return an immutable set containing every entry tracked by this list - */ - @NotNull - public 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 - */ - public boolean isBanned(@NotNull String target); - - /** - * Removes the specified target from this list, therefore indicating a - * "not banned" status. - * - * @param target the target to remove from this list - */ - public void pardon(@NotNull String target); -} diff --git a/api/src/main/java/org/bukkit/BlockChangeDelegate.java b/api/src/main/java/org/bukkit/BlockChangeDelegate.java deleted file mode 100644 index 41eff1a31..000000000 --- a/api/src/main/java/org/bukkit/BlockChangeDelegate.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit; - -import org.bukkit.block.data.BlockData; -import org.jetbrains.annotations.NotNull; - -/** - * 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 data at the specified coordinates. - * - * @param x X coordinate - * @param y Y coordinate - * @param z Z coordinate - * @param blockData Block data - * @return true if the block was set successfully - */ - public boolean setBlockData(int x, int y, int z, @NotNull BlockData blockData); - - /** - * Get the block data at the location. - * - * @param x X coordinate - * @param y Y coordinate - * @param z Z coordinate - * @return The block data - */ - @NotNull - public BlockData getBlockData(int x, int y, int z); - - /** - * Gets the height of the world. - * - * @return Height of the world - */ - public 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. - */ - public boolean isEmpty(int x, int y, int z); -} diff --git a/api/src/main/java/org/bukkit/Bukkit.java b/api/src/main/java/org/bukkit/Bukkit.java deleted file mode 100644 index 231bc6e31..000000000 --- a/api/src/main/java/org/bukkit/Bukkit.java +++ /dev/null @@ -1,1613 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.ImmutableList; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.function.Consumer; -import java.util.logging.Logger; -import org.bukkit.Warning.WarningState; -import org.bukkit.advancement.Advancement; -import org.bukkit.block.data.BlockData; -import org.bukkit.boss.BarColor; -import org.bukkit.boss.BarFlag; -import org.bukkit.boss.BarStyle; -import org.bukkit.boss.BossBar; -import org.bukkit.boss.KeyedBossBar; -import org.bukkit.command.CommandException; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.command.PluginCommand; -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.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemFactory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.Recipe; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.loot.LootTable; -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 org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @NotNull - 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(@NotNull 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() + " (Implementing API version " + getBukkitVersion() + ")"); - } - - /** - * Gets the name of this server implementation. - * - * @return name of this server implementation - */ - @NotNull - public static String getName() { - return server.getName(); - } - - /** - * Gets the version string of this server implementation. - * - * @return version of this server implementation - */ - @NotNull - public static String getVersion() { - return server.getVersion(); - } - - /** - * Gets the Bukkit version that this server is running. - * - * @return version of Bukkit - */ - @NotNull - public static String getBukkitVersion() { - return server.getBukkitVersion(); - } - - /** - * 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. - */ - @NotNull - 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(); - } - - /** - * 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 - */ - @NotNull - public static String getIp() { - return server.getIp(); - } - - /** - * Get world type (level-type setting) for default world. - * - * @return the value of level-type (e.g. DEFAULT, FLAT, DEFAULT_1_1) - */ - @NotNull - 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 - */ - @NotNull - 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(java.lang.String, - * java.lang.String)} to {@link Server#BROADCAST_CHANNEL_USERS} - * - * @param message the message - * @return the number of players - */ - public static int broadcastMessage(@NotNull String message) { - return server.broadcastMessage(message); - } - - // Paper start - /** - * Sends the component to all online players. - * - * @param component the component to send - */ - public static void broadcast(@NotNull net.md_5.bungee.api.chat.BaseComponent component) { - server.broadcast(component); - } - - /** - * Sends an array of components as a single message to all online players. - * - * @param components the components to send - */ - public static void broadcast(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @Nullable - public static Player getPlayer(@NotNull 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 - */ - @Nullable - public static Player getPlayerExact(@NotNull 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 - */ - @NotNull - public static List matchPlayer(@NotNull 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 - */ - @Nullable - public static Player getPlayer(@NotNull UUID id) { - return server.getPlayer(id); - } - - // Paper start - /** - * Gets the unique ID of the player currently known as the specified player name - * In Offline Mode, will return an Offline UUID - * - * @param playerName the player name to look up the unique ID for - * @return A UUID, or null if that player name is not registered with Minecraft and the server is in online mode - */ - @Nullable - public static UUID getPlayerUniqueId(@NotNull String playerName) { - return server.getPlayerUniqueId(playerName); - } - // Paper end - - /** - * Gets the plugin manager for interfacing with plugins. - * - * @return a plugin manager for this Server instance - */ - @NotNull - public static PluginManager getPluginManager() { - return server.getPluginManager(); - } - - /** - * Gets the scheduler for managing scheduled events. - * - * @return a scheduling service for this server - */ - @NotNull - public static BukkitScheduler getScheduler() { - return server.getScheduler(); - } - - /** - * Gets a services manager. - * - * @return s services manager - */ - @NotNull - public static ServicesManager getServicesManager() { - return server.getServicesManager(); - } - - /** - * Gets a list of all worlds on this server. - * - * @return a list of worlds - */ - @NotNull - 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 - */ - @Nullable - public static World createWorld(@NotNull 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(@NotNull 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(@NotNull 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 - */ - @Nullable - public static World getWorld(@NotNull 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 - */ - @Nullable - public static World getWorld(@NotNull 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 - @Nullable - public static MapView getMap(int 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 - */ - @NotNull - public static MapView createMap(@NotNull World world) { - return server.createMap(world); - } - - /** - * Create a new explorer map targeting the closest nearby structure of a - * given {@link StructureType}. - *
- * This method uses implementation default values for radius and - * findUnexplored (usually 100, true). - * - * @param world the world the map will belong to - * @param location the origin location to find the nearest structure - * @param structureType the type of structure to find - * @return a newly created item stack - * - * @see World#locateNearestStructure(org.bukkit.Location, - * org.bukkit.StructureType, int, boolean) - */ - @NotNull - public static ItemStack createExplorerMap(@NotNull World world, @NotNull Location location, @NotNull StructureType structureType) { - return server.createExplorerMap(world, location, structureType); - } - - /** - * Create a new explorer map targeting the closest nearby structure of a - * given {@link StructureType}. - *
- * This method uses implementation default values for radius and - * findUnexplored (usually 100, true). - * - * @param world the world the map will belong to - * @param location the origin location to find the nearest structure - * @param structureType the type of structure to find - * @param radius radius to search, see World#locateNearestStructure for more - * information - * @param findUnexplored whether to find unexplored structures - * @return the newly created item stack - * - * @see World#locateNearestStructure(org.bukkit.Location, - * org.bukkit.StructureType, int, boolean) - */ - @NotNull - public static ItemStack createExplorerMap(@NotNull World world, @NotNull Location location, @NotNull StructureType structureType, int radius, boolean findUnexplored) { - return server.createExplorerMap(world, location, structureType, radius, findUnexplored); - } - - /** - * Reloads the server, refreshing settings and plugin information. - */ - public static void reload() { - server.reload(); - } - - /** - * Reload only the Minecraft data for the server. This includes custom - * advancements and loot tables. - */ - public static void reloadData() { - server.reloadData(); - } - - /** - * Returns the primary logger associated with this server instance. - * - * @return Logger associated with this server - */ - @NotNull - 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 - */ - @Nullable - public static PluginCommand getPluginCommand(@NotNull 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(@NotNull CommandSender sender, @NotNull String commandLine) throws CommandException { - return server.dispatchCommand(sender, commandLine); - } - - /** - * 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 - */ - @Contract("null -> false") - public static boolean addRecipe(@Nullable 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 - */ - @NotNull - public static List getRecipesFor(@NotNull ItemStack result) { - return server.getRecipesFor(result); - } - - /** - * Get an iterator through the list of crafting recipes. - * - * @return an iterator - */ - @NotNull - 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 - */ - @NotNull - 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(); - } - - /** - * 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(@NotNull String message, @NotNull 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(java.util.UUID) - */ - @Deprecated - @NotNull - public static OfflinePlayer getOfflinePlayer(@NotNull 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 - */ - @NotNull - public static OfflinePlayer getOfflinePlayer(@NotNull UUID id) { - return server.getOfflinePlayer(id); - } - - /** - * Gets a set containing all current IPs that are banned. - * - * @return a set containing banned IP addresses - */ - @NotNull - 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(@NotNull String address) { - server.banIP(address); - } - - /** - * Unbans the specified address from the server. - * - * @param address the IP address to unban - */ - public static void unbanIP(@NotNull String address) { - server.unbanIP(address); - } - - /** - * Gets a set containing all banned players. - * - * @return a set containing banned players - */ - @NotNull - 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 - */ - @NotNull - public static BanList getBanList(@NotNull BanList.Type type) { - return server.getBanList(type); - } - - /** - * Gets a set containing all player operators. - * - * @return a set containing player operators - */ - @NotNull - public static Set getOperators() { - return server.getOperators(); - } - - /** - * Gets the default {@link GameMode} for new players. - * - * @return the default game mode - */ - @NotNull - 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(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - public static File getWorldContainer() { - return server.getWorldContainer(); - } - - /** - * Gets every player that has ever played on this server. - * - * @return an array containing all previous players - */ - @NotNull - public static OfflinePlayer[] getOfflinePlayers() { - return server.getOfflinePlayers(); - } - - /** - * Gets the {@link Messenger} responsible for this server. - * - * @return messenger responsible for this server - */ - @NotNull - public static Messenger getMessenger() { - return server.getMessenger(); - } - - /** - * Gets the {@link HelpMap} providing help topics for this server. - * - * @return a help map for this server - */ - @NotNull - public static HelpMap getHelpMap() { - return server.getHelpMap(); - } - - /** - * Creates an empty inventory with 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. - *
- * {@link InventoryType#WORKBENCH} will not process crafting recipes if - * created with this method. Use - * {@link Player#openWorkbench(Location, boolean)} instead. - *
- * {@link InventoryType#ENCHANTING} will not process {@link ItemStack}s - * for possible enchanting results. Use - * {@link Player#openEnchanting(Location, boolean)} instead. - * - * @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 - * @throws IllegalArgumentException if the {@link InventoryType} cannot be - * viewed. - * - * @see InventoryType#isCreatable() - */ - @NotNull - public static Inventory createInventory(@Nullable InventoryHolder owner, @NotNull 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. - *
- * {@link InventoryType#WORKBENCH} will not process crafting recipes if - * created with this method. Use - * {@link Player#openWorkbench(Location, boolean)} instead. - *
- * {@link InventoryType#ENCHANTING} will not process {@link ItemStack}s - * for possible enchanting results. Use - * {@link Player#openEnchanting(Location, boolean)} instead. - * - * @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. - * @throws IllegalArgumentException if the {@link InventoryType} cannot be - * viewed. - * - * @see InventoryType#isCreatable() - */ - @NotNull - public static Inventory createInventory(@Nullable InventoryHolder owner, @NotNull InventoryType type, @NotNull 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 - */ - @NotNull - public static Inventory createInventory(@Nullable 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 - */ - @NotNull - public static Inventory createInventory(@Nullable InventoryHolder owner, int size, @NotNull String title) throws IllegalArgumentException { - return server.createInventory(owner, size, title); - } - - /** - * Creates an empty merchant. - * - * @param title the title of the corresponding merchant inventory, displayed - * when the merchant inventory is viewed - * @return a new merchant - */ - @NotNull - public static Merchant createMerchant(@Nullable String title) { - return server.createMerchant(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 - */ - @NotNull - public static String getMotd() { - return server.getMotd(); - } - - /** - * Gets the default message that is displayed when the server is stopped. - * - * @return the shutdown message - */ - @Nullable - public static String getShutdownMessage() { - return server.getShutdownMessage(); - } - - /** - * Gets the current warning state for the server. - * - * @return the configured warning state - */ - @NotNull - public static WarningState getWarningState() { - return server.getWarningState(); - } - - /** - * Gets the instance of the item factory (for {@link ItemMeta}). - * - * @return the item factory - * @see ItemFactory - */ - @NotNull - 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. - */ - @NotNull // Paper - 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 - */ - @Nullable - 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)} - */ - @NotNull - public static CachedServerIcon loadServerIcon(@NotNull 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)} - */ - @NotNull - public static CachedServerIcon loadServerIcon(@NotNull 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(org.bukkit.World, java.util.Random, int, int, org.bukkit.generator.ChunkGenerator.BiomeGrid)} - * - * @param world the world to create the ChunkData for - * @return a new ChunkData for the world - * - */ - @NotNull - public static ChunkGenerator.ChunkData createChunkData(@NotNull World world) { - return server.createChunkData(world); - } - - /** - * Creates a boss bar instance to display to players. The progress - * defaults to 1.0 - * - * @param title the title of the boss bar - * @param color the color of the boss bar - * @param style the style of the boss bar - * @param flags an optional list of flags to set on the boss bar - * @return the created boss bar - */ - @NotNull - public static BossBar createBossBar(@Nullable String title, @NotNull BarColor color, @NotNull BarStyle style, @NotNull BarFlag... flags) { - return server.createBossBar(title, color, style, flags); - } - - /** - * Creates a boss bar instance to display to players. The progress defaults - * to 1.0. - *
- * This instance is added to the persistent storage of the server and will - * be editable by commands and restored after restart. - * - * @param key the key of the boss bar that is used to access the boss bar - * @param title the title of the boss bar - * @param color the color of the boss bar - * @param style the style of the boss bar - * @param flags an optional list of flags to set on the boss bar - * @return the created boss bar - */ - @NotNull - public static KeyedBossBar createBossBar(@NotNull NamespacedKey key, @Nullable String title, @NotNull BarColor color, @NotNull BarStyle style, @NotNull BarFlag... flags) { - return server.createBossBar(key, title, color, style, flags); - } - - /** - * Gets an unmodifiable iterator through all persistent bossbars. - *

    - *
  • not bound to a {@link org.bukkit.entity.Boss}
  • - *
  • - * not created using - * {@link #createBossBar(String, BarColor, BarStyle, BarFlag...)} - *
  • - *
- * - * e.g. bossbars created using the bossbar command - * - * @return a bossbar iterator - */ - @NotNull - public static Iterator getBossBars() { - return server.getBossBars(); - } - - /** - * Gets the {@link KeyedBossBar} specified by this key. - *
    - *
  • not bound to a {@link org.bukkit.entity.Boss}
  • - *
  • - * not created using - * {@link #createBossBar(String, BarColor, BarStyle, BarFlag...)} - *
  • - *
- * - * e.g. bossbars created using the bossbar command - * - * @param key unique bossbar key - * @return bossbar or null if not exists - */ - @Nullable - public static KeyedBossBar getBossBar(@NotNull NamespacedKey key) { - return server.getBossBar(key); - } - - /** - * Removes a {@link KeyedBossBar} specified by this key. - *
    - *
  • not bound to a {@link org.bukkit.entity.Boss}
  • - *
  • - * not created using - * {@link #createBossBar(String, BarColor, BarStyle, BarFlag...)} - *
  • - *
- * - * e.g. bossbars created using the bossbar command - * - * @param key unique bossbar key - * @return true if removal succeeded or false - */ - public static boolean removeBossBar(@NotNull NamespacedKey key) { - return server.removeBossBar(key); - } - - /** - * Gets an entity on the server by its UUID - * - * @param uuid the UUID of the entity - * @return the entity with the given UUID, or null if it isn't found - */ - @Nullable - public static Entity getEntity(@NotNull UUID uuid) { - return server.getEntity(uuid); - } - - // Paper start - /** - * Gets the current server TPS - * @return current server TPS (1m, 5m, 15m in Paper-Server) - */ - @NotNull - public static double[] getTPS() { - return server.getTPS(); - } - // Paper end - - /** - * Get the advancement specified by this key. - * - * @param key unique advancement key - * @return advancement or null if not exists - */ - @Nullable - public static Advancement getAdvancement(@NotNull NamespacedKey key) { - return server.getAdvancement(key); - } - - /** - * Get an iterator through all advancements. Advancements cannot be removed - * from this iterator, - * - * @return an advancement iterator - */ - @NotNull - public static Iterator advancementIterator() { - return server.advancementIterator(); - } - - /** - * Creates a new {@link BlockData} instance for the specified Material, with - * all properties initialized to unspecified defaults. - * - * @param material the material - * @return new data instance - */ - @NotNull - public static BlockData createBlockData(@NotNull Material material) { - return server.createBlockData(material); - } - - /** - * Creates a new {@link BlockData} instance for the specified Material, with - * all properties initialized to unspecified defaults. - * - * @param material the material - * @param consumer consumer to run on new instance before returning - * @return new data instance - */ - @NotNull - public static BlockData createBlockData(@NotNull Material material, @Nullable Consumer consumer) { - return server.createBlockData(material, consumer); - } - - /** - * Creates a new {@link BlockData} instance with material and properties - * parsed from provided data. - * - * @param data data string - * @return new data instance - * @throws IllegalArgumentException if the specified data is not valid - */ - @NotNull - public static BlockData createBlockData(@NotNull String data) throws IllegalArgumentException { - return server.createBlockData(data); - } - - /** - * Creates a new {@link BlockData} instance for the specified Material, with - * all properties initialized to unspecified defaults, except for those - * provided in data. - * - * @param material the material - * @param data data string - * @return new data instance - * @throws IllegalArgumentException if the specified data is not valid - */ - @NotNull - @Contract("null, null -> fail") - public static BlockData createBlockData(@Nullable Material material, @Nullable String data) throws IllegalArgumentException { - return server.createBlockData(material, data); - } - - /** - * Gets a tag which has already been defined within the server. Plugins are - * suggested to use the concrete tags in {@link Tag} rather than this method - * which makes no guarantees about which tags are available, and may also be - * less performant due to lack of caching. - *
- * Tags will be searched for in an implementation specific manner, but a - * path consisting of namespace/tags/registry/key is expected. - *
- * Server implementations are allowed to handle only the registries - * indicated in {@link Tag}. - * - * @param type of the tag - * @param registry the tag registry to look at - * @param tag the name of the tag - * @param clazz the class of the tag entries - * @return the tag or null - */ - @UndefinedNullability // Paper - public static Tag getTag(@NotNull String registry, @NotNull NamespacedKey tag, @NotNull Class clazz) { - return server.getTag(registry, tag, clazz); - } - - /** - * Gets a all tags which have been defined within the server. - *
- * Server implementations are allowed to handle only the registries - * indicated in {@link Tag}. - *
- * No guarantees are made about the mutability of the returned iterator. - * - * @param type of the tag - * @param registry the tag registry to look at - * @param clazz the class of the tag entries - * @return all defined tags - */ - @NotNull - public static Iterable> getTags(@NotNull String registry, @NotNull Class clazz) { - return server.getTags(registry, clazz); - } - - /** - * Gets the specified {@link LootTable}. - * - * @param key the name of the LootTable - * @return the LootTable, or null if no LootTable is found with that name - */ - @Nullable - public static LootTable getLootTable(@NotNull NamespacedKey key) { - return server.getLootTable(key); - } - - /** - * Selects entities using the given Vanilla selector. - *
- * No guarantees are made about the selector format, other than they match - * the Vanilla format for the active Minecraft version. - *
- * Usually a selector will start with '@', unless selecting a Player in - * which case it may simply be the Player's name or UUID. - *
- * Note that in Vanilla, elevated permissions are usually required to use - * '@' selectors, but this method should not check such permissions from the - * sender. - * - * @param sender the sender to execute as, must be provided - * @param selector the selection string - * @return a list of the selected entities. The list will not be null, but - * no further guarantees are made. - * @throws IllegalArgumentException if the selector is malformed in any way - * or a parameter is null - */ - @NotNull - public static List selectEntities(@NotNull CommandSender sender, @NotNull String selector) throws IllegalArgumentException { - return server.selectEntities(sender, selector); - } - - /** - * @see UnsafeValues - * @return the unsafe values instance - */ - @Deprecated - @NotNull - public static UnsafeValues getUnsafe() { - return server.getUnsafe(); - } - - - // Paper start - /** - * Gets the active {@link org.bukkit.command.CommandMap} - * - * @return the active command map - */ - @NotNull - public static org.bukkit.command.CommandMap getCommandMap() { - return server.getCommandMap(); - } - - /** - * Reload the Permissions in permissions.yml - */ - public static void reloadPermissions() { - server.reloadPermissions(); - } - - /** - * Reload the Command Aliases in commands.yml - * - * @return Whether the reload was successful - */ - public static boolean reloadCommandAliases() { - return server.reloadCommandAliases(); - } - - /** - * Checks if player names should be suggested when a command returns {@code null} as - * their tab completion result. - * - * @return true if player names should be suggested - */ - public static boolean suggestPlayerNamesWhenNullTabCompletions() { - return server.suggestPlayerNamesWhenNullTabCompletions(); - } - - /** - * - * @return the default no permission message used on the server - */ - @NotNull - public static String getPermissionMessage() { - return server.getPermissionMessage(); - } - - /** - * Creates a PlayerProfile for the specified uuid, with name as null - * @param uuid UUID to create profile for - * @return A PlayerProfile object - */ - @NotNull - public static com.destroystokyo.paper.profile.PlayerProfile createProfile(@NotNull UUID uuid) { - return server.createProfile(uuid); - } - - /** - * Creates a PlayerProfile for the specified name, with UUID as null - * @param name Name to create profile for - * @return A PlayerProfile object - */ - @NotNull - public static com.destroystokyo.paper.profile.PlayerProfile createProfile(@NotNull String name) { - return server.createProfile(name); - } - - /** - * Creates a PlayerProfile for the specified name/uuid - * - * Both UUID and Name can not be null at same time. One must be supplied. - * - * @param uuid UUID to create profile for - * @param name Name to create profile for - * @return A PlayerProfile object - */ - @NotNull - public static com.destroystokyo.paper.profile.PlayerProfile createProfile(@Nullable UUID uuid, @Nullable String name) { - return server.createProfile(uuid, name); - } - - public static int getCurrentTick() { - return server.getCurrentTick(); - } - // Paper end - - @NotNull - public static Server.Spigot spigot() - { - return server.spigot(); - } -} diff --git a/api/src/main/java/org/bukkit/ChatColor.java b/api/src/main/java/org/bukkit/ChatColor.java deleted file mode 100644 index b2c82940c..000000000 --- a/api/src/main/java/org/bukkit/ChatColor.java +++ /dev/null @@ -1,406 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import java.util.regex.Pattern; -import org.apache.commons.lang.Validate; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * All supported color values for chat - */ -public enum ChatColor { - /** - * Represents black - */ - BLACK('0', 0x00) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.BLACK; - } - }, - /** - * Represents dark blue - */ - DARK_BLUE('1', 0x1) { - @NotNull - @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) { - @NotNull - @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) { - @NotNull - @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) { - @NotNull - @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) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.DARK_PURPLE; - } - }, - /** - * Represents gold - */ - GOLD('6', 0x6) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.GOLD; - } - }, - /** - * Represents gray - */ - GRAY('7', 0x7) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.GRAY; - } - }, - /** - * Represents dark gray - */ - DARK_GRAY('8', 0x8) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.DARK_GRAY; - } - }, - /** - * Represents blue - */ - BLUE('9', 0x9) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.BLUE; - } - }, - /** - * Represents green - */ - GREEN('a', 0xA) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.GREEN; - } - }, - /** - * Represents aqua - */ - AQUA('b', 0xB) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.AQUA; - } - }, - /** - * Represents red - */ - RED('c', 0xC) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.RED; - } - }, - /** - * Represents light purple - */ - LIGHT_PURPLE('d', 0xD) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.LIGHT_PURPLE; - } - }, - /** - * Represents yellow - */ - YELLOW('e', 0xE) { - @NotNull - @Override - public net.md_5.bungee.api.ChatColor asBungee() { - return net.md_5.bungee.api.ChatColor.YELLOW; - } - }, - /** - * Represents white - */ - WHITE('f', 0xF) { - @NotNull - @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) { - @NotNull - @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) { - @NotNull - @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) { - @NotNull - @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) { - @NotNull - @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) { - @NotNull - @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) { - @NotNull - @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 static final Map BY_ID = Maps.newHashMap(); - private static final Map BY_CHAR = Maps.newHashMap(); - - private ChatColor(char code, int intCode) { - this(code, intCode, false); - } - - private 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}); - } - - @NotNull - 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; - } - - @NotNull - @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 org.bukkit.ChatColor} with the given code, - * or null if it doesn't exist - */ - @Nullable - 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 org.bukkit.ChatColor} with the given code, - * or null if it doesn't exist - */ - @Nullable - public static ChatColor getByChar(@NotNull 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 - */ - @Contract("!null -> !null; null -> null") - @Nullable - public static String stripColor(@Nullable 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. - */ - @NotNull - public static String translateAlternateColorCodes(char altColorChar, @NotNull String textToTranslate) { - Validate.notNull(textToTranslate, "Cannot translate null text"); - - 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. - */ - @NotNull - public static String getLastColors(@NotNull String input) { - Validate.notNull(input, "Cannot get last colors from null text"); - - 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/api/src/main/java/org/bukkit/Chunk.java b/api/src/main/java/org/bukkit/Chunk.java deleted file mode 100644 index 7909caef7..000000000 --- a/api/src/main/java/org/bukkit/Chunk.java +++ /dev/null @@ -1,265 +0,0 @@ -package org.bukkit; - -import java.util.Collection; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Entity; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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(); - - // Paper start - /** - * @return The Chunks X and Z coordinates packed into a long - */ - default long getChunkKey() { - return getChunkKey(getX(), getZ()); - } - - /** - * @param loc Location to get chunk key - * @return Location's chunk coordinates packed into a long - */ - static long getChunkKey(@NotNull Location loc) { - return getChunkKey((int) Math.floor(loc.getX()) << 4, (int) Math.floor(loc.getZ()) << 4); - } - - /** - * @param x X Coordinate - * @param z Z Coordinate - * @return Chunk coordinates packed into a long - */ - static long getChunkKey(int x, int z) { - return (long) x & 0xffffffffL | ((long) z & 0xffffffffL) << 32; - } - // Paper end - - /** - * Gets the world containing this chunk - * - * @return Parent World - */ - @NotNull - World getWorld(); - - /** - * Gets a block from this chunk - * - * @param x 0-15 - * @param y 0-255 - * @param z 0-15 - * @return the Block - */ - @NotNull - Block getBlock(int x, int y, int z); - - /** - * Capture thread-safe read-only snapshot of chunk data - * - * @return ChunkSnapshot - */ - @NotNull - 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 - */ - @NotNull - ChunkSnapshot getChunkSnapshot(boolean includeMaxblocky, boolean includeBiome, boolean includeBiomeTempRain); - - /** - * Get a list of all entities in the chunk. - * - * @return The entities. - */ - @NotNull - Entity[] getEntities(); - - // Paper start - /** - * Get a list of all tile entities in the chunk. - * - * @return The tile entities. - */ - @NotNull - default BlockState[] getTileEntities() { - return getTileEntities(true); - } - - /** - * Get a list of all tile entities in the chunk. - * - * @param useSnapshot Take snapshots or direct references - * @return The tile entities. - */ - @NotNull - BlockState[] getTileEntities(boolean useSnapshot); - // Paper end - - /** - * 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 - * @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(); - - /** - * Checks if this chunk can spawn slimes without being a swamp biome. - * - * @return true if slimes are able to spawn in this chunk - */ - boolean isSlimeChunk(); - - /** - * Gets whether the chunk at the specified chunk coordinates is force - * loaded. - *

- * A force loaded chunk will not be unloaded due to lack of player activity. - * - * @return force load status - * @see World#isChunkForceLoaded(int, int) - */ - boolean isForceLoaded(); - - /** - * Sets whether the chunk at the specified chunk coordinates is force - * loaded. - *

- * A force loaded chunk will not be unloaded due to lack of player activity. - * - * @param forced force load status - * @see World#setChunkForceLoaded(int, int, boolean) - */ - void setForceLoaded(boolean forced); - - /** - * Adds a plugin ticket for this chunk, loading this chunk if it is not - * already loaded. - *

- * A plugin ticket will prevent a chunk from unloading until it is - * explicitly removed. A plugin instance may only have one ticket per chunk, - * but each chunk can have multiple plugin tickets. - *

- * - * @param plugin Plugin which owns the ticket - * @return {@code true} if a plugin ticket was added, {@code false} if the - * ticket already exists for the plugin - * @throws IllegalStateException If the specified plugin is not enabled - * @see World#addPluginChunkTicket(int, int, Plugin) - */ - boolean addPluginChunkTicket(@NotNull Plugin plugin); - - /** - * Removes the specified plugin's ticket for this chunk - *

- * A plugin ticket will prevent a chunk from unloading until it is - * explicitly removed. A plugin instance may only have one ticket per chunk, - * but each chunk can have multiple plugin tickets. - *

- * - * @param plugin Plugin which owns the ticket - * @return {@code true} if the plugin ticket was removed, {@code false} if - * there is no plugin ticket for the chunk - * @see World#removePluginChunkTicket(int, int, Plugin) - */ - boolean removePluginChunkTicket(@NotNull Plugin plugin); - - /** - * Retrieves a collection specifying which plugins have tickets for this - * chunk. This collection is not updated when plugin tickets are added or - * removed to this chunk. - *

- * A plugin ticket will prevent a chunk from unloading until it is - * explicitly removed. A plugin instance may only have one ticket per chunk, - * but each chunk can have multiple plugin tickets. - *

- * - * @return unmodifiable collection containing which plugins have tickets for - * this chunk - * @see World#getPluginChunkTickets(int, int) - */ - @NotNull - Collection getPluginChunkTickets(); - - /** - * Gets the amount of time in ticks that this chunk has been inhabited. - * - * Note that the time is incremented once per tick per player in the chunk. - * - * @return inhabited time - */ - long getInhabitedTime(); - - /** - * Sets the amount of time in ticks that this chunk has been inhabited. - * - * @param ticks new inhabited time - */ - void setInhabitedTime(long ticks); - - /** - * Tests if this chunk contains the specified block. - * - * @param block block to test - * @return if the block is contained within - */ - boolean contains(@NotNull BlockData block); -} diff --git a/api/src/main/java/org/bukkit/ChunkSnapshot.java b/api/src/main/java/org/bukkit/ChunkSnapshot.java deleted file mode 100644 index dc5e6918d..000000000 --- a/api/src/main/java/org/bukkit/ChunkSnapshot.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.bukkit; - -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - String getWorldName(); - - /** - * Get block type for block at corresponding coordinate in the chunk - * - * @param x 0-15 - * @param y 0-255 - * @param z 0-15 - * @return block material type - */ - @NotNull - Material getBlockType(int x, int y, int z); - - /** - * Get block data for block at corresponding coordinate in the chunk - * - * @param x 0-15 - * @param y 0-255 - * @param z 0-15 - * @return block material type - */ - @NotNull - BlockData getBlockData(int x, int y, int z); - - /** - * Get block data for block at corresponding coordinate in the chunk - * - * @param x 0-15 - * @param y 0-255 - * @param z 0-15 - * @return 0-15 - * @deprecated Magic value - */ - @Deprecated - int getData(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-255 - * @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-255 - * @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 (0-15) - * @param z Z-coordinate of the blocks (0-15) - * @return Y-coordinate of the highest non-air block - */ - int getHighestBlockYAt(int x, int z); - - /** - * Get biome at given coordinates - * - * @param x X-coordinate (0-15) - * @param z Z-coordinate (0-15) - * @return Biome at given coordinate - */ - @NotNull - Biome getBiome(int x, int z); - - /** - * Get raw biome temperature (0.0-1.0) at given coordinate - * - * @param x X-coordinate (0-15) - * @param z Z-coordinate (0-15) - * @return temperature at given coordinate - */ - double getRawBiomeTemperature(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, 0-255) - * @return true if empty, false if not - */ - boolean isSectionEmpty(int sy); - - /** - * Tests if this snapshot contains the specified block. - * - * @param block block to test - * @return if the block is contained within - */ - boolean contains(@NotNull BlockData block); -} diff --git a/api/src/main/java/org/bukkit/CoalType.java b/api/src/main/java/org/bukkit/CoalType.java deleted file mode 100644 index c07499dbd..000000000 --- a/api/src/main/java/org/bukkit/CoalType.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -/** - * Represents the two types of coal - */ -public enum CoalType { - COAL(0x0), - CHARCOAL(0x1); - - private final byte data; - private static final Map BY_DATA = Maps.newHashMap(); - - private 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 - @Nullable - 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/api/src/main/java/org/bukkit/Color.java b/api/src/main/java/org/bukkit/Color.java deleted file mode 100644 index 78be0f3b9..000000000 --- a/api/src/main/java/org/bukkit/Color.java +++ /dev/null @@ -1,355 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import org.apache.commons.lang.Validate; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.SerializableAs; -import org.jetbrains.annotations.NotNull; - -/** - * 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} - */ - @NotNull - 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} - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - @NotNull - public Color mixDyes(@NotNull 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 - @NotNull - public Color mixColors(@NotNull 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(); - } - - @Override - @NotNull - public Map serialize() { - return ImmutableMap.of( - "RED", getRed(), - "BLUE", getBlue(), - "GREEN", getGreen() - ); - } - - @SuppressWarnings("javadoc") - @NotNull - public static Color deserialize(@NotNull Map map) { - return fromRGB( - asInt("RED", map), - asInt("GREEN", map), - asInt("BLUE", map) - ); - } - - private static int asInt(@NotNull String string, @NotNull 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/api/src/main/java/org/bukkit/CropState.java b/api/src/main/java/org/bukkit/CropState.java deleted file mode 100644 index fb4832fb7..000000000 --- a/api/src/main/java/org/bukkit/CropState.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -/** - * 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 static final Map BY_DATA = Maps.newHashMap(); - - private 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 - @Nullable - 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/api/src/main/java/org/bukkit/Difficulty.java b/api/src/main/java/org/bukkit/Difficulty.java deleted file mode 100644 index 3f6cbefc2..000000000 --- a/api/src/main/java/org/bukkit/Difficulty.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -/** - * 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 static final Map BY_ID = Maps.newHashMap(); - - private 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 - @Nullable - 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/api/src/main/java/org/bukkit/DyeColor.java b/api/src/main/java/org/bukkit/DyeColor.java deleted file mode 100644 index bd213cabd..000000000 --- a/api/src/main/java/org/bukkit/DyeColor.java +++ /dev/null @@ -1,229 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * All supported color values for dyes and cloth - */ -public enum DyeColor { - - /** - * Represents white dye. - */ - WHITE(0x0, 0xF, Color.fromRGB(0xF9FFFE), Color.fromRGB(0xF0F0F0)), - /** - * Represents orange dye. - */ - ORANGE(0x1, 0xE, Color.fromRGB(0xF9801D), Color.fromRGB(0xEB8844)), - /** - * Represents magenta dye. - */ - MAGENTA(0x2, 0xD, Color.fromRGB(0xC74EBD), Color.fromRGB(0xC354CD)), - /** - * Represents light blue dye. - */ - LIGHT_BLUE(0x3, 0xC, Color.fromRGB(0x3AB3DA), Color.fromRGB(0x6689D3)), - /** - * Represents yellow dye. - */ - YELLOW(0x4, 0xB, Color.fromRGB(0xFED83D), Color.fromRGB(0xDECF2A)), - /** - * Represents lime dye. - */ - LIME(0x5, 0xA, Color.fromRGB(0x80C71F), Color.fromRGB(0x41CD34)), - /** - * Represents pink dye. - */ - PINK(0x6, 0x9, Color.fromRGB(0xF38BAA), Color.fromRGB(0xD88198)), - /** - * Represents gray dye. - */ - GRAY(0x7, 0x8, Color.fromRGB(0x474F52), Color.fromRGB(0x434343)), - /** - * Represents light gray dye. - */ - LIGHT_GRAY(0x8, 0x7, Color.fromRGB(0x9D9D97), Color.fromRGB(0xABABAB)), - /** - * Represents cyan dye. - */ - CYAN(0x9, 0x6, Color.fromRGB(0x169C9C), Color.fromRGB(0x287697)), - /** - * Represents purple dye. - */ - PURPLE(0xA, 0x5, Color.fromRGB(0x8932B8), Color.fromRGB(0x7B2FBE)), - /** - * Represents blue dye. - */ - BLUE(0xB, 0x4, Color.fromRGB(0x3C44AA), Color.fromRGB(0x253192)), - /** - * Represents brown dye. - */ - BROWN(0xC, 0x3, Color.fromRGB(0x835432), Color.fromRGB(0x51301A)), - /** - * Represents green dye. - */ - GREEN(0xD, 0x2, Color.fromRGB(0x5E7C16), Color.fromRGB(0x3B511A)), - /** - * Represents red dye. - */ - RED(0xE, 0x1, Color.fromRGB(0xB02E26), Color.fromRGB(0xB3312C)), - /** - * Represents black dye. - */ - BLACK(0xF, 0x0, Color.fromRGB(0x1D1D21), Color.fromRGB(0x1E1B1B)); - - private final byte woolData; - private final byte dyeData; - private final Color color; - private final Color firework; - private static final DyeColor[] BY_WOOL_DATA; - private static final DyeColor[] BY_DYE_DATA; - private static final Map BY_COLOR; - private static final Map BY_FIREWORK; - - private DyeColor(final int woolData, final int dyeData, /*@NotNull*/ Color color, /*@NotNull*/ 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 - * @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 - */ - @NotNull - public Color getColor() { - return color; - } - - /** - * Gets the firework color that this dye represents. - * - * @return The {@link Color} that this dye represents - */ - @NotNull - 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 - * @see #getByDyeData(byte) - * @deprecated Magic value - */ - @Deprecated - @Nullable - 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 - @Nullable - 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 - */ - @Nullable - public static DyeColor getByColor(@NotNull 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 - */ - @Nullable - public static DyeColor getByFireworkColor(@NotNull final Color color) { - return BY_FIREWORK.get(color); - } - - /** - * Gets the DyeColor for the given name, possibly doing legacy transformations. - * - * @param name dye name - * @return dye color - * @deprecated legacy use only - */ - @Deprecated - @NotNull - public static DyeColor legacyValueOf(@Nullable String name) { - return "SILVER".equals(name) ? DyeColor.LIGHT_GRAY : DyeColor.valueOf(name); - } - - 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/api/src/main/java/org/bukkit/Effect.java b/api/src/main/java/org/bukkit/Effect.java deleted file mode 100644 index 87911e08b..000000000 --- a/api/src/main/java/org/bukkit/Effect.java +++ /dev/null @@ -1,267 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.bukkit.block.BlockFace; -import org.bukkit.potion.Potion; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - DOOR_TOGGLE(1006, Type.SOUND), - /** - * Sound of a door opening. - */ - IRON_DOOR_TOGGLE(1005, Type.SOUND), - /** - * Sound of a trapdoor opening. - */ - TRAPDOOR_TOGGLE(1007, Type.SOUND), - /** - * Sound of a door opening. - */ - IRON_TRAPDOOR_TOGGLE(1037, Type.SOUND), - /** - * Sound of a door opening. - */ - FENCE_GATE_TOGGLE(1008, Type.SOUND), - /** - * Sound of a door closing. - */ - DOOR_CLOSE(1012, Type.SOUND), - /** - * Sound of a door closing. - */ - IRON_DOOR_CLOSE(1011, Type.SOUND), - /** - * Sound of a trapdoor closing. - */ - TRAPDOOR_CLOSE(1013, Type.SOUND), - /** - * Sound of a door closing. - */ - IRON_TRAPDOOR_CLOSE(1036, Type.SOUND), - /** - * Sound of a door closing. - */ - FENCE_GATE_CLOSE(1014, Type.SOUND), - /** - * Sound of fire being extinguished. - */ - EXTINGUISH(1009, Type.SOUND), - /** - * A song from a record. Needs the record item ID as additional info - */ - RECORD_PLAY(1010, Type.SOUND, Material.class), - /** - * Sound of ghast shrieking. - */ - GHAST_SHRIEK(1015, Type.SOUND), - /** - * Sound of ghast firing. - */ - GHAST_SHOOT(1016, Type.SOUND), - /** - * Sound of blaze firing. - */ - BLAZE_SHOOT(1018, Type.SOUND), - /** - * Sound of zombies chewing on wooden doors. - */ - ZOMBIE_CHEW_WOODEN_DOOR(1019, Type.SOUND), - /** - * Sound of zombies chewing on iron doors. - */ - ZOMBIE_CHEW_IRON_DOOR(1020, Type.SOUND), - /** - * Sound of zombies destroying a door. - */ - ZOMBIE_DESTROY_DOOR(1021, 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 sound played by brewing stands when brewing - */ - BREWING_STAND_BREW(1035, Type.SOUND), - /** - * The sound played when a chorus flower grows - */ - CHORUS_FLOWER_GROW(1033, Type.SOUND), - /** - * The sound played when a chorus flower dies - */ - CHORUS_FLOWER_DEATH(1034, Type.SOUND), - /** - * The sound played when traveling through a portal - */ - PORTAL_TRAVEL(1032, Type.SOUND), - /** - * The sound played when launching an endereye - */ - ENDEREYE_LAUNCH(1003, Type.SOUND), - /** - * The sound played when launching a firework - */ - FIREWORK_SHOOT(1004, Type.SOUND), - /** - * Particles displayed when a villager grows a plant, data - * is the number of particles - */ - VILLAGER_PLANT_GROW(2005, Type.VISUAL, Integer.class), - /** - * The sound/particles used by the enderdragon's breath - * attack. - */ - DRAGON_BREATH(2006, Type.VISUAL), - /** - * The sound played when an anvil breaks - */ - ANVIL_BREAK(1029, Type.SOUND), - /** - * The sound played when an anvil is used - */ - ANVIL_USE(1030, Type.SOUND), - /** - * The sound played when an anvil lands after - * falling - */ - ANVIL_LAND(1031, Type.SOUND), - /** - * Sound of an enderdragon firing - */ - ENDERDRAGON_SHOOT(1017, Type.SOUND), - /** - * The sound played when a wither breaks a block - */ - WITHER_BREAK_BLOCK(1022, Type.SOUND), - /** - * Sound of a wither shooting - */ - WITHER_SHOOT(1024, Type.SOUND), - /** - * The sound played when a zombie infects a target - */ - ZOMBIE_INFECT(1026, Type.SOUND), - /** - * The sound played when a villager is converted by - * a zombie - */ - ZOMBIE_CONVERTED_VILLAGER(1027, Type.SOUND), - /** - * Sound played by a bat taking off - */ - BAT_TAKEOFF(1025, Type.SOUND), - /** - * The sound/particles caused by a end gateway spawning - */ - END_GATEWAY_SPAWN(3000, Type.VISUAL), - /** - * The sound of an enderdragon growling - */ - ENDERDRAGON_GROWL(3001, Type.SOUND), - ; - - private final int id; - private final Type type; - private final Class data; - private static final Map BY_ID = Maps.newHashMap(); - - Effect(int id, /*@NotNull*/ Type type) { - this(id, type, null); - } - - Effect(int id, /*@NotNull*/ Type type, /*@Nullable*/ Class data) { - this.id = id; - this.type = type; - this.data = data; - } - - /** - * Gets the ID for this effect. - * - * @return ID of this effect - * @deprecated Magic value - */ - @Deprecated - public int getId() { - return this.id; - } - - /** - * @return The type of the effect. - */ - @NotNull - public Type getType() { - return this.type; - } - - /** - * @return The class which represents data for this effect, or null if - * none - */ - @Nullable - 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 - @Nullable - public static Effect getById(int id) { - return BY_ID.get(id); - } - - static { - for (Effect effect : values()) { - BY_ID.put(effect.id, effect); - } - } - - /** - * Represents the type of an effect. - */ - public enum Type {SOUND, VISUAL} -} diff --git a/api/src/main/java/org/bukkit/EntityEffect.java b/api/src/main/java/org/bukkit/EntityEffect.java deleted file mode 100644 index 4cec72688..000000000 --- a/api/src/main/java/org/bukkit/EntityEffect.java +++ /dev/null @@ -1,202 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Firework; -import org.bukkit.entity.Guardian; -import org.bukkit.entity.IronGolem; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Rabbit; -import org.bukkit.entity.Squid; -import org.bukkit.entity.Tameable; -import org.bukkit.entity.TippedArrow; -import org.bukkit.entity.Villager; -import org.bukkit.entity.Witch; -import org.bukkit.entity.Wolf; -import org.bukkit.entity.ZombieVillager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * A list of all Effects that can happen to entities. - */ -public enum EntityEffect { - - /** - * Colored particles from a tipped arrow. - */ - ARROW_PARTICLES(0, TippedArrow.class), - /** - * Rabbit jumping. - */ - RABBIT_JUMP(1, Rabbit.class), - /** - * When mobs get hurt. - */ - HURT(2, LivingEntity.class), - /** - * When a mob dies. - *

- * This will cause client-glitches! - * - * @deprecated although this effect may trigger other events on non-living - * entities, it's only supported usage is on living ones. - */ - @Deprecated - DEATH(3, Entity.class), - // PAIL - SPIGOT-3641 duplicate - // GOLEM_ATTACK(4, IronGolem.class), - // 5 - unused - /** - * The smoke when taming a wolf fails. - */ - WOLF_SMOKE(6, Tameable.class), - /** - * The hearts when taming a wolf succeeds. - */ - WOLF_HEARTS(7, Wolf.class), - /** - * When a wolf shakes (after being wet). - */ - WOLF_SHAKE(8, Wolf.class), - // 9 - unused - /** - * When an entity eats a LONG_GRASS block. - * - * @deprecated although this effect may trigger other events on non-living - * entities, it's only supported usage is on living ones. - */ - @Deprecated - SHEEP_EAT(10, Entity.class), - /** - * When an Iron Golem gives a rose. - */ - IRON_GOLEM_ROSE(11, IronGolem.class), - /** - * Hearts from a villager. - */ - VILLAGER_HEART(12, Villager.class), - /** - * When a villager is angry. - */ - VILLAGER_ANGRY(13, Villager.class), - /** - * Happy particles from a villager. - */ - VILLAGER_HAPPY(14, Villager.class), - /** - * Magic particles from a witch. - */ - WITCH_MAGIC(15, Witch.class), - /** - * When a zombie transforms into a villager by shaking violently. - */ - ZOMBIE_TRANSFORM(16, ZombieVillager.class), - /** - * When a firework explodes. - */ - FIREWORK_EXPLODE(17, Firework.class), - /** - * Hearts from a breeding entity. - */ - LOVE_HEARTS(18, Ageable.class), - /** - * Resets squid rotation. - */ - SQUID_ROTATE(19, Squid.class), - /** - * Silverfish entering block, spawner spawning. - */ - ENTITY_POOF(20, LivingEntity.class), - /** - * Guardian sets laser target. - */ - GUARDIAN_TARGET(21, Guardian.class), - // 22-28 player internal flags - /** - * Shield blocks attack. - */ - SHIELD_BLOCK(29, LivingEntity.class), - /** - * Shield breaks. - */ - SHIELD_BREAK(30, LivingEntity.class), - // 31 - unused - /** - * Armor stand is hit. - */ - ARMOR_STAND_HIT(32, ArmorStand.class), - /** - * Entity hurt by thorns attack. - */ - THORNS_HURT(33, LivingEntity.class), - /** - * Iron golem puts away rose. - */ - IRON_GOLEM_SHEATH(34, IronGolem.class), - /** - * Totem prevents entity death. - */ - TOTEM_RESURRECT(35, LivingEntity.class), - /** - * Entity hurt due to drowning damage. - */ - HURT_DROWN(36, LivingEntity.class), - /** - * Entity hurt due to explosion damage. - */ - HURT_EXPLOSION(37, LivingEntity.class); - - private final byte data; - private final Class applicable; - private static final Map BY_DATA = Maps.newHashMap(); - - EntityEffect(final int data, /*@NotNull*/ Class clazz) { - this.data = (byte) data; - this.applicable = clazz; - } - - /** - * Gets the data value of this EntityEffect - * - * @return The data value - * @deprecated Magic value - */ - @Deprecated - public byte getData() { - return data; - } - - /** - * Gets entity superclass which this affect is applicable to. - * - * @return applicable class - */ - @NotNull - public Class getApplicable() { - return applicable; - } - - /** - * 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 - @Nullable - 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/api/src/main/java/org/bukkit/FireworkEffect.java b/api/src/main/java/org/bukkit/FireworkEffect.java deleted file mode 100644 index 31e14b0ce..000000000 --- a/api/src/main/java/org/bukkit/FireworkEffect.java +++ /dev/null @@ -1,438 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang.Validate; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.SerializableAs; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - 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 - */ - @NotNull - public Builder with(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - public Builder flicker(boolean flicker) { - this.flicker = flicker; - return this; - } - - /** - * Add a trail to the firework effect. - * - * @return This object, for chaining - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - public Builder withColor(@NotNull 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) - */ - @NotNull - public Builder withColor(@NotNull 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) - */ - @NotNull - public Builder withColor(@NotNull 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) - */ - @NotNull - public Builder withFade(@NotNull 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) - */ - @NotNull - public Builder withFade(@NotNull 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) - */ - @NotNull - public Builder withFade(@NotNull 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 - */ - @NotNull - 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, @NotNull ImmutableList colors, @NotNull ImmutableList fadeColors, @NotNull 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 - */ - @NotNull - public List getColors() { - return colors; - } - - /** - * Get the fade colors of the firework effect. - * - * @return An immutable list of the fade colors - */ - @NotNull - public List getFadeColors() { - return fadeColors; - } - - /** - * Get the type of the firework effect. - * - * @return The effect type - */ - @NotNull - public Type getType() { - return type; - } - - /** - * @see ConfigurationSerializable - * @param map the map to deserialize - * @return the resulting serializable - */ - @NotNull - public static ConfigurationSerializable deserialize(@NotNull Map map) { - Type type = Type.valueOf((String) map.get(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(); - } - - @NotNull - @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/api/src/main/java/org/bukkit/FluidCollisionMode.java b/api/src/main/java/org/bukkit/FluidCollisionMode.java deleted file mode 100644 index ae2895894..000000000 --- a/api/src/main/java/org/bukkit/FluidCollisionMode.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bukkit; - -/** - * Determines the collision behavior when fluids get hit during ray tracing. - */ -public enum FluidCollisionMode { - - /** - * Ignore fluids. - */ - NEVER, - /** - * Only collide with source fluid blocks. - */ - SOURCE_ONLY, - /** - * Collide with all fluids. - */ - ALWAYS; -} diff --git a/api/src/main/java/org/bukkit/GameMode.java b/api/src/main/java/org/bukkit/GameMode.java deleted file mode 100644 index 938c3217f..000000000 --- a/api/src/main/java/org/bukkit/GameMode.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.bukkit.entity.HumanEntity; -import org.jetbrains.annotations.Nullable; - -/** - * 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 static final Map BY_ID = Maps.newHashMap(); - - private 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 - @Nullable - 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/api/src/main/java/org/bukkit/GameRule.java b/api/src/main/java/org/bukkit/GameRule.java deleted file mode 100644 index ee7ae56f9..000000000 --- a/api/src/main/java/org/bukkit/GameRule.java +++ /dev/null @@ -1,228 +0,0 @@ -package org.bukkit; - -import com.google.common.base.Preconditions; -import java.util.HashMap; -import java.util.Map; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * GameRules dictate certain behavior within Minecraft itself - *
- * For more information please visit the - * Minecraft - * Wiki - */ -public final class GameRule { - - private static Map> gameRules = new HashMap<>(); - // Boolean rules - /** - * Toggles the announcing of advancements. - */ - public static final GameRule ANNOUNCE_ADVANCEMENTS = new GameRule<>("announceAdvancements", Boolean.class); - - /** - * Whether command blocks should notify admins when they perform commands. - */ - public static final GameRule COMMAND_BLOCK_OUTPUT = new GameRule<>("commandBlockOutput", Boolean.class); - - /** - * Whether the server should skip checking player speed when the player is - * wearing elytra. - */ - public static final GameRule DISABLE_ELYTRA_MOVEMENT_CHECK = new GameRule<>("disableElytraMovementCheck", Boolean.class); - - /** - * Whether time progresses from the current moment. - */ - public static final GameRule DO_DAYLIGHT_CYCLE = new GameRule<>("doDaylightCycle", Boolean.class); - - /** - * Whether entities that are not mobs should have drops. - */ - public static final GameRule DO_ENTITY_DROPS = new GameRule<>("doEntityDrops", Boolean.class); - - /** - * Whether fire should spread and naturally extinguish. - */ - public static final GameRule DO_FIRE_TICK = new GameRule<>("doFireTick", Boolean.class); - - /** - * Whether players should only be able to craft recipes they've unlocked - * first. - */ - public static final GameRule DO_LIMITED_CRAFTING = new GameRule<>("doLimitedCrafting", Boolean.class); - - /** - * Whether mobs should drop items. - */ - public static final GameRule DO_MOB_LOOT = new GameRule<>("doMobLoot", Boolean.class); - - /** - * Whether mobs should naturally spawn. - */ - public static final GameRule DO_MOB_SPAWNING = new GameRule<>("doMobSpawning", Boolean.class); - - /** - * Whether blocks should have drops. - */ - public static final GameRule DO_TILE_DROPS = new GameRule<>("doTileDrops", Boolean.class); - - /** - * Whether the weather will change from the current moment. - */ - public static final GameRule DO_WEATHER_CYCLE = new GameRule<>("doWeatherCycle", Boolean.class); - - /** - * Whether the player should keep items in their inventory after death. - */ - public static final GameRule KEEP_INVENTORY = new GameRule<>("keepInventory", Boolean.class); - - /** - * Whether to log admin commands to server log. - */ - public static final GameRule LOG_ADMIN_COMMANDS = new GameRule<>("logAdminCommands", Boolean.class); - - /** - * Whether mobs can pick up items or change blocks. - */ - public static final GameRule MOB_GRIEFING = new GameRule<>("mobGriefing", Boolean.class); - - /** - * Whether players can regenerate health naturally through their hunger bar. - */ - public static final GameRule NATURAL_REGENERATION = new GameRule<>("naturalRegeneration", Boolean.class); - - /** - * Whether the debug screen shows all or reduced information. - */ - public static final GameRule REDUCED_DEBUG_INFO = new GameRule<>("reducedDebugInfo", Boolean.class); - - /** - * Whether the feedback from commands executed by a player should show up in - * chat. Also affects the default behavior of whether command blocks store - * their output text. - */ - public static final GameRule SEND_COMMAND_FEEDBACK = new GameRule<>("sendCommandFeedback", Boolean.class); - - /** - * Whether a message appears in chat when a player dies. - */ - public static final GameRule SHOW_DEATH_MESSAGES = new GameRule<>("showDeathMessages", Boolean.class); - - /** - * Whether players in spectator mode can generate chunks. - */ - public static final GameRule SPECTATORS_GENERATE_CHUNKS = new GameRule<>("spectatorsGenerateChunks", Boolean.class); - - /** - * Whether pillager raids are enabled or not. - */ - public static final GameRule DISABLE_RAIDS = new GameRule<>("disableRaids", Boolean.class); - - // Numerical rules - /** - * How often a random block tick occurs (such as plant growth, leaf decay, - * etc.) per chunk section per game tick. 0 will disable random ticks, - * higher numbers will increase random ticks. - */ - public static final GameRule RANDOM_TICK_SPEED = new GameRule<>("randomTickSpeed", Integer.class); - - /** - * The number of blocks outward from the world spawn coordinates that a - * player will spawn in when first joining a server or when dying without a - * spawnpoint. - */ - public static final GameRule SPAWN_RADIUS = new GameRule<>("spawnRadius", Integer.class); - - /** - * The maximum number of other pushable entities a mob or player can push, - * before taking suffocation damage. - *
- * Setting to 0 disables this rule. - */ - public static final GameRule MAX_ENTITY_CRAMMING = new GameRule<>("maxEntityCramming", Integer.class); - - /** - * Determines the number at which the chain of command blocks act as a - * "chain." - *
- * This is the maximum amount of command blocks that can be activated in a - * single tick from a single chain. - */ - public static final GameRule MAX_COMMAND_CHAIN_LENGTH = new GameRule<>("maxCommandChainLength", Integer.class); - - // All GameRules instantiated above this for organizational purposes - private final String name; - private final Class type; - - private GameRule(@NotNull String name, @NotNull Class clazz) { - Preconditions.checkNotNull(name, "GameRule name cannot be null"); - Preconditions.checkNotNull(clazz, "GameRule type cannot be null"); - Preconditions.checkArgument(clazz == Boolean.class || clazz == Integer.class, "Must be of type Boolean or Integer. Found %s ", clazz.getName()); - this.name = name; - this.type = clazz; - gameRules.put(name, this); - } - - /** - * Get the name of this GameRule. - * - * @return the name of this GameRule - */ - @NotNull - public String getName() { - return name; - } - - /** - * Get the type of this rule. - * - * @return the rule type; Integer or Boolean - */ - @NotNull - public Class getType() { - return type; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof GameRule)) { - return false; - } - GameRule other = (GameRule) obj; - return this.getName().equals(other.getName()) && this.getType() == other.getType(); - } - - @Override - public String toString() { - return "GameRule{" + "key=" + name + ", type=" + type + '}'; - } - - /** - * Get a {@link GameRule} by its name. - * - * @param rule the name of the GameRule - * @return the {@link GameRule} or null if no GameRule matches the given - * name - */ - @Nullable - public static GameRule getByName(@NotNull String rule) { - Preconditions.checkNotNull(rule, "Rule cannot be null"); - return gameRules.get(rule); - } - - /** - * Get an immutable collection of {@link GameRule}s. - * - * @return an immutable collection containing all registered GameRules. - */ - @NotNull - public static GameRule[] values() { - return gameRules.values().toArray(new GameRule[gameRules.size()]); - } -} diff --git a/api/src/main/java/org/bukkit/GrassSpecies.java b/api/src/main/java/org/bukkit/GrassSpecies.java deleted file mode 100644 index f9c9ae463..000000000 --- a/api/src/main/java/org/bukkit/GrassSpecies.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -/** - * 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 static final Map BY_DATA = Maps.newHashMap(); - - private 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 - @Nullable - 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/api/src/main/java/org/bukkit/Instrument.java b/api/src/main/java/org/bukkit/Instrument.java deleted file mode 100644 index 92194803b..000000000 --- a/api/src/main/java/org/bukkit/Instrument.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -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), - /** - * Flute is normally played when a note block is on top of a clay block. - */ - FLUTE(0x5), - /** - * Bell is normally played when a note block is on top of a gold block. - */ - BELL(0x6), - /** - * Guitar is normally played when a note block is on top of a woolen block. - */ - GUITAR(0x7), - /** - * Chime is normally played when a note block is on top of a packed ice - * block. - */ - CHIME(0x8), - /** - * Xylophone is normally played when a note block is on top of a bone block. - */ - XYLOPHONE(0x9), - /** - * Iron Xylophone is normally played when a note block is on top of a iron block. - */ - IRON_XYLOPHONE(0xA), - /** - * Cow Bell is normally played when a note block is on top of a soul sand block. - */ - COW_BELL(0xB), - /** - * Didgeridoo is normally played when a note block is on top of a pumpkin block. - */ - DIDGERIDOO(0xC), - /** - * Bit is normally played when a note block is on top of a emerald block. - */ - BIT(0xD), - /** - * Banjo is normally played when a note block is on top of a hay block. - */ - BANJO(0xE), - /** - * Pling is normally played when a note block is on top of a glowstone block. - */ - PLING(0xF); - - private final byte type; - private static final Map BY_DATA = Maps.newHashMap(); - - private 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 - @Nullable - 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/api/src/main/java/org/bukkit/Keyed.java b/api/src/main/java/org/bukkit/Keyed.java deleted file mode 100644 index 32c92621c..000000000 --- a/api/src/main/java/org/bukkit/Keyed.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents an object which has a {@link NamespacedKey} attached to it. - */ -public interface Keyed { - - /** - * Return the namespaced identifier for this object. - * - * @return this object's key - */ - @NotNull - NamespacedKey getKey(); -} diff --git a/api/src/main/java/org/bukkit/Location.java b/api/src/main/java/org/bukkit/Location.java deleted file mode 100644 index 3e1ca4c9f..000000000 --- a/api/src/main/java/org/bukkit/Location.java +++ /dev/null @@ -1,1164 +0,0 @@ -package org.bukkit; - -import com.google.common.base.Preconditions; -import java.lang.ref.Reference; -import java.lang.ref.WeakReference; -import com.google.common.base.Preconditions; // Paper -import java.util.HashMap; -import java.util.Map; -import org.bukkit.block.Block; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.entity.Entity; // Paper -import org.bukkit.util.NumberConversions; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -// Paper start -import java.util.Collection; -import java.util.function.Predicate; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -// Paper end - -/** - * Represents a 3-dimensional position in a world. - *
- * No constraints are placed on any angular values other than that they be - * specified in degrees. This means that negative angles or angles of greater - * magnitude than 360 are valid, but may be normalized to any other equivalent - * representation by the implementation. - */ -public class Location implements Cloneable, ConfigurationSerializable { - private Reference 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(@UndefinedNullability final World world, final double x, final double y, final double z) { // Paper - 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(@UndefinedNullability final World world, final double x, final double y, final double z, final float yaw, final float pitch) { - if (world != null) { - 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(@Nullable World world) { - this.world = (world == null) ? null : new WeakReference<>(world); - } - - /** - * Checks if world in this location is present and loaded. - * - * @return true if is loaded, otherwise false - */ - public boolean isWorldLoaded() { - if (this.world == null) { - return false; - } - - World world = this.world.get(); - return world != null && Bukkit.getWorld(world.getUID()) != null; - } - - /** - * Gets the world that this location resides in - * - * @return World that contains this location, or {@code null} if it is not set - * @throws IllegalArgumentException when world is unloaded - * @see #isWorldLoaded() - */ - @UndefinedNullability - public World getWorld() { - if (this.world == null) { - return null; - } - - World world = this.world.get(); - Preconditions.checkArgument(world != null, "World unloaded"); - return world; - } - - /** - * Gets the chunk at the represented location - * - * @return Chunk at the represented location - */ - @NotNull - public Chunk getChunk() { - return getWorld().getChunkAt(this); - } - - /** - * Gets the block at the represented location - * - * @return Block at the represented location - */ - @NotNull - 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} - */ - @NotNull - 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 - */ - @NotNull - public Location setDirection(@NotNull 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 - */ - @NotNull - public Location add(@NotNull 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 - */ - @NotNull - public Location add(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - public Location subtract(@NotNull 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 - */ - @NotNull - public Location subtract(@NotNull 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 - */ - @NotNull - 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(@NotNull 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(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - public Location zero() { - x = 0; - y = 0; - z = 0; - return this; - } - - public boolean isChunkLoaded() { return this.getWorld().isChunkLoaded(locToBlock(x) >> 4, locToBlock(z) >> 4); } // Paper - - // Paper start - /** - * Checks if a {@link Chunk} has been generated at this location. - * - * @return true if a chunk has been generated at this location - */ - public boolean isGenerated() { - World world = this.getWorld(); - Preconditions.checkNotNull(world, "Location has no world!"); - return world.isChunkGenerated(locToBlock(x) >> 4, locToBlock(z) >> 4); - } - - /** - * Sets the position of this Location and returns itself - * - * This mutates this object, clone first. - * @param x X coordinate - * @param y Y coordinate - * @param z Z coordinate - * @return self (not cloned) - */ - @NotNull - public Location set(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - return this; - } - - /** - * Takes the x/y/z from base and adds the specified x/y/z to it and returns self - * - * This mutates this object, clone first. - * @param base The base coordinate to modify - * @param x X coordinate to add to base - * @param y Y coordinate to add to base - * @param z Z coordinate to add to base - * @return self (not cloned) - */ - @NotNull - public Location add(@NotNull Location base, double x, double y, double z) { - return this.set(base.x + x, base.y + y, base.z + z); - } - - /** - * Takes the x/y/z from base and subtracts the specified x/y/z to it and returns self - * - * This mutates this object, clone first. - * @param base The base coordinate to modify - * @param x X coordinate to subtract from base - * @param y Y coordinate to subtract from base - * @param z Z coordinate to subtract from base - * @return self (not cloned) - */ - @NotNull - public Location subtract(@NotNull Location base, double x, double y, double z) { - return this.set(base.x - x, base.y - y, base.z - z); - } - - /** - * @return A new location where X/Y/Z are on the Block location (integer value of X/Y/Z) - */ - @NotNull - public Location toBlockLocation() { - Location blockLoc = clone(); - blockLoc.setX(getBlockX()); - blockLoc.setY(getBlockY()); - blockLoc.setZ(getBlockZ()); - return blockLoc; - } - - // Paper Start - /** - * @return The block key for this location's block location. - * @see Block#getBlockKey(int, int, int) - */ - public long toBlockKey() { - return Block.getBlockKey(getBlockX(), getBlockY(), getBlockZ()); - } - // Paper End - - /** - * @return A new location where X/Y/Z are the center of the block - */ - @NotNull - public Location toCenterLocation() { - Location centerLoc = clone(); - centerLoc.setX(getBlockX() + 0.5); - centerLoc.setY(getBlockY() + 0.5); - centerLoc.setZ(getBlockZ() + 0.5); - return centerLoc; - } - - // Paper start - Add heightmap api - - /** - * Returns a copy of this location except with y = getWorld().getHighestBlockYAt(this.getBlockX(), this.getBlockZ()) - * @return A copy of this location except with y = getWorld().getHighestBlockYAt(this.getBlockX(), this.getBlockZ()) - * @throws NullPointerException if {{@link #getWorld()}} is {@code null} - */ - @NotNull - public Location toHighestLocation() { - return this.toHighestLocation(com.destroystokyo.paper.HeightmapType.LIGHT_BLOCKING); - } - - /** - * Returns a copy of this location except with y = getWorld().getHighestBlockYAt(this.getBlockX(), this.getBlockZ(), heightmap) - * @param heightmap The heightmap to use for finding the highest y location. - * @return A copy of this location except with y = getWorld().getHighestBlockYAt(this.getBlockX(), this.getBlockZ(), heightmap) - * @throws NullPointerException if {{@link #getWorld()}} is {@code null} - * @throws UnsupportedOperationException if {@link World#getHighestBlockYAt(int, int, com.destroystokyo.paper.HeightmapType)} does not support the specified heightmap - */ - @NotNull - public Location toHighestLocation(@NotNull final com.destroystokyo.paper.HeightmapType heightmap) { - final Location ret = this.clone(); - ret.setY(this.getWorld().getHighestBlockYAt(this, heightmap)); - return ret; - } - // Paper end - - /** - * Creates explosion at this location with given power - * - * Will break blocks and ignite blocks on fire. - * - * @param power The power of explosion, where 4F is TNT - * @return false if explosion was canceled, otherwise true - */ - public boolean createExplosion(float power) { - return this.getWorld().createExplosion(this, power); - } - - /** - * Creates explosion at this location with given power and optionally - * setting blocks on fire. - * - * Will break blocks. - * - * @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 - */ - public boolean createExplosion(float power, boolean setFire) { - return this.getWorld().createExplosion(this, power, setFire); - } - - /** - * Creates explosion at this location with given power and optionally - * setting blocks on fire. - * - * @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 - */ - public boolean createExplosion(float power, boolean setFire, boolean breakBlocks) { - return this.getWorld().createExplosion(this, power, setFire, breakBlocks); - } - - /** - * Creates explosion at this location with given power, with the specified entity as the source. - * - * Will break blocks and ignite blocks on fire. - * - * @param source The source entity of the explosion - * @param power The power of explosion, where 4F is TNT - * @return false if explosion was canceled, otherwise true - */ - public boolean createExplosion(@Nullable Entity source, float power) { - return this.getWorld().createExplosion(source, this, power, true, true); - } - - /** - * Creates explosion at this location with given power and optionally - * setting blocks on fire, with the specified entity as the source. - * - * Will break blocks. - * - * @param source The source entity of the explosion - * @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 - */ - public boolean createExplosion(@Nullable Entity source, float power, boolean setFire) { - return this.getWorld().createExplosion(source, this, power, setFire, true); - } - - /** - * Creates explosion at this location with given power and optionally - * setting blocks on fire, with the specified entity as the source. - * - * @param source The source entity of the explosion - * @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 - */ - public boolean createExplosion(@NotNull Entity source, float power, boolean setFire, boolean breakBlocks) { - return this.getWorld().createExplosion(source, source.getLocation(), power, setFire, breakBlocks); - } - - /** - * 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 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. - */ - @NotNull - public Collection getNearbyEntities(double x, double y, double z) { - World world = this.getWorld(); - if (world == null) { - throw new IllegalArgumentException("Location has no world"); - } - return world.getNearbyEntities(this, x, y, z); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param radius X Radius - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyLivingEntities(double radius) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, radius, radius, radius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param xzRadius X/Z Radius - * @param yRadius Y Radius - * @return the collection of living entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyLivingEntities(double xzRadius, double yRadius) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, xzRadius, yRadius, xzRadius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z radius - * @return the collection of living entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyLivingEntities(double xRadius, double yRadius, double zRadius) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, xRadius, yRadius, zRadius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param radius Radius - * @param predicate a predicate used to filter results - * @return the collection of living entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyLivingEntities(double radius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, radius, radius, radius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param xzRadius X/Z Radius - * @param yRadius Y Radius - * @param predicate a predicate used to filter results - * @return the collection of living entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyLivingEntities(double xzRadius, double yRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, xzRadius, yRadius, xzRadius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z radius - * @param predicate a predicate used to filter results - * @return the collection of living entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyLivingEntities(double xRadius, double yRadius, double zRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, xRadius, yRadius, zRadius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param radius X/Y/Z Radius - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyPlayers(double radius) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, radius, radius, radius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param xzRadius X/Z Radius - * @param yRadius Y Radius - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyPlayers(double xzRadius, double yRadius) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, xzRadius, yRadius, xzRadius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z Radius - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyPlayers(double xRadius, double yRadius, double zRadius) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, xRadius, yRadius, zRadius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param radius X/Y/Z Radius - * @param predicate a predicate used to filter results - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyPlayers(double radius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, radius, radius, radius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param xzRadius X/Z Radius - * @param yRadius Y Radius - * @param predicate a predicate used to filter results - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyPlayers(double xzRadius, double yRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, xzRadius, yRadius, xzRadius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z Radius - * @param predicate a predicate used to filter results - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyPlayers(double xRadius, double yRadius, double zRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, xRadius, yRadius, zRadius, predicate); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius (bounding box) - * @param clazz Type to filter by - * @param radius X/Y/Z radius to search within - * @param the entity type - * @return the collection of entities of type clazz near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyEntitiesByType(@Nullable Class clazz, double radius) { - return getNearbyEntitiesByType(clazz, radius, radius, radius, null); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius, with x and x radius matching (bounding box) - * @param clazz Type to filter by - * @param xzRadius X/Z radius to search within - * @param yRadius Y radius to search within - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyEntitiesByType(@Nullable Class clazz, double xzRadius, double yRadius) { - return getNearbyEntitiesByType(clazz, xzRadius, yRadius, xzRadius, null); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius (bounding box) - * @param clazz Type to filter by - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z Radius - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyEntitiesByType(@Nullable Class clazz, double xRadius, double yRadius, double zRadius) { - return getNearbyEntitiesByType(clazz, xRadius, yRadius, zRadius, null); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius (bounding box) - * @param clazz Type to filter by - * @param radius X/Y/Z radius to search within - * @param predicate a predicate used to filter results - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyEntitiesByType(@Nullable Class clazz, double radius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(clazz, radius, radius, radius, predicate); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius, with x and x radius matching (bounding box) - * @param clazz Type to filter by - * @param xzRadius X/Z radius to search within - * @param yRadius Y radius to search within - * @param predicate a predicate used to filter results - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyEntitiesByType(@Nullable Class clazz, double xzRadius, double yRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(clazz, xzRadius, yRadius, xzRadius, predicate); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius (bounding box) - * @param clazz Type to filter by - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z Radius - * @param predicate a predicate used to filter results - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public Collection getNearbyEntitiesByType(@Nullable Class clazz, double xRadius, double yRadius, double zRadius, @Nullable Predicate predicate) { - World world = this.getWorld(); - if (world == null) { - throw new IllegalArgumentException("Location has no world"); - } - return world.getNearbyEntitiesByType(clazz, this, xRadius, yRadius, zRadius, predicate); - } - // Paper end - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Location other = (Location) obj; - - World world = (this.world == null) ? null : this.world.get(); - World otherWorld = (other.world == null) ? null : other.world.get(); - if (world != otherWorld && (world == null || !world.equals(otherWorld))) { - 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; - - World world = (this.world == null) ? null : this.world.get(); - hash = 19 * hash + (world != null ? world.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() { - World world = (this.world == null) ? null : this.world.get(); - return "Location{" + "world=" + world + ",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 - */ - @NotNull - public Vector toVector() { - return new Vector(x, y, z); - } - - @Override - @NotNull - public Location clone() { - try { - return (Location) super.clone(); - } catch (CloneNotSupportedException e) { - throw new Error(e); - } - } - - /** - * Check if each component of this Location is finite. - * - * @throws IllegalArgumentException if any component is not finite - */ - public void checkFinite() throws IllegalArgumentException { - NumberConversions.checkFinite(x, "x not finite"); - NumberConversions.checkFinite(y, "y not finite"); - NumberConversions.checkFinite(z, "z not finite"); - NumberConversions.checkFinite(pitch, "pitch not finite"); - NumberConversions.checkFinite(yaw, "yaw not finite"); - } - - /** - * 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); - } - - @Override - @Utility - @NotNull - public Map serialize() { - Map data = new HashMap(); - - if (this.world != null) { - 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 - */ - @NotNull - public static Location deserialize(@NotNull Map args) { - World world = null; - if (args.containsKey("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"))); - } - - /** - * Normalizes the given yaw angle to a value between +/-180 - * degrees. - * - * @param yaw the yaw in degrees - * @return the normalized yaw in degrees - * @see Location#getYaw() - */ - public static float normalizeYaw(float yaw) { - yaw %= 360.0f; - if (yaw >= 180.0f) { - yaw -= 360.0f; - } else if (yaw < -180.0f) { - yaw += 360.0f; - } - return yaw; - } - - /** - * Normalizes the given pitch angle to a value between +/-90 - * degrees. - * - * @param pitch the pitch in degrees - * @return the normalized pitch in degrees - * @see Location#getPitch() - */ - public static float normalizePitch(float pitch) { - if (pitch > 90.0f) { - pitch = 90.0f; - } else if (pitch < -90.0f) { - pitch = -90.0f; - } - return pitch; - } -} diff --git a/api/src/main/java/org/bukkit/Material.java b/api/src/main/java/org/bukkit/Material.java deleted file mode 100644 index bb0833f62..000000000 --- a/api/src/main/java/org/bukkit/Material.java +++ /dev/null @@ -1,7953 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.lang.reflect.Constructor; -import java.util.Locale; -import java.util.Map; -import java.util.function.Consumer; -import org.apache.commons.lang.Validate; -import org.bukkit.block.data.Ageable; -import org.bukkit.block.data.AnaloguePowerable; -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Levelled; -import org.bukkit.block.data.Lightable; -import org.bukkit.block.data.MultipleFacing; -import org.bukkit.block.data.Orientable; -import org.bukkit.block.data.Powerable; -import org.bukkit.block.data.Rail; -import org.bukkit.block.data.Rotatable; -import org.bukkit.block.data.Snowable; -import org.bukkit.block.data.Waterlogged; -import org.bukkit.block.data.type.Bamboo; -import org.bukkit.block.data.type.Bed; -import org.bukkit.block.data.type.Bell; -import org.bukkit.block.data.type.BrewingStand; -import org.bukkit.block.data.type.BubbleColumn; -import org.bukkit.block.data.type.Cake; -import org.bukkit.block.data.type.Campfire; -import org.bukkit.block.data.type.Chest; -import org.bukkit.block.data.type.Cocoa; -import org.bukkit.block.data.type.CommandBlock; -import org.bukkit.block.data.type.Comparator; -import org.bukkit.block.data.type.CoralWallFan; -import org.bukkit.block.data.type.DaylightDetector; -import org.bukkit.block.data.type.Dispenser; -import org.bukkit.block.data.type.Door; -import org.bukkit.block.data.type.EndPortalFrame; -import org.bukkit.block.data.type.EnderChest; -import org.bukkit.block.data.type.Farmland; -import org.bukkit.block.data.type.Fence; -import org.bukkit.block.data.type.Fire; -import org.bukkit.block.data.type.Furnace; -import org.bukkit.block.data.type.Gate; -import org.bukkit.block.data.type.GlassPane; -import org.bukkit.block.data.type.Hopper; -import org.bukkit.block.data.type.Jukebox; -import org.bukkit.block.data.type.Ladder; -import org.bukkit.block.data.type.Lantern; -import org.bukkit.block.data.type.Leaves; -import org.bukkit.block.data.type.Lectern; -import org.bukkit.block.data.type.NoteBlock; -import org.bukkit.block.data.type.Observer; -import org.bukkit.block.data.type.Piston; -import org.bukkit.block.data.type.PistonHead; -import org.bukkit.block.data.type.RedstoneRail; -import org.bukkit.block.data.type.RedstoneWallTorch; -import org.bukkit.block.data.type.RedstoneWire; -import org.bukkit.block.data.type.Repeater; -import org.bukkit.block.data.type.Sapling; -import org.bukkit.block.data.type.Scaffolding; -import org.bukkit.block.data.type.SeaPickle; -import org.bukkit.block.data.type.Sign; -import org.bukkit.block.data.type.Slab; -import org.bukkit.block.data.type.Snow; -import org.bukkit.block.data.type.Stairs; -import org.bukkit.block.data.type.StructureBlock; -import org.bukkit.block.data.type.Switch; -import org.bukkit.block.data.type.TNT; -import org.bukkit.block.data.type.TechnicalPiston; -import org.bukkit.block.data.type.TrapDoor; -import org.bukkit.block.data.type.Tripwire; -import org.bukkit.block.data.type.TripwireHook; -import org.bukkit.block.data.type.TurtleEgg; -import org.bukkit.block.data.type.WallSign; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * An enum of all material IDs accepted by the official server and client - */ -@SuppressWarnings({"DeprecatedIsStillUsed", "deprecation"}) // Paper -public enum Material implements Keyed { - // - ACACIA_BOAT(27326, 1), - /** - * BlockData: {@link Switch} - */ - ACACIA_BUTTON(13993, Switch.class), - /** - * BlockData: {@link Door} - */ - ACACIA_DOOR(23797, Door.class), - /** - * BlockData: {@link Fence} - */ - ACACIA_FENCE(4569, Fence.class), - /** - * BlockData: {@link Gate} - */ - ACACIA_FENCE_GATE(14145, Gate.class), - /** - * BlockData: {@link Leaves} - */ - ACACIA_LEAVES(16606, Leaves.class), - /** - * BlockData: {@link Orientable} - */ - ACACIA_LOG(8385, Orientable.class), - ACACIA_PLANKS(31312), - /** - * BlockData: {@link Powerable} - */ - ACACIA_PRESSURE_PLATE(17586, Powerable.class), - /** - * BlockData: {@link Sapling} - */ - ACACIA_SAPLING(20806, Sapling.class), - /** - * BlockData: {@link Sign} - */ - ACACIA_SIGN(29808, 16, Sign.class), - /** - * BlockData: {@link Slab} - */ - ACACIA_SLAB(23730, Slab.class), - /** - * BlockData: {@link Stairs} - */ - ACACIA_STAIRS(17453, Stairs.class), - /** - * BlockData: {@link TrapDoor} - */ - ACACIA_TRAPDOOR(18343, TrapDoor.class), - /** - * BlockData: {@link WallSign} - */ - ACACIA_WALL_SIGN(20316, 16, WallSign.class), - /** - * BlockData: {@link Orientable} - */ - ACACIA_WOOD(9541, Orientable.class), - /** - * BlockData: {@link RedstoneRail} - */ - ACTIVATOR_RAIL(5834, RedstoneRail.class), - AIR(9648, 0), - ALLIUM(6871), - ANDESITE(25975), - /** - * BlockData: {@link Slab} - */ - ANDESITE_SLAB(32124, Slab.class), - /** - * BlockData: {@link Stairs} - */ - ANDESITE_STAIRS(17747, Stairs.class), - /** - * BlockData: {@link Fence} - */ - ANDESITE_WALL(14938, Fence.class), - /** - * BlockData: {@link Directional} - */ - ANVIL(18718, Directional.class), - APPLE(7720), - ARMOR_STAND(12852, 16), - ARROW(31091), - /** - * BlockData: {@link Directional} - */ - ATTACHED_MELON_STEM(30882, Directional.class), - /** - * BlockData: {@link Directional} - */ - ATTACHED_PUMPKIN_STEM(12724, Directional.class), - AZURE_BLUET(17608), - BAKED_POTATO(14624), - /** - * BlockData: {@link Bamboo} - */ - BAMBOO(18728, Bamboo.class), - BAMBOO_SAPLING(8478), - /** - * BlockData: {@link Directional} - */ - BARREL(22396, Directional.class), - BARRIER(26453), - BAT_SPAWN_EGG(14607), - BEACON(6608), - BEDROCK(23130), - BEEF(4803), - BEETROOT(23305), - /** - * BlockData: {@link Ageable} - */ - BEETROOTS(22075, Ageable.class), - BEETROOT_SEEDS(21282), - BEETROOT_SOUP(16036, 1), - /** - * BlockData: {@link Bell} - */ - BELL(20000, Bell.class), - BIRCH_BOAT(28104, 1), - /** - * BlockData: {@link Switch} - */ - BIRCH_BUTTON(26934, Switch.class), - /** - * BlockData: {@link Door} - */ - BIRCH_DOOR(14759, Door.class), - /** - * BlockData: {@link Fence} - */ - BIRCH_FENCE(17347, Fence.class), - /** - * BlockData: {@link Gate} - */ - BIRCH_FENCE_GATE(6322, Gate.class), - /** - * BlockData: {@link Leaves} - */ - BIRCH_LEAVES(12601, Leaves.class), - /** - * BlockData: {@link Orientable} - */ - BIRCH_LOG(26727, Orientable.class), - BIRCH_PLANKS(29322), - /** - * BlockData: {@link Powerable} - */ - BIRCH_PRESSURE_PLATE(9664, Powerable.class), - /** - * BlockData: {@link Sapling} - */ - BIRCH_SAPLING(31533, Sapling.class), - /** - * BlockData: {@link Sign} - */ - BIRCH_SIGN(11351, 16, Sign.class), - /** - * BlockData: {@link Slab} - */ - BIRCH_SLAB(13807, Slab.class), - /** - * BlockData: {@link Stairs} - */ - BIRCH_STAIRS(7657, Stairs.class), - /** - * BlockData: {@link TrapDoor} - */ - BIRCH_TRAPDOOR(32585, TrapDoor.class), - /** - * BlockData: {@link WallSign} - */ - BIRCH_WALL_SIGN(9887, 16, WallSign.class), - /** - * BlockData: {@link Orientable} - */ - BIRCH_WOOD(20913, Orientable.class), - /** - * BlockData: {@link Rotatable} - */ - BLACK_BANNER(9365, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - BLACK_BED(20490, 1, Bed.class), - BLACK_CARPET(6056), - BLACK_CONCRETE(13338), - BLACK_CONCRETE_POWDER(16150), - BLACK_DYE(6202), - /** - * BlockData: {@link Directional} - */ - BLACK_GLAZED_TERRACOTTA(29678, Directional.class), - /** - * BlockData: {@link Directional} - */ - BLACK_SHULKER_BOX(24076, 1, Directional.class), - BLACK_STAINED_GLASS(13941), - /** - * BlockData: {@link GlassPane} - */ - BLACK_STAINED_GLASS_PANE(13201, GlassPane.class), - BLACK_TERRACOTTA(26691), - /** - * BlockData: {@link Directional} - */ - BLACK_WALL_BANNER(4919, Directional.class), - BLACK_WOOL(16693), - /** - * BlockData: {@link Furnace} - */ - BLAST_FURNACE(31157, Furnace.class), - BLAZE_POWDER(18941), - BLAZE_ROD(8289), - BLAZE_SPAWN_EGG(4759), - /** - * BlockData: {@link Rotatable} - */ - BLUE_BANNER(18481, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - BLUE_BED(12714, 1, Bed.class), - BLUE_CARPET(13292), - BLUE_CONCRETE(18756), - BLUE_CONCRETE_POWDER(17773), - BLUE_DYE(11588), - /** - * BlockData: {@link Directional} - */ - BLUE_GLAZED_TERRACOTTA(23823, Directional.class), - BLUE_ICE(22449), - BLUE_ORCHID(13432), - /** - * BlockData: {@link Directional} - */ - BLUE_SHULKER_BOX(11476, 1, Directional.class), - BLUE_STAINED_GLASS(7107), - /** - * BlockData: {@link GlassPane} - */ - BLUE_STAINED_GLASS_PANE(28484, GlassPane.class), - BLUE_TERRACOTTA(5236), - /** - * BlockData: {@link Directional} - */ - BLUE_WALL_BANNER(17757, Directional.class), - BLUE_WOOL(15738), - BONE(5686), - /** - * BlockData: {@link Orientable} - */ - BONE_BLOCK(17312, Orientable.class), - BONE_MEAL(32458), - BOOK(23097), - BOOKSHELF(10069), - BOW(8745, 1, 384), - BOWL(32661), - /** - * BlockData: {@link Waterlogged} - */ - BRAIN_CORAL(31316, Waterlogged.class), - BRAIN_CORAL_BLOCK(30618), - /** - * BlockData: {@link Waterlogged} - */ - BRAIN_CORAL_FAN(13849, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - BRAIN_CORAL_WALL_FAN(22685, CoralWallFan.class), - BREAD(32049), - /** - * BlockData: {@link BrewingStand} - */ - BREWING_STAND(14539, BrewingStand.class), - BRICK(6820), - BRICKS(14165), - /** - * BlockData: {@link Slab} - */ - BRICK_SLAB(26333, Slab.class), - /** - * BlockData: {@link Stairs} - */ - BRICK_STAIRS(21534, Stairs.class), - /** - * BlockData: {@link Fence} - */ - BRICK_WALL(18995, Fence.class), - /** - * BlockData: {@link Rotatable} - */ - BROWN_BANNER(11481, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - BROWN_BED(25624, 1, Bed.class), - BROWN_CARPET(23352), - BROWN_CONCRETE(19006), - BROWN_CONCRETE_POWDER(21485), - BROWN_DYE(7648), - /** - * BlockData: {@link Directional} - */ - BROWN_GLAZED_TERRACOTTA(5655, Directional.class), - BROWN_MUSHROOM(9665), - /** - * BlockData: {@link MultipleFacing} - */ - BROWN_MUSHROOM_BLOCK(6291, MultipleFacing.class), - /** - * BlockData: {@link Directional} - */ - BROWN_SHULKER_BOX(24230, 1, Directional.class), - BROWN_STAINED_GLASS(20945), - /** - * BlockData: {@link GlassPane} - */ - BROWN_STAINED_GLASS_PANE(17557, GlassPane.class), - BROWN_TERRACOTTA(23664), - /** - * BlockData: {@link Directional} - */ - BROWN_WALL_BANNER(14731, Directional.class), - BROWN_WOOL(32638), - /** - * BlockData: {@link BubbleColumn} - */ - BUBBLE_COLUMN(13758, BubbleColumn.class), - /** - * BlockData: {@link Waterlogged} - */ - BUBBLE_CORAL(12464, Waterlogged.class), - BUBBLE_CORAL_BLOCK(15437), - /** - * BlockData: {@link Waterlogged} - */ - BUBBLE_CORAL_FAN(10795, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - BUBBLE_CORAL_WALL_FAN(20382, CoralWallFan.class), - BUCKET(15215, 16), - /** - * BlockData: {@link Ageable} - */ - CACTUS(12191, Ageable.class), - /** - * BlockData: {@link Cake} - */ - CAKE(27048, 1, Cake.class), - /** - * BlockData: {@link Campfire} - */ - CAMPFIRE(8488, Campfire.class), - CARROT(22824), - /** - * BlockData: {@link Ageable} - */ - CARROTS(17258, Ageable.class), - CARROT_ON_A_STICK(27809, 1, 25), - CARTOGRAPHY_TABLE(28529), - /** - * BlockData: {@link Directional} - */ - CARVED_PUMPKIN(25833, Directional.class), - CAT_SPAWN_EGG(29583), - /** - * BlockData: {@link Levelled} - */ - CAULDRON(26531, Levelled.class), - CAVE_AIR(17422), - CAVE_SPIDER_SPAWN_EGG(23341), - CHAINMAIL_BOOTS(17953, 1, 195), - CHAINMAIL_CHESTPLATE(23602, 1, 240), - CHAINMAIL_HELMET(26114, 1, 165), - CHAINMAIL_LEGGINGS(19087, 1, 225), - /** - * BlockData: {@link CommandBlock} - */ - CHAIN_COMMAND_BLOCK(26798, CommandBlock.class), - CHARCOAL(5390), - /** - * BlockData: {@link Chest} - */ - CHEST(22969, Chest.class), - CHEST_MINECART(4497, 1), - CHICKEN(17281), - CHICKEN_SPAWN_EGG(5462), - /** - * BlockData: {@link Directional} - */ - CHIPPED_ANVIL(10623, Directional.class), - CHISELED_QUARTZ_BLOCK(30964), - CHISELED_RED_SANDSTONE(15529), - CHISELED_SANDSTONE(31763), - CHISELED_STONE_BRICKS(9087), - /** - * BlockData: {@link Ageable} - */ - CHORUS_FLOWER(28542, Ageable.class), - CHORUS_FRUIT(7652), - /** - * BlockData: {@link MultipleFacing} - */ - CHORUS_PLANT(28243, MultipleFacing.class), - CLAY(27880), - CLAY_BALL(24603), - CLOCK(14980), - COAL(29067), - COAL_BLOCK(27968), - COAL_ORE(30965), - COARSE_DIRT(15411), - COBBLESTONE(32147), - /** - * BlockData: {@link Slab} - */ - COBBLESTONE_SLAB(6340, Slab.class), - /** - * BlockData: {@link Stairs} - */ - COBBLESTONE_STAIRS(24715, Stairs.class), - /** - * BlockData: {@link Fence} - */ - COBBLESTONE_WALL(12616, Fence.class), - COBWEB(9469), - /** - * BlockData: {@link Cocoa} - */ - COCOA(29709, Cocoa.class), - COCOA_BEANS(27381), - COD(24691), - COD_BUCKET(28601, 1), - COD_SPAWN_EGG(27248), - /** - * BlockData: {@link CommandBlock} - */ - COMMAND_BLOCK(4355, CommandBlock.class), - COMMAND_BLOCK_MINECART(7992, 1), - /** - * BlockData: {@link Comparator} - */ - COMPARATOR(18911, Comparator.class), - COMPASS(24139), - /** - * BlockData: {@link Levelled} - */ - COMPOSTER(31247, Levelled.class), - /** - * BlockData: {@link Waterlogged} - */ - CONDUIT(5148, Waterlogged.class), - COOKED_BEEF(21595), - COOKED_CHICKEN(20780), - COOKED_COD(9681), - COOKED_MUTTON(31447), - COOKED_PORKCHOP(27231), - COOKED_RABBIT(4454), - COOKED_SALMON(5615), - COOKIE(27431), - CORNFLOWER(15405), - COW_SPAWN_EGG(14761), - CRACKED_STONE_BRICKS(27869), - CRAFTING_TABLE(20706), - CREEPER_BANNER_PATTERN(15774, 1), - /** - * BlockData: {@link Rotatable} - */ - CREEPER_HEAD(29146, Rotatable.class), - CREEPER_SPAWN_EGG(9653), - /** - * BlockData: {@link Directional} - */ - CREEPER_WALL_HEAD(30123, Directional.class), - CROSSBOW(4340, 1, 326), - CUT_RED_SANDSTONE(26842), - /** - * BlockData: {@link Slab} - */ - CUT_RED_SANDSTONE_SLAB(7220, Slab.class), - CUT_SANDSTONE(6118), - /** - * BlockData: {@link Slab} - */ - CUT_SANDSTONE_SLAB(30944, Slab.class), - /** - * BlockData: {@link Rotatable} - */ - CYAN_BANNER(9839, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - CYAN_BED(16746, 1, Bed.class), - CYAN_CARPET(31495), - CYAN_CONCRETE(26522), - CYAN_CONCRETE_POWDER(15734), - CYAN_DYE(8043), - /** - * BlockData: {@link Directional} - */ - CYAN_GLAZED_TERRACOTTA(9550, Directional.class), - /** - * BlockData: {@link Directional} - */ - CYAN_SHULKER_BOX(28123, 1, Directional.class), - CYAN_STAINED_GLASS(30604), - /** - * BlockData: {@link GlassPane} - */ - CYAN_STAINED_GLASS_PANE(11784, GlassPane.class), - CYAN_TERRACOTTA(25940), - /** - * BlockData: {@link Directional} - */ - CYAN_WALL_BANNER(10889, Directional.class), - CYAN_WOOL(12221), - /** - * BlockData: {@link Directional} - */ - DAMAGED_ANVIL(10274, Directional.class), - DANDELION(30558), - DARK_OAK_BOAT(28618, 1), - /** - * BlockData: {@link Switch} - */ - DARK_OAK_BUTTON(6214, Switch.class), - /** - * BlockData: {@link Door} - */ - DARK_OAK_DOOR(10669, Door.class), - /** - * BlockData: {@link Fence} - */ - DARK_OAK_FENCE(21767, Fence.class), - /** - * BlockData: {@link Gate} - */ - DARK_OAK_FENCE_GATE(10679, Gate.class), - /** - * BlockData: {@link Leaves} - */ - DARK_OAK_LEAVES(22254, Leaves.class), - /** - * BlockData: {@link Orientable} - */ - DARK_OAK_LOG(14831, Orientable.class), - DARK_OAK_PLANKS(20869), - /** - * BlockData: {@link Powerable} - */ - DARK_OAK_PRESSURE_PLATE(31375, Powerable.class), - /** - * BlockData: {@link Sapling} - */ - DARK_OAK_SAPLING(14933, Sapling.class), - /** - * BlockData: {@link Sign} - */ - DARK_OAK_SIGN(15127, 16, Sign.class), - /** - * BlockData: {@link Slab} - */ - DARK_OAK_SLAB(28852, Slab.class), - /** - * BlockData: {@link Stairs} - */ - DARK_OAK_STAIRS(22921, Stairs.class), - /** - * BlockData: {@link TrapDoor} - */ - DARK_OAK_TRAPDOOR(10355, TrapDoor.class), - /** - * BlockData: {@link WallSign} - */ - DARK_OAK_WALL_SIGN(9508, 16, WallSign.class), - /** - * BlockData: {@link Orientable} - */ - DARK_OAK_WOOD(16995, Orientable.class), - DARK_PRISMARINE(19940), - /** - * BlockData: {@link Slab} - */ - DARK_PRISMARINE_SLAB(7577, Slab.class), - /** - * BlockData: {@link Stairs} - */ - DARK_PRISMARINE_STAIRS(26511, Stairs.class), - /** - * BlockData: {@link DaylightDetector} - */ - DAYLIGHT_DETECTOR(8864, DaylightDetector.class), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_BRAIN_CORAL(9116, Waterlogged.class), - DEAD_BRAIN_CORAL_BLOCK(12979), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_BRAIN_CORAL_FAN(26150, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - DEAD_BRAIN_CORAL_WALL_FAN(23718, CoralWallFan.class), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_BUBBLE_CORAL(30583, Waterlogged.class), - DEAD_BUBBLE_CORAL_BLOCK(28220), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_BUBBLE_CORAL_FAN(17322, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - DEAD_BUBBLE_CORAL_WALL_FAN(18453, CoralWallFan.class), - DEAD_BUSH(22888), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_FIRE_CORAL(8365, Waterlogged.class), - DEAD_FIRE_CORAL_BLOCK(5307), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_FIRE_CORAL_FAN(27073, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - DEAD_FIRE_CORAL_WALL_FAN(23375, CoralWallFan.class), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_HORN_CORAL(5755, Waterlogged.class), - DEAD_HORN_CORAL_BLOCK(15103), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_HORN_CORAL_FAN(11387, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - DEAD_HORN_CORAL_WALL_FAN(27550, CoralWallFan.class), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_TUBE_CORAL(18028, Waterlogged.class), - DEAD_TUBE_CORAL_BLOCK(28350), - /** - * BlockData: {@link Waterlogged} - */ - DEAD_TUBE_CORAL_FAN(17628, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - DEAD_TUBE_CORAL_WALL_FAN(5128, CoralWallFan.class), - DEBUG_STICK(24562, 1), - /** - * BlockData: {@link RedstoneRail} - */ - DETECTOR_RAIL(13475, RedstoneRail.class), - DIAMOND(20865), - DIAMOND_AXE(27277, 1, 1561), - DIAMOND_BLOCK(5944), - DIAMOND_BOOTS(16522, 1, 429), - DIAMOND_CHESTPLATE(32099, 1, 528), - DIAMOND_HELMET(10755, 1, 363), - DIAMOND_HOE(24050, 1, 1561), - DIAMOND_HORSE_ARMOR(10321, 1), - DIAMOND_LEGGINGS(11202, 1, 495), - DIAMOND_ORE(9292), - DIAMOND_PICKAXE(24291, 1, 1561), - DIAMOND_SHOVEL(25415, 1, 1561), - DIAMOND_SWORD(27707, 1, 1561), - DIORITE(24688), - /** - * BlockData: {@link Slab} - */ - DIORITE_SLAB(10715, Slab.class), - /** - * BlockData: {@link Stairs} - */ - DIORITE_STAIRS(13134, Stairs.class), - /** - * BlockData: {@link Fence} - */ - DIORITE_WALL(17412, Fence.class), - DIRT(10580), - /** - * BlockData: {@link Dispenser} - */ - DISPENSER(20871, Dispenser.class), - DOLPHIN_SPAWN_EGG(20787), - DONKEY_SPAWN_EGG(14513), - DRAGON_BREATH(20154), - DRAGON_EGG(29946), - /** - * BlockData: {@link Rotatable} - */ - DRAGON_HEAD(20084, Rotatable.class), - /** - * BlockData: {@link Directional} - */ - DRAGON_WALL_HEAD(19818, Directional.class), - DRIED_KELP(21042), - DRIED_KELP_BLOCK(12966), - /** - * BlockData: {@link Dispenser} - */ - DROPPER(31273, Dispenser.class), - DROWNED_SPAWN_EGG(19368), - EGG(21603, 16), - ELDER_GUARDIAN_SPAWN_EGG(11418), - ELYTRA(23829, 1, 432), - EMERALD(5654), - EMERALD_BLOCK(9914), - EMERALD_ORE(16630), - ENCHANTED_BOOK(11741, 1), - ENCHANTED_GOLDEN_APPLE(8280), - ENCHANTING_TABLE(16255), - ENDERMAN_SPAWN_EGG(29488), - ENDERMITE_SPAWN_EGG(16617), - /** - * BlockData: {@link EnderChest} - */ - ENDER_CHEST(32349, EnderChest.class), - ENDER_EYE(24860), - ENDER_PEARL(5259, 16), - END_CRYSTAL(19090), - END_GATEWAY(26605), - END_PORTAL(16782), - /** - * BlockData: {@link EndPortalFrame} - */ - END_PORTAL_FRAME(15480, EndPortalFrame.class), - /** - * BlockData: {@link Directional} - */ - END_ROD(24832, Directional.class), - END_STONE(29686), - END_STONE_BRICKS(20314), - /** - * BlockData: {@link Slab} - */ - END_STONE_BRICK_SLAB(23239, Slab.class), - /** - * BlockData: {@link Stairs} - */ - END_STONE_BRICK_STAIRS(28831, Stairs.class), - /** - * BlockData: {@link Fence} - */ - END_STONE_BRICK_WALL(27225, Fence.class), - EVOKER_SPAWN_EGG(21271), - EXPERIENCE_BOTTLE(12858), - /** - * BlockData: {@link Farmland} - */ - FARMLAND(31166, Farmland.class), - FEATHER(30548), - FERMENTED_SPIDER_EYE(19386), - FERN(15794), - FILLED_MAP(23504), - /** - * BlockData: {@link Fire} - */ - FIRE(16396, Fire.class), - FIREWORK_ROCKET(23841), - FIREWORK_STAR(12190), - FIRE_CHARGE(4842), - /** - * BlockData: {@link Waterlogged} - */ - FIRE_CORAL(29151, Waterlogged.class), - FIRE_CORAL_BLOCK(12119), - /** - * BlockData: {@link Waterlogged} - */ - FIRE_CORAL_FAN(11112, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - FIRE_CORAL_WALL_FAN(20100, CoralWallFan.class), - FISHING_ROD(4167, 1, 64), - FLETCHING_TABLE(30838), - FLINT(23596), - FLINT_AND_STEEL(28620, 1, 64), - FLOWER_BANNER_PATTERN(5762, 1), - FLOWER_POT(30567), - FOX_SPAWN_EGG(22376), - /** - * BlockData: {@link Ageable} - */ - FROSTED_ICE(21814, Ageable.class), - /** - * BlockData: {@link Furnace} - */ - FURNACE(8133, Furnace.class), - FURNACE_MINECART(14196, 1), - GHAST_SPAWN_EGG(9970), - GHAST_TEAR(18222), - GLASS(6195), - GLASS_BOTTLE(6116), - /** - * BlockData: {@link Fence} - */ - GLASS_PANE(5709, Fence.class), - GLISTERING_MELON_SLICE(20158), - GLOBE_BANNER_PATTERN(27753, 1), - GLOWSTONE(32713), - GLOWSTONE_DUST(6665), - GOLDEN_APPLE(27732), - GOLDEN_AXE(4878, 1, 32), - GOLDEN_BOOTS(7859, 1, 91), - GOLDEN_CARROT(5300), - GOLDEN_CHESTPLATE(4507, 1, 112), - GOLDEN_HELMET(7945, 1, 77), - GOLDEN_HOE(19337, 1, 32), - GOLDEN_HORSE_ARMOR(7996, 1), - GOLDEN_LEGGINGS(21002, 1, 105), - GOLDEN_PICKAXE(10901, 1, 32), - GOLDEN_SHOVEL(15597, 1, 32), - GOLDEN_SWORD(10505, 1, 32), - GOLD_BLOCK(27392), - GOLD_INGOT(28927), - GOLD_NUGGET(28814), - GOLD_ORE(32625), - GRANITE(21091), - /** - * BlockData: {@link Slab} - */ - GRANITE_SLAB(25898, Slab.class), - /** - * BlockData: {@link Stairs} - */ - GRANITE_STAIRS(21840, Stairs.class), - /** - * BlockData: {@link Fence} - */ - GRANITE_WALL(23279, Fence.class), - GRASS(6155), - /** - * BlockData: {@link Snowable} - */ - GRASS_BLOCK(28346, Snowable.class), - GRASS_PATH(8604), - GRAVEL(7804), - /** - * BlockData: {@link Rotatable} - */ - GRAY_BANNER(12053, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - GRAY_BED(15745, 1, Bed.class), - GRAY_CARPET(26991), - GRAY_CONCRETE(13959), - GRAY_CONCRETE_POWDER(13031), - GRAY_DYE(9184), - /** - * BlockData: {@link Directional} - */ - GRAY_GLAZED_TERRACOTTA(6256, Directional.class), - /** - * BlockData: {@link Directional} - */ - GRAY_SHULKER_BOX(12754, 1, Directional.class), - GRAY_STAINED_GLASS(29979), - /** - * BlockData: {@link GlassPane} - */ - GRAY_STAINED_GLASS_PANE(25272, GlassPane.class), - GRAY_TERRACOTTA(18004), - /** - * BlockData: {@link Directional} - */ - GRAY_WALL_BANNER(24275, Directional.class), - GRAY_WOOL(27209), - /** - * BlockData: {@link Rotatable} - */ - GREEN_BANNER(10698, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - GREEN_BED(13797, 1, Bed.class), - GREEN_CARPET(7780), - GREEN_CONCRETE(17949), - GREEN_CONCRETE_POWDER(6904), - GREEN_DYE(23215), - /** - * BlockData: {@link Directional} - */ - GREEN_GLAZED_TERRACOTTA(6958, Directional.class), - /** - * BlockData: {@link Directional} - */ - GREEN_SHULKER_BOX(9377, 1, Directional.class), - GREEN_STAINED_GLASS(22503), - /** - * BlockData: {@link GlassPane} - */ - GREEN_STAINED_GLASS_PANE(4767, GlassPane.class), - GREEN_TERRACOTTA(4105), - /** - * BlockData: {@link Directional} - */ - GREEN_WALL_BANNER(15046, Directional.class), - GREEN_WOOL(25085), - /** - * BlockData: {@link Directional} - */ - GRINDSTONE(26260, Directional.class), - GUARDIAN_SPAWN_EGG(20113), - GUNPOWDER(29974), - /** - * BlockData: {@link Orientable} - */ - HAY_BLOCK(17461, Orientable.class), - HEART_OF_THE_SEA(11807), - /** - * BlockData: {@link AnaloguePowerable} - */ - HEAVY_WEIGHTED_PRESSURE_PLATE(16970, AnaloguePowerable.class), - /** - * BlockData: {@link Hopper} - */ - HOPPER(31974, Hopper.class), - HOPPER_MINECART(19024, 1), - /** - * BlockData: {@link Waterlogged} - */ - HORN_CORAL(19511, Waterlogged.class), - HORN_CORAL_BLOCK(19958), - /** - * BlockData: {@link Waterlogged} - */ - HORN_CORAL_FAN(13610, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - HORN_CORAL_WALL_FAN(28883, CoralWallFan.class), - HORSE_SPAWN_EGG(25981), - HUSK_SPAWN_EGG(20178), - ICE(30428), - INFESTED_CHISELED_STONE_BRICKS(4728), - INFESTED_COBBLESTONE(28798), - INFESTED_CRACKED_STONE_BRICKS(7476), - INFESTED_MOSSY_STONE_BRICKS(9850), - INFESTED_STONE(18440), - INFESTED_STONE_BRICKS(19749), - INK_SAC(7184), - IRON_AXE(15894, 1, 250), - /** - * BlockData: {@link Fence} - */ - IRON_BARS(9378, Fence.class), - IRON_BLOCK(24754), - IRON_BOOTS(8531, 1, 195), - IRON_CHESTPLATE(28112, 1, 240), - /** - * BlockData: {@link Door} - */ - IRON_DOOR(4788, Door.class), - IRON_HELMET(12025, 1, 165), - IRON_HOE(11339, 1, 250), - IRON_HORSE_ARMOR(30108, 1), - IRON_INGOT(24895), - IRON_LEGGINGS(18951, 1, 225), - IRON_NUGGET(13715), - IRON_ORE(19834), - IRON_PICKAXE(8842, 1, 250), - IRON_SHOVEL(30045, 1, 250), - IRON_SWORD(10904, 1, 250), - /** - * BlockData: {@link TrapDoor} - */ - IRON_TRAPDOOR(17095, TrapDoor.class), - ITEM_FRAME(27318), - /** - * BlockData: {@link Directional} - */ - JACK_O_LANTERN(31612, Directional.class), - /** - * BlockData: {@link Directional} - */ - JIGSAW(17398, Directional.class), - /** - * BlockData: {@link Jukebox} - */ - JUKEBOX(19264, Jukebox.class), - JUNGLE_BOAT(4495, 1), - /** - * BlockData: {@link Switch} - */ - JUNGLE_BUTTON(25317, Switch.class), - /** - * BlockData: {@link Door} - */ - JUNGLE_DOOR(28163, Door.class), - /** - * BlockData: {@link Fence} - */ - JUNGLE_FENCE(14358, Fence.class), - /** - * BlockData: {@link Gate} - */ - JUNGLE_FENCE_GATE(21360, Gate.class), - /** - * BlockData: {@link Leaves} - */ - JUNGLE_LEAVES(5133, Leaves.class), - /** - * BlockData: {@link Orientable} - */ - JUNGLE_LOG(20721, Orientable.class), - JUNGLE_PLANKS(26445), - /** - * BlockData: {@link Powerable} - */ - JUNGLE_PRESSURE_PLATE(11376, Powerable.class), - /** - * BlockData: {@link Sapling} - */ - JUNGLE_SAPLING(17951, Sapling.class), - /** - * BlockData: {@link Sign} - */ - JUNGLE_SIGN(24717, 16, Sign.class), - /** - * BlockData: {@link Slab} - */ - JUNGLE_SLAB(19117, Slab.class), - /** - * BlockData: {@link Stairs} - */ - JUNGLE_STAIRS(20636, Stairs.class), - /** - * BlockData: {@link TrapDoor} - */ - JUNGLE_TRAPDOOR(8626, TrapDoor.class), - /** - * BlockData: {@link WallSign} - */ - JUNGLE_WALL_SIGN(29629, 16, WallSign.class), - /** - * BlockData: {@link Orientable} - */ - JUNGLE_WOOD(10341, Orientable.class), - /** - * BlockData: {@link Ageable} - */ - KELP(21916, Ageable.class), - KELP_PLANT(29697), - KNOWLEDGE_BOOK(12646, 1), - /** - * BlockData: {@link Ladder} - */ - LADDER(23599, Ladder.class), - /** - * BlockData: {@link Lantern} - */ - LANTERN(5992, Lantern.class), - LAPIS_BLOCK(14485), - LAPIS_LAZULI(11075), - LAPIS_ORE(22934), - /** - * BlockData: {@link Bisected} - */ - LARGE_FERN(30177, Bisected.class), - /** - * BlockData: {@link Levelled} - */ - LAVA(8415, Levelled.class), - LAVA_BUCKET(9228, 1), - LEAD(29539), - LEATHER(16414), - LEATHER_BOOTS(15282, 1, 65), - LEATHER_CHESTPLATE(29275, 1, 80), - LEATHER_HELMET(11624, 1, 55), - LEATHER_HORSE_ARMOR(30667, 1), - LEATHER_LEGGINGS(28210, 1, 75), - /** - * BlockData: {@link Lectern} - */ - LECTERN(23490, Lectern.class), - /** - * BlockData: {@link Switch} - */ - LEVER(15319, Switch.class), - /** - * BlockData: {@link Rotatable} - */ - LIGHT_BLUE_BANNER(18060, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - LIGHT_BLUE_BED(20957, 1, Bed.class), - LIGHT_BLUE_CARPET(21194), - LIGHT_BLUE_CONCRETE(29481), - LIGHT_BLUE_CONCRETE_POWDER(31206), - LIGHT_BLUE_DYE(28738), - /** - * BlockData: {@link Directional} - */ - LIGHT_BLUE_GLAZED_TERRACOTTA(4336, Directional.class), - /** - * BlockData: {@link Directional} - */ - LIGHT_BLUE_SHULKER_BOX(18226, 1, Directional.class), - LIGHT_BLUE_STAINED_GLASS(17162), - /** - * BlockData: {@link GlassPane} - */ - LIGHT_BLUE_STAINED_GLASS_PANE(18721, GlassPane.class), - LIGHT_BLUE_TERRACOTTA(31779), - /** - * BlockData: {@link Directional} - */ - LIGHT_BLUE_WALL_BANNER(12011, Directional.class), - LIGHT_BLUE_WOOL(21073), - /** - * BlockData: {@link Rotatable} - */ - LIGHT_GRAY_BANNER(11417, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - LIGHT_GRAY_BED(5090, 1, Bed.class), - LIGHT_GRAY_CARPET(11317), - LIGHT_GRAY_CONCRETE(14453), - LIGHT_GRAY_CONCRETE_POWDER(21589), - LIGHT_GRAY_DYE(27643), - /** - * BlockData: {@link Directional} - */ - LIGHT_GRAY_GLAZED_TERRACOTTA(10707, Directional.class), - /** - * BlockData: {@link Directional} - */ - LIGHT_GRAY_SHULKER_BOX(21345, 1, Directional.class), - LIGHT_GRAY_STAINED_GLASS(5843), - /** - * BlockData: {@link GlassPane} - */ - LIGHT_GRAY_STAINED_GLASS_PANE(19008, GlassPane.class), - LIGHT_GRAY_TERRACOTTA(26388), - /** - * BlockData: {@link Directional} - */ - LIGHT_GRAY_WALL_BANNER(31088, Directional.class), - LIGHT_GRAY_WOOL(22936), - /** - * BlockData: {@link AnaloguePowerable} - */ - LIGHT_WEIGHTED_PRESSURE_PLATE(14875, AnaloguePowerable.class), - /** - * BlockData: {@link Bisected} - */ - LILAC(22837, Bisected.class), - LILY_OF_THE_VALLEY(7185), - LILY_PAD(19271), - /** - * BlockData: {@link Rotatable} - */ - LIME_BANNER(18887, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - LIME_BED(27860, 1, Bed.class), - LIME_CARPET(15443), - LIME_CONCRETE(5863), - LIME_CONCRETE_POWDER(28859), - LIME_DYE(6147), - /** - * BlockData: {@link Directional} - */ - LIME_GLAZED_TERRACOTTA(13861, Directional.class), - /** - * BlockData: {@link Directional} - */ - LIME_SHULKER_BOX(28360, 1, Directional.class), - LIME_STAINED_GLASS(24266), - /** - * BlockData: {@link GlassPane} - */ - LIME_STAINED_GLASS_PANE(10610, GlassPane.class), - LIME_TERRACOTTA(24013), - /** - * BlockData: {@link Directional} - */ - LIME_WALL_BANNER(21422, Directional.class), - LIME_WOOL(10443), - LINGERING_POTION(25857, 1), - LLAMA_SPAWN_EGG(23640), - /** - * BlockData: {@link Directional} - */ - LOOM(14276, Directional.class), - /** - * BlockData: {@link Rotatable} - */ - MAGENTA_BANNER(15591, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - MAGENTA_BED(20061, 1, Bed.class), - MAGENTA_CARPET(6180), - MAGENTA_CONCRETE(20591), - MAGENTA_CONCRETE_POWDER(8272), - MAGENTA_DYE(11788), - /** - * BlockData: {@link Directional} - */ - MAGENTA_GLAZED_TERRACOTTA(8067, Directional.class), - /** - * BlockData: {@link Directional} - */ - MAGENTA_SHULKER_BOX(21566, 1, Directional.class), - MAGENTA_STAINED_GLASS(26814), - /** - * BlockData: {@link GlassPane} - */ - MAGENTA_STAINED_GLASS_PANE(14082, GlassPane.class), - MAGENTA_TERRACOTTA(25900), - /** - * BlockData: {@link Directional} - */ - MAGENTA_WALL_BANNER(23291, Directional.class), - MAGENTA_WOOL(11853), - MAGMA_BLOCK(25927), - MAGMA_CREAM(25097), - MAGMA_CUBE_SPAWN_EGG(26638), - MAP(21655), - MELON(25172), - MELON_SEEDS(18340), - MELON_SLICE(5347), - /** - * BlockData: {@link Ageable} - */ - MELON_STEM(8247, Ageable.class), - MILK_BUCKET(9680, 1), - MINECART(14352, 1), - MOJANG_BANNER_PATTERN(11903, 1), - MOOSHROOM_SPAWN_EGG(22125), - /** - * BlockData: {@link MultipleFacing} - */ - MOSSY_COBBLESTONE(21900, MultipleFacing.class), - /** - * BlockData: {@link Slab} - */ - MOSSY_COBBLESTONE_SLAB(12139, Slab.class), - /** - * BlockData: {@link Stairs} - */ - MOSSY_COBBLESTONE_STAIRS(29210, Stairs.class), - /** - * BlockData: {@link Fence} - */ - MOSSY_COBBLESTONE_WALL(11536, Fence.class), - MOSSY_STONE_BRICKS(16415), - /** - * BlockData: {@link Slab} - */ - MOSSY_STONE_BRICK_SLAB(14002, Slab.class), - /** - * BlockData: {@link Stairs} - */ - MOSSY_STONE_BRICK_STAIRS(27578, Stairs.class), - /** - * BlockData: {@link Fence} - */ - MOSSY_STONE_BRICK_WALL(18259, Fence.class), - /** - * BlockData: {@link TechnicalPiston} - */ - MOVING_PISTON(13831, TechnicalPiston.class), - MULE_SPAWN_EGG(11229), - /** - * BlockData: {@link MultipleFacing} - */ - MUSHROOM_STEM(16543, MultipleFacing.class), - MUSHROOM_STEW(16336, 1), - MUSIC_DISC_11(27426, 1), - MUSIC_DISC_13(16359, 1), - MUSIC_DISC_BLOCKS(26667, 1), - MUSIC_DISC_CAT(16246, 1), - MUSIC_DISC_CHIRP(19436, 1), - MUSIC_DISC_FAR(13823, 1), - MUSIC_DISC_MALL(11517, 1), - MUSIC_DISC_MELLOHI(26117, 1), - MUSIC_DISC_STAL(14989, 1), - MUSIC_DISC_STRAD(16785, 1), - MUSIC_DISC_WAIT(26499, 1), - MUSIC_DISC_WARD(24026, 1), - MUTTON(4792), - /** - * BlockData: {@link Snowable} - */ - MYCELIUM(9913, Snowable.class), - NAME_TAG(30731), - NAUTILUS_SHELL(19989), - NETHERRACK(23425), - NETHER_BRICK(19996), - NETHER_BRICKS(27802), - /** - * BlockData: {@link Fence} - */ - NETHER_BRICK_FENCE(5286, Fence.class), - /** - * BlockData: {@link Slab} - */ - NETHER_BRICK_SLAB(26586, Slab.class), - /** - * BlockData: {@link Stairs} - */ - NETHER_BRICK_STAIRS(12085, Stairs.class), - /** - * BlockData: {@link Fence} - */ - NETHER_BRICK_WALL(10398, Fence.class), - /** - * BlockData: {@link Orientable} - */ - NETHER_PORTAL(19469, Orientable.class), - NETHER_QUARTZ_ORE(4807), - NETHER_STAR(12469), - /** - * BlockData: {@link Ageable} - */ - NETHER_WART(29227, Ageable.class), - NETHER_WART_BLOCK(15486), - /** - * BlockData: {@link NoteBlock} - */ - NOTE_BLOCK(20979, NoteBlock.class), - OAK_BOAT(17570, 1), - /** - * BlockData: {@link Switch} - */ - OAK_BUTTON(13510, Switch.class), - /** - * BlockData: {@link Door} - */ - OAK_DOOR(20341, Door.class), - /** - * BlockData: {@link Fence} - */ - OAK_FENCE(6442, Fence.class), - /** - * BlockData: {@link Gate} - */ - OAK_FENCE_GATE(16689, Gate.class), - /** - * BlockData: {@link Leaves} - */ - OAK_LEAVES(4385, Leaves.class), - /** - * BlockData: {@link Orientable} - */ - OAK_LOG(26723, Orientable.class), - OAK_PLANKS(14905), - /** - * BlockData: {@link Powerable} - */ - OAK_PRESSURE_PLATE(20108, Powerable.class), - /** - * BlockData: {@link Sapling} - */ - OAK_SAPLING(9636, Sapling.class), - /** - * BlockData: {@link Sign} - */ - OAK_SIGN(8192, 16, Sign.class), - /** - * BlockData: {@link Slab} - */ - OAK_SLAB(12002, Slab.class), - /** - * BlockData: {@link Stairs} - */ - OAK_STAIRS(5449, Stairs.class), - /** - * BlockData: {@link TrapDoor} - */ - OAK_TRAPDOOR(16927, TrapDoor.class), - /** - * BlockData: {@link WallSign} - */ - OAK_WALL_SIGN(12984, 16, WallSign.class), - /** - * BlockData: {@link Orientable} - */ - OAK_WOOD(7378, Orientable.class), - /** - * BlockData: {@link Observer} - */ - OBSERVER(10726, Observer.class), - OBSIDIAN(32723), - OCELOT_SPAWN_EGG(30080), - /** - * BlockData: {@link Rotatable} - */ - ORANGE_BANNER(4839, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - ORANGE_BED(11194, 1, Bed.class), - ORANGE_CARPET(24752), - ORANGE_CONCRETE(19914), - ORANGE_CONCRETE_POWDER(30159), - ORANGE_DYE(13866), - /** - * BlockData: {@link Directional} - */ - ORANGE_GLAZED_TERRACOTTA(27451, Directional.class), - /** - * BlockData: {@link Directional} - */ - ORANGE_SHULKER_BOX(21673, 1, Directional.class), - ORANGE_STAINED_GLASS(25142), - /** - * BlockData: {@link GlassPane} - */ - ORANGE_STAINED_GLASS_PANE(21089, GlassPane.class), - ORANGE_TERRACOTTA(18684), - ORANGE_TULIP(26038), - /** - * BlockData: {@link Directional} - */ - ORANGE_WALL_BANNER(9936, Directional.class), - ORANGE_WOOL(23957), - OXEYE_DAISY(11709), - PACKED_ICE(28993), - PAINTING(23945), - PANDA_SPAWN_EGG(23759), - PAPER(9923), - PARROT_SPAWN_EGG(23614), - /** - * BlockData: {@link Bisected} - */ - PEONY(21155, Bisected.class), - /** - * BlockData: {@link Slab} - */ - PETRIFIED_OAK_SLAB(18658, Slab.class), - PHANTOM_MEMBRANE(18398), - PHANTOM_SPAWN_EGG(24648), - PIG_SPAWN_EGG(22584), - PILLAGER_SPAWN_EGG(28659), - /** - * BlockData: {@link Rotatable} - */ - PINK_BANNER(19439, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - PINK_BED(13795, 1, Bed.class), - PINK_CARPET(30186), - PINK_CONCRETE(5227), - PINK_CONCRETE_POWDER(6421), - PINK_DYE(31151), - /** - * BlockData: {@link Directional} - */ - PINK_GLAZED_TERRACOTTA(10260, Directional.class), - /** - * BlockData: {@link Directional} - */ - PINK_SHULKER_BOX(24968, 1, Directional.class), - PINK_STAINED_GLASS(16164), - /** - * BlockData: {@link GlassPane} - */ - PINK_STAINED_GLASS_PANE(24637, GlassPane.class), - PINK_TERRACOTTA(23727), - PINK_TULIP(27319), - /** - * BlockData: {@link Directional} - */ - PINK_WALL_BANNER(9421, Directional.class), - PINK_WOOL(7611), - /** - * BlockData: {@link Piston} - */ - PISTON(21130, Piston.class), - /** - * BlockData: {@link PistonHead} - */ - PISTON_HEAD(30226, PistonHead.class), - /** - * BlockData: {@link Rotatable} - */ - PLAYER_HEAD(21174, Rotatable.class), - /** - * BlockData: {@link Directional} - */ - PLAYER_WALL_HEAD(13164, Directional.class), - /** - * BlockData: {@link Snowable} - */ - PODZOL(24068, Snowable.class), - POISONOUS_POTATO(32640), - POLAR_BEAR_SPAWN_EGG(17015), - POLISHED_ANDESITE(8335), - /** - * BlockData: {@link Slab} - */ - POLISHED_ANDESITE_SLAB(24573, Slab.class), - /** - * BlockData: {@link Stairs} - */ - POLISHED_ANDESITE_STAIRS(7573, Stairs.class), - POLISHED_DIORITE(31615), - /** - * BlockData: {@link Slab} - */ - POLISHED_DIORITE_SLAB(18303, Slab.class), - /** - * BlockData: {@link Stairs} - */ - POLISHED_DIORITE_STAIRS(4625, Stairs.class), - POLISHED_GRANITE(5477), - /** - * BlockData: {@link Slab} - */ - POLISHED_GRANITE_SLAB(4521, Slab.class), - /** - * BlockData: {@link Stairs} - */ - POLISHED_GRANITE_STAIRS(29588, Stairs.class), - POPPED_CHORUS_FRUIT(27844), - POPPY(12851), - PORKCHOP(30896), - POTATO(21088), - /** - * BlockData: {@link Ageable} - */ - POTATOES(10879, Ageable.class), - POTION(24020, 1), - POTTED_ACACIA_SAPLING(14096), - POTTED_ALLIUM(13184), - POTTED_AZURE_BLUET(8754), - POTTED_BAMBOO(22542), - POTTED_BIRCH_SAPLING(32484), - POTTED_BLUE_ORCHID(6599), - POTTED_BROWN_MUSHROOM(14481), - POTTED_CACTUS(8777), - POTTED_CORNFLOWER(28917), - POTTED_DANDELION(9727), - POTTED_DARK_OAK_SAPLING(6486), - POTTED_DEAD_BUSH(13020), - POTTED_FERN(23315), - POTTED_JUNGLE_SAPLING(7525), - POTTED_LILY_OF_THE_VALLEY(9364), - POTTED_OAK_SAPLING(11905), - POTTED_ORANGE_TULIP(28807), - POTTED_OXEYE_DAISY(19707), - POTTED_PINK_TULIP(10089), - POTTED_POPPY(7457), - POTTED_RED_MUSHROOM(22881), - POTTED_RED_TULIP(28594), - POTTED_SPRUCE_SAPLING(29498), - POTTED_WHITE_TULIP(24330), - POTTED_WITHER_ROSE(26876), - /** - * BlockData: {@link RedstoneRail} - */ - POWERED_RAIL(11064, RedstoneRail.class), - PRISMARINE(7539), - PRISMARINE_BRICKS(29118), - /** - * BlockData: {@link Slab} - */ - PRISMARINE_BRICK_SLAB(26672, Slab.class), - /** - * BlockData: {@link Stairs} - */ - PRISMARINE_BRICK_STAIRS(15445, Stairs.class), - PRISMARINE_CRYSTALS(31546), - PRISMARINE_SHARD(10993), - /** - * BlockData: {@link Slab} - */ - PRISMARINE_SLAB(31323, Slab.class), - /** - * BlockData: {@link Stairs} - */ - PRISMARINE_STAIRS(19217, Stairs.class), - /** - * BlockData: {@link Fence} - */ - PRISMARINE_WALL(18184, Fence.class), - PUFFERFISH(8115), - PUFFERFISH_BUCKET(8861, 1), - PUFFERFISH_SPAWN_EGG(24570), - PUMPKIN(19170), - PUMPKIN_PIE(28725), - PUMPKIN_SEEDS(28985), - /** - * BlockData: {@link Ageable} - */ - PUMPKIN_STEM(19021, Ageable.class), - /** - * BlockData: {@link Rotatable} - */ - PURPLE_BANNER(29027, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - PURPLE_BED(29755, 1, Bed.class), - PURPLE_CARPET(5574), - PURPLE_CONCRETE(20623), - PURPLE_CONCRETE_POWDER(26808), - PURPLE_DYE(6347), - /** - * BlockData: {@link Directional} - */ - PURPLE_GLAZED_TERRACOTTA(4818, Directional.class), - /** - * BlockData: {@link Directional} - */ - PURPLE_SHULKER_BOX(10373, 1, Directional.class), - PURPLE_STAINED_GLASS(21845), - /** - * BlockData: {@link GlassPane} - */ - PURPLE_STAINED_GLASS_PANE(10948, GlassPane.class), - PURPLE_TERRACOTTA(10387), - /** - * BlockData: {@link Directional} - */ - PURPLE_WALL_BANNER(14298, Directional.class), - PURPLE_WOOL(11922), - PURPUR_BLOCK(7538), - /** - * BlockData: {@link Orientable} - */ - PURPUR_PILLAR(26718, Orientable.class), - /** - * BlockData: {@link Slab} - */ - PURPUR_SLAB(11487, Slab.class), - /** - * BlockData: {@link Stairs} - */ - PURPUR_STAIRS(8921, Stairs.class), - QUARTZ(23608), - QUARTZ_BLOCK(11987), - /** - * BlockData: {@link Orientable} - */ - QUARTZ_PILLAR(16452, Orientable.class), - /** - * BlockData: {@link Slab} - */ - QUARTZ_SLAB(4423, Slab.class), - /** - * BlockData: {@link Stairs} - */ - QUARTZ_STAIRS(24079, Stairs.class), - RABBIT(23068), - RABBIT_FOOT(13864), - RABBIT_HIDE(12467), - RABBIT_SPAWN_EGG(26496), - RABBIT_STEW(10611, 1), - /** - * BlockData: {@link Rail} - */ - RAIL(13285, Rail.class), - RAVAGER_SPAWN_EGG(8726), - REDSTONE(11233), - REDSTONE_BLOCK(19496), - /** - * BlockData: {@link Lightable} - */ - REDSTONE_LAMP(8217, Lightable.class), - /** - * BlockData: {@link Lightable} - */ - REDSTONE_ORE(10887, Lightable.class), - /** - * BlockData: {@link Lightable} - */ - REDSTONE_TORCH(22547, Lightable.class), - /** - * BlockData: {@link RedstoneWallTorch} - */ - REDSTONE_WALL_TORCH(7595, RedstoneWallTorch.class), - /** - * BlockData: {@link RedstoneWire} - */ - REDSTONE_WIRE(25984, RedstoneWire.class), - /** - * BlockData: {@link Rotatable} - */ - RED_BANNER(26961, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - RED_BED(30910, 1, Bed.class), - RED_CARPET(5424), - RED_CONCRETE(8032), - RED_CONCRETE_POWDER(13286), - RED_DYE(5728), - /** - * BlockData: {@link Directional} - */ - RED_GLAZED_TERRACOTTA(24989, Directional.class), - RED_MUSHROOM(19728), - /** - * BlockData: {@link MultipleFacing} - */ - RED_MUSHROOM_BLOCK(20766, MultipleFacing.class), - RED_NETHER_BRICKS(18056), - /** - * BlockData: {@link Slab} - */ - RED_NETHER_BRICK_SLAB(12462, Slab.class), - /** - * BlockData: {@link Stairs} - */ - RED_NETHER_BRICK_STAIRS(26374, Stairs.class), - /** - * BlockData: {@link Fence} - */ - RED_NETHER_BRICK_WALL(4580, Fence.class), - RED_SAND(16279), - RED_SANDSTONE(9092), - /** - * BlockData: {@link Slab} - */ - RED_SANDSTONE_SLAB(17550, Slab.class), - /** - * BlockData: {@link Stairs} - */ - RED_SANDSTONE_STAIRS(25466, Stairs.class), - /** - * BlockData: {@link Fence} - */ - RED_SANDSTONE_WALL(4753, Fence.class), - /** - * BlockData: {@link Directional} - */ - RED_SHULKER_BOX(32448, 1, Directional.class), - RED_STAINED_GLASS(9717), - /** - * BlockData: {@link GlassPane} - */ - RED_STAINED_GLASS_PANE(8630, GlassPane.class), - RED_TERRACOTTA(5086), - RED_TULIP(16781), - /** - * BlockData: {@link Directional} - */ - RED_WALL_BANNER(4378, Directional.class), - RED_WOOL(11621), - /** - * BlockData: {@link Repeater} - */ - REPEATER(28823, Repeater.class), - /** - * BlockData: {@link CommandBlock} - */ - REPEATING_COMMAND_BLOCK(12405, CommandBlock.class), - /** - * BlockData: {@link Bisected} - */ - ROSE_BUSH(6080, Bisected.class), - ROTTEN_FLESH(21591), - SADDLE(30206, 1), - SALMON(18516), - SALMON_BUCKET(31427, 1), - SALMON_SPAWN_EGG(18739), - SAND(11542), - SANDSTONE(13141), - /** - * BlockData: {@link Slab} - */ - SANDSTONE_SLAB(29830, Slab.class), - /** - * BlockData: {@link Stairs} - */ - SANDSTONE_STAIRS(18474, Stairs.class), - /** - * BlockData: {@link Fence} - */ - SANDSTONE_WALL(18470, Fence.class), - /** - * BlockData: {@link Scaffolding} - */ - SCAFFOLDING(15757, Scaffolding.class), - SCUTE(11914), - SEAGRASS(23942), - SEA_LANTERN(16984), - /** - * BlockData: {@link SeaPickle} - */ - SEA_PICKLE(19562, SeaPickle.class), - SHEARS(27971, 1, 238), - SHEEP_SPAWN_EGG(24488), - SHIELD(29943, 1, 336), - /** - * BlockData: {@link Directional} - */ - SHULKER_BOX(7776, 1, Directional.class), - SHULKER_SHELL(27848), - SHULKER_SPAWN_EGG(31848), - SILVERFISH_SPAWN_EGG(14537), - SKELETON_HORSE_SPAWN_EGG(21356), - /** - * BlockData: {@link Rotatable} - */ - SKELETON_SKULL(13270, Rotatable.class), - SKELETON_SPAWN_EGG(15261), - /** - * BlockData: {@link Directional} - */ - SKELETON_WALL_SKULL(31650, Directional.class), - SKULL_BANNER_PATTERN(7680, 1), - SLIME_BALL(5242), - SLIME_BLOCK(31892), - SLIME_SPAWN_EGG(6550), - SMITHING_TABLE(9082), - /** - * BlockData: {@link Furnace} - */ - SMOKER(24781, Furnace.class), - SMOOTH_QUARTZ(14415), - /** - * BlockData: {@link Slab} - */ - SMOOTH_QUARTZ_SLAB(26543, Slab.class), - /** - * BlockData: {@link Stairs} - */ - SMOOTH_QUARTZ_STAIRS(19560, Stairs.class), - SMOOTH_RED_SANDSTONE(25180), - /** - * BlockData: {@link Slab} - */ - SMOOTH_RED_SANDSTONE_SLAB(16304, Slab.class), - /** - * BlockData: {@link Stairs} - */ - SMOOTH_RED_SANDSTONE_STAIRS(17561, Stairs.class), - SMOOTH_SANDSTONE(30039), - /** - * BlockData: {@link Slab} - */ - SMOOTH_SANDSTONE_SLAB(9030, Slab.class), - /** - * BlockData: {@link Stairs} - */ - SMOOTH_SANDSTONE_STAIRS(21183, Stairs.class), - SMOOTH_STONE(21910), - /** - * BlockData: {@link Slab} - */ - SMOOTH_STONE_SLAB(24129, Slab.class), - /** - * BlockData: {@link Snow} - */ - SNOW(14146, Snow.class), - SNOWBALL(19487, 16), - SNOW_BLOCK(19913), - SOUL_SAND(16841), - SPAWNER(7018), - SPECTRAL_ARROW(4568), - SPIDER_EYE(9318), - SPIDER_SPAWN_EGG(14984), - SPLASH_POTION(30248, 1), - SPONGE(15860), - SPRUCE_BOAT(9606, 1), - /** - * BlockData: {@link Switch} - */ - SPRUCE_BUTTON(23281, Switch.class), - /** - * BlockData: {@link Door} - */ - SPRUCE_DOOR(10642, Door.class), - /** - * BlockData: {@link Fence} - */ - SPRUCE_FENCE(25416, Fence.class), - /** - * BlockData: {@link Gate} - */ - SPRUCE_FENCE_GATE(26423, Gate.class), - /** - * BlockData: {@link Leaves} - */ - SPRUCE_LEAVES(20039, Leaves.class), - /** - * BlockData: {@link Orientable} - */ - SPRUCE_LOG(9726, Orientable.class), - SPRUCE_PLANKS(14593), - /** - * BlockData: {@link Powerable} - */ - SPRUCE_PRESSURE_PLATE(15932, Powerable.class), - /** - * BlockData: {@link Sapling} - */ - SPRUCE_SAPLING(19874, Sapling.class), - /** - * BlockData: {@link Sign} - */ - SPRUCE_SIGN(21502, 16, Sign.class), - /** - * BlockData: {@link Slab} - */ - SPRUCE_SLAB(4348, Slab.class), - /** - * BlockData: {@link Stairs} - */ - SPRUCE_STAIRS(11192, Stairs.class), - /** - * BlockData: {@link TrapDoor} - */ - SPRUCE_TRAPDOOR(10289, TrapDoor.class), - /** - * BlockData: {@link WallSign} - */ - SPRUCE_WALL_SIGN(7352, 16, WallSign.class), - /** - * BlockData: {@link Orientable} - */ - SPRUCE_WOOD(32328, Orientable.class), - SQUID_SPAWN_EGG(10682), - STICK(9773), - /** - * BlockData: {@link Piston} - */ - STICKY_PISTON(18127, Piston.class), - STONE(22948), - /** - * BlockData: {@link Directional} - */ - STONECUTTER(25170, Directional.class), - STONE_AXE(6338, 1, 131), - STONE_BRICKS(6962), - /** - * BlockData: {@link Slab} - */ - STONE_BRICK_SLAB(19676, Slab.class), - /** - * BlockData: {@link Stairs} - */ - STONE_BRICK_STAIRS(27032, Stairs.class), - /** - * BlockData: {@link Fence} - */ - STONE_BRICK_WALL(29073, Fence.class), - /** - * BlockData: {@link Switch} - */ - STONE_BUTTON(12279, Switch.class), - STONE_HOE(22855, 1, 131), - STONE_PICKAXE(14611, 1, 131), - /** - * BlockData: {@link Powerable} - */ - STONE_PRESSURE_PLATE(22591, Powerable.class), - STONE_SHOVEL(9520, 1, 131), - /** - * BlockData: {@link Slab} - */ - STONE_SLAB(19838, Slab.class), - /** - * BlockData: {@link Stairs} - */ - STONE_STAIRS(23784, Stairs.class), - STONE_SWORD(25084, 1, 131), - STRAY_SPAWN_EGG(30153), - STRING(12806), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_ACACIA_LOG(18167, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_ACACIA_WOOD(27193, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_BIRCH_LOG(8838, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_BIRCH_WOOD(22350, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_DARK_OAK_LOG(6492, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_DARK_OAK_WOOD(16000, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_JUNGLE_LOG(15476, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_JUNGLE_WOOD(30315, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_OAK_LOG(20523, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_OAK_WOOD(31455, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_SPRUCE_LOG(6140, Orientable.class), - /** - * BlockData: {@link Orientable} - */ - STRIPPED_SPRUCE_WOOD(6467, Orientable.class), - /** - * BlockData: {@link StructureBlock} - */ - STRUCTURE_BLOCK(26831, StructureBlock.class), - STRUCTURE_VOID(30806), - SUGAR(30638), - /** - * BlockData: {@link Ageable} - */ - SUGAR_CANE(7726, Ageable.class), - /** - * BlockData: {@link Bisected} - */ - SUNFLOWER(7408, Bisected.class), - SUSPICIOUS_STEW(8173, 1), - SWEET_BERRIES(19747), - /** - * BlockData: {@link Ageable} - */ - SWEET_BERRY_BUSH(11958, Ageable.class), - /** - * BlockData: {@link Bisected} - */ - TALL_GRASS(21559, Bisected.class), - /** - * BlockData: {@link Bisected} - */ - TALL_SEAGRASS(27189, Bisected.class), - TERRACOTTA(16544), - TIPPED_ARROW(25164), - /** - * BlockData: {@link TNT} - */ - TNT(7896, TNT.class), - TNT_MINECART(4277, 1), - TORCH(6063), - TOTEM_OF_UNDYING(10139, 1), - TRADER_LLAMA_SPAWN_EGG(8439), - /** - * BlockData: {@link Chest} - */ - TRAPPED_CHEST(18970, Chest.class), - TRIDENT(7534, 1, 250), - /** - * BlockData: {@link Tripwire} - */ - TRIPWIRE(8810, Tripwire.class), - /** - * BlockData: {@link TripwireHook} - */ - TRIPWIRE_HOOK(8130, TripwireHook.class), - TROPICAL_FISH(24879), - TROPICAL_FISH_BUCKET(29995, 1), - TROPICAL_FISH_SPAWN_EGG(19713), - /** - * BlockData: {@link Waterlogged} - */ - TUBE_CORAL(23048, Waterlogged.class), - TUBE_CORAL_BLOCK(23723), - /** - * BlockData: {@link Waterlogged} - */ - TUBE_CORAL_FAN(19929, Waterlogged.class), - /** - * BlockData: {@link CoralWallFan} - */ - TUBE_CORAL_WALL_FAN(25282, CoralWallFan.class), - /** - * BlockData: {@link TurtleEgg} - */ - TURTLE_EGG(32101, TurtleEgg.class), - TURTLE_HELMET(30120, 1, 275), - TURTLE_SPAWN_EGG(17324), - VEX_SPAWN_EGG(27751), - VILLAGER_SPAWN_EGG(30348), - VINDICATOR_SPAWN_EGG(25324), - /** - * BlockData: {@link MultipleFacing} - */ - VINE(14564, MultipleFacing.class), - VOID_AIR(13668), - /** - * BlockData: {@link Directional} - */ - WALL_TORCH(25890, Directional.class), - WANDERING_TRADER_SPAWN_EGG(17904), - /** - * BlockData: {@link Levelled} - */ - WATER(24998, Levelled.class), - WATER_BUCKET(8802, 1), - WET_SPONGE(9043), - /** - * BlockData: {@link Ageable} - */ - WHEAT(27709, Ageable.class), - WHEAT_SEEDS(28742), - /** - * BlockData: {@link Rotatable} - */ - WHITE_BANNER(17562, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - WHITE_BED(8185, 1, Bed.class), - WHITE_CARPET(15117), - WHITE_CONCRETE(6281), - WHITE_CONCRETE_POWDER(10363), - WHITE_DYE(10758), - /** - * BlockData: {@link Directional} - */ - WHITE_GLAZED_TERRACOTTA(11326, Directional.class), - /** - * BlockData: {@link Directional} - */ - WHITE_SHULKER_BOX(31750, 1, Directional.class), - WHITE_STAINED_GLASS(31190), - /** - * BlockData: {@link GlassPane} - */ - WHITE_STAINED_GLASS_PANE(10557, GlassPane.class), - WHITE_TERRACOTTA(20975), - WHITE_TULIP(9742), - /** - * BlockData: {@link Directional} - */ - WHITE_WALL_BANNER(15967, Directional.class), - WHITE_WOOL(8624), - WITCH_SPAWN_EGG(11837), - WITHER_ROSE(8619), - /** - * BlockData: {@link Rotatable} - */ - WITHER_SKELETON_SKULL(31487, Rotatable.class), - WITHER_SKELETON_SPAWN_EGG(10073), - /** - * BlockData: {@link Directional} - */ - WITHER_SKELETON_WALL_SKULL(9326, Directional.class), - WOLF_SPAWN_EGG(21692), - WOODEN_AXE(6292, 1, 59), - WOODEN_HOE(16043, 1, 59), - WOODEN_PICKAXE(12792, 1, 59), - WOODEN_SHOVEL(28432, 1, 59), - WOODEN_SWORD(7175, 1, 59), - WRITABLE_BOOK(13393, 1), - WRITTEN_BOOK(24164, 16), - /** - * BlockData: {@link Rotatable} - */ - YELLOW_BANNER(30382, 16, Rotatable.class), - /** - * BlockData: {@link Bed} - */ - YELLOW_BED(30410, 1, Bed.class), - YELLOW_CARPET(18149), - YELLOW_CONCRETE(15722), - YELLOW_CONCRETE_POWDER(10655), - YELLOW_DYE(5952), - /** - * BlockData: {@link Directional} - */ - YELLOW_GLAZED_TERRACOTTA(10914, Directional.class), - /** - * BlockData: {@link Directional} - */ - YELLOW_SHULKER_BOX(28700, 1, Directional.class), - YELLOW_STAINED_GLASS(12182), - /** - * BlockData: {@link GlassPane} - */ - YELLOW_STAINED_GLASS_PANE(20298, GlassPane.class), - YELLOW_TERRACOTTA(32129), - /** - * BlockData: {@link Directional} - */ - YELLOW_WALL_BANNER(32004, Directional.class), - YELLOW_WOOL(29507), - /** - * BlockData: {@link Rotatable} - */ - ZOMBIE_HEAD(9304, Rotatable.class), - ZOMBIE_HORSE_SPAWN_EGG(4275), - ZOMBIE_PIGMAN_SPAWN_EGG(11531), - ZOMBIE_SPAWN_EGG(5814), - ZOMBIE_VILLAGER_SPAWN_EGG(10311), - /** - * BlockData: {@link Directional} - */ - ZOMBIE_WALL_HEAD(16296, Directional.class), - // ----- Legacy Separator ----- - @Deprecated - LEGACY_AIR(0, 0), - @Deprecated - LEGACY_STONE(1), - @Deprecated - LEGACY_GRASS(2), - @Deprecated - LEGACY_DIRT(3), - @Deprecated - LEGACY_COBBLESTONE(4), - @Deprecated - LEGACY_WOOD(5, org.bukkit.material.Wood.class), - @Deprecated - LEGACY_SAPLING(6, org.bukkit.material.Sapling.class), - @Deprecated - LEGACY_BEDROCK(7), - @Deprecated - LEGACY_WATER(8, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_STATIONARY_WATER(9, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_LAVA(10, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_STATIONARY_LAVA(11, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_SAND(12), - @Deprecated - LEGACY_GRAVEL(13), - @Deprecated - LEGACY_GOLD_ORE(14), - @Deprecated - LEGACY_IRON_ORE(15), - @Deprecated - LEGACY_COAL_ORE(16), - @Deprecated - LEGACY_LOG(17, org.bukkit.material.Tree.class), - @Deprecated - LEGACY_LEAVES(18, org.bukkit.material.Leaves.class), - @Deprecated - LEGACY_SPONGE(19), - @Deprecated - LEGACY_GLASS(20), - @Deprecated - LEGACY_LAPIS_ORE(21), - @Deprecated - LEGACY_LAPIS_BLOCK(22), - @Deprecated - LEGACY_DISPENSER(23, org.bukkit.material.Dispenser.class), - @Deprecated - LEGACY_SANDSTONE(24, org.bukkit.material.Sandstone.class), - @Deprecated - LEGACY_NOTE_BLOCK(25), - @Deprecated - LEGACY_BED_BLOCK(26, org.bukkit.material.Bed.class), - @Deprecated - LEGACY_POWERED_RAIL(27, org.bukkit.material.PoweredRail.class), - @Deprecated - LEGACY_DETECTOR_RAIL(28, org.bukkit.material.DetectorRail.class), - @Deprecated - LEGACY_PISTON_STICKY_BASE(29, org.bukkit.material.PistonBaseMaterial.class), - @Deprecated - LEGACY_WEB(30), - @Deprecated - LEGACY_LONG_GRASS(31, org.bukkit.material.LongGrass.class), - @Deprecated - LEGACY_DEAD_BUSH(32), - @Deprecated - LEGACY_PISTON_BASE(33, org.bukkit.material.PistonBaseMaterial.class), - @Deprecated - LEGACY_PISTON_EXTENSION(34, org.bukkit.material.PistonExtensionMaterial.class), - @Deprecated - LEGACY_WOOL(35, org.bukkit.material.Wool.class), - @Deprecated - LEGACY_PISTON_MOVING_PIECE(36), - @Deprecated - LEGACY_YELLOW_FLOWER(37), - @Deprecated - LEGACY_RED_ROSE(38), - @Deprecated - LEGACY_BROWN_MUSHROOM(39), - @Deprecated - LEGACY_RED_MUSHROOM(40), - @Deprecated - LEGACY_GOLD_BLOCK(41), - @Deprecated - LEGACY_IRON_BLOCK(42), - @Deprecated - LEGACY_DOUBLE_STEP(43, org.bukkit.material.Step.class), - @Deprecated - LEGACY_STEP(44, org.bukkit.material.Step.class), - @Deprecated - LEGACY_BRICK(45), - @Deprecated - LEGACY_TNT(46), - @Deprecated - LEGACY_BOOKSHELF(47), - @Deprecated - LEGACY_MOSSY_COBBLESTONE(48), - @Deprecated - LEGACY_OBSIDIAN(49), - @Deprecated - LEGACY_TORCH(50, org.bukkit.material.Torch.class), - @Deprecated - LEGACY_FIRE(51), - @Deprecated - LEGACY_MOB_SPAWNER(52), - @Deprecated - LEGACY_WOOD_STAIRS(53, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_CHEST(54, org.bukkit.material.Chest.class), - @Deprecated - LEGACY_REDSTONE_WIRE(55, org.bukkit.material.RedstoneWire.class), - @Deprecated - LEGACY_DIAMOND_ORE(56), - @Deprecated - LEGACY_DIAMOND_BLOCK(57), - @Deprecated - LEGACY_WORKBENCH(58), - @Deprecated - LEGACY_CROPS(59, org.bukkit.material.Crops.class), - @Deprecated - LEGACY_SOIL(60, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_FURNACE(61, org.bukkit.material.Furnace.class), - @Deprecated - LEGACY_BURNING_FURNACE(62, org.bukkit.material.Furnace.class), - @Deprecated - LEGACY_SIGN_POST(63, 64, org.bukkit.material.Sign.class), - @Deprecated - LEGACY_WOODEN_DOOR(64, org.bukkit.material.Door.class), - @Deprecated - LEGACY_LADDER(65, org.bukkit.material.Ladder.class), - @Deprecated - LEGACY_RAILS(66, org.bukkit.material.Rails.class), - @Deprecated - LEGACY_COBBLESTONE_STAIRS(67, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_WALL_SIGN(68, 64, org.bukkit.material.Sign.class), - @Deprecated - LEGACY_LEVER(69, org.bukkit.material.Lever.class), - @Deprecated - LEGACY_STONE_PLATE(70, org.bukkit.material.PressurePlate.class), - @Deprecated - LEGACY_IRON_DOOR_BLOCK(71, org.bukkit.material.Door.class), - @Deprecated - LEGACY_WOOD_PLATE(72, org.bukkit.material.PressurePlate.class), - @Deprecated - LEGACY_REDSTONE_ORE(73), - @Deprecated - LEGACY_GLOWING_REDSTONE_ORE(74), - @Deprecated - LEGACY_REDSTONE_TORCH_OFF(75, org.bukkit.material.RedstoneTorch.class), - @Deprecated - LEGACY_REDSTONE_TORCH_ON(76, org.bukkit.material.RedstoneTorch.class), - @Deprecated - LEGACY_STONE_BUTTON(77, org.bukkit.material.Button.class), - @Deprecated - LEGACY_SNOW(78), - @Deprecated - LEGACY_ICE(79), - @Deprecated - LEGACY_SNOW_BLOCK(80), - @Deprecated - LEGACY_CACTUS(81, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_CLAY(82), - @Deprecated - LEGACY_SUGAR_CANE_BLOCK(83, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_JUKEBOX(84), - @Deprecated - LEGACY_FENCE(85), - @Deprecated - LEGACY_PUMPKIN(86, org.bukkit.material.Pumpkin.class), - @Deprecated - LEGACY_NETHERRACK(87), - @Deprecated - LEGACY_SOUL_SAND(88), - @Deprecated - LEGACY_GLOWSTONE(89), - @Deprecated - LEGACY_PORTAL(90), - @Deprecated - LEGACY_JACK_O_LANTERN(91, org.bukkit.material.Pumpkin.class), - @Deprecated - LEGACY_CAKE_BLOCK(92, 64, org.bukkit.material.Cake.class), - @Deprecated - LEGACY_DIODE_BLOCK_OFF(93, org.bukkit.material.Diode.class), - @Deprecated - LEGACY_DIODE_BLOCK_ON(94, org.bukkit.material.Diode.class), - @Deprecated - LEGACY_STAINED_GLASS(95), - @Deprecated - LEGACY_TRAP_DOOR(96, org.bukkit.material.TrapDoor.class), - @Deprecated - LEGACY_MONSTER_EGGS(97, org.bukkit.material.MonsterEggs.class), - @Deprecated - LEGACY_SMOOTH_BRICK(98, org.bukkit.material.SmoothBrick.class), - @Deprecated - LEGACY_HUGE_MUSHROOM_1(99, org.bukkit.material.Mushroom.class), - @Deprecated - LEGACY_HUGE_MUSHROOM_2(100, org.bukkit.material.Mushroom.class), - @Deprecated - LEGACY_IRON_FENCE(101), - @Deprecated - LEGACY_THIN_GLASS(102), - @Deprecated - LEGACY_MELON_BLOCK(103), - @Deprecated - LEGACY_PUMPKIN_STEM(104, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_MELON_STEM(105, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_VINE(106, org.bukkit.material.Vine.class), - @Deprecated - LEGACY_FENCE_GATE(107, org.bukkit.material.Gate.class), - @Deprecated - LEGACY_BRICK_STAIRS(108, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_SMOOTH_STAIRS(109, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_MYCEL(110), - @Deprecated - LEGACY_WATER_LILY(111), - @Deprecated - LEGACY_NETHER_BRICK(112), - @Deprecated - LEGACY_NETHER_FENCE(113), - @Deprecated - LEGACY_NETHER_BRICK_STAIRS(114, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_NETHER_WARTS(115, org.bukkit.material.NetherWarts.class), - @Deprecated - LEGACY_ENCHANTMENT_TABLE(116), - @Deprecated - LEGACY_BREWING_STAND(117, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_CAULDRON(118, org.bukkit.material.Cauldron.class), - @Deprecated - LEGACY_ENDER_PORTAL(119), - @Deprecated - LEGACY_ENDER_PORTAL_FRAME(120), - @Deprecated - LEGACY_ENDER_STONE(121), - @Deprecated - LEGACY_DRAGON_EGG(122), - @Deprecated - LEGACY_REDSTONE_LAMP_OFF(123), - @Deprecated - LEGACY_REDSTONE_LAMP_ON(124), - @Deprecated - LEGACY_WOOD_DOUBLE_STEP(125, org.bukkit.material.Wood.class), - @Deprecated - LEGACY_WOOD_STEP(126, org.bukkit.material.WoodenStep.class), - @Deprecated - LEGACY_COCOA(127, org.bukkit.material.CocoaPlant.class), - @Deprecated - LEGACY_SANDSTONE_STAIRS(128, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_EMERALD_ORE(129), - @Deprecated - LEGACY_ENDER_CHEST(130, org.bukkit.material.EnderChest.class), - @Deprecated - LEGACY_TRIPWIRE_HOOK(131, org.bukkit.material.TripwireHook.class), - @Deprecated - LEGACY_TRIPWIRE(132, org.bukkit.material.Tripwire.class), - @Deprecated - LEGACY_EMERALD_BLOCK(133), - @Deprecated - LEGACY_SPRUCE_WOOD_STAIRS(134, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_BIRCH_WOOD_STAIRS(135, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_JUNGLE_WOOD_STAIRS(136, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_COMMAND(137, org.bukkit.material.Command.class), - @Deprecated - LEGACY_BEACON(138), - @Deprecated - LEGACY_COBBLE_WALL(139), - @Deprecated - LEGACY_FLOWER_POT(140, org.bukkit.material.FlowerPot.class), - @Deprecated - LEGACY_CARROT(141, org.bukkit.material.Crops.class), - @Deprecated - LEGACY_POTATO(142, org.bukkit.material.Crops.class), - @Deprecated - LEGACY_WOOD_BUTTON(143, org.bukkit.material.Button.class), - @Deprecated - LEGACY_SKULL(144, org.bukkit.material.Skull.class), - @Deprecated - LEGACY_ANVIL(145), - @Deprecated - LEGACY_TRAPPED_CHEST(146, org.bukkit.material.Chest.class), - @Deprecated - LEGACY_GOLD_PLATE(147), - @Deprecated - LEGACY_IRON_PLATE(148), - @Deprecated - LEGACY_REDSTONE_COMPARATOR_OFF(149, org.bukkit.material.Comparator.class), - @Deprecated - LEGACY_REDSTONE_COMPARATOR_ON(150, org.bukkit.material.Comparator.class), - @Deprecated - LEGACY_DAYLIGHT_DETECTOR(151), - @Deprecated - LEGACY_REDSTONE_BLOCK(152), - @Deprecated - LEGACY_QUARTZ_ORE(153), - @Deprecated - LEGACY_HOPPER(154, org.bukkit.material.Hopper.class), - @Deprecated - LEGACY_QUARTZ_BLOCK(155), - @Deprecated - LEGACY_QUARTZ_STAIRS(156, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_ACTIVATOR_RAIL(157, org.bukkit.material.PoweredRail.class), - @Deprecated - LEGACY_DROPPER(158, org.bukkit.material.Dispenser.class), - @Deprecated - LEGACY_STAINED_CLAY(159), - @Deprecated - LEGACY_STAINED_GLASS_PANE(160), - @Deprecated - LEGACY_LEAVES_2(161, org.bukkit.material.Leaves.class), - @Deprecated - LEGACY_LOG_2(162, org.bukkit.material.Tree.class), - @Deprecated - LEGACY_ACACIA_STAIRS(163, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_DARK_OAK_STAIRS(164, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_SLIME_BLOCK(165), - @Deprecated - LEGACY_BARRIER(166), - @Deprecated - LEGACY_IRON_TRAPDOOR(167, org.bukkit.material.TrapDoor.class), - @Deprecated - LEGACY_PRISMARINE(168), - @Deprecated - LEGACY_SEA_LANTERN(169), - @Deprecated - LEGACY_HAY_BLOCK(170), - @Deprecated - LEGACY_CARPET(171), - @Deprecated - LEGACY_HARD_CLAY(172), - @Deprecated - LEGACY_COAL_BLOCK(173), - @Deprecated - LEGACY_PACKED_ICE(174), - @Deprecated - LEGACY_DOUBLE_PLANT(175), - @Deprecated - LEGACY_STANDING_BANNER(176, org.bukkit.material.Banner.class), - @Deprecated - LEGACY_WALL_BANNER(177, org.bukkit.material.Banner.class), - @Deprecated - LEGACY_DAYLIGHT_DETECTOR_INVERTED(178), - @Deprecated - LEGACY_RED_SANDSTONE(179), - @Deprecated - LEGACY_RED_SANDSTONE_STAIRS(180, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_DOUBLE_STONE_SLAB2(181), - @Deprecated - LEGACY_STONE_SLAB2(182), - @Deprecated - LEGACY_SPRUCE_FENCE_GATE(183, org.bukkit.material.Gate.class), - @Deprecated - LEGACY_BIRCH_FENCE_GATE(184, org.bukkit.material.Gate.class), - @Deprecated - LEGACY_JUNGLE_FENCE_GATE(185, org.bukkit.material.Gate.class), - @Deprecated - LEGACY_DARK_OAK_FENCE_GATE(186, org.bukkit.material.Gate.class), - @Deprecated - LEGACY_ACACIA_FENCE_GATE(187, org.bukkit.material.Gate.class), - @Deprecated - LEGACY_SPRUCE_FENCE(188), - @Deprecated - LEGACY_BIRCH_FENCE(189), - @Deprecated - LEGACY_JUNGLE_FENCE(190), - @Deprecated - LEGACY_DARK_OAK_FENCE(191), - @Deprecated - LEGACY_ACACIA_FENCE(192), - @Deprecated - LEGACY_SPRUCE_DOOR(193, org.bukkit.material.Door.class), - @Deprecated - LEGACY_BIRCH_DOOR(194, org.bukkit.material.Door.class), - @Deprecated - LEGACY_JUNGLE_DOOR(195, org.bukkit.material.Door.class), - @Deprecated - LEGACY_ACACIA_DOOR(196, org.bukkit.material.Door.class), - @Deprecated - LEGACY_DARK_OAK_DOOR(197, org.bukkit.material.Door.class), - @Deprecated - LEGACY_END_ROD(198), - @Deprecated - LEGACY_CHORUS_PLANT(199), - @Deprecated - LEGACY_CHORUS_FLOWER(200), - @Deprecated - LEGACY_PURPUR_BLOCK(201), - @Deprecated - LEGACY_PURPUR_PILLAR(202), - @Deprecated - LEGACY_PURPUR_STAIRS(203, org.bukkit.material.Stairs.class), - @Deprecated - LEGACY_PURPUR_DOUBLE_SLAB(204), - @Deprecated - LEGACY_PURPUR_SLAB(205), - @Deprecated - LEGACY_END_BRICKS(206), - @Deprecated - LEGACY_BEETROOT_BLOCK(207, org.bukkit.material.Crops.class), - @Deprecated - LEGACY_GRASS_PATH(208), - @Deprecated - LEGACY_END_GATEWAY(209), - @Deprecated - LEGACY_COMMAND_REPEATING(210, org.bukkit.material.Command.class), - @Deprecated - LEGACY_COMMAND_CHAIN(211, org.bukkit.material.Command.class), - @Deprecated - LEGACY_FROSTED_ICE(212), - @Deprecated - LEGACY_MAGMA(213), - @Deprecated - LEGACY_NETHER_WART_BLOCK(214), - @Deprecated - LEGACY_RED_NETHER_BRICK(215), - @Deprecated - LEGACY_BONE_BLOCK(216), - @Deprecated - LEGACY_STRUCTURE_VOID(217), - @Deprecated - LEGACY_OBSERVER(218, org.bukkit.material.Observer.class), - @Deprecated - LEGACY_WHITE_SHULKER_BOX(219, 1), - @Deprecated - LEGACY_ORANGE_SHULKER_BOX(220, 1), - @Deprecated - LEGACY_MAGENTA_SHULKER_BOX(221, 1), - @Deprecated - LEGACY_LIGHT_BLUE_SHULKER_BOX(222, 1), - @Deprecated - LEGACY_YELLOW_SHULKER_BOX(223, 1), - @Deprecated - LEGACY_LIME_SHULKER_BOX(224, 1), - @Deprecated - LEGACY_PINK_SHULKER_BOX(225, 1), - @Deprecated - LEGACY_GRAY_SHULKER_BOX(226, 1), - @Deprecated - LEGACY_SILVER_SHULKER_BOX(227, 1), - @Deprecated - LEGACY_CYAN_SHULKER_BOX(228, 1), - @Deprecated - LEGACY_PURPLE_SHULKER_BOX(229, 1), - @Deprecated - LEGACY_BLUE_SHULKER_BOX(230, 1), - @Deprecated - LEGACY_BROWN_SHULKER_BOX(231, 1), - @Deprecated - LEGACY_GREEN_SHULKER_BOX(232, 1), - @Deprecated - LEGACY_RED_SHULKER_BOX(233, 1), - @Deprecated - LEGACY_BLACK_SHULKER_BOX(234, 1), - @Deprecated - LEGACY_WHITE_GLAZED_TERRACOTTA(235), - @Deprecated - LEGACY_ORANGE_GLAZED_TERRACOTTA(236), - @Deprecated - LEGACY_MAGENTA_GLAZED_TERRACOTTA(237), - @Deprecated - LEGACY_LIGHT_BLUE_GLAZED_TERRACOTTA(238), - @Deprecated - LEGACY_YELLOW_GLAZED_TERRACOTTA(239), - @Deprecated - LEGACY_LIME_GLAZED_TERRACOTTA(240), - @Deprecated - LEGACY_PINK_GLAZED_TERRACOTTA(241), - @Deprecated - LEGACY_GRAY_GLAZED_TERRACOTTA(242), - @Deprecated - LEGACY_SILVER_GLAZED_TERRACOTTA(243), - @Deprecated - LEGACY_CYAN_GLAZED_TERRACOTTA(244), - @Deprecated - LEGACY_PURPLE_GLAZED_TERRACOTTA(245), - @Deprecated - LEGACY_BLUE_GLAZED_TERRACOTTA(246), - @Deprecated - LEGACY_BROWN_GLAZED_TERRACOTTA(247), - @Deprecated - LEGACY_GREEN_GLAZED_TERRACOTTA(248), - @Deprecated - LEGACY_RED_GLAZED_TERRACOTTA(249), - @Deprecated - LEGACY_BLACK_GLAZED_TERRACOTTA(250), - @Deprecated - LEGACY_CONCRETE(251), - @Deprecated - LEGACY_CONCRETE_POWDER(252), - @Deprecated - LEGACY_STRUCTURE_BLOCK(255), - // ----- Item Separator ----- - @Deprecated - LEGACY_IRON_SPADE(256, 1, 250), - @Deprecated - LEGACY_IRON_PICKAXE(257, 1, 250), - @Deprecated - LEGACY_IRON_AXE(258, 1, 250), - @Deprecated - LEGACY_FLINT_AND_STEEL(259, 1, 64), - @Deprecated - LEGACY_APPLE(260), - @Deprecated - LEGACY_BOW(261, 1, 384), - @Deprecated - LEGACY_ARROW(262), - @Deprecated - LEGACY_COAL(263, org.bukkit.material.Coal.class), - @Deprecated - LEGACY_DIAMOND(264), - @Deprecated - LEGACY_IRON_INGOT(265), - @Deprecated - LEGACY_GOLD_INGOT(266), - @Deprecated - LEGACY_IRON_SWORD(267, 1, 250), - @Deprecated - LEGACY_WOOD_SWORD(268, 1, 59), - @Deprecated - LEGACY_WOOD_SPADE(269, 1, 59), - @Deprecated - LEGACY_WOOD_PICKAXE(270, 1, 59), - @Deprecated - LEGACY_WOOD_AXE(271, 1, 59), - @Deprecated - LEGACY_STONE_SWORD(272, 1, 131), - @Deprecated - LEGACY_STONE_SPADE(273, 1, 131), - @Deprecated - LEGACY_STONE_PICKAXE(274, 1, 131), - @Deprecated - LEGACY_STONE_AXE(275, 1, 131), - @Deprecated - LEGACY_DIAMOND_SWORD(276, 1, 1561), - @Deprecated - LEGACY_DIAMOND_SPADE(277, 1, 1561), - @Deprecated - LEGACY_DIAMOND_PICKAXE(278, 1, 1561), - @Deprecated - LEGACY_DIAMOND_AXE(279, 1, 1561), - @Deprecated - LEGACY_STICK(280), - @Deprecated - LEGACY_BOWL(281), - @Deprecated - LEGACY_MUSHROOM_SOUP(282, 1), - @Deprecated - LEGACY_GOLD_SWORD(283, 1, 32), - @Deprecated - LEGACY_GOLD_SPADE(284, 1, 32), - @Deprecated - LEGACY_GOLD_PICKAXE(285, 1, 32), - @Deprecated - LEGACY_GOLD_AXE(286, 1, 32), - @Deprecated - LEGACY_STRING(287), - @Deprecated - LEGACY_FEATHER(288), - @Deprecated - LEGACY_SULPHUR(289), - @Deprecated - LEGACY_WOOD_HOE(290, 1, 59), - @Deprecated - LEGACY_STONE_HOE(291, 1, 131), - @Deprecated - LEGACY_IRON_HOE(292, 1, 250), - @Deprecated - LEGACY_DIAMOND_HOE(293, 1, 1561), - @Deprecated - LEGACY_GOLD_HOE(294, 1, 32), - @Deprecated - LEGACY_SEEDS(295), - @Deprecated - LEGACY_WHEAT(296), - @Deprecated - LEGACY_BREAD(297), - @Deprecated - LEGACY_LEATHER_HELMET(298, 1, 55), - @Deprecated - LEGACY_LEATHER_CHESTPLATE(299, 1, 80), - @Deprecated - LEGACY_LEATHER_LEGGINGS(300, 1, 75), - @Deprecated - LEGACY_LEATHER_BOOTS(301, 1, 65), - @Deprecated - LEGACY_CHAINMAIL_HELMET(302, 1, 165), - @Deprecated - LEGACY_CHAINMAIL_CHESTPLATE(303, 1, 240), - @Deprecated - LEGACY_CHAINMAIL_LEGGINGS(304, 1, 225), - @Deprecated - LEGACY_CHAINMAIL_BOOTS(305, 1, 195), - @Deprecated - LEGACY_IRON_HELMET(306, 1, 165), - @Deprecated - LEGACY_IRON_CHESTPLATE(307, 1, 240), - @Deprecated - LEGACY_IRON_LEGGINGS(308, 1, 225), - @Deprecated - LEGACY_IRON_BOOTS(309, 1, 195), - @Deprecated - LEGACY_DIAMOND_HELMET(310, 1, 363), - @Deprecated - LEGACY_DIAMOND_CHESTPLATE(311, 1, 528), - @Deprecated - LEGACY_DIAMOND_LEGGINGS(312, 1, 495), - @Deprecated - LEGACY_DIAMOND_BOOTS(313, 1, 429), - @Deprecated - LEGACY_GOLD_HELMET(314, 1, 77), - @Deprecated - LEGACY_GOLD_CHESTPLATE(315, 1, 112), - @Deprecated - LEGACY_GOLD_LEGGINGS(316, 1, 105), - @Deprecated - LEGACY_GOLD_BOOTS(317, 1, 91), - @Deprecated - LEGACY_FLINT(318), - @Deprecated - LEGACY_PORK(319), - @Deprecated - LEGACY_GRILLED_PORK(320), - @Deprecated - LEGACY_PAINTING(321), - @Deprecated - LEGACY_GOLDEN_APPLE(322), - @Deprecated - LEGACY_SIGN(323, 16), - @Deprecated - LEGACY_WOOD_DOOR(324, 64), - @Deprecated - LEGACY_BUCKET(325, 16), - @Deprecated - LEGACY_WATER_BUCKET(326, 1), - @Deprecated - LEGACY_LAVA_BUCKET(327, 1), - @Deprecated - LEGACY_MINECART(328, 1), - @Deprecated - LEGACY_SADDLE(329, 1), - @Deprecated - LEGACY_IRON_DOOR(330, 64), - @Deprecated - LEGACY_REDSTONE(331), - @Deprecated - LEGACY_SNOW_BALL(332, 16), - @Deprecated - LEGACY_BOAT(333, 1), - @Deprecated - LEGACY_LEATHER(334), - @Deprecated - LEGACY_MILK_BUCKET(335, 1), - @Deprecated - LEGACY_CLAY_BRICK(336), - @Deprecated - LEGACY_CLAY_BALL(337), - @Deprecated - LEGACY_SUGAR_CANE(338), - @Deprecated - LEGACY_PAPER(339), - @Deprecated - LEGACY_BOOK(340), - @Deprecated - LEGACY_SLIME_BALL(341), - @Deprecated - LEGACY_STORAGE_MINECART(342, 1), - @Deprecated - LEGACY_POWERED_MINECART(343, 1), - @Deprecated - LEGACY_EGG(344, 16), - @Deprecated - LEGACY_COMPASS(345), - @Deprecated - LEGACY_FISHING_ROD(346, 1, 64), - @Deprecated - LEGACY_WATCH(347), - @Deprecated - LEGACY_GLOWSTONE_DUST(348), - @Deprecated - LEGACY_RAW_FISH(349), - @Deprecated - LEGACY_COOKED_FISH(350), - @Deprecated - LEGACY_INK_SACK(351, org.bukkit.material.Dye.class), - @Deprecated - LEGACY_BONE(352), - @Deprecated - LEGACY_SUGAR(353), - @Deprecated - LEGACY_CAKE(354, 1), - @Deprecated - LEGACY_BED(355, 1), - @Deprecated - LEGACY_DIODE(356), - @Deprecated - LEGACY_COOKIE(357), - /** - * @see org.bukkit.map.MapView - */ - @Deprecated - LEGACY_MAP(358, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_SHEARS(359, 1, 238), - @Deprecated - LEGACY_MELON(360), - @Deprecated - LEGACY_PUMPKIN_SEEDS(361), - @Deprecated - LEGACY_MELON_SEEDS(362), - @Deprecated - LEGACY_RAW_BEEF(363), - @Deprecated - LEGACY_COOKED_BEEF(364), - @Deprecated - LEGACY_RAW_CHICKEN(365), - @Deprecated - LEGACY_COOKED_CHICKEN(366), - @Deprecated - LEGACY_ROTTEN_FLESH(367), - @Deprecated - LEGACY_ENDER_PEARL(368, 16), - @Deprecated - LEGACY_BLAZE_ROD(369), - @Deprecated - LEGACY_GHAST_TEAR(370), - @Deprecated - LEGACY_GOLD_NUGGET(371), - @Deprecated - LEGACY_NETHER_STALK(372), - @Deprecated - LEGACY_POTION(373, 1, org.bukkit.material.MaterialData.class), - @Deprecated - LEGACY_GLASS_BOTTLE(374), - @Deprecated - LEGACY_SPIDER_EYE(375), - @Deprecated - LEGACY_FERMENTED_SPIDER_EYE(376), - @Deprecated - LEGACY_BLAZE_POWDER(377), - @Deprecated - LEGACY_MAGMA_CREAM(378), - @Deprecated - LEGACY_BREWING_STAND_ITEM(379), - @Deprecated - LEGACY_CAULDRON_ITEM(380), - @Deprecated - LEGACY_EYE_OF_ENDER(381), - @Deprecated - LEGACY_SPECKLED_MELON(382), - @Deprecated - LEGACY_MONSTER_EGG(383, 64, org.bukkit.material.SpawnEgg.class), - @Deprecated - LEGACY_EXP_BOTTLE(384, 64), - @Deprecated - LEGACY_FIREBALL(385, 64), - @Deprecated - LEGACY_BOOK_AND_QUILL(386, 1), - @Deprecated - LEGACY_WRITTEN_BOOK(387, 16), - @Deprecated - LEGACY_EMERALD(388, 64), - @Deprecated - LEGACY_ITEM_FRAME(389), - @Deprecated - LEGACY_FLOWER_POT_ITEM(390), - @Deprecated - LEGACY_CARROT_ITEM(391), - @Deprecated - LEGACY_POTATO_ITEM(392), - @Deprecated - LEGACY_BAKED_POTATO(393), - @Deprecated - LEGACY_POISONOUS_POTATO(394), - @Deprecated - LEGACY_EMPTY_MAP(395), - @Deprecated - LEGACY_GOLDEN_CARROT(396), - @Deprecated - LEGACY_SKULL_ITEM(397), - @Deprecated - LEGACY_CARROT_STICK(398, 1, 25), - @Deprecated - LEGACY_NETHER_STAR(399), - @Deprecated - LEGACY_PUMPKIN_PIE(400), - @Deprecated - LEGACY_FIREWORK(401), - @Deprecated - LEGACY_FIREWORK_CHARGE(402), - @Deprecated - LEGACY_ENCHANTED_BOOK(403, 1), - @Deprecated - LEGACY_REDSTONE_COMPARATOR(404), - @Deprecated - LEGACY_NETHER_BRICK_ITEM(405), - @Deprecated - LEGACY_QUARTZ(406), - @Deprecated - LEGACY_EXPLOSIVE_MINECART(407, 1), - @Deprecated - LEGACY_HOPPER_MINECART(408, 1), - @Deprecated - LEGACY_PRISMARINE_SHARD(409), - @Deprecated - LEGACY_PRISMARINE_CRYSTALS(410), - @Deprecated - LEGACY_RABBIT(411), - @Deprecated - LEGACY_COOKED_RABBIT(412), - @Deprecated - LEGACY_RABBIT_STEW(413, 1), - @Deprecated - LEGACY_RABBIT_FOOT(414), - @Deprecated - LEGACY_RABBIT_HIDE(415), - @Deprecated - LEGACY_ARMOR_STAND(416, 16), - @Deprecated - LEGACY_IRON_BARDING(417, 1), - @Deprecated - LEGACY_GOLD_BARDING(418, 1), - @Deprecated - LEGACY_DIAMOND_BARDING(419, 1), - @Deprecated - LEGACY_LEASH(420), - @Deprecated - LEGACY_NAME_TAG(421), - @Deprecated - LEGACY_COMMAND_MINECART(422, 1), - @Deprecated - LEGACY_MUTTON(423), - @Deprecated - LEGACY_COOKED_MUTTON(424), - @Deprecated - LEGACY_BANNER(425, 16), - @Deprecated - LEGACY_END_CRYSTAL(426), - @Deprecated - LEGACY_SPRUCE_DOOR_ITEM(427), - @Deprecated - LEGACY_BIRCH_DOOR_ITEM(428), - @Deprecated - LEGACY_JUNGLE_DOOR_ITEM(429), - @Deprecated - LEGACY_ACACIA_DOOR_ITEM(430), - @Deprecated - LEGACY_DARK_OAK_DOOR_ITEM(431), - @Deprecated - LEGACY_CHORUS_FRUIT(432), - @Deprecated - LEGACY_CHORUS_FRUIT_POPPED(433), - @Deprecated - LEGACY_BEETROOT(434), - @Deprecated - LEGACY_BEETROOT_SEEDS(435), - @Deprecated - LEGACY_BEETROOT_SOUP(436, 1), - @Deprecated - LEGACY_DRAGONS_BREATH(437), - @Deprecated - LEGACY_SPLASH_POTION(438, 1), - @Deprecated - LEGACY_SPECTRAL_ARROW(439), - @Deprecated - LEGACY_TIPPED_ARROW(440), - @Deprecated - LEGACY_LINGERING_POTION(441, 1), - @Deprecated - LEGACY_SHIELD(442, 1, 336), - @Deprecated - LEGACY_ELYTRA(443, 1, 431), - @Deprecated - LEGACY_BOAT_SPRUCE(444, 1), - @Deprecated - LEGACY_BOAT_BIRCH(445, 1), - @Deprecated - LEGACY_BOAT_JUNGLE(446, 1), - @Deprecated - LEGACY_BOAT_ACACIA(447, 1), - @Deprecated - LEGACY_BOAT_DARK_OAK(448, 1), - @Deprecated - LEGACY_TOTEM(449, 1), - @Deprecated - LEGACY_SHULKER_SHELL(450), - @Deprecated - LEGACY_IRON_NUGGET(452), - @Deprecated - LEGACY_KNOWLEDGE_BOOK(453, 1), - @Deprecated - LEGACY_GOLD_RECORD(2256, 1), - @Deprecated - LEGACY_GREEN_RECORD(2257, 1), - @Deprecated - LEGACY_RECORD_3(2258, 1), - @Deprecated - LEGACY_RECORD_4(2259, 1), - @Deprecated - LEGACY_RECORD_5(2260, 1), - @Deprecated - LEGACY_RECORD_6(2261, 1), - @Deprecated - LEGACY_RECORD_7(2262, 1), - @Deprecated - LEGACY_RECORD_8(2263, 1), - @Deprecated - LEGACY_RECORD_9(2264, 1), - @Deprecated - LEGACY_RECORD_10(2265, 1), - @Deprecated - LEGACY_RECORD_11(2266, 1), - @Deprecated - LEGACY_RECORD_12(2267, 1), - ; - // - - @Deprecated - public static final String LEGACY_PREFIX = "LEGACY_"; - - private final int id; - private final Constructor ctor; - private static final Map BY_NAME = Maps.newHashMap(); - private final int maxStack; - private final short durability; - public final Class data; - private final boolean legacy; - private final NamespacedKey key; - - private Material(final int id) { - this(id, 64); - } - - private Material(final int id, final int stack) { - this(id, stack, MaterialData.class); - } - - private Material(final int id, final int stack, final int durability) { - this(id, stack, durability, MaterialData.class); - } - - private Material(final int id, /*@NotNull*/ final Class data) { - this(id, 64, data); - } - - private Material(final int id, final int stack, /*@NotNull*/ final Class data) { - this(id, stack, 0, data); - } - - private Material(final int id, final int stack, final int durability, /*@NotNull*/ final Class data) { - this.id = id; - this.durability = (short) durability; - this.maxStack = stack; - this.data = data; - this.legacy = this.name().startsWith(LEGACY_PREFIX); - this.key = NamespacedKey.minecraft(this.name().toLowerCase(Locale.ROOT)); - // try to cache the constructor for this material - try { - if (MaterialData.class.isAssignableFrom(data)) { - this.ctor = (Constructor) data.getConstructor(Material.class, byte.class); - } else { - this.ctor = null; - } - } catch (NoSuchMethodException ex) { - throw new AssertionError(ex); - } catch (SecurityException ex) { - throw new AssertionError(ex); - } - } - - // Paper start - - /** - * @return If the type is either AIR, CAVE_AIR or VOID_AIR - */ - public boolean isEmpty() { - switch (this) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - return true; - } - return false; - } - // Paper end - - /** - * Do not use for any reason. - * - * @return ID of this material - * @deprecated Magic value - */ - @Deprecated - public int getId() { - Validate.isTrue(legacy, "Cannot get ID of Modern Material"); - return id; - } - - /** - * Do not use for any reason. - * - * @return legacy status - */ - @Deprecated - public boolean isLegacy() { - return legacy; - } - - @NotNull - @Override - public NamespacedKey getKey() { - Validate.isTrue(!legacy, "Cannot get key of Legacy Material"); - return key; - } - - /** - * 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; - } - - /** - * Creates a new {@link BlockData} instance for this Material, with all - * properties initialized to unspecified defaults. - * - * @return new data instance - */ - @NotNull - public BlockData createBlockData() { - return Bukkit.createBlockData(this); - } - - /** - * Creates a new {@link BlockData} instance for this Material, with - * all properties initialized to unspecified defaults. - * - * @param consumer consumer to run on new instance before returning - * @return new data instance - */ - @NotNull - public BlockData createBlockData(@Nullable Consumer consumer) { - return Bukkit.createBlockData(this, consumer); - } - - /** - * Creates a new {@link BlockData} instance for this Material, with all - * properties initialized to unspecified defaults, except for those provided - * in data. - * - * @param data data string - * @return new data instance - * @throws IllegalArgumentException if the specified data is not valid - */ - @NotNull - public BlockData createBlockData(@Nullable String data) throws IllegalArgumentException { - return Bukkit.createBlockData(this, data); - } - - /** - * Gets the MaterialData class associated with this Material - * - * @return MaterialData associated with this Material - */ - @NotNull - public Class getData() { - Validate.isTrue(legacy, "Cannot get data class of Modern Material"); - 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 - @NotNull - public MaterialData getNewData(final byte raw) { - Validate.isTrue(legacy, "Cannot get new data of Modern Material"); - try { - return ctor.newInstance(this, 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() { - switch (this) { - // - case ACACIA_BUTTON: - case ACACIA_DOOR: - case ACACIA_FENCE: - case ACACIA_FENCE_GATE: - case ACACIA_LEAVES: - case ACACIA_LOG: - case ACACIA_PLANKS: - case ACACIA_PRESSURE_PLATE: - case ACACIA_SAPLING: - case ACACIA_SIGN: - case ACACIA_SLAB: - case ACACIA_STAIRS: - case ACACIA_TRAPDOOR: - case ACACIA_WALL_SIGN: - case ACACIA_WOOD: - case ACTIVATOR_RAIL: - case AIR: - case ALLIUM: - case ANDESITE: - case ANDESITE_SLAB: - case ANDESITE_STAIRS: - case ANDESITE_WALL: - case ANVIL: - case ATTACHED_MELON_STEM: - case ATTACHED_PUMPKIN_STEM: - case AZURE_BLUET: - case BAMBOO: - case BAMBOO_SAPLING: - case BARREL: - case BARRIER: - case BEACON: - case BEDROCK: - case BEETROOTS: - case BELL: - case BIRCH_BUTTON: - case BIRCH_DOOR: - case BIRCH_FENCE: - case BIRCH_FENCE_GATE: - case BIRCH_LEAVES: - case BIRCH_LOG: - case BIRCH_PLANKS: - case BIRCH_PRESSURE_PLATE: - case BIRCH_SAPLING: - case BIRCH_SIGN: - case BIRCH_SLAB: - case BIRCH_STAIRS: - case BIRCH_TRAPDOOR: - case BIRCH_WALL_SIGN: - case BIRCH_WOOD: - case BLACK_BANNER: - case BLACK_BED: - case BLACK_CARPET: - case BLACK_CONCRETE: - case BLACK_CONCRETE_POWDER: - case BLACK_GLAZED_TERRACOTTA: - case BLACK_SHULKER_BOX: - case BLACK_STAINED_GLASS: - case BLACK_STAINED_GLASS_PANE: - case BLACK_TERRACOTTA: - case BLACK_WALL_BANNER: - case BLACK_WOOL: - case BLAST_FURNACE: - case BLUE_BANNER: - case BLUE_BED: - case BLUE_CARPET: - case BLUE_CONCRETE: - case BLUE_CONCRETE_POWDER: - case BLUE_GLAZED_TERRACOTTA: - case BLUE_ICE: - case BLUE_ORCHID: - case BLUE_SHULKER_BOX: - case BLUE_STAINED_GLASS: - case BLUE_STAINED_GLASS_PANE: - case BLUE_TERRACOTTA: - case BLUE_WALL_BANNER: - case BLUE_WOOL: - case BONE_BLOCK: - case BOOKSHELF: - case BRAIN_CORAL: - case BRAIN_CORAL_BLOCK: - case BRAIN_CORAL_FAN: - case BRAIN_CORAL_WALL_FAN: - case BREWING_STAND: - case BRICKS: - case BRICK_SLAB: - case BRICK_STAIRS: - case BRICK_WALL: - case BROWN_BANNER: - case BROWN_BED: - case BROWN_CARPET: - case BROWN_CONCRETE: - case BROWN_CONCRETE_POWDER: - case BROWN_GLAZED_TERRACOTTA: - case BROWN_MUSHROOM: - case BROWN_MUSHROOM_BLOCK: - case BROWN_SHULKER_BOX: - case BROWN_STAINED_GLASS: - case BROWN_STAINED_GLASS_PANE: - case BROWN_TERRACOTTA: - case BROWN_WALL_BANNER: - case BROWN_WOOL: - case BUBBLE_COLUMN: - case BUBBLE_CORAL: - case BUBBLE_CORAL_BLOCK: - case BUBBLE_CORAL_FAN: - case BUBBLE_CORAL_WALL_FAN: - case CACTUS: - case CAKE: - case CAMPFIRE: - case CARROTS: - case CARTOGRAPHY_TABLE: - case CARVED_PUMPKIN: - case CAULDRON: - case CAVE_AIR: - case CHAIN_COMMAND_BLOCK: - case CHEST: - case CHIPPED_ANVIL: - case CHISELED_QUARTZ_BLOCK: - case CHISELED_RED_SANDSTONE: - case CHISELED_SANDSTONE: - case CHISELED_STONE_BRICKS: - case CHORUS_FLOWER: - case CHORUS_PLANT: - case CLAY: - case COAL_BLOCK: - case COAL_ORE: - case COARSE_DIRT: - case COBBLESTONE: - case COBBLESTONE_SLAB: - case COBBLESTONE_STAIRS: - case COBBLESTONE_WALL: - case COBWEB: - case COCOA: - case COMMAND_BLOCK: - case COMPARATOR: - case COMPOSTER: - case CONDUIT: - case CORNFLOWER: - case CRACKED_STONE_BRICKS: - case CRAFTING_TABLE: - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case CUT_RED_SANDSTONE: - case CUT_RED_SANDSTONE_SLAB: - case CUT_SANDSTONE: - case CUT_SANDSTONE_SLAB: - case CYAN_BANNER: - case CYAN_BED: - case CYAN_CARPET: - case CYAN_CONCRETE: - case CYAN_CONCRETE_POWDER: - case CYAN_GLAZED_TERRACOTTA: - case CYAN_SHULKER_BOX: - case CYAN_STAINED_GLASS: - case CYAN_STAINED_GLASS_PANE: - case CYAN_TERRACOTTA: - case CYAN_WALL_BANNER: - case CYAN_WOOL: - case DAMAGED_ANVIL: - case DANDELION: - case DARK_OAK_BUTTON: - case DARK_OAK_DOOR: - case DARK_OAK_FENCE: - case DARK_OAK_FENCE_GATE: - case DARK_OAK_LEAVES: - case DARK_OAK_LOG: - case DARK_OAK_PLANKS: - case DARK_OAK_PRESSURE_PLATE: - case DARK_OAK_SAPLING: - case DARK_OAK_SIGN: - case DARK_OAK_SLAB: - case DARK_OAK_STAIRS: - case DARK_OAK_TRAPDOOR: - case DARK_OAK_WALL_SIGN: - case DARK_OAK_WOOD: - case DARK_PRISMARINE: - case DARK_PRISMARINE_SLAB: - case DARK_PRISMARINE_STAIRS: - case DAYLIGHT_DETECTOR: - case DEAD_BRAIN_CORAL: - case DEAD_BRAIN_CORAL_BLOCK: - case DEAD_BRAIN_CORAL_FAN: - case DEAD_BRAIN_CORAL_WALL_FAN: - case DEAD_BUBBLE_CORAL: - case DEAD_BUBBLE_CORAL_BLOCK: - case DEAD_BUBBLE_CORAL_FAN: - case DEAD_BUBBLE_CORAL_WALL_FAN: - case DEAD_BUSH: - case DEAD_FIRE_CORAL: - case DEAD_FIRE_CORAL_BLOCK: - case DEAD_FIRE_CORAL_FAN: - case DEAD_FIRE_CORAL_WALL_FAN: - case DEAD_HORN_CORAL: - case DEAD_HORN_CORAL_BLOCK: - case DEAD_HORN_CORAL_FAN: - case DEAD_HORN_CORAL_WALL_FAN: - case DEAD_TUBE_CORAL: - case DEAD_TUBE_CORAL_BLOCK: - case DEAD_TUBE_CORAL_FAN: - case DEAD_TUBE_CORAL_WALL_FAN: - case DETECTOR_RAIL: - case DIAMOND_BLOCK: - case DIAMOND_ORE: - case DIORITE: - case DIORITE_SLAB: - case DIORITE_STAIRS: - case DIORITE_WALL: - case DIRT: - case DISPENSER: - case DRAGON_EGG: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case DRIED_KELP_BLOCK: - case DROPPER: - case EMERALD_BLOCK: - case EMERALD_ORE: - case ENCHANTING_TABLE: - case ENDER_CHEST: - case END_GATEWAY: - case END_PORTAL: - case END_PORTAL_FRAME: - case END_ROD: - case END_STONE: - case END_STONE_BRICKS: - case END_STONE_BRICK_SLAB: - case END_STONE_BRICK_STAIRS: - case END_STONE_BRICK_WALL: - case FARMLAND: - case FERN: - case FIRE: - case FIRE_CORAL: - case FIRE_CORAL_BLOCK: - case FIRE_CORAL_FAN: - case FIRE_CORAL_WALL_FAN: - case FLETCHING_TABLE: - case FLOWER_POT: - case FROSTED_ICE: - case FURNACE: - case GLASS: - case GLASS_PANE: - case GLOWSTONE: - case GOLD_BLOCK: - case GOLD_ORE: - case GRANITE: - case GRANITE_SLAB: - case GRANITE_STAIRS: - case GRANITE_WALL: - case GRASS: - case GRASS_BLOCK: - case GRASS_PATH: - case GRAVEL: - case GRAY_BANNER: - case GRAY_BED: - case GRAY_CARPET: - case GRAY_CONCRETE: - case GRAY_CONCRETE_POWDER: - case GRAY_GLAZED_TERRACOTTA: - case GRAY_SHULKER_BOX: - case GRAY_STAINED_GLASS: - case GRAY_STAINED_GLASS_PANE: - case GRAY_TERRACOTTA: - case GRAY_WALL_BANNER: - case GRAY_WOOL: - case GREEN_BANNER: - case GREEN_BED: - case GREEN_CARPET: - case GREEN_CONCRETE: - case GREEN_CONCRETE_POWDER: - case GREEN_GLAZED_TERRACOTTA: - case GREEN_SHULKER_BOX: - case GREEN_STAINED_GLASS: - case GREEN_STAINED_GLASS_PANE: - case GREEN_TERRACOTTA: - case GREEN_WALL_BANNER: - case GREEN_WOOL: - case GRINDSTONE: - case HAY_BLOCK: - case HEAVY_WEIGHTED_PRESSURE_PLATE: - case HOPPER: - case HORN_CORAL: - case HORN_CORAL_BLOCK: - case HORN_CORAL_FAN: - case HORN_CORAL_WALL_FAN: - case ICE: - case INFESTED_CHISELED_STONE_BRICKS: - case INFESTED_COBBLESTONE: - case INFESTED_CRACKED_STONE_BRICKS: - case INFESTED_MOSSY_STONE_BRICKS: - case INFESTED_STONE: - case INFESTED_STONE_BRICKS: - case IRON_BARS: - case IRON_BLOCK: - case IRON_DOOR: - case IRON_ORE: - case IRON_TRAPDOOR: - case JACK_O_LANTERN: - case JIGSAW: - case JUKEBOX: - case JUNGLE_BUTTON: - case JUNGLE_DOOR: - case JUNGLE_FENCE: - case JUNGLE_FENCE_GATE: - case JUNGLE_LEAVES: - case JUNGLE_LOG: - case JUNGLE_PLANKS: - case JUNGLE_PRESSURE_PLATE: - case JUNGLE_SAPLING: - case JUNGLE_SIGN: - case JUNGLE_SLAB: - case JUNGLE_STAIRS: - case JUNGLE_TRAPDOOR: - case JUNGLE_WALL_SIGN: - case JUNGLE_WOOD: - case KELP: - case KELP_PLANT: - case LADDER: - case LANTERN: - case LAPIS_BLOCK: - case LAPIS_ORE: - case LARGE_FERN: - case LAVA: - case LECTERN: - case LEVER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_BED: - case LIGHT_BLUE_CARPET: - case LIGHT_BLUE_CONCRETE: - case LIGHT_BLUE_CONCRETE_POWDER: - case LIGHT_BLUE_GLAZED_TERRACOTTA: - case LIGHT_BLUE_SHULKER_BOX: - case LIGHT_BLUE_STAINED_GLASS: - case LIGHT_BLUE_STAINED_GLASS_PANE: - case LIGHT_BLUE_TERRACOTTA: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_BLUE_WOOL: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_BED: - case LIGHT_GRAY_CARPET: - case LIGHT_GRAY_CONCRETE: - case LIGHT_GRAY_CONCRETE_POWDER: - case LIGHT_GRAY_GLAZED_TERRACOTTA: - case LIGHT_GRAY_SHULKER_BOX: - case LIGHT_GRAY_STAINED_GLASS: - case LIGHT_GRAY_STAINED_GLASS_PANE: - case LIGHT_GRAY_TERRACOTTA: - case LIGHT_GRAY_WALL_BANNER: - case LIGHT_GRAY_WOOL: - case LIGHT_WEIGHTED_PRESSURE_PLATE: - case LILAC: - case LILY_OF_THE_VALLEY: - case LILY_PAD: - case LIME_BANNER: - case LIME_BED: - case LIME_CARPET: - case LIME_CONCRETE: - case LIME_CONCRETE_POWDER: - case LIME_GLAZED_TERRACOTTA: - case LIME_SHULKER_BOX: - case LIME_STAINED_GLASS: - case LIME_STAINED_GLASS_PANE: - case LIME_TERRACOTTA: - case LIME_WALL_BANNER: - case LIME_WOOL: - case LOOM: - case MAGENTA_BANNER: - case MAGENTA_BED: - case MAGENTA_CARPET: - case MAGENTA_CONCRETE: - case MAGENTA_CONCRETE_POWDER: - case MAGENTA_GLAZED_TERRACOTTA: - case MAGENTA_SHULKER_BOX: - case MAGENTA_STAINED_GLASS: - case MAGENTA_STAINED_GLASS_PANE: - case MAGENTA_TERRACOTTA: - case MAGENTA_WALL_BANNER: - case MAGENTA_WOOL: - case MAGMA_BLOCK: - case MELON: - case MELON_STEM: - case MOSSY_COBBLESTONE: - case MOSSY_COBBLESTONE_SLAB: - case MOSSY_COBBLESTONE_STAIRS: - case MOSSY_COBBLESTONE_WALL: - case MOSSY_STONE_BRICKS: - case MOSSY_STONE_BRICK_SLAB: - case MOSSY_STONE_BRICK_STAIRS: - case MOSSY_STONE_BRICK_WALL: - case MOVING_PISTON: - case MUSHROOM_STEM: - case MYCELIUM: - case NETHERRACK: - case NETHER_BRICKS: - case NETHER_BRICK_FENCE: - case NETHER_BRICK_SLAB: - case NETHER_BRICK_STAIRS: - case NETHER_BRICK_WALL: - case NETHER_PORTAL: - case NETHER_QUARTZ_ORE: - case NETHER_WART: - case NETHER_WART_BLOCK: - case NOTE_BLOCK: - case OAK_BUTTON: - case OAK_DOOR: - case OAK_FENCE: - case OAK_FENCE_GATE: - case OAK_LEAVES: - case OAK_LOG: - case OAK_PLANKS: - case OAK_PRESSURE_PLATE: - case OAK_SAPLING: - case OAK_SIGN: - case OAK_SLAB: - case OAK_STAIRS: - case OAK_TRAPDOOR: - case OAK_WALL_SIGN: - case OAK_WOOD: - case OBSERVER: - case OBSIDIAN: - case ORANGE_BANNER: - case ORANGE_BED: - case ORANGE_CARPET: - case ORANGE_CONCRETE: - case ORANGE_CONCRETE_POWDER: - case ORANGE_GLAZED_TERRACOTTA: - case ORANGE_SHULKER_BOX: - case ORANGE_STAINED_GLASS: - case ORANGE_STAINED_GLASS_PANE: - case ORANGE_TERRACOTTA: - case ORANGE_TULIP: - case ORANGE_WALL_BANNER: - case ORANGE_WOOL: - case OXEYE_DAISY: - case PACKED_ICE: - case PEONY: - case PETRIFIED_OAK_SLAB: - case PINK_BANNER: - case PINK_BED: - case PINK_CARPET: - case PINK_CONCRETE: - case PINK_CONCRETE_POWDER: - case PINK_GLAZED_TERRACOTTA: - case PINK_SHULKER_BOX: - case PINK_STAINED_GLASS: - case PINK_STAINED_GLASS_PANE: - case PINK_TERRACOTTA: - case PINK_TULIP: - case PINK_WALL_BANNER: - case PINK_WOOL: - case PISTON: - case PISTON_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case PODZOL: - case POLISHED_ANDESITE: - case POLISHED_ANDESITE_SLAB: - case POLISHED_ANDESITE_STAIRS: - case POLISHED_DIORITE: - case POLISHED_DIORITE_SLAB: - case POLISHED_DIORITE_STAIRS: - case POLISHED_GRANITE: - case POLISHED_GRANITE_SLAB: - case POLISHED_GRANITE_STAIRS: - case POPPY: - case POTATOES: - case POTTED_ACACIA_SAPLING: - case POTTED_ALLIUM: - case POTTED_AZURE_BLUET: - case POTTED_BAMBOO: - case POTTED_BIRCH_SAPLING: - case POTTED_BLUE_ORCHID: - case POTTED_BROWN_MUSHROOM: - case POTTED_CACTUS: - case POTTED_CORNFLOWER: - case POTTED_DANDELION: - case POTTED_DARK_OAK_SAPLING: - case POTTED_DEAD_BUSH: - case POTTED_FERN: - case POTTED_JUNGLE_SAPLING: - case POTTED_LILY_OF_THE_VALLEY: - case POTTED_OAK_SAPLING: - case POTTED_ORANGE_TULIP: - case POTTED_OXEYE_DAISY: - case POTTED_PINK_TULIP: - case POTTED_POPPY: - case POTTED_RED_MUSHROOM: - case POTTED_RED_TULIP: - case POTTED_SPRUCE_SAPLING: - case POTTED_WHITE_TULIP: - case POTTED_WITHER_ROSE: - case POWERED_RAIL: - case PRISMARINE: - case PRISMARINE_BRICKS: - case PRISMARINE_BRICK_SLAB: - case PRISMARINE_BRICK_STAIRS: - case PRISMARINE_SLAB: - case PRISMARINE_STAIRS: - case PRISMARINE_WALL: - case PUMPKIN: - case PUMPKIN_STEM: - case PURPLE_BANNER: - case PURPLE_BED: - case PURPLE_CARPET: - case PURPLE_CONCRETE: - case PURPLE_CONCRETE_POWDER: - case PURPLE_GLAZED_TERRACOTTA: - case PURPLE_SHULKER_BOX: - case PURPLE_STAINED_GLASS: - case PURPLE_STAINED_GLASS_PANE: - case PURPLE_TERRACOTTA: - case PURPLE_WALL_BANNER: - case PURPLE_WOOL: - case PURPUR_BLOCK: - case PURPUR_PILLAR: - case PURPUR_SLAB: - case PURPUR_STAIRS: - case QUARTZ_BLOCK: - case QUARTZ_PILLAR: - case QUARTZ_SLAB: - case QUARTZ_STAIRS: - case RAIL: - case REDSTONE_BLOCK: - case REDSTONE_LAMP: - case REDSTONE_ORE: - case REDSTONE_TORCH: - case REDSTONE_WALL_TORCH: - case REDSTONE_WIRE: - case RED_BANNER: - case RED_BED: - case RED_CARPET: - case RED_CONCRETE: - case RED_CONCRETE_POWDER: - case RED_GLAZED_TERRACOTTA: - case RED_MUSHROOM: - case RED_MUSHROOM_BLOCK: - case RED_NETHER_BRICKS: - case RED_NETHER_BRICK_SLAB: - case RED_NETHER_BRICK_STAIRS: - case RED_NETHER_BRICK_WALL: - case RED_SAND: - case RED_SANDSTONE: - case RED_SANDSTONE_SLAB: - case RED_SANDSTONE_STAIRS: - case RED_SANDSTONE_WALL: - case RED_SHULKER_BOX: - case RED_STAINED_GLASS: - case RED_STAINED_GLASS_PANE: - case RED_TERRACOTTA: - case RED_TULIP: - case RED_WALL_BANNER: - case RED_WOOL: - case REPEATER: - case REPEATING_COMMAND_BLOCK: - case ROSE_BUSH: - case SAND: - case SANDSTONE: - case SANDSTONE_SLAB: - case SANDSTONE_STAIRS: - case SANDSTONE_WALL: - case SCAFFOLDING: - case SEAGRASS: - case SEA_LANTERN: - case SEA_PICKLE: - case SHULKER_BOX: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case SLIME_BLOCK: - case SMITHING_TABLE: - case SMOKER: - case SMOOTH_QUARTZ: - case SMOOTH_QUARTZ_SLAB: - case SMOOTH_QUARTZ_STAIRS: - case SMOOTH_RED_SANDSTONE: - case SMOOTH_RED_SANDSTONE_SLAB: - case SMOOTH_RED_SANDSTONE_STAIRS: - case SMOOTH_SANDSTONE: - case SMOOTH_SANDSTONE_SLAB: - case SMOOTH_SANDSTONE_STAIRS: - case SMOOTH_STONE: - case SMOOTH_STONE_SLAB: - case SNOW: - case SNOW_BLOCK: - case SOUL_SAND: - case SPAWNER: - case SPONGE: - case SPRUCE_BUTTON: - case SPRUCE_DOOR: - case SPRUCE_FENCE: - case SPRUCE_FENCE_GATE: - case SPRUCE_LEAVES: - case SPRUCE_LOG: - case SPRUCE_PLANKS: - case SPRUCE_PRESSURE_PLATE: - case SPRUCE_SAPLING: - case SPRUCE_SIGN: - case SPRUCE_SLAB: - case SPRUCE_STAIRS: - case SPRUCE_TRAPDOOR: - case SPRUCE_WALL_SIGN: - case SPRUCE_WOOD: - case STICKY_PISTON: - case STONE: - case STONECUTTER: - case STONE_BRICKS: - case STONE_BRICK_SLAB: - case STONE_BRICK_STAIRS: - case STONE_BRICK_WALL: - case STONE_BUTTON: - case STONE_PRESSURE_PLATE: - case STONE_SLAB: - case STONE_STAIRS: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - case STRUCTURE_BLOCK: - case STRUCTURE_VOID: - case SUGAR_CANE: - case SUNFLOWER: - case SWEET_BERRY_BUSH: - case TALL_GRASS: - case TALL_SEAGRASS: - case TERRACOTTA: - case TNT: - case TORCH: - case TRAPPED_CHEST: - case TRIPWIRE: - case TRIPWIRE_HOOK: - case TUBE_CORAL: - case TUBE_CORAL_BLOCK: - case TUBE_CORAL_FAN: - case TUBE_CORAL_WALL_FAN: - case TURTLE_EGG: - case VINE: - case VOID_AIR: - case WALL_TORCH: - case WATER: - case WET_SPONGE: - case WHEAT: - case WHITE_BANNER: - case WHITE_BED: - case WHITE_CARPET: - case WHITE_CONCRETE: - case WHITE_CONCRETE_POWDER: - case WHITE_GLAZED_TERRACOTTA: - case WHITE_SHULKER_BOX: - case WHITE_STAINED_GLASS: - case WHITE_STAINED_GLASS_PANE: - case WHITE_TERRACOTTA: - case WHITE_TULIP: - case WHITE_WALL_BANNER: - case WHITE_WOOL: - case WITHER_ROSE: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case YELLOW_BANNER: - case YELLOW_BED: - case YELLOW_CARPET: - case YELLOW_CONCRETE: - case YELLOW_CONCRETE_POWDER: - case YELLOW_GLAZED_TERRACOTTA: - case YELLOW_SHULKER_BOX: - case YELLOW_STAINED_GLASS: - case YELLOW_STAINED_GLASS_PANE: - case YELLOW_TERRACOTTA: - case YELLOW_WALL_BANNER: - case YELLOW_WOOL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - // - return true; - default: - return 0 <= id && id < 256; - } - } - - /** - * Checks if this Material is edible. - * - * @return true if this Material is edible. - */ - public boolean isEdible() { - switch (this) { - // - case APPLE: - case BAKED_POTATO: - case BEEF: - case BEETROOT: - case BEETROOT_SOUP: - case BREAD: - case CARROT: - case CHICKEN: - case CHORUS_FRUIT: - case COD: - case COOKED_BEEF: - case COOKED_CHICKEN: - case COOKED_COD: - case COOKED_MUTTON: - case COOKED_PORKCHOP: - case COOKED_RABBIT: - case COOKED_SALMON: - case COOKIE: - case DRIED_KELP: - case ENCHANTED_GOLDEN_APPLE: - case GOLDEN_APPLE: - case GOLDEN_CARROT: - case MELON_SLICE: - case MUSHROOM_STEW: - case MUTTON: - case POISONOUS_POTATO: - case PORKCHOP: - case POTATO: - case PUFFERFISH: - case PUMPKIN_PIE: - case RABBIT: - case RABBIT_STEW: - case ROTTEN_FLESH: - case SALMON: - case SPIDER_EYE: - case SUSPICIOUS_STEW: - case SWEET_BERRIES: - case TROPICAL_FISH: - // ----- Legacy Separator ----- - case LEGACY_BREAD: - case LEGACY_CARROT_ITEM: - case LEGACY_BAKED_POTATO: - case LEGACY_POTATO_ITEM: - case LEGACY_POISONOUS_POTATO: - case LEGACY_GOLDEN_CARROT: - case LEGACY_PUMPKIN_PIE: - case LEGACY_COOKIE: - case LEGACY_MELON: - case LEGACY_MUSHROOM_SOUP: - case LEGACY_RAW_CHICKEN: - case LEGACY_COOKED_CHICKEN: - case LEGACY_RAW_BEEF: - case LEGACY_COOKED_BEEF: - case LEGACY_RAW_FISH: - case LEGACY_COOKED_FISH: - case LEGACY_PORK: - case LEGACY_GRILLED_PORK: - case LEGACY_APPLE: - case LEGACY_GOLDEN_APPLE: - case LEGACY_ROTTEN_FLESH: - case LEGACY_SPIDER_EYE: - case LEGACY_RABBIT: - case LEGACY_COOKED_RABBIT: - case LEGACY_RABBIT_STEW: - case LEGACY_MUTTON: - case LEGACY_COOKED_MUTTON: - case LEGACY_BEETROOT: - case LEGACY_CHORUS_FRUIT: - case LEGACY_BEETROOT_SOUP: - // - return true; - default: - return false; - } - } - - /** - * 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 - */ - @Nullable - public static Material getMaterial(@NotNull final String name) { - return getMaterial(name, false); - } - - /** - * 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 - * @param legacyName whether this is a legacy name - * @return Material if found, or null - */ - @Nullable - public static Material getMaterial(@NotNull String name, boolean legacyName) { - if (legacyName) { - if (!name.startsWith(LEGACY_PREFIX)) { - name = LEGACY_PREFIX + name; - } - - Material match = BY_NAME.get(name); - return Bukkit.getUnsafe().fromLegacy(match); - } - - return BY_NAME.get(name); - } - - /** - * Attempts to match the Material with the given name. - *

- * This is a match lookup; names will be stripped of the "minecraft:" - * namespace, converted to uppercase, then stripped of special characters in - * an attempt to format it like the enum. - * - * @param name Name of the material to get - * @return Material if found, or null - */ - @Nullable - public static Material matchMaterial(@NotNull final String name) { - return matchMaterial(name, false); - } - - /** - * Attempts to match the Material with the given name. - *

- * This is a match lookup; names will be stripped of the "minecraft:" - * namespace, converted to uppercase, then stripped of special characters in - * an attempt to format it like the enum. - * - * @param name Name of the material to get - * @param legacyName whether this is a legacy name - * @return Material if found, or null - */ - @Nullable - public static Material matchMaterial(@NotNull final String name, boolean legacyName) { - Validate.notNull(name, "Name cannot be null"); - - String filtered = name; - if (filtered.startsWith(NamespacedKey.MINECRAFT + ":")) { - filtered = filtered.substring((NamespacedKey.MINECRAFT + ":").length()); - } - - filtered = filtered.toUpperCase(java.util.Locale.ENGLISH); - - filtered = filtered.replaceAll("\\s+", "_").replaceAll("\\W", ""); - return getMaterial(filtered, legacyName); - } - - static { - for (Material material : values()) { - BY_NAME.put(material.name(), material); - } - } - - /** - * @return True if this material represents a playable music disk. - */ - public boolean isRecord() { - switch (this) { - // - case MUSIC_DISC_11: - case MUSIC_DISC_13: - case MUSIC_DISC_BLOCKS: - case MUSIC_DISC_CAT: - case MUSIC_DISC_CHIRP: - case MUSIC_DISC_FAR: - case MUSIC_DISC_MALL: - case MUSIC_DISC_MELLOHI: - case MUSIC_DISC_STAL: - case MUSIC_DISC_STRAD: - case MUSIC_DISC_WAIT: - case MUSIC_DISC_WARD: - // - return true; - default: - return id >= LEGACY_GOLD_RECORD.id && id <= LEGACY_RECORD_12.id; - } - } - - /** - * Check if the material is a block and solid (can be built upon) - * - * @return True if this material is a block and solid - */ - public boolean isSolid() { - if (!isBlock() || id == 0) { - return false; - } - switch (this) { - // - case ACACIA_DOOR: - case ACACIA_FENCE: - case ACACIA_FENCE_GATE: - case ACACIA_LEAVES: - case ACACIA_LOG: - case ACACIA_PLANKS: - case ACACIA_PRESSURE_PLATE: - case ACACIA_SIGN: - case ACACIA_SLAB: - case ACACIA_STAIRS: - case ACACIA_TRAPDOOR: - case ACACIA_WALL_SIGN: - case ACACIA_WOOD: - case ANDESITE: - case ANDESITE_SLAB: - case ANDESITE_STAIRS: - case ANDESITE_WALL: - case ANVIL: - case BAMBOO: - case BARREL: - case BARRIER: - case BEACON: - case BEDROCK: - case BELL: - case BIRCH_DOOR: - case BIRCH_FENCE: - case BIRCH_FENCE_GATE: - case BIRCH_LEAVES: - case BIRCH_LOG: - case BIRCH_PLANKS: - case BIRCH_PRESSURE_PLATE: - case BIRCH_SIGN: - case BIRCH_SLAB: - case BIRCH_STAIRS: - case BIRCH_TRAPDOOR: - case BIRCH_WALL_SIGN: - case BIRCH_WOOD: - case BLACK_BANNER: - case BLACK_BED: - case BLACK_CONCRETE: - case BLACK_CONCRETE_POWDER: - case BLACK_GLAZED_TERRACOTTA: - case BLACK_SHULKER_BOX: - case BLACK_STAINED_GLASS: - case BLACK_STAINED_GLASS_PANE: - case BLACK_TERRACOTTA: - case BLACK_WALL_BANNER: - case BLACK_WOOL: - case BLAST_FURNACE: - case BLUE_BANNER: - case BLUE_BED: - case BLUE_CONCRETE: - case BLUE_CONCRETE_POWDER: - case BLUE_GLAZED_TERRACOTTA: - case BLUE_ICE: - case BLUE_SHULKER_BOX: - case BLUE_STAINED_GLASS: - case BLUE_STAINED_GLASS_PANE: - case BLUE_TERRACOTTA: - case BLUE_WALL_BANNER: - case BLUE_WOOL: - case BONE_BLOCK: - case BOOKSHELF: - case BRAIN_CORAL_BLOCK: - case BREWING_STAND: - case BRICKS: - case BRICK_SLAB: - case BRICK_STAIRS: - case BRICK_WALL: - case BROWN_BANNER: - case BROWN_BED: - case BROWN_CONCRETE: - case BROWN_CONCRETE_POWDER: - case BROWN_GLAZED_TERRACOTTA: - case BROWN_MUSHROOM_BLOCK: - case BROWN_SHULKER_BOX: - case BROWN_STAINED_GLASS: - case BROWN_STAINED_GLASS_PANE: - case BROWN_TERRACOTTA: - case BROWN_WALL_BANNER: - case BROWN_WOOL: - case BUBBLE_CORAL_BLOCK: - case CACTUS: - case CAKE: - case CAMPFIRE: - case CARTOGRAPHY_TABLE: - case CARVED_PUMPKIN: - case CAULDRON: - case CHAIN_COMMAND_BLOCK: - case CHEST: - case CHIPPED_ANVIL: - case CHISELED_QUARTZ_BLOCK: - case CHISELED_RED_SANDSTONE: - case CHISELED_SANDSTONE: - case CHISELED_STONE_BRICKS: - case CLAY: - case COAL_BLOCK: - case COAL_ORE: - case COARSE_DIRT: - case COBBLESTONE: - case COBBLESTONE_SLAB: - case COBBLESTONE_STAIRS: - case COBBLESTONE_WALL: - case COMMAND_BLOCK: - case COMPOSTER: - case CONDUIT: - case CRACKED_STONE_BRICKS: - case CRAFTING_TABLE: - case CUT_RED_SANDSTONE: - case CUT_RED_SANDSTONE_SLAB: - case CUT_SANDSTONE: - case CUT_SANDSTONE_SLAB: - case CYAN_BANNER: - case CYAN_BED: - case CYAN_CONCRETE: - case CYAN_CONCRETE_POWDER: - case CYAN_GLAZED_TERRACOTTA: - case CYAN_SHULKER_BOX: - case CYAN_STAINED_GLASS: - case CYAN_STAINED_GLASS_PANE: - case CYAN_TERRACOTTA: - case CYAN_WALL_BANNER: - case CYAN_WOOL: - case DAMAGED_ANVIL: - case DARK_OAK_DOOR: - case DARK_OAK_FENCE: - case DARK_OAK_FENCE_GATE: - case DARK_OAK_LEAVES: - case DARK_OAK_LOG: - case DARK_OAK_PLANKS: - case DARK_OAK_PRESSURE_PLATE: - case DARK_OAK_SIGN: - case DARK_OAK_SLAB: - case DARK_OAK_STAIRS: - case DARK_OAK_TRAPDOOR: - case DARK_OAK_WALL_SIGN: - case DARK_OAK_WOOD: - case DARK_PRISMARINE: - case DARK_PRISMARINE_SLAB: - case DARK_PRISMARINE_STAIRS: - case DAYLIGHT_DETECTOR: - case DEAD_BRAIN_CORAL: - case DEAD_BRAIN_CORAL_BLOCK: - case DEAD_BRAIN_CORAL_FAN: - case DEAD_BRAIN_CORAL_WALL_FAN: - case DEAD_BUBBLE_CORAL: - case DEAD_BUBBLE_CORAL_BLOCK: - case DEAD_BUBBLE_CORAL_FAN: - case DEAD_BUBBLE_CORAL_WALL_FAN: - case DEAD_FIRE_CORAL: - case DEAD_FIRE_CORAL_BLOCK: - case DEAD_FIRE_CORAL_FAN: - case DEAD_FIRE_CORAL_WALL_FAN: - case DEAD_HORN_CORAL: - case DEAD_HORN_CORAL_BLOCK: - case DEAD_HORN_CORAL_FAN: - case DEAD_HORN_CORAL_WALL_FAN: - case DEAD_TUBE_CORAL: - case DEAD_TUBE_CORAL_BLOCK: - case DEAD_TUBE_CORAL_FAN: - case DEAD_TUBE_CORAL_WALL_FAN: - case DIAMOND_BLOCK: - case DIAMOND_ORE: - case DIORITE: - case DIORITE_SLAB: - case DIORITE_STAIRS: - case DIORITE_WALL: - case DIRT: - case DISPENSER: - case DRAGON_EGG: - case DRIED_KELP_BLOCK: - case DROPPER: - case EMERALD_BLOCK: - case EMERALD_ORE: - case ENCHANTING_TABLE: - case ENDER_CHEST: - case END_PORTAL_FRAME: - case END_STONE: - case END_STONE_BRICKS: - case END_STONE_BRICK_SLAB: - case END_STONE_BRICK_STAIRS: - case END_STONE_BRICK_WALL: - case FARMLAND: - case FIRE_CORAL_BLOCK: - case FLETCHING_TABLE: - case FROSTED_ICE: - case FURNACE: - case GLASS: - case GLASS_PANE: - case GLOWSTONE: - case GOLD_BLOCK: - case GOLD_ORE: - case GRANITE: - case GRANITE_SLAB: - case GRANITE_STAIRS: - case GRANITE_WALL: - case GRASS_BLOCK: - case GRASS_PATH: - case GRAVEL: - case GRAY_BANNER: - case GRAY_BED: - case GRAY_CONCRETE: - case GRAY_CONCRETE_POWDER: - case GRAY_GLAZED_TERRACOTTA: - case GRAY_SHULKER_BOX: - case GRAY_STAINED_GLASS: - case GRAY_STAINED_GLASS_PANE: - case GRAY_TERRACOTTA: - case GRAY_WALL_BANNER: - case GRAY_WOOL: - case GREEN_BANNER: - case GREEN_BED: - case GREEN_CONCRETE: - case GREEN_CONCRETE_POWDER: - case GREEN_GLAZED_TERRACOTTA: - case GREEN_SHULKER_BOX: - case GREEN_STAINED_GLASS: - case GREEN_STAINED_GLASS_PANE: - case GREEN_TERRACOTTA: - case GREEN_WALL_BANNER: - case GREEN_WOOL: - case GRINDSTONE: - case HAY_BLOCK: - case HEAVY_WEIGHTED_PRESSURE_PLATE: - case HOPPER: - case HORN_CORAL_BLOCK: - case ICE: - case INFESTED_CHISELED_STONE_BRICKS: - case INFESTED_COBBLESTONE: - case INFESTED_CRACKED_STONE_BRICKS: - case INFESTED_MOSSY_STONE_BRICKS: - case INFESTED_STONE: - case INFESTED_STONE_BRICKS: - case IRON_BARS: - case IRON_BLOCK: - case IRON_DOOR: - case IRON_ORE: - case IRON_TRAPDOOR: - case JACK_O_LANTERN: - case JIGSAW: - case JUKEBOX: - case JUNGLE_DOOR: - case JUNGLE_FENCE: - case JUNGLE_FENCE_GATE: - case JUNGLE_LEAVES: - case JUNGLE_LOG: - case JUNGLE_PLANKS: - case JUNGLE_PRESSURE_PLATE: - case JUNGLE_SIGN: - case JUNGLE_SLAB: - case JUNGLE_STAIRS: - case JUNGLE_TRAPDOOR: - case JUNGLE_WALL_SIGN: - case JUNGLE_WOOD: - case LANTERN: - case LAPIS_BLOCK: - case LAPIS_ORE: - case LECTERN: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_BED: - case LIGHT_BLUE_CONCRETE: - case LIGHT_BLUE_CONCRETE_POWDER: - case LIGHT_BLUE_GLAZED_TERRACOTTA: - case LIGHT_BLUE_SHULKER_BOX: - case LIGHT_BLUE_STAINED_GLASS: - case LIGHT_BLUE_STAINED_GLASS_PANE: - case LIGHT_BLUE_TERRACOTTA: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_BLUE_WOOL: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_BED: - case LIGHT_GRAY_CONCRETE: - case LIGHT_GRAY_CONCRETE_POWDER: - case LIGHT_GRAY_GLAZED_TERRACOTTA: - case LIGHT_GRAY_SHULKER_BOX: - case LIGHT_GRAY_STAINED_GLASS: - case LIGHT_GRAY_STAINED_GLASS_PANE: - case LIGHT_GRAY_TERRACOTTA: - case LIGHT_GRAY_WALL_BANNER: - case LIGHT_GRAY_WOOL: - case LIGHT_WEIGHTED_PRESSURE_PLATE: - case LIME_BANNER: - case LIME_BED: - case LIME_CONCRETE: - case LIME_CONCRETE_POWDER: - case LIME_GLAZED_TERRACOTTA: - case LIME_SHULKER_BOX: - case LIME_STAINED_GLASS: - case LIME_STAINED_GLASS_PANE: - case LIME_TERRACOTTA: - case LIME_WALL_BANNER: - case LIME_WOOL: - case LOOM: - case MAGENTA_BANNER: - case MAGENTA_BED: - case MAGENTA_CONCRETE: - case MAGENTA_CONCRETE_POWDER: - case MAGENTA_GLAZED_TERRACOTTA: - case MAGENTA_SHULKER_BOX: - case MAGENTA_STAINED_GLASS: - case MAGENTA_STAINED_GLASS_PANE: - case MAGENTA_TERRACOTTA: - case MAGENTA_WALL_BANNER: - case MAGENTA_WOOL: - case MAGMA_BLOCK: - case MELON: - case MOSSY_COBBLESTONE: - case MOSSY_COBBLESTONE_SLAB: - case MOSSY_COBBLESTONE_STAIRS: - case MOSSY_COBBLESTONE_WALL: - case MOSSY_STONE_BRICKS: - case MOSSY_STONE_BRICK_SLAB: - case MOSSY_STONE_BRICK_STAIRS: - case MOSSY_STONE_BRICK_WALL: - case MOVING_PISTON: - case MUSHROOM_STEM: - case MYCELIUM: - case NETHERRACK: - case NETHER_BRICKS: - case NETHER_BRICK_FENCE: - case NETHER_BRICK_SLAB: - case NETHER_BRICK_STAIRS: - case NETHER_BRICK_WALL: - case NETHER_QUARTZ_ORE: - case NETHER_WART_BLOCK: - case NOTE_BLOCK: - case OAK_DOOR: - case OAK_FENCE: - case OAK_FENCE_GATE: - case OAK_LEAVES: - case OAK_LOG: - case OAK_PLANKS: - case OAK_PRESSURE_PLATE: - case OAK_SIGN: - case OAK_SLAB: - case OAK_STAIRS: - case OAK_TRAPDOOR: - case OAK_WALL_SIGN: - case OAK_WOOD: - case OBSERVER: - case OBSIDIAN: - case ORANGE_BANNER: - case ORANGE_BED: - case ORANGE_CONCRETE: - case ORANGE_CONCRETE_POWDER: - case ORANGE_GLAZED_TERRACOTTA: - case ORANGE_SHULKER_BOX: - case ORANGE_STAINED_GLASS: - case ORANGE_STAINED_GLASS_PANE: - case ORANGE_TERRACOTTA: - case ORANGE_WALL_BANNER: - case ORANGE_WOOL: - case PACKED_ICE: - case PETRIFIED_OAK_SLAB: - case PINK_BANNER: - case PINK_BED: - case PINK_CONCRETE: - case PINK_CONCRETE_POWDER: - case PINK_GLAZED_TERRACOTTA: - case PINK_SHULKER_BOX: - case PINK_STAINED_GLASS: - case PINK_STAINED_GLASS_PANE: - case PINK_TERRACOTTA: - case PINK_WALL_BANNER: - case PINK_WOOL: - case PISTON: - case PISTON_HEAD: - case PODZOL: - case POLISHED_ANDESITE: - case POLISHED_ANDESITE_SLAB: - case POLISHED_ANDESITE_STAIRS: - case POLISHED_DIORITE: - case POLISHED_DIORITE_SLAB: - case POLISHED_DIORITE_STAIRS: - case POLISHED_GRANITE: - case POLISHED_GRANITE_SLAB: - case POLISHED_GRANITE_STAIRS: - case PRISMARINE: - case PRISMARINE_BRICKS: - case PRISMARINE_BRICK_SLAB: - case PRISMARINE_BRICK_STAIRS: - case PRISMARINE_SLAB: - case PRISMARINE_STAIRS: - case PRISMARINE_WALL: - case PUMPKIN: - case PURPLE_BANNER: - case PURPLE_BED: - case PURPLE_CONCRETE: - case PURPLE_CONCRETE_POWDER: - case PURPLE_GLAZED_TERRACOTTA: - case PURPLE_SHULKER_BOX: - case PURPLE_STAINED_GLASS: - case PURPLE_STAINED_GLASS_PANE: - case PURPLE_TERRACOTTA: - case PURPLE_WALL_BANNER: - case PURPLE_WOOL: - case PURPUR_BLOCK: - case PURPUR_PILLAR: - case PURPUR_SLAB: - case PURPUR_STAIRS: - case QUARTZ_BLOCK: - case QUARTZ_PILLAR: - case QUARTZ_SLAB: - case QUARTZ_STAIRS: - case REDSTONE_BLOCK: - case REDSTONE_LAMP: - case REDSTONE_ORE: - case RED_BANNER: - case RED_BED: - case RED_CONCRETE: - case RED_CONCRETE_POWDER: - case RED_GLAZED_TERRACOTTA: - case RED_MUSHROOM_BLOCK: - case RED_NETHER_BRICKS: - case RED_NETHER_BRICK_SLAB: - case RED_NETHER_BRICK_STAIRS: - case RED_NETHER_BRICK_WALL: - case RED_SAND: - case RED_SANDSTONE: - case RED_SANDSTONE_SLAB: - case RED_SANDSTONE_STAIRS: - case RED_SANDSTONE_WALL: - case RED_SHULKER_BOX: - case RED_STAINED_GLASS: - case RED_STAINED_GLASS_PANE: - case RED_TERRACOTTA: - case RED_WALL_BANNER: - case RED_WOOL: - case REPEATING_COMMAND_BLOCK: - case SAND: - case SANDSTONE: - case SANDSTONE_SLAB: - case SANDSTONE_STAIRS: - case SANDSTONE_WALL: - case SEA_LANTERN: - case SHULKER_BOX: - case SLIME_BLOCK: - case SMITHING_TABLE: - case SMOKER: - case SMOOTH_QUARTZ: - case SMOOTH_QUARTZ_SLAB: - case SMOOTH_QUARTZ_STAIRS: - case SMOOTH_RED_SANDSTONE: - case SMOOTH_RED_SANDSTONE_SLAB: - case SMOOTH_RED_SANDSTONE_STAIRS: - case SMOOTH_SANDSTONE: - case SMOOTH_SANDSTONE_SLAB: - case SMOOTH_SANDSTONE_STAIRS: - case SMOOTH_STONE: - case SMOOTH_STONE_SLAB: - case SNOW_BLOCK: - case SOUL_SAND: - case SPAWNER: - case SPONGE: - case SPRUCE_DOOR: - case SPRUCE_FENCE: - case SPRUCE_FENCE_GATE: - case SPRUCE_LEAVES: - case SPRUCE_LOG: - case SPRUCE_PLANKS: - case SPRUCE_PRESSURE_PLATE: - case SPRUCE_SIGN: - case SPRUCE_SLAB: - case SPRUCE_STAIRS: - case SPRUCE_TRAPDOOR: - case SPRUCE_WALL_SIGN: - case SPRUCE_WOOD: - case STICKY_PISTON: - case STONE: - case STONECUTTER: - case STONE_BRICKS: - case STONE_BRICK_SLAB: - case STONE_BRICK_STAIRS: - case STONE_BRICK_WALL: - case STONE_PRESSURE_PLATE: - case STONE_SLAB: - case STONE_STAIRS: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - case STRUCTURE_BLOCK: - case TERRACOTTA: - case TNT: - case TRAPPED_CHEST: - case TUBE_CORAL_BLOCK: - case TURTLE_EGG: - case WET_SPONGE: - case WHITE_BANNER: - case WHITE_BED: - case WHITE_CONCRETE: - case WHITE_CONCRETE_POWDER: - case WHITE_GLAZED_TERRACOTTA: - case WHITE_SHULKER_BOX: - case WHITE_STAINED_GLASS: - case WHITE_STAINED_GLASS_PANE: - case WHITE_TERRACOTTA: - case WHITE_WALL_BANNER: - case WHITE_WOOL: - case YELLOW_BANNER: - case YELLOW_BED: - case YELLOW_CONCRETE: - case YELLOW_CONCRETE_POWDER: - case YELLOW_GLAZED_TERRACOTTA: - case YELLOW_SHULKER_BOX: - case YELLOW_STAINED_GLASS: - case YELLOW_STAINED_GLASS_PANE: - case YELLOW_TERRACOTTA: - case YELLOW_WALL_BANNER: - case YELLOW_WOOL: - // ----- Legacy Separator ----- - case LEGACY_STONE: - case LEGACY_GRASS: - case LEGACY_DIRT: - case LEGACY_COBBLESTONE: - case LEGACY_WOOD: - case LEGACY_BEDROCK: - case LEGACY_SAND: - case LEGACY_GRAVEL: - case LEGACY_GOLD_ORE: - case LEGACY_IRON_ORE: - case LEGACY_COAL_ORE: - case LEGACY_LOG: - case LEGACY_LEAVES: - case LEGACY_SPONGE: - case LEGACY_GLASS: - case LEGACY_LAPIS_ORE: - case LEGACY_LAPIS_BLOCK: - case LEGACY_DISPENSER: - case LEGACY_SANDSTONE: - case LEGACY_NOTE_BLOCK: - case LEGACY_BED_BLOCK: - case LEGACY_PISTON_STICKY_BASE: - case LEGACY_PISTON_BASE: - case LEGACY_PISTON_EXTENSION: - case LEGACY_WOOL: - case LEGACY_PISTON_MOVING_PIECE: - case LEGACY_GOLD_BLOCK: - case LEGACY_IRON_BLOCK: - case LEGACY_DOUBLE_STEP: - case LEGACY_STEP: - case LEGACY_BRICK: - case LEGACY_TNT: - case LEGACY_BOOKSHELF: - case LEGACY_MOSSY_COBBLESTONE: - case LEGACY_OBSIDIAN: - case LEGACY_MOB_SPAWNER: - case LEGACY_WOOD_STAIRS: - case LEGACY_CHEST: - case LEGACY_DIAMOND_ORE: - case LEGACY_DIAMOND_BLOCK: - case LEGACY_WORKBENCH: - case LEGACY_SOIL: - case LEGACY_FURNACE: - case LEGACY_BURNING_FURNACE: - case LEGACY_SIGN_POST: - case LEGACY_WOODEN_DOOR: - case LEGACY_COBBLESTONE_STAIRS: - case LEGACY_WALL_SIGN: - case LEGACY_STONE_PLATE: - case LEGACY_IRON_DOOR_BLOCK: - case LEGACY_WOOD_PLATE: - case LEGACY_REDSTONE_ORE: - case LEGACY_GLOWING_REDSTONE_ORE: - case LEGACY_ICE: - case LEGACY_SNOW_BLOCK: - case LEGACY_CACTUS: - case LEGACY_CLAY: - case LEGACY_JUKEBOX: - case LEGACY_FENCE: - case LEGACY_PUMPKIN: - case LEGACY_NETHERRACK: - case LEGACY_SOUL_SAND: - case LEGACY_GLOWSTONE: - case LEGACY_JACK_O_LANTERN: - case LEGACY_CAKE_BLOCK: - case LEGACY_STAINED_GLASS: - case LEGACY_TRAP_DOOR: - case LEGACY_MONSTER_EGGS: - case LEGACY_SMOOTH_BRICK: - case LEGACY_HUGE_MUSHROOM_1: - case LEGACY_HUGE_MUSHROOM_2: - case LEGACY_IRON_FENCE: - case LEGACY_THIN_GLASS: - case LEGACY_MELON_BLOCK: - case LEGACY_FENCE_GATE: - case LEGACY_BRICK_STAIRS: - case LEGACY_SMOOTH_STAIRS: - case LEGACY_MYCEL: - case LEGACY_NETHER_BRICK: - case LEGACY_NETHER_FENCE: - case LEGACY_NETHER_BRICK_STAIRS: - case LEGACY_ENCHANTMENT_TABLE: - case LEGACY_BREWING_STAND: - case LEGACY_CAULDRON: - case LEGACY_ENDER_PORTAL_FRAME: - case LEGACY_ENDER_STONE: - case LEGACY_DRAGON_EGG: - case LEGACY_REDSTONE_LAMP_OFF: - case LEGACY_REDSTONE_LAMP_ON: - case LEGACY_WOOD_DOUBLE_STEP: - case LEGACY_WOOD_STEP: - case LEGACY_SANDSTONE_STAIRS: - case LEGACY_EMERALD_ORE: - case LEGACY_ENDER_CHEST: - case LEGACY_EMERALD_BLOCK: - case LEGACY_SPRUCE_WOOD_STAIRS: - case LEGACY_BIRCH_WOOD_STAIRS: - case LEGACY_JUNGLE_WOOD_STAIRS: - case LEGACY_COMMAND: - case LEGACY_BEACON: - case LEGACY_COBBLE_WALL: - case LEGACY_ANVIL: - case LEGACY_TRAPPED_CHEST: - case LEGACY_GOLD_PLATE: - case LEGACY_IRON_PLATE: - case LEGACY_DAYLIGHT_DETECTOR: - case LEGACY_REDSTONE_BLOCK: - case LEGACY_QUARTZ_ORE: - case LEGACY_HOPPER: - case LEGACY_QUARTZ_BLOCK: - case LEGACY_QUARTZ_STAIRS: - case LEGACY_DROPPER: - case LEGACY_STAINED_CLAY: - case LEGACY_HAY_BLOCK: - case LEGACY_HARD_CLAY: - case LEGACY_COAL_BLOCK: - case LEGACY_STAINED_GLASS_PANE: - case LEGACY_LEAVES_2: - case LEGACY_LOG_2: - case LEGACY_ACACIA_STAIRS: - case LEGACY_DARK_OAK_STAIRS: - case LEGACY_PACKED_ICE: - case LEGACY_RED_SANDSTONE: - case LEGACY_SLIME_BLOCK: - case LEGACY_BARRIER: - case LEGACY_IRON_TRAPDOOR: - case LEGACY_PRISMARINE: - case LEGACY_SEA_LANTERN: - case LEGACY_DOUBLE_STONE_SLAB2: - case LEGACY_RED_SANDSTONE_STAIRS: - case LEGACY_STONE_SLAB2: - case LEGACY_SPRUCE_FENCE_GATE: - case LEGACY_BIRCH_FENCE_GATE: - case LEGACY_JUNGLE_FENCE_GATE: - case LEGACY_DARK_OAK_FENCE_GATE: - case LEGACY_ACACIA_FENCE_GATE: - case LEGACY_SPRUCE_FENCE: - case LEGACY_BIRCH_FENCE: - case LEGACY_JUNGLE_FENCE: - case LEGACY_DARK_OAK_FENCE: - case LEGACY_ACACIA_FENCE: - case LEGACY_STANDING_BANNER: - case LEGACY_WALL_BANNER: - case LEGACY_DAYLIGHT_DETECTOR_INVERTED: - case LEGACY_SPRUCE_DOOR: - case LEGACY_BIRCH_DOOR: - case LEGACY_JUNGLE_DOOR: - case LEGACY_ACACIA_DOOR: - case LEGACY_DARK_OAK_DOOR: - case LEGACY_PURPUR_BLOCK: - case LEGACY_PURPUR_PILLAR: - case LEGACY_PURPUR_STAIRS: - case LEGACY_PURPUR_DOUBLE_SLAB: - case LEGACY_PURPUR_SLAB: - case LEGACY_END_BRICKS: - case LEGACY_GRASS_PATH: - case LEGACY_STRUCTURE_BLOCK: - case LEGACY_COMMAND_REPEATING: - case LEGACY_COMMAND_CHAIN: - case LEGACY_FROSTED_ICE: - case LEGACY_MAGMA: - case LEGACY_NETHER_WART_BLOCK: - case LEGACY_RED_NETHER_BRICK: - case LEGACY_BONE_BLOCK: - case LEGACY_OBSERVER: - case LEGACY_WHITE_SHULKER_BOX: - case LEGACY_ORANGE_SHULKER_BOX: - case LEGACY_MAGENTA_SHULKER_BOX: - case LEGACY_LIGHT_BLUE_SHULKER_BOX: - case LEGACY_YELLOW_SHULKER_BOX: - case LEGACY_LIME_SHULKER_BOX: - case LEGACY_PINK_SHULKER_BOX: - case LEGACY_GRAY_SHULKER_BOX: - case LEGACY_SILVER_SHULKER_BOX: - case LEGACY_CYAN_SHULKER_BOX: - case LEGACY_PURPLE_SHULKER_BOX: - case LEGACY_BLUE_SHULKER_BOX: - case LEGACY_BROWN_SHULKER_BOX: - case LEGACY_GREEN_SHULKER_BOX: - case LEGACY_RED_SHULKER_BOX: - case LEGACY_BLACK_SHULKER_BOX: - case LEGACY_WHITE_GLAZED_TERRACOTTA: - case LEGACY_ORANGE_GLAZED_TERRACOTTA: - case LEGACY_MAGENTA_GLAZED_TERRACOTTA: - case LEGACY_LIGHT_BLUE_GLAZED_TERRACOTTA: - case LEGACY_YELLOW_GLAZED_TERRACOTTA: - case LEGACY_LIME_GLAZED_TERRACOTTA: - case LEGACY_PINK_GLAZED_TERRACOTTA: - case LEGACY_GRAY_GLAZED_TERRACOTTA: - case LEGACY_SILVER_GLAZED_TERRACOTTA: - case LEGACY_CYAN_GLAZED_TERRACOTTA: - case LEGACY_PURPLE_GLAZED_TERRACOTTA: - case LEGACY_BLUE_GLAZED_TERRACOTTA: - case LEGACY_BROWN_GLAZED_TERRACOTTA: - case LEGACY_GREEN_GLAZED_TERRACOTTA: - case LEGACY_RED_GLAZED_TERRACOTTA: - case LEGACY_BLACK_GLAZED_TERRACOTTA: - case LEGACY_CONCRETE: - case LEGACY_CONCRETE_POWDER: - // - return true; - default: - return false; - } - } - - /** - * Check if the material is an air block. - * - * @return True if this material is an air block. - */ - public boolean isAir() { - switch (this) { - // - case AIR: - case CAVE_AIR: - case VOID_AIR: - // ----- Legacy Separator ----- - case LEGACY_AIR: - // - 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 - * @deprecated currently does not have an implementation which is well - * linked to the underlying server. Contributions welcome. - */ - @Deprecated - public boolean isTransparent() { - if (!isBlock()) { - return false; - } - switch (this) { - // - case ACACIA_BUTTON: - case ACACIA_SAPLING: - case ACTIVATOR_RAIL: - case AIR: - case ALLIUM: - case ATTACHED_MELON_STEM: - case ATTACHED_PUMPKIN_STEM: - case AZURE_BLUET: - case BARRIER: - case BEETROOTS: - case BIRCH_BUTTON: - case BIRCH_SAPLING: - case BLACK_CARPET: - case BLUE_CARPET: - case BLUE_ORCHID: - case BROWN_CARPET: - case BROWN_MUSHROOM: - case CARROTS: - case CAVE_AIR: - case CHORUS_FLOWER: - case CHORUS_PLANT: - case COCOA: - case COMPARATOR: - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case CYAN_CARPET: - case DANDELION: - case DARK_OAK_BUTTON: - case DARK_OAK_SAPLING: - case DEAD_BUSH: - case DETECTOR_RAIL: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case END_GATEWAY: - case END_PORTAL: - case END_ROD: - case FERN: - case FIRE: - case FLOWER_POT: - case GRASS: - case GRAY_CARPET: - case GREEN_CARPET: - case JUNGLE_BUTTON: - case JUNGLE_SAPLING: - case LADDER: - case LARGE_FERN: - case LEVER: - case LIGHT_BLUE_CARPET: - case LIGHT_GRAY_CARPET: - case LILAC: - case LILY_PAD: - case LIME_CARPET: - case MAGENTA_CARPET: - case MELON_STEM: - case NETHER_PORTAL: - case NETHER_WART: - case OAK_BUTTON: - case OAK_SAPLING: - case ORANGE_CARPET: - case ORANGE_TULIP: - case OXEYE_DAISY: - case PEONY: - case PINK_CARPET: - case PINK_TULIP: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case POPPY: - case POTATOES: - case POTTED_ACACIA_SAPLING: - case POTTED_ALLIUM: - case POTTED_AZURE_BLUET: - case POTTED_BIRCH_SAPLING: - case POTTED_BLUE_ORCHID: - case POTTED_BROWN_MUSHROOM: - case POTTED_CACTUS: - case POTTED_DANDELION: - case POTTED_DARK_OAK_SAPLING: - case POTTED_DEAD_BUSH: - case POTTED_FERN: - case POTTED_JUNGLE_SAPLING: - case POTTED_OAK_SAPLING: - case POTTED_ORANGE_TULIP: - case POTTED_OXEYE_DAISY: - case POTTED_PINK_TULIP: - case POTTED_POPPY: - case POTTED_RED_MUSHROOM: - case POTTED_RED_TULIP: - case POTTED_SPRUCE_SAPLING: - case POTTED_WHITE_TULIP: - case POWERED_RAIL: - case PUMPKIN_STEM: - case PURPLE_CARPET: - case RAIL: - case REDSTONE_TORCH: - case REDSTONE_WALL_TORCH: - case REDSTONE_WIRE: - case RED_CARPET: - case RED_MUSHROOM: - case RED_TULIP: - case REPEATER: - case ROSE_BUSH: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case SNOW: - case SPRUCE_BUTTON: - case SPRUCE_SAPLING: - case STONE_BUTTON: - case STRUCTURE_VOID: - case SUGAR_CANE: - case SUNFLOWER: - case TALL_GRASS: - case TORCH: - case TRIPWIRE: - case TRIPWIRE_HOOK: - case VINE: - case VOID_AIR: - case WALL_TORCH: - case WHEAT: - case WHITE_CARPET: - case WHITE_TULIP: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case YELLOW_CARPET: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - // ----- Legacy Separator ----- - case LEGACY_AIR: - case LEGACY_SAPLING: - case LEGACY_POWERED_RAIL: - case LEGACY_DETECTOR_RAIL: - case LEGACY_LONG_GRASS: - case LEGACY_DEAD_BUSH: - case LEGACY_YELLOW_FLOWER: - case LEGACY_RED_ROSE: - case LEGACY_BROWN_MUSHROOM: - case LEGACY_RED_MUSHROOM: - case LEGACY_TORCH: - case LEGACY_FIRE: - case LEGACY_REDSTONE_WIRE: - case LEGACY_CROPS: - case LEGACY_LADDER: - case LEGACY_RAILS: - case LEGACY_LEVER: - case LEGACY_REDSTONE_TORCH_OFF: - case LEGACY_REDSTONE_TORCH_ON: - case LEGACY_STONE_BUTTON: - case LEGACY_SNOW: - case LEGACY_SUGAR_CANE_BLOCK: - case LEGACY_PORTAL: - case LEGACY_DIODE_BLOCK_OFF: - case LEGACY_DIODE_BLOCK_ON: - case LEGACY_PUMPKIN_STEM: - case LEGACY_MELON_STEM: - case LEGACY_VINE: - case LEGACY_WATER_LILY: - case LEGACY_NETHER_WARTS: - case LEGACY_ENDER_PORTAL: - case LEGACY_COCOA: - case LEGACY_TRIPWIRE_HOOK: - case LEGACY_TRIPWIRE: - case LEGACY_FLOWER_POT: - case LEGACY_CARROT: - case LEGACY_POTATO: - case LEGACY_WOOD_BUTTON: - case LEGACY_SKULL: - case LEGACY_REDSTONE_COMPARATOR_OFF: - case LEGACY_REDSTONE_COMPARATOR_ON: - case LEGACY_ACTIVATOR_RAIL: - case LEGACY_CARPET: - case LEGACY_DOUBLE_PLANT: - case LEGACY_END_ROD: - case LEGACY_CHORUS_PLANT: - case LEGACY_CHORUS_FLOWER: - case LEGACY_BEETROOT_BLOCK: - case LEGACY_END_GATEWAY: - case LEGACY_STRUCTURE_VOID: - // - 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 ACACIA_DOOR: - case ACACIA_FENCE: - case ACACIA_FENCE_GATE: - case ACACIA_LEAVES: - case ACACIA_LOG: - case ACACIA_PLANKS: - case ACACIA_PRESSURE_PLATE: - case ACACIA_SIGN: - case ACACIA_SLAB: - case ACACIA_STAIRS: - case ACACIA_TRAPDOOR: - case ACACIA_WALL_SIGN: - case ACACIA_WOOD: - case BAMBOO: - case BAMBOO_SAPLING: - case BARREL: - case BIRCH_DOOR: - case BIRCH_FENCE: - case BIRCH_FENCE_GATE: - case BIRCH_LEAVES: - case BIRCH_LOG: - case BIRCH_PLANKS: - case BIRCH_PRESSURE_PLATE: - case BIRCH_SIGN: - case BIRCH_SLAB: - case BIRCH_STAIRS: - case BIRCH_TRAPDOOR: - case BIRCH_WALL_SIGN: - case BIRCH_WOOD: - case BLACK_BANNER: - case BLACK_BED: - case BLACK_CARPET: - case BLACK_WALL_BANNER: - case BLACK_WOOL: - case BLUE_BANNER: - case BLUE_BED: - case BLUE_CARPET: - case BLUE_WALL_BANNER: - case BLUE_WOOL: - case BOOKSHELF: - case BROWN_BANNER: - case BROWN_BED: - case BROWN_CARPET: - case BROWN_MUSHROOM_BLOCK: - case BROWN_WALL_BANNER: - case BROWN_WOOL: - case CAMPFIRE: - case CARTOGRAPHY_TABLE: - case CHEST: - case COMPOSTER: - case CRAFTING_TABLE: - case CYAN_BANNER: - case CYAN_BED: - case CYAN_CARPET: - case CYAN_WALL_BANNER: - case CYAN_WOOL: - case DARK_OAK_DOOR: - case DARK_OAK_FENCE: - case DARK_OAK_FENCE_GATE: - case DARK_OAK_LEAVES: - case DARK_OAK_LOG: - case DARK_OAK_PLANKS: - case DARK_OAK_PRESSURE_PLATE: - case DARK_OAK_SIGN: - case DARK_OAK_SLAB: - case DARK_OAK_STAIRS: - case DARK_OAK_TRAPDOOR: - case DARK_OAK_WALL_SIGN: - case DARK_OAK_WOOD: - case DAYLIGHT_DETECTOR: - case DEAD_BUSH: - case FERN: - case FLETCHING_TABLE: - case GRASS: - case GRAY_BANNER: - case GRAY_BED: - case GRAY_CARPET: - case GRAY_WALL_BANNER: - case GRAY_WOOL: - case GREEN_BANNER: - case GREEN_BED: - case GREEN_CARPET: - case GREEN_WALL_BANNER: - case GREEN_WOOL: - case JUKEBOX: - case JUNGLE_DOOR: - case JUNGLE_FENCE: - case JUNGLE_FENCE_GATE: - case JUNGLE_LEAVES: - case JUNGLE_LOG: - case JUNGLE_PLANKS: - case JUNGLE_PRESSURE_PLATE: - case JUNGLE_SIGN: - case JUNGLE_SLAB: - case JUNGLE_STAIRS: - case JUNGLE_TRAPDOOR: - case JUNGLE_WALL_SIGN: - case JUNGLE_WOOD: - case LARGE_FERN: - case LECTERN: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_BED: - case LIGHT_BLUE_CARPET: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_BLUE_WOOL: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_BED: - case LIGHT_GRAY_CARPET: - case LIGHT_GRAY_WALL_BANNER: - case LIGHT_GRAY_WOOL: - case LILAC: - case LIME_BANNER: - case LIME_BED: - case LIME_CARPET: - case LIME_WALL_BANNER: - case LIME_WOOL: - case LOOM: - case MAGENTA_BANNER: - case MAGENTA_BED: - case MAGENTA_CARPET: - case MAGENTA_WALL_BANNER: - case MAGENTA_WOOL: - case MUSHROOM_STEM: - case NOTE_BLOCK: - case OAK_DOOR: - case OAK_FENCE: - case OAK_FENCE_GATE: - case OAK_LEAVES: - case OAK_LOG: - case OAK_PLANKS: - case OAK_PRESSURE_PLATE: - case OAK_SIGN: - case OAK_SLAB: - case OAK_STAIRS: - case OAK_TRAPDOOR: - case OAK_WALL_SIGN: - case OAK_WOOD: - case ORANGE_BANNER: - case ORANGE_BED: - case ORANGE_CARPET: - case ORANGE_WALL_BANNER: - case ORANGE_WOOL: - case PEONY: - case PINK_BANNER: - case PINK_BED: - case PINK_CARPET: - case PINK_WALL_BANNER: - case PINK_WOOL: - case PURPLE_BANNER: - case PURPLE_BED: - case PURPLE_CARPET: - case PURPLE_WALL_BANNER: - case PURPLE_WOOL: - case RED_BANNER: - case RED_BED: - case RED_CARPET: - case RED_MUSHROOM_BLOCK: - case RED_WALL_BANNER: - case RED_WOOL: - case ROSE_BUSH: - case SMITHING_TABLE: - case SPRUCE_DOOR: - case SPRUCE_FENCE: - case SPRUCE_FENCE_GATE: - case SPRUCE_LEAVES: - case SPRUCE_LOG: - case SPRUCE_PLANKS: - case SPRUCE_PRESSURE_PLATE: - case SPRUCE_SIGN: - case SPRUCE_SLAB: - case SPRUCE_STAIRS: - case SPRUCE_TRAPDOOR: - case SPRUCE_WALL_SIGN: - case SPRUCE_WOOD: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - case SUNFLOWER: - case TALL_GRASS: - case TNT: - case TRAPPED_CHEST: - case VINE: - case WHITE_BANNER: - case WHITE_BED: - case WHITE_CARPET: - case WHITE_WALL_BANNER: - case WHITE_WOOL: - case YELLOW_BANNER: - case YELLOW_BED: - case YELLOW_CARPET: - case YELLOW_WALL_BANNER: - case YELLOW_WOOL: - // ----- Legacy Separator ----- - case LEGACY_WOOD: - case LEGACY_LOG: - case LEGACY_LEAVES: - case LEGACY_NOTE_BLOCK: - case LEGACY_BED_BLOCK: - case LEGACY_LONG_GRASS: - case LEGACY_DEAD_BUSH: - case LEGACY_WOOL: - case LEGACY_TNT: - case LEGACY_BOOKSHELF: - case LEGACY_WOOD_STAIRS: - case LEGACY_CHEST: - case LEGACY_WORKBENCH: - case LEGACY_SIGN_POST: - case LEGACY_WOODEN_DOOR: - case LEGACY_WALL_SIGN: - case LEGACY_WOOD_PLATE: - case LEGACY_JUKEBOX: - case LEGACY_FENCE: - case LEGACY_TRAP_DOOR: - case LEGACY_HUGE_MUSHROOM_1: - case LEGACY_HUGE_MUSHROOM_2: - case LEGACY_VINE: - case LEGACY_FENCE_GATE: - case LEGACY_WOOD_DOUBLE_STEP: - case LEGACY_WOOD_STEP: - case LEGACY_SPRUCE_WOOD_STAIRS: - case LEGACY_BIRCH_WOOD_STAIRS: - case LEGACY_JUNGLE_WOOD_STAIRS: - case LEGACY_TRAPPED_CHEST: - case LEGACY_DAYLIGHT_DETECTOR: - case LEGACY_CARPET: - case LEGACY_LEAVES_2: - case LEGACY_LOG_2: - case LEGACY_ACACIA_STAIRS: - case LEGACY_DARK_OAK_STAIRS: - case LEGACY_DOUBLE_PLANT: - case LEGACY_SPRUCE_FENCE_GATE: - case LEGACY_BIRCH_FENCE_GATE: - case LEGACY_JUNGLE_FENCE_GATE: - case LEGACY_DARK_OAK_FENCE_GATE: - case LEGACY_ACACIA_FENCE_GATE: - case LEGACY_SPRUCE_FENCE: - case LEGACY_BIRCH_FENCE: - case LEGACY_JUNGLE_FENCE: - case LEGACY_DARK_OAK_FENCE: - case LEGACY_ACACIA_FENCE: - case LEGACY_STANDING_BANNER: - case LEGACY_WALL_BANNER: - case LEGACY_DAYLIGHT_DETECTOR_INVERTED: - case LEGACY_SPRUCE_DOOR: - case LEGACY_BIRCH_DOOR: - case LEGACY_JUNGLE_DOOR: - case LEGACY_ACACIA_DOOR: - case LEGACY_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 ACACIA_FENCE: - case ACACIA_FENCE_GATE: - case ACACIA_LEAVES: - case ACACIA_LOG: - case ACACIA_PLANKS: - case ACACIA_SLAB: - case ACACIA_STAIRS: - case ACACIA_WOOD: - case ALLIUM: - case AZURE_BLUET: - case BAMBOO: - case BIRCH_FENCE: - case BIRCH_FENCE_GATE: - case BIRCH_LEAVES: - case BIRCH_LOG: - case BIRCH_PLANKS: - case BIRCH_SLAB: - case BIRCH_STAIRS: - case BIRCH_WOOD: - case BLACK_CARPET: - case BLACK_WOOL: - case BLUE_CARPET: - case BLUE_ORCHID: - case BLUE_WOOL: - case BOOKSHELF: - case BROWN_CARPET: - case BROWN_WOOL: - case COAL_BLOCK: - case COMPOSTER: - case CORNFLOWER: - case CYAN_CARPET: - case CYAN_WOOL: - case DANDELION: - case DARK_OAK_FENCE: - case DARK_OAK_FENCE_GATE: - case DARK_OAK_LEAVES: - case DARK_OAK_LOG: - case DARK_OAK_PLANKS: - case DARK_OAK_SLAB: - case DARK_OAK_STAIRS: - case DARK_OAK_WOOD: - case DEAD_BUSH: - case DRIED_KELP_BLOCK: - case FERN: - case GRASS: - case GRAY_CARPET: - case GRAY_WOOL: - case GREEN_CARPET: - case GREEN_WOOL: - case HAY_BLOCK: - case JUNGLE_FENCE: - case JUNGLE_FENCE_GATE: - case JUNGLE_LEAVES: - case JUNGLE_LOG: - case JUNGLE_PLANKS: - case JUNGLE_SLAB: - case JUNGLE_STAIRS: - case JUNGLE_WOOD: - case LARGE_FERN: - case LECTERN: - case LIGHT_BLUE_CARPET: - case LIGHT_BLUE_WOOL: - case LIGHT_GRAY_CARPET: - case LIGHT_GRAY_WOOL: - case LILAC: - case LILY_OF_THE_VALLEY: - case LIME_CARPET: - case LIME_WOOL: - case MAGENTA_CARPET: - case MAGENTA_WOOL: - case OAK_FENCE: - case OAK_FENCE_GATE: - case OAK_LEAVES: - case OAK_LOG: - case OAK_PLANKS: - case OAK_SLAB: - case OAK_STAIRS: - case OAK_WOOD: - case ORANGE_CARPET: - case ORANGE_TULIP: - case ORANGE_WOOL: - case OXEYE_DAISY: - case PEONY: - case PINK_CARPET: - case PINK_TULIP: - case PINK_WOOL: - case POPPY: - case PURPLE_CARPET: - case PURPLE_WOOL: - case RED_CARPET: - case RED_TULIP: - case RED_WOOL: - case ROSE_BUSH: - case SCAFFOLDING: - case SPRUCE_FENCE: - case SPRUCE_FENCE_GATE: - case SPRUCE_LEAVES: - case SPRUCE_LOG: - case SPRUCE_PLANKS: - case SPRUCE_SLAB: - case SPRUCE_STAIRS: - case SPRUCE_WOOD: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - case SUNFLOWER: - case SWEET_BERRY_BUSH: - case TALL_GRASS: - case TNT: - case VINE: - case WHITE_CARPET: - case WHITE_TULIP: - case WHITE_WOOL: - case WITHER_ROSE: - case YELLOW_CARPET: - case YELLOW_WOOL: - // ----- Legacy Separator ----- - case LEGACY_WOOD: - case LEGACY_LOG: - case LEGACY_LEAVES: - case LEGACY_LONG_GRASS: - case LEGACY_WOOL: - case LEGACY_YELLOW_FLOWER: - case LEGACY_RED_ROSE: - case LEGACY_TNT: - case LEGACY_BOOKSHELF: - case LEGACY_WOOD_STAIRS: - case LEGACY_FENCE: - case LEGACY_VINE: - case LEGACY_WOOD_DOUBLE_STEP: - case LEGACY_WOOD_STEP: - case LEGACY_SPRUCE_WOOD_STAIRS: - case LEGACY_BIRCH_WOOD_STAIRS: - case LEGACY_JUNGLE_WOOD_STAIRS: - case LEGACY_HAY_BLOCK: - case LEGACY_COAL_BLOCK: - case LEGACY_LEAVES_2: - case LEGACY_LOG_2: - case LEGACY_CARPET: - case LEGACY_DOUBLE_PLANT: - case LEGACY_DEAD_BUSH: - case LEGACY_FENCE_GATE: - case LEGACY_SPRUCE_FENCE_GATE: - case LEGACY_BIRCH_FENCE_GATE: - case LEGACY_JUNGLE_FENCE_GATE: - case LEGACY_DARK_OAK_FENCE_GATE: - case LEGACY_ACACIA_FENCE_GATE: - case LEGACY_SPRUCE_FENCE: - case LEGACY_BIRCH_FENCE: - case LEGACY_JUNGLE_FENCE: - case LEGACY_DARK_OAK_FENCE: - case LEGACY_ACACIA_FENCE: - case LEGACY_ACACIA_STAIRS: - case LEGACY_DARK_OAK_STAIRS: - // - return true; - default: - return false; - } - } - - /** - * Checks if this Material can be used as fuel in a Furnace - * - * @return true if this Material can be used as fuel. - */ - public boolean isFuel() { - switch (this) { - // - case ACACIA_BOAT: - case ACACIA_BUTTON: - case ACACIA_DOOR: - case ACACIA_FENCE: - case ACACIA_FENCE_GATE: - case ACACIA_LOG: - case ACACIA_PLANKS: - case ACACIA_PRESSURE_PLATE: - case ACACIA_SAPLING: - case ACACIA_SIGN: - case ACACIA_SLAB: - case ACACIA_STAIRS: - case ACACIA_TRAPDOOR: - case ACACIA_WOOD: - case BAMBOO: - case BARREL: - case BIRCH_BOAT: - case BIRCH_BUTTON: - case BIRCH_DOOR: - case BIRCH_FENCE: - case BIRCH_FENCE_GATE: - case BIRCH_LOG: - case BIRCH_PLANKS: - case BIRCH_PRESSURE_PLATE: - case BIRCH_SAPLING: - case BIRCH_SIGN: - case BIRCH_SLAB: - case BIRCH_STAIRS: - case BIRCH_TRAPDOOR: - case BIRCH_WOOD: - case BLACK_BANNER: - case BLACK_CARPET: - case BLACK_WOOL: - case BLAZE_ROD: - case BLUE_BANNER: - case BLUE_CARPET: - case BLUE_WOOL: - case BOOKSHELF: - case BOW: - case BOWL: - case BROWN_BANNER: - case BROWN_CARPET: - case BROWN_WOOL: - case CARTOGRAPHY_TABLE: - case CHARCOAL: - case CHEST: - case COAL: - case COAL_BLOCK: - case COMPOSTER: - case CRAFTING_TABLE: - case CROSSBOW: - case CYAN_BANNER: - case CYAN_CARPET: - case CYAN_WOOL: - case DARK_OAK_BOAT: - case DARK_OAK_BUTTON: - case DARK_OAK_DOOR: - case DARK_OAK_FENCE: - case DARK_OAK_FENCE_GATE: - case DARK_OAK_LOG: - case DARK_OAK_PLANKS: - case DARK_OAK_PRESSURE_PLATE: - case DARK_OAK_SAPLING: - case DARK_OAK_SIGN: - case DARK_OAK_SLAB: - case DARK_OAK_STAIRS: - case DARK_OAK_TRAPDOOR: - case DARK_OAK_WOOD: - case DAYLIGHT_DETECTOR: - case DEAD_BUSH: - case DRIED_KELP_BLOCK: - case FISHING_ROD: - case FLETCHING_TABLE: - case GRAY_BANNER: - case GRAY_CARPET: - case GRAY_WOOL: - case GREEN_BANNER: - case GREEN_CARPET: - case GREEN_WOOL: - case JUKEBOX: - case JUNGLE_BOAT: - case JUNGLE_BUTTON: - case JUNGLE_DOOR: - case JUNGLE_FENCE: - case JUNGLE_FENCE_GATE: - case JUNGLE_LOG: - case JUNGLE_PLANKS: - case JUNGLE_PRESSURE_PLATE: - case JUNGLE_SAPLING: - case JUNGLE_SIGN: - case JUNGLE_SLAB: - case JUNGLE_STAIRS: - case JUNGLE_TRAPDOOR: - case JUNGLE_WOOD: - case LADDER: - case LAVA_BUCKET: - case LECTERN: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_CARPET: - case LIGHT_BLUE_WOOL: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_CARPET: - case LIGHT_GRAY_WOOL: - case LIME_BANNER: - case LIME_CARPET: - case LIME_WOOL: - case LOOM: - case MAGENTA_BANNER: - case MAGENTA_CARPET: - case MAGENTA_WOOL: - case NOTE_BLOCK: - case OAK_BOAT: - case OAK_BUTTON: - case OAK_DOOR: - case OAK_FENCE: - case OAK_FENCE_GATE: - case OAK_LOG: - case OAK_PLANKS: - case OAK_PRESSURE_PLATE: - case OAK_SAPLING: - case OAK_SIGN: - case OAK_SLAB: - case OAK_STAIRS: - case OAK_TRAPDOOR: - case OAK_WOOD: - case ORANGE_BANNER: - case ORANGE_CARPET: - case ORANGE_WOOL: - case PINK_BANNER: - case PINK_CARPET: - case PINK_WOOL: - case PURPLE_BANNER: - case PURPLE_CARPET: - case PURPLE_WOOL: - case RED_BANNER: - case RED_CARPET: - case RED_WOOL: - case SCAFFOLDING: - case SMITHING_TABLE: - case SPRUCE_BOAT: - case SPRUCE_BUTTON: - case SPRUCE_DOOR: - case SPRUCE_FENCE: - case SPRUCE_FENCE_GATE: - case SPRUCE_LOG: - case SPRUCE_PLANKS: - case SPRUCE_PRESSURE_PLATE: - case SPRUCE_SAPLING: - case SPRUCE_SIGN: - case SPRUCE_SLAB: - case SPRUCE_STAIRS: - case SPRUCE_TRAPDOOR: - case SPRUCE_WOOD: - case STICK: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - case TRAPPED_CHEST: - case WHITE_BANNER: - case WHITE_CARPET: - case WHITE_WOOL: - case WOODEN_AXE: - case WOODEN_HOE: - case WOODEN_PICKAXE: - case WOODEN_SHOVEL: - case WOODEN_SWORD: - case YELLOW_BANNER: - case YELLOW_CARPET: - case YELLOW_WOOL: - // ----- Legacy Separator ----- - case LEGACY_LAVA_BUCKET: - case LEGACY_COAL_BLOCK: - case LEGACY_BLAZE_ROD: - case LEGACY_COAL: - case LEGACY_BOAT: - case LEGACY_BOAT_ACACIA: - case LEGACY_BOAT_BIRCH: - case LEGACY_BOAT_DARK_OAK: - case LEGACY_BOAT_JUNGLE: - case LEGACY_BOAT_SPRUCE: - case LEGACY_LOG: - case LEGACY_LOG_2: - case LEGACY_WOOD: - case LEGACY_WOOD_PLATE: - case LEGACY_FENCE: - case LEGACY_ACACIA_FENCE: - case LEGACY_BIRCH_FENCE: - case LEGACY_DARK_OAK_FENCE: - case LEGACY_JUNGLE_FENCE: - case LEGACY_SPRUCE_FENCE: - case LEGACY_FENCE_GATE: - case LEGACY_ACACIA_FENCE_GATE: - case LEGACY_BIRCH_FENCE_GATE: - case LEGACY_DARK_OAK_FENCE_GATE: - case LEGACY_JUNGLE_FENCE_GATE: - case LEGACY_SPRUCE_FENCE_GATE: - case LEGACY_WOOD_STAIRS: - case LEGACY_ACACIA_STAIRS: - case LEGACY_BIRCH_WOOD_STAIRS: - case LEGACY_DARK_OAK_STAIRS: - case LEGACY_JUNGLE_WOOD_STAIRS: - case LEGACY_SPRUCE_WOOD_STAIRS: - case LEGACY_TRAP_DOOR: - case LEGACY_WORKBENCH: - case LEGACY_BOOKSHELF: - case LEGACY_CHEST: - case LEGACY_TRAPPED_CHEST: - case LEGACY_DAYLIGHT_DETECTOR: - case LEGACY_JUKEBOX: - case LEGACY_NOTE_BLOCK: - case LEGACY_BANNER: - case LEGACY_FISHING_ROD: - case LEGACY_LADDER: - case LEGACY_WOOD_SWORD: - case LEGACY_WOOD_PICKAXE: - case LEGACY_WOOD_AXE: - case LEGACY_WOOD_SPADE: - case LEGACY_WOOD_HOE: - case LEGACY_BOW: - case LEGACY_SIGN: - case LEGACY_WOOD_DOOR: - case LEGACY_ACACIA_DOOR_ITEM: - case LEGACY_BIRCH_DOOR_ITEM: - case LEGACY_DARK_OAK_DOOR_ITEM: - case LEGACY_JUNGLE_DOOR_ITEM: - case LEGACY_SPRUCE_DOOR_ITEM: - case LEGACY_WOOD_STEP: - case LEGACY_SAPLING: - case LEGACY_STICK: - case LEGACY_WOOD_BUTTON: - case LEGACY_WOOL: - case LEGACY_CARPET: - case LEGACY_BOWL: - // - 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 ACACIA_LOG: - case ACACIA_PLANKS: - case ACACIA_WOOD: - case ANDESITE: - case BARREL: - case BARRIER: - case BEDROCK: - case BIRCH_LOG: - case BIRCH_PLANKS: - case BIRCH_WOOD: - case BLACK_CONCRETE: - case BLACK_CONCRETE_POWDER: - case BLACK_GLAZED_TERRACOTTA: - case BLACK_SHULKER_BOX: - case BLACK_TERRACOTTA: - case BLACK_WOOL: - case BLAST_FURNACE: - case BLUE_CONCRETE: - case BLUE_CONCRETE_POWDER: - case BLUE_GLAZED_TERRACOTTA: - case BLUE_ICE: - case BLUE_SHULKER_BOX: - case BLUE_TERRACOTTA: - case BLUE_WOOL: - case BONE_BLOCK: - case BOOKSHELF: - case BRAIN_CORAL_BLOCK: - case BRICKS: - case BROWN_CONCRETE: - case BROWN_CONCRETE_POWDER: - case BROWN_GLAZED_TERRACOTTA: - case BROWN_MUSHROOM_BLOCK: - case BROWN_SHULKER_BOX: - case BROWN_TERRACOTTA: - case BROWN_WOOL: - case BUBBLE_CORAL_BLOCK: - case CARTOGRAPHY_TABLE: - case CARVED_PUMPKIN: - case CHAIN_COMMAND_BLOCK: - case CHISELED_QUARTZ_BLOCK: - case CHISELED_RED_SANDSTONE: - case CHISELED_SANDSTONE: - case CHISELED_STONE_BRICKS: - case CLAY: - case COAL_BLOCK: - case COAL_ORE: - case COARSE_DIRT: - case COBBLESTONE: - case COMMAND_BLOCK: - case CRACKED_STONE_BRICKS: - case CRAFTING_TABLE: - case CUT_RED_SANDSTONE: - case CUT_SANDSTONE: - case CYAN_CONCRETE: - case CYAN_CONCRETE_POWDER: - case CYAN_GLAZED_TERRACOTTA: - case CYAN_SHULKER_BOX: - case CYAN_TERRACOTTA: - case CYAN_WOOL: - case DARK_OAK_LOG: - case DARK_OAK_PLANKS: - case DARK_OAK_WOOD: - case DARK_PRISMARINE: - case DEAD_BRAIN_CORAL_BLOCK: - case DEAD_BUBBLE_CORAL_BLOCK: - case DEAD_FIRE_CORAL_BLOCK: - case DEAD_HORN_CORAL_BLOCK: - case DEAD_TUBE_CORAL_BLOCK: - case DIAMOND_BLOCK: - case DIAMOND_ORE: - case DIORITE: - case DIRT: - case DISPENSER: - case DRIED_KELP_BLOCK: - case DROPPER: - case EMERALD_BLOCK: - case EMERALD_ORE: - case END_STONE: - case END_STONE_BRICKS: - case FIRE_CORAL_BLOCK: - case FLETCHING_TABLE: - case FURNACE: - case GOLD_BLOCK: - case GOLD_ORE: - case GRANITE: - case GRASS_BLOCK: - case GRAVEL: - case GRAY_CONCRETE: - case GRAY_CONCRETE_POWDER: - case GRAY_GLAZED_TERRACOTTA: - case GRAY_SHULKER_BOX: - case GRAY_TERRACOTTA: - case GRAY_WOOL: - case GREEN_CONCRETE: - case GREEN_CONCRETE_POWDER: - case GREEN_GLAZED_TERRACOTTA: - case GREEN_SHULKER_BOX: - case GREEN_TERRACOTTA: - case GREEN_WOOL: - case HAY_BLOCK: - case HORN_CORAL_BLOCK: - case INFESTED_CHISELED_STONE_BRICKS: - case INFESTED_COBBLESTONE: - case INFESTED_CRACKED_STONE_BRICKS: - case INFESTED_MOSSY_STONE_BRICKS: - case INFESTED_STONE: - case INFESTED_STONE_BRICKS: - case IRON_BLOCK: - case IRON_ORE: - case JACK_O_LANTERN: - case JIGSAW: - case JUKEBOX: - case JUNGLE_LOG: - case JUNGLE_PLANKS: - case JUNGLE_WOOD: - case LAPIS_BLOCK: - case LAPIS_ORE: - case LIGHT_BLUE_CONCRETE: - case LIGHT_BLUE_CONCRETE_POWDER: - case LIGHT_BLUE_GLAZED_TERRACOTTA: - case LIGHT_BLUE_SHULKER_BOX: - case LIGHT_BLUE_TERRACOTTA: - case LIGHT_BLUE_WOOL: - case LIGHT_GRAY_CONCRETE: - case LIGHT_GRAY_CONCRETE_POWDER: - case LIGHT_GRAY_GLAZED_TERRACOTTA: - case LIGHT_GRAY_SHULKER_BOX: - case LIGHT_GRAY_TERRACOTTA: - case LIGHT_GRAY_WOOL: - case LIME_CONCRETE: - case LIME_CONCRETE_POWDER: - case LIME_GLAZED_TERRACOTTA: - case LIME_SHULKER_BOX: - case LIME_TERRACOTTA: - case LIME_WOOL: - case LOOM: - case MAGENTA_CONCRETE: - case MAGENTA_CONCRETE_POWDER: - case MAGENTA_GLAZED_TERRACOTTA: - case MAGENTA_SHULKER_BOX: - case MAGENTA_TERRACOTTA: - case MAGENTA_WOOL: - case MAGMA_BLOCK: - case MELON: - case MOSSY_COBBLESTONE: - case MOSSY_STONE_BRICKS: - case MUSHROOM_STEM: - case MYCELIUM: - case NETHERRACK: - case NETHER_BRICKS: - case NETHER_QUARTZ_ORE: - case NETHER_WART_BLOCK: - case NOTE_BLOCK: - case OAK_LOG: - case OAK_PLANKS: - case OAK_WOOD: - case OBSIDIAN: - case ORANGE_CONCRETE: - case ORANGE_CONCRETE_POWDER: - case ORANGE_GLAZED_TERRACOTTA: - case ORANGE_SHULKER_BOX: - case ORANGE_TERRACOTTA: - case ORANGE_WOOL: - case PACKED_ICE: - case PINK_CONCRETE: - case PINK_CONCRETE_POWDER: - case PINK_GLAZED_TERRACOTTA: - case PINK_SHULKER_BOX: - case PINK_TERRACOTTA: - case PINK_WOOL: - case PODZOL: - case POLISHED_ANDESITE: - case POLISHED_DIORITE: - case POLISHED_GRANITE: - case PRISMARINE: - case PRISMARINE_BRICKS: - case PUMPKIN: - case PURPLE_CONCRETE: - case PURPLE_CONCRETE_POWDER: - case PURPLE_GLAZED_TERRACOTTA: - case PURPLE_SHULKER_BOX: - case PURPLE_TERRACOTTA: - case PURPLE_WOOL: - case PURPUR_BLOCK: - case PURPUR_PILLAR: - case QUARTZ_BLOCK: - case QUARTZ_PILLAR: - case REDSTONE_LAMP: - case REDSTONE_ORE: - case RED_CONCRETE: - case RED_CONCRETE_POWDER: - case RED_GLAZED_TERRACOTTA: - case RED_MUSHROOM_BLOCK: - case RED_NETHER_BRICKS: - case RED_SAND: - case RED_SANDSTONE: - case RED_SHULKER_BOX: - case RED_TERRACOTTA: - case RED_WOOL: - case REPEATING_COMMAND_BLOCK: - case SAND: - case SANDSTONE: - case SHULKER_BOX: - case SLIME_BLOCK: - case SMITHING_TABLE: - case SMOKER: - case SMOOTH_QUARTZ: - case SMOOTH_RED_SANDSTONE: - case SMOOTH_SANDSTONE: - case SMOOTH_STONE: - case SNOW_BLOCK: - case SOUL_SAND: - case SPAWNER: - case SPONGE: - case SPRUCE_LOG: - case SPRUCE_PLANKS: - case SPRUCE_WOOD: - case STONE: - case STONE_BRICKS: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - case STRUCTURE_BLOCK: - case TERRACOTTA: - case TUBE_CORAL_BLOCK: - case WET_SPONGE: - case WHITE_CONCRETE: - case WHITE_CONCRETE_POWDER: - case WHITE_GLAZED_TERRACOTTA: - case WHITE_SHULKER_BOX: - case WHITE_TERRACOTTA: - case WHITE_WOOL: - case YELLOW_CONCRETE: - case YELLOW_CONCRETE_POWDER: - case YELLOW_GLAZED_TERRACOTTA: - case YELLOW_SHULKER_BOX: - case YELLOW_TERRACOTTA: - case YELLOW_WOOL: - // ----- Legacy Separator ----- - case LEGACY_STONE: - case LEGACY_GRASS: - case LEGACY_DIRT: - case LEGACY_COBBLESTONE: - case LEGACY_WOOD: - case LEGACY_BEDROCK: - case LEGACY_SAND: - case LEGACY_GRAVEL: - case LEGACY_GOLD_ORE: - case LEGACY_IRON_ORE: - case LEGACY_COAL_ORE: - case LEGACY_LOG: - case LEGACY_SPONGE: - case LEGACY_LAPIS_ORE: - case LEGACY_LAPIS_BLOCK: - case LEGACY_DISPENSER: - case LEGACY_SANDSTONE: - case LEGACY_NOTE_BLOCK: - case LEGACY_WOOL: - case LEGACY_GOLD_BLOCK: - case LEGACY_IRON_BLOCK: - case LEGACY_DOUBLE_STEP: - case LEGACY_BRICK: - case LEGACY_BOOKSHELF: - case LEGACY_MOSSY_COBBLESTONE: - case LEGACY_OBSIDIAN: - case LEGACY_MOB_SPAWNER: - case LEGACY_DIAMOND_ORE: - case LEGACY_DIAMOND_BLOCK: - case LEGACY_WORKBENCH: - case LEGACY_FURNACE: - case LEGACY_BURNING_FURNACE: - case LEGACY_REDSTONE_ORE: - case LEGACY_GLOWING_REDSTONE_ORE: - case LEGACY_SNOW_BLOCK: - case LEGACY_CLAY: - case LEGACY_JUKEBOX: - case LEGACY_PUMPKIN: - case LEGACY_NETHERRACK: - case LEGACY_SOUL_SAND: - case LEGACY_JACK_O_LANTERN: - case LEGACY_MONSTER_EGGS: - case LEGACY_SMOOTH_BRICK: - case LEGACY_HUGE_MUSHROOM_1: - case LEGACY_HUGE_MUSHROOM_2: - case LEGACY_MELON_BLOCK: - case LEGACY_MYCEL: - case LEGACY_NETHER_BRICK: - case LEGACY_ENDER_STONE: - case LEGACY_REDSTONE_LAMP_OFF: - case LEGACY_REDSTONE_LAMP_ON: - case LEGACY_WOOD_DOUBLE_STEP: - case LEGACY_EMERALD_ORE: - case LEGACY_EMERALD_BLOCK: - case LEGACY_COMMAND: - case LEGACY_QUARTZ_ORE: - case LEGACY_QUARTZ_BLOCK: - case LEGACY_DROPPER: - case LEGACY_STAINED_CLAY: - case LEGACY_HAY_BLOCK: - case LEGACY_HARD_CLAY: - case LEGACY_COAL_BLOCK: - case LEGACY_LOG_2: - case LEGACY_PACKED_ICE: - case LEGACY_SLIME_BLOCK: - case LEGACY_BARRIER: - case LEGACY_PRISMARINE: - case LEGACY_RED_SANDSTONE: - case LEGACY_DOUBLE_STONE_SLAB2: - case LEGACY_PURPUR_BLOCK: - case LEGACY_PURPUR_PILLAR: - case LEGACY_PURPUR_DOUBLE_SLAB: - case LEGACY_END_BRICKS: - case LEGACY_STRUCTURE_BLOCK: - case LEGACY_COMMAND_REPEATING: - case LEGACY_COMMAND_CHAIN: - case LEGACY_MAGMA: - case LEGACY_NETHER_WART_BLOCK: - case LEGACY_RED_NETHER_BRICK: - case LEGACY_BONE_BLOCK: - case LEGACY_WHITE_GLAZED_TERRACOTTA: - case LEGACY_ORANGE_GLAZED_TERRACOTTA: - case LEGACY_MAGENTA_GLAZED_TERRACOTTA: - case LEGACY_LIGHT_BLUE_GLAZED_TERRACOTTA: - case LEGACY_YELLOW_GLAZED_TERRACOTTA: - case LEGACY_LIME_GLAZED_TERRACOTTA: - case LEGACY_PINK_GLAZED_TERRACOTTA: - case LEGACY_GRAY_GLAZED_TERRACOTTA: - case LEGACY_SILVER_GLAZED_TERRACOTTA: - case LEGACY_CYAN_GLAZED_TERRACOTTA: - case LEGACY_PURPLE_GLAZED_TERRACOTTA: - case LEGACY_BLUE_GLAZED_TERRACOTTA: - case LEGACY_BROWN_GLAZED_TERRACOTTA: - case LEGACY_GREEN_GLAZED_TERRACOTTA: - case LEGACY_RED_GLAZED_TERRACOTTA: - case LEGACY_BLACK_GLAZED_TERRACOTTA: - case LEGACY_CONCRETE: - case LEGACY_CONCRETE_POWDER: - // - return true; - default: - return false; - } - } - - /** - * @return True if this material is affected by gravity. - */ - public boolean hasGravity() { - if (!isBlock()) { - return false; - } - switch (this) { - // - case ANVIL: - case BLACK_CONCRETE_POWDER: - case BLUE_CONCRETE_POWDER: - case BROWN_CONCRETE_POWDER: - case CHIPPED_ANVIL: - case CYAN_CONCRETE_POWDER: - case DAMAGED_ANVIL: - case DRAGON_EGG: - case GRAVEL: - case GRAY_CONCRETE_POWDER: - case GREEN_CONCRETE_POWDER: - case LIGHT_BLUE_CONCRETE_POWDER: - case LIGHT_GRAY_CONCRETE_POWDER: - case LIME_CONCRETE_POWDER: - case MAGENTA_CONCRETE_POWDER: - case ORANGE_CONCRETE_POWDER: - case PINK_CONCRETE_POWDER: - case PURPLE_CONCRETE_POWDER: - case RED_CONCRETE_POWDER: - case RED_SAND: - case SAND: - case WHITE_CONCRETE_POWDER: - case YELLOW_CONCRETE_POWDER: - // ----- Legacy Separator ----- - case LEGACY_SAND: - case LEGACY_GRAVEL: - case LEGACY_ANVIL: - case LEGACY_CONCRETE_POWDER: - // - return true; - default: - return false; - } - } - - /** - * Checks if this Material is an obtainable item. - * - * @return true if this material is an item - */ - public boolean isItem() { - switch (this) { - // - case ACACIA_WALL_SIGN: - case ATTACHED_MELON_STEM: - case ATTACHED_PUMPKIN_STEM: - case BAMBOO_SAPLING: - case BEETROOTS: - case BIRCH_WALL_SIGN: - case BLACK_WALL_BANNER: - case BLUE_WALL_BANNER: - case BRAIN_CORAL_WALL_FAN: - case BROWN_WALL_BANNER: - case BUBBLE_COLUMN: - case BUBBLE_CORAL_WALL_FAN: - case CARROTS: - case CAVE_AIR: - case COCOA: - case CREEPER_WALL_HEAD: - case CYAN_WALL_BANNER: - case DARK_OAK_WALL_SIGN: - case DEAD_BRAIN_CORAL_WALL_FAN: - case DEAD_BUBBLE_CORAL_WALL_FAN: - case DEAD_FIRE_CORAL_WALL_FAN: - case DEAD_HORN_CORAL_WALL_FAN: - case DEAD_TUBE_CORAL_WALL_FAN: - case DRAGON_WALL_HEAD: - case END_GATEWAY: - case END_PORTAL: - case FIRE: - case FIRE_CORAL_WALL_FAN: - case FROSTED_ICE: - case GRAY_WALL_BANNER: - case GREEN_WALL_BANNER: - case HORN_CORAL_WALL_FAN: - case JUNGLE_WALL_SIGN: - case KELP_PLANT: - case LAVA: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_WALL_BANNER: - case MELON_STEM: - case MOVING_PISTON: - case NETHER_PORTAL: - case OAK_WALL_SIGN: - case ORANGE_WALL_BANNER: - case PINK_WALL_BANNER: - case PISTON_HEAD: - case PLAYER_WALL_HEAD: - case POTATOES: - case POTTED_ACACIA_SAPLING: - case POTTED_ALLIUM: - case POTTED_AZURE_BLUET: - case POTTED_BAMBOO: - case POTTED_BIRCH_SAPLING: - case POTTED_BLUE_ORCHID: - case POTTED_BROWN_MUSHROOM: - case POTTED_CACTUS: - case POTTED_CORNFLOWER: - case POTTED_DANDELION: - case POTTED_DARK_OAK_SAPLING: - case POTTED_DEAD_BUSH: - case POTTED_FERN: - case POTTED_JUNGLE_SAPLING: - case POTTED_LILY_OF_THE_VALLEY: - case POTTED_OAK_SAPLING: - case POTTED_ORANGE_TULIP: - case POTTED_OXEYE_DAISY: - case POTTED_PINK_TULIP: - case POTTED_POPPY: - case POTTED_RED_MUSHROOM: - case POTTED_RED_TULIP: - case POTTED_SPRUCE_SAPLING: - case POTTED_WHITE_TULIP: - case POTTED_WITHER_ROSE: - case PUMPKIN_STEM: - case PURPLE_WALL_BANNER: - case REDSTONE_WALL_TORCH: - case REDSTONE_WIRE: - case RED_WALL_BANNER: - case SKELETON_WALL_SKULL: - case SPRUCE_WALL_SIGN: - case SWEET_BERRY_BUSH: - case TALL_SEAGRASS: - case TRIPWIRE: - case TUBE_CORAL_WALL_FAN: - case VOID_AIR: - case WALL_TORCH: - case WATER: - case WHITE_WALL_BANNER: - case WITHER_SKELETON_WALL_SKULL: - case YELLOW_WALL_BANNER: - case ZOMBIE_WALL_HEAD: - // ----- Legacy Separator ----- - case LEGACY_ACACIA_DOOR: - case LEGACY_BED_BLOCK: - case LEGACY_BEETROOT_BLOCK: - case LEGACY_BIRCH_DOOR: - case LEGACY_BREWING_STAND: - case LEGACY_BURNING_FURNACE: - case LEGACY_CAKE_BLOCK: - case LEGACY_CARROT: - case LEGACY_CAULDRON: - case LEGACY_COCOA: - case LEGACY_CROPS: - case LEGACY_DARK_OAK_DOOR: - case LEGACY_DAYLIGHT_DETECTOR_INVERTED: - case LEGACY_DIODE_BLOCK_OFF: - case LEGACY_DIODE_BLOCK_ON: - case LEGACY_DOUBLE_STEP: - case LEGACY_DOUBLE_STONE_SLAB2: - case LEGACY_ENDER_PORTAL: - case LEGACY_END_GATEWAY: - case LEGACY_FIRE: - case LEGACY_FLOWER_POT: - case LEGACY_FROSTED_ICE: - case LEGACY_GLOWING_REDSTONE_ORE: - case LEGACY_IRON_DOOR_BLOCK: - case LEGACY_JUNGLE_DOOR: - case LEGACY_LAVA: - case LEGACY_MELON_STEM: - case LEGACY_NETHER_WARTS: - case LEGACY_PISTON_EXTENSION: - case LEGACY_PISTON_MOVING_PIECE: - case LEGACY_PORTAL: - case LEGACY_POTATO: - case LEGACY_PUMPKIN_STEM: - case LEGACY_PURPUR_DOUBLE_SLAB: - case LEGACY_REDSTONE_COMPARATOR_OFF: - case LEGACY_REDSTONE_COMPARATOR_ON: - case LEGACY_REDSTONE_LAMP_ON: - case LEGACY_REDSTONE_TORCH_OFF: - case LEGACY_REDSTONE_WIRE: - case LEGACY_SIGN_POST: - case LEGACY_SKULL: - case LEGACY_SPRUCE_DOOR: - case LEGACY_STANDING_BANNER: - case LEGACY_STATIONARY_LAVA: - case LEGACY_STATIONARY_WATER: - case LEGACY_SUGAR_CANE_BLOCK: - case LEGACY_TRIPWIRE: - case LEGACY_WALL_BANNER: - case LEGACY_WALL_SIGN: - case LEGACY_WATER: - case LEGACY_WOODEN_DOOR: - case LEGACY_WOOD_DOUBLE_STEP: - // - return false; - default: - return true; - } - } - - /** - * Checks if this Material can be interacted with. - * - * Interactable materials include those with functionality when they are - * interacted with by a player such as chests, furnaces, etc. - * - * Some blocks such as piston heads and stairs are considered interactable - * though may not perform any additional functionality. - * - * Note that the interactability of some materials may be dependant on their - * state as well. This method will return true if there is at least one - * state in which additional interact handling is performed for the - * material. - * - * @return true if this material can be interacted with. - */ - public boolean isInteractable() { - switch (this) { - // - case ACACIA_BUTTON: - case ACACIA_DOOR: - case ACACIA_FENCE: - case ACACIA_FENCE_GATE: - case ACACIA_SIGN: - case ACACIA_STAIRS: - case ACACIA_TRAPDOOR: - case ACACIA_WALL_SIGN: - case ANDESITE_STAIRS: - case ANVIL: - case BARREL: - case BEACON: - case BELL: - case BIRCH_BUTTON: - case BIRCH_DOOR: - case BIRCH_FENCE: - case BIRCH_FENCE_GATE: - case BIRCH_SIGN: - case BIRCH_STAIRS: - case BIRCH_TRAPDOOR: - case BIRCH_WALL_SIGN: - case BLACK_BED: - case BLACK_SHULKER_BOX: - case BLAST_FURNACE: - case BLUE_BED: - case BLUE_SHULKER_BOX: - case BREWING_STAND: - case BRICK_STAIRS: - case BROWN_BED: - case BROWN_SHULKER_BOX: - case CAKE: - case CAMPFIRE: - case CARTOGRAPHY_TABLE: - case CAULDRON: - case CHAIN_COMMAND_BLOCK: - case CHEST: - case CHIPPED_ANVIL: - case COBBLESTONE_STAIRS: - case COMMAND_BLOCK: - case COMPARATOR: - case COMPOSTER: - case CRAFTING_TABLE: - case CYAN_BED: - case CYAN_SHULKER_BOX: - case DAMAGED_ANVIL: - case DARK_OAK_BUTTON: - case DARK_OAK_DOOR: - case DARK_OAK_FENCE: - case DARK_OAK_FENCE_GATE: - case DARK_OAK_SIGN: - case DARK_OAK_STAIRS: - case DARK_OAK_TRAPDOOR: - case DARK_OAK_WALL_SIGN: - case DARK_PRISMARINE_STAIRS: - case DAYLIGHT_DETECTOR: - case DIORITE_STAIRS: - case DISPENSER: - case DRAGON_EGG: - case DROPPER: - case ENCHANTING_TABLE: - case ENDER_CHEST: - case END_STONE_BRICK_STAIRS: - case FLETCHING_TABLE: - case FLOWER_POT: - case FURNACE: - case GRANITE_STAIRS: - case GRAY_BED: - case GRAY_SHULKER_BOX: - case GREEN_BED: - case GREEN_SHULKER_BOX: - case GRINDSTONE: - case HOPPER: - case IRON_DOOR: - case IRON_TRAPDOOR: - case JIGSAW: - case JUKEBOX: - case JUNGLE_BUTTON: - case JUNGLE_DOOR: - case JUNGLE_FENCE: - case JUNGLE_FENCE_GATE: - case JUNGLE_SIGN: - case JUNGLE_STAIRS: - case JUNGLE_TRAPDOOR: - case JUNGLE_WALL_SIGN: - case LECTERN: - case LEVER: - case LIGHT_BLUE_BED: - case LIGHT_BLUE_SHULKER_BOX: - case LIGHT_GRAY_BED: - case LIGHT_GRAY_SHULKER_BOX: - case LIME_BED: - case LIME_SHULKER_BOX: - case LOOM: - case MAGENTA_BED: - case MAGENTA_SHULKER_BOX: - case MOSSY_COBBLESTONE_STAIRS: - case MOSSY_STONE_BRICK_STAIRS: - case MOVING_PISTON: - case NETHER_BRICK_FENCE: - case NETHER_BRICK_STAIRS: - case NOTE_BLOCK: - case OAK_BUTTON: - case OAK_DOOR: - case OAK_FENCE: - case OAK_FENCE_GATE: - case OAK_SIGN: - case OAK_STAIRS: - case OAK_TRAPDOOR: - case OAK_WALL_SIGN: - case ORANGE_BED: - case ORANGE_SHULKER_BOX: - case PINK_BED: - case PINK_SHULKER_BOX: - case POLISHED_ANDESITE_STAIRS: - case POLISHED_DIORITE_STAIRS: - case POLISHED_GRANITE_STAIRS: - case POTTED_ACACIA_SAPLING: - case POTTED_ALLIUM: - case POTTED_AZURE_BLUET: - case POTTED_BAMBOO: - case POTTED_BIRCH_SAPLING: - case POTTED_BLUE_ORCHID: - case POTTED_BROWN_MUSHROOM: - case POTTED_CACTUS: - case POTTED_CORNFLOWER: - case POTTED_DANDELION: - case POTTED_DARK_OAK_SAPLING: - case POTTED_DEAD_BUSH: - case POTTED_FERN: - case POTTED_JUNGLE_SAPLING: - case POTTED_LILY_OF_THE_VALLEY: - case POTTED_OAK_SAPLING: - case POTTED_ORANGE_TULIP: - case POTTED_OXEYE_DAISY: - case POTTED_PINK_TULIP: - case POTTED_POPPY: - case POTTED_RED_MUSHROOM: - case POTTED_RED_TULIP: - case POTTED_SPRUCE_SAPLING: - case POTTED_WHITE_TULIP: - case POTTED_WITHER_ROSE: - case PRISMARINE_BRICK_STAIRS: - case PRISMARINE_STAIRS: - case PUMPKIN: - case PURPLE_BED: - case PURPLE_SHULKER_BOX: - case PURPUR_STAIRS: - case QUARTZ_STAIRS: - case REDSTONE_ORE: - case RED_BED: - case RED_NETHER_BRICK_STAIRS: - case RED_SANDSTONE_STAIRS: - case RED_SHULKER_BOX: - case REPEATER: - case REPEATING_COMMAND_BLOCK: - case SANDSTONE_STAIRS: - case SHULKER_BOX: - case SMITHING_TABLE: - case SMOKER: - case SMOOTH_QUARTZ_STAIRS: - case SMOOTH_RED_SANDSTONE_STAIRS: - case SMOOTH_SANDSTONE_STAIRS: - case SPRUCE_BUTTON: - case SPRUCE_DOOR: - case SPRUCE_FENCE: - case SPRUCE_FENCE_GATE: - case SPRUCE_SIGN: - case SPRUCE_STAIRS: - case SPRUCE_TRAPDOOR: - case SPRUCE_WALL_SIGN: - case STONECUTTER: - case STONE_BRICK_STAIRS: - case STONE_BUTTON: - case STONE_STAIRS: - case STRUCTURE_BLOCK: - case SWEET_BERRY_BUSH: - case TNT: - case TRAPPED_CHEST: - case WHITE_BED: - case WHITE_SHULKER_BOX: - case YELLOW_BED: - case YELLOW_SHULKER_BOX: - // - return true; - default: - return false; - } - } - - /** - * Obtains the block's hardness level (also known as "strength"). - *
- * This number is used to calculate the time required to break each block. - *
- * Only available when {@link #isBlock()} is true. - * - * @return the hardness of that material. - */ - public float getHardness() { - Validate.isTrue(isBlock(), "The Material is not a block!"); - switch (this) { - // - case BARRIER: - case BEDROCK: - case CHAIN_COMMAND_BLOCK: - case COMMAND_BLOCK: - case END_GATEWAY: - case END_PORTAL: - case END_PORTAL_FRAME: - case JIGSAW: - case MOVING_PISTON: - case NETHER_PORTAL: - case REPEATING_COMMAND_BLOCK: - case STRUCTURE_BLOCK: - return -1.0F; - case BLACK_CARPET: - case BLUE_CARPET: - case BROWN_CARPET: - case CYAN_CARPET: - case GRAY_CARPET: - case GREEN_CARPET: - case LIGHT_BLUE_CARPET: - case LIGHT_GRAY_CARPET: - case LIME_CARPET: - case MAGENTA_CARPET: - case ORANGE_CARPET: - case PINK_CARPET: - case PURPLE_CARPET: - case RED_CARPET: - case SNOW: - case WHITE_CARPET: - case YELLOW_CARPET: - return 0.1F; - case ACACIA_LEAVES: - case BIRCH_LEAVES: - case BLACK_BED: - case BLUE_BED: - case BROWN_BED: - case BROWN_MUSHROOM_BLOCK: - case COCOA: - case CYAN_BED: - case DARK_OAK_LEAVES: - case DAYLIGHT_DETECTOR: - case GRAY_BED: - case GREEN_BED: - case JUNGLE_LEAVES: - case LIGHT_BLUE_BED: - case LIGHT_GRAY_BED: - case LIME_BED: - case MAGENTA_BED: - case MUSHROOM_STEM: - case OAK_LEAVES: - case ORANGE_BED: - case PINK_BED: - case PURPLE_BED: - case RED_BED: - case RED_MUSHROOM_BLOCK: - case SNOW_BLOCK: - case SPRUCE_LEAVES: - case VINE: - case WHITE_BED: - case YELLOW_BED: - return 0.2F; - case BLACK_STAINED_GLASS: - case BLACK_STAINED_GLASS_PANE: - case BLUE_STAINED_GLASS: - case BLUE_STAINED_GLASS_PANE: - case BROWN_STAINED_GLASS: - case BROWN_STAINED_GLASS_PANE: - case CYAN_STAINED_GLASS: - case CYAN_STAINED_GLASS_PANE: - case GLASS: - case GLASS_PANE: - case GLOWSTONE: - case GRAY_STAINED_GLASS: - case GRAY_STAINED_GLASS_PANE: - case GREEN_STAINED_GLASS: - case GREEN_STAINED_GLASS_PANE: - case LIGHT_BLUE_STAINED_GLASS: - case LIGHT_BLUE_STAINED_GLASS_PANE: - case LIGHT_GRAY_STAINED_GLASS: - case LIGHT_GRAY_STAINED_GLASS_PANE: - case LIME_STAINED_GLASS: - case LIME_STAINED_GLASS_PANE: - case MAGENTA_STAINED_GLASS: - case MAGENTA_STAINED_GLASS_PANE: - case ORANGE_STAINED_GLASS: - case ORANGE_STAINED_GLASS_PANE: - case PINK_STAINED_GLASS: - case PINK_STAINED_GLASS_PANE: - case PURPLE_STAINED_GLASS: - case PURPLE_STAINED_GLASS_PANE: - case REDSTONE_LAMP: - case RED_STAINED_GLASS: - case RED_STAINED_GLASS_PANE: - case SEA_LANTERN: - case WHITE_STAINED_GLASS: - case WHITE_STAINED_GLASS_PANE: - case YELLOW_STAINED_GLASS: - case YELLOW_STAINED_GLASS_PANE: - return 0.3F; - case CACTUS: - case CHORUS_FLOWER: - case CHORUS_PLANT: - case LADDER: - case NETHERRACK: - return 0.4F; - case ACACIA_BUTTON: - case ACACIA_PRESSURE_PLATE: - case BIRCH_BUTTON: - case BIRCH_PRESSURE_PLATE: - case BLACK_CONCRETE_POWDER: - case BLUE_CONCRETE_POWDER: - case BREWING_STAND: - case BROWN_CONCRETE_POWDER: - case CAKE: - case COARSE_DIRT: - case CYAN_CONCRETE_POWDER: - case DARK_OAK_BUTTON: - case DARK_OAK_PRESSURE_PLATE: - case DIRT: - case DRIED_KELP_BLOCK: - case FROSTED_ICE: - case GRAY_CONCRETE_POWDER: - case GREEN_CONCRETE_POWDER: - case HAY_BLOCK: - case HEAVY_WEIGHTED_PRESSURE_PLATE: - case ICE: - case JUNGLE_BUTTON: - case JUNGLE_PRESSURE_PLATE: - case LEVER: - case LIGHT_BLUE_CONCRETE_POWDER: - case LIGHT_GRAY_CONCRETE_POWDER: - case LIGHT_WEIGHTED_PRESSURE_PLATE: - case LIME_CONCRETE_POWDER: - case MAGENTA_CONCRETE_POWDER: - case MAGMA_BLOCK: - case OAK_BUTTON: - case OAK_PRESSURE_PLATE: - case ORANGE_CONCRETE_POWDER: - case PACKED_ICE: - case PINK_CONCRETE_POWDER: - case PISTON: - case PISTON_HEAD: - case PODZOL: - case PURPLE_CONCRETE_POWDER: - case RED_CONCRETE_POWDER: - case RED_SAND: - case SAND: - case SOUL_SAND: - case SPRUCE_BUTTON: - case SPRUCE_PRESSURE_PLATE: - case STICKY_PISTON: - case STONE_BUTTON: - case STONE_PRESSURE_PLATE: - case TURTLE_EGG: - case WHITE_CONCRETE_POWDER: - case YELLOW_CONCRETE_POWDER: - return 0.5F; - case CLAY: - case COMPOSTER: - case FARMLAND: - case GRASS_BLOCK: - case GRAVEL: - case MYCELIUM: - case SPONGE: - case WET_SPONGE: - return 0.6F; - case GRASS_PATH: - return 0.65F; - case ACTIVATOR_RAIL: - case DETECTOR_RAIL: - case POWERED_RAIL: - case RAIL: - return 0.7F; - case BLACK_WOOL: - case BLUE_WOOL: - case BROWN_WOOL: - case CHISELED_QUARTZ_BLOCK: - case CHISELED_RED_SANDSTONE: - case CHISELED_SANDSTONE: - case CUT_RED_SANDSTONE: - case CUT_SANDSTONE: - case CYAN_WOOL: - case END_STONE_BRICKS: - case END_STONE_BRICK_SLAB: - case END_STONE_BRICK_STAIRS: - case END_STONE_BRICK_WALL: - case GRAY_WOOL: - case GREEN_WOOL: - case LIGHT_BLUE_WOOL: - case LIGHT_GRAY_WOOL: - case LIME_WOOL: - case MAGENTA_WOOL: - case NOTE_BLOCK: - case ORANGE_WOOL: - case PINK_WOOL: - case PURPLE_WOOL: - case QUARTZ_BLOCK: - case QUARTZ_PILLAR: - case QUARTZ_STAIRS: - case RED_SANDSTONE: - case RED_SANDSTONE_STAIRS: - case RED_SANDSTONE_WALL: - case RED_WOOL: - case SANDSTONE: - case SANDSTONE_STAIRS: - case SANDSTONE_WALL: - case WHITE_WOOL: - case YELLOW_WOOL: - return 0.8F; - case ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BAMBOO: - case BAMBOO_SAPLING: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CARVED_PUMPKIN: - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case JACK_O_LANTERN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case MELON: - case NETHER_WART_BLOCK: - case OAK_SIGN: - case OAK_WALL_SIGN: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case PUMPKIN: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case SPRUCE_SIGN: - case SPRUCE_WALL_SIGN: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return 1.0F; - case BLACK_TERRACOTTA: - case BLUE_TERRACOTTA: - case BROWN_TERRACOTTA: - case CYAN_TERRACOTTA: - case GRAY_TERRACOTTA: - case GREEN_TERRACOTTA: - case LIGHT_BLUE_TERRACOTTA: - case LIGHT_GRAY_TERRACOTTA: - case LIME_TERRACOTTA: - case MAGENTA_TERRACOTTA: - case ORANGE_TERRACOTTA: - case PINK_TERRACOTTA: - case PURPLE_TERRACOTTA: - case RED_TERRACOTTA: - case TERRACOTTA: - case WHITE_TERRACOTTA: - case YELLOW_TERRACOTTA: - return 1.25F; - case BLACK_GLAZED_TERRACOTTA: - case BLUE_GLAZED_TERRACOTTA: - case BROWN_GLAZED_TERRACOTTA: - case CYAN_GLAZED_TERRACOTTA: - case GRAY_GLAZED_TERRACOTTA: - case GREEN_GLAZED_TERRACOTTA: - case LIGHT_BLUE_GLAZED_TERRACOTTA: - case LIGHT_GRAY_GLAZED_TERRACOTTA: - case LIME_GLAZED_TERRACOTTA: - case MAGENTA_GLAZED_TERRACOTTA: - case ORANGE_GLAZED_TERRACOTTA: - case PINK_GLAZED_TERRACOTTA: - case PURPLE_GLAZED_TERRACOTTA: - case RED_GLAZED_TERRACOTTA: - case WHITE_GLAZED_TERRACOTTA: - case YELLOW_GLAZED_TERRACOTTA: - return 1.4F; - case ANDESITE: - case ANDESITE_SLAB: - case ANDESITE_STAIRS: - case ANDESITE_WALL: - case BOOKSHELF: - case BRAIN_CORAL_BLOCK: - case BUBBLE_CORAL_BLOCK: - case CHISELED_STONE_BRICKS: - case CRACKED_STONE_BRICKS: - case DARK_PRISMARINE: - case DARK_PRISMARINE_SLAB: - case DARK_PRISMARINE_STAIRS: - case DEAD_BRAIN_CORAL_BLOCK: - case DEAD_BUBBLE_CORAL_BLOCK: - case DEAD_FIRE_CORAL_BLOCK: - case DEAD_HORN_CORAL_BLOCK: - case DEAD_TUBE_CORAL_BLOCK: - case DIORITE: - case DIORITE_SLAB: - case DIORITE_STAIRS: - case DIORITE_WALL: - case FIRE_CORAL_BLOCK: - case GRANITE: - case GRANITE_SLAB: - case GRANITE_STAIRS: - case GRANITE_WALL: - case HORN_CORAL_BLOCK: - case MOSSY_STONE_BRICKS: - case MOSSY_STONE_BRICK_SLAB: - case MOSSY_STONE_BRICK_STAIRS: - case MOSSY_STONE_BRICK_WALL: - case POLISHED_ANDESITE: - case POLISHED_ANDESITE_SLAB: - case POLISHED_ANDESITE_STAIRS: - case POLISHED_DIORITE: - case POLISHED_DIORITE_SLAB: - case POLISHED_DIORITE_STAIRS: - case POLISHED_GRANITE: - case POLISHED_GRANITE_SLAB: - case POLISHED_GRANITE_STAIRS: - case PRISMARINE: - case PRISMARINE_BRICKS: - case PRISMARINE_BRICK_SLAB: - case PRISMARINE_BRICK_STAIRS: - case PRISMARINE_SLAB: - case PRISMARINE_STAIRS: - case PRISMARINE_WALL: - case PURPUR_BLOCK: - case PURPUR_PILLAR: - case PURPUR_STAIRS: - case STONE: - case STONE_BRICKS: - case STONE_BRICK_STAIRS: - case STONE_BRICK_WALL: - case STONE_STAIRS: - case TUBE_CORAL_BLOCK: - return 1.5F; - case BLACK_CONCRETE: - case BLUE_CONCRETE: - case BROWN_CONCRETE: - case CYAN_CONCRETE: - case GRAY_CONCRETE: - case GREEN_CONCRETE: - case LIGHT_BLUE_CONCRETE: - case LIGHT_GRAY_CONCRETE: - case LIME_CONCRETE: - case MAGENTA_CONCRETE: - case ORANGE_CONCRETE: - case PINK_CONCRETE: - case PURPLE_CONCRETE: - case RED_CONCRETE: - case WHITE_CONCRETE: - case YELLOW_CONCRETE: - return 1.8F; - case ACACIA_FENCE: - case ACACIA_FENCE_GATE: - case ACACIA_LOG: - case ACACIA_PLANKS: - case ACACIA_SLAB: - case ACACIA_STAIRS: - case ACACIA_WOOD: - case BIRCH_FENCE: - case BIRCH_FENCE_GATE: - case BIRCH_LOG: - case BIRCH_PLANKS: - case BIRCH_SLAB: - case BIRCH_STAIRS: - case BIRCH_WOOD: - case BLACK_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BONE_BLOCK: - case BRICKS: - case BRICK_SLAB: - case BRICK_STAIRS: - case BRICK_WALL: - case BROWN_SHULKER_BOX: - case CAMPFIRE: - case CAULDRON: - case COBBLESTONE: - case COBBLESTONE_SLAB: - case COBBLESTONE_STAIRS: - case COBBLESTONE_WALL: - case CUT_RED_SANDSTONE_SLAB: - case CUT_SANDSTONE_SLAB: - case CYAN_SHULKER_BOX: - case DARK_OAK_FENCE: - case DARK_OAK_FENCE_GATE: - case DARK_OAK_LOG: - case DARK_OAK_PLANKS: - case DARK_OAK_SLAB: - case DARK_OAK_STAIRS: - case DARK_OAK_WOOD: - case GRAY_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case GRINDSTONE: - case JUKEBOX: - case JUNGLE_FENCE: - case JUNGLE_FENCE_GATE: - case JUNGLE_LOG: - case JUNGLE_PLANKS: - case JUNGLE_SLAB: - case JUNGLE_STAIRS: - case JUNGLE_WOOD: - case LIGHT_BLUE_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case LIME_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case MOSSY_COBBLESTONE: - case MOSSY_COBBLESTONE_SLAB: - case MOSSY_COBBLESTONE_STAIRS: - case MOSSY_COBBLESTONE_WALL: - case NETHER_BRICKS: - case NETHER_BRICK_FENCE: - case NETHER_BRICK_SLAB: - case NETHER_BRICK_STAIRS: - case NETHER_BRICK_WALL: - case OAK_FENCE: - case OAK_FENCE_GATE: - case OAK_LOG: - case OAK_PLANKS: - case OAK_SLAB: - case OAK_STAIRS: - case OAK_WOOD: - case ORANGE_SHULKER_BOX: - case PETRIFIED_OAK_SLAB: - case PINK_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case PURPUR_SLAB: - case QUARTZ_SLAB: - case RED_NETHER_BRICKS: - case RED_NETHER_BRICK_SLAB: - case RED_NETHER_BRICK_STAIRS: - case RED_NETHER_BRICK_WALL: - case RED_SANDSTONE_SLAB: - case RED_SHULKER_BOX: - case SANDSTONE_SLAB: - case SHULKER_BOX: - case SMOOTH_QUARTZ: - case SMOOTH_QUARTZ_SLAB: - case SMOOTH_QUARTZ_STAIRS: - case SMOOTH_RED_SANDSTONE: - case SMOOTH_RED_SANDSTONE_SLAB: - case SMOOTH_RED_SANDSTONE_STAIRS: - case SMOOTH_SANDSTONE: - case SMOOTH_SANDSTONE_SLAB: - case SMOOTH_SANDSTONE_STAIRS: - case SMOOTH_STONE: - case SMOOTH_STONE_SLAB: - case SPRUCE_FENCE: - case SPRUCE_FENCE_GATE: - case SPRUCE_LOG: - case SPRUCE_PLANKS: - case SPRUCE_SLAB: - case SPRUCE_STAIRS: - case SPRUCE_WOOD: - case STONE_BRICK_SLAB: - case STONE_SLAB: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - case WHITE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - return 2.0F; - case BARREL: - case CARTOGRAPHY_TABLE: - case CHEST: - case CRAFTING_TABLE: - case FLETCHING_TABLE: - case LECTERN: - case LOOM: - case SMITHING_TABLE: - case TRAPPED_CHEST: - return 2.5F; - case BLUE_ICE: - return 2.8F; - case ACACIA_DOOR: - case ACACIA_TRAPDOOR: - case BEACON: - case BIRCH_DOOR: - case BIRCH_TRAPDOOR: - case COAL_ORE: - case CONDUIT: - case DARK_OAK_DOOR: - case DARK_OAK_TRAPDOOR: - case DIAMOND_ORE: - case DRAGON_EGG: - case EMERALD_ORE: - case END_STONE: - case GOLD_BLOCK: - case GOLD_ORE: - case HOPPER: - case IRON_ORE: - case JUNGLE_DOOR: - case JUNGLE_TRAPDOOR: - case LAPIS_BLOCK: - case LAPIS_ORE: - case NETHER_QUARTZ_ORE: - case OAK_DOOR: - case OAK_TRAPDOOR: - case OBSERVER: - case REDSTONE_ORE: - case SPRUCE_DOOR: - case SPRUCE_TRAPDOOR: - return 3.0F; - case BLAST_FURNACE: - case DISPENSER: - case DROPPER: - case FURNACE: - case LANTERN: - case SMOKER: - case STONECUTTER: - return 3.5F; - case COBWEB: - return 4.0F; - case ANVIL: - case BELL: - case CHIPPED_ANVIL: - case COAL_BLOCK: - case DAMAGED_ANVIL: - case DIAMOND_BLOCK: - case EMERALD_BLOCK: - case ENCHANTING_TABLE: - case IRON_BARS: - case IRON_BLOCK: - case IRON_DOOR: - case IRON_TRAPDOOR: - case REDSTONE_BLOCK: - case SPAWNER: - return 5.0F; - case ENDER_CHEST: - return 22.5F; - case OBSIDIAN: - return 50.0F; - case LAVA: - case WATER: - return 100.0F; - default: - return 0F; - // - } - } - - /** - * Obtains the blast resistance value (also known as block "durability"). - *
- * This value is used in explosions to calculate whether a block should be - * broken or not. - *
- * Only available when {@link #isBlock()} is true. - * - * @return the blast resistance of that material. - */ - public float getBlastResistance() { - Validate.isTrue(isBlock(), "The Material is not a block!"); - switch (this) { - // - case BLACK_CARPET: - case BLUE_CARPET: - case BROWN_CARPET: - case CYAN_CARPET: - case GRAY_CARPET: - case GREEN_CARPET: - case LIGHT_BLUE_CARPET: - case LIGHT_GRAY_CARPET: - case LIME_CARPET: - case MAGENTA_CARPET: - case ORANGE_CARPET: - case PINK_CARPET: - case PURPLE_CARPET: - case RED_CARPET: - case SNOW: - case WHITE_CARPET: - case YELLOW_CARPET: - return 0.1F; - case ACACIA_LEAVES: - case BIRCH_LEAVES: - case BLACK_BED: - case BLUE_BED: - case BROWN_BED: - case BROWN_MUSHROOM_BLOCK: - case CYAN_BED: - case DARK_OAK_LEAVES: - case DAYLIGHT_DETECTOR: - case GRAY_BED: - case GREEN_BED: - case JUNGLE_LEAVES: - case LIGHT_BLUE_BED: - case LIGHT_GRAY_BED: - case LIME_BED: - case MAGENTA_BED: - case MUSHROOM_STEM: - case OAK_LEAVES: - case ORANGE_BED: - case PINK_BED: - case PURPLE_BED: - case RED_BED: - case RED_MUSHROOM_BLOCK: - case SNOW_BLOCK: - case SPRUCE_LEAVES: - case VINE: - case WHITE_BED: - case YELLOW_BED: - return 0.2F; - case BLACK_STAINED_GLASS: - case BLACK_STAINED_GLASS_PANE: - case BLUE_STAINED_GLASS: - case BLUE_STAINED_GLASS_PANE: - case BROWN_STAINED_GLASS: - case BROWN_STAINED_GLASS_PANE: - case CYAN_STAINED_GLASS: - case CYAN_STAINED_GLASS_PANE: - case GLASS: - case GLASS_PANE: - case GLOWSTONE: - case GRAY_STAINED_GLASS: - case GRAY_STAINED_GLASS_PANE: - case GREEN_STAINED_GLASS: - case GREEN_STAINED_GLASS_PANE: - case LIGHT_BLUE_STAINED_GLASS: - case LIGHT_BLUE_STAINED_GLASS_PANE: - case LIGHT_GRAY_STAINED_GLASS: - case LIGHT_GRAY_STAINED_GLASS_PANE: - case LIME_STAINED_GLASS: - case LIME_STAINED_GLASS_PANE: - case MAGENTA_STAINED_GLASS: - case MAGENTA_STAINED_GLASS_PANE: - case ORANGE_STAINED_GLASS: - case ORANGE_STAINED_GLASS_PANE: - case PINK_STAINED_GLASS: - case PINK_STAINED_GLASS_PANE: - case PURPLE_STAINED_GLASS: - case PURPLE_STAINED_GLASS_PANE: - case REDSTONE_LAMP: - case RED_STAINED_GLASS: - case RED_STAINED_GLASS_PANE: - case SEA_LANTERN: - case WHITE_STAINED_GLASS: - case WHITE_STAINED_GLASS_PANE: - case YELLOW_STAINED_GLASS: - case YELLOW_STAINED_GLASS_PANE: - return 0.3F; - case CACTUS: - case CHORUS_FLOWER: - case CHORUS_PLANT: - case LADDER: - case NETHERRACK: - return 0.4F; - case ACACIA_BUTTON: - case ACACIA_PRESSURE_PLATE: - case BIRCH_BUTTON: - case BIRCH_PRESSURE_PLATE: - case BLACK_CONCRETE_POWDER: - case BLUE_CONCRETE_POWDER: - case BREWING_STAND: - case BROWN_CONCRETE_POWDER: - case CAKE: - case COARSE_DIRT: - case CYAN_CONCRETE_POWDER: - case DARK_OAK_BUTTON: - case DARK_OAK_PRESSURE_PLATE: - case DIRT: - case FROSTED_ICE: - case GRAY_CONCRETE_POWDER: - case GREEN_CONCRETE_POWDER: - case HAY_BLOCK: - case HEAVY_WEIGHTED_PRESSURE_PLATE: - case ICE: - case JUNGLE_BUTTON: - case JUNGLE_PRESSURE_PLATE: - case LEVER: - case LIGHT_BLUE_CONCRETE_POWDER: - case LIGHT_GRAY_CONCRETE_POWDER: - case LIGHT_WEIGHTED_PRESSURE_PLATE: - case LIME_CONCRETE_POWDER: - case MAGENTA_CONCRETE_POWDER: - case MAGMA_BLOCK: - case OAK_BUTTON: - case OAK_PRESSURE_PLATE: - case ORANGE_CONCRETE_POWDER: - case PACKED_ICE: - case PINK_CONCRETE_POWDER: - case PISTON: - case PISTON_HEAD: - case PODZOL: - case PURPLE_CONCRETE_POWDER: - case RED_CONCRETE_POWDER: - case RED_SAND: - case SAND: - case SOUL_SAND: - case SPRUCE_BUTTON: - case SPRUCE_PRESSURE_PLATE: - case STICKY_PISTON: - case STONE_BUTTON: - case STONE_PRESSURE_PLATE: - case TURTLE_EGG: - case WHITE_CONCRETE_POWDER: - case YELLOW_CONCRETE_POWDER: - return 0.5F; - case CLAY: - case COMPOSTER: - case FARMLAND: - case GRASS_BLOCK: - case GRAVEL: - case MYCELIUM: - case SPONGE: - case WET_SPONGE: - return 0.6F; - case GRASS_PATH: - return 0.65F; - case ACTIVATOR_RAIL: - case DETECTOR_RAIL: - case POWERED_RAIL: - case RAIL: - return 0.7F; - case INFESTED_CHISELED_STONE_BRICKS: - case INFESTED_COBBLESTONE: - case INFESTED_CRACKED_STONE_BRICKS: - case INFESTED_MOSSY_STONE_BRICKS: - case INFESTED_STONE: - case INFESTED_STONE_BRICKS: - return 0.75F; - case BLACK_WOOL: - case BLUE_WOOL: - case BROWN_WOOL: - case CHISELED_QUARTZ_BLOCK: - case CHISELED_RED_SANDSTONE: - case CHISELED_SANDSTONE: - case CUT_RED_SANDSTONE: - case CUT_SANDSTONE: - case CYAN_WOOL: - case END_STONE_BRICKS: - case END_STONE_BRICK_SLAB: - case END_STONE_BRICK_STAIRS: - case END_STONE_BRICK_WALL: - case GRAY_WOOL: - case GREEN_WOOL: - case LIGHT_BLUE_WOOL: - case LIGHT_GRAY_WOOL: - case LIME_WOOL: - case MAGENTA_WOOL: - case NOTE_BLOCK: - case ORANGE_WOOL: - case PINK_WOOL: - case PURPLE_WOOL: - case QUARTZ_BLOCK: - case QUARTZ_PILLAR: - case QUARTZ_STAIRS: - case RED_SANDSTONE: - case RED_SANDSTONE_STAIRS: - case RED_SANDSTONE_WALL: - case RED_WOOL: - case SANDSTONE: - case SANDSTONE_STAIRS: - case SANDSTONE_WALL: - case WHITE_WOOL: - case YELLOW_WOOL: - return 0.8F; - case ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BAMBOO: - case BAMBOO_SAPLING: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CARVED_PUMPKIN: - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case JACK_O_LANTERN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case MELON: - case NETHER_WART_BLOCK: - case OAK_SIGN: - case OAK_WALL_SIGN: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case PUMPKIN: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case SPRUCE_SIGN: - case SPRUCE_WALL_SIGN: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return 1.0F; - case BLACK_GLAZED_TERRACOTTA: - case BLUE_GLAZED_TERRACOTTA: - case BROWN_GLAZED_TERRACOTTA: - case CYAN_GLAZED_TERRACOTTA: - case GRAY_GLAZED_TERRACOTTA: - case GREEN_GLAZED_TERRACOTTA: - case LIGHT_BLUE_GLAZED_TERRACOTTA: - case LIGHT_GRAY_GLAZED_TERRACOTTA: - case LIME_GLAZED_TERRACOTTA: - case MAGENTA_GLAZED_TERRACOTTA: - case ORANGE_GLAZED_TERRACOTTA: - case PINK_GLAZED_TERRACOTTA: - case PURPLE_GLAZED_TERRACOTTA: - case RED_GLAZED_TERRACOTTA: - case WHITE_GLAZED_TERRACOTTA: - case YELLOW_GLAZED_TERRACOTTA: - return 1.4F; - case BOOKSHELF: - return 1.5F; - case BLACK_CONCRETE: - case BLUE_CONCRETE: - case BROWN_CONCRETE: - case CYAN_CONCRETE: - case GRAY_CONCRETE: - case GREEN_CONCRETE: - case LIGHT_BLUE_CONCRETE: - case LIGHT_GRAY_CONCRETE: - case LIME_CONCRETE: - case MAGENTA_CONCRETE: - case ORANGE_CONCRETE: - case PINK_CONCRETE: - case PURPLE_CONCRETE: - case RED_CONCRETE: - case WHITE_CONCRETE: - case YELLOW_CONCRETE: - return 1.8F; - case ACACIA_LOG: - case ACACIA_WOOD: - case BIRCH_LOG: - case BIRCH_WOOD: - case BLACK_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BONE_BLOCK: - case BROWN_SHULKER_BOX: - case CAMPFIRE: - case CAULDRON: - case CYAN_SHULKER_BOX: - case DARK_OAK_LOG: - case DARK_OAK_WOOD: - case GRAY_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case JUNGLE_LOG: - case JUNGLE_WOOD: - case LIGHT_BLUE_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case LIME_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case OAK_LOG: - case OAK_WOOD: - case ORANGE_SHULKER_BOX: - case PINK_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case RED_SHULKER_BOX: - case SHULKER_BOX: - case SPRUCE_LOG: - case SPRUCE_WOOD: - case STRIPPED_ACACIA_LOG: - case STRIPPED_ACACIA_WOOD: - case STRIPPED_BIRCH_LOG: - case STRIPPED_BIRCH_WOOD: - case STRIPPED_DARK_OAK_LOG: - case STRIPPED_DARK_OAK_WOOD: - case STRIPPED_JUNGLE_LOG: - case STRIPPED_JUNGLE_WOOD: - case STRIPPED_OAK_LOG: - case STRIPPED_OAK_WOOD: - case STRIPPED_SPRUCE_LOG: - case STRIPPED_SPRUCE_WOOD: - case WHITE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - return 2.0F; - case BARREL: - case CARTOGRAPHY_TABLE: - case CHEST: - case CRAFTING_TABLE: - case DRIED_KELP_BLOCK: - case FLETCHING_TABLE: - case LECTERN: - case LOOM: - case SMITHING_TABLE: - case TRAPPED_CHEST: - return 2.5F; - case BLUE_ICE: - return 2.8F; - case ACACIA_DOOR: - case ACACIA_FENCE: - case ACACIA_FENCE_GATE: - case ACACIA_PLANKS: - case ACACIA_SLAB: - case ACACIA_STAIRS: - case ACACIA_TRAPDOOR: - case BEACON: - case BIRCH_DOOR: - case BIRCH_FENCE: - case BIRCH_FENCE_GATE: - case BIRCH_PLANKS: - case BIRCH_SLAB: - case BIRCH_STAIRS: - case BIRCH_TRAPDOOR: - case COAL_ORE: - case COCOA: - case CONDUIT: - case DARK_OAK_DOOR: - case DARK_OAK_FENCE: - case DARK_OAK_FENCE_GATE: - case DARK_OAK_PLANKS: - case DARK_OAK_SLAB: - case DARK_OAK_STAIRS: - case DARK_OAK_TRAPDOOR: - case DIAMOND_ORE: - case EMERALD_ORE: - case GOLD_ORE: - case IRON_ORE: - case JUNGLE_DOOR: - case JUNGLE_FENCE: - case JUNGLE_FENCE_GATE: - case JUNGLE_PLANKS: - case JUNGLE_SLAB: - case JUNGLE_STAIRS: - case JUNGLE_TRAPDOOR: - case LAPIS_BLOCK: - case LAPIS_ORE: - case NETHER_QUARTZ_ORE: - case OAK_DOOR: - case OAK_FENCE: - case OAK_FENCE_GATE: - case OAK_PLANKS: - case OAK_SLAB: - case OAK_STAIRS: - case OAK_TRAPDOOR: - case OBSERVER: - case REDSTONE_ORE: - case SPRUCE_DOOR: - case SPRUCE_FENCE: - case SPRUCE_FENCE_GATE: - case SPRUCE_PLANKS: - case SPRUCE_SLAB: - case SPRUCE_STAIRS: - case SPRUCE_TRAPDOOR: - return 3.0F; - case BLAST_FURNACE: - case DISPENSER: - case DROPPER: - case FURNACE: - case LANTERN: - case SMOKER: - case STONECUTTER: - return 3.5F; - case COBWEB: - return 4.0F; - case BLACK_TERRACOTTA: - case BLUE_TERRACOTTA: - case BROWN_TERRACOTTA: - case CYAN_TERRACOTTA: - case GRAY_TERRACOTTA: - case GREEN_TERRACOTTA: - case LIGHT_BLUE_TERRACOTTA: - case LIGHT_GRAY_TERRACOTTA: - case LIME_TERRACOTTA: - case MAGENTA_TERRACOTTA: - case ORANGE_TERRACOTTA: - case PINK_TERRACOTTA: - case PURPLE_TERRACOTTA: - case RED_TERRACOTTA: - case TERRACOTTA: - case WHITE_TERRACOTTA: - case YELLOW_TERRACOTTA: - return 4.2F; - case HOPPER: - return 4.8F; - case BELL: - case IRON_DOOR: - case IRON_TRAPDOOR: - case SPAWNER: - return 5.0F; - case ANDESITE: - case ANDESITE_SLAB: - case ANDESITE_STAIRS: - case ANDESITE_WALL: - case BRAIN_CORAL_BLOCK: - case BRICKS: - case BRICK_SLAB: - case BRICK_STAIRS: - case BRICK_WALL: - case BUBBLE_CORAL_BLOCK: - case CHISELED_STONE_BRICKS: - case COAL_BLOCK: - case COBBLESTONE: - case COBBLESTONE_SLAB: - case COBBLESTONE_STAIRS: - case COBBLESTONE_WALL: - case CRACKED_STONE_BRICKS: - case CUT_RED_SANDSTONE_SLAB: - case CUT_SANDSTONE_SLAB: - case DARK_PRISMARINE: - case DARK_PRISMARINE_SLAB: - case DARK_PRISMARINE_STAIRS: - case DEAD_BRAIN_CORAL_BLOCK: - case DEAD_BUBBLE_CORAL_BLOCK: - case DEAD_FIRE_CORAL_BLOCK: - case DEAD_HORN_CORAL_BLOCK: - case DEAD_TUBE_CORAL_BLOCK: - case DIAMOND_BLOCK: - case DIORITE: - case DIORITE_SLAB: - case DIORITE_STAIRS: - case DIORITE_WALL: - case EMERALD_BLOCK: - case FIRE_CORAL_BLOCK: - case GOLD_BLOCK: - case GRANITE: - case GRANITE_SLAB: - case GRANITE_STAIRS: - case GRANITE_WALL: - case GRINDSTONE: - case HORN_CORAL_BLOCK: - case IRON_BARS: - case IRON_BLOCK: - case JUKEBOX: - case MOSSY_COBBLESTONE: - case MOSSY_COBBLESTONE_SLAB: - case MOSSY_COBBLESTONE_STAIRS: - case MOSSY_COBBLESTONE_WALL: - case MOSSY_STONE_BRICKS: - case MOSSY_STONE_BRICK_SLAB: - case MOSSY_STONE_BRICK_STAIRS: - case MOSSY_STONE_BRICK_WALL: - case NETHER_BRICKS: - case NETHER_BRICK_FENCE: - case NETHER_BRICK_SLAB: - case NETHER_BRICK_STAIRS: - case NETHER_BRICK_WALL: - case PETRIFIED_OAK_SLAB: - case POLISHED_ANDESITE: - case POLISHED_ANDESITE_SLAB: - case POLISHED_ANDESITE_STAIRS: - case POLISHED_DIORITE: - case POLISHED_DIORITE_SLAB: - case POLISHED_DIORITE_STAIRS: - case POLISHED_GRANITE: - case POLISHED_GRANITE_SLAB: - case POLISHED_GRANITE_STAIRS: - case PRISMARINE: - case PRISMARINE_BRICKS: - case PRISMARINE_BRICK_SLAB: - case PRISMARINE_BRICK_STAIRS: - case PRISMARINE_SLAB: - case PRISMARINE_STAIRS: - case PRISMARINE_WALL: - case PURPUR_BLOCK: - case PURPUR_PILLAR: - case PURPUR_SLAB: - case PURPUR_STAIRS: - case QUARTZ_SLAB: - case REDSTONE_BLOCK: - case RED_NETHER_BRICKS: - case RED_NETHER_BRICK_SLAB: - case RED_NETHER_BRICK_STAIRS: - case RED_NETHER_BRICK_WALL: - case RED_SANDSTONE_SLAB: - case SANDSTONE_SLAB: - case SMOOTH_QUARTZ: - case SMOOTH_QUARTZ_SLAB: - case SMOOTH_QUARTZ_STAIRS: - case SMOOTH_RED_SANDSTONE: - case SMOOTH_RED_SANDSTONE_SLAB: - case SMOOTH_RED_SANDSTONE_STAIRS: - case SMOOTH_SANDSTONE: - case SMOOTH_SANDSTONE_SLAB: - case SMOOTH_SANDSTONE_STAIRS: - case SMOOTH_STONE: - case SMOOTH_STONE_SLAB: - case STONE: - case STONE_BRICKS: - case STONE_BRICK_SLAB: - case STONE_BRICK_STAIRS: - case STONE_BRICK_WALL: - case STONE_SLAB: - case STONE_STAIRS: - case TUBE_CORAL_BLOCK: - return 6.0F; - case DRAGON_EGG: - case END_STONE: - return 9.0F; - case LAVA: - case WATER: - return 100.0F; - case ENDER_CHEST: - return 600.0F; - case ANVIL: - case CHIPPED_ANVIL: - case DAMAGED_ANVIL: - case ENCHANTING_TABLE: - case OBSIDIAN: - return 1200.0F; - case BEDROCK: - case CHAIN_COMMAND_BLOCK: - case COMMAND_BLOCK: - case END_GATEWAY: - case END_PORTAL: - case END_PORTAL_FRAME: - case JIGSAW: - case REPEATING_COMMAND_BLOCK: - case STRUCTURE_BLOCK: - return 3600000.0F; - case BARRIER: - return 3600000.8F; - default: - return 0; - // - } - } -} diff --git a/api/src/main/java/org/bukkit/Nameable.java b/api/src/main/java/org/bukkit/Nameable.java deleted file mode 100644 index fee814e01..000000000 --- a/api/src/main/java/org/bukkit/Nameable.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit; - -import org.jetbrains.annotations.Nullable; - -public interface Nameable { - - /** - * Gets the custom name on a mob or block. 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/block or null - */ - @Nullable - public String getCustomName(); - - /** - * Sets a custom name on a mob or block. 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 - */ - public void setCustomName(@Nullable String name); -} diff --git a/api/src/main/java/org/bukkit/NamespacedKey.java b/api/src/main/java/org/bukkit/NamespacedKey.java deleted file mode 100644 index 620a962df..000000000 --- a/api/src/main/java/org/bukkit/NamespacedKey.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.bukkit; - -import com.google.common.base.Preconditions; -import java.util.Locale; -import java.util.UUID; -import java.util.regex.Pattern; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a String based key which consists of two components - a namespace - * and a key. - * - * Namespaces may only contain lowercase alphanumeric characters, periods, - * underscores, and hyphens. - *

- * Keys may only contain lowercase alphanumeric characters, periods, - * underscores, hyphens, and forward slashes. - * - */ -public final class NamespacedKey implements com.destroystokyo.paper.Namespaced { // Paper - implement namespaced - - /** - * The namespace representing all inbuilt keys. - */ - public static final String MINECRAFT = "minecraft"; - /** - * The namespace representing all keys generated by Bukkit for backwards - * compatibility measures. - */ - public static final String BUKKIT = "bukkit"; - // - private static final Pattern VALID_NAMESPACE = Pattern.compile("[a-z0-9._-]+"); - private static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); - // - private final String namespace; - private final String key; - - /** - * Create a key in a specific namespace. - * - * @param namespace namespace - * @param key key - * @deprecated should never be used by plugins, for internal use only!! - */ - @Deprecated - public NamespacedKey(@NotNull String namespace, @NotNull String key) { - Preconditions.checkArgument(namespace != null && VALID_NAMESPACE.matcher(namespace).matches(), "Invalid namespace. Must be [a-z0-9._-]: %s", namespace); - Preconditions.checkArgument(key != null && VALID_KEY.matcher(key).matches(), "Invalid key. Must be [a-z0-9/._-]: %s", key); - - this.namespace = namespace; - this.key = key; - - String string = toString(); - Preconditions.checkArgument(string.length() < 256, "NamespacedKey must be less than 256 characters", string); - } - - /** - * Create a key in the plugin's namespace. - *

- * Namespaces may only contain lowercase alphanumeric characters, periods, - * underscores, and hyphens. - *

- * Keys may only contain lowercase alphanumeric characters, periods, - * underscores, hyphens, and forward slashes. - * - * @param plugin the plugin to use for the namespace - * @param key the key to create - */ - public NamespacedKey(@NotNull Plugin plugin, @NotNull String key) { - Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); - Preconditions.checkArgument(key != null, "Key cannot be null"); - - this.namespace = plugin.getName().toLowerCase(Locale.ROOT); - this.key = key.toLowerCase(Locale.ROOT); - - // Check validity after normalization - Preconditions.checkArgument(VALID_NAMESPACE.matcher(this.namespace).matches(), "Invalid namespace. Must be [a-z0-9._-]: %s", this.namespace); - Preconditions.checkArgument(VALID_KEY.matcher(this.key).matches(), "Invalid key. Must be [a-z0-9/._-]: %s", this.key); - - String string = toString(); - Preconditions.checkArgument(string.length() < 256, "NamespacedKey must be less than 256 characters (%s)", string); - } - - @NotNull - @Override // Paper - public String getNamespace() { - return namespace; - } - - @NotNull - @Override // Paper - public String getKey() { - return key; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 47 * hash + this.namespace.hashCode(); - hash = 47 * hash + this.key.hashCode(); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final NamespacedKey other = (NamespacedKey) obj; - return this.namespace.equals(other.namespace) && this.key.equals(other.key); - } - - @Override - public String toString() { - return this.namespace + ":" + this.key; - } - - /** - * Return a new random key in the {@link #BUKKIT} namespace. - * - * @return new key - * @deprecated should never be used by plugins, for internal use only!! - */ - @Deprecated - @NotNull - public static NamespacedKey randomKey() { - return new NamespacedKey(BUKKIT, UUID.randomUUID().toString()); - } - - /** - * Get a key in the Minecraft namespace. - * - * @param key the key to use - * @return new key in the Minecraft namespace - */ - @NotNull - public static NamespacedKey minecraft(@NotNull String key) { - return new NamespacedKey(MINECRAFT, key); - } -} diff --git a/api/src/main/java/org/bukkit/NetherWartsState.java b/api/src/main/java/org/bukkit/NetherWartsState.java deleted file mode 100644 index f43209cf7..000000000 --- a/api/src/main/java/org/bukkit/NetherWartsState.java +++ /dev/null @@ -1,21 +0,0 @@ -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/api/src/main/java/org/bukkit/Note.java b/api/src/main/java/org/bukkit/Note.java deleted file mode 100644 index b1c86aefb..000000000 --- a/api/src/main/java/org/bukkit/Note.java +++ /dev/null @@ -1,283 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.apache.commons.lang.Validate; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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; - - private 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 - @Nullable - 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, @NotNull 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. - */ - @NotNull - public static Note flat(int octave, @NotNull 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. - */ - @NotNull - public static Note sharp(int octave, @NotNull 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. - */ - @NotNull - public static Note natural(int octave, @NotNull 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. - */ - @NotNull - 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. - */ - @NotNull - 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. - */ - @NotNull - 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/api/src/main/java/org/bukkit/OfflinePlayer.java b/api/src/main/java/org/bukkit/OfflinePlayer.java deleted file mode 100644 index 3ab914fb2..000000000 --- a/api/src/main/java/org/bukkit/OfflinePlayer.java +++ /dev/null @@ -1,196 +0,0 @@ -package org.bukkit; - -import java.util.UUID; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.entity.AnimalTamer; -import org.bukkit.entity.Player; -import org.bukkit.permissions.ServerOperator; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface OfflinePlayer extends ServerOperator, AnimalTamer, ConfigurationSerializable { - - /** - * Checks if this player is currently online - * - * @return true if they are online - */ - public 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 - */ - @Override - @Nullable - public String getName(); - - /** - * Returns the UUID of this player - * - * @return Player UUID - */ - @Override - @NotNull - public UUID getUniqueId(); - - /** - * Checks if this player is banned or not - * - * @return true if banned, otherwise false - */ - public boolean isBanned(); - // Paper start - - /** - * Permanently Bans this player from the server - * - * @param reason Reason for Ban - * @return Ban Entry - */ - @NotNull - public default BanEntry banPlayer(@Nullable String reason) { - return banPlayer(reason, null, null); - } - - /** - * Permanently Bans this player from the server - * @param reason Reason for Ban - * @param source Source of the ban, or null for default - * @return Ban Entry - */ - @NotNull - public default BanEntry banPlayer(@Nullable String reason, @Nullable String source) { - return banPlayer(reason, null, source); - } - - /** - * Bans this player from the server - * @param reason Reason for Ban - * @param expires When to expire the ban - * @return Ban Entry - */ - @NotNull - public default BanEntry banPlayer(@Nullable String reason, @Nullable java.util.Date expires) { - return banPlayer(reason, expires, null); - } - - /** - * Bans this player from the server - * @param reason Reason for Ban - * @param expires When to expire the ban - * @param source Source of the ban or null for default - * @return Ban Entry - */ - @NotNull - public default BanEntry banPlayer(@Nullable String reason, @Nullable java.util.Date expires, @Nullable String source) { - return banPlayer(reason, expires, source, true); - } - @NotNull - public default BanEntry banPlayer(@Nullable String reason, @Nullable java.util.Date expires, @Nullable String source, boolean kickIfOnline) { - BanEntry banEntry = Bukkit.getServer().getBanList(BanList.Type.NAME).addBan(getName(), reason, expires, source); - if (kickIfOnline && isOnline()) { - getPlayer().kickPlayer(reason); - } - return banEntry; - } - // Paper end - - /** - * Checks if this player is whitelisted or not - * - * @return true if whitelisted - */ - public boolean isWhitelisted(); - - /** - * Sets if this player is whitelisted or not - * - * @param value true if whitelisted - */ - public 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 - */ - @Nullable - public 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 - */ - public 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 - * @deprecated The API contract is ambiguous and the implementation may or may not return the correct value given this API ambiguity. It is instead recommended use {@link #getLastLogin()} or {@link #getLastSeen()} depending on your needs. - */ - @Deprecated - public long getLastPlayed(); - - /** - * Checks if this player has played on this server before. - * - * @return True if the player has played before, otherwise false - */ - public 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. - */ - @Nullable - public Location getBedSpawnLocation(); - - // Paper start - - /** - * Gets the last date and time that this player logged into the 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 last login time - */ - public long getLastLogin(); - - /** - * Gets the last date and time that this player was seen on the server. - *

- * If the player has never played before, this will return 0. If the - * player is currently online, this will return the current time. - * Otherwise it will be the amount of milliseconds since midnight, - * January 1, 1970 UTC. - * - * @return last seen time - */ - public long getLastSeen(); - // Paper end - -} diff --git a/api/src/main/java/org/bukkit/Particle.java b/api/src/main/java/org/bukkit/Particle.java deleted file mode 100644 index 69aae30a3..000000000 --- a/api/src/main/java/org/bukkit/Particle.java +++ /dev/null @@ -1,140 +0,0 @@ -package org.bukkit; - -import com.google.common.base.Preconditions; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.NotNull; - -public enum Particle { - EXPLOSION_NORMAL, - EXPLOSION_LARGE, - EXPLOSION_HUGE, - FIREWORKS_SPARK, - WATER_BUBBLE, - WATER_SPLASH, - WATER_WAKE, - SUSPENDED, - SUSPENDED_DEPTH, - CRIT, - CRIT_MAGIC, - SMOKE_NORMAL, - SMOKE_LARGE, - SPELL, - SPELL_INSTANT, - SPELL_MOB, - SPELL_MOB_AMBIENT, - SPELL_WITCH, - DRIP_WATER, - DRIP_LAVA, - VILLAGER_ANGRY, - VILLAGER_HAPPY, - TOWN_AURA, - NOTE, - PORTAL, - ENCHANTMENT_TABLE, - FLAME, - LAVA, - CLOUD, - REDSTONE(DustOptions.class), - SNOWBALL, - SNOW_SHOVEL, - SLIME, - HEART, - BARRIER, - ITEM_CRACK(ItemStack.class), - BLOCK_CRACK(BlockData.class), - BLOCK_DUST(BlockData.class), - WATER_DROP, - MOB_APPEARANCE, - DRAGON_BREATH, - END_ROD, - DAMAGE_INDICATOR, - SWEEP_ATTACK, - FALLING_DUST(BlockData.class), - TOTEM, - SPIT, - SQUID_INK, - BUBBLE_POP, - CURRENT_DOWN, - BUBBLE_COLUMN_UP, - NAUTILUS, - DOLPHIN, - SNEEZE, - CAMPFIRE_COSY_SMOKE, - CAMPFIRE_SIGNAL_SMOKE, - COMPOSTER, - FLASH, - FALLING_LAVA, - LANDING_LAVA, - FALLING_WATER, - // ----- Legacy Separator ----- - LEGACY_BLOCK_CRACK(MaterialData.class), - LEGACY_BLOCK_DUST(MaterialData.class), - LEGACY_FALLING_DUST(MaterialData.class); - - private final Class dataType; - - Particle() { - dataType = Void.class; - } - - Particle(/*@NotNull*/ Class data) { - dataType = data; - } - - /** - * Returns the required data type for the particle - * @return the required data type - */ - @NotNull - public Class getDataType() { - return dataType; - } - - // Paper start - Particle API expansion - /** - * Creates a {@link com.destroystokyo.paper.ParticleBuilder} - * - * @return a {@link com.destroystokyo.paper.ParticleBuilder} for the particle - */ - @NotNull - public com.destroystokyo.paper.ParticleBuilder builder() { - return new com.destroystokyo.paper.ParticleBuilder(this); - } - // Paper end - /** - * Options which can be applied to redstone dust particles - a particle - * color and size. - */ - public static class DustOptions { - - private final Color color; - private final float size; - - public DustOptions(@NotNull Color color, float size) { - Preconditions.checkArgument(color != null, "color"); - this.color = color; - this.size = size; - } - - /** - * The color of the particles to be displayed. - * - * @return particle color - */ - @NotNull - public Color getColor() { - return color; - } - - /** - * Relative size of the particle. - * - * @return relative particle size - */ - public float getSize() { - return size; - } - } -} diff --git a/api/src/main/java/org/bukkit/PortalType.java b/api/src/main/java/org/bukkit/PortalType.java deleted file mode 100644 index 427cfbb8b..000000000 --- a/api/src/main/java/org/bukkit/PortalType.java +++ /dev/null @@ -1,22 +0,0 @@ -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/api/src/main/java/org/bukkit/Raid.java b/api/src/main/java/org/bukkit/Raid.java deleted file mode 100644 index 983a8c20a..000000000 --- a/api/src/main/java/org/bukkit/Raid.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.bukkit; - -import java.util.List; -import java.util.Set; -import java.util.UUID; -import org.bukkit.entity.Raider; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a raid event. - */ -public interface Raid { - - /** - * Get whether this raid started. - * - * @return whether raid is started - */ - boolean isStarted(); - - /** - * Gets the amount of ticks this raid has existed. - * - * @return active ticks - */ - long getActiveTicks(); - - /** - * Gets the Bad Omen level of this raid. - * - * @return Bad Omen level (between 0 and 5) - */ - int getBadOmenLevel(); - - /** - * Sets the Bad Omen level. - *
- * If the level is higher than 1, there will be an additional wave that as - * strong as the final wave. - * - * @param badOmenLevel new Bad Omen level (from 0-5) - * @throws IllegalArgumentException if invalid Bad Omen level - */ - void setBadOmenLevel(int badOmenLevel); - - /** - * Gets the center location where the raid occurs. - * - * @return location - */ - @NotNull - Location getLocation(); - - /** - * Gets the current status of the raid. - *
- * Do not use this method to check if the raid has been started, call - * {@link #isStarted()} instead. - * - * @return Raids status - */ - @NotNull - RaidStatus getStatus(); - - /** - * Gets the number of raider groups which have spawned. - * - * @return total spawned groups - */ - int getSpawnedGroups(); - - /** - * Gets the number of raider groups which would spawn. - *
- * This also includes the group which spawns in the additional wave (if - * present). - * - * @return total groups - */ - int getTotalGroups(); - - /** - * Gets the number of waves in this raid (exclude the additional wave). - * - * @return number of waves - */ - int getTotalWaves(); - - /** - * Gets the sum of all raider's health. - * - * @return total raiders health - */ - float getTotalHealth(); - - /** - * Get the UUID of all heroes in this raid. - * - * @return a set of unique ids - */ - @NotNull - Set getHeroes(); - - /** - * Gets all remaining {@link Raider} in the present wave. - * - * @return a list of current raiders - */ - @NotNull - List getRaiders(); - - /** - * Represents the status of a {@link Raid}. - */ - public enum RaidStatus { - - /** - * The raid is in progress. - */ - ONGOING, - /** - * The raid was beaten by heroes. - */ - VICTORY, - /** - * The village has fallen (i.e. all villagers died). - */ - LOSS, - /** - * The raid was terminated. - */ - STOPPED; - } -} diff --git a/api/src/main/java/org/bukkit/Registry.java b/api/src/main/java/org/bukkit/Registry.java deleted file mode 100644 index 9d0d0d745..000000000 --- a/api/src/main/java/org/bukkit/Registry.java +++ /dev/null @@ -1,196 +0,0 @@ -package org.bukkit; - -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableMap; -import java.util.Arrays; -import java.util.Iterator; -import java.util.Map; -import java.util.function.Predicate; -import org.bukkit.advancement.Advancement; -import org.bukkit.block.Biome; -import org.bukkit.boss.KeyedBossBar; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Villager; -import org.bukkit.entity.memory.MemoryKey; -import org.bukkit.loot.LootTables; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a registry of Bukkit objects that may be retrieved by - * {@link NamespacedKey}. - * - * @param type of item in the registry - */ -public interface Registry extends Iterable { - - /** - * Server advancements. - * - * @see Bukkit#getAdvancement(org.bukkit.NamespacedKey) - * @see Bukkit#advancementIterator() - */ - Registry ADVANCEMENT = new Registry() { - - @Nullable - @Override - public Advancement get(@NotNull NamespacedKey key) { - return Bukkit.getAdvancement(key); - } - - @NotNull - @Override - public Iterator iterator() { - return Bukkit.advancementIterator(); - } - }; - /** - * Server art. - * - * @see Art - */ - Registry ART = new SimpleRegistry<>(Art.class); - /** - * Server biomes. - * - * @see Biome - */ - Registry BIOME = new SimpleRegistry<>(Biome.class); - /** - * Custom boss bars. - * - * @see Bukkit#getBossBar(org.bukkit.NamespacedKey) - * @see Bukkit#getBossBars() - */ - Registry BOSS_BARS = new Registry() { - - @Nullable - @Override - public KeyedBossBar get(@NotNull NamespacedKey key) { - return Bukkit.getBossBar(key); - } - - @NotNull - @Override - public Iterator iterator() { - return Bukkit.getBossBars(); - } - }; - /** - * Server enchantments. - * - * @see Enchantment#getByKey(org.bukkit.NamespacedKey) - */ - Registry ENCHANTMENT = new Registry() { - - @Nullable - @Override - public Enchantment get(@NotNull NamespacedKey key) { - return Enchantment.getByKey(key); - } - - @NotNull - @Override - public Iterator iterator() { - return Arrays.asList(Enchantment.values()).iterator(); - } - }; - /** - * Server entity types. - * - * @see EntityType - */ - Registry ENTITY_TYPE = new SimpleRegistry<>(EntityType.class, (entity) -> entity != EntityType.UNKNOWN); - /** - * Default server loot tables. - * - * @see LootTables - */ - Registry LOOT_TABLES = new SimpleRegistry<>(LootTables.class); - /** - * Server materials. - * - * @see Material - */ - Registry MATERIAL = new SimpleRegistry<>(Material.class, (mat) -> !mat.isLegacy()); - /** - * Server statistics. - * - * @see Statistic - */ - Registry STATISTIC = new SimpleRegistry<>(Statistic.class); - /** - * Villager profession. - * - * @see Villager.Profession - */ - Registry VILLAGER_PROFESSION = new SimpleRegistry<>(Villager.Profession.class); - /** - * Villager type. - * - * @see Villager.Type - */ - Registry VILLAGER_TYPE = new SimpleRegistry<>(Villager.Type.class); - /** - * Memory Keys. - * - * @see MemoryKey - */ - Registry MEMORY_MODULE_TYPE = new Registry() { - - @NotNull - @Override - public Iterator iterator() { - return MemoryKey.values().iterator(); - } - - @Nullable - @Override - public MemoryKey get(@NotNull NamespacedKey key) { - return MemoryKey.getByKey(key); - } - }; - - /** - * Get the object by its key. - * - * @param key non-null key - * @return item or null if does not exist - */ - @Nullable - T get(@NotNull NamespacedKey key); - - static final class SimpleRegistry & Keyed> implements Registry { - - private final Map map; - - protected SimpleRegistry(@NotNull Class type) { - this(type, Predicates.alwaysTrue()); - } - - protected SimpleRegistry(@NotNull Class type, @NotNull Predicate predicate) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - - for (T entry : type.getEnumConstants()) { - if (predicate.test(entry)) { - builder.put(entry.getKey(), entry); - } - } - - map = builder.build(); - } - - @Nullable - @Override - public T get(@NotNull NamespacedKey key) { - return map.get(key); - } - - @NotNull - @Override - public Iterator iterator() { - return map.values().iterator(); - } - } -} diff --git a/api/src/main/java/org/bukkit/Rotation.java b/api/src/main/java/org/bukkit/Rotation.java deleted file mode 100644 index 78708fe39..000000000 --- a/api/src/main/java/org/bukkit/Rotation.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bukkit; - -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public Rotation rotateClockwise() { - return rotations[(this.ordinal() + 1) & 0x7]; - } - - /** - * Rotate counter-clockwise by 90 degrees. - * - * @return the relative rotation - */ - @NotNull - public Rotation rotateCounterClockwise() { - return rotations[(this.ordinal() - 1) & 0x7]; - } -} diff --git a/api/src/main/java/org/bukkit/SandstoneType.java b/api/src/main/java/org/bukkit/SandstoneType.java deleted file mode 100644 index 6277451c3..000000000 --- a/api/src/main/java/org/bukkit/SandstoneType.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -/** - * Represents the three different types of Sandstone - */ -public enum SandstoneType { - CRACKED(0x0), - GLYPHED(0x1), - SMOOTH(0x2); - - private final byte data; - private static final Map BY_DATA = Maps.newHashMap(); - - private 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 - @Nullable - 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/api/src/main/java/org/bukkit/Server.java b/api/src/main/java/org/bukkit/Server.java deleted file mode 100644 index 314704790..000000000 --- a/api/src/main/java/org/bukkit/Server.java +++ /dev/null @@ -1,1409 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.ImmutableList; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.function.Consumer; -import java.util.logging.Logger; -import org.bukkit.Warning.WarningState; -import org.bukkit.advancement.Advancement; -import org.bukkit.block.data.BlockData; -import org.bukkit.boss.BarColor; -import org.bukkit.boss.BarFlag; -import org.bukkit.boss.BarStyle; -import org.bukkit.boss.BossBar; -import org.bukkit.boss.KeyedBossBar; -import org.bukkit.command.CommandException; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.command.PluginCommand; -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.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemFactory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.Recipe; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.loot.LootTable; -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 org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(java.lang.String, java.lang.String)}. - */ - public static final String BROADCAST_CHANNEL_ADMINISTRATIVE = "bukkit.broadcast.admin"; - - /** - * Used for all announcement messages, such as informing users that a - * player has joined. - *

- * For use in {@link #broadcast(java.lang.String, java.lang.String)}. - */ - public static final String BROADCAST_CHANNEL_USERS = "bukkit.broadcast.user"; - - /** - * Gets the name of this server implementation. - * - * @return name of this server implementation - */ - @NotNull - public String getName(); - - /** - * Gets the version string of this server implementation. - * - * @return version of this server implementation - */ - @NotNull - public String getVersion(); - - /** - * Gets the Bukkit version that this server is running. - * - * @return version of Bukkit - */ - @NotNull - public String getBukkitVersion(); - - /** - * 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. - */ - @NotNull - public Collection getOnlinePlayers(); - - /** - * Get the maximum amount of players which can login to this server. - * - * @return the amount of players this server allows - */ - public int getMaxPlayers(); - - /** - * Get the game port that the server runs on. - * - * @return the port number of this server - */ - public int getPort(); - - /** - * Get the view distance from this server. - * - * @return the view distance from this server. - */ - public 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 - */ - @NotNull - public String getIp(); - - /** - * Get world type (level-type setting) for default world. - * - * @return the value of level-type (e.g. DEFAULT, FLAT, DEFAULT_1_1) - */ - @NotNull - public String getWorldType(); - - /** - * Get generate-structures setting. - * - * @return true if structure generation is enabled, false otherwise - */ - public boolean getGenerateStructures(); - - /** - * Gets whether this server allows the End or not. - * - * @return whether this server allows the End or not - */ - public boolean getAllowEnd(); - - /** - * Gets whether this server allows the Nether or not. - * - * @return whether this server allows the Nether or not - */ - public boolean getAllowNether(); - - /** - * Gets whether this server has a whitelist or not. - * - * @return whether this server has a whitelist or not - */ - public boolean hasWhitelist(); - - /** - * Sets if the server is whitelisted. - * - * @param value true for whitelist on, false for off - */ - public void setWhitelist(boolean value); - - /** - * Gets a list of whitelisted players. - * - * @return a set containing all whitelisted players - */ - @NotNull - public Set getWhitelistedPlayers(); - - /** - * Reloads the whitelist from disk. - */ - public void reloadWhitelist(); - - /** - * Broadcast a message to all players. - *

- * This is the same as calling {@link #broadcast(java.lang.String, - * java.lang.String)} to {@link #BROADCAST_CHANNEL_USERS} - * - * @param message the message - * @return the number of players - */ - public int broadcastMessage(@NotNull String message); - - // Paper start - /** - * Sends the component to all online players. - * - * @param component the component to send - */ - public default void broadcast(@NotNull net.md_5.bungee.api.chat.BaseComponent component) { - spigot().broadcast(component); - } - - /** - * Sends an array of components as a single message to all online players. - * - * @param components the components to send - */ - public default void broadcast(@NotNull net.md_5.bungee.api.chat.BaseComponent... components) { - spigot().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 - */ - @NotNull - public 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 - */ - @NotNull - public File getUpdateFolderFile(); - - /** - * Gets the value of the connection throttle setting. - * - * @return the value of the connection throttle setting - */ - public 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 - */ - public 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 - */ - public 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 - */ - @Nullable - public Player getPlayer(@NotNull 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 - */ - @Nullable - public Player getPlayerExact(@NotNull 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 - */ - @NotNull - public List matchPlayer(@NotNull 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 - */ - @Nullable - public Player getPlayer(@NotNull UUID id); - - // Paper start - /** - * Gets the unique ID of the player currently known as the specified player name - * In Offline Mode, will return an Offline UUID - * - * @param playerName the player name to look up the unique ID for - * @return A UUID, or null if that player name is not registered with Minecraft and the server is in online mode - */ - @Nullable - public UUID getPlayerUniqueId(@NotNull String playerName); - // Paper end - - /** - * Gets the plugin manager for interfacing with plugins. - * - * @return a plugin manager for this Server instance - */ - @NotNull - public PluginManager getPluginManager(); - - /** - * Gets the scheduler for managing scheduled events. - * - * @return a scheduling service for this server - */ - @NotNull - public BukkitScheduler getScheduler(); - - /** - * Gets a services manager. - * - * @return s services manager - */ - @NotNull - public ServicesManager getServicesManager(); - - /** - * Gets a list of all worlds on this server. - * - * @return a list of worlds - */ - @NotNull - public 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 - */ - @Nullable - public World createWorld(@NotNull 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 - */ - public boolean unloadWorld(@NotNull 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 - */ - public boolean unloadWorld(@NotNull 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 - */ - @Nullable - public World getWorld(@NotNull 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 - */ - @Nullable - public World getWorld(@NotNull 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 - @Nullable - public MapView getMap(int 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 - */ - @NotNull - public MapView createMap(@NotNull World world); - - /** - * Create a new explorer map targeting the closest nearby structure of a - * given {@link StructureType}. - *
- * This method uses implementation default values for radius and - * findUnexplored (usually 100, true). - * - * @param world the world the map will belong to - * @param location the origin location to find the nearest structure - * @param structureType the type of structure to find - * @return a newly created item stack - * - * @see World#locateNearestStructure(org.bukkit.Location, - * org.bukkit.StructureType, int, boolean) - */ - @NotNull - public ItemStack createExplorerMap(@NotNull World world, @NotNull Location location, @NotNull StructureType structureType); - - /** - * Create a new explorer map targeting the closest nearby structure of a - * given {@link StructureType}. - *
- * This method uses implementation default values for radius and - * findUnexplored (usually 100, true). - * - * @param world the world the map will belong to - * @param location the origin location to find the nearest structure - * @param structureType the type of structure to find - * @param radius radius to search, see World#locateNearestStructure for more - * information - * @param findUnexplored whether to find unexplored structures - * @return the newly created item stack - * - * @see World#locateNearestStructure(org.bukkit.Location, - * org.bukkit.StructureType, int, boolean) - */ - @NotNull - public ItemStack createExplorerMap(@NotNull World world, @NotNull Location location, @NotNull StructureType structureType, int radius, boolean findUnexplored); - - /** - * Reloads the server, refreshing settings and plugin information. - */ - public void reload(); - - /** - * Reload only the Minecraft data for the server. This includes custom - * advancements and loot tables. - */ - public void reloadData(); - - /** - * Returns the primary logger associated with this server instance. - * - * @return Logger associated with this server - */ - @NotNull - public 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 - */ - @Nullable - public PluginCommand getPluginCommand(@NotNull String name); - - /** - * Writes loaded players to disk. - */ - public 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 - */ - public boolean dispatchCommand(@NotNull CommandSender sender, @NotNull String commandLine) throws CommandException; - - /** - * 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 - */ - @Contract("null -> false") - public boolean addRecipe(@Nullable 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 - */ - @NotNull - public List getRecipesFor(@NotNull ItemStack result); - - /** - * Get an iterator through the list of crafting recipes. - * - * @return an iterator - */ - @NotNull - public Iterator recipeIterator(); - - /** - * Clears the list of crafting recipes. - */ - public void clearRecipes(); - - /** - * Resets the list of crafting recipes to the default. - */ - public void resetRecipes(); - - /** - * Gets a list of command aliases defined in the server properties. - * - * @return a map of aliases to command names - */ - @NotNull - public Map getCommandAliases(); - - /** - * Gets the radius, in blocks, around each worlds spawn point to protect. - * - * @return spawn radius, or 0 if none - */ - public int getSpawnRadius(); - - /** - * Sets the radius, in blocks, around each worlds spawn point to protect. - * - * @param value new spawn radius, or 0 if none - */ - public void setSpawnRadius(int value); - - /** - * Gets whether the Server is in online mode or not. - * - * @return true if the server authenticates clients, false otherwise - */ - public boolean getOnlineMode(); - - /** - * Gets whether this server allows flying or not. - * - * @return true if the server allows flight, false otherwise - */ - public boolean getAllowFlight(); - - /** - * Gets whether the server is in hardcore mode or not. - * - * @return true if the server mode is hardcore, false otherwise - */ - public boolean isHardcore(); - - /** - * Shutdowns the server, stopping everything. - */ - public 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 - */ - public int broadcast(@NotNull String message, @NotNull 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(java.util.UUID) - */ - @Deprecated - @NotNull - public OfflinePlayer getOfflinePlayer(@NotNull 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 - */ - @NotNull - public OfflinePlayer getOfflinePlayer(@NotNull UUID id); - - /** - * Gets a set containing all current IPs that are banned. - * - * @return a set containing banned IP addresses - */ - @NotNull - public Set getIPBans(); - - /** - * Bans the specified address from the server. - * - * @param address the IP address to ban - */ - public void banIP(@NotNull String address); - - /** - * Unbans the specified address from the server. - * - * @param address the IP address to unban - */ - public void unbanIP(@NotNull String address); - - /** - * Gets a set containing all banned players. - * - * @return a set containing banned players - */ - @NotNull - public 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 - */ - @NotNull - public BanList getBanList(@NotNull BanList.Type type); - - /** - * Gets a set containing all player operators. - * - * @return a set containing player operators - */ - @NotNull - public Set getOperators(); - - /** - * Gets the default {@link GameMode} for new players. - * - * @return the default game mode - */ - @NotNull - public GameMode getDefaultGameMode(); - - /** - * Sets the default {@link GameMode} for new players. - * - * @param mode the new game mode - */ - public void setDefaultGameMode(@NotNull GameMode mode); - - /** - * Gets a {@link ConsoleCommandSender} that may be used as an input source - * for this server. - * - * @return a console command sender - */ - @NotNull - public ConsoleCommandSender getConsoleSender(); - - /** - * Gets the folder that contains all of the various {@link World}s. - * - * @return folder that contains all worlds - */ - @NotNull - public File getWorldContainer(); - - /** - * Gets every player that has ever played on this server. - * - * @return an array containing all previous players - */ - @NotNull - public OfflinePlayer[] getOfflinePlayers(); - - /** - * Gets the {@link Messenger} responsible for this server. - * - * @return messenger responsible for this server - */ - @NotNull - public Messenger getMessenger(); - - /** - * Gets the {@link HelpMap} providing help topics for this server. - * - * @return a help map for this server - */ - @NotNull - public HelpMap getHelpMap(); - - /** - * Creates an empty inventory with 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. - *
- * {@link InventoryType#WORKBENCH} will not process crafting recipes if - * created with this method. Use - * {@link Player#openWorkbench(Location, boolean)} instead. - *
- * {@link InventoryType#ENCHANTING} will not process {@link ItemStack}s - * for possible enchanting results. Use - * {@link Player#openEnchanting(Location, boolean)} instead. - * - * @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 - * @throws IllegalArgumentException if the {@link InventoryType} cannot be - * viewed. - * - * @see InventoryType#isCreatable() - */ - @NotNull - Inventory createInventory(@Nullable InventoryHolder owner, @NotNull 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. - *
- * {@link InventoryType#WORKBENCH} will not process crafting recipes if - * created with this method. Use - * {@link Player#openWorkbench(Location, boolean)} instead. - *
- * {@link InventoryType#ENCHANTING} will not process {@link ItemStack}s - * for possible enchanting results. Use - * {@link Player#openEnchanting(Location, boolean)} instead. - * - * @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. - * @throws IllegalArgumentException if the {@link InventoryType} cannot be - * viewed. - * - * @see InventoryType#isCreatable() - */ - @NotNull - Inventory createInventory(@Nullable InventoryHolder owner, @NotNull InventoryType type, @NotNull 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 - */ - @NotNull - Inventory createInventory(@Nullable 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 - */ - @NotNull - Inventory createInventory(@Nullable InventoryHolder owner, int size, @NotNull String title) throws IllegalArgumentException; - - /** - * Creates an empty merchant. - * - * @param title the title of the corresponding merchant inventory, displayed - * when the merchant inventory is viewed - * @return a new merchant - */ - @NotNull - Merchant createMerchant(@Nullable String title); - - /** - * 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 - */ - @NotNull - String getMotd(); - - /** - * Gets the default message that is displayed when the server is stopped. - * - * @return the shutdown message - */ - @Nullable - String getShutdownMessage(); - - /** - * Gets the current warning state for the server. - * - * @return the configured warning state - */ - @NotNull - public WarningState getWarningState(); - - /** - * Gets the instance of the item factory (for {@link ItemMeta}). - * - * @return the item factory - * @see ItemFactory - */ - @NotNull - 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. - */ - @NotNull // Paper - 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 - */ - @Nullable - 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)} - */ - @NotNull - CachedServerIcon loadServerIcon(@NotNull 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)} - */ - @NotNull - CachedServerIcon loadServerIcon(@NotNull 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 - */ - public void setIdleTimeout(int threshold); - - /** - * Gets the idle kick timeout. - * - * @return the idle timeout in minutes - */ - public int getIdleTimeout(); - - /** - * Create a ChunkData for use in a generator. - * - * See {@link ChunkGenerator#generateChunkData(org.bukkit.World, java.util.Random, int, int, org.bukkit.generator.ChunkGenerator.BiomeGrid)} - * - * @param world the world to create the ChunkData for - * @return a new ChunkData for the world - * - */ - @NotNull - public ChunkGenerator.ChunkData createChunkData(@NotNull World world); - - /** - * Creates a boss bar instance to display to players. The progress - * defaults to 1.0 - * - * @param title the title of the boss bar - * @param color the color of the boss bar - * @param style the style of the boss bar - * @param flags an optional list of flags to set on the boss bar - * @return the created boss bar - */ - @NotNull - BossBar createBossBar(@Nullable String title, @NotNull BarColor color, @NotNull BarStyle style, @NotNull BarFlag... flags); - - /** - * Creates a boss bar instance to display to players. The progress defaults - * to 1.0. - *
- * This instance is added to the persistent storage of the server and will - * be editable by commands and restored after restart. - * - * @param key the key of the boss bar that is used to access the boss bar - * @param title the title of the boss bar - * @param color the color of the boss bar - * @param style the style of the boss bar - * @param flags an optional list of flags to set on the boss bar - * @return the created boss bar - */ - @NotNull - KeyedBossBar createBossBar(@NotNull NamespacedKey key, @Nullable String title, @NotNull BarColor color, @NotNull BarStyle style, @NotNull BarFlag... flags); - - /** - * Gets an unmodifiable iterator through all persistent bossbars. - *

    - *
  • not bound to a {@link org.bukkit.entity.Boss}
  • - *
  • - * not created using - * {@link #createBossBar(String, BarColor, BarStyle, BarFlag...)} - *
  • - *
- * - * e.g. bossbars created using the bossbar command - * - * @return a bossbar iterator - */ - @NotNull - Iterator getBossBars(); - - /** - * Gets the {@link KeyedBossBar} specified by this key. - *
    - *
  • not bound to a {@link org.bukkit.entity.Boss}
  • - *
  • - * not created using - * {@link #createBossBar(String, BarColor, BarStyle, BarFlag...)} - *
  • - *
- * - * e.g. bossbars created using the bossbar command - * - * @param key unique bossbar key - * @return bossbar or null if not exists - */ - @Nullable - KeyedBossBar getBossBar(@NotNull NamespacedKey key); - - /** - * Removes a {@link KeyedBossBar} specified by this key. - *
    - *
  • not bound to a {@link org.bukkit.entity.Boss}
  • - *
  • - * not created using - * {@link #createBossBar(String, BarColor, BarStyle, BarFlag...)} - *
  • - *
- * - * e.g. bossbars created using the bossbar command - * - * @param key unique bossbar key - * @return true if removal succeeded or false - */ - boolean removeBossBar(@NotNull NamespacedKey key); - - /** - * Gets an entity on the server by its UUID - * - * @param uuid the UUID of the entity - * @return the entity with the given UUID, or null if it isn't found - */ - @Nullable - Entity getEntity(@NotNull UUID uuid); - - // Paper start - /** - * Gets the current server TPS - * - * @return current server TPS (1m, 5m, 15m in Paper-Server) - */ - @NotNull - public double[] getTPS(); - // Paper end - - // Paper start - /** - * Gets the active {@link org.bukkit.command.CommandMap} - * - * @return the active command map - */ - @NotNull - org.bukkit.command.CommandMap getCommandMap(); - - /** - * Get the advancement specified by this key. - * - * @param key unique advancement key - * @return advancement or null if not exists - */ - @Nullable - Advancement getAdvancement(@NotNull NamespacedKey key); - - /** - * Get an iterator through all advancements. Advancements cannot be removed - * from this iterator, - * - * @return an advancement iterator - */ - @NotNull - Iterator advancementIterator(); - - /** - * Creates a new {@link BlockData} instance for the specified Material, with - * all properties initialized to unspecified defaults. - * - * @param material the material - * @return new data instance - */ - @NotNull - BlockData createBlockData(@NotNull Material material); - - /** - * Creates a new {@link BlockData} instance for the specified Material, with - * all properties initialized to unspecified defaults. - * - * @param material the material - * @param consumer consumer to run on new instance before returning - * @return new data instance - */ - @NotNull - public BlockData createBlockData(@NotNull Material material, @Nullable Consumer consumer); - - /** - * Creates a new {@link BlockData} instance with material and properties - * parsed from provided data. - * - * @param data data string - * @return new data instance - * @throws IllegalArgumentException if the specified data is not valid - */ - @NotNull - BlockData createBlockData(@NotNull String data) throws IllegalArgumentException; - - /** - * Creates a new {@link BlockData} instance for the specified Material, with - * all properties initialized to unspecified defaults, except for those - * provided in data. - *
- * If material is specified, then the data string must not also - * contain the material. - * - * @param material the material - * @param data data string - * @return new data instance - * @throws IllegalArgumentException if the specified data is not valid - */ - @NotNull - @Contract("null, null -> fail") - BlockData createBlockData(@Nullable Material material, @Nullable String data) throws IllegalArgumentException; - - /** - * Gets a tag which has already been defined within the server. Plugins are - * suggested to use the concrete tags in {@link Tag} rather than this method - * which makes no guarantees about which tags are available, and may also be - * less performant due to lack of caching. - *
- * Tags will be searched for in an implementation specific manner, but a - * path consisting of namespace/tags/registry/key is expected. - *
- * Server implementations are allowed to handle only the registries - * indicated in {@link Tag}. - * - * @param type of the tag - * @param registry the tag registry to look at - * @param tag the name of the tag - * @param clazz the class of the tag entries - * @return the tag or null - */ - @UndefinedNullability - Tag getTag(@NotNull String registry, @NotNull NamespacedKey tag, @NotNull Class clazz); - - /** - * Gets a all tags which have been defined within the server. - *
- * Server implementations are allowed to handle only the registries - * indicated in {@link Tag}. - *
- * No guarantees are made about the mutability of the returned iterator. - * - * @param type of the tag - * @param registry the tag registry to look at - * @param clazz the class of the tag entries - * @return all defined tags - */ - @NotNull - Iterable> getTags(@NotNull String registry, @NotNull Class clazz); - - /** - * Gets the specified {@link LootTable}. - * - * @param key the name of the LootTable - * @return the LootTable, or null if no LootTable is found with that name - */ - @Nullable - LootTable getLootTable(@NotNull NamespacedKey key); - - /** - * Selects entities using the given Vanilla selector. - *
- * No guarantees are made about the selector format, other than they match - * the Vanilla format for the active Minecraft version. - *
- * Usually a selector will start with '@', unless selecting a Player in - * which case it may simply be the Player's name or UUID. - *
- * Note that in Vanilla, elevated permissions are usually required to use - * '@' selectors, but this method should not check such permissions from the - * sender. - * - * @param sender the sender to execute as, must be provided - * @param selector the selection string - * @return a list of the selected entities. The list will not be null, but - * no further guarantees are made. - * @throws IllegalArgumentException if the selector is malformed in any way - * or a parameter is null - */ - @NotNull - List selectEntities(@NotNull CommandSender sender, @NotNull String selector) throws IllegalArgumentException; - - /** - * @see UnsafeValues - * @return the unsafe values instance - */ - @Deprecated - @NotNull - UnsafeValues getUnsafe(); - - // Spigot start - public class Spigot - { - - @NotNull - public org.bukkit.configuration.file.YamlConfiguration getConfig() - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - - // Paper start - @NotNull - public org.bukkit.configuration.file.YamlConfiguration getBukkitConfig() - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - - @NotNull - public org.bukkit.configuration.file.YamlConfiguration getSpigotConfig() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @NotNull - public org.bukkit.configuration.file.YamlConfiguration getPaperConfig() - { - throw new UnsupportedOperationException("Not supported yet."); - } - // Paper end - - /** - * Sends the component to the player - * - * @param component the components to send - */ - public void broadcast(@NotNull 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(@NotNull 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."); - } - } - - @NotNull - Spigot spigot(); - // Spigot end - - void reloadPermissions(); // Paper - - boolean reloadCommandAliases(); // Paper - - // Paper start - allow preventing player name suggestions by default - /** - * Checks if player names should be suggested when a command returns {@code null} as - * their tab completion result. - * - * @return true if player names should be suggested - */ - boolean suggestPlayerNamesWhenNullTabCompletions(); - - /** - * - * @return the default no permission message used on the server - */ - @NotNull - String getPermissionMessage(); - - /** - * Creates a PlayerProfile for the specified uuid, with name as null - * @param uuid UUID to create profile for - * @return A PlayerProfile object - */ - @NotNull - com.destroystokyo.paper.profile.PlayerProfile createProfile(@NotNull UUID uuid); - - /** - * Creates a PlayerProfile for the specified name, with UUID as null - * @param name Name to create profile for - * @return A PlayerProfile object - */ - @NotNull - com.destroystokyo.paper.profile.PlayerProfile createProfile(@NotNull String name); - - /** - * Creates a PlayerProfile for the specified name/uuid - * - * Both UUID and Name can not be null at same time. One must be supplied. - * - * @param uuid UUID to create profile for - * @param name Name to create profile for - * @return A PlayerProfile object - */ - @NotNull - com.destroystokyo.paper.profile.PlayerProfile createProfile(@Nullable UUID uuid, @Nullable String name); - - /** - * Get the current internal server tick - * - * @return Current tick - */ - int getCurrentTick(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/SkullType.java b/api/src/main/java/org/bukkit/SkullType.java deleted file mode 100644 index 1c3d9ae9b..000000000 --- a/api/src/main/java/org/bukkit/SkullType.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -/** - * Represents the different types of skulls. - * @deprecated check {@link Material} instead - */ -@Deprecated -public enum SkullType { - SKELETON, - WITHER, - ZOMBIE, - PLAYER, - CREEPER, - DRAGON; -} diff --git a/api/src/main/java/org/bukkit/Sound.java b/api/src/main/java/org/bukkit/Sound.java deleted file mode 100644 index 91e5f0f09..000000000 --- a/api/src/main/java/org/bukkit/Sound.java +++ /dev/null @@ -1,807 +0,0 @@ -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 { - AMBIENT_CAVE, - AMBIENT_UNDERWATER_ENTER, - AMBIENT_UNDERWATER_EXIT, - AMBIENT_UNDERWATER_LOOP, - AMBIENT_UNDERWATER_LOOP_ADDITIONS, - AMBIENT_UNDERWATER_LOOP_ADDITIONS_RARE, - AMBIENT_UNDERWATER_LOOP_ADDITIONS_ULTRA_RARE, - BLOCK_ANVIL_BREAK, - BLOCK_ANVIL_DESTROY, - BLOCK_ANVIL_FALL, - BLOCK_ANVIL_HIT, - BLOCK_ANVIL_LAND, - BLOCK_ANVIL_PLACE, - BLOCK_ANVIL_STEP, - BLOCK_ANVIL_USE, - BLOCK_BAMBOO_BREAK, - BLOCK_BAMBOO_FALL, - BLOCK_BAMBOO_HIT, - BLOCK_BAMBOO_PLACE, - BLOCK_BAMBOO_SAPLING_BREAK, - BLOCK_BAMBOO_SAPLING_HIT, - BLOCK_BAMBOO_SAPLING_PLACE, - BLOCK_BAMBOO_STEP, - BLOCK_BARREL_CLOSE, - BLOCK_BARREL_OPEN, - BLOCK_BEACON_ACTIVATE, - BLOCK_BEACON_AMBIENT, - BLOCK_BEACON_DEACTIVATE, - BLOCK_BEACON_POWER_SELECT, - BLOCK_BELL_RESONATE, - BLOCK_BELL_USE, - BLOCK_BLASTFURNACE_FIRE_CRACKLE, - BLOCK_BREWING_STAND_BREW, - BLOCK_BUBBLE_COLUMN_BUBBLE_POP, - BLOCK_BUBBLE_COLUMN_UPWARDS_AMBIENT, - BLOCK_BUBBLE_COLUMN_UPWARDS_INSIDE, - BLOCK_BUBBLE_COLUMN_WHIRLPOOL_AMBIENT, - BLOCK_BUBBLE_COLUMN_WHIRLPOOL_INSIDE, - BLOCK_CAMPFIRE_CRACKLE, - BLOCK_CHEST_CLOSE, - BLOCK_CHEST_LOCKED, - BLOCK_CHEST_OPEN, - BLOCK_CHORUS_FLOWER_DEATH, - BLOCK_CHORUS_FLOWER_GROW, - BLOCK_COMPARATOR_CLICK, - BLOCK_COMPOSTER_EMPTY, - BLOCK_COMPOSTER_FILL, - BLOCK_COMPOSTER_FILL_SUCCESS, - BLOCK_COMPOSTER_READY, - BLOCK_CONDUIT_ACTIVATE, - BLOCK_CONDUIT_AMBIENT, - BLOCK_CONDUIT_AMBIENT_SHORT, - BLOCK_CONDUIT_ATTACK_TARGET, - BLOCK_CONDUIT_DEACTIVATE, - BLOCK_CORAL_BLOCK_BREAK, - BLOCK_CORAL_BLOCK_FALL, - BLOCK_CORAL_BLOCK_HIT, - BLOCK_CORAL_BLOCK_PLACE, - BLOCK_CORAL_BLOCK_STEP, - BLOCK_CROP_BREAK, - BLOCK_DISPENSER_DISPENSE, - BLOCK_DISPENSER_FAIL, - BLOCK_DISPENSER_LAUNCH, - BLOCK_ENCHANTMENT_TABLE_USE, - BLOCK_ENDER_CHEST_CLOSE, - BLOCK_ENDER_CHEST_OPEN, - BLOCK_END_GATEWAY_SPAWN, - BLOCK_END_PORTAL_FRAME_FILL, - BLOCK_END_PORTAL_SPAWN, - BLOCK_FENCE_GATE_CLOSE, - BLOCK_FENCE_GATE_OPEN, - BLOCK_FIRE_AMBIENT, - BLOCK_FIRE_EXTINGUISH, - BLOCK_FURNACE_FIRE_CRACKLE, - BLOCK_GLASS_BREAK, - BLOCK_GLASS_FALL, - BLOCK_GLASS_HIT, - BLOCK_GLASS_PLACE, - BLOCK_GLASS_STEP, - BLOCK_GRASS_BREAK, - BLOCK_GRASS_FALL, - BLOCK_GRASS_HIT, - BLOCK_GRASS_PLACE, - BLOCK_GRASS_STEP, - BLOCK_GRAVEL_BREAK, - BLOCK_GRAVEL_FALL, - BLOCK_GRAVEL_HIT, - BLOCK_GRAVEL_PLACE, - BLOCK_GRAVEL_STEP, - BLOCK_GRINDSTONE_USE, - BLOCK_IRON_DOOR_CLOSE, - BLOCK_IRON_DOOR_OPEN, - BLOCK_IRON_TRAPDOOR_CLOSE, - BLOCK_IRON_TRAPDOOR_OPEN, - BLOCK_LADDER_BREAK, - BLOCK_LADDER_FALL, - BLOCK_LADDER_HIT, - BLOCK_LADDER_PLACE, - BLOCK_LADDER_STEP, - BLOCK_LANTERN_BREAK, - BLOCK_LANTERN_FALL, - BLOCK_LANTERN_HIT, - BLOCK_LANTERN_PLACE, - BLOCK_LANTERN_STEP, - BLOCK_LAVA_AMBIENT, - BLOCK_LAVA_EXTINGUISH, - BLOCK_LAVA_POP, - BLOCK_LEVER_CLICK, - BLOCK_LILY_PAD_PLACE, - BLOCK_METAL_BREAK, - BLOCK_METAL_FALL, - BLOCK_METAL_HIT, - BLOCK_METAL_PLACE, - BLOCK_METAL_PRESSURE_PLATE_CLICK_OFF, - BLOCK_METAL_PRESSURE_PLATE_CLICK_ON, - BLOCK_METAL_STEP, - BLOCK_NETHER_WART_BREAK, - BLOCK_NOTE_BLOCK_BANJO, - BLOCK_NOTE_BLOCK_BASEDRUM, - BLOCK_NOTE_BLOCK_BASS, - BLOCK_NOTE_BLOCK_BELL, - BLOCK_NOTE_BLOCK_BIT, - BLOCK_NOTE_BLOCK_CHIME, - BLOCK_NOTE_BLOCK_COW_BELL, - BLOCK_NOTE_BLOCK_DIDGERIDOO, - BLOCK_NOTE_BLOCK_FLUTE, - BLOCK_NOTE_BLOCK_GUITAR, - BLOCK_NOTE_BLOCK_HARP, - BLOCK_NOTE_BLOCK_HAT, - BLOCK_NOTE_BLOCK_IRON_XYLOPHONE, - BLOCK_NOTE_BLOCK_PLING, - BLOCK_NOTE_BLOCK_SNARE, - BLOCK_NOTE_BLOCK_XYLOPHONE, - BLOCK_PISTON_CONTRACT, - BLOCK_PISTON_EXTEND, - BLOCK_PORTAL_AMBIENT, - BLOCK_PORTAL_TRAVEL, - BLOCK_PORTAL_TRIGGER, - BLOCK_PUMPKIN_CARVE, - BLOCK_REDSTONE_TORCH_BURNOUT, - BLOCK_SAND_BREAK, - BLOCK_SAND_FALL, - BLOCK_SAND_HIT, - BLOCK_SAND_PLACE, - BLOCK_SAND_STEP, - BLOCK_SCAFFOLDING_BREAK, - BLOCK_SCAFFOLDING_FALL, - BLOCK_SCAFFOLDING_HIT, - BLOCK_SCAFFOLDING_PLACE, - BLOCK_SCAFFOLDING_STEP, - BLOCK_SHULKER_BOX_CLOSE, - BLOCK_SHULKER_BOX_OPEN, - BLOCK_SLIME_BLOCK_BREAK, - BLOCK_SLIME_BLOCK_FALL, - BLOCK_SLIME_BLOCK_HIT, - BLOCK_SLIME_BLOCK_PLACE, - BLOCK_SLIME_BLOCK_STEP, - BLOCK_SMOKER_SMOKE, - BLOCK_SNOW_BREAK, - BLOCK_SNOW_FALL, - BLOCK_SNOW_HIT, - BLOCK_SNOW_PLACE, - BLOCK_SNOW_STEP, - BLOCK_STONE_BREAK, - BLOCK_STONE_BUTTON_CLICK_OFF, - BLOCK_STONE_BUTTON_CLICK_ON, - BLOCK_STONE_FALL, - BLOCK_STONE_HIT, - BLOCK_STONE_PLACE, - BLOCK_STONE_PRESSURE_PLATE_CLICK_OFF, - BLOCK_STONE_PRESSURE_PLATE_CLICK_ON, - BLOCK_STONE_STEP, - BLOCK_SWEET_BERRY_BUSH_BREAK, - BLOCK_SWEET_BERRY_BUSH_PLACE, - BLOCK_TRIPWIRE_ATTACH, - BLOCK_TRIPWIRE_CLICK_OFF, - BLOCK_TRIPWIRE_CLICK_ON, - BLOCK_TRIPWIRE_DETACH, - BLOCK_WATER_AMBIENT, - BLOCK_WET_GRASS_BREAK, - BLOCK_WET_GRASS_FALL, - BLOCK_WET_GRASS_HIT, - BLOCK_WET_GRASS_PLACE, - BLOCK_WET_GRASS_STEP, - BLOCK_WOODEN_BUTTON_CLICK_OFF, - BLOCK_WOODEN_BUTTON_CLICK_ON, - BLOCK_WOODEN_DOOR_CLOSE, - BLOCK_WOODEN_DOOR_OPEN, - BLOCK_WOODEN_PRESSURE_PLATE_CLICK_OFF, - BLOCK_WOODEN_PRESSURE_PLATE_CLICK_ON, - BLOCK_WOODEN_TRAPDOOR_CLOSE, - BLOCK_WOODEN_TRAPDOOR_OPEN, - BLOCK_WOOD_BREAK, - BLOCK_WOOD_FALL, - BLOCK_WOOD_HIT, - BLOCK_WOOD_PLACE, - BLOCK_WOOD_STEP, - BLOCK_WOOL_BREAK, - BLOCK_WOOL_FALL, - BLOCK_WOOL_HIT, - BLOCK_WOOL_PLACE, - BLOCK_WOOL_STEP, - ENCHANT_THORNS_HIT, - ENTITY_ARMOR_STAND_BREAK, - ENTITY_ARMOR_STAND_FALL, - ENTITY_ARMOR_STAND_HIT, - ENTITY_ARMOR_STAND_PLACE, - ENTITY_ARROW_HIT, - ENTITY_ARROW_HIT_PLAYER, - ENTITY_ARROW_SHOOT, - ENTITY_BAT_AMBIENT, - ENTITY_BAT_DEATH, - ENTITY_BAT_HURT, - ENTITY_BAT_LOOP, - ENTITY_BAT_TAKEOFF, - ENTITY_BLAZE_AMBIENT, - ENTITY_BLAZE_BURN, - ENTITY_BLAZE_DEATH, - ENTITY_BLAZE_HURT, - ENTITY_BLAZE_SHOOT, - ENTITY_BOAT_PADDLE_LAND, - ENTITY_BOAT_PADDLE_WATER, - ENTITY_CAT_AMBIENT, - ENTITY_CAT_BEG_FOR_FOOD, - ENTITY_CAT_DEATH, - ENTITY_CAT_EAT, - ENTITY_CAT_HISS, - ENTITY_CAT_HURT, - ENTITY_CAT_PURR, - ENTITY_CAT_PURREOW, - ENTITY_CAT_STRAY_AMBIENT, - ENTITY_CHICKEN_AMBIENT, - ENTITY_CHICKEN_DEATH, - ENTITY_CHICKEN_EGG, - ENTITY_CHICKEN_HURT, - ENTITY_CHICKEN_STEP, - ENTITY_COD_AMBIENT, - ENTITY_COD_DEATH, - ENTITY_COD_FLOP, - ENTITY_COD_HURT, - ENTITY_COW_AMBIENT, - ENTITY_COW_DEATH, - ENTITY_COW_HURT, - ENTITY_COW_MILK, - ENTITY_COW_STEP, - ENTITY_CREEPER_DEATH, - ENTITY_CREEPER_HURT, - ENTITY_CREEPER_PRIMED, - ENTITY_DOLPHIN_AMBIENT, - ENTITY_DOLPHIN_AMBIENT_WATER, - ENTITY_DOLPHIN_ATTACK, - ENTITY_DOLPHIN_DEATH, - ENTITY_DOLPHIN_EAT, - ENTITY_DOLPHIN_HURT, - ENTITY_DOLPHIN_JUMP, - ENTITY_DOLPHIN_PLAY, - ENTITY_DOLPHIN_SPLASH, - ENTITY_DOLPHIN_SWIM, - ENTITY_DONKEY_AMBIENT, - ENTITY_DONKEY_ANGRY, - ENTITY_DONKEY_CHEST, - ENTITY_DONKEY_DEATH, - ENTITY_DONKEY_HURT, - ENTITY_DRAGON_FIREBALL_EXPLODE, - ENTITY_DROWNED_AMBIENT, - ENTITY_DROWNED_AMBIENT_WATER, - ENTITY_DROWNED_DEATH, - ENTITY_DROWNED_DEATH_WATER, - ENTITY_DROWNED_HURT, - ENTITY_DROWNED_HURT_WATER, - ENTITY_DROWNED_SHOOT, - ENTITY_DROWNED_STEP, - ENTITY_DROWNED_SWIM, - ENTITY_EGG_THROW, - ENTITY_ELDER_GUARDIAN_AMBIENT, - ENTITY_ELDER_GUARDIAN_AMBIENT_LAND, - ENTITY_ELDER_GUARDIAN_CURSE, - ENTITY_ELDER_GUARDIAN_DEATH, - ENTITY_ELDER_GUARDIAN_DEATH_LAND, - ENTITY_ELDER_GUARDIAN_FLOP, - ENTITY_ELDER_GUARDIAN_HURT, - ENTITY_ELDER_GUARDIAN_HURT_LAND, - ENTITY_ENDERMAN_AMBIENT, - ENTITY_ENDERMAN_DEATH, - ENTITY_ENDERMAN_HURT, - ENTITY_ENDERMAN_SCREAM, - ENTITY_ENDERMAN_STARE, - ENTITY_ENDERMAN_TELEPORT, - ENTITY_ENDERMITE_AMBIENT, - ENTITY_ENDERMITE_DEATH, - ENTITY_ENDERMITE_HURT, - ENTITY_ENDERMITE_STEP, - ENTITY_ENDER_DRAGON_AMBIENT, - ENTITY_ENDER_DRAGON_DEATH, - ENTITY_ENDER_DRAGON_FLAP, - ENTITY_ENDER_DRAGON_GROWL, - ENTITY_ENDER_DRAGON_HURT, - ENTITY_ENDER_DRAGON_SHOOT, - ENTITY_ENDER_EYE_DEATH, - ENTITY_ENDER_EYE_LAUNCH, - ENTITY_ENDER_PEARL_THROW, - ENTITY_EVOKER_AMBIENT, - ENTITY_EVOKER_CAST_SPELL, - ENTITY_EVOKER_CELEBRATE, - ENTITY_EVOKER_DEATH, - ENTITY_EVOKER_FANGS_ATTACK, - ENTITY_EVOKER_HURT, - ENTITY_EVOKER_PREPARE_ATTACK, - ENTITY_EVOKER_PREPARE_SUMMON, - ENTITY_EVOKER_PREPARE_WOLOLO, - ENTITY_EXPERIENCE_BOTTLE_THROW, - ENTITY_EXPERIENCE_ORB_PICKUP, - ENTITY_FIREWORK_ROCKET_BLAST, - ENTITY_FIREWORK_ROCKET_BLAST_FAR, - ENTITY_FIREWORK_ROCKET_LARGE_BLAST, - ENTITY_FIREWORK_ROCKET_LARGE_BLAST_FAR, - ENTITY_FIREWORK_ROCKET_LAUNCH, - ENTITY_FIREWORK_ROCKET_SHOOT, - ENTITY_FIREWORK_ROCKET_TWINKLE, - ENTITY_FIREWORK_ROCKET_TWINKLE_FAR, - ENTITY_FISHING_BOBBER_RETRIEVE, - ENTITY_FISHING_BOBBER_SPLASH, - ENTITY_FISHING_BOBBER_THROW, - ENTITY_FISH_SWIM, - ENTITY_FOX_AGGRO, - ENTITY_FOX_AMBIENT, - ENTITY_FOX_BITE, - ENTITY_FOX_DEATH, - ENTITY_FOX_EAT, - ENTITY_FOX_HURT, - ENTITY_FOX_SCREECH, - ENTITY_FOX_SLEEP, - ENTITY_FOX_SNIFF, - ENTITY_FOX_SPIT, - ENTITY_GENERIC_BIG_FALL, - ENTITY_GENERIC_BURN, - ENTITY_GENERIC_DEATH, - ENTITY_GENERIC_DRINK, - ENTITY_GENERIC_EAT, - ENTITY_GENERIC_EXPLODE, - ENTITY_GENERIC_EXTINGUISH_FIRE, - ENTITY_GENERIC_HURT, - ENTITY_GENERIC_SMALL_FALL, - ENTITY_GENERIC_SPLASH, - ENTITY_GENERIC_SWIM, - ENTITY_GHAST_AMBIENT, - ENTITY_GHAST_DEATH, - ENTITY_GHAST_HURT, - ENTITY_GHAST_SCREAM, - ENTITY_GHAST_SHOOT, - ENTITY_GHAST_WARN, - ENTITY_GUARDIAN_AMBIENT, - ENTITY_GUARDIAN_AMBIENT_LAND, - ENTITY_GUARDIAN_ATTACK, - ENTITY_GUARDIAN_DEATH, - ENTITY_GUARDIAN_DEATH_LAND, - ENTITY_GUARDIAN_FLOP, - ENTITY_GUARDIAN_HURT, - ENTITY_GUARDIAN_HURT_LAND, - ENTITY_HORSE_AMBIENT, - ENTITY_HORSE_ANGRY, - ENTITY_HORSE_ARMOR, - ENTITY_HORSE_BREATHE, - ENTITY_HORSE_DEATH, - ENTITY_HORSE_EAT, - ENTITY_HORSE_GALLOP, - ENTITY_HORSE_HURT, - ENTITY_HORSE_JUMP, - ENTITY_HORSE_LAND, - ENTITY_HORSE_SADDLE, - ENTITY_HORSE_STEP, - ENTITY_HORSE_STEP_WOOD, - ENTITY_HOSTILE_BIG_FALL, - ENTITY_HOSTILE_DEATH, - ENTITY_HOSTILE_HURT, - ENTITY_HOSTILE_SMALL_FALL, - ENTITY_HOSTILE_SPLASH, - ENTITY_HOSTILE_SWIM, - ENTITY_HUSK_AMBIENT, - ENTITY_HUSK_CONVERTED_TO_ZOMBIE, - ENTITY_HUSK_DEATH, - ENTITY_HUSK_HURT, - ENTITY_HUSK_STEP, - ENTITY_ILLUSIONER_AMBIENT, - ENTITY_ILLUSIONER_CAST_SPELL, - ENTITY_ILLUSIONER_DEATH, - ENTITY_ILLUSIONER_HURT, - ENTITY_ILLUSIONER_MIRROR_MOVE, - ENTITY_ILLUSIONER_PREPARE_BLINDNESS, - ENTITY_ILLUSIONER_PREPARE_MIRROR, - ENTITY_IRON_GOLEM_ATTACK, - ENTITY_IRON_GOLEM_DEATH, - ENTITY_IRON_GOLEM_HURT, - ENTITY_IRON_GOLEM_STEP, - ENTITY_ITEM_BREAK, - ENTITY_ITEM_FRAME_ADD_ITEM, - ENTITY_ITEM_FRAME_BREAK, - ENTITY_ITEM_FRAME_PLACE, - ENTITY_ITEM_FRAME_REMOVE_ITEM, - ENTITY_ITEM_FRAME_ROTATE_ITEM, - ENTITY_ITEM_PICKUP, - ENTITY_LEASH_KNOT_BREAK, - ENTITY_LEASH_KNOT_PLACE, - ENTITY_LIGHTNING_BOLT_IMPACT, - ENTITY_LIGHTNING_BOLT_THUNDER, - ENTITY_LINGERING_POTION_THROW, - ENTITY_LLAMA_AMBIENT, - ENTITY_LLAMA_ANGRY, - ENTITY_LLAMA_CHEST, - ENTITY_LLAMA_DEATH, - ENTITY_LLAMA_EAT, - ENTITY_LLAMA_HURT, - ENTITY_LLAMA_SPIT, - ENTITY_LLAMA_STEP, - ENTITY_LLAMA_SWAG, - ENTITY_MAGMA_CUBE_DEATH, - ENTITY_MAGMA_CUBE_DEATH_SMALL, - ENTITY_MAGMA_CUBE_HURT, - ENTITY_MAGMA_CUBE_HURT_SMALL, - ENTITY_MAGMA_CUBE_JUMP, - ENTITY_MAGMA_CUBE_SQUISH, - ENTITY_MAGMA_CUBE_SQUISH_SMALL, - ENTITY_MINECART_INSIDE, - ENTITY_MINECART_RIDING, - ENTITY_MOOSHROOM_CONVERT, - ENTITY_MOOSHROOM_EAT, - ENTITY_MOOSHROOM_MILK, - ENTITY_MOOSHROOM_SHEAR, - ENTITY_MOOSHROOM_SUSPICIOUS_MILK, - ENTITY_MULE_AMBIENT, - ENTITY_MULE_CHEST, - ENTITY_MULE_DEATH, - ENTITY_MULE_HURT, - ENTITY_OCELOT_AMBIENT, - ENTITY_OCELOT_DEATH, - ENTITY_OCELOT_HURT, - ENTITY_PAINTING_BREAK, - ENTITY_PAINTING_PLACE, - ENTITY_PANDA_AGGRESSIVE_AMBIENT, - ENTITY_PANDA_AMBIENT, - ENTITY_PANDA_BITE, - ENTITY_PANDA_CANT_BREED, - ENTITY_PANDA_DEATH, - ENTITY_PANDA_EAT, - ENTITY_PANDA_HURT, - ENTITY_PANDA_PRE_SNEEZE, - ENTITY_PANDA_SNEEZE, - ENTITY_PANDA_STEP, - ENTITY_PANDA_WORRIED_AMBIENT, - ENTITY_PARROT_AMBIENT, - ENTITY_PARROT_DEATH, - ENTITY_PARROT_EAT, - ENTITY_PARROT_FLY, - ENTITY_PARROT_HURT, - ENTITY_PARROT_IMITATE_BLAZE, - ENTITY_PARROT_IMITATE_CREEPER, - ENTITY_PARROT_IMITATE_DROWNED, - ENTITY_PARROT_IMITATE_ELDER_GUARDIAN, - ENTITY_PARROT_IMITATE_ENDERMAN, - ENTITY_PARROT_IMITATE_ENDERMITE, - ENTITY_PARROT_IMITATE_ENDER_DRAGON, - ENTITY_PARROT_IMITATE_EVOKER, - ENTITY_PARROT_IMITATE_GHAST, - ENTITY_PARROT_IMITATE_GUARDIAN, - ENTITY_PARROT_IMITATE_HUSK, - ENTITY_PARROT_IMITATE_ILLUSIONER, - ENTITY_PARROT_IMITATE_MAGMA_CUBE, - ENTITY_PARROT_IMITATE_PANDA, - ENTITY_PARROT_IMITATE_PHANTOM, - ENTITY_PARROT_IMITATE_PILLAGER, - ENTITY_PARROT_IMITATE_POLAR_BEAR, - ENTITY_PARROT_IMITATE_RAVAGER, - ENTITY_PARROT_IMITATE_SHULKER, - ENTITY_PARROT_IMITATE_SILVERFISH, - ENTITY_PARROT_IMITATE_SKELETON, - ENTITY_PARROT_IMITATE_SLIME, - ENTITY_PARROT_IMITATE_SPIDER, - ENTITY_PARROT_IMITATE_STRAY, - ENTITY_PARROT_IMITATE_VEX, - ENTITY_PARROT_IMITATE_VINDICATOR, - ENTITY_PARROT_IMITATE_WITCH, - ENTITY_PARROT_IMITATE_WITHER, - ENTITY_PARROT_IMITATE_WITHER_SKELETON, - ENTITY_PARROT_IMITATE_WOLF, - ENTITY_PARROT_IMITATE_ZOMBIE, - ENTITY_PARROT_IMITATE_ZOMBIE_PIGMAN, - ENTITY_PARROT_IMITATE_ZOMBIE_VILLAGER, - ENTITY_PARROT_STEP, - ENTITY_PHANTOM_AMBIENT, - ENTITY_PHANTOM_BITE, - ENTITY_PHANTOM_DEATH, - ENTITY_PHANTOM_FLAP, - ENTITY_PHANTOM_HURT, - ENTITY_PHANTOM_SWOOP, - ENTITY_PIG_AMBIENT, - ENTITY_PIG_DEATH, - ENTITY_PIG_HURT, - ENTITY_PIG_SADDLE, - ENTITY_PIG_STEP, - ENTITY_PILLAGER_AMBIENT, - ENTITY_PILLAGER_CELEBRATE, - ENTITY_PILLAGER_DEATH, - ENTITY_PILLAGER_HURT, - ENTITY_PLAYER_ATTACK_CRIT, - ENTITY_PLAYER_ATTACK_KNOCKBACK, - ENTITY_PLAYER_ATTACK_NODAMAGE, - ENTITY_PLAYER_ATTACK_STRONG, - ENTITY_PLAYER_ATTACK_SWEEP, - ENTITY_PLAYER_ATTACK_WEAK, - ENTITY_PLAYER_BIG_FALL, - ENTITY_PLAYER_BREATH, - ENTITY_PLAYER_BURP, - ENTITY_PLAYER_DEATH, - ENTITY_PLAYER_HURT, - ENTITY_PLAYER_HURT_DROWN, - ENTITY_PLAYER_HURT_ON_FIRE, - ENTITY_PLAYER_HURT_SWEET_BERRY_BUSH, - ENTITY_PLAYER_LEVELUP, - ENTITY_PLAYER_SMALL_FALL, - ENTITY_PLAYER_SPLASH, - ENTITY_PLAYER_SPLASH_HIGH_SPEED, - ENTITY_PLAYER_SWIM, - ENTITY_POLAR_BEAR_AMBIENT, - ENTITY_POLAR_BEAR_AMBIENT_BABY, - ENTITY_POLAR_BEAR_DEATH, - ENTITY_POLAR_BEAR_HURT, - ENTITY_POLAR_BEAR_STEP, - ENTITY_POLAR_BEAR_WARNING, - ENTITY_PUFFER_FISH_AMBIENT, - ENTITY_PUFFER_FISH_BLOW_OUT, - ENTITY_PUFFER_FISH_BLOW_UP, - ENTITY_PUFFER_FISH_DEATH, - ENTITY_PUFFER_FISH_FLOP, - ENTITY_PUFFER_FISH_HURT, - ENTITY_PUFFER_FISH_STING, - ENTITY_RABBIT_AMBIENT, - ENTITY_RABBIT_ATTACK, - ENTITY_RABBIT_DEATH, - ENTITY_RABBIT_HURT, - ENTITY_RABBIT_JUMP, - ENTITY_RAVAGER_AMBIENT, - ENTITY_RAVAGER_ATTACK, - ENTITY_RAVAGER_CELEBRATE, - ENTITY_RAVAGER_DEATH, - ENTITY_RAVAGER_HURT, - ENTITY_RAVAGER_ROAR, - ENTITY_RAVAGER_STEP, - ENTITY_RAVAGER_STUNNED, - ENTITY_SALMON_AMBIENT, - ENTITY_SALMON_DEATH, - ENTITY_SALMON_FLOP, - ENTITY_SALMON_HURT, - ENTITY_SHEEP_AMBIENT, - ENTITY_SHEEP_DEATH, - ENTITY_SHEEP_HURT, - ENTITY_SHEEP_SHEAR, - ENTITY_SHEEP_STEP, - ENTITY_SHULKER_AMBIENT, - ENTITY_SHULKER_BULLET_HIT, - ENTITY_SHULKER_BULLET_HURT, - ENTITY_SHULKER_CLOSE, - ENTITY_SHULKER_DEATH, - ENTITY_SHULKER_HURT, - ENTITY_SHULKER_HURT_CLOSED, - ENTITY_SHULKER_OPEN, - ENTITY_SHULKER_SHOOT, - ENTITY_SHULKER_TELEPORT, - ENTITY_SILVERFISH_AMBIENT, - ENTITY_SILVERFISH_DEATH, - ENTITY_SILVERFISH_HURT, - ENTITY_SILVERFISH_STEP, - ENTITY_SKELETON_AMBIENT, - ENTITY_SKELETON_DEATH, - ENTITY_SKELETON_HORSE_AMBIENT, - ENTITY_SKELETON_HORSE_AMBIENT_WATER, - ENTITY_SKELETON_HORSE_DEATH, - ENTITY_SKELETON_HORSE_GALLOP_WATER, - ENTITY_SKELETON_HORSE_HURT, - ENTITY_SKELETON_HORSE_JUMP_WATER, - ENTITY_SKELETON_HORSE_STEP_WATER, - ENTITY_SKELETON_HORSE_SWIM, - ENTITY_SKELETON_HURT, - ENTITY_SKELETON_SHOOT, - ENTITY_SKELETON_STEP, - ENTITY_SLIME_ATTACK, - ENTITY_SLIME_DEATH, - ENTITY_SLIME_DEATH_SMALL, - ENTITY_SLIME_HURT, - ENTITY_SLIME_HURT_SMALL, - ENTITY_SLIME_JUMP, - ENTITY_SLIME_JUMP_SMALL, - ENTITY_SLIME_SQUISH, - ENTITY_SLIME_SQUISH_SMALL, - ENTITY_SNOWBALL_THROW, - ENTITY_SNOW_GOLEM_AMBIENT, - ENTITY_SNOW_GOLEM_DEATH, - ENTITY_SNOW_GOLEM_HURT, - ENTITY_SNOW_GOLEM_SHOOT, - ENTITY_SPIDER_AMBIENT, - ENTITY_SPIDER_DEATH, - ENTITY_SPIDER_HURT, - ENTITY_SPIDER_STEP, - ENTITY_SPLASH_POTION_BREAK, - ENTITY_SPLASH_POTION_THROW, - ENTITY_SQUID_AMBIENT, - ENTITY_SQUID_DEATH, - ENTITY_SQUID_HURT, - ENTITY_SQUID_SQUIRT, - ENTITY_STRAY_AMBIENT, - ENTITY_STRAY_DEATH, - ENTITY_STRAY_HURT, - ENTITY_STRAY_STEP, - ENTITY_TNT_PRIMED, - ENTITY_TROPICAL_FISH_AMBIENT, - ENTITY_TROPICAL_FISH_DEATH, - ENTITY_TROPICAL_FISH_FLOP, - ENTITY_TROPICAL_FISH_HURT, - ENTITY_TURTLE_AMBIENT_LAND, - ENTITY_TURTLE_DEATH, - ENTITY_TURTLE_DEATH_BABY, - ENTITY_TURTLE_EGG_BREAK, - ENTITY_TURTLE_EGG_CRACK, - ENTITY_TURTLE_EGG_HATCH, - ENTITY_TURTLE_HURT, - ENTITY_TURTLE_HURT_BABY, - ENTITY_TURTLE_LAY_EGG, - ENTITY_TURTLE_SHAMBLE, - ENTITY_TURTLE_SHAMBLE_BABY, - ENTITY_TURTLE_SWIM, - ENTITY_VEX_AMBIENT, - ENTITY_VEX_CHARGE, - ENTITY_VEX_DEATH, - ENTITY_VEX_HURT, - ENTITY_VILLAGER_AMBIENT, - ENTITY_VILLAGER_CELEBRATE, - ENTITY_VILLAGER_DEATH, - ENTITY_VILLAGER_HURT, - ENTITY_VILLAGER_NO, - ENTITY_VILLAGER_TRADE, - ENTITY_VILLAGER_WORK_ARMORER, - ENTITY_VILLAGER_WORK_BUTCHER, - ENTITY_VILLAGER_WORK_CARTOGRAPHER, - ENTITY_VILLAGER_WORK_CLERIC, - ENTITY_VILLAGER_WORK_FARMER, - ENTITY_VILLAGER_WORK_FISHERMAN, - ENTITY_VILLAGER_WORK_FLETCHER, - ENTITY_VILLAGER_WORK_LEATHERWORKER, - ENTITY_VILLAGER_WORK_LIBRARIAN, - ENTITY_VILLAGER_WORK_MASON, - ENTITY_VILLAGER_WORK_SHEPHERD, - ENTITY_VILLAGER_WORK_TOOLSMITH, - ENTITY_VILLAGER_WORK_WEAPONSMITH, - ENTITY_VILLAGER_YES, - ENTITY_VINDICATOR_AMBIENT, - ENTITY_VINDICATOR_CELEBRATE, - ENTITY_VINDICATOR_DEATH, - ENTITY_VINDICATOR_HURT, - ENTITY_WANDERING_TRADER_AMBIENT, - ENTITY_WANDERING_TRADER_DEATH, - ENTITY_WANDERING_TRADER_DISAPPEARED, - ENTITY_WANDERING_TRADER_DRINK_MILK, - ENTITY_WANDERING_TRADER_DRINK_POTION, - ENTITY_WANDERING_TRADER_HURT, - ENTITY_WANDERING_TRADER_NO, - ENTITY_WANDERING_TRADER_REAPPEARED, - ENTITY_WANDERING_TRADER_TRADE, - ENTITY_WANDERING_TRADER_YES, - ENTITY_WITCH_AMBIENT, - ENTITY_WITCH_CELEBRATE, - ENTITY_WITCH_DEATH, - ENTITY_WITCH_DRINK, - ENTITY_WITCH_HURT, - ENTITY_WITCH_THROW, - ENTITY_WITHER_AMBIENT, - ENTITY_WITHER_BREAK_BLOCK, - ENTITY_WITHER_DEATH, - ENTITY_WITHER_HURT, - ENTITY_WITHER_SHOOT, - ENTITY_WITHER_SKELETON_AMBIENT, - ENTITY_WITHER_SKELETON_DEATH, - ENTITY_WITHER_SKELETON_HURT, - ENTITY_WITHER_SKELETON_STEP, - ENTITY_WITHER_SPAWN, - ENTITY_WOLF_AMBIENT, - ENTITY_WOLF_DEATH, - ENTITY_WOLF_GROWL, - ENTITY_WOLF_HOWL, - ENTITY_WOLF_HURT, - ENTITY_WOLF_PANT, - ENTITY_WOLF_SHAKE, - ENTITY_WOLF_STEP, - ENTITY_WOLF_WHINE, - ENTITY_ZOMBIE_AMBIENT, - ENTITY_ZOMBIE_ATTACK_IRON_DOOR, - ENTITY_ZOMBIE_ATTACK_WOODEN_DOOR, - ENTITY_ZOMBIE_BREAK_WOODEN_DOOR, - ENTITY_ZOMBIE_CONVERTED_TO_DROWNED, - ENTITY_ZOMBIE_DEATH, - ENTITY_ZOMBIE_DESTROY_EGG, - ENTITY_ZOMBIE_HORSE_AMBIENT, - ENTITY_ZOMBIE_HORSE_DEATH, - ENTITY_ZOMBIE_HORSE_HURT, - ENTITY_ZOMBIE_HURT, - ENTITY_ZOMBIE_INFECT, - ENTITY_ZOMBIE_PIGMAN_AMBIENT, - ENTITY_ZOMBIE_PIGMAN_ANGRY, - ENTITY_ZOMBIE_PIGMAN_DEATH, - ENTITY_ZOMBIE_PIGMAN_HURT, - ENTITY_ZOMBIE_STEP, - ENTITY_ZOMBIE_VILLAGER_AMBIENT, - ENTITY_ZOMBIE_VILLAGER_CONVERTED, - ENTITY_ZOMBIE_VILLAGER_CURE, - ENTITY_ZOMBIE_VILLAGER_DEATH, - ENTITY_ZOMBIE_VILLAGER_HURT, - ENTITY_ZOMBIE_VILLAGER_STEP, - EVENT_RAID_HORN, - ITEM_ARMOR_EQUIP_CHAIN, - ITEM_ARMOR_EQUIP_DIAMOND, - ITEM_ARMOR_EQUIP_ELYTRA, - ITEM_ARMOR_EQUIP_GENERIC, - ITEM_ARMOR_EQUIP_GOLD, - ITEM_ARMOR_EQUIP_IRON, - ITEM_ARMOR_EQUIP_LEATHER, - ITEM_ARMOR_EQUIP_TURTLE, - ITEM_AXE_STRIP, - ITEM_BOOK_PAGE_TURN, - ITEM_BOOK_PUT, - ITEM_BOTTLE_EMPTY, - ITEM_BOTTLE_FILL, - ITEM_BOTTLE_FILL_DRAGONBREATH, - ITEM_BUCKET_EMPTY, - ITEM_BUCKET_EMPTY_FISH, - ITEM_BUCKET_EMPTY_LAVA, - ITEM_BUCKET_FILL, - ITEM_BUCKET_FILL_FISH, - ITEM_BUCKET_FILL_LAVA, - ITEM_CHORUS_FRUIT_TELEPORT, - ITEM_CROP_PLANT, - ITEM_CROSSBOW_HIT, - ITEM_CROSSBOW_LOADING_END, - ITEM_CROSSBOW_LOADING_MIDDLE, - ITEM_CROSSBOW_LOADING_START, - ITEM_CROSSBOW_QUICK_CHARGE_1, - ITEM_CROSSBOW_QUICK_CHARGE_2, - ITEM_CROSSBOW_QUICK_CHARGE_3, - ITEM_CROSSBOW_SHOOT, - ITEM_ELYTRA_FLYING, - ITEM_FIRECHARGE_USE, - ITEM_FLINTANDSTEEL_USE, - ITEM_HOE_TILL, - ITEM_NETHER_WART_PLANT, - ITEM_SHIELD_BLOCK, - ITEM_SHIELD_BREAK, - ITEM_SHOVEL_FLATTEN, - ITEM_SWEET_BERRIES_PICK_FROM_BUSH, - ITEM_TOTEM_USE, - ITEM_TRIDENT_HIT, - ITEM_TRIDENT_HIT_GROUND, - ITEM_TRIDENT_RETURN, - ITEM_TRIDENT_RIPTIDE_1, - ITEM_TRIDENT_RIPTIDE_2, - ITEM_TRIDENT_RIPTIDE_3, - ITEM_TRIDENT_THROW, - ITEM_TRIDENT_THUNDER, - MUSIC_CREATIVE, - MUSIC_CREDITS, - MUSIC_DISC_11, - MUSIC_DISC_13, - MUSIC_DISC_BLOCKS, - MUSIC_DISC_CAT, - MUSIC_DISC_CHIRP, - MUSIC_DISC_FAR, - MUSIC_DISC_MALL, - MUSIC_DISC_MELLOHI, - MUSIC_DISC_STAL, - MUSIC_DISC_STRAD, - MUSIC_DISC_WAIT, - MUSIC_DISC_WARD, - MUSIC_DRAGON, - MUSIC_END, - MUSIC_GAME, - MUSIC_MENU, - MUSIC_NETHER, - MUSIC_UNDER_WATER, - UI_BUTTON_CLICK, - UI_CARTOGRAPHY_TABLE_TAKE_RESULT, - UI_LOOM_SELECT_PATTERN, - UI_LOOM_TAKE_RESULT, - UI_STONECUTTER_SELECT_RECIPE, - UI_STONECUTTER_TAKE_RESULT, - UI_TOAST_CHALLENGE_COMPLETE, - UI_TOAST_IN, - UI_TOAST_OUT, - WEATHER_RAIN, - WEATHER_RAIN_ABOVE, -} diff --git a/api/src/main/java/org/bukkit/SoundCategory.java b/api/src/main/java/org/bukkit/SoundCategory.java deleted file mode 100644 index ac5e263d7..000000000 --- a/api/src/main/java/org/bukkit/SoundCategory.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit; - -/** - * An Enum of categories for sounds. - */ -public enum SoundCategory { - - MASTER, - MUSIC, - RECORDS, - WEATHER, - BLOCKS, - HOSTILE, - NEUTRAL, - PLAYERS, - AMBIENT, - VOICE; -} diff --git a/api/src/main/java/org/bukkit/Statistic.java b/api/src/main/java/org/bukkit/Statistic.java deleted file mode 100644 index c54c00128..000000000 --- a/api/src/main/java/org/bukkit/Statistic.java +++ /dev/null @@ -1,171 +0,0 @@ -package org.bukkit; - -import java.util.Locale; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a countable statistic, which is tracked by the server. - */ -public enum Statistic implements Keyed { - DAMAGE_DEALT, - DAMAGE_TAKEN, - DEATHS, - MOB_KILLS, - PLAYER_KILLS, - FISH_CAUGHT, - ANIMALS_BRED, - LEAVE_GAME, - JUMP, - DROP_COUNT, - DROP(Type.ITEM), - PICKUP(Type.ITEM), - /** - * Name is misleading, actually records ticks played. - */ - PLAY_ONE_MINUTE, - WALK_ONE_CM, - WALK_ON_WATER_ONE_CM, - FALL_ONE_CM, - SNEAK_TIME, - CLIMB_ONE_CM, - FLY_ONE_CM, - WALK_UNDER_WATER_ONE_CM, - MINECART_ONE_CM, - BOAT_ONE_CM, - PIG_ONE_CM, - HORSE_ONE_CM, - SPRINT_ONE_CM, - CROUCH_ONE_CM, - AVIATE_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, - SLEEP_IN_BED, - SHULKER_BOX_OPENED, - TIME_SINCE_REST, - SWIM_ONE_CM, - DAMAGE_DEALT_ABSORBED, - DAMAGE_DEALT_RESISTED, - DAMAGE_BLOCKED_BY_SHIELD, - DAMAGE_ABSORBED, - DAMAGE_RESISTED, - CLEAN_SHULKER_BOX, - OPEN_BARREL, - INTERACT_WITH_BLAST_FURNACE, - INTERACT_WITH_SMOKER, - INTERACT_WITH_LECTERN, - INTERACT_WITH_CAMPFIRE, - INTERACT_WITH_CARTOGRAPHY_TABLE, - INTERACT_WITH_LOOM, - INTERACT_WITH_STONECUTTER, - BELL_RING, - RAID_TRIGGER, - RAID_WIN; - - private final Type type; - private final NamespacedKey key; - - private Statistic() { - this(Type.UNTYPED); - } - - private Statistic(/*@NotNull*/ Type type) { - this.type = type; - this.key = NamespacedKey.minecraft(name().toLowerCase(Locale.ROOT)); - } - - /** - * Gets the type of this statistic. - * - * @return the type of this statistic - */ - @NotNull - 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; - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - - /** - * 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/api/src/main/java/org/bukkit/StructureType.java b/api/src/main/java/org/bukkit/StructureType.java deleted file mode 100644 index e062c90ea..000000000 --- a/api/src/main/java/org/bukkit/StructureType.java +++ /dev/null @@ -1,232 +0,0 @@ -package org.bukkit; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import org.apache.commons.lang.Validate; -import org.bukkit.map.MapCursor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * This class handles the creation and storage of all structure types for - * Bukkit. Structure Types are the different kinds of structures that can be - * generated during world/chunk generation. These include Villages, Mineshafts, - * Mansions, etc. - *
- * The registration of new {@link StructureType}s is case-sensitive. - */ -// Order is retrieved from WorldGenFactory -public final class StructureType { - - private static final Map structureTypeMap = new HashMap<>(); - - /** - * Mineshafts are underground structures which consist of branching mining - * tunnels with wooden supports and broken rails. - *
- * They are the only place where cave spider spawners and minecarts with - * chests can be found naturally. - */ - public static final StructureType MINESHAFT = register(new StructureType("mineshaft", MapCursor.Type.RED_X)); - - /** - * Villages are naturally generating structures that form above ground. - *
- * They are usually generated in desert, plains, taiga, and savanna biomes - * and are a site for villager spawns, with whom the player can trade. - */ - public static final StructureType VILLAGE = register(new StructureType("village", MapCursor.Type.MANSION)); - - /** - * Nether fortresses are very large complexes that mainly consist of - * netherbricks. - *
- * They contain blaze spawners, nether wart farms, and loot chests. They are - * only generated in the nether dimension. - */ - public static final StructureType NETHER_FORTRESS = register(new StructureType("fortress", MapCursor.Type.RED_X)); - - /** - * Strongholds are underground structures that consist of many rooms, - * libraries, and an end portal room. - *
- * They can be found using an {@link Material#ENDER_EYE}. - */ - public static final StructureType STRONGHOLD = register(new StructureType("stronghold", MapCursor.Type.MANSION)); - - /** - * Jungle pyramids (also known as jungle temples) are found in jungles. - *
- * They are usually composed of cobblestone and mossy cobblestone. They - * consist of three floors, with the bottom floor containing treasure - * chests. - */ - public static final StructureType JUNGLE_PYRAMID = register(new StructureType("jungle_pyramid", MapCursor.Type.RED_X)); - - /** - * Ocean ruins are clusters of many different blocks that generate - * underwater in ocean biomes (as well as on the surface of beaches). - *
- * They come in my different variations. The cold variants consist primarily - * of stone brick, and the warm variants consist of sandstone. - */ - public static final StructureType OCEAN_RUIN = register(new StructureType("ocean_ruin", MapCursor.Type.TEMPLE)); - - /** - * Desert pyramids (also known as desert temples) are found in deserts. - *
- * They are usually composed of sandstone and stained terracotta. - */ - public static final StructureType DESERT_PYRAMID = register(new StructureType("desert_pyramid", MapCursor.Type.RED_X)); - - /** - * Igloos are structures that generate in snowy biomes. - *
- * They consist of the house, as well as a basement. - */ - public static final StructureType IGLOO = register(new StructureType("igloo", MapCursor.Type.RED_X)); - - /** - * Swamp huts (also known as witch huts) generate in swamp biomes and have - * the ability to spawn witches. - */ - public static final StructureType SWAMP_HUT = register(new StructureType("swamp_hut", MapCursor.Type.RED_X)); - - /** - * Ocean monuments are underwater structures. - *
- * They are usually composed on all three different prismarine types and sea - * lanterns. They are the only place guardians and elder guardians spawn - * naturally. - */ - public static final StructureType OCEAN_MONUMENT = register(new StructureType("monument", MapCursor.Type.TEMPLE)); - - /** - * End Cities are tall castle-like structures that generate in the outer - * island of the End dimension. - *
- * They consist primarily of end stone bricks, purpur blocks, and end rods. - * They are the only place where shulkers can be found. - */ - public static final StructureType END_CITY = register(new StructureType("endcity", MapCursor.Type.RED_X)); - - /** - * Mansions (also known as woodland mansions) are massive house structures - * that generate in dark forests, containing a wide variety of rooms. - *
- * They are the only place where evokers, vindicators, and vexes spawn - * naturally (but only once) - */ - public static final StructureType WOODLAND_MANSION = register(new StructureType("mansion", MapCursor.Type.MANSION)); - - /** - * Buried treasure consists of a single chest buried in the beach sand or - * gravel, with random loot in it. - */ - public static final StructureType BURIED_TREASURE = register(new StructureType("buried_treasure", MapCursor.Type.RED_X)); - - /** - * Shipwrecks are structures that generate on the floor of oceans or - * beaches. - *
- * They are made up of wood materials, and contain 1-3 loot chests. They can - * generate sideways, upside-down, or upright. - */ - public static final StructureType SHIPWRECK = register(new StructureType("shipwreck", MapCursor.Type.RED_X)); - - /** - * Pillager outposts may contain crossbows. - */ - public static final StructureType PILLAGER_OUTPOST = register(new StructureType("pillager_outpost", MapCursor.Type.RED_X)); - - /* **************** - * STRUCTURE TYPES REGISTERED ABOVE THIS - * **************** - */ - private final String name; - private final MapCursor.Type mapCursor; - - /** - * Create a new StructureType with a given name and map cursor. To indicate - * this structure should not be compatible with explorer maps, use null for - * mapIcon. - * - * @param name the name of the structure, case-sensitive - * @param mapIcon the {@link org.bukkit.map.MapCursor.Type} this structure type should use - * when creating explorer maps. Use null to indicate this structure should - * not be compatible with explorer maps. - */ - private StructureType(@NotNull String name, @Nullable MapCursor.Type mapIcon) { - Validate.notEmpty(name, "Structure name cannot be empty"); - this.name = name; - this.mapCursor = mapIcon; - } - - /** - * Get the name of this structure. This is case-sensitive when used in - * commands. - * - * @return the name of this structure - */ - @NotNull - public String getName() { - return name; - } - - /** - * Get the {@link org.bukkit.map.MapCursor.Type} that this structure can use on maps. If - * this is null, this structure will not appear on explorer maps. - * - * @return the {@link org.bukkit.map.MapCursor.Type} or null. - */ - @Nullable - public MapCursor.Type getMapIcon() { - return mapCursor; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof StructureType)) { - return false; - } - StructureType that = (StructureType) other; - return this.name.equals(that.name) && this.mapCursor == that.mapCursor; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 71 * hash + Objects.hashCode(this.name); - hash = 71 * hash + Objects.hashCode(this.mapCursor); - return hash; - } - - @Override - public String toString() { - return "StructureType{name=" + this.name + ", cursor=" + this.mapCursor + "}"; - } - - @NotNull - private static T register(@NotNull T type) { - Preconditions.checkNotNull(type, "Cannot register null StructureType."); - Preconditions.checkArgument(!structureTypeMap.containsKey(type.getName()), "Cannot register same StructureType twice. %s", type.getName()); - StructureType.structureTypeMap.put(type.getName(), type); - return type; - } - - /** - * Get all registered {@link StructureType}s. - * - * @return an immutable copy of registered structure types. - */ - @NotNull - public static Map getStructureTypes() { - return ImmutableMap.copyOf(structureTypeMap); - } -} diff --git a/api/src/main/java/org/bukkit/Tag.java b/api/src/main/java/org/bukkit/Tag.java deleted file mode 100644 index 1d9021b0b..000000000 --- a/api/src/main/java/org/bukkit/Tag.java +++ /dev/null @@ -1,262 +0,0 @@ -package org.bukkit; - -import java.util.Set; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a tag that may be defined by the server or a resource pack to - * group like things together. - * - * Note that whilst all tags defined within this interface must be present in - * implementations, their existence is not guaranteed across future versions. - * - * @param the type of things grouped by this tag - */ -public interface Tag extends Keyed { - - /** - * Key for the built in block registry. - */ - String REGISTRY_BLOCKS = "blocks"; - /** - * Vanilla block tag representing all colors of wool. - */ - Tag WOOL = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wool"), Material.class); - /** - * Vanilla block tag representing all plank variants. - */ - Tag PLANKS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("planks"), Material.class); - /** - * Vanilla block tag representing all regular/mossy/cracked/chiseled stone - * bricks. - */ - Tag STONE_BRICKS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("stone_bricks"), Material.class); - /** - * Vanilla block tag representing all wooden buttons. - */ - Tag WOODEN_BUTTONS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wooden_buttons"), Material.class); - /** - * Vanilla block tag representing all buttons (inherits from - * {@link #WOODEN_BUTTONS}. - */ - Tag BUTTONS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("buttons"), Material.class); - /** - * Vanilla block tag representing all colors of carpet. - */ - Tag CARPETS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("carpets"), Material.class); - /** - * Vanilla block tag representing all wooden doors. - */ - Tag WOODEN_DOORS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wooden_doors"), Material.class); - /** - * Vanilla block tag representing all wooden stairs. - */ - Tag WOODEN_STAIRS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wooden_stairs"), Material.class); - /** - * Vanilla block tag representing all wooden slabs. - */ - Tag WOODEN_SLABS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wooden_slabs"), Material.class); - /** - * Vanilla block tag representing all wooden fences. - */ - Tag WOODEN_FENCES = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wooden_fences"), Material.class); - /** - * Vanilla block tag representing all wooden pressure plates. - */ - Tag WOODEN_PRESSURE_PLATES = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wooden_pressure_plates"), Material.class); - /** - * Vanilla block tag representing all wooden trapdoors. - */ - Tag WOODEN_TRAPDOORS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wooden_trapdoors"), Material.class); - /** - * Vanilla block tag representing all doors (inherits from - * {@link #WOODEN_DOORS}. - */ - Tag DOORS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("doors"), Material.class); - /** - * Vanilla block tag representing all sapling variants. - */ - Tag SAPLINGS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("saplings"), Material.class); - /** - * Vanilla block tag representing all log and bark variants. - */ - Tag LOGS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("logs"), Material.class); - /** - * Vanilla block tag representing all dark oak log and bark variants. - */ - Tag DARK_OAK_LOGS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("dark_oak_logs"), Material.class); - /** - * Vanilla block tag representing all oak log and bark variants. - */ - Tag OAK_LOGS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("oak_logs"), Material.class); - /** - * Vanilla block tag representing all birch log and bark variants. - */ - Tag BIRCH_LOGS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("birch_logs"), Material.class); - /** - * Vanilla block tag representing all acacia log and bark variants. - */ - Tag ACACIA_LOGS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("acacia_logs"), Material.class); - /** - * Vanilla block tag representing all jungle log and bark variants. - */ - Tag JUNGLE_LOGS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("jungle_logs"), Material.class); - /** - * Vanilla block tag representing all spruce log and bark variants. - */ - Tag SPRUCE_LOGS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("spruce_logs"), Material.class); - /** - * Vanilla block tag representing all banner blocks. - */ - Tag BANNERS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("banners"), Material.class); - /** - * Vanilla block tag representing all sand blocks. - */ - Tag SAND = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("sand"), Material.class); - /** - * Vanilla block tag representing all stairs. - */ - Tag STAIRS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("stairs"), Material.class); - /** - * Vanilla block tag representing all slabs. - */ - Tag SLABS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("slabs"), Material.class); - /** - * Vanilla block tag representing all walls. - */ - Tag WALLS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("walls"), Material.class); - /** - * Vanilla block tag representing all damaged and undamaged anvils. - */ - Tag ANVIL = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("anvil"), Material.class); - /** - * Vanilla block tag representing all Minecart rails. - */ - Tag RAILS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("rails"), Material.class); - /** - * Vanilla block tag representing all leaves fans. - */ - Tag LEAVES = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("leaves"), Material.class); - /** - * Vanilla block tag representing all trapdoors (inherits from - * {@link #WOODEN_TRAPDOORS}. - */ - Tag TRAPDOORS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("trapdoors"), Material.class); - /** - * Vanilla block tag representing all empty and filled flower pots. - */ - Tag FLOWER_POTS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("flower_pots"), Material.class); - /** - * Vanilla block tag representing all small flowers. - */ - Tag SMALL_FLOWERS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("small_flowers"), Material.class); - /** - * Vanilla block tag representing all beds. - */ - Tag BEDS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("beds"), Material.class); - /** - * Vanilla block tag representing all fences. - */ - Tag FENCES = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("fences"), Material.class); - /** - * Vanilla block tag denoting blocks that enderman may pick up and hold. - */ - Tag ENDERMAN_HOLDABLE = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("enderman_holdable"), Material.class); - /** - * Vanilla block tag denoting ice blocks. - */ - Tag ICE = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("ice"), Material.class); - /** - * Vanilla block tag denoting all valid mob spawn positions. - */ - Tag VALID_SPAWN = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("valid_spawn"), Material.class); - /** - * Vanilla block tag denoting impermeable blocks which do not drip fluids. - */ - Tag IMPERMEABLE = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("impermeable"), Material.class); - /** - * Vanilla block tag denoting all underwater blocks which may be bonemealed. - */ - Tag UNDERWATER_BONEMEALS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("underwater_bonemeals"), Material.class); - /** - * Vanilla block tag representing all coral blocks. - */ - Tag CORAL_BLOCKS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("coral_blocks"), Material.class); - /** - * Vanilla block tag representing all wall corals. - */ - Tag WALL_CORALS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wall_corals"), Material.class); - /** - * Vanilla block tag representing all coral plants. - */ - Tag CORAL_PLANTS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("coral_plants"), Material.class); - /** - * Vanilla block tag representing all coral. - */ - Tag CORALS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("corals"), Material.class); - /** - * Vanilla block tag denoting all blocks bamboo may be planted on. - */ - Tag BAMBOO_PLANTABLE_ON = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("bamboo_plantable_on"), Material.class); - /** - * Vanilla block tag denoting dirt like blocks. - */ - Tag DIRT_LIKE = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("dirt_like"), Material.class); - /** - * Vanilla block tag representing all standing signs. - */ - Tag STANDING_SIGNS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("standing_signs"), Material.class); - /** - * Vanilla block tag representing all wall signs. - */ - Tag WALL_SIGNS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("wall_signs"), Material.class); - /** - * Vanilla block tag representing all signs. - */ - Tag SIGNS = Bukkit.getTag(REGISTRY_BLOCKS, NamespacedKey.minecraft("signs"), Material.class); - /** - * Key for the built in item registry. - */ - String REGISTRY_ITEMS = "items"; - /** - * Vanilla item tag representing all banner items. - */ - Tag ITEMS_BANNERS = Bukkit.getTag(REGISTRY_ITEMS, NamespacedKey.minecraft("banners"), Material.class); - /** - * Vanilla item tag representing all boat items. - */ - Tag ITEMS_BOATS = Bukkit.getTag(REGISTRY_ITEMS, NamespacedKey.minecraft("boats"), Material.class); - /** - * Vanilla item tag representing all fish items. - */ - Tag ITEMS_FISHES = Bukkit.getTag(REGISTRY_ITEMS, NamespacedKey.minecraft("fishes"), Material.class); - /** - * Vanilla item tag representing all music disc items. - */ - Tag ITEMS_MUSIC_DISCS = Bukkit.getTag(REGISTRY_ITEMS, NamespacedKey.minecraft("music_discs"), Material.class); - /** - * Vanilla item tag representing all coal items. - */ - Tag ITEMS_COALS = Bukkit.getTag(REGISTRY_ITEMS, NamespacedKey.minecraft("coals"), Material.class); - /** - * Vanilla item tag representing all arrow items. - */ - Tag ITEMS_ARROWS = Bukkit.getTag(REGISTRY_ITEMS, NamespacedKey.minecraft("arrows"), Material.class); - - /** - * Returns whether or not this tag has an entry for the specified item. - * - * @param item to check - * @return if it is tagged - */ - boolean isTagged(@NotNull T item); - - /** - * Gets an immutable set of all tagged items. - * - * @return set of tagged items - */ - @NotNull - Set getValues(); - -} diff --git a/api/src/main/java/org/bukkit/TreeSpecies.java b/api/src/main/java/org/bukkit/TreeSpecies.java deleted file mode 100644 index 2b177f98a..000000000 --- a/api/src/main/java/org/bukkit/TreeSpecies.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -/** - * 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 static final Map BY_DATA = Maps.newHashMap(); - - private 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 - @Nullable - 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/api/src/main/java/org/bukkit/TreeType.java b/api/src/main/java/org/bukkit/TreeType.java deleted file mode 100644 index dba084fa9..000000000 --- a/api/src/main/java/org/bukkit/TreeType.java +++ /dev/null @@ -1,76 +0,0 @@ -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, - /** - * Large plant native to The End - */ - CHORUS_PLANT, -} diff --git a/api/src/main/java/org/bukkit/UndefinedNullability.java b/api/src/main/java/org/bukkit/UndefinedNullability.java deleted file mode 100644 index f465ea001..000000000 --- a/api/src/main/java/org/bukkit/UndefinedNullability.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Annotation for types, whose nullability is not well defined, so - * {@link org.jetbrains.annotations.NotNull} nor - * {@link org.jetbrains.annotations.Nullable} is applicable. For example when - * interface defines a method, whose nullability depends on the implementation. - * - * @deprecated This should generally not be used in any new API code as it - * suggests a bad API design. - */ -@Retention(RetentionPolicy.CLASS) -@Deprecated -public @interface UndefinedNullability { - - /** - * Human readable description of the circumstances, in which the type is - * nullable. - * - * @return description - */ - String value() default ""; -} diff --git a/api/src/main/java/org/bukkit/UnsafeValues.java b/api/src/main/java/org/bukkit/UnsafeValues.java deleted file mode 100644 index b173e2ece..000000000 --- a/api/src/main/java/org/bukkit/UnsafeValues.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.bukkit; - -import org.bukkit.advancement.Advancement; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.bukkit.plugin.InvalidPluginException; -import org.bukkit.plugin.PluginDescriptionFile; - -/** - * 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. - */ -@Deprecated -public interface UnsafeValues { - - Material toLegacy(Material material); - - Material fromLegacy(Material material); - - Material fromLegacy(MaterialData material); - - Material fromLegacy(MaterialData material, boolean itemPriority); - - BlockData fromLegacy(Material material, byte data); - - Material getMaterial(String material, int version); - - int getDataVersion(); - - ItemStack modifyItemStack(ItemStack stack, String arguments); - - void checkSupported(PluginDescriptionFile pdf) throws InvalidPluginException; - - byte[] processClass(PluginDescriptionFile pdf, String path, byte[] clazz); - - /** - * Load an advancement represented by the specified string into the server. - * The advancement format is governed by Minecraft and has no specified - * layout. - *
- * It is currently a JSON object, as described by the Minecraft Wiki: - * http://minecraft.gamepedia.com/Advancements - *
- * Loaded advancements will be stored and persisted across server restarts - * and reloads. - *
- * Callers should be prepared for {@link Exception} to be thrown. - * - * @param key the unique advancement key - * @param advancement representation of the advancement - * @return the loaded advancement or null if an error occurred - */ - Advancement loadAdvancement(NamespacedKey key, String advancement); - - /** - * Delete an advancement which was loaded and saved by - * {@link #loadAdvancement(org.bukkit.NamespacedKey, java.lang.String)}. - *
- * This method will only remove advancement from persistent storage. It - * should be accompanied by a call to {@link Server#reloadData()} in order - * to fully remove it from the running instance. - * - * @param key the unique advancement key - * @return true if a file matching this key was found and deleted - */ - boolean removeAdvancement(NamespacedKey key); - - // Paper start - /** - * Server name to report to timings v2 - * @return name - */ - String getTimingsServerName(); - - /** - * Called once by the version command on first use, then cached. - */ - default com.destroystokyo.paper.util.VersionFetcher getVersionFetcher() { - return new com.destroystokyo.paper.util.VersionFetcher.DummyVersionFetcher(); - } - - static boolean isLegacyPlugin(org.bukkit.plugin.Plugin plugin) { - return !"1.13".equals(plugin.getDescription().getAPIVersion()) && !"1.14".equals(plugin.getDescription().getAPIVersion()); - } - // Paper end -} diff --git a/api/src/main/java/org/bukkit/Utility.java b/api/src/main/java/org/bukkit/Utility.java deleted file mode 100644 index da66853ef..000000000 --- a/api/src/main/java/org/bukkit/Utility.java +++ /dev/null @@ -1,18 +0,0 @@ -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/api/src/main/java/org/bukkit/Warning.java b/api/src/main/java/org/bukkit/Warning.java deleted file mode 100644 index 91c9cb8fa..000000000 --- a/api/src/main/java/org/bukkit/Warning.java +++ /dev/null @@ -1,111 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - public 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(@Nullable 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 - */ - @NotNull - public static WarningState value(@Nullable 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/api/src/main/java/org/bukkit/WeatherType.java b/api/src/main/java/org/bukkit/WeatherType.java deleted file mode 100644 index 36b993f1c..000000000 --- a/api/src/main/java/org/bukkit/WeatherType.java +++ /dev/null @@ -1,17 +0,0 @@ -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/api/src/main/java/org/bukkit/World.java b/api/src/main/java/org/bukkit/World.java deleted file mode 100644 index 2d22ab30a..000000000 --- a/api/src/main/java/org/bukkit/World.java +++ /dev/null @@ -1,3046 +0,0 @@ -package org.bukkit; - -import java.io.File; -import org.bukkit.generator.ChunkGenerator; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.function.Predicate; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.FallingBlock; -import org.bukkit.entity.Item; -import org.bukkit.entity.LightningStrike; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.generator.BlockPopulator; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.bukkit.metadata.Metadatable; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.messaging.PluginMessageRecipient; -import org.bukkit.util.BoundingBox; -import org.bukkit.util.Consumer; -import org.bukkit.util.RayTraceResult; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a world, which may contain entities, chunks and blocks - */ -public interface World extends PluginMessageRecipient, Metadatable { - - // Paper start - /** - * @return The amount of Entities in this world - */ - int getEntityCount(); - - /** - * @return The amount of Tile Entities in this world - */ - int getTileEntityCount(); - - /** - * @return The amount of Tickable Tile Entities in this world - */ - int getTickableTileEntityCount(); - - /** - * @return The amount of Chunks in this world - */ - int getChunkCount(); - - /** - * @return The amount of Players in this world - */ - int getPlayerCount(); - // Paper end - - /** - * 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 - */ - @NotNull - public 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 - */ - @NotNull - public Block getBlockAt(@NotNull Location location); - - // Paper start - /** - * Gets the {@link Block} at the given block key - * - * @param key The block key. See {@link Block#getBlockKey()} - * @return Block at the key - * @see Block#getBlockKey(int, int, int) - */ - @NotNull - public default Block getBlockAtKey(long key) { - int x = Block.getBlockKeyX(key); - int y = Block.getBlockKeyY(key); - int z = Block.getBlockKeyZ(key); - return getBlockAt(x, y, z); - } - - /** - * Gets the {@link Location} at the given block key - * - * @param key The block key. See {@link Location#toBlockKey()} - * @return Location at the key - * @see Block#getBlockKey(int, int, int) - */ - @NotNull - public default Location getLocationAtKey(long key) { - int x = Block.getBlockKeyX(key); - int y = Block.getBlockKeyY(key); - int z = Block.getBlockKeyZ(key); - return new Location(this, x, y, z); - } - // Paper end - - /** - * Gets the y coordinate of the lowest block at this position such that the - * block and all blocks above it are transparent for lighting purposes. - * - * @param x X-coordinate of the blocks - * @param z Z-coordinate of the blocks - * @return Y-coordinate of the described block - */ - public int getHighestBlockYAt(int x, int z); - - /** - * Gets the y coordinate of the lowest block at the given {@link Location} - * such that the block and all blocks above it are transparent for lighting - * purposes. - * - * @param location Location of the blocks - * @return Y-coordinate of the highest non-air block - */ - public int getHighestBlockYAt(@NotNull Location location); - - /** - * Gets the lowest block at the given coordinates such that the block and - * all blocks above it are transparent for lighting purposes. - * - * @param x X-coordinate of the block - * @param z Z-coordinate of the block - * @return Highest non-empty block - */ - @NotNull - public Block getHighestBlockAt(int x, int z); - - /** - * Gets the lowest block at the given {@link Location} such that the block - * and all blocks above it are transparent for lighting purposes. - * - * @param location Coordinates to get the highest block - * @return Highest non-empty block - */ - @NotNull - public Block getHighestBlockAt(@NotNull Location location); - - // Paper start - Add heightmap API - /** - * Returns the highest block's y-coordinate at the specified block coordinates that match the specified heightmap's conditions. - *

- * implNote: Implementations are recommended to use an iterative search as a fallback before resorting to - * throwing an {@code UnsupportedOperationException}. - *

- * - * @param x The block's x-coordinate. - * @param z The block's z-coordinate. - * @param heightmap The specified heightmap to use. See {@link com.destroystokyo.paper.HeightmapType} - * @return The highest block's y-coordinate at (x, z) that matches the specified heightmap's conditions. - * @throws UnsupportedOperationException If the heightmap type is not supported. - * - * @see com.destroystokyo.paper.HeightmapType - */ - public int getHighestBlockYAt(int x, int z, @NotNull com.destroystokyo.paper.HeightmapType heightmap) throws UnsupportedOperationException; - - /** - * Returns the highest block's y-coordinate at the specified block coordinates that match the specified heightmap's conditions. - * Note that the y-coordinate of the specified location is ignored. - *

- * implNote: Implementations are recommended to use an iterative search as a fallback before resorting to - * throwing an {@code UnsupportedOperationException}. - *

- * - * @param location The specified block coordinates. - * @param heightmap The specified heightmap to use. See {@link com.destroystokyo.paper.HeightmapType} - * @return The highest block's y-coordinate at {@code location} that matches the specified heightmap's conditions. - * @throws UnsupportedOperationException If the heightmap type is not supported. - * @see com.destroystokyo.paper.HeightmapType - */ - default int getHighestBlockYAt(@NotNull Location location, @NotNull com.destroystokyo.paper.HeightmapType heightmap) throws UnsupportedOperationException { - return this.getHighestBlockYAt(location.getBlockX(), location.getBlockZ(), heightmap); - } - - /** - * Returns the highest {@link Block} at the specified block coordinates that match the specified heightmap's conditions. - *

- * implNote: Implementations are recommended to use an iterative search as a fallback before resorting to - * throwing an {@code UnsupportedOperationException}. - *

- * @param x The block's x-coordinate. - * @param z The block's z-coordinate. - * @param heightmap The specified heightmap to use. See {@link com.destroystokyo.paper.HeightmapType} - * @return The highest {@link Block} at (x, z) that matches the specified heightmap's conditions. - * @throws UnsupportedOperationException If the heightmap type is not supported. - * @see com.destroystokyo.paper.HeightmapType - */ - @NotNull - default Block getHighestBlockAt(int x, int z, @NotNull com.destroystokyo.paper.HeightmapType heightmap) throws UnsupportedOperationException { - return this.getBlockAt(x, this.getHighestBlockYAt(x, z, heightmap), z); - } - - /** - * Returns the highest {@link Block} at the specified block coordinates that match the specified heightmap's conditions. - * Note that the y-coordinate of the specified location is ignored. - *

- * implNote: Implementations are recommended to use an iterative search as a fallback before resorting to - * throwing an {@code UnsupportedOperationException}. - *

- * @param location The specified block coordinates. - * @param heightmap The specified heightmap to use. See {@link com.destroystokyo.paper.HeightmapType} - * @return The highest {@link Block} at {@code location} that matches the specified heightmap's conditions. - * @throws UnsupportedOperationException If the heightmap type is not supported. - * @see com.destroystokyo.paper.HeightmapType - */ - @NotNull - default Block getHighestBlockAt(@NotNull Location location, @NotNull com.destroystokyo.paper.HeightmapType heightmap) throws UnsupportedOperationException { - return this.getHighestBlockAt(location.getBlockX(), location.getBlockZ(), heightmap); - } - // Paper end - - /** - * 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 - */ - @NotNull - public 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 - */ - @NotNull - public Chunk getChunkAt(@NotNull 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 - */ - @NotNull - public Chunk getChunkAt(@NotNull Block block); - - // Paper start - /** - * Gets the chunk at the specified chunk key, which is the X and Z packed into a long. - * - * See {@link Chunk#getChunkKey()} for easy access to the key, or you may calculate it as: - * long chunkKey = (long) chunkX & 0xffffffffL | ((long) chunkZ & 0xffffffffL) >> 32; - * - * @param chunkKey The Chunk Key to look up the chunk by - * @return The chunk at the specified key - */ - @NotNull - public default Chunk getChunkAt(long chunkKey) { - return getChunkAt((int) chunkKey, (int) (chunkKey >> 32)); - } - - /** - * Checks if a {@link Chunk} has been generated at the specified chunk key, - * which is the X and Z packed into a long. - * - * @param chunkKey The Chunk Key to look up the chunk by - * @return true if the chunk has been generated, otherwise false - */ - public default boolean isChunkGenerated(long chunkKey) { - return isChunkGenerated((int) chunkKey, (int) (chunkKey >> 32)); - } - - /** - * This is the Legacy API before Java 8 was supported. Java 8 Consumer is provided, - * as well as future support - * - * Used by {@link World#getChunkAtAsync(Location,ChunkLoadCallback)} methods - * to request a {@link Chunk} to be loaded, with this callback receiving - * the chunk when it is finished. - * - * This callback will be executed on synchronously on the main thread. - * - * Timing and order this callback is fired is intentionally not defined and - * and subject to change. - * - * @deprecated Use either the Future or the Consumer based methods - */ - @Deprecated - public static interface ChunkLoadCallback extends java.util.function.Consumer { - public void onLoad(@NotNull Chunk chunk); - - // backwards compat to old api - @Override - default void accept(@NotNull Chunk chunk) { - onLoad(chunk); - } - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link ChunkLoadCallback} will always be executed synchronously - * on the main Server Thread. - * - * @deprecated Use either the Future or the Consumer based methods - * @param x Chunk X-coordinate of the chunk - (world coordinate / 16) - * @param z Chunk Z-coordinate of the chunk - (world coordinate / 16) - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - @Deprecated - public default void getChunkAtAsync(int x, int z, @NotNull ChunkLoadCallback cb) { - getChunkAtAsync(x, z, true).thenAccept(cb::onLoad); - } - - /** - * Requests a {@link Chunk} to be loaded at the given {@link Location} - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link ChunkLoadCallback} will always be executed synchronously - * on the main Server Thread. - * - * @deprecated Use either the Future or the Consumer based methods - * @param loc Location of the chunk - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - @Deprecated - public default void getChunkAtAsync(@NotNull Location loc, @NotNull ChunkLoadCallback cb) { - getChunkAtAsync(loc, true).thenAccept(cb::onLoad); - } - - /** - * Requests {@link Chunk} to be loaded that contains the given {@link Block} - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link ChunkLoadCallback} will always be executed synchronously - * on the main Server Thread. - * - * @deprecated Use either the Future or the Consumer based methods - * @param block Block to get the containing chunk from - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - @Deprecated - public default void getChunkAtAsync(@NotNull Block block, @NotNull ChunkLoadCallback cb) { - getChunkAtAsync(block, true).thenAccept(cb::onLoad); - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link java.util.function.Consumer} will always be executed synchronously - * on the main Server Thread. - * - * @param x Chunk X-coordinate of the chunk - (world coordinate / 16) - * @param z Chunk Z-coordinate of the chunk - (world coordinate / 16) - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - public default void getChunkAtAsync(int x, int z, @NotNull java.util.function.Consumer cb) { - getChunkAtAsync(x, z, true).thenAccept(cb); - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link java.util.function.Consumer} will always be executed synchronously - * on the main Server Thread. - * - * @param x Chunk X-coordinate of the chunk - (world coordinate / 16) - * @param z Chunk Z-coordinate of the chunk - (world coordinate / 16) - * @param gen Should we generate a chunk if it doesn't exists or not - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - public default void getChunkAtAsync(int x, int z, boolean gen, @NotNull java.util.function.Consumer cb) { - getChunkAtAsync(x, z, gen).thenAccept(cb); - } - - /** - * Requests a {@link Chunk} to be loaded at the given {@link Location} - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link java.util.function.Consumer} will always be executed synchronously - * on the main Server Thread. - * - * @param loc Location of the chunk - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - public default void getChunkAtAsync(@NotNull Location loc, @NotNull java.util.function.Consumer cb) { - getChunkAtAsync((int)Math.floor(loc.getX()) >> 4, (int)Math.floor(loc.getZ()) >> 4, true, cb); - } - - /** - * Requests a {@link Chunk} to be loaded at the given {@link Location} - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link java.util.function.Consumer} will always be executed synchronously - * on the main Server Thread. - * - * @param loc Location of the chunk - * @param gen Should the chunk generate - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - public default void getChunkAtAsync(@NotNull Location loc, boolean gen, @NotNull java.util.function.Consumer cb) { - getChunkAtAsync((int)Math.floor(loc.getX()) >> 4, (int)Math.floor(loc.getZ()) >> 4, gen, cb); - } - - /** - * Requests {@link Chunk} to be loaded that contains the given {@link Block} - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link java.util.function.Consumer} will always be executed synchronously - * on the main Server Thread. - * - * @param block Block to get the containing chunk from - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - public default void getChunkAtAsync(@NotNull Block block, @NotNull java.util.function.Consumer cb) { - getChunkAtAsync(block.getX() >> 4, block.getZ() >> 4, true, cb); - } - - /** - * Requests {@link Chunk} to be loaded that contains the given {@link Block} - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The {@link java.util.function.Consumer} will always be executed synchronously - * on the main Server Thread. - * - * @param block Block to get the containing chunk from - * @param gen Should the chunk generate - * @param cb Callback to receive the chunk when it is loaded. - * will be executed synchronously - */ - public default void getChunkAtAsync(@NotNull Block block, boolean gen, @NotNull java.util.function.Consumer cb) { - getChunkAtAsync(block.getX() >> 4, block.getZ() >> 4, gen, cb); - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The future will always be executed synchronously - * on the main Server Thread. - * @param loc Location to load the corresponding chunk from - * @return Future that will resolve when the chunk is loaded - */ - @NotNull - public default java.util.concurrent.CompletableFuture getChunkAtAsync(@NotNull Location loc) { - return getChunkAtAsync((int)Math.floor(loc.getX()) >> 4, (int)Math.floor(loc.getZ()) >> 4, true); - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The future will always be executed synchronously - * on the main Server Thread. - * @param loc Location to load the corresponding chunk from - * @param gen Should the chunk generate - * @return Future that will resolve when the chunk is loaded - */ - @NotNull - public default java.util.concurrent.CompletableFuture getChunkAtAsync(@NotNull Location loc, boolean gen) { - return getChunkAtAsync((int)Math.floor(loc.getX()) >> 4, (int)Math.floor(loc.getZ()) >> 4, gen); - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The future will always be executed synchronously - * on the main Server Thread. - * @param block Block to load the corresponding chunk from - * @return Future that will resolve when the chunk is loaded - */ - @NotNull - public default java.util.concurrent.CompletableFuture getChunkAtAsync(@NotNull Block block) { - return getChunkAtAsync(block.getX() >> 4, block.getZ() >> 4, true); - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The future will always be executed synchronously - * on the main Server Thread. - * @param block Block to load the corresponding chunk from - * @param gen Should the chunk generate - * @return Future that will resolve when the chunk is loaded - */ - @NotNull - public default java.util.concurrent.CompletableFuture getChunkAtAsync(@NotNull Block block, boolean gen) { - return getChunkAtAsync(block.getX() >> 4, block.getZ() >> 4, gen); - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The future will always be executed synchronously - * on the main Server Thread. - * - * @param x X Coord - * @param z Z Coord - * @return Future that will resolve when the chunk is loaded - */ - @NotNull - public default java.util.concurrent.CompletableFuture getChunkAtAsync(int x, int z) { - return getChunkAtAsync(x, z, true); - } - - /** - * Requests a {@link Chunk} to be loaded at the given coordinates - * - * This method makes no guarantee on how fast the chunk will load, - * and will return the chunk to the callback at a later time. - * - * You should use this method if you need a chunk but do not need it - * immediately, and you wish to let the server control the speed - * of chunk loads, keeping performance in mind. - * - * The future will always be executed synchronously - * on the main Server Thread. - * - * @param x Chunk X-coordinate of the chunk - (world coordinate / 16) - * @param z Chunk Z-coordinate of the chunk - (world coordinate / 16) - * @param gen Should we generate a chunk if it doesn't exists or not - * @return Future that will resolve when the chunk is loaded - */ - @NotNull - public java.util.concurrent.CompletableFuture getChunkAtAsync(int x, int z, boolean gen); - // Paper end - - /** - * Checks if the specified {@link Chunk} is loaded - * - * @param chunk The chunk to check - * @return true if the chunk is loaded, otherwise false - */ - public boolean isChunkLoaded(@NotNull Chunk chunk); - - /** - * Gets an array of all loaded {@link Chunk}s - * - * @return Chunk[] containing all loaded chunks - */ - @NotNull - public Chunk[] getLoadedChunks(); - - /** - * Loads the specified {@link Chunk}. - *

- * This method will keep the specified chunk loaded until one of the - * unload methods is manually called. Callers are advised to instead use - * getChunkAt which will only temporarily load the requested chunk. - * - * @param chunk The chunk to load - */ - public void loadChunk(@NotNull 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 - */ - public boolean isChunkLoaded(int x, int z); - - /** - * Checks if the {@link Chunk} at the specified coordinates is generated - * - * @param x X-coordinate of the chunk - * @param z Z-coordinate of the chunk - * @return true if the chunk is generated, otherwise false - */ - public boolean isChunkGenerated(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 - * @deprecated This method was added to facilitate chunk garbage collection. - * As of the current Minecraft version chunks are now strictly managed and - * will not be loaded for more than 1 tick unless they are in use. - */ - @Deprecated - public boolean isChunkInUse(int x, int z); - - /** - * Loads the {@link Chunk} at the specified coordinates. - *

- * This method will keep the specified chunk loaded until one of the - * unload methods is manually called. Callers are advised to instead use - * getChunkAt which will only temporarily load the requested chunk. - *

- * 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 - */ - public void loadChunk(int x, int z); - - /** - * Loads the {@link Chunk} at the specified coordinates. - *

- * This method will keep the specified chunk loaded until one of the - * unload methods is manually called. Callers are advised to instead use - * getChunkAt which will only temporarily load the requested chunk. - * - * @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 - */ - public 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)} - * where save is true. - * - * @param chunk the chunk to unload - * @return true if the chunk has unloaded successfully, otherwise false - */ - public boolean unloadChunk(@NotNull Chunk chunk); - - /** - * Safely unloads and saves the {@link Chunk} at the specified coordinates - *

- * This method is analogous to {@link #unloadChunk(int, int, boolean)} - * where save is 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 - */ - public boolean unloadChunk(int x, int z); - - /** - * Safely 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 Whether or not to save the chunk - * @return true if the chunk has unloaded successfully, otherwise false - */ - public boolean unloadChunk(int x, int z, boolean save); - - /** - * Safely queues the {@link Chunk} at the specified coordinates for - * unloading. - * - * @param x X-coordinate of the chunk - * @param z Z-coordinate of the chunk - * @return true is the queue attempt was successful, otherwise false - */ - public boolean unloadChunkRequest(int x, int z); - - /** - * 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 - * - * @deprecated regenerating a single chunk is not likely to produce the same - * chunk as before as terrain decoration may be spread across chunks. Use of - * this method should be avoided as it is known to produce buggy results. - */ - @Deprecated - public 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 - public boolean refreshChunk(int x, int z); - - /** - * Gets whether the chunk at the specified chunk coordinates is force - * loaded. - *

- * A force loaded chunk will not be unloaded due to lack of player activity. - * - * @param x X-coordinate of the chunk - * @param z Z-coordinate of the chunk - * @return force load status - */ - public boolean isChunkForceLoaded(int x, int z); - - /** - * Sets whether the chunk at the specified chunk coordinates is force - * loaded. - *

- * A force loaded chunk will not be unloaded due to lack of player activity. - * - * @param x X-coordinate of the chunk - * @param z Z-coordinate of the chunk - * @param forced force load status - */ - public void setChunkForceLoaded(int x, int z, boolean forced); - - /** - * Returns all force loaded chunks in this world. - *

- * A force loaded chunk will not be unloaded due to lack of player activity. - * - * @return unmodifiable collection of force loaded chunks - */ - @NotNull - public Collection getForceLoadedChunks(); - - /** - * Adds a plugin ticket for the specified chunk, loading the chunk if it is - * not already loaded. - *

- * A plugin ticket will prevent a chunk from unloading until it is - * explicitly removed. A plugin instance may only have one ticket per chunk, - * but each chunk can have multiple plugin tickets. - *

- * - * @param x X-coordinate of the chunk - * @param z Z-coordinate of the chunk - * @param plugin Plugin which owns the ticket - * @return {@code true} if a plugin ticket was added, {@code false} if the - * ticket already exists for the plugin - * @throws IllegalStateException If the specified plugin is not enabled - * @see #removePluginChunkTicket(int, int, Plugin) - */ - public boolean addPluginChunkTicket(int x, int z, @NotNull Plugin plugin); - - /** - * Removes the specified plugin's ticket for the specified chunk - *

- * A plugin ticket will prevent a chunk from unloading until it is - * explicitly removed. A plugin instance may only have one ticket per chunk, - * but each chunk can have multiple plugin tickets. - *

- * - * @param x X-coordinate of the chunk - * @param z Z-coordinate of the chunk - * @param plugin Plugin which owns the ticket - * @return {@code true} if the plugin ticket was removed, {@code false} if - * there is no plugin ticket for the chunk - * @see #addPluginChunkTicket(int, int, Plugin) - */ - public boolean removePluginChunkTicket(int x, int z, @NotNull Plugin plugin); - - /** - * Removes all plugin tickets for the specified plugin - *

- * A plugin ticket will prevent a chunk from unloading until it is - * explicitly removed. A plugin instance may only have one ticket per chunk, - * but each chunk can have multiple plugin tickets. - *

- * - * @param plugin Specified plugin - * @see #addPluginChunkTicket(int, int, Plugin) - * @see #removePluginChunkTicket(int, int, Plugin) - */ - public void removePluginChunkTickets(@NotNull Plugin plugin); - - /** - * Retrieves a collection specifying which plugins have tickets for the - * specified chunk. This collection is not updated when plugin tickets are - * added or removed to the chunk. - *

- * A plugin ticket will prevent a chunk from unloading until it is - * explicitly removed. A plugin instance may only have one ticket per chunk, - * but each chunk can have multiple plugin tickets. - *

- * - * @param x X-coordinate of the chunk - * @param z Z-coordinate of the chunk - * @return unmodifiable collection containing which plugins have tickets for - * the chunk - * @see #addPluginChunkTicket(int, int, Plugin) - * @see #removePluginChunkTicket(int, int, Plugin) - */ - @NotNull - public Collection getPluginChunkTickets(int x, int z); - - /** - * Returns a map of which plugins have tickets for what chunks. The returned - * map is not updated when plugin tickets are added or removed to chunks. If - * a plugin has no tickets, it will be absent from the map. - *

- * A plugin ticket will prevent a chunk from unloading until it is - * explicitly removed. A plugin instance may only have one ticket per chunk, - * but each chunk can have multiple plugin tickets. - *

- * - * @return unmodifiable map containing which plugins have tickets for what - * chunks - * @see #addPluginChunkTicket(int, int, Plugin) - * @see #removePluginChunkTicket(int, int, Plugin) - */ - @NotNull - public Map> getPluginChunkTickets(); - - /** - * 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 - */ - @NotNull - public Item dropItem(@NotNull Location location, @NotNull 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 - */ - @NotNull - public Item dropItemNaturally(@NotNull Location location, @NotNull 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 - */ - @NotNull - public Arrow spawnArrow(@NotNull Location location, @NotNull Vector direction, float speed, float spread); - - /** - * Creates an arrow entity of the given class at the given {@link Location} - * - * @param type of arrow to spawn - * @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 - * @param clazz the Entity class for the arrow - * {@link org.bukkit.entity.SpectralArrow},{@link org.bukkit.entity.Arrow},{@link org.bukkit.entity.TippedArrow} - * @return Arrow entity spawned as a result of this method - */ - @NotNull - public T spawnArrow(@NotNull Location location, @NotNull Vector direction, float speed, float spread, @NotNull Class clazz); - - /** - * 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 - */ - public boolean generateTree(@NotNull Location location, @NotNull 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 - */ - public boolean generateTree(@NotNull Location loc, @NotNull TreeType type, @NotNull 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 - */ - @NotNull - public Entity spawnEntity(@NotNull Location loc, @NotNull EntityType type); - - /** - * Strikes lightning at the given {@link Location} - * - * @param loc The location to strike lightning - * @return The lightning entity. - */ - @NotNull - public LightningStrike strikeLightning(@NotNull Location loc); - - /** - * Strikes lightning at the given {@link Location} without doing damage - * - * @param loc The location to strike lightning - * @return The lightning entity. - */ - @NotNull - public LightningStrike strikeLightningEffect(@NotNull Location loc); - - /** - * Get a list of all entities in this World - * - * @return A List of all Entities currently residing in this world - */ - @NotNull - public List getEntities(); - - /** - * Get a list of all living entities in this World - * - * @return A List of all LivingEntities currently residing in this world - */ - @NotNull - public 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 - @NotNull - public Collection getEntitiesByClass(@NotNull 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 - */ - @NotNull - public Collection getEntitiesByClass(@NotNull 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 - */ - @NotNull - public Collection getEntitiesByClasses(@NotNull Class... classes); - - // Paper start - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param radius Radius - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyLivingEntities(@NotNull Location loc, double radius) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, loc, radius, radius, radius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param xzRadius X/Z Radius - * @param yRadius Y Radius - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyLivingEntities(@NotNull Location loc, double xzRadius, double yRadius) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, loc, xzRadius, yRadius, xzRadius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z radius - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyLivingEntities(@NotNull Location loc, double xRadius, double yRadius, double zRadius) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, loc, xRadius, yRadius, zRadius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param radius X Radius - * @param predicate a predicate used to filter results - * @return the collection of living entities near location. This will always be a non-null collection - */ - @NotNull - public default Collection getNearbyLivingEntities(@NotNull Location loc, double radius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, loc, radius, radius, radius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param xzRadius X/Z Radius - * @param yRadius Y Radius - * @param predicate a predicate used to filter results - * @return the collection of living entities near location. This will always be a non-null collection - */ - @NotNull - public default Collection getNearbyLivingEntities(@NotNull Location loc, double xzRadius, double yRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, loc, xzRadius, yRadius, xzRadius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z radius - * @param predicate a predicate used to filter results - * @return the collection of living entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyLivingEntities(@NotNull Location loc, double xRadius, double yRadius, double zRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.LivingEntity.class, loc, xRadius, yRadius, zRadius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param radius X/Y/Z Radius - * @return the collection of living entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyPlayers(@NotNull Location loc, double radius) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, loc, radius, radius, radius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param xzRadius X/Z Radius - * @param yRadius Y Radius - * @return the collection of living entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyPlayers(@NotNull Location loc, double xzRadius, double yRadius) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, loc, xzRadius, yRadius, xzRadius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z Radius - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyPlayers(@NotNull Location loc, double xRadius, double yRadius, double zRadius) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, loc, xRadius, yRadius, zRadius); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param radius X/Y/Z Radius - * @param predicate a predicate used to filter results - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyPlayers(@NotNull Location loc, double radius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, loc, radius, radius, radius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param xzRadius X/Z Radius - * @param yRadius Y Radius - * @param predicate a predicate used to filter results - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyPlayers(@NotNull Location loc, double xzRadius, double yRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, loc, xzRadius, yRadius, xzRadius, predicate); - } - - /** - * Gets nearby players within the specified radius (bounding box) - * @param loc Center location - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z Radius - * @param predicate a predicate used to filter results - * @return the collection of players near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyPlayers(@NotNull Location loc, double xRadius, double yRadius, double zRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(org.bukkit.entity.Player.class, loc, xRadius, yRadius, zRadius, predicate); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius (bounding box) - * @param clazz Type to filter by - * @param loc Center location - * @param radius X/Y/Z radius to search within - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyEntitiesByType(@Nullable Class clazz, @NotNull Location loc, double radius) { - return getNearbyEntitiesByType(clazz, loc, radius, radius, radius, null); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius, with x and x radius matching (bounding box) - * @param clazz Type to filter by - * @param loc Center location - * @param xzRadius X/Z radius to search within - * @param yRadius Y radius to search within - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyEntitiesByType(@Nullable Class clazz, @NotNull Location loc, double xzRadius, double yRadius) { - return getNearbyEntitiesByType(clazz, loc, xzRadius, yRadius, xzRadius, null); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius (bounding box) - * @param clazz Type to filter by - * @param loc Center location - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z Radius - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyEntitiesByType(@Nullable Class clazz, @NotNull Location loc, double xRadius, double yRadius, double zRadius) { - return getNearbyEntitiesByType(clazz, loc, xRadius, yRadius, zRadius, null); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius (bounding box) - * @param clazz Type to filter by - * @param loc Center location - * @param radius X/Y/Z radius to search within - * @param predicate a predicate used to filter results - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyEntitiesByType(@Nullable Class clazz, @NotNull Location loc, double radius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(clazz, loc, radius, radius, radius, predicate); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius, with x and x radius matching (bounding box) - * @param clazz Type to filter by - * @param loc Center location - * @param xzRadius X/Z radius to search within - * @param yRadius Y radius to search within - * @param predicate a predicate used to filter results - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyEntitiesByType(@Nullable Class clazz, @NotNull Location loc, double xzRadius, double yRadius, @Nullable Predicate predicate) { - return getNearbyEntitiesByType(clazz, loc, xzRadius, yRadius, xzRadius, predicate); - } - - /** - * Gets all nearby entities of the specified type, within the specified radius (bounding box) - * @param clazz Type to filter by - * @param loc Center location - * @param xRadius X Radius - * @param yRadius Y Radius - * @param zRadius Z Radius - * @param predicate a predicate used to filter results - * @param the entity type - * @return the collection of entities near location. This will always be a non-null collection. - */ - @NotNull - public default Collection getNearbyEntitiesByType(@Nullable Class clazz, @NotNull Location loc, double xRadius, double yRadius, double zRadius, @Nullable Predicate predicate) { - if (clazz == null) { - clazz = Entity.class; - } - List nearby = new ArrayList<>(); - for (Entity bukkitEntity : getNearbyEntities(loc, xRadius, yRadius, zRadius)) { - //noinspection unchecked - if (clazz.isAssignableFrom(bukkitEntity.getClass()) && (predicate == null || predicate.test((T) bukkitEntity))) { - //noinspection unchecked - nearby.add((T) bukkitEntity); - } - } - return nearby; - } - // Paper end - - /** - * Get a list of all players in this World - * - * @return A list of all Players currently residing in this world - */ - @NotNull - public List getPlayers(); - - /** - * Returns a list of entities within a bounding box centered around a - * Location. - *

- * This may not consider entities in currently unloaded chunks. 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. - */ - @NotNull - public Collection getNearbyEntities(@NotNull Location location, double x, double y, double z); - - // Paper start - getEntity by UUID API - /** - * Gets an entity in this world by its UUID - * - * @param uuid the UUID of the entity - * @return the entity with the given UUID, or null if it isn't found - */ - @Nullable - public Entity getEntity(@NotNull UUID uuid); - // Paper end - - /** - * Returns a list of entities within a bounding box centered around a - * Location. - *

- * This may not consider entities in currently unloaded chunks. 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 - * @param filter only entities that fulfill this predicate are considered, - * or null to consider all entities - * @return the collection of entities near location. This will always be a - * non-null collection. - */ - @NotNull - public Collection getNearbyEntities(@NotNull Location location, double x, double y, double z, @Nullable Predicate filter); - - /** - * Returns a list of entities within the given bounding box. - *

- * This may not consider entities in currently unloaded chunks. Some - * implementations may impose artificial restrictions on the size of the - * search bounding box. - * - * @param boundingBox the bounding box - * @return the collection of entities within the bounding box, will always - * be a non-null collection - */ - @NotNull - public Collection getNearbyEntities(@NotNull BoundingBox boundingBox); - - /** - * Returns a list of entities within the given bounding box. - *

- * This may not consider entities in currently unloaded chunks. Some - * implementations may impose artificial restrictions on the size of the - * search bounding box. - * - * @param boundingBox the bounding box - * @param filter only entities that fulfill this predicate are considered, - * or null to consider all entities - * @return the collection of entities within the bounding box, will always - * be a non-null collection - */ - @NotNull - public Collection getNearbyEntities(@NotNull BoundingBox boundingBox, @Nullable Predicate filter); - - /** - * Performs a ray trace that checks for entity collisions. - *

- * This may not consider entities in currently unloaded chunks. Some - * implementations may impose artificial restrictions on the maximum - * distance. - * - * @param start the start position - * @param direction the ray direction - * @param maxDistance the maximum distance - * @return the closest ray trace hit result, or null if there - * is no hit - * @see #rayTraceEntities(Location, Vector, double, double, Predicate) - */ - @Nullable - public RayTraceResult rayTraceEntities(@NotNull Location start, @NotNull Vector direction, double maxDistance); - - /** - * Performs a ray trace that checks for entity collisions. - *

- * This may not consider entities in currently unloaded chunks. Some - * implementations may impose artificial restrictions on the maximum - * distance. - * - * @param start the start position - * @param direction the ray direction - * @param maxDistance the maximum distance - * @param raySize entity bounding boxes will be uniformly expanded (or - * shrinked) by this value before doing collision checks - * @return the closest ray trace hit result, or null if there - * is no hit - * @see #rayTraceEntities(Location, Vector, double, double, Predicate) - */ - @Nullable - public RayTraceResult rayTraceEntities(@NotNull Location start, @NotNull Vector direction, double maxDistance, double raySize); - - /** - * Performs a ray trace that checks for entity collisions. - *

- * This may not consider entities in currently unloaded chunks. Some - * implementations may impose artificial restrictions on the maximum - * distance. - * - * @param start the start position - * @param direction the ray direction - * @param maxDistance the maximum distance - * @param filter only entities that fulfill this predicate are considered, - * or null to consider all entities - * @return the closest ray trace hit result, or null if there - * is no hit - * @see #rayTraceEntities(Location, Vector, double, double, Predicate) - */ - @Nullable - public RayTraceResult rayTraceEntities(@NotNull Location start, @NotNull Vector direction, double maxDistance, @Nullable Predicate filter); - - /** - * Performs a ray trace that checks for entity collisions. - *

- * This may not consider entities in currently unloaded chunks. Some - * implementations may impose artificial restrictions on the maximum - * distance. - * - * @param start the start position - * @param direction the ray direction - * @param maxDistance the maximum distance - * @param raySize entity bounding boxes will be uniformly expanded (or - * shrinked) by this value before doing collision checks - * @param filter only entities that fulfill this predicate are considered, - * or null to consider all entities - * @return the closest ray trace hit result, or null if there - * is no hit - */ - @Nullable - public RayTraceResult rayTraceEntities(@NotNull Location start, @NotNull Vector direction, double maxDistance, double raySize, @Nullable Predicate filter); - - /** - * Performs a ray trace that checks for block collisions using the blocks' - * precise collision shapes. - *

- * This takes collisions with passable blocks into account, but ignores - * fluids. - *

- * This may cause loading of chunks! Some implementations may impose - * artificial restrictions on the maximum distance. - * - * @param start the start location - * @param direction the ray direction - * @param maxDistance the maximum distance - * @return the ray trace hit result, or null if there is no hit - * @see #rayTraceBlocks(Location, Vector, double, FluidCollisionMode, boolean) - */ - @Nullable - public RayTraceResult rayTraceBlocks(@NotNull Location start, @NotNull Vector direction, double maxDistance); - - /** - * Performs a ray trace that checks for block collisions using the blocks' - * precise collision shapes. - *

- * This takes collisions with passable blocks into account. - *

- * This may cause loading of chunks! Some implementations may impose - * artificial restrictions on the maximum distance. - * - * @param start the start location - * @param direction the ray direction - * @param maxDistance the maximum distance - * @param fluidCollisionMode the fluid collision mode - * @return the ray trace hit result, or null if there is no hit - * @see #rayTraceBlocks(Location, Vector, double, FluidCollisionMode, boolean) - */ - @Nullable - public RayTraceResult rayTraceBlocks(@NotNull Location start, @NotNull Vector direction, double maxDistance, @NotNull FluidCollisionMode fluidCollisionMode); - - /** - * Performs a ray trace that checks for block collisions using the blocks' - * precise collision shapes. - *

- * If collisions with passable blocks are ignored, fluid collisions are - * ignored as well regardless of the fluid collision mode. - *

- * Portal blocks are only considered passable if the ray starts within - * them. Apart from that collisions with portal blocks will be considered - * even if collisions with passable blocks are otherwise ignored. - *

- * This may cause loading of chunks! Some implementations may impose - * artificial restrictions on the maximum distance. - * - * @param start the start location - * @param direction the ray direction - * @param maxDistance the maximum distance - * @param fluidCollisionMode the fluid collision mode - * @param ignorePassableBlocks whether to ignore passable but collidable - * blocks (ex. tall grass, signs, fluids, ..) - * @return the ray trace hit result, or null if there is no hit - */ - @Nullable - public RayTraceResult rayTraceBlocks(@NotNull Location start, @NotNull Vector direction, double maxDistance, @NotNull FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks); - - /** - * Performs a ray trace that checks for both block and entity collisions. - *

- * Block collisions use the blocks' precise collision shapes. The - * raySize parameter is only taken into account for entity - * collision checks. - *

- * If collisions with passable blocks are ignored, fluid collisions are - * ignored as well regardless of the fluid collision mode. - *

- * Portal blocks are only considered passable if the ray starts within them. - * Apart from that collisions with portal blocks will be considered even if - * collisions with passable blocks are otherwise ignored. - *

- * This may cause loading of chunks! Some implementations may impose - * artificial restrictions on the maximum distance. - * - * @param start the start location - * @param direction the ray direction - * @param maxDistance the maximum distance - * @param fluidCollisionMode the fluid collision mode - * @param ignorePassableBlocks whether to ignore passable but collidable - * blocks (ex. tall grass, signs, fluids, ..) - * @param raySize entity bounding boxes will be uniformly expanded (or - * shrinked) by this value before doing collision checks - * @param filter only entities that fulfill this predicate are considered, - * or null to consider all entities - * @return the closest ray trace hit result with either a block or an - * entity, or null if there is no hit - */ - @Nullable - public RayTraceResult rayTrace(@NotNull Location start, @NotNull Vector direction, double maxDistance, @NotNull FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks, double raySize, @Nullable Predicate filter); - - /** - * Gets the unique name of this world - * - * @return Name of this world - */ - @NotNull - public String getName(); - - /** - * Gets the Unique ID of this world - * - * @return Unique ID of this world. - */ - @NotNull - public UUID getUID(); - - /** - * Gets the default spawn {@link Location} of this world - * - * @return The spawn location of this world - */ - @NotNull - public Location getSpawnLocation(); - - /** - * Sets the spawn location of the world. - *
- * The location provided must be equal to this world. - * - * @param location The {@link Location} to set the spawn for this world at. - * @return True if it was successfully set. - */ - @NotNull - public boolean setSpawnLocation(@NotNull Location location); - - /** - * 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. - */ - public 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 - */ - public 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 - */ - public 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 - */ - public 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 - */ - public void setFullTime(long time); - - // Paper start - - /** - * Check if it is currently daytime in this world - * - * @return True if it is daytime - */ - public boolean isDayTime(); - // Paper end - - /** - * Returns whether the world has an ongoing storm. - * - * @return Whether there is an ongoing storm - */ - public 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 - */ - public void setStorm(boolean hasStorm); - - /** - * Get the remaining time in ticks of the current conditions. - * - * @return Time in ticks - */ - public int getWeatherDuration(); - - /** - * Set the remaining time in ticks of the current conditions. - * - * @param duration Time in ticks - */ - public void setWeatherDuration(int duration); - - /** - * Returns whether there is thunder. - * - * @return Whether there is thunder - */ - public boolean isThundering(); - - /** - * Set whether it is thundering. - * - * @param thundering Whether it is thundering - */ - public void setThundering(boolean thundering); - - /** - * Get the thundering duration. - * - * @return Duration in ticks - */ - public int getThunderDuration(); - - /** - * Set the thundering duration. - * - * @param duration Duration in ticks - */ - public 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 - */ - public 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 - */ - public 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 - */ - public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks); - - /** - * 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 - * @param source the source entity, used for tracking damage - * @return false if explosion was canceled, otherwise true - */ - public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, @Nullable Entity source); - - /** - * 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 - */ - public boolean createExplosion(@NotNull 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 - */ - public boolean createExplosion(@NotNull Location loc, float power, boolean setFire); - - // Paper start - /** - * Creates explosion at given location with given power and optionally - * setting blocks on fire, with the specified entity as the source. - * - * @param source The source entity of the explosion - * @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 - * @param breakBlocks Whether or not to have blocks be destroyed - * @return false if explosion was canceled, otherwise true - */ - public boolean createExplosion(@Nullable Entity source, @NotNull Location loc, float power, boolean setFire, boolean breakBlocks); - - /** - * Creates explosion at given location with given power and optionally - * setting blocks on fire, with the specified entity as the source. - * - * Will destroy other blocks - * - * @param source The source entity of the explosion - * @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 - */ - public default boolean createExplosion(@Nullable Entity source, @NotNull Location loc, float power, boolean setFire) { - return createExplosion(source, loc, power, setFire, true); - } - /** - * Creates explosion at given location with given power, with the specified entity as the source. - * Will set blocks on fire and destroy blocks. - * - * @param source The source entity of the explosion - * @param loc Location to blow up - * @param power The power of explosion, where 4F is TNT - * @return false if explosion was canceled, otherwise true - */ - public default boolean createExplosion(@Nullable Entity source, @NotNull Location loc, float power) { - return createExplosion(source, loc, power, true, true); - } - /** - * Creates explosion at given entities location with given power and optionally - * setting blocks on fire, with the specified entity as the source. - * - * @param source The source entity of the explosion - * @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 - */ - public default boolean createExplosion(@NotNull Entity source, float power, boolean setFire, boolean breakBlocks) { - return createExplosion(source, source.getLocation(), power, setFire, breakBlocks); - } - /** - * Creates explosion at given entities location with given power and optionally - * setting blocks on fire, with the specified entity as the source. - * - * Will destroy blocks. - * - * @param source The source entity of the explosion - * @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 - */ - public default boolean createExplosion(@NotNull Entity source, float power, boolean setFire) { - return createExplosion(source, source.getLocation(), power, setFire, true); - } - - /** - * Creates explosion at given entities location with given power and optionally - * setting blocks on fire, with the specified entity as the source. - * - * @param source The source entity of the explosion - * @param power The power of explosion, where 4F is TNT - * @return false if explosion was canceled, otherwise true - */ - public default boolean createExplosion(@NotNull Entity source, float power) { - return createExplosion(source, source.getLocation(), power, true, true); - } - // Paper end - - /** - * Creates explosion at given coordinates with given power and optionally - * setting blocks on fire or breaking blocks. - * - * @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 - * @param breakBlocks Whether or not to have blocks be destroyed - * @return false if explosion was canceled, otherwise true - */ - public boolean createExplosion(@NotNull Location loc, float power, boolean setFire, boolean breakBlocks); - - /** - * Creates explosion at given coordinates with given power and optionally - * setting blocks on fire or breaking blocks. - * - * @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 - * @param breakBlocks Whether or not to have blocks be destroyed - * @param source the source entity, used for tracking damage - * @return false if explosion was canceled, otherwise true - */ - public boolean createExplosion(@NotNull Location loc, float power, boolean setFire, boolean breakBlocks, @Nullable Entity source); - - /** - * Gets the {@link Environment} type of this world - * - * @return This worlds Environment type - */ - @NotNull - public Environment getEnvironment(); - - /** - * Gets the Seed for this world. - * - * @return This worlds Seed - */ - public long getSeed(); - - /** - * Gets the current PVP setting for this world. - * - * @return True if PVP is enabled - */ - public boolean getPVP(); - - /** - * Sets the PVP setting for this world. - * - * @param pvp True/False whether PVP should be Enabled. - */ - public void setPVP(boolean pvp); - - /** - * Gets the chunk generator for this world - * - * @return ChunkGenerator associated with this world - */ - @Nullable - public ChunkGenerator getGenerator(); - - /** - * Saves world to disk - */ - public void save(); - - /** - * Gets a list of all applied {@link BlockPopulator}s for this World - * - * @return List containing any or none BlockPopulators - */ - @NotNull - public 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 - */ - @NotNull - public T spawn(@NotNull Location location, @NotNull Class clazz) throws IllegalArgumentException; - - /** - * Spawn an entity of a specific class at the given {@link Location}, with - * the supplied function run before the entity is added to the world. - *
- * Note that when the function is run, the entity will not be actually in - * the world. Any operation involving such as teleporting the entity is undefined - * until after this function returns. - * - * @param location the {@link Location} to spawn the entity at - * @param clazz the class of the {@link Entity} to spawn - * @param function the function to be run before the entity is spawned. - * @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 - */ - @NotNull - public T spawn(@NotNull Location location, @NotNull Class clazz, @Nullable Consumer function) 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 data The block data - * @return The spawned {@link FallingBlock} instance - * @throws IllegalArgumentException if {@link Location} or {@link - * MaterialData} are null or {@link Material} of the {@link MaterialData} is not a block - */ - @NotNull - public FallingBlock spawnFallingBlock(@NotNull Location location, @NotNull MaterialData data) 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 data The block data - * @return The spawned {@link FallingBlock} instance - * @throws IllegalArgumentException if {@link Location} or {@link - * BlockData} are null - */ - @NotNull - public FallingBlock spawnFallingBlock(@NotNull Location location, @NotNull BlockData data) 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 - @NotNull - public FallingBlock spawnFallingBlock(@NotNull Location location, @NotNull Material material, byte data) 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 - */ - public void playEffect(@NotNull Location location, @NotNull 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 - */ - public void playEffect(@NotNull Location location, @NotNull 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 - */ - public void playEffect(@NotNull Location location, @NotNull Effect effect, @Nullable 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 - */ - public void playEffect(@NotNull Location location, @NotNull Effect effect, @Nullable 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 includeBiomeTemp - if true, snapshot includes per-coordinate - * raw biome temperature - * @return The empty snapshot. - */ - @NotNull - public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTemp); - - /** - * 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. - */ - public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals); - - /** - * Gets whether animals can spawn in this world. - * - * @return whether animals can spawn in this world. - */ - public boolean getAllowAnimals(); - - /** - * Gets whether monsters can spawn in this world. - * - * @return whether monsters can spawn in this world. - */ - public 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 - */ - @NotNull - 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, @NotNull 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. - *

- * This method will return the raw temperature without adjusting for block - * height effects. - * - * @param x X coordinate of the block - * @param z Z coordinate of the block - * @return Temperature of the requested block - */ - public 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 - */ - public 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 - */ - public int getMaxHeight(); - - /** - * Gets the sea level for this world. - *

- * This is often half of {@link #getMaxHeight()} - * - * @return Sea level - */ - public 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. - */ - public 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. - */ - public void setKeepSpawnInMemory(boolean keepLoaded); - - /** - * Gets whether or not the world will automatically save - * - * @return true if the world will automatically save, otherwise false - */ - public boolean isAutoSave(); - - /** - * Sets whether or not the world will automatically save - * - * @param value true if the world should automatically save, otherwise - * false - */ - public void setAutoSave(boolean value); - - /** - * Sets the Difficulty of the world. - * - * @param difficulty the new difficulty you want to set the world to - */ - public void setDifficulty(@NotNull Difficulty difficulty); - - /** - * Gets the Difficulty of the world. - * - * @return The difficulty of the world. - */ - @NotNull - public Difficulty getDifficulty(); - - /** - * Gets the folder of this world on disk. - * - * @return The folder of this world. - */ - @NotNull - public File getWorldFolder(); - - /** - * Gets the type of this world. - * - * @return Type of this world. - */ - @Nullable - public WorldType getWorldType(); - - /** - * Gets whether or not structures are being generated. - * - * @return True if structures are being generated. - */ - public 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 - */ - public 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 - */ - public 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 - */ - public 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 - */ - public 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(@NotNull Location location, @NotNull Sound sound, float volume, float pitch); - - /** - * Play a Sound at the provided Location in the World. - *

- * This function will fail silently if Location or Sound are null. No - * sound will be heard by the players if their clients do 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(@NotNull Location location, @NotNull String sound, float volume, float pitch); - - /** - * 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 category the category of the sound - * @param volume The volume of the sound - * @param pitch The pitch of the sound - */ - void playSound(@NotNull Location location, @NotNull Sound sound, @NotNull SoundCategory category, float volume, float pitch); - - /** - * Play a Sound at the provided Location in the World. - *

- * This function will fail silently if Location or Sound are null. No sound - * will be heard by the players if their clients do 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 category the category of the sound - * @param volume the volume of the sound - * @param pitch the pitch of the sound - */ - void playSound(@NotNull Location location, @NotNull String sound, @NotNull SoundCategory category, float volume, float pitch); - - /** - * Get an array containing the names of all the {@link GameRule}s. - * - * @return An array of {@link GameRule} names. - */ - @NotNull - public 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 - * @deprecated use {@link #getGameRuleValue(GameRule)} instead - */ - @Deprecated - @Contract("null -> null; !null -> !null") - @Nullable - public String getGameRuleValue(@Nullable 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 - * @deprecated use {@link #setGameRule(GameRule, Object)} instead. - */ - @Deprecated - public boolean setGameRuleValue(@NotNull String rule, @NotNull String value); - - /** - * Checks if string is a valid game rule - * - * @param rule Rule to check - * @return True if rule exists - */ - public boolean isGameRule(@NotNull String rule); - - /** - * Get the current value for a given {@link GameRule}. - * - * @param rule the GameRule to check - * @param the GameRule's type - * @return the current value - */ - @Nullable - public T getGameRuleValue(@NotNull GameRule rule); - - /** - * Get the default value for a given {@link GameRule}. This value is not - * guaranteed to match the current value. - * - * @param rule the rule to return a default value for - * @param the type of GameRule - * @return the default value - */ - @Nullable - public T getGameRuleDefault(@NotNull GameRule rule); - - /** - * Set the given {@link GameRule}'s new value. - * - * @param rule the GameRule to update - * @param newValue the new value - * @param the value type of the GameRule - * @return true if the value was successfully set - */ - public boolean setGameRule(@NotNull GameRule rule, @NotNull T newValue); - - /** - * Gets the world border for this world. - * - * @return The world border for this world. - */ - @NotNull - public WorldBorder getWorldBorder(); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. - * - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. - * - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, @Nullable T data); - - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, @Nullable T data); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ, @Nullable T data); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, @Nullable T data); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ, double extra); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, @Nullable T data); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public default void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, @Nullable T data) { spawnParticle(particle, null, null, x, y, z, count, offsetX, offsetY, offsetZ, extra, data, true); }// Paper start - Expand Particle API - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param receivers List of players to receive the particles, or null for all in world - * @param source Source of the particles to be used in visibility checks, or null if no player source - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public default void spawnParticle(@NotNull Particle particle, @Nullable List receivers, @NotNull Player source, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, @Nullable T data) { spawnParticle(particle, receivers, source, x, y, z, count, offsetX, offsetY, offsetZ, extra, data, true); } - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param receivers List of players to receive the particles, or null for all in world - * @param source Source of the particles to be used in visibility checks, or null if no player source - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - * @param force allows the particle to be seen further away from the player - * and shows to players using any vanilla client particle settings - */ - public void spawnParticle(@NotNull Particle particle, @Nullable List receivers, @Nullable Player source, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, @Nullable T data, boolean force); - // Paper end - - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param force whether to send the particle to players within an extended - * range and encourage their client to render it regardless of - * settings - * @param Particle data type - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, @Nullable T data, boolean force); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param force whether to send the particle to players within an extended - * range and encourage their client to render it regardless of - * settings - * @param Particle data type - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, @Nullable T data, boolean force); - - /** - * Find the closest nearby structure of a given {@link StructureType}. - * Finding unexplored structures can, and will, block if the world is - * looking in chunks that gave not generated yet. This can lead to the world - * temporarily freezing while locating an unexplored structure. - *

- * The {@code radius} is not a rigid square radius. Each structure may alter - * how many chunks to check for each iteration. Do not assume that only a - * radius x radius chunk area will be checked. For example, - * {@link StructureType#WOODLAND_MANSION} can potentially check up to 20,000 - * blocks away (or more) regardless of the radius used. - *

- * This will not load or generate chunks. This can also lead to - * instances where the server can hang if you are only looking for - * unexplored structures. This is because it will keep looking further and - * further out in order to find the structure. - * - * @param origin where to start looking for a structure - * @param structureType the type of structure to find - * @param radius the radius, in chunks, around which to search - * @param findUnexplored true to only find unexplored structures - * @return the closest {@link Location}, or null if no structure of the - * specified type exists. - */ - @Nullable - public Location locateNearestStructure(@NotNull Location origin, @NotNull StructureType structureType, int radius, boolean findUnexplored); - - // Spigot start - /** - * Returns the view distance used for this world. - * - * @return the view distance used for this world - */ - int getViewDistance(); - // Spigot end - - // Spigot start - public class Spigot - { - - /** - * 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. - */ - @NotNull - public LightningStrike strikeLightning(@NotNull 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. - */ - @NotNull - public LightningStrike strikeLightningEffect(@NotNull Location loc, boolean isSilent) - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - } - - @NotNull - Spigot spigot(); - // Spigot end - - /** - * Finds the nearest raid close to the given location. - * - * @param location the origin location - * @param radius the radius - * @return the closest {@link Raid}, or null if no raids were found - */ - @Nullable - public Raid locateNearestRaid(@NotNull Location location, int radius); - - /** - * Gets all raids that are going on over this world. - * - * @return the list of all active raids - */ - @NotNull - public List getRaids(); - - /** - * Represents various map environment types that a world may be - */ - public 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(); - - private 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 - @Nullable - public static Environment getEnvironment(int id) { - return lookup.get(id); - } - - static { - for (Environment env : values()) { - lookup.put(env.getId(), env); - } - } - } -} diff --git a/api/src/main/java/org/bukkit/WorldBorder.java b/api/src/main/java/org/bukkit/WorldBorder.java deleted file mode 100644 index afb7b136b..000000000 --- a/api/src/main/java/org/bukkit/WorldBorder.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.bukkit; - -import org.jetbrains.annotations.NotNull; - -public interface WorldBorder { - - /** - * Resets the border to default values. - */ - public void reset(); - - /** - * Gets the current side length of the border. - * - * @return The current side length of the border. - */ - public double getSize(); - - /** - * Sets the border to a square region with the specified side length in blocks. - * - * @param newSize The new size of the border. - */ - public 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. - */ - public void setSize(double newSize, long seconds); - - /** - * Gets the current border center. - * - * @return The current border center. - */ - @NotNull - public Location getCenter(); - - /** - * Sets the new border center. - * - * @param x The new center x-coordinate. - * @param z The new center z-coordinate. - */ - public void setCenter(double x, double z); - - /** - * Sets the new border center. - * - * @param location The new location of the border center. (Only x/z used) - */ - public void setCenter(@NotNull Location location); - - /** - * Gets the current border damage buffer. - * - * @return The current border damage buffer. - */ - public 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.) - */ - public void setDamageBuffer(double blocks); - - /** - * Gets the current border damage amount. - * - * @return The current border damage amount. - */ - public 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.) - */ - public void setDamageAmount(double damage); - - /** - * Gets the current border warning time in seconds. - * - * @return The current border warning time in seconds. - */ - public 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.) - */ - public void setWarningTime(int seconds); - - /** - * Gets the current border warning distance. - * - * @return The current border warning distance. - */ - public 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.) - */ - public void setWarningDistance(int distance); - - /** - * Check if the specified location is inside this border. - * - * @param location the location to check - * @return if this location is inside the border or not - */ - public boolean isInside(@NotNull Location location); - - // Paper start - /** - * Checks if the location is within the boundaries of this border. - * - * @param location specific location to check - * @return true if the location is within the bounds of this border, false otherwise. - * @deprecated use {@link #isInside(Location)} for an upstream compatible replacement - */ - @Deprecated - public default boolean isInBounds(@NotNull Location location) { - return this.isInside(location); - } - // Paper end -} diff --git a/api/src/main/java/org/bukkit/WorldCreator.java b/api/src/main/java/org/bukkit/WorldCreator.java deleted file mode 100644 index 435fce5b0..000000000 --- a/api/src/main/java/org/bukkit/WorldCreator.java +++ /dev/null @@ -1,342 +0,0 @@ -package org.bukkit; - -import java.util.Random; -import org.bukkit.command.CommandSender; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull 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 - */ - @NotNull - public WorldCreator copy(@NotNull World world) { - if (world == null) { - throw new IllegalArgumentException("World cannot be null"); - } - - seed = world.getSeed(); - environment = world.getEnvironment(); - generator = world.getGenerator(); - type = world.getWorldType(); - generateStructures = world.canGenerateStructures(); - - return this; - } - - /** - * Copies the options from the specified {@link WorldCreator} - * - * @param creator World creator to copy options from - * @return This object, for chaining - */ - @NotNull - public WorldCreator copy(@NotNull WorldCreator creator) { - if (creator == null) { - throw new IllegalArgumentException("Creator cannot be null"); - } - - seed = creator.seed(); - environment = creator.environment(); - generator = creator.generator(); - type = creator.type(); - generateStructures = creator.generateStructures(); - generatorSettings = creator.generatorSettings(); - - return this; - } - - /** - * Gets the name of the world that is to be loaded or created. - * - * @return World name - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - public WorldCreator environment(@NotNull World.Environment env) { - this.environment = env; - - return this; - } - - /** - * Gets the type of the world that will be created or loaded - * - * @return World type - */ - @NotNull - 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 - */ - @NotNull - public WorldCreator type(@NotNull 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 - */ - @Nullable - 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 - */ - @NotNull - public WorldCreator generator(@Nullable 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 - */ - @NotNull - public WorldCreator generator(@Nullable 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 - */ - @NotNull - public WorldCreator generator(@Nullable String generator, @Nullable 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 - */ - @NotNull - public WorldCreator generatorSettings(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @Nullable - 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 - */ - @NotNull - public static WorldCreator name(@NotNull 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 - */ - @Nullable - public static ChunkGenerator getGeneratorForName(@NotNull String world, @Nullable String name, @Nullable 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/api/src/main/java/org/bukkit/WorldType.java b/api/src/main/java/org/bukkit/WorldType.java deleted file mode 100644 index f98b13e71..000000000 --- a/api/src/main/java/org/bukkit/WorldType.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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"), - BUFFET("BUFFET"); - - private static final Map BY_NAME = Maps.newHashMap(); - private final String name; - - private WorldType(/*@NotNull*/ String name) { - this.name = name; - } - - /** - * Gets the name of this WorldType - * - * @return Name of this type - */ - @NotNull - 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 - */ - @Nullable - public static WorldType getByName(@NotNull String name) { - return BY_NAME.get(name.toUpperCase(java.util.Locale.ENGLISH)); - } - - static { - for (WorldType type : values()) { - BY_NAME.put(type.name, type); - } - } -} diff --git a/api/src/main/java/org/bukkit/advancement/Advancement.java b/api/src/main/java/org/bukkit/advancement/Advancement.java deleted file mode 100644 index 7c5009974..000000000 --- a/api/src/main/java/org/bukkit/advancement/Advancement.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bukkit.advancement; - -import java.util.Collection; -import org.bukkit.Keyed; -import org.jetbrains.annotations.NotNull; - -/** - * Represents an advancement that may be awarded to a player. This class is not - * reference safe as the underlying advancement may be reloaded. - */ -public interface Advancement extends Keyed { - - /** - * Get all the criteria present in this advancement. - * - * @return a unmodifiable copy of all criteria - */ - @NotNull - Collection getCriteria(); -} diff --git a/api/src/main/java/org/bukkit/advancement/AdvancementProgress.java b/api/src/main/java/org/bukkit/advancement/AdvancementProgress.java deleted file mode 100644 index f9bc179da..000000000 --- a/api/src/main/java/org/bukkit/advancement/AdvancementProgress.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.bukkit.advancement; - -import java.util.Collection; -import java.util.Date; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * The individual status of an advancement for a player. This class is not - * reference safe as the underlying advancement may be reloaded. - */ -public interface AdvancementProgress { - - /** - * The advancement this progress is concerning. - * - * @return the relevant advancement - */ - @NotNull - Advancement getAdvancement(); - - /** - * Check if all criteria for this advancement have been met. - * - * @return true if this advancement is done - */ - boolean isDone(); - - /** - * Mark the specified criteria as awarded at the current time. - * - * @param criteria the criteria to mark - * @return true if awarded, false if criteria does not exist or already - * awarded. - */ - boolean awardCriteria(@NotNull String criteria); - - /** - * Mark the specified criteria as uncompleted. - * - * @param criteria the criteria to mark - * @return true if removed, false if criteria does not exist or not awarded - */ - boolean revokeCriteria(@NotNull String criteria); - - /** - * Get the date the specified criteria was awarded. - * - * @param criteria the criteria to check - * @return date awarded or null if unawarded or criteria does not exist - */ - @Nullable - Date getDateAwarded(@NotNull String criteria); - - /** - * Get the criteria which have not been awarded. - * - * @return unmodifiable copy of criteria remaining - */ - @NotNull - Collection getRemainingCriteria(); - - /** - * Gets the criteria which have been awarded. - * - * @return unmodifiable copy of criteria awarded - */ - @NotNull - Collection getAwardedCriteria(); -} diff --git a/api/src/main/java/org/bukkit/attribute/Attributable.java b/api/src/main/java/org/bukkit/attribute/Attributable.java deleted file mode 100644 index 0ed96b5af..000000000 --- a/api/src/main/java/org/bukkit/attribute/Attributable.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bukkit.attribute; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents an object which may contain attributes. - */ -public interface Attributable { - - /** - * Gets the specified attribute instance from the object. This instance will - * be backed directly to the object and any changes will be visible at once. - * - * @param attribute the attribute to get - * @return the attribute instance or null if not applicable to this object - */ - @Nullable - AttributeInstance getAttribute(@NotNull Attribute attribute); -} diff --git a/api/src/main/java/org/bukkit/attribute/Attribute.java b/api/src/main/java/org/bukkit/attribute/Attribute.java deleted file mode 100644 index b282dc863..000000000 --- a/api/src/main/java/org/bukkit/attribute/Attribute.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.attribute; - -/** - * Types of attributes which may be present on an {@link Attributable}. - */ -public enum Attribute { - - /** - * Maximum health of an Entity. - */ - GENERIC_MAX_HEALTH, - /** - * Range at which an Entity will follow others. - */ - GENERIC_FOLLOW_RANGE, - /** - * Resistance of an Entity to knockback. - */ - GENERIC_KNOCKBACK_RESISTANCE, - /** - * Movement speed of an Entity. - */ - GENERIC_MOVEMENT_SPEED, - /** - * Flying speed of an Entity. - */ - GENERIC_FLYING_SPEED, - /** - * Attack damage of an Entity. - */ - GENERIC_ATTACK_DAMAGE, - /** - * Attack speed of an Entity. - */ - GENERIC_ATTACK_SPEED, - /** - * Armor bonus of an Entity. - */ - GENERIC_ARMOR, - /** - * Armor durability bonus of an Entity. - */ - GENERIC_ARMOR_TOUGHNESS, - /** - * Luck bonus of an Entity. - */ - GENERIC_LUCK, - /** - * Strength with which a horse will jump. - */ - HORSE_JUMP_STRENGTH, - /** - * Chance of a zombie to spawn reinforcements. - */ - ZOMBIE_SPAWN_REINFORCEMENTS; -} diff --git a/api/src/main/java/org/bukkit/attribute/AttributeInstance.java b/api/src/main/java/org/bukkit/attribute/AttributeInstance.java deleted file mode 100644 index f08ee26cc..000000000 --- a/api/src/main/java/org/bukkit/attribute/AttributeInstance.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.bukkit.attribute; - -import java.util.Collection; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a mutable instance of an attribute and its associated modifiers - * and values. - */ -public interface AttributeInstance { - - /** - * The attribute pertaining to this instance. - * - * @return the attribute - */ - @NotNull - Attribute getAttribute(); - - /** - * Base value of this instance before modifiers are applied. - * - * @return base value - */ - double getBaseValue(); - - /** - * Set the base value of this instance. - * - * @param value new base value - */ - void setBaseValue(double value); - - /** - * Get all modifiers present on this instance. - * - * @return a copied collection of all modifiers - */ - @NotNull - Collection getModifiers(); - - /** - * Add a modifier to this instance. - * - * @param modifier to add - */ - void addModifier(@NotNull AttributeModifier modifier); - - /** - * Remove a modifier from this instance. - * - * @param modifier to remove - */ - void removeModifier(@NotNull AttributeModifier modifier); - - /** - * Get the value of this instance after all associated modifiers have been - * applied. - * - * @return the total attribute value - */ - double getValue(); - - /** - * Gets the default value of the Attribute attached to this instance. - * - * @return server default value - */ - double getDefaultValue(); -} diff --git a/api/src/main/java/org/bukkit/attribute/AttributeModifier.java b/api/src/main/java/org/bukkit/attribute/AttributeModifier.java deleted file mode 100644 index f0dff145a..000000000 --- a/api/src/main/java/org/bukkit/attribute/AttributeModifier.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.bukkit.attribute; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import org.apache.commons.lang.Validate; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.util.NumberConversions; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Concrete implementation of an attribute modifier. - */ -public class AttributeModifier implements ConfigurationSerializable { - - private final UUID uuid; - private final String name; - private final double amount; - private final Operation operation; - private final EquipmentSlot slot; - - public AttributeModifier(@NotNull String name, double amount, @NotNull Operation operation) { - this(UUID.randomUUID(), name, amount, operation); - } - - public AttributeModifier(@NotNull UUID uuid, @NotNull String name, double amount, @NotNull Operation operation) { - this(uuid, name, amount, operation, null); - } - - public AttributeModifier(@NotNull UUID uuid, @NotNull String name, double amount, @NotNull Operation operation, @Nullable EquipmentSlot slot) { - Validate.notNull(uuid, "UUID cannot be null"); - //Validate.notEmpty(name, "Name cannot be empty"); // Paper - Validate.notNull(operation, "Operation cannot be null"); - this.uuid = uuid; - this.name = name != null ? name : ""; // Paper - this.amount = amount; - this.operation = operation; - this.slot = slot; - } - - /** - * Get the unique ID for this modifier. - * - * @return unique id - */ - @NotNull - public UUID getUniqueId() { - return uuid; - } - - /** - * Get the name of this modifier. - * - * @return name - */ - @NotNull - public String getName() { - return name; - } - - /** - * Get the amount by which this modifier will apply its {@link Operation}. - * - * @return modification amount - */ - public double getAmount() { - return amount; - } - - /** - * Get the operation this modifier will apply. - * - * @return operation - */ - @NotNull - public Operation getOperation() { - return operation; - } - - /** - * Get the {@link EquipmentSlot} this AttributeModifier is active on, - * or null if this modifier is applicable for any slot. - * - * @return the slot - */ - @Nullable - public EquipmentSlot getSlot() { - return slot; - } - - @NotNull - @Override - public Map serialize() { - Map data = new HashMap(); - data.put("uuid", uuid.toString()); - data.put("name", name); - data.put("operation", operation.ordinal()); - data.put("amount", amount); - if (slot != null) { - data.put("slot", slot.name()); - } - return data; - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof AttributeModifier)) { - return false; - } - AttributeModifier mod = (AttributeModifier) other; - boolean slots = (this.slot != null ? (this.slot == mod.slot) : mod.slot == null); - return this.uuid.equals(mod.uuid) && this.name.equals(mod.name) && this.amount == mod.amount && this.operation == mod.operation && slots; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 17 * hash + Objects.hashCode(this.uuid); - hash = 17 * hash + Objects.hashCode(this.name); - hash = 17 * hash + (int) (Double.doubleToLongBits(this.amount) ^ (Double.doubleToLongBits(this.amount) >>> 32)); - hash = 17 * hash + Objects.hashCode(this.operation); - hash = 17 * hash + Objects.hashCode(this.slot); - return hash; - } - - @Override - public String toString() { - return "AttributeModifier{" - + "uuid=" + this.uuid.toString() - + ", name=" + this.name - + ", operation=" + this.operation.name() - + ", amount=" + this.amount - + ", slot=" + (this.slot != null ? this.slot.name() : "") - + "}"; - } - - @NotNull - public static AttributeModifier deserialize(@NotNull Map args) { - if (args.containsKey("slot")) { - return new AttributeModifier(UUID.fromString((String) args.get("uuid")), (String) args.get("name"), NumberConversions.toDouble(args.get("amount")), Operation.values()[NumberConversions.toInt(args.get("operation"))], EquipmentSlot.valueOf((args.get("slot").toString().toUpperCase()))); - } - return new AttributeModifier(UUID.fromString((String) args.get("uuid")), (String) args.get("name"), NumberConversions.toDouble(args.get("amount")), Operation.values()[NumberConversions.toInt(args.get("operation"))]); - } - - /** - * Enumerable operation to be applied. - */ - public enum Operation { - - /** - * Adds (or subtracts) the specified amount to the base value. - */ - ADD_NUMBER, - /** - * Adds this scalar of amount to the base value. - */ - ADD_SCALAR, - /** - * Multiply amount by this value, after adding 1 to it. - */ - MULTIPLY_SCALAR_1; - } -} diff --git a/api/src/main/java/org/bukkit/block/Banner.java b/api/src/main/java/org/bukkit/block/Banner.java deleted file mode 100644 index e6eb3c04b..000000000 --- a/api/src/main/java/org/bukkit/block/Banner.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.bukkit.block; - -import java.util.List; -import org.bukkit.DyeColor; -import org.bukkit.block.banner.Pattern; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of a banner. - */ -public interface Banner extends TileState { - - /** - * Returns the base color for this banner - * - * @return the base color - */ - @NotNull - DyeColor getBaseColor(); - - /** - * Sets the base color for this banner. - * Only valid for shield pseudo banners, otherwise base depends on block - * type - * - * @param color the base color - */ - void setBaseColor(@NotNull DyeColor color); - - /** - * Returns a list of patterns on this banner - * - * @return the patterns - */ - @NotNull - List getPatterns(); - - /** - * Sets the patterns used on this banner - * - * @param patterns the new list of patterns - */ - void setPatterns(@NotNull List patterns); - - /** - * Adds a new pattern on top of the existing - * patterns - * - * @param pattern the new pattern to add - */ - void addPattern(@NotNull Pattern pattern); - - /** - * Returns the pattern at the specified index - * - * @param i the index - * @return the pattern - */ - @NotNull - Pattern getPattern(int i); - - /** - * Removes the pattern at the specified index - * - * @param i the index - * @return the removed pattern - */ - @NotNull - Pattern removePattern(int i); - - /** - * Sets the pattern at the specified index - * - * @param i the index - * @param pattern the new pattern - */ - void setPattern(int i, @NotNull Pattern pattern); - - /** - * Returns the number of patterns on this - * banner - * - * @return the number of patterns - */ - int numberOfPatterns(); -} diff --git a/api/src/main/java/org/bukkit/block/Barrel.java b/api/src/main/java/org/bukkit/block/Barrel.java deleted file mode 100644 index 5eacc44ac..000000000 --- a/api/src/main/java/org/bukkit/block/Barrel.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.loot.Lootable; - -/** - * Represents a captured state of a Barrel. - */ -public interface Barrel extends Container, Lootable { } diff --git a/api/src/main/java/org/bukkit/block/Beacon.java b/api/src/main/java/org/bukkit/block/Beacon.java deleted file mode 100644 index 6349fa9da..000000000 --- a/api/src/main/java/org/bukkit/block/Beacon.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bukkit.block; - -import java.util.Collection; -import org.bukkit.Nameable; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a captured state of a beacon. - */ -public interface Beacon extends TileState, Lockable, Nameable { - - /** - * Returns the list of players within the beacon's range of effect. - *

- * This will return an empty list if the block represented by this state is - * no longer a beacon. - * - * @return the players in range - * @throws IllegalStateException if this block state is not placed - */ - @NotNull - Collection getEntitiesInRange(); - - /** - * Returns the tier of the beacon pyramid (0-4). The tier refers to the - * beacon's power level, based on how many layers of blocks are in the - * pyramid. Tier 1 refers to a beacon with one layer of 9 blocks under it. - * - * @return the beacon tier - */ - int getTier(); - - /** - * Returns the primary effect set on the beacon - * - * @return the primary effect or null if not set - */ - @Nullable - PotionEffect getPrimaryEffect(); - - /** - * Set the primary effect on this beacon, or null to clear. - * - * @param effect new primary effect - */ - void setPrimaryEffect(@Nullable PotionEffectType effect); - - /** - * Returns the secondary effect set on the beacon. - * - * @return the secondary effect or null if no secondary effect - */ - @Nullable - PotionEffect getSecondaryEffect(); - - /** - * Set the secondary effect on this beacon, or null to clear. Note that tier - * must be >= 4 for this effect to be active. - * - * @param effect desired secondary effect - */ - void setSecondaryEffect(@Nullable PotionEffectType effect); -} diff --git a/api/src/main/java/org/bukkit/block/Bed.java b/api/src/main/java/org/bukkit/block/Bed.java deleted file mode 100644 index f9bd74f9c..000000000 --- a/api/src/main/java/org/bukkit/block/Bed.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.material.Colorable; - -/** - * Represents a captured state of a bed. - * @deprecated does not provide useful information beyond the material itself - */ -@Deprecated -public interface Bed extends TileState, Colorable { } diff --git a/api/src/main/java/org/bukkit/block/Bell.java b/api/src/main/java/org/bukkit/block/Bell.java deleted file mode 100644 index 6fee356a3..000000000 --- a/api/src/main/java/org/bukkit/block/Bell.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.block; - -/** - * Represents a captured state of Bell. - */ -public interface Bell extends TileState { } diff --git a/api/src/main/java/org/bukkit/block/Biome.java b/api/src/main/java/org/bukkit/block/Biome.java deleted file mode 100644 index 55386ffe0..000000000 --- a/api/src/main/java/org/bukkit/block/Biome.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.bukkit.block; - -import java.util.Locale; -import org.bukkit.Keyed; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -/** - * Holds all accepted Biomes in the default server - */ -public enum Biome implements Keyed { - OCEAN, - PLAINS, - DESERT, - MOUNTAINS, - FOREST, - TAIGA, - SWAMP, - RIVER, - NETHER, - THE_END, - FROZEN_OCEAN, - FROZEN_RIVER, - SNOWY_TUNDRA, - SNOWY_MOUNTAINS, - MUSHROOM_FIELDS, - MUSHROOM_FIELD_SHORE, - BEACH, - DESERT_HILLS, - WOODED_HILLS, - TAIGA_HILLS, - MOUNTAIN_EDGE, - JUNGLE, - JUNGLE_HILLS, - JUNGLE_EDGE, - DEEP_OCEAN, - STONE_SHORE, - SNOWY_BEACH, - BIRCH_FOREST, - BIRCH_FOREST_HILLS, - DARK_FOREST, - SNOWY_TAIGA, - SNOWY_TAIGA_HILLS, - GIANT_TREE_TAIGA, - GIANT_TREE_TAIGA_HILLS, - WOODED_MOUNTAINS, - SAVANNA, - SAVANNA_PLATEAU, - BADLANDS, - WOODED_BADLANDS_PLATEAU, - BADLANDS_PLATEAU, - SMALL_END_ISLANDS, - END_MIDLANDS, - END_HIGHLANDS, - END_BARRENS, - WARM_OCEAN, - LUKEWARM_OCEAN, - COLD_OCEAN, - DEEP_WARM_OCEAN, - DEEP_LUKEWARM_OCEAN, - DEEP_COLD_OCEAN, - DEEP_FROZEN_OCEAN, - THE_VOID, - SUNFLOWER_PLAINS, - DESERT_LAKES, - GRAVELLY_MOUNTAINS, - FLOWER_FOREST, - TAIGA_MOUNTAINS, - SWAMP_HILLS, - ICE_SPIKES, - MODIFIED_JUNGLE, - MODIFIED_JUNGLE_EDGE, - TALL_BIRCH_FOREST, - TALL_BIRCH_HILLS, - DARK_FOREST_HILLS, - SNOWY_TAIGA_MOUNTAINS, - GIANT_SPRUCE_TAIGA, - GIANT_SPRUCE_TAIGA_HILLS, - MODIFIED_GRAVELLY_MOUNTAINS, - SHATTERED_SAVANNA, - SHATTERED_SAVANNA_PLATEAU, - ERODED_BADLANDS, - MODIFIED_WOODED_BADLANDS_PLATEAU, - MODIFIED_BADLANDS_PLATEAU, - BAMBOO_JUNGLE, - BAMBOO_JUNGLE_HILLS; - - private final NamespacedKey key; - - private Biome() { - this.key = NamespacedKey.minecraft(name().toLowerCase(Locale.ROOT)); - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } -} diff --git a/api/src/main/java/org/bukkit/block/BlastFurnace.java b/api/src/main/java/org/bukkit/block/BlastFurnace.java deleted file mode 100644 index 3c4d8571b..000000000 --- a/api/src/main/java/org/bukkit/block/BlastFurnace.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.block; - -/** - * Represents a captured state of a blast furnace. - */ -public interface BlastFurnace extends Furnace { } diff --git a/api/src/main/java/org/bukkit/block/Block.java b/api/src/main/java/org/bukkit/block/Block.java deleted file mode 100644 index 038de5a64..000000000 --- a/api/src/main/java/org/bukkit/block/Block.java +++ /dev/null @@ -1,543 +0,0 @@ -package org.bukkit.block; - -import java.util.Collection; - -import org.bukkit.Chunk; -import org.bukkit.FluidCollisionMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; -import org.bukkit.metadata.Metadatable; -import org.bukkit.util.BoundingBox; -import org.bukkit.util.RayTraceResult; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - * - *
- * Note that parts of this class which require access to the world at large - * (i.e. lighting and power) may not be able to be safely accessed during world - * generation when used in cases like BlockPhysicsEvent!!!! - */ -public interface Block extends Metadatable { - - /** - * Gets the metadata for this block - * - * @return block specific metadata - * @deprecated Magic value - */ - @Deprecated - byte getData(); - - /** - * Gets the complete block data for this block - * - * @return block specific data - */ - @NotNull - BlockData getBlockData(); - - /** - * 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 - */ - @NotNull - 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) - */ - @NotNull - Block getRelative(@NotNull 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 - */ - @NotNull - Block getRelative(@NotNull BlockFace face, int distance); - - /** - * Gets the type of this block - * - * @return block type - */ - @NotNull - Material getType(); - - /** - * 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 - */ - @NotNull - 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(); - - // Paper Start - /** - * Returns this block's coordinates packed into a long value. - * Computed via: {@code Block.getBlockKey(this.getX(), this.getY(), this.getZ())} - * @see Block#getBlockKey(int, int, int) - * @return This block's x, y, and z coordinates packed into a long value - */ - public default long getBlockKey() { - return Block.getBlockKey(this.getX(), this.getY(), this.getZ()); - } - - /** - * Returns the specified block coordinates packed into a long value - *

- * The return value can be computed as follows: - *
- * {@code long value = ((long)x & 0x7FFFFFF) | (((long)z & 0x7FFFFFF) << 27) | ((long)y << 54);} - *

- * - *

- * And may be unpacked as follows: - *
- * {@code int x = (int) ((packed << 37) >> 37);} - *
- * {@code int y = (int) (packed >>> 54);} - *
- * {@code int z = (int) ((packed << 10) >> 37);} - *

- * - * @return This block's x, y, and z coordinates packed into a long value - */ - public static long getBlockKey(int x, int y, int z) { - return ((long)x & 0x7FFFFFF) | (((long)z & 0x7FFFFFF) << 27) | ((long)y << 54); - } - - /** - * Returns the x component from the packed value. - * @param packed The packed value, as computed by {@link Block#getBlockKey(int, int, int)} - * @see Block#getBlockKey(int, int, int) - * @return The x component from the packed value. - */ - public static int getBlockKeyX(long packed) { - return (int) ((packed << 37) >> 37); - } - - /** - * Returns the y component from the packed value. - * @param packed The packed value, as computed by {@link Block#getBlockKey(int, int, int)} - * @see Block#getBlockKey(int, int, int) - * @return The y component from the packed value. - */ - public static int getBlockKeyY(long packed) { - return (int) (packed >>> 54); - } - - /** - * Returns the z component from the packed value. - * @param packed The packed value, as computed by {@link Block#getBlockKey(int, int, int)} - * @see Block#getBlockKey(int, int, int) - * @return The z component from the packed value. - */ - public static int getBlockKeyZ(long packed) { - return (int) ((packed << 10) >> 37); - } - // Paper End - - /** - * Gets the Location of the block - * - * @return Location of block - */ - @NotNull - 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 - */ - @Contract("null -> null; !null -> !null") - @Nullable - Location getLocation(@Nullable Location loc); - - /** - * Gets the chunk which contains this block - * - * @return Containing Chunk - */ - @NotNull - Chunk getChunk(); - - /** - * Sets the complete data for this block - * - * @param data new block specific data - */ - void setBlockData(@NotNull BlockData data); - - /** - * Sets the complete data for this block - * - *
- * Note that applyPhysics = false is not in general safe. It should only be - * used when you need to avoid triggering a physics update of neighboring - * blocks, for example when creating a {@link Bisected} block. If you are - * using a custom populator, then this parameter may also be required to - * prevent triggering infinite chunk loads on border blocks. This method - * should NOT be used to "hack" physics by placing blocks in impossible - * locations. Such blocks are liable to be removed on various events such as - * world upgrades. Furthermore setting large amounts of such blocks in close - * proximity may overload the server physics engine if an update is - * triggered at a later point. If this occurs, the resulting behavior is - * undefined. - * - * @param data new block specific data - * @param applyPhysics false to cancel physics from the changed block - */ - void setBlockData(@NotNull BlockData data, boolean applyPhysics); - - /** - * Sets the type of this block - * - * @param type Material to change this block to - */ - void setType(@NotNull Material type); - - /** - * Sets the type of this block - * - *
- * Note that applyPhysics = false is not in general safe. It should only be - * used when you need to avoid triggering a physics update of neighboring - * blocks, for example when creating a {@link Bisected} block. If you are - * using a custom populator, then this parameter may also be required to - * prevent triggering infinite chunk loads on border blocks. This method - * should NOT be used to "hack" physics by placing blocks in impossible - * locations. Such blocks are liable to be removed on various events such as - * world upgrades. Furthermore setting large amounts of such blocks in close - * proximity may overload the server physics engine if an update is - * triggered at a later point. If this occurs, the resulting behavior is - * undefined. - * - * @param type Material to change this block to - * @param applyPhysics False to cancel physics on the changed block. - */ - void setType(@NotNull Material type, 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 - */ - @Nullable - BlockFace getFace(@NotNull 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. - */ - @NotNull - BlockState getState(); - - // Paper start - /** - * @see #getState() optionally disables use of snapshot, to operate on real block data - * @param useSnapshot if this block is a TE, should we create a fully copy of the TileEntity - * @return BlockState with the current state of this block - */ - @NotNull - BlockState getState(boolean useSnapshot); - // Paper end - - /** - * Returns the biome that this block resides in - * - * @return Biome type containing this block - */ - @NotNull - Biome getBiome(); - - /** - * Sets the biome that this block resides in - * - * @param bio new Biome type for this block - */ - void setBiome(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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} or {@link Material#LAVA}. - * - * @return true if this block is liquid - */ - boolean isLiquid(); - - /** - * Gets the temperature of this block. - *

- * If the raw biome temperature without adjusting for height effects is - * required then please use {@link World#getTemperature(int, int)}. - * - * @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 - */ - @NotNull - 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(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - Collection getDrops(@NotNull ItemStack tool); - - /** - * Checks if this block is passable. - *

- * A block is passable if it has no colliding parts that would prevent - * players from moving through it. - *

- * Examples: Tall grass, flowers, signs, etc. are passable, but open doors, - * fence gates, trap doors, etc. are not because they still have parts that - * can be collided with. - * - * @return true if passable - */ - boolean isPassable(); - - /** - * Performs a ray trace that checks for collision with this specific block - * in its current state using its precise collision shape. - * - * @param start the start location - * @param direction the ray direction - * @param maxDistance the maximum distance - * @param fluidCollisionMode the fluid collision mode - * @return the ray trace hit result, or null if there is no hit - */ - @Nullable - RayTraceResult rayTrace(@NotNull Location start, @NotNull Vector direction, double maxDistance, @NotNull FluidCollisionMode fluidCollisionMode); - - /** - * Gets the approximate bounding box for this block. - *

- * This isn't exact as some blocks {@link org.bukkit.block.data.type.Stairs} - * contain many bounding boxes to establish their complete form. - * - * Also, the box may not be exactly the same as the collision shape (such as - * cactus, which is 16/16 of a block with 15/16 collisional bounds). - * - * This method will return an empty bounding box if the geometric shape of - * the block is empty (such as air blocks). - * - * @return the approximate bounding box of the block - */ - @NotNull - BoundingBox getBoundingBox(); - - // Paper start - /** - * Gets the {@link com.destroystokyo.paper.block.BlockSoundGroup} for this block. - *

- * This object contains the block, step, place, hit, and fall sounds. - * - * @return the sound group for this block - */ - @NotNull - com.destroystokyo.paper.block.BlockSoundGroup getSoundGroup(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/block/BlockFace.java b/api/src/main/java/org/bukkit/block/BlockFace.java deleted file mode 100644 index 2fed469b6..000000000 --- a/api/src/main/java/org/bukkit/block/BlockFace.java +++ /dev/null @@ -1,150 +0,0 @@ -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; - - private BlockFace(final int modX, final int modY, final int modZ) { - this.modX = modX; - this.modY = modY; - this.modZ = modZ; - } - - private 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; - } - - @NotNull - 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/api/src/main/java/org/bukkit/block/BlockState.java b/api/src/main/java/org/bukkit/block/BlockState.java deleted file mode 100644 index 631cbf2be..000000000 --- a/api/src/main/java/org/bukkit/block/BlockState.java +++ /dev/null @@ -1,224 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; -import org.bukkit.material.MaterialData; -import org.bukkit.metadata.Metadatable; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 block state. - * - * @return the block represented by this block state - * @throws IllegalStateException if this block state is not placed - */ - @NotNull - Block getBlock(); - - /** - * Gets the metadata for this block state. - * - * @return block specific metadata - */ - @NotNull - MaterialData getData(); - - /** - * Gets the data for this block state. - * - * @return block specific data - */ - @NotNull - BlockData getBlockData(); - - /** - * Gets the type of this block state. - * - * @return block type - */ - @NotNull - Material getType(); - - /** - * Gets the current light level of the block represented by this block state. - * - * @return the light level between 0-15 - * @throws IllegalStateException if this block state is not placed - */ - byte getLightLevel(); - - /** - * Gets the world which contains the block represented by this block state. - * - * @return the world containing the block represented by this block state - * @throws IllegalStateException if this block state is not placed - */ - @NotNull - World getWorld(); - - /** - * Gets the x-coordinate of this block state. - * - * @return x-coordinate - */ - int getX(); - - /** - * Gets the y-coordinate of this block state. - * - * @return y-coordinate - */ - int getY(); - - /** - * Gets the z-coordinate of this block state. - * - * @return z-coordinate - */ - int getZ(); - - /** - * Gets the location of this block state. - *

- * If this block state is not placed the location's world will be null! - * - * @return the location - */ - @NotNull - Location getLocation(); - - /** - * Stores the location of this block state in the provided Location object. - *

- * If the provided Location is null this method does nothing and returns - * null. - *

- * If this block state is not placed the location's world will be null! - * - * @param loc the location to copy into - * @return The Location object provided or null - */ - @Contract("null -> null; !null -> !null") - @Nullable - Location getLocation(@Nullable Location loc); - - /** - * Gets the chunk which contains the block represented by this block state. - * - * @return the containing Chunk - * @throws IllegalStateException if this block state is not placed - */ - @NotNull - Chunk getChunk(); - - /** - * Sets the metadata for this block state. - * - * @param data New block specific metadata - */ - void setData(@NotNull MaterialData data); - - /** - * Sets the data for this block state. - * - * @param data New block specific data - */ - void setBlockData(@NotNull BlockData data); - - /** - * Sets the type of this block state. - * - * @param type Material to change this block state to - */ - void setType(@NotNull Material 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. - *

- * If this state is not placed, this will have no effect and return true. - *

- * 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 - public byte getRawData(); - - /** - * @param data The new data value for the block. - * @deprecated Magic value - */ - @Deprecated - public void setRawData(byte data); - - /** - * Returns whether this state is placed in the world. - *

- * Some methods will not work if the block state 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/api/src/main/java/org/bukkit/block/BrewingStand.java b/api/src/main/java/org/bukkit/block/BrewingStand.java deleted file mode 100644 index fe155f14d..000000000 --- a/api/src/main/java/org/bukkit/block/BrewingStand.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.inventory.BrewerInventory; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of a brewing stand. - */ -public interface BrewingStand extends Container { - - /** - * 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); - - /** - * Get the level of current fuel for brewing. - * - * @return The fuel level - */ - int getFuelLevel(); - - /** - * Set the level of current fuel for brewing. - * - * @param level fuel level - */ - void setFuelLevel(int level); - - @NotNull - @Override - BrewerInventory getInventory(); - - @NotNull - @Override - BrewerInventory getSnapshotInventory(); -} diff --git a/api/src/main/java/org/bukkit/block/Campfire.java b/api/src/main/java/org/bukkit/block/Campfire.java deleted file mode 100644 index 09522d5e8..000000000 --- a/api/src/main/java/org/bukkit/block/Campfire.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a captured state of a campfire. - */ -public interface Campfire extends TileState { - - /** - * @see Inventory#getSize() - * - * @return The size of the inventory - */ - int getSize(); - - /** - * @see Inventory#getItem(int) - * - * @param index The index of the Slot's ItemStack to return - * @return The ItemStack in the slot - */ - @Nullable - ItemStack getItem(int index); - - /** - * @see Inventory#setItem(int, org.bukkit.inventory.ItemStack) - * - * @param index The index where to put the ItemStack - * @param item The ItemStack to set - */ - void setItem(int index, @Nullable ItemStack item); - - /** - * Get cook time. - * - * This is the amount of time the item has been cooking for. - * - * @param index item slot index - * @return Cook time - */ - int getCookTime(int index); - - /** - * Set cook time. - * - * This is the amount of time the item has been cooking for. - * - * @param index item slot index - * @param cookTime Cook time - */ - void setCookTime(int index, int cookTime); - - /** - * Get cook time total. - * - * This is the amount of time the item is required to cook for. - * - * @param index item slot index - * @return Cook time total - */ - int getCookTimeTotal(int index); - - /** - * Set cook time. - * - * This is the amount of time the item is required to cook for. - * - * @param index item slot index - * @param cookTimeTotal Cook time total - */ - void setCookTimeTotal(int index, int cookTimeTotal); -} diff --git a/api/src/main/java/org/bukkit/block/Chest.java b/api/src/main/java/org/bukkit/block/Chest.java deleted file mode 100644 index a569c7b63..000000000 --- a/api/src/main/java/org/bukkit/block/Chest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.block; - -import com.destroystokyo.paper.loottable.LootableBlockInventory; // Paper -import org.bukkit.Nameable; // Paper -import org.bukkit.inventory.Inventory; -import org.bukkit.loot.Lootable; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of a chest. - */ -public interface Chest extends Container, LootableBlockInventory { // Paper - - /** - * Gets the inventory of the chest block represented by this block state. - *

- * If the chest is a double chest, it returns just the portion of the - * inventory linked to the half of the chest corresponding to this block state. - *

- * If the block was changed to a different type in the meantime, the - * returned inventory might no longer be valid. - *

- * If this block state is not placed this will return the captured - * inventory snapshot instead. - * - * @return the inventory - */ - @NotNull - Inventory getBlockInventory(); -} diff --git a/api/src/main/java/org/bukkit/block/CommandBlock.java b/api/src/main/java/org/bukkit/block/CommandBlock.java deleted file mode 100644 index 372c0bd5a..000000000 --- a/api/src/main/java/org/bukkit/block/CommandBlock.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bukkit.block; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a captured state of a command block. - */ -public interface CommandBlock extends TileState { - - /** - * 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. - */ - @NotNull - public 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. - */ - public void setCommand(@Nullable 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. - */ - @NotNull - public 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. - */ - public void setName(@Nullable String name); -} diff --git a/api/src/main/java/org/bukkit/block/Comparator.java b/api/src/main/java/org/bukkit/block/Comparator.java deleted file mode 100644 index 6fb4c1a94..000000000 --- a/api/src/main/java/org/bukkit/block/Comparator.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.block; - -/** - * Represents a captured state of an on / off comparator. - */ -public interface Comparator extends TileState { } diff --git a/api/src/main/java/org/bukkit/block/Conduit.java b/api/src/main/java/org/bukkit/block/Conduit.java deleted file mode 100644 index 554316553..000000000 --- a/api/src/main/java/org/bukkit/block/Conduit.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.block; - -/** - * Represents a captured state of a conduit. - */ -public interface Conduit extends TileState { } diff --git a/api/src/main/java/org/bukkit/block/Container.java b/api/src/main/java/org/bukkit/block/Container.java deleted file mode 100644 index bc06199f0..000000000 --- a/api/src/main/java/org/bukkit/block/Container.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.Nameable; -import org.bukkit.inventory.BlockInventoryHolder; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of a container block. - */ -public interface Container extends TileState, BlockInventoryHolder, Lockable, Nameable { - - /** - * Gets the inventory of the block represented by this block state. - *

- * If the block was changed to a different type in the meantime, the - * returned inventory might no longer be valid. - *

- * If this block state is not placed this will return the captured inventory - * snapshot instead. - * - * @return the inventory - */ - @NotNull - @Override - Inventory getInventory(); - - /** - * Gets the captured inventory snapshot of this container. - *

- * The returned inventory is not linked to any block. Any modifications to - * the returned inventory will not be applied to the block represented by - * this block state up until {@link #update(boolean, boolean)} has been - * called. - * - * @return the captured inventory snapshot - */ - @NotNull - Inventory getSnapshotInventory(); -} diff --git a/api/src/main/java/org/bukkit/block/CreatureSpawner.java b/api/src/main/java/org/bukkit/block/CreatureSpawner.java deleted file mode 100644 index 2ff0f24d5..000000000 --- a/api/src/main/java/org/bukkit/block/CreatureSpawner.java +++ /dev/null @@ -1,216 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.entity.EntityType; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of a creature spawner. - */ -public interface CreatureSpawner extends TileState { - - /** - * Get the spawner's creature type. - * - * @return The creature type. - */ - @NotNull - public EntityType getSpawnedType(); - - /** - * Set the spawner's creature type. - * - * @param creatureType The creature type. - */ - public void setSpawnedType(@NotNull EntityType creatureType); - - /** - * Set the spawner mob type. - * - * @param creatureType The creature type's name. - * @deprecated magic value, use - * {@link #setSpawnedType(org.bukkit.entity.EntityType)}. - */ - @Deprecated - public void setCreatureTypeByName(@NotNull String creatureType); - - /** - * Get the spawner's creature type. - * - * @return The creature type's name. - * @deprecated magic value, use {@link #getSpawnedType()}. - */ - @Deprecated - @NotNull - public String getCreatureTypeName(); - - /** - * Get the spawner's delay. - *
- * This is the delay, in ticks, until the spawner will spawn its next mob. - * - * @return The delay. - */ - public int getDelay(); - - /** - * Set the spawner's delay. - *
- * If set to -1, the spawn delay will be reset to a random value between - * {@link #getMinSpawnDelay} and {@link #getMaxSpawnDelay()}. - * - * @param delay The delay. - */ - public void setDelay(int delay); - - /** - * The minimum spawn delay amount (in ticks). - *
- * This value is used when the spawner resets its delay (for any reason). - * It will choose a random number between {@link #getMinSpawnDelay()} - * and {@link #getMaxSpawnDelay()} for its next {@link #getDelay()}. - * - * Default value is 200 ticks. - * - * @return the minimum spawn delay amount - */ - public int getMinSpawnDelay(); - - /** - * Set the minimum spawn delay amount (in ticks). - * - * @see #getMinSpawnDelay() - * @param delay the minimum spawn delay amount - */ - public void setMinSpawnDelay(int delay); - - /** - * The maximum spawn delay amount (in ticks). - *
- * This value is used when the spawner resets its delay (for any reason). - * It will choose a random number between {@link #getMinSpawnDelay()} - * and {@link #getMaxSpawnDelay()} for its next {@link #getDelay()}. - *
- * This value must be greater than 0 and less than or equal to - * {@link #getMaxSpawnDelay()}. - * - * Default value is 800 ticks. - * - * @return the maximum spawn delay amount - */ - public int getMaxSpawnDelay(); - - /** - * Set the maximum spawn delay amount (in ticks). - *
- * This value must be greater than 0, as well as greater than or - * equal to {@link #getMinSpawnDelay()} - * - * @see #getMaxSpawnDelay() - * @param delay the new maximum spawn delay amount - */ - public void setMaxSpawnDelay(int delay); - - /** - * Get how many mobs attempt to spawn. - *
- * Default value is 4. - * - * @return the current spawn count - */ - public int getSpawnCount(); - - /** - * Set how many mobs attempt to spawn. - * - * @param spawnCount the new spawn count - */ - public void setSpawnCount(int spawnCount); - - /** - * Set the new maximum amount of similar entities that are allowed to be - * within spawning range of this spawner. - *
- * If more than the maximum number of entities are within range, the spawner - * will not spawn and try again with a new {@link #getDelay()}. - *
- * Default value is 16. - * - * @return the maximum number of nearby, similar, entities - */ - public int getMaxNearbyEntities(); - - /** - * Set the maximum number of similar entities that are allowed to be within - * spawning range of this spawner. - *
- * Similar entities are entities that are of the same {@link EntityType} - * - * @param maxNearbyEntities the maximum number of nearby, similar, entities - */ - public void setMaxNearbyEntities(int maxNearbyEntities); - - /** - * Get the maximum distance(squared) a player can be in order for this - * spawner to be active. - *
- * If this value is less than or equal to 0, this spawner is always active - * (given that there are players online). - *
- * Default value is 16. - * - * @return the maximum distance(squared) a player can be in order for this - * spawner to be active. - */ - public int getRequiredPlayerRange(); - - /** - * Set the maximum distance (squared) a player can be in order for this - * spawner to be active. - *
- * Setting this value to less than or equal to 0 will make this spawner - * always active (given that there are players online). - * - * @param requiredPlayerRange the maximum distance (squared) a player can be - * in order for this spawner to be active. - */ - public void setRequiredPlayerRange(int requiredPlayerRange); - - /** - * Get the radius around which the spawner will attempt to spawn mobs in. - *
- * This area is square, includes the block the spawner is in, and is - * centered on the spawner's x,z coordinates - not the spawner itself. - *
- * It is 2 blocks high, centered on the spawner's y-coordinate (its bottom); - * thus allowing mobs to spawn as high as its top surface and as low - * as 1 block below its bottom surface. - *
- * Default value is 4. - * - * @return the spawn range - */ - public int getSpawnRange(); - - /** - * Set the new spawn range. - *
- * - * @see #getSpawnRange() - * @param spawnRange the new spawn range - */ - public void setSpawnRange(int spawnRange); - - // Paper start - /** - * Check if spawner is activated (a player is close enough) - * - * @return True if a player is close enough to activate it - */ - public boolean isActivated(); - - /** - * Resets the spawn delay timer within the min/max range - */ - public void resetTimer(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/block/DaylightDetector.java b/api/src/main/java/org/bukkit/block/DaylightDetector.java deleted file mode 100644 index 702ee7fbe..000000000 --- a/api/src/main/java/org/bukkit/block/DaylightDetector.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.block; - -/** - * Represents a captured state of a (possibly inverted) daylight detector. - */ -public interface DaylightDetector extends TileState { } diff --git a/api/src/main/java/org/bukkit/block/Dispenser.java b/api/src/main/java/org/bukkit/block/Dispenser.java deleted file mode 100644 index 07af1a3f0..000000000 --- a/api/src/main/java/org/bukkit/block/Dispenser.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.block; - -import com.destroystokyo.paper.loottable.LootableBlockInventory; -import org.bukkit.Nameable; -import org.bukkit.loot.Lootable; -import org.bukkit.projectiles.BlockProjectileSource; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a captured state of a dispenser. - */ -public interface Dispenser extends Container, Nameable, LootableBlockInventory { // Paper - - /** - * Gets the BlockProjectileSource object for the dispenser. - *

- * If the block represented by this state is no longer a dispenser, this - * will return null. - * - * @return a BlockProjectileSource if valid, otherwise null - * @throws IllegalStateException if this block state is not placed - */ - @Nullable - public BlockProjectileSource getBlockProjectileSource(); - - /** - * Attempts to dispense the contents of the dispenser. - *

- * If the block represented by this state is no longer a dispenser, this - * will return false. - * - * @return true if successful, otherwise false - * @throws IllegalStateException if this block state is not placed - */ - public boolean dispense(); -} diff --git a/api/src/main/java/org/bukkit/block/DoubleChest.java b/api/src/main/java/org/bukkit/block/DoubleChest.java deleted file mode 100644 index 83a464211..000000000 --- a/api/src/main/java/org/bukkit/block/DoubleChest.java +++ /dev/null @@ -1,58 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a double chest. - */ -public class DoubleChest implements InventoryHolder { - private DoubleChestInventory inventory; - - public DoubleChest(@NotNull DoubleChestInventory chest) { - inventory = chest; - } - - @Override - @NotNull - public Inventory getInventory() { - return inventory; - } - - @Nullable - public InventoryHolder getLeftSide() { - return inventory.getLeftSide().getHolder(); - } - - @Nullable - public InventoryHolder getRightSide() { - return inventory.getRightSide().getHolder(); - } - - @NotNull - public Location getLocation() { - return getInventory().getLocation(); - } - - @Nullable - public World getWorld() { - return getLocation().getWorld(); - } - - public double getX() { - return getLocation().getX(); - } - - public double getY() { - return getLocation().getY(); - } - - public double getZ() { - return getLocation().getZ(); - } -} diff --git a/api/src/main/java/org/bukkit/block/Dropper.java b/api/src/main/java/org/bukkit/block/Dropper.java deleted file mode 100644 index c76202321..000000000 --- a/api/src/main/java/org/bukkit/block/Dropper.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bukkit.block; - -import com.destroystokyo.paper.loottable.LootableBlockInventory; -import org.bukkit.loot.Lootable; - -/** - * Represents a captured state of a dropper. - */ -public interface Dropper extends Container, LootableBlockInventory { // Paper - - /** - * 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, - * 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, - * the randomly selected ItemStack is dropped on - * the ground in the form of an {@link org.bukkit.entity.Item Item}. - *

- * If the block represented by this state is no longer a dropper, this will - * do nothing. - * - * @throws IllegalStateException if this block state is not placed - */ - public void drop(); -} diff --git a/api/src/main/java/org/bukkit/block/EnchantingTable.java b/api/src/main/java/org/bukkit/block/EnchantingTable.java deleted file mode 100644 index 68b9e034a..000000000 --- a/api/src/main/java/org/bukkit/block/EnchantingTable.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.Nameable; - -/** - * Represents a captured state of an enchanting table. - */ -public interface EnchantingTable extends TileState, Nameable { } diff --git a/api/src/main/java/org/bukkit/block/EndGateway.java b/api/src/main/java/org/bukkit/block/EndGateway.java deleted file mode 100644 index 5e76a1cf4..000000000 --- a/api/src/main/java/org/bukkit/block/EndGateway.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.Location; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a captured state of an end gateway. - */ -public interface EndGateway extends TileState { - - /** - * Gets the location that entities are teleported to when - * entering the gateway portal. - *

- * If this block state is not placed the location's world will be null. - * - * @return the gateway exit location - */ - @Nullable - Location getExitLocation(); - - /** - * Sets the exit location that entities are teleported to when - * they enter the gateway portal. - *

- * If this block state is not placed the location's world has to be null. - * - * @param location the new exit location - * @throws IllegalArgumentException for differing worlds - */ - void setExitLocation(@Nullable Location location); - - /** - * Gets whether this gateway will teleport entities directly to - * the exit location instead of finding a nearby location. - * - * @return true if the gateway is teleporting to the exact location - */ - boolean isExactTeleport(); - - /** - * Sets whether this gateway will teleport entities directly to - * the exit location instead of finding a nearby location. - * - * @param exact whether to teleport to the exact location - */ - void setExactTeleport(boolean exact); - - /** - * Gets the age in ticks of the gateway. - *
- * If the age is less than 200 ticks a magenta beam will be emitted, whilst - * if it is a multiple of 2400 ticks a purple beam will be emitted. - * - * @return age in ticks - */ - long getAge(); - - /** - * Sets the age in ticks of the gateway. - *
- * If the age is less than 200 ticks a magenta beam will be emitted, whilst - * if it is a multiple of 2400 ticks a purple beam will be emitted. - * - * @param age new age in ticks - */ - void setAge(long age); -} diff --git a/api/src/main/java/org/bukkit/block/EnderChest.java b/api/src/main/java/org/bukkit/block/EnderChest.java deleted file mode 100644 index 17843e338..000000000 --- a/api/src/main/java/org/bukkit/block/EnderChest.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.block; - -/** - * Represents a captured state of an ender chest. - */ -public interface EnderChest extends TileState { } diff --git a/api/src/main/java/org/bukkit/block/FlowerPot.java b/api/src/main/java/org/bukkit/block/FlowerPot.java deleted file mode 100644 index 1155edc3a..000000000 --- a/api/src/main/java/org/bukkit/block/FlowerPot.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a captured state of a flower pot. - * @deprecated not a tile entity in future versions of Minecraft - */ -@Deprecated -public interface FlowerPot extends BlockState { - - /** - * Gets the item present in this flower pot. - * - * @return item present, or null for empty. - */ - @Nullable - MaterialData getContents(); - - /** - * Sets the item present in this flower pot. - * - * NOTE: The Vanilla Minecraft client will currently not refresh this until - * a block update is triggered. - * - * @param item new item, or null for empty. - */ - void setContents(@Nullable MaterialData item); -} diff --git a/api/src/main/java/org/bukkit/block/Furnace.java b/api/src/main/java/org/bukkit/block/Furnace.java deleted file mode 100644 index 9063cf370..000000000 --- a/api/src/main/java/org/bukkit/block/Furnace.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.inventory.FurnaceInventory; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of a furnace. - */ -public interface Furnace extends Container { - - /** - * Get burn time. - * - * @return Burn time - */ - public short getBurnTime(); - - /** - * Set burn time. - * - * A burn time greater than 0 will cause this block to be lit, whilst a time - * less than 0 will extinguish it. - * - * @param burnTime Burn time - */ - public void setBurnTime(short burnTime); - - /** - * Get cook time. - * - * This is the amount of time the item has been cooking for. - * - * @return Cook time - */ - public short getCookTime(); - - /** - * Set cook time. - * - * This is the amount of time the item has been cooking for. - * - * @param cookTime Cook time - */ - public void setCookTime(short cookTime); - - /** - * Get cook time total. - * - * This is the amount of time the item is required to cook for. - * - * @return Cook time total - */ - public int getCookTimeTotal(); - - /** - * Set cook time. - * - * This is the amount of time the item is required to cook for. - * - * @param cookTimeTotal Cook time total - */ - public void setCookTimeTotal(int cookTimeTotal); - - // Paper start - /** - * Gets the cook speed multiplier that this {@link Furnace} will cook - * compared to vanilla. - * - * @return the multiplier, a value between 0 and 200 - */ - public double getCookSpeedMultiplier(); - - /** - * Sets the speed multiplier that this {@link Furnace} will cook - * compared to vanilla. - * - * @param multiplier the multiplier to set, a value between 0 and 200 - * @throws IllegalArgumentException if value is less than 0 - * @throws IllegalArgumentException if value is more than 200 - */ - public void setCookSpeedMultiplier(double multiplier); - // Paper end - - @NotNull - @Override - public FurnaceInventory getInventory(); - - @NotNull - @Override - public FurnaceInventory getSnapshotInventory(); -} diff --git a/api/src/main/java/org/bukkit/block/Hopper.java b/api/src/main/java/org/bukkit/block/Hopper.java deleted file mode 100644 index 7ade312f1..000000000 --- a/api/src/main/java/org/bukkit/block/Hopper.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bukkit.block; - -import com.destroystokyo.paper.loottable.LootableBlockInventory; -import org.bukkit.loot.Lootable; - -/** - * Represents a captured state of a hopper. - */ -public interface Hopper extends Container, LootableBlockInventory { } // Paper diff --git a/api/src/main/java/org/bukkit/block/Jigsaw.java b/api/src/main/java/org/bukkit/block/Jigsaw.java deleted file mode 100644 index 02c7fa58e..000000000 --- a/api/src/main/java/org/bukkit/block/Jigsaw.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.block; - -/** - * Represents a captured state of a jigsaw. - */ -public interface Jigsaw extends TileState { } diff --git a/api/src/main/java/org/bukkit/block/Jukebox.java b/api/src/main/java/org/bukkit/block/Jukebox.java deleted file mode 100644 index 363294cff..000000000 --- a/api/src/main/java/org/bukkit/block/Jukebox.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a captured state of a jukebox. - */ -public interface Jukebox extends TileState { - - /** - * Gets the record inserted into the jukebox. - * - * @return The record Material, or AIR if none is inserted - */ - @NotNull - public Material getPlaying(); - - /** - * Sets the record being played. - * - * @param record The record Material, or null/AIR to stop playing - */ - public void setPlaying(@Nullable Material record); - - /** - * Gets the record item inserted into the jukebox. - * - * @return a copy of the inserted record, or an air stack if none - */ - @NotNull - public ItemStack getRecord(); - - /** - * Sets the record being played. - * - * @param record the record to insert or null/AIR to empty - */ - public void setRecord(@Nullable ItemStack record); - - /** - * Checks if the jukebox is playing a record. - * - * @return True if there is a record playing - */ - public boolean isPlaying(); - - /** - * Stops the jukebox playing and ejects the current record. - *

- * If the block represented by this state is no longer a jukebox, this will - * do nothing and return false. - * - * @return True if a record was ejected; false if there was none playing - * @throws IllegalStateException if this block state is not placed - */ - public boolean eject(); -} diff --git a/api/src/main/java/org/bukkit/block/Lectern.java b/api/src/main/java/org/bukkit/block/Lectern.java deleted file mode 100644 index 78107207b..000000000 --- a/api/src/main/java/org/bukkit/block/Lectern.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.inventory.BlockInventoryHolder; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of a lectern. - */ -public interface Lectern extends TileState, BlockInventoryHolder { - - /** - * Get the current lectern page. - * - * @return current page - */ - int getPage(); - - /** - * Set the current lectern page. - * - * If the page is greater than the number of pages of the book currently in - * the inventory, then behavior is undefined. - * - * @param page new page - */ - void setPage(int page); - - /** - * @see Container#getInventory() - * - * @return inventory - */ - @NotNull - @Override - Inventory getInventory(); - - /** - * @see Container#getSnapshotInventory() - * - * @return snapshot inventory - */ - @NotNull - Inventory getSnapshotInventory(); -} diff --git a/api/src/main/java/org/bukkit/block/Lockable.java b/api/src/main/java/org/bukkit/block/Lockable.java deleted file mode 100644 index f307cb170..000000000 --- a/api/src/main/java/org/bukkit/block/Lockable.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.block; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a block (usually a container) that may be locked. When a lock is - * active an item with a name corresponding to the key will be required to open - * this block. - */ -public interface Lockable { - - /** - * Checks if the container has a valid (non empty) key. - * - * @return true if the key is valid. - */ - boolean isLocked(); - - /** - * Gets the key needed to access the container. - * - * @return the key needed. - */ - @NotNull - String getLock(); - - /** - * Sets the key required to access this container. Set to null (or empty - * string) to remove key. - * - * @param key the key required to access the container. - */ - void setLock(@Nullable String key); -} diff --git a/api/src/main/java/org/bukkit/block/NoteBlock.java b/api/src/main/java/org/bukkit/block/NoteBlock.java deleted file mode 100644 index 14bb68bae..000000000 --- a/api/src/main/java/org/bukkit/block/NoteBlock.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.Instrument; -import org.bukkit.Note; - -/** - * Represents a captured state of a note block. - * @deprecated not a tile entity in future versions of Minecraft - */ -@Deprecated -public interface NoteBlock extends BlockState { - - /** - * Gets the note. - * - * @return The note. - */ - public Note getNote(); - - /** - * Gets the note. - * - * @return The note ID. - * @deprecated Magic value - */ - @Deprecated - public byte getRawNote(); - - /** - * Set the note. - * - * @param note The note. - */ - public void setNote(Note note); - - /** - * Set the note. - * - * @param note The note ID. - * @deprecated Magic value - */ - @Deprecated - public void setRawNote(byte note); - - /** - * Attempts to play the note at the block. - *

- * If the block represented by this block state is no longer a note block, - * this will return false. - * - * @return true if successful, otherwise false - * @throws IllegalStateException if this block state is not placed - */ - public boolean play(); - - /** - * Plays an arbitrary note with an arbitrary instrument at the block. - *

- * If the block represented by this block state is no longer a note block, - * this will return false. - * - * @param instrument Instrument ID - * @param note Note ID - * @return true if successful, otherwise false - * @throws IllegalStateException if this block state is not placed - * @deprecated Magic value - */ - @Deprecated - public boolean play(byte instrument, byte note); - - /** - * Plays an arbitrary note with an arbitrary instrument at the block. - *

- * If the block represented by this block state is no longer a note block, - * this will return false. - * - * @param instrument The instrument - * @param note The note - * @return true if successful, otherwise false - * @throws IllegalStateException if this block state is not placed - * @see Instrument Note - */ - public boolean play(Instrument instrument, Note note); -} diff --git a/api/src/main/java/org/bukkit/block/PistonMoveReaction.java b/api/src/main/java/org/bukkit/block/PistonMoveReaction.java deleted file mode 100644 index b90f5dc34..000000000 --- a/api/src/main/java/org/bukkit/block/PistonMoveReaction.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bukkit.block; - -import java.util.HashMap; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -/** - * Represents how a block or entity will react when interacting with a piston - * when it is extending or retracting. - */ -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), - /** - * Indicates that the entity will ignore any interaction(s) with - * pistons. - *
- * Blocks should use {@link PistonMoveReaction#BLOCK}. - */ - IGNORE(3), - /** - * Indicates that the block can only be pushed by pistons, not pulled. - */ - PUSH_ONLY(4); - - private int id; - private static Map byId = new HashMap(); - static { - for (PistonMoveReaction reaction : PistonMoveReaction.values()) { - byId.put(reaction.id, reaction); - } - } - - private 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 - @Nullable - public static PistonMoveReaction getById(int id) { - return byId.get(id); - } -} diff --git a/api/src/main/java/org/bukkit/block/ShulkerBox.java b/api/src/main/java/org/bukkit/block/ShulkerBox.java deleted file mode 100644 index 42f5b4ea3..000000000 --- a/api/src/main/java/org/bukkit/block/ShulkerBox.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bukkit.block; - -import com.destroystokyo.paper.loottable.LootableBlockInventory; -import org.bukkit.DyeColor; -import org.bukkit.loot.Lootable; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of a ShulkerBox. - */ -public interface ShulkerBox extends Container, LootableBlockInventory { // Paper - - /** - * Get the {@link DyeColor} corresponding to this ShulkerBox - * - * @return the {@link DyeColor} of this ShulkerBox - */ - @NotNull - public DyeColor getColor(); -} diff --git a/api/src/main/java/org/bukkit/block/Sign.java b/api/src/main/java/org/bukkit/block/Sign.java deleted file mode 100644 index 7e3cf00e4..000000000 --- a/api/src/main/java/org/bukkit/block/Sign.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.material.Colorable; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a captured state of either a SignPost or a WallSign. - */ -public interface Sign extends TileState, Colorable { - - /** - * Gets all the lines of text currently on this sign. - * - * @return Array of Strings containing each line of text - */ - @NotNull - public 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 - */ - @NotNull - public 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 - */ - public void setLine(int index, @NotNull String line) throws IndexOutOfBoundsException; - - /** - * Marks whether this sign can be edited by players. - *
- * This is a special value, which is not persisted. It should only be set if - * a placed sign is manipulated during the BlockPlaceEvent. Behaviour - * outside of this event is undefined. - * - * @return if this sign is currently editable - */ - public boolean isEditable(); - - /** - * Marks whether this sign can be edited by players. - *
- * This is a special value, which is not persisted. It should only be set if - * a placed sign is manipulated during the BlockPlaceEvent. Behaviour - * outside of this event is undefined. - * - * @param editable if this sign is currently editable - */ - public void setEditable(boolean editable); -} diff --git a/api/src/main/java/org/bukkit/block/Skull.java b/api/src/main/java/org/bukkit/block/Skull.java deleted file mode 100644 index a6914f01e..000000000 --- a/api/src/main/java/org/bukkit/block/Skull.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.SkullType; -import org.bukkit.block.data.BlockData; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import com.destroystokyo.paper.profile.PlayerProfile; // Paper - -/** - * Represents a captured state of a skull block. - */ -public interface Skull extends TileState { - - /** - * Checks to see if the skull has an owner - * - * @return true if the skull has an owner - */ - public 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 - * @deprecated See {@link #getOwningPlayer()}. - */ - @Deprecated - @Nullable - public 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 - * @deprecated see {@link #setOwningPlayer(org.bukkit.OfflinePlayer)}. - */ - @Deprecated - @Contract("null -> false") - public boolean setOwner(@Nullable String name); - - /** - * Get the player which owns the skull. This player may appear as the - * texture depending on skull type. - * - * @return owning player - */ - @Nullable - public OfflinePlayer getOwningPlayer(); - - /** - * Set the player which owns the skull. This player may appear as the - * texture depending on skull type. - * - * @param player the owning player - */ - public void setOwningPlayer(@NotNull OfflinePlayer player); - - // Paper start - /** - * Sets this skull to use the supplied Player Profile, which can include textures already prefilled. - * @param profile The profile to set this Skull to use, may not be null - */ - void setPlayerProfile(@NotNull PlayerProfile profile); - - /** - * If the skull has an owner, per {@link #hasOwner()}, return the owners {@link PlayerProfile} - * @return The profile of the owner, if set - */ - @Nullable PlayerProfile getPlayerProfile(); - // Paper end - - /** - * Gets the rotation of the skull in the world (or facing direction if this - * is a wall mounted skull). - * - * @return the rotation of the skull - * @deprecated use {@link BlockData} - */ - @Deprecated - @NotNull - public BlockFace getRotation(); - - /** - * Sets the rotation of the skull in the world (or facing direction if this - * is a wall mounted skull). - * - * @param rotation the rotation of the skull - * @deprecated use {@link BlockData} - */ - @Deprecated - public void setRotation(@NotNull BlockFace rotation); - - /** - * Gets the type of skull - * - * @return the type of skull - * @deprecated check {@link Material} instead - */ - @Deprecated - @NotNull - public SkullType getSkullType(); - - /** - * Sets the type of skull - * - * @param skullType the type of skull - * @deprecated check {@link Material} instead - */ - @Deprecated - @Contract("_ -> fail") - public void setSkullType(SkullType skullType); -} diff --git a/api/src/main/java/org/bukkit/block/Smoker.java b/api/src/main/java/org/bukkit/block/Smoker.java deleted file mode 100644 index 7601c30d7..000000000 --- a/api/src/main/java/org/bukkit/block/Smoker.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.block; - -/** - * Represents a captured state of a smoker. - */ -public interface Smoker extends Furnace { } diff --git a/api/src/main/java/org/bukkit/block/Structure.java b/api/src/main/java/org/bukkit/block/Structure.java deleted file mode 100644 index dc4006955..000000000 --- a/api/src/main/java/org/bukkit/block/Structure.java +++ /dev/null @@ -1,243 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.block.structure.Mirror; -import org.bukkit.block.structure.StructureRotation; -import org.bukkit.block.structure.UsageMode; -import org.bukkit.entity.LivingEntity; -import org.bukkit.util.BlockVector; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a structure block that can save and load blocks from a file. They - * can only be used by OPs, and are not obtainable in survival. - */ -public interface Structure extends TileState { - - /** - * The name of this structure. - * - * @return structure name - */ - @NotNull - String getStructureName(); - - /** - * Set the name of this structure. This is case-sensitive. The name of the - * structure in the {@link UsageMode#SAVE} structure block MUST match the - * name within the {@link UsageMode#CORNER} block or the size calculation - * will fail. - * - * @param name the case-sensitive name of this structure - */ - void setStructureName(@NotNull String name); - - /** - * Get the name of who created this structure. - * - * @return the name of whoever created this structure. - */ - @NotNull - String getAuthor(); - - /** - * Set the name of whoever created this structure. - * - * @param author whoever created this structure (not empty) - */ - void setAuthor(@NotNull String author); - - /** - * Set the name of whoever created this structure using a - * {@link LivingEntity}. - * - * @param livingEntity the entity who created this structure - */ - void setAuthor(@NotNull LivingEntity livingEntity); - - /** - * The relative position of the structure outline based on the position of - * the structure block. Maximum allowed distance is 32 blocks in any - * direction. - * - * @return a Location which contains the relative distance this structure is - * from the structure block. - */ - @NotNull - BlockVector getRelativePosition(); - - /** - * Set the relative position from the structure block. Maximum allowed - * distance is 32 blocks in any direction. - * - * @param vector the {@link BlockVector} containing the relative origin - * coordinates of this structure. - */ - void setRelativePosition(@NotNull BlockVector vector); - - /** - * The distance to the opposite corner of this structure. The maximum - * structure size is 32x32x32. When a structure has successfully been - * calculated (i.e. it is within the maximum allowed distance) a white - * border surrounds the structure. - * - * @return a {@link BlockVector} which contains the total size of the - * structure. - */ - @NotNull - BlockVector getStructureSize(); - - /** - * Set the maximum size of this structure from the origin point. Maximum - * allowed size is 32x32x32. - * - * @param vector the {@link BlockVector} containing the size of this - * structure, based off of the origin coordinates. - */ - void setStructureSize(@NotNull BlockVector vector); - - /** - * Sets the mirroring of the structure. - * - * @param mirror the new mirroring method - */ - void setMirror(@NotNull Mirror mirror); - - /** - * How this structure is mirrored. - * - * @return the current mirroring method - */ - @NotNull - Mirror getMirror(); - - /** - * Set how this structure is rotated. - * - * @param rotation the new rotation - */ - void setRotation(@NotNull StructureRotation rotation); - - /** - * Get how this structure is rotated. - * - * @return the new rotation - */ - @NotNull - StructureRotation getRotation(); - - /** - * Set the {@link UsageMode} of this structure block. - * - * @param mode the new mode to set. - */ - void setUsageMode(@NotNull UsageMode mode); - - /** - * Get the {@link UsageMode} of this structure block. - * - * @return the mode this block is currently in. - */ - @NotNull - UsageMode getUsageMode(); - - /** - * While in {@link UsageMode#SAVE} mode, this will ignore any entities when - * saving the structure. - *
- * While in {@link UsageMode#LOAD} mode this will ignore any entities that - * were saved to file. - * - * @param ignoreEntities the flag to set - */ - void setIgnoreEntities(boolean ignoreEntities); - - /** - * Get if this structure block should ignore entities. - * - * @return true if the appropriate {@link UsageMode} should ignore entities. - */ - boolean isIgnoreEntities(); - - /** - * Set if the structure outline should show air blocks. - * - * @param showAir if the structure block should show air blocks - */ - void setShowAir(boolean showAir); - - /** - * Check if this structure block is currently showing all air blocks - * - * @return true if the structure block is showing all air blocks - */ - boolean isShowAir(); - - /** - * Set if this structure box should show the bounding box. - * - * @param showBoundingBox if the structure box should be shown - */ - void setBoundingBoxVisible(boolean showBoundingBox); - - /** - * Get if this structure block is currently showing the bounding box. - * - * @return true if the bounding box is shown - */ - boolean isBoundingBoxVisible(); - - /** - * Set the integrity of the structure. Integrity must be between 0.0 and 1.0 - * Lower integrity values will result in more blocks being removed when - * loading a structure. Integrity and {@link #getSeed()} are used together - * to determine which blocks are randomly removed to mimic "decay." - * - * @param integrity the integrity of this structure - */ - void setIntegrity(float integrity); - - /** - * Get the integrity of this structure. - * - * @return the integrity of this structure - */ - float getIntegrity(); - - /** - * The seed used to determine which blocks will be removed upon loading. - * {@link #getIntegrity()} and seed are used together to determine which - * blocks are randomly removed to mimic "decay." - * - * @param seed the seed used to determine how many blocks will be removed - */ - void setSeed(long seed); - - /** - * The seed used to determine how many blocks are removed upon loading of - * this structure. - * - * @return the seed used - */ - long getSeed(); - - /** - * Only applicable while in {@link UsageMode#DATA}. Metadata are specific - * functions that can be applied to the structure location. Consult the - * Minecraft - * wiki for more information. - * - * @param metadata the function to perform on the selected location - */ - void setMetadata(@NotNull String metadata); - - /** - * Get the metadata function this structure block will perform when - * activated. Consult the - * Minecraft - * Wiki for more information. - * - * @return the function that will be performed when this block is activated - */ - @NotNull - String getMetadata(); -} diff --git a/api/src/main/java/org/bukkit/block/TileState.java b/api/src/main/java/org/bukkit/block/TileState.java deleted file mode 100644 index 3b10fcc13..000000000 --- a/api/src/main/java/org/bukkit/block/TileState.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.block; - -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataHolder; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a block state that also hosts a tile entity at the given location. - * - * This interface alone is merely a marker that does not provide any data. - * - * Data about the tile entities is provided by the respective interface for each - * tile entity type. - * - * After modifying the data provided by a TileState, {@link #update()} needs to - * be called to store the data. - */ -public interface TileState extends BlockState, PersistentDataHolder { - - /** - * Returns a custom tag container capable of storing tags on the object. - * - * Note that the tags stored on this container are all stored under their - * own custom namespace therefore modifying default tags using this - * {@link PersistentDataHolder} is impossible. - *

- * This {@link PersistentDataHolder} is only linked to the snapshot instance - * stored by the {@link BlockState}. - * - * When storing changes on the {@link PersistentDataHolder}, the updated - * content will only be applied to the actual tile entity after one of the - * {@link #update()} methods is called. - * - * @return the custom tag container - */ - @NotNull - @Override - PersistentDataContainer getPersistentDataContainer(); -} diff --git a/api/src/main/java/org/bukkit/block/banner/Pattern.java b/api/src/main/java/org/bukkit/block/banner/Pattern.java deleted file mode 100644 index 5c293ab0b..000000000 --- a/api/src/main/java/org/bukkit/block/banner/Pattern.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.bukkit.block.banner; - -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import java.util.NoSuchElementException; -import org.bukkit.DyeColor; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.SerializableAs; -import org.jetbrains.annotations.NotNull; - -@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(@NotNull DyeColor color, @NotNull PatternType pattern) { - this.color = color; - this.pattern = pattern; - } - - /** - * Constructor for deserialization. - * - * @param map the map to deserialize from - */ - public Pattern(@NotNull Map map) { - color = DyeColor.legacyValueOf(getString(map, COLOR)); - pattern = PatternType.getByIdentifier(getString(map, PATTERN)); - } - - private static String getString(@NotNull Map map, @NotNull Object key) { - Object str = map.get(key); - if (str instanceof String) { - return (String) str; - } - throw new NoSuchElementException(map + " does not contain " + key); - } - - @NotNull - @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 - */ - @NotNull - public DyeColor getColor() { - return color; - } - - /** - * Returns the type of pattern - * - * @return the pattern type - */ - @NotNull - 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/api/src/main/java/org/bukkit/block/banner/PatternType.java b/api/src/main/java/org/bukkit/block/banner/PatternType.java deleted file mode 100644 index 754582aa0..000000000 --- a/api/src/main/java/org/bukkit/block/banner/PatternType.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.block.banner; - -import java.util.HashMap; -import java.util.Map; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -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"), - GLOBE("glb"); - - private final String identifier; - private static final Map byString = new HashMap(); - - static { - for (PatternType p : values()) { - byString.put(p.identifier, p); - } - } - - private PatternType(/*@NotNull*/ String key) { - this.identifier = key; - } - - /** - * Returns the identifier used to represent - * this pattern type - * - * @return the pattern's identifier - */ - @NotNull - 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 - */ - @Contract("null -> null") - @Nullable - public static PatternType getByIdentifier(@Nullable String identifier) { - return byString.get(identifier); - } -} diff --git a/api/src/main/java/org/bukkit/block/data/Ageable.java b/api/src/main/java/org/bukkit/block/data/Ageable.java deleted file mode 100644 index 2f7b84a3f..000000000 --- a/api/src/main/java/org/bukkit/block/data/Ageable.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'age' represents the different growth stages that a crop-like block can go - * through. - *
- * A value of 0 indicates that the crop was freshly planted, whilst a value - * equal to {@link #getMaximumAge()} indicates that the crop is ripe and ready - * to be harvested. - */ -public interface Ageable extends BlockData { - - /** - * Gets the value of the 'age' property. - * - * @return the 'age' value - */ - int getAge(); - - /** - * Sets the value of the 'age' property. - * - * @param age the new 'age' value - */ - void setAge(int age); - - /** - * Gets the maximum allowed value of the 'age' property. - * - * @return the maximum 'age' value - */ - int getMaximumAge(); -} diff --git a/api/src/main/java/org/bukkit/block/data/AnaloguePowerable.java b/api/src/main/java/org/bukkit/block/data/AnaloguePowerable.java deleted file mode 100644 index 68ec26a10..000000000 --- a/api/src/main/java/org/bukkit/block/data/AnaloguePowerable.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'power' represents the redstone power level currently being emitted or - * transmitted via this block. - *
- * May not be over 9000 or {@link #getMaximumPower()} (usually 15). - */ -public interface AnaloguePowerable extends BlockData { - - /** - * Gets the value of the 'power' property. - * - * @return the 'power' value - */ - int getPower(); - - /** - * Sets the value of the 'power' property. - * - * @param power the new 'power' value - */ - void setPower(int power); - - /** - * Gets the maximum allowed value of the 'power' property. - * - * @return the maximum 'power' value - */ - int getMaximumPower(); -} diff --git a/api/src/main/java/org/bukkit/block/data/Attachable.java b/api/src/main/java/org/bukkit/block/data/Attachable.java deleted file mode 100644 index 97c7fa728..000000000 --- a/api/src/main/java/org/bukkit/block/data/Attachable.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'attached' denotes whether a tripwire hook or string forms a complete - * tripwire circuit and is ready to trigger. - *
- * Updating the property on a tripwire hook will change the texture to indicate - * a connected string, but will not have any effect when used on the tripwire - * string itself. It may however still be used to check whether the string forms - * a circuit. - */ -public interface Attachable extends BlockData { - - /** - * Gets the value of the 'attached' property. - * - * @return the 'attached' value - */ - boolean isAttached(); - - /** - * Sets the value of the 'attached' property. - * - * @param attached the new 'attached' value - */ - void setAttached(boolean attached); -} diff --git a/api/src/main/java/org/bukkit/block/data/Bisected.java b/api/src/main/java/org/bukkit/block/data/Bisected.java deleted file mode 100644 index 7b7c0d2be..000000000 --- a/api/src/main/java/org/bukkit/block/data/Bisected.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.block.data; - -import org.jetbrains.annotations.NotNull; - -/** - * 'half' denotes which half of a two block tall material this block is. - *
- * In game it may be referred to as either (top, bottom) or (upper, lower). - */ -public interface Bisected extends BlockData { - - /** - * Gets the value of the 'half' property. - * - * @return the 'half' value - */ - @NotNull - Half getHalf(); - - /** - * Sets the value of the 'half' property. - * - * @param half the new 'half' value - */ - void setHalf(@NotNull Half half); - - /** - * The half of a vertically bisected block. - */ - public enum Half { - /** - * The top half of the block, normally with the higher y coordinate. - */ - TOP, - /** - * The bottom half of the block, normally with the lower y coordinate. - */ - BOTTOM; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/BlockData.java b/api/src/main/java/org/bukkit/block/data/BlockData.java deleted file mode 100644 index 22c5e84eb..000000000 --- a/api/src/main/java/org/bukkit/block/data/BlockData.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.bukkit.block.data; - -import org.bukkit.Material; -import org.bukkit.Server; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface BlockData extends Cloneable { - - /** - * Get the Material represented by this block data. - * - * @return the material - */ - @NotNull - Material getMaterial(); - - /** - * Gets a string, which when passed into a method such as - * {@link Server#createBlockData(java.lang.String)} will unambiguously - * recreate this instance. - * - * @return serialized data string for this block - */ - @NotNull - String getAsString(); - - /** - * Gets a string, which when passed into a method such as - * {@link Server#createBlockData(java.lang.String)} will recreate this or a - * similar instance where unspecified states (if any) may be optionally - * omitted. If this instance was parsed and states are omitted, this exact - * instance will be creatable when parsed again, else their equality cannot - * be guaranteed. - *

- * This method will only take effect for BlockData instances created by - * methods such as {@link Server#createBlockData(String)} or any similar - * method whereby states are optionally defined. If otherwise, the result of - * {@link #getAsString()} will be returned. The following behaviour would be - * expected: - *

{@code
-     * String dataString = "minecraft:chest[waterlogged=true]"
-     * BlockData data = Bukkit.createBlockData(dataString);
-     * dataString.equals(data.getAsString(true)); // This would return true
-     * dataString.equals(data.getAsString(false)); // This would return false as all states are present
-     * dataString.equals(data.getAsString()); // This is equivalent to the above, "getAsString(false)"
-     * }
- * - * @param hideUnspecified true if unspecified states should be omitted, - * false if they are to be shown as performed by {@link #getAsString()}. - * - * @return serialized data string for this block - */ - @NotNull - String getAsString(boolean hideUnspecified); - - /** - * Merges all explicitly set states from the given data with this BlockData. - *
- * Note that the given data MUST have been created from one of the String - * parse methods, e.g. {@link Server#createBlockData(java.lang.String)} and - * not have been subsequently modified. - *
- * Note also that the block types must match identically. - * - * @param data the data to merge from - * @return a new instance of this blockdata with the merged data - */ - @NotNull - BlockData merge(@NotNull BlockData data); - - /** - * Checks if the specified BlockData matches this block data. - *
- * The semantics of this method are such that for manually created or - * modified BlockData it has the same effect as - * {@link Object#equals(java.lang.Object)}, whilst for parsed data (that to - * which {@link #merge(org.bukkit.block.data.BlockData)} applies, it will - * return true when the type and all explicitly set states match. - *
- * Note that these semantics mean that a.matches(b) may not be the same - * as b.matches(a) - * - * @param data the data to match against (normally a parsed constant) - * @return if there is a match - */ - boolean matches(@Nullable BlockData data); - - /** - * Returns a copy of this BlockData. - * - * @return a copy of the block data - */ - @NotNull - BlockData clone(); -} diff --git a/api/src/main/java/org/bukkit/block/data/Directional.java b/api/src/main/java/org/bukkit/block/data/Directional.java deleted file mode 100644 index 825ff08dd..000000000 --- a/api/src/main/java/org/bukkit/block/data/Directional.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.block.data; - -import java.util.Set; -import org.bukkit.block.BlockFace; -import org.jetbrains.annotations.NotNull; - -/** - * 'facing' represents the face towards which the block is pointing. - *
- * Some blocks may not be able to face in all directions, use - * {@link #getFaces()} to get all possible directions for this block. - */ -public interface Directional extends BlockData { - - /** - * Gets the value of the 'facing' property. - * - * @return the 'facing' value - */ - @NotNull - BlockFace getFacing(); - - /** - * Sets the value of the 'facing' property. - * - * @param facing the new 'facing' value - */ - void setFacing(@NotNull BlockFace facing); - - /** - * Gets the faces which are applicable to this block. - * - * @return the allowed 'facing' values - */ - @NotNull - Set getFaces(); -} diff --git a/api/src/main/java/org/bukkit/block/data/Levelled.java b/api/src/main/java/org/bukkit/block/data/Levelled.java deleted file mode 100644 index 5255538fe..000000000 --- a/api/src/main/java/org/bukkit/block/data/Levelled.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'level' represents the amount of fluid contained within this block, either by - * itself or inside a cauldron. - *
- * In the case of water and lava blocks the levels have special meanings: a - * level of 0 corresponds to a source block, 1-7 regular fluid heights, and 8-15 - * to "falling" fluids. All falling fluids have the same behaviour, but the - * level corresponds to that of the block above them, equal to - * this.level - 8 - * Note that counterintuitively, an adjusted level of 1 is the highest level, - * whilst 7 is the lowest. - *
- * May not be higher than {@link #getMaximumLevel()}. - */ -public interface Levelled extends BlockData { - - /** - * Gets the value of the 'level' property. - * - * @return the 'level' value - */ - int getLevel(); - - /** - * Sets the value of the 'level' property. - * - * @param level the new 'level' value - */ - void setLevel(int level); - - /** - * Gets the maximum allowed value of the 'level' property. - * - * @return the maximum 'level' value - */ - int getMaximumLevel(); -} diff --git a/api/src/main/java/org/bukkit/block/data/Lightable.java b/api/src/main/java/org/bukkit/block/data/Lightable.java deleted file mode 100644 index 59a725e3a..000000000 --- a/api/src/main/java/org/bukkit/block/data/Lightable.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'lit' denotes whether this block (either a redstone torch or furnace) is - * currently lit - that is not burned out. - */ -public interface Lightable extends BlockData { - - /** - * Gets the value of the 'lit' property. - * - * @return the 'lit' value - */ - boolean isLit(); - - /** - * Sets the value of the 'lit' property. - * - * @param lit the new 'lit' value - */ - void setLit(boolean lit); -} diff --git a/api/src/main/java/org/bukkit/block/data/MultipleFacing.java b/api/src/main/java/org/bukkit/block/data/MultipleFacing.java deleted file mode 100644 index e790b7fdb..000000000 --- a/api/src/main/java/org/bukkit/block/data/MultipleFacing.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.block.data; - -import java.util.Set; -import org.bukkit.block.BlockFace; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * This class encompasses the 'north', 'east', 'south', 'west', 'up', 'down' - * boolean flags which are used to set which faces of the block textures are - * displayed on. - *
- * Some blocks may not be able to have faces on all directions, use - * {@link #getAllowedFaces()} to get all possible faces for this block. - */ -public interface MultipleFacing extends BlockData { - - /** - * Checks if this block has the specified face enabled. - * - * @param face to check - * @return if face is enabled - */ - boolean hasFace(@NotNull BlockFace face); - - /** - * Set whether this block has the specified face enabled. - * - * @param face to set - * @param has the face - */ - void setFace(@Nullable BlockFace face, boolean has); - - /** - * Get all of the faces which are enabled on this block. - * - * @return all faces enabled - */ - @NotNull - Set getFaces(); - - /** - * Gets all of this faces which may be set on this block. - * - * @return all allowed faces - */ - @NotNull - Set getAllowedFaces(); -} diff --git a/api/src/main/java/org/bukkit/block/data/Openable.java b/api/src/main/java/org/bukkit/block/data/Openable.java deleted file mode 100644 index c04944ed7..000000000 --- a/api/src/main/java/org/bukkit/block/data/Openable.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'open' denotes whether this door-like block is currently opened. - */ -public interface Openable extends BlockData { - - /** - * Gets the value of the 'open' property. - * - * @return the 'open' value - */ - boolean isOpen(); - - /** - * Sets the value of the 'open' property. - * - * @param open the new 'open' value - */ - void setOpen(boolean open); -} diff --git a/api/src/main/java/org/bukkit/block/data/Orientable.java b/api/src/main/java/org/bukkit/block/data/Orientable.java deleted file mode 100644 index 5b4561a16..000000000 --- a/api/src/main/java/org/bukkit/block/data/Orientable.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.block.data; - -import java.util.Set; -import org.bukkit.Axis; -import org.jetbrains.annotations.NotNull; - -/** - * 'axis' represents the axis along whilst this block is oriented. - *
- * Some blocks such as the portal block may not be able to be placed in all - * orientations, use {@link #getAxes()} to retrieve all possible such - * orientations. - */ -public interface Orientable extends BlockData { - - /** - * Gets the value of the 'axis' property. - * - * @return the 'axis' value - */ - @NotNull - Axis getAxis(); - - /** - * Sets the value of the 'axis' property. - * - * @param axis the new 'axis' value - */ - void setAxis(@NotNull Axis axis); - - /** - * Gets the axes which are applicable to this block. - * - * @return the allowed 'axis' values - */ - @NotNull - Set getAxes(); -} diff --git a/api/src/main/java/org/bukkit/block/data/Powerable.java b/api/src/main/java/org/bukkit/block/data/Powerable.java deleted file mode 100644 index 994f72f53..000000000 --- a/api/src/main/java/org/bukkit/block/data/Powerable.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'powered' indicates whether this block is in the powered state or not, i.e. - * receiving a redstone current of power > 0. - */ -public interface Powerable extends BlockData { - - /** - * Gets the value of the 'powered' property. - * - * @return the 'powered' value - */ - boolean isPowered(); - - /** - * Sets the value of the 'powered' property. - * - * @param powered the new 'powered' value - */ - void setPowered(boolean powered); -} diff --git a/api/src/main/java/org/bukkit/block/data/Rail.java b/api/src/main/java/org/bukkit/block/data/Rail.java deleted file mode 100644 index b89938800..000000000 --- a/api/src/main/java/org/bukkit/block/data/Rail.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.block.data; - -import java.util.Set; -import org.jetbrains.annotations.NotNull; - -/** - * 'shape' represents the current layout of a minecart rail. - *
- * Some types of rail may not be able to be laid out in all shapes, use - * {@link #getShapes()} to get those applicable to this block. - */ -public interface Rail extends BlockData { - - /** - * Gets the value of the 'shape' property. - * - * @return the 'shape' value - */ - @NotNull - Shape getShape(); - - /** - * Sets the value of the 'shape' property. - * - * @param shape the new 'shape' value - */ - void setShape(@NotNull Shape shape); - - /** - * Gets the shapes which are applicable to this block. - * - * @return the allowed 'shape' values - */ - @NotNull - Set getShapes(); - - /** - * The different types of shapes a rail block can occupy. - */ - public enum Shape { - - /** - * The rail runs flat along the north/south (Z) axis. - */ - NORTH_SOUTH, - /** - * The rail runs flat along the east/west (X) axis. - */ - EAST_WEST, - /** - * The rail ascends in the east (positive X) direction. - */ - ASCENDING_EAST, - /** - * The rail ascends in the west (negative X) direction. - */ - ASCENDING_WEST, - /** - * The rail ascends in the north (negative Z) direction. - */ - ASCENDING_NORTH, - /** - * The rail ascends in the south (positive Z) direction. - */ - ASCENDING_SOUTH, - /** - * The rail forms a curve connecting the south and east faces of the - * block. - */ - SOUTH_EAST, - /** - * The rail forms a curve connecting the south and west faces of the - * block. - */ - SOUTH_WEST, - /** - * The rail forms a curve connecting the north and west faces of the - * block. - */ - NORTH_WEST, - /** - * The rail forms a curve connecting the north and east faces of the - * block. - */ - NORTH_EAST; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/Rotatable.java b/api/src/main/java/org/bukkit/block/data/Rotatable.java deleted file mode 100644 index 3f60fbce4..000000000 --- a/api/src/main/java/org/bukkit/block/data/Rotatable.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.block.data; - -import org.bukkit.block.BlockFace; -import org.jetbrains.annotations.NotNull; - -/** - * 'rotation' represents the current rotation of this block. - */ -public interface Rotatable extends BlockData { - - /** - * Gets the value of the 'rotation' property. - * - * @return the 'rotation' value - */ - @NotNull - BlockFace getRotation(); - - /** - * Sets the value of the 'rotation' property. - * - * @param rotation the new 'rotation' value - */ - void setRotation(@NotNull BlockFace rotation); -} diff --git a/api/src/main/java/org/bukkit/block/data/Snowable.java b/api/src/main/java/org/bukkit/block/data/Snowable.java deleted file mode 100644 index dbb034ed8..000000000 --- a/api/src/main/java/org/bukkit/block/data/Snowable.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'snowy' denotes whether this block has a snow covered side and top texture - * (normally because the block above is snow). - */ -public interface Snowable extends BlockData { - - /** - * Gets the value of the 'snowy' property. - * - * @return the 'snowy' value - */ - boolean isSnowy(); - - /** - * Sets the value of the 'snowy' property. - * - * @param snowy the new 'snowy' value - */ - void setSnowy(boolean snowy); -} diff --git a/api/src/main/java/org/bukkit/block/data/Waterlogged.java b/api/src/main/java/org/bukkit/block/data/Waterlogged.java deleted file mode 100644 index 400cc9971..000000000 --- a/api/src/main/java/org/bukkit/block/data/Waterlogged.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.block.data; - -/** - * 'waterlogged' denotes whether this block has fluid in it. - */ -public interface Waterlogged extends BlockData { - - /** - * Gets the value of the 'waterlogged' property. - * - * @return the 'waterlogged' value - */ - boolean isWaterlogged(); - - /** - * Sets the value of the 'waterlogged' property. - * - * @param waterlogged the new 'waterlogged' value - */ - void setWaterlogged(boolean waterlogged); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Bamboo.java b/api/src/main/java/org/bukkit/block/data/type/Bamboo.java deleted file mode 100644 index 96b5add29..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Bamboo.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Ageable; -import org.jetbrains.annotations.NotNull; - -/** - * 'leaves' represents the size of the leaves on this bamboo block. - */ -public interface Bamboo extends Ageable, Sapling { - - /** - * Gets the value of the 'leaves' property. - * - * @return the 'leaves' value - */ - @NotNull - Leaves getLeaves(); - - /** - * Sets the value of the 'leaves' property. - * - * @param leaves the new 'leaves' value - */ - void setLeaves(@NotNull Leaves leaves); - - /** - * Bamboo leaf size. - */ - public enum Leaves { - - /** - * No leaves. - */ - NONE, - /** - * Small leaves. - */ - SMALL, - /** - * Large leaves. - */ - LARGE; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Bed.java b/api/src/main/java/org/bukkit/block/data/type/Bed.java deleted file mode 100644 index ed519bfeb..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Bed.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.Directional; -import org.jetbrains.annotations.NotNull; - -/** - * Similar to {@link Bisected}, 'part' denotes which half of the bed this block - * corresponds to. - *
- * 'occupied' property is a quick flag to check if a player is currently - * sleeping in this bed block. - */ -public interface Bed extends Directional { - - /** - * Gets the value of the 'part' property. - * - * @return the 'part' value - */ - @NotNull - Part getPart(); - - /** - * Sets the value of the 'part' property. - * - * @param part the new 'part' value - */ - void setPart(@NotNull Part part); - - /** - * Gets the value of the 'occupied' property. - * - * @return the 'occupied' value - */ - boolean isOccupied(); - - /** - * Horizontal half of a bed. - */ - public enum Part { - - /** - * The head is the upper part of the bed containing the pillow. - */ - HEAD, - /** - * The foot is the lower half of the bed. - */ - FOOT; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Bell.java b/api/src/main/java/org/bukkit/block/data/type/Bell.java deleted file mode 100644 index e83f41b23..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Bell.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.jetbrains.annotations.NotNull; - -/** - * 'attachment' denotes how the bell is attached to its block. - */ -public interface Bell extends Directional { - - /** - * Gets the value of the 'attachment' property. - * - * @return the 'attachment' value - */ - @NotNull - Attachment getAttachment(); - - /** - * Sets the value of the 'attachment' property. - * - * @param attachment the new 'attachment' value - */ - void setAttachment(@NotNull Attachment attachment); - - /** - * What the bell is attached to. - */ - public enum Attachment { - - /** - * Placed on floor. - */ - FLOOR, - /** - * Placed on ceiling. - */ - CEILING, - /** - * Placed on one wall. - */ - SINGLE_WALL, - /** - * Placed between two walls. - */ - DOUBLE_WALL; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/BrewingStand.java b/api/src/main/java/org/bukkit/block/data/type/BrewingStand.java deleted file mode 100644 index 6a7687d52..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/BrewingStand.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.block.data.type; - -import java.util.Set; -import org.bukkit.block.data.BlockData; -import org.jetbrains.annotations.NotNull; - -/** - * Interface to the 'has_bottle_0', 'has_bottle_1', 'has_bottle_2' flags on a - * brewing stand which indicate which bottles are rendered on the outside. - *
- * Stand may have 0, 1... {@link #getMaximumBottles()}-1 bottles. - */ -public interface BrewingStand extends BlockData { - - /** - * Checks if the stand has the following bottle - * - * @param bottle to check - * @return if bottle is present - */ - boolean hasBottle(int bottle); - - /** - * Set whether the stand has this bottle present. - * - * @param bottle to set - * @param has bottle - */ - void setBottle(int bottle, boolean has); - - /** - * Get the indexes of all the bottles present on this block. - * - * @return set of all bottles - */ - @NotNull - Set getBottles(); - - /** - * Get the maximum amount of bottles present on this stand. - * - * @return maximum bottle count - */ - int getMaximumBottles(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/BubbleColumn.java b/api/src/main/java/org/bukkit/block/data/type/BubbleColumn.java deleted file mode 100644 index 5ab82d209..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/BubbleColumn.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'drag' indicates whether a force will be applied on entities moving through - * this block. - */ -public interface BubbleColumn extends BlockData { - - /** - * Gets the value of the 'drag' property. - * - * @return the 'part' value - */ - boolean isDrag(); - - /** - * Sets the value of the 'drag' property. - * - * @param drag the new 'drag' value - */ - void setDrag(boolean drag); - -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Cake.java b/api/src/main/java/org/bukkit/block/data/type/Cake.java deleted file mode 100644 index 65c9ea1e8..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Cake.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'bites' represents the amount of bites which have been taken from this slice - * of cake. - *
- * A value of 0 indicates that the cake has not been eaten, whilst a value of - * {@link #getMaximumBites()} indicates that it is all gone :( - */ -public interface Cake extends BlockData { - - /** - * Gets the value of the 'bites' property. - * - * @return the 'bites' value - */ - int getBites(); - - /** - * Sets the value of the 'bites' property. - * - * @param bites the new 'bites' value - */ - void setBites(int bites); - - /** - * Gets the maximum allowed value of the 'bites' property. - * - * @return the maximum 'bites' value - */ - int getMaximumBites(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Campfire.java b/api/src/main/java/org/bukkit/block/data/type/Campfire.java deleted file mode 100644 index bc5159b40..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Campfire.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Lightable; -import org.bukkit.block.data.Waterlogged; - -/** - * 'signal_fire' denotes whether the fire is extra smokey due to having a hay - * bale placed beneath it. - */ -public interface Campfire extends Lightable, Waterlogged { - - /** - * Gets the value of the 'signal_fire' property. - * - * @return the 'signal_fire' value - */ - boolean isSignalFire(); - - /** - * Sets the value of the 'signal_fire' property. - * - * @param signalFire the new 'signal_fire' value - */ - void setSignalFire(boolean signalFire); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Chest.java b/api/src/main/java/org/bukkit/block/data/type/Chest.java deleted file mode 100644 index d79c3d000..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Chest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Waterlogged; -import org.jetbrains.annotations.NotNull; - -/** - * 'type' represents which part of a double chest this block is, or if it is a - * single chest. - */ -public interface Chest extends Directional, Waterlogged { - - /** - * Gets the value of the 'type' property. - * - * @return the 'type' value - */ - @NotNull - Type getType(); - - /** - * Sets the value of the 'type' property. - * - * @param type the new 'type' value - */ - void setType(@NotNull Type type); - - /** - * Type of this chest block. - *
- * NB: Left and right are relative to the chest itself, i.e opposite to what - * a player placing the appropriate block would see. - */ - public enum Type { - /** - * The chest is not linked to any others and contains only one 27 slot - * inventory. - */ - SINGLE, - /** - * The chest is the left hand side of a double chest and shares a 54 - * block inventory with the chest to its right. - */ - LEFT, - /** - * The chest is the right hand side of a double chest and shares a 54 - * block inventory with the chest to its left. - */ - RIGHT; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Cocoa.java b/api/src/main/java/org/bukkit/block/data/type/Cocoa.java deleted file mode 100644 index 092e46c72..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Cocoa.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Ageable; -import org.bukkit.block.data.Directional; - -public interface Cocoa extends Ageable, Directional { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/CommandBlock.java b/api/src/main/java/org/bukkit/block/data/type/CommandBlock.java deleted file mode 100644 index 9a7122c90..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/CommandBlock.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; - -/** - * 'conditional' denotes whether this command block is conditional or not, i.e. - * will only execute if the preceeding command block also executed successfully. - */ -public interface CommandBlock extends Directional { - - /** - * Gets the value of the 'conditional' property. - * - * @return the 'conditional' value - */ - boolean isConditional(); - - /** - * Sets the value of the 'conditional' property. - * - * @param conditional the new 'conditional' value - */ - void setConditional(boolean conditional); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Comparator.java b/api/src/main/java/org/bukkit/block/data/type/Comparator.java deleted file mode 100644 index 6cfd29660..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Comparator.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; -import org.jetbrains.annotations.NotNull; - -/** - * 'mode' indicates what mode this comparator will operate in. - */ -public interface Comparator extends Directional, Powerable { - - /** - * Gets the value of the 'mode' property. - * - * @return the 'mode' value - */ - @NotNull - Mode getMode(); - - /** - * Sets the value of the 'mode' property. - * - * @param mode the new 'mode' value - */ - void setMode(@NotNull Mode mode); - - /** - * The mode in which a comparator will operate in. - */ - public enum Mode { - - /** - * The default mode, similar to a transistor. The comparator will turn - * off if either side input is greater than the rear input. - */ - COMPARE, - /** - * Alternate subtraction mode. The output signal strength will be equal - * to max(rear-max(left,right),0). - */ - SUBTRACT; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/CoralWallFan.java b/api/src/main/java/org/bukkit/block/data/type/CoralWallFan.java deleted file mode 100644 index 3b92d4f99..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/CoralWallFan.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Waterlogged; - -public interface CoralWallFan extends Directional, Waterlogged { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/DaylightDetector.java b/api/src/main/java/org/bukkit/block/data/type/DaylightDetector.java deleted file mode 100644 index deefb6c62..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/DaylightDetector.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.AnaloguePowerable; - -/** - * 'inverted' denotes whether this daylight detector is in the inverted mode, - * i.e. activates in the absence of light rather than presence." - */ -public interface DaylightDetector extends AnaloguePowerable { - - /** - * Gets the value of the 'inverted' property. - * - * @return the 'inverted' value - */ - boolean isInverted(); - - /** - * Sets the value of the 'inverted' property. - * - * @param inverted the new 'inverted' value - */ - void setInverted(boolean inverted); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Dispenser.java b/api/src/main/java/org/bukkit/block/data/type/Dispenser.java deleted file mode 100644 index fea25e1c2..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Dispenser.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; - -/** - * Similar to {@link Powerable}, 'triggered' indicates whether or not the - * dispenser is currently activated. - */ -public interface Dispenser extends Directional { - - /** - * Gets the value of the 'triggered' property. - * - * @return the 'triggered' value - */ - boolean isTriggered(); - - /** - * Sets the value of the 'triggered' property. - * - * @param triggered the new 'triggered' value - */ - void setTriggered(boolean triggered); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Door.java b/api/src/main/java/org/bukkit/block/data/type/Door.java deleted file mode 100644 index 5b0bba5ef..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Door.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Openable; -import org.bukkit.block.data.Powerable; -import org.jetbrains.annotations.NotNull; - -/** - * 'hinge' indicates which hinge this door is attached to and will rotate around - * when opened. - */ -public interface Door extends Bisected, Directional, Openable, Powerable { - - /** - * Gets the value of the 'hinge' property. - * - * @return the 'hinge' value - */ - @NotNull - Hinge getHinge(); - - /** - * Sets the value of the 'hinge' property. - * - * @param hinge the new 'hinge' value - */ - void setHinge(@NotNull Hinge hinge); - - /** - * The hinge of a door. - */ - public enum Hinge { - /** - * Door is attached to the left side. - */ - LEFT, - /** - * Door is attached to the right side. - */ - RIGHT; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/EndPortalFrame.java b/api/src/main/java/org/bukkit/block/data/type/EndPortalFrame.java deleted file mode 100644 index 6c181d633..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/EndPortalFrame.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; - -/** - * 'eye' denotes whether this end portal frame has been activated by having an - * eye of ender placed in it. - */ -public interface EndPortalFrame extends Directional { - - /** - * Gets the value of the 'eye' property. - * - * @return the 'eye' value - */ - boolean hasEye(); - - /** - * Sets the value of the 'eye' property. - * - * @param eye the new 'eye' value - */ - void setEye(boolean eye); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/EnderChest.java b/api/src/main/java/org/bukkit/block/data/type/EnderChest.java deleted file mode 100644 index 5a9e04c4a..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/EnderChest.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Waterlogged; - -public interface EnderChest extends Directional, Waterlogged { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Farmland.java b/api/src/main/java/org/bukkit/block/data/type/Farmland.java deleted file mode 100644 index a9fff6f61..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Farmland.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * The 'moisture' level of farmland indicates how close it is to a water source - * (if any). - *
- * A higher moisture level leads, to faster growth of crops on this block, but - * cannot be higher than {@link #getMaximumMoisture()}. - */ -public interface Farmland extends BlockData { - - /** - * Gets the value of the 'moisture' property. - * - * @return the 'moisture' value - */ - int getMoisture(); - - /** - * Sets the value of the 'moisture' property. - * - * @param moisture the new 'moisture' value - */ - void setMoisture(int moisture); - - /** - * Gets the maximum allowed value of the 'moisture' property. - * - * @return the maximum 'moisture' value - */ - int getMaximumMoisture(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Fence.java b/api/src/main/java/org/bukkit/block/data/type/Fence.java deleted file mode 100644 index f2c627421..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Fence.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.MultipleFacing; -import org.bukkit.block.data.Waterlogged; - -public interface Fence extends MultipleFacing, Waterlogged { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Fire.java b/api/src/main/java/org/bukkit/block/data/type/Fire.java deleted file mode 100644 index 6282d021e..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Fire.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Ageable; -import org.bukkit.block.data.MultipleFacing; - -/** - * md_5's mixtape. - */ -public interface Fire extends Ageable, MultipleFacing { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Furnace.java b/api/src/main/java/org/bukkit/block/data/type/Furnace.java deleted file mode 100644 index 830366ce0..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Furnace.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Lightable; - -public interface Furnace extends Directional, Lightable { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Gate.java b/api/src/main/java/org/bukkit/block/data/type/Gate.java deleted file mode 100644 index 494f97d47..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Gate.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Openable; -import org.bukkit.block.data.Powerable; - -/** - * 'in_wall" indicates if the fence gate is attached to a wall, and if true the - * texture is lowered by a small amount to blend in better. - */ -public interface Gate extends Directional, Openable, Powerable { - - /** - * Gets the value of the 'in_wall' property. - * - * @return the 'in_wall' value - */ - boolean isInWall(); - - /** - * Sets the value of the 'in_wall' property. - * - * @param inWall the new 'in_wall' value - */ - void setInWall(boolean inWall); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/GlassPane.java b/api/src/main/java/org/bukkit/block/data/type/GlassPane.java deleted file mode 100644 index 44eaa553c..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/GlassPane.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.MultipleFacing; -import org.bukkit.block.data.Waterlogged; - -public interface GlassPane extends MultipleFacing, Waterlogged { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Hopper.java b/api/src/main/java/org/bukkit/block/data/type/Hopper.java deleted file mode 100644 index b176fc8b6..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Hopper.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; - -/** - * Similar to {@link Powerable}, 'enabled' indicates whether or not the hopper - * is currently activated. - *
- * Unlike most other blocks, a hopper is only enabled when it is not - * receiving any power. - */ -public interface Hopper extends Directional { - - /** - * Gets the value of the 'enabled' property. - * - * @return the 'enabled' value - */ - boolean isEnabled(); - - /** - * Sets the value of the 'enabled' property. - * - * @param enabled the new 'enabled' value - */ - void setEnabled(boolean enabled); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Jukebox.java b/api/src/main/java/org/bukkit/block/data/type/Jukebox.java deleted file mode 100644 index 5e3713620..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Jukebox.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'has_record' is a quick flag to check whether this jukebox has a record - * inside it. - */ -public interface Jukebox extends BlockData { - - /** - * Gets the value of the 'has_record' property. - * - * @return the 'has_record' value - */ - boolean hasRecord(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Ladder.java b/api/src/main/java/org/bukkit/block/data/type/Ladder.java deleted file mode 100644 index ee1b340f2..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Ladder.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Waterlogged; - -public interface Ladder extends Directional, Waterlogged { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Lantern.java b/api/src/main/java/org/bukkit/block/data/type/Lantern.java deleted file mode 100644 index a6c35655a..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Lantern.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'hanging' denotes whether the lantern is hanging from a block. - */ -public interface Lantern extends BlockData { - - /** - * Gets the value of the 'hanging' property. - * - * @return the 'hanging' value - */ - boolean isHanging(); - - /** - * Sets the value of the 'hanging' property. - * - * @param hanging the new 'hanging' value - */ - void setHanging(boolean hanging); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Leaves.java b/api/src/main/java/org/bukkit/block/data/type/Leaves.java deleted file mode 100644 index 3874d5d96..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Leaves.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'persistent' indicates whether or not leaves will be checked by the server to - * see if they are subject to decay or not. - *
- * 'distance' denotes how far the block is from a tree and is used in - * conjunction with 'persistent' flag to determine if the leaves will decay or - * not. - */ -public interface Leaves extends BlockData { - - /** - * Gets the value of the 'persistent' property. - * - * @return the persistent value - */ - boolean isPersistent(); - - /** - * Sets the value of the 'persistent' property. - * - * @param persistent the new 'persistent' value - */ - void setPersistent(boolean persistent); - - /** - * Gets the value of the 'distance' property. - * - * @return the 'distance' value - */ - int getDistance(); - - /** - * Sets the value of the 'distance' property. - * - * @param distance the new 'distance' value - */ - void setDistance(int distance); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Lectern.java b/api/src/main/java/org/bukkit/block/data/type/Lectern.java deleted file mode 100644 index 11b4a173f..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Lectern.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; - -/** - * 'has_book' is a quick flag to check whether this lectern has a book inside - * it. - */ -public interface Lectern extends Directional, Powerable { - - /** - * Gets the value of the 'has_book' property. - * - * @return the 'has_book' value - */ - boolean hasBook(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/NoteBlock.java b/api/src/main/java/org/bukkit/block/data/type/NoteBlock.java deleted file mode 100644 index ec48ca8ca..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/NoteBlock.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.Instrument; -import org.bukkit.Note; -import org.bukkit.block.data.Powerable; -import org.jetbrains.annotations.NotNull; - -/** - * 'instrument' is the type of sound made when this note block is activated. - *
- * 'note' is the specified tuned pitch that the instrument will be played in. - */ -public interface NoteBlock extends Powerable { - - /** - * Gets the value of the 'instrument' property. - * - * @return the 'instrument' value - */ - @NotNull - Instrument getInstrument(); - - /** - * Sets the value of the 'instrument' property. - * - * @param instrument the new 'instrument' value - */ - void setInstrument(@NotNull Instrument instrument); - - /** - * Gets the value of the 'note' property. - * - * @return the 'note' value - */ - @NotNull - Note getNote(); - - /** - * Sets the value of the 'note' property. - * - * @param note the new 'note' value - */ - void setNote(@NotNull Note note); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Observer.java b/api/src/main/java/org/bukkit/block/data/type/Observer.java deleted file mode 100644 index f40c73500..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Observer.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; - -public interface Observer extends Directional, Powerable { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Piston.java b/api/src/main/java/org/bukkit/block/data/type/Piston.java deleted file mode 100644 index 9eec7317b..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Piston.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; - -/** - * 'extended' denotes whether the piston head is currently extended or not. - */ -public interface Piston extends Directional { - - /** - * Gets the value of the 'extended' property. - * - * @return the 'extended' value - */ - boolean isExtended(); - - /** - * Sets the value of the 'extended' property. - * - * @param extended the new 'extended' value - */ - void setExtended(boolean extended); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/PistonHead.java b/api/src/main/java/org/bukkit/block/data/type/PistonHead.java deleted file mode 100644 index d1eaa20a0..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/PistonHead.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.block.data.type; - -/** - * 'short' denotes this piston head is shorter than the usual amount because it - * is currently retracting. - */ -public interface PistonHead extends TechnicalPiston { - - /** - * Gets the value of the 'short' property. - * - * @return the 'short' value - */ - boolean isShort(); - - /** - * Sets the value of the 'short' property. - * - * @param _short the new 'short' value - */ - void setShort(boolean _short); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/RedstoneRail.java b/api/src/main/java/org/bukkit/block/data/type/RedstoneRail.java deleted file mode 100644 index 1cf7630c3..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/RedstoneRail.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Powerable; -import org.bukkit.block.data.Rail; - -/** - * A type of minecart rail which interacts with redstone in one way or another. - */ -public interface RedstoneRail extends Powerable, Rail { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/RedstoneWallTorch.java b/api/src/main/java/org/bukkit/block/data/type/RedstoneWallTorch.java deleted file mode 100644 index 7e1e09859..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/RedstoneWallTorch.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Lightable; - -public interface RedstoneWallTorch extends Directional, Lightable { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/RedstoneWire.java b/api/src/main/java/org/bukkit/block/data/type/RedstoneWire.java deleted file mode 100644 index ba8a80ee3..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/RedstoneWire.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.block.data.type; - -import java.util.Set; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.AnaloguePowerable; -import org.jetbrains.annotations.NotNull; - -/** - * 'north', 'east', 'south', 'west' represent the types of connections this - * redstone wire has to adjacent blocks. - */ -public interface RedstoneWire extends AnaloguePowerable { - - /** - * Checks the type of connection on the specified face. - * - * @param face to check - * @return connection type - */ - @NotNull - Connection getFace(@NotNull BlockFace face); - - /** - * Sets the type of connection on the specified face. - * - * @param face to set - * @param connection the connection type - */ - void setFace(@NotNull BlockFace face, @NotNull Connection connection); - - /** - * Gets all of this faces which may be set on this block. - * - * @return all allowed faces - */ - @NotNull - Set getAllowedFaces(); - - /** - * The way in which a redstone wire can connect to an adjacent block face. - */ - public enum Connection { - /** - * The wire travels up the side of the block adjacent to this face. - */ - UP, - /** - * The wire travels flat from this face and into the adjacent block. - */ - SIDE, - /** - * The wire does not connect in this direction. - */ - NONE; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Repeater.java b/api/src/main/java/org/bukkit/block/data/type/Repeater.java deleted file mode 100644 index a78563ed8..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Repeater.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; - -/** - * 'delay' is the propagation delay of a repeater, i.e. how many ticks before it - * will be activated from a current change and propagate it to the next block. - *
- * Delay may not be lower than {@link #getMinimumDelay()} or higher than - * {@link #getMaximumDelay()}. - *
- * 'locked' denotes whether the repeater is in the locked state or not. - *
- * A locked repeater will not change its output until it is unlocked. In game, a - * locked repeater is created by having a constant current perpendicularly - * entering the block. - */ -public interface Repeater extends Directional, Powerable { - - /** - * Gets the value of the 'delay' property. - * - * @return the 'delay' value - */ - int getDelay(); - - /** - * Sets the value of the 'delay' property. - * - * @param delay the new 'delay' value - */ - void setDelay(int delay); - - /** - * Gets the minimum allowed value of the 'delay' property. - * - * @return the minimum 'delay' value - */ - int getMinimumDelay(); - - /** - * Gets the maximum allowed value of the 'delay' property. - * - * @return the maximum 'delay' value - */ - int getMaximumDelay(); - - /** - * Gets the value of the 'locked' property. - * - * @return the 'locked' value - */ - boolean isLocked(); - - /** - * Sets the value of the 'locked' property. - * - * @param locked the new 'locked' value - */ - void setLocked(boolean locked); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Sapling.java b/api/src/main/java/org/bukkit/block/data/type/Sapling.java deleted file mode 100644 index a4e1c2f4c..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Sapling.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'stage' represents the growth stage of a sapling. - *
- * When the sapling reaches {@link #getMaximumStage()} it will attempt to grow - * into a tree as the next stage. - */ -public interface Sapling extends BlockData { - - /** - * Gets the value of the 'stage' property. - * - * @return the 'stage' value - */ - int getStage(); - - /** - * Sets the value of the 'stage' property. - * - * @param stage the new 'stage' value - */ - void setStage(int stage); - - /** - * Gets the maximum allowed value of the 'stage' property. - * - * @return the maximum 'stage' value - */ - int getMaximumStage(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Scaffolding.java b/api/src/main/java/org/bukkit/block/data/type/Scaffolding.java deleted file mode 100644 index 1f6859eee..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Scaffolding.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Waterlogged; - -/** - * 'bottom' indicates whether the scaffolding is floating or not. - *
- * 'distance' indicates the distance from a scaffolding block placed above a - * 'bottom' scaffold. - *
- * When 'distance' reaches {@link #getMaximumDistance()} the block will drop. - */ -public interface Scaffolding extends Waterlogged { - - /** - * Gets the value of the 'bottom' property. - * - * @return the 'bottom' value - */ - boolean isBottom(); - - /** - * Sets the value of the 'bottom' property. - * - * @param bottom the new 'bottom' value - */ - void setBottom(boolean bottom); - - /** - * Gets the value of the 'distance' property. - * - * @return the 'distance' value - */ - int getDistance(); - - /** - * Sets the value of the 'distance' property. - * - * @param distance the new 'distance' value - */ - void setDistance(int distance); - - /** - * Gets the maximum allowed value of the 'distance' property. - * - * @return the maximum 'distance' value - */ - int getMaximumDistance(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/SeaPickle.java b/api/src/main/java/org/bukkit/block/data/type/SeaPickle.java deleted file mode 100644 index 62013c6af..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/SeaPickle.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Waterlogged; - -/** - * 'pickles' indicates the number of pickles in this block. - */ -public interface SeaPickle extends Waterlogged { - - /** - * Gets the value of the 'pickles' property. - * - * @return the 'pickles' value - */ - int getPickles(); - - /** - * Sets the value of the 'pickles' property. - * - * @param pickles the new 'pickles' value - */ - void setPickles(int pickles); - - /** - * Gets the minimum allowed value of the 'pickles' property. - * - * @return the minimum 'pickles' value - */ - int getMinimumPickles(); - - /** - * Gets the maximum allowed value of the 'pickles' property. - * - * @return the maximum 'pickles' value - */ - int getMaximumPickles(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Sign.java b/api/src/main/java/org/bukkit/block/data/type/Sign.java deleted file mode 100644 index 29ef2c5bf..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Sign.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Rotatable; -import org.bukkit.block.data.Waterlogged; - -public interface Sign extends Rotatable, Waterlogged { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Slab.java b/api/src/main/java/org/bukkit/block/data/type/Slab.java deleted file mode 100644 index cb09c3268..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Slab.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Waterlogged; -import org.jetbrains.annotations.NotNull; - -/** - * 'type' represents what state the slab is in - either top, bottom, or a double - * slab occupying the full block. - */ -public interface Slab extends Waterlogged { - - /** - * Gets the value of the 'type' property. - * - * @return the 'type' value - */ - @NotNull - Type getType(); - - /** - * Sets the value of the 'type' property. - * - * @param type the new 'type' value - */ - void setType(@NotNull Type type); - - /** - * The type of the slab. - */ - public enum Type { - /** - * The slab occupies the upper y half of the block. - */ - TOP, - /** - * The slab occupies the lower y half of the block. - */ - BOTTOM, - /** - * The slab occupies the entire block. - */ - DOUBLE; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Snow.java b/api/src/main/java/org/bukkit/block/data/type/Snow.java deleted file mode 100644 index 9c089cff2..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Snow.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'layers' represents the amount of layers of snow which are present in this - * block. - *
- * May not be lower than {@link #getMinimumLayers()} or higher than - * {@link #getMaximumLayers()}. - */ -public interface Snow extends BlockData { - - /** - * Gets the value of the 'layers' property. - * - * @return the 'layers' value - */ - int getLayers(); - - /** - * Sets the value of the 'layers' property. - * - * @param layers the new 'layers' value - */ - void setLayers(int layers); - - /** - * Gets the minimum allowed value of the 'layers' property. - * - * @return the minimum 'layers' value - */ - int getMinimumLayers(); - - /** - * Gets the maximum allowed value of the 'layers' property. - * - * @return the maximum 'layers' value - */ - int getMaximumLayers(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Stairs.java b/api/src/main/java/org/bukkit/block/data/type/Stairs.java deleted file mode 100644 index 8bc553956..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Stairs.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Waterlogged; -import org.jetbrains.annotations.NotNull; - -/** - * 'shape' represents the texture and bounding box shape of these stairs. - */ -public interface Stairs extends Bisected, Directional, Waterlogged { - - /** - * Gets the value of the 'shape' property. - * - * @return the 'shape' value - */ - @NotNull - Shape getShape(); - - /** - * Sets the value of the 'shape' property. - * - * @param shape the new 'shape' value - */ - void setShape(@NotNull Shape shape); - - /** - * The shape of a stair block - used for constructing corners. - */ - public enum Shape { - /** - * Regular stair block. - */ - STRAIGHT, - /** - * Inner corner stair block with higher left side. - */ - INNER_LEFT, - /** - * Inner corner stair block with higher right side. - */ - INNER_RIGHT, - /** - * Outer corner stair block with higher left side. - */ - OUTER_LEFT, - /** - * Outer corner stair block with higher right side. - */ - OUTER_RIGHT; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/StructureBlock.java b/api/src/main/java/org/bukkit/block/data/type/StructureBlock.java deleted file mode 100644 index 3c13a9a56..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/StructureBlock.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; -import org.jetbrains.annotations.NotNull; - -/** - * 'mode' represents the different modes in which this structure block may - * operate. - */ -public interface StructureBlock extends BlockData { - - /** - * Gets the value of the 'mode' property. - * - * @return the 'mode' value - */ - @NotNull - Mode getMode(); - - /** - * Sets the value of the 'mode' property. - * - * @param mode the new 'mode' value - */ - void setMode(@NotNull Mode mode); - - /** - * Operating mode of a structure block. - */ - public enum Mode { - /** - * Allows selection and saving of a structure. - */ - SAVE, - /** - * Allows loading of a structure. - */ - LOAD, - /** - * Used for detection of two opposite corners of a structure. - */ - CORNER, - /** - * Dummy block used to run a custom function during world generation - * before being removed. - */ - DATA; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Switch.java b/api/src/main/java/org/bukkit/block/data/type/Switch.java deleted file mode 100644 index 1060cb55b..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Switch.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; -import org.jetbrains.annotations.NotNull; - -/** - * 'face' represents the face to which a lever or button is stuck. - *
- * This is used in conjunction with {@link Directional} to compute the - * orientation of these blocks. - */ -public interface Switch extends Directional, Powerable { - - /** - * Gets the value of the 'face' property. - * - * @return the 'face' value - */ - @NotNull - Face getFace(); - - /** - * Sets the value of the 'face' property. - * - * @param face the new 'face' value - */ - void setFace(@NotNull Face face); - - /** - * The face to which a switch type block is stuck. - */ - public enum Face { - /** - * The switch is mounted to the floor and pointing upwards. - */ - FLOOR, - /** - * The switch is mounted to the wall. - */ - WALL, - /** - * The switch is mounted to the ceiling and pointing dowanrds. - */ - CEILING; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/TNT.java b/api/src/main/java/org/bukkit/block/data/type/TNT.java deleted file mode 100644 index 7008c20fd..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/TNT.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'unstable' indicates whether this TNT will explode on punching. - */ -public interface TNT extends BlockData { - - /** - * Gets the value of the 'unstable' property. - * - * @return the 'unstable' value - */ - boolean isUnstable(); - - /** - * Sets the value of the 'unstable' property. - * - * @param unstable the new 'unstable' value - */ - void setUnstable(boolean unstable); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/TechnicalPiston.java b/api/src/main/java/org/bukkit/block/data/type/TechnicalPiston.java deleted file mode 100644 index 4c8b6e9be..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/TechnicalPiston.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.jetbrains.annotations.NotNull; - -/** - * 'type' represents the type of piston which this (technical) block corresponds - * to. - */ -public interface TechnicalPiston extends Directional { - - /** - * Gets the value of the 'type' property. - * - * @return the 'type' value - */ - @NotNull - Type getType(); - - /** - * Sets the value of the 'type' property. - * - * @param type the new 'type' value - */ - void setType(@NotNull Type type); - - /** - * Different piston variants. - */ - public enum Type { - /** - * A normal piston which does not pull connected blocks backwards on - * retraction. - */ - NORMAL, - /** - * A sticky piston which will also retract connected blocks. - */ - STICKY; - } -} diff --git a/api/src/main/java/org/bukkit/block/data/type/TrapDoor.java b/api/src/main/java/org/bukkit/block/data/type/TrapDoor.java deleted file mode 100644 index 13876b379..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/TrapDoor.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Openable; -import org.bukkit.block.data.Powerable; -import org.bukkit.block.data.Waterlogged; - -public interface TrapDoor extends Bisected, Directional, Openable, Powerable, Waterlogged { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/Tripwire.java b/api/src/main/java/org/bukkit/block/data/type/Tripwire.java deleted file mode 100644 index 567f6f00f..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/Tripwire.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Attachable; -import org.bukkit.block.data.MultipleFacing; -import org.bukkit.block.data.Powerable; - -/** - * 'disarmed' denotes that the tripwire was broken with shears and will not - * subsequently produce a current when destroyed. - */ -public interface Tripwire extends Attachable, MultipleFacing, Powerable { - - /** - * Gets the value of the 'disarmed' property. - * - * @return the 'disarmed' value - */ - boolean isDisarmed(); - - /** - * Sets the value of the 'disarmed' property. - * - * @param disarmed the new 'disarmed' value - */ - void setDisarmed(boolean disarmed); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/TripwireHook.java b/api/src/main/java/org/bukkit/block/data/type/TripwireHook.java deleted file mode 100644 index 1e450761f..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/TripwireHook.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Attachable; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; - -public interface TripwireHook extends Attachable, Directional, Powerable { -} diff --git a/api/src/main/java/org/bukkit/block/data/type/TurtleEgg.java b/api/src/main/java/org/bukkit/block/data/type/TurtleEgg.java deleted file mode 100644 index a88fad4af..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/TurtleEgg.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.BlockData; - -/** - * 'hatch' is the number of turtles which may hatch from these eggs. - *
- * 'eggs' is the number of eggs which appear in this block. - */ -public interface TurtleEgg extends BlockData { - - /** - * Gets the value of the 'eggs' property. - * - * @return the 'eggs' value - */ - int getEggs(); - - /** - * Sets the value of the 'eggs' property. - * - * @param eggs the new 'eggs' value - */ - void setEggs(int eggs); - - /** - * Gets the minimum allowed value of the 'eggs' property. - * - * @return the minimum 'eggs' value - */ - int getMinimumEggs(); - - /** - * Gets the maximum allowed value of the 'eggs' property. - * - * @return the maximum 'eggs' value - */ - int getMaximumEggs(); - - /** - * Gets the value of the 'hatch' property. - * - * @return the 'hatch' value - */ - int getHatch(); - - /** - * Sets the value of the 'hatch' property. - * - * @param hatch the new 'hatch' value - */ - void setHatch(int hatch); - - /** - * Gets the maximum allowed value of the 'hatch' property. - * - * @return the maximum 'hatch' value - */ - int getMaximumHatch(); -} diff --git a/api/src/main/java/org/bukkit/block/data/type/WallSign.java b/api/src/main/java/org/bukkit/block/data/type/WallSign.java deleted file mode 100644 index 66238859d..000000000 --- a/api/src/main/java/org/bukkit/block/data/type/WallSign.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.block.data.type; - -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Waterlogged; - -public interface WallSign extends Directional, Waterlogged { -} diff --git a/api/src/main/java/org/bukkit/block/structure/Mirror.java b/api/src/main/java/org/bukkit/block/structure/Mirror.java deleted file mode 100644 index 86e812a1b..000000000 --- a/api/src/main/java/org/bukkit/block/structure/Mirror.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.block.structure; - -/** - * Represents how a {@link org.bukkit.block.Structure} can be mirrored upon - * being loaded. - */ -public enum Mirror { - - /** - * No mirroring. - *
- * Positive X to Positive Z - */ - NONE, - /** - * Structure is mirrored left to right. - *
- * Similar to looking in a mirror. Positive X to Negative Z - */ - LEFT_RIGHT, - /** - * Structure is mirrored front to back. - *
- * Positive Z to Negative X - */ - FRONT_BACK; -} diff --git a/api/src/main/java/org/bukkit/block/structure/StructureRotation.java b/api/src/main/java/org/bukkit/block/structure/StructureRotation.java deleted file mode 100644 index 0d0bfca43..000000000 --- a/api/src/main/java/org/bukkit/block/structure/StructureRotation.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.block.structure; - -/** - * Represents how a {@link org.bukkit.block.Structure} can be rotated. - */ -public enum StructureRotation { - - /** - * No rotation. - */ - NONE, - /** - * Rotated clockwise 90 degrees. - */ - CLOCKWISE_90, - /** - * Rotated clockwise 180 degrees. - */ - CLOCKWISE_180, - /** - * Rotated counter clockwise 90 degrees. - *
- * Equivalent to rotating clockwise 270 degrees. - */ - COUNTERCLOCKWISE_90; -} diff --git a/api/src/main/java/org/bukkit/block/structure/UsageMode.java b/api/src/main/java/org/bukkit/block/structure/UsageMode.java deleted file mode 100644 index cbea3f386..000000000 --- a/api/src/main/java/org/bukkit/block/structure/UsageMode.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.block.structure; - -/** - * Represents how a {@link org.bukkit.block.Structure} can be used. - */ -public enum UsageMode { - - /** - * The mode used when saving a structure. - */ - SAVE, - /** - * The mode used when loading a structure. - */ - LOAD, - /** - * Used when saving a structure for easy size calculation. When using this - * mode, the Structure name MUST match the name in the second Structure - * block that is in {@link UsageMode#SAVE}. - */ - CORNER, - /** - * Used to run specific custom functions, which can only be used for certain - * Structures. The structure block is removed after this function completes. - * The data tags (functions) can be found on the - * wiki. - */ - DATA; -} diff --git a/api/src/main/java/org/bukkit/boss/BarColor.java b/api/src/main/java/org/bukkit/boss/BarColor.java deleted file mode 100644 index e191d9ffe..000000000 --- a/api/src/main/java/org/bukkit/boss/BarColor.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bukkit.boss; - -public enum BarColor { - PINK, - BLUE, - RED, - GREEN, - YELLOW, - PURPLE, - WHITE -} diff --git a/api/src/main/java/org/bukkit/boss/BarFlag.java b/api/src/main/java/org/bukkit/boss/BarFlag.java deleted file mode 100644 index 69e02998d..000000000 --- a/api/src/main/java/org/bukkit/boss/BarFlag.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.boss; - -public enum BarFlag { - - /** - * Darkens the sky like during fighting a wither. - */ - DARKEN_SKY, - /** - * Tells the client to play the Ender Dragon boss music. - */ - PLAY_BOSS_MUSIC, - /** - * Creates fog around the world. - */ - CREATE_FOG, -} diff --git a/api/src/main/java/org/bukkit/boss/BarStyle.java b/api/src/main/java/org/bukkit/boss/BarStyle.java deleted file mode 100644 index 3e499eb77..000000000 --- a/api/src/main/java/org/bukkit/boss/BarStyle.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.boss; - -public enum BarStyle { - /** - * Makes the boss bar solid (no segments) - */ - SOLID, - /** - * Splits the boss bar into 6 segments - */ - SEGMENTED_6, - /** - * Splits the boss bar into 10 segments - */ - SEGMENTED_10, - /** - * Splits the boss bar into 12 segments - */ - SEGMENTED_12, - /** - * Splits the boss bar into 20 segments - */ - SEGMENTED_20, -} diff --git a/api/src/main/java/org/bukkit/boss/BossBar.java b/api/src/main/java/org/bukkit/boss/BossBar.java deleted file mode 100644 index 70274f2e2..000000000 --- a/api/src/main/java/org/bukkit/boss/BossBar.java +++ /dev/null @@ -1,149 +0,0 @@ -package org.bukkit.boss; - -import java.util.List; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface BossBar { - - /** - * Returns the title of this boss bar - * - * @return the title of the bar - */ - @NotNull - String getTitle(); - - /** - * Sets the title of this boss bar - * - * @param title the title of the bar - */ - void setTitle(@Nullable String title); - - /** - * Returns the color of this boss bar - * - * @return the color of the bar - */ - @NotNull - BarColor getColor(); - - /** - * Sets the color of this boss bar. - * - * @param color the color of the bar - */ - void setColor(@NotNull BarColor color); - - /** - * Returns the style of this boss bar - * - * @return the style of the bar - */ - @NotNull - BarStyle getStyle(); - - /** - * Sets the bar style of this boss bar - * - * @param style the style of the bar - */ - void setStyle(@NotNull BarStyle style); - - /** - * Remove an existing flag on this boss bar - * - * @param flag the existing flag to remove - */ - void removeFlag(@NotNull BarFlag flag); - - /** - * Add an optional flag to this boss bar - * - * @param flag an optional flag to set on the boss bar - */ - void addFlag(@NotNull BarFlag flag); - - /** - * Returns whether this boss bar as the passed flag set - * - * @param flag the flag to check - * @return whether it has the flag - */ - boolean hasFlag(@NotNull BarFlag flag); - - /** - * Sets the progress of the bar. Values should be between 0.0 (empty) and - * 1.0 (full) - * - * @param progress the progress of the bar - */ - void setProgress(double progress); - - /** - * Returns the progress of the bar between 0.0 and 1.0 - * - * @return the progress of the bar - */ - double getProgress(); - - /** - * Adds the player to this boss bar causing it to display on their screen. - * - * @param player the player to add - */ - void addPlayer(@NotNull Player player); - - /** - * Removes the player from this boss bar causing it to be removed from their - * screen. - * - * @param player the player to remove - */ - void removePlayer(@NotNull Player player); - - /** - * Removes all players from this boss bar - * - * @see #removePlayer(Player) - */ - void removeAll(); - - /** - * Returns all players viewing this boss bar - * - * @return a immutable list of players - */ - @NotNull - List getPlayers(); - - /** - * Set if the boss bar is displayed to attached players. - * - * @param visible visible status - */ - void setVisible(boolean visible); - - /** - * Return if the boss bar is displayed to attached players. - * - * @return visible status - */ - boolean isVisible(); - - /** - * Shows the previously hidden boss bar to all attached players - * @deprecated {@link #setVisible(boolean)} - */ - @Deprecated - void show(); - - /** - * Hides this boss bar from all attached players - * @deprecated {@link #setVisible(boolean)} - */ - @Deprecated - void hide(); -} diff --git a/api/src/main/java/org/bukkit/boss/KeyedBossBar.java b/api/src/main/java/org/bukkit/boss/KeyedBossBar.java deleted file mode 100644 index 6a1fe5f91..000000000 --- a/api/src/main/java/org/bukkit/boss/KeyedBossBar.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bukkit.boss; - -import org.bukkit.Keyed; - -/** - * Represents a custom {@link BossBar} that has a - * {@link org.bukkit.NamespacedKey} - */ -public interface KeyedBossBar extends BossBar, Keyed { } diff --git a/api/src/main/java/org/bukkit/command/BlockCommandSender.java b/api/src/main/java/org/bukkit/command/BlockCommandSender.java deleted file mode 100644 index b8f2f7ebe..000000000 --- a/api/src/main/java/org/bukkit/command/BlockCommandSender.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit.command; - -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; - -public interface BlockCommandSender extends CommandSender { - - /** - * Returns the block this command sender belongs to - * - * @return Block for the command sender - */ - @NotNull - public Block getBlock(); -} diff --git a/api/src/main/java/org/bukkit/command/BufferedCommandSender.java b/api/src/main/java/org/bukkit/command/BufferedCommandSender.java deleted file mode 100644 index f9a00aecc..000000000 --- a/api/src/main/java/org/bukkit/command/BufferedCommandSender.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.command; - -import org.jetbrains.annotations.NotNull; - -public class BufferedCommandSender implements MessageCommandSender { - private final StringBuffer buffer = new StringBuffer(); - @Override - public void sendMessage(@NotNull String message) { - buffer.append(message); - buffer.append("\n"); - } - - @NotNull - public String getBuffer() { - return buffer.toString(); - } - - public void reset() { - this.buffer.setLength(0); - } -} diff --git a/api/src/main/java/org/bukkit/command/Command.java b/api/src/main/java/org/bukkit/command/Command.java deleted file mode 100644 index 0b0d1bd7c..000000000 --- a/api/src/main/java/org/bukkit/command/Command.java +++ /dev/null @@ -1,449 +0,0 @@ -package org.bukkit.command; - -import com.google.common.collect.ImmutableList; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameRule; -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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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; - protected String description; - protected String usageMessage; - private String permission; - private String permissionMessage; - public co.aikar.timings.Timing timings; // Paper - @NotNull public String getTimingName() {return getName();} // Paper - - protected Command(@NotNull String name) { - this(name, "", "/" + name, new ArrayList()); - } - - protected Command(@NotNull String name, @NotNull String description, @NotNull String usageMessage, @NotNull List aliases) { - this.name = name; - this.nextLabel = name; - this.label = name; - this.description = (description == null) ? "" : description; - this.usageMessage = (usageMessage == null) ? "/" + name : 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(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args); - - /** - * 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 - */ - @NotNull - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException { - return tabComplete0(sender, alias, args, 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 ' ' - * @param location The position looked at by the sender, or null if none - * @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 - */ - @NotNull - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args, @Nullable Location location) throws IllegalArgumentException { - return tabComplete(sender, alias, args); - } - - @NotNull - private List tabComplete0(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args, @Nullable 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 (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)) { - matchedPlayers.add(name); - } - } - - Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); - return matchedPlayers; - } - - /** - * Returns the name of this command - * - * @return Name of this command - */ - @NotNull - 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(@NotNull String name) { - if (!isRegistered()) { - this.name = (name == null) ? "" : 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 - */ - @Nullable - 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(@Nullable 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(@NotNull CommandSender target) { - if (testPermissionSilent(target)) { - return true; - } - - if (permissionMessage == null) { - target.sendMessage(Bukkit.getPermissionMessage()); // Paper - } 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(@NotNull 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 - */ - @NotNull - 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(@NotNull String name) { - if (name == null) { - 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(@NotNull 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 successful (the current - * registered CommandMap was the passed CommandMap or null) false - * otherwise - */ - public boolean unregister(@NotNull 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(@NotNull 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 - */ - @NotNull - public List getAliases() { - return activeAliases; - } - - /** - * Returns a message to be displayed on a failed permission check for this - * command - * - * @return Permission check failed message - */ - @Nullable - public String getPermissionMessage() { - return permissionMessage; - } - - /** - * Gets a brief description of this command - * - * @return Description of this command - */ - @NotNull - public String getDescription() { - return description; - } - - /** - * Gets an example usage of this command - * - * @return One or more example usages - */ - @NotNull - 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 - */ - @NotNull - public Command setAliases(@NotNull 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 - */ - @NotNull - public Command setDescription(@NotNull String description) { - this.description = (description == null) ? "" : 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 - */ - @NotNull - public Command setPermissionMessage(@Nullable 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 - */ - @NotNull - public Command setUsage(@NotNull String usage) { - this.usageMessage = (usage == null) ? "" : usage; - return this; - } - - public static void broadcastCommandMessage(@NotNull CommandSender source, @NotNull String message) { - broadcastCommandMessage(source, message, true); - } - - public static void broadcastCommandMessage(@NotNull CommandSender source, @NotNull String message, boolean sendToSource) { - String result = source.getName() + ": " + message; - - if (source instanceof BlockCommandSender) { - BlockCommandSender blockCommandSender = (BlockCommandSender) source; - - if (!blockCommandSender.getBlock().getWorld().getGameRuleValue(GameRule.COMMAND_BLOCK_OUTPUT)) { - Bukkit.getConsoleSender().sendMessage(result); - return; - } - } else if (source instanceof CommandMinecart) { - CommandMinecart commandMinecart = (CommandMinecart) source; - - if (!commandMinecart.getWorld().getGameRuleValue(GameRule.COMMAND_BLOCK_OUTPUT)) { - 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 && user.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { - 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/api/src/main/java/org/bukkit/command/CommandException.java b/api/src/main/java/org/bukkit/command/CommandException.java deleted file mode 100644 index b63015f40..000000000 --- a/api/src/main/java/org/bukkit/command/CommandException.java +++ /dev/null @@ -1,28 +0,0 @@ -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/api/src/main/java/org/bukkit/command/CommandExecutor.java b/api/src/main/java/org/bukkit/command/CommandExecutor.java deleted file mode 100644 index 45cb8da12..000000000 --- a/api/src/main/java/org/bukkit/command/CommandExecutor.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.command; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents a class which contains a single method for executing commands - */ -public interface CommandExecutor { - - /** - * Executes the given command, returning its success. - *
- * If false is returned, then the "usage" plugin.yml entry for this command - * (if defined) will be sent to the player. - * - * @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 - */ - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args); -} diff --git a/api/src/main/java/org/bukkit/command/CommandMap.java b/api/src/main/java/org/bukkit/command/CommandMap.java deleted file mode 100644 index 864c263bb..000000000 --- a/api/src/main/java/org/bukkit/command/CommandMap.java +++ /dev/null @@ -1,141 +0,0 @@ -package org.bukkit.command; - -import java.util.List; -import org.bukkit.Location; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -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 - */ - public void registerAll(@NotNull String fallbackPrefix, @NotNull 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 - */ - public boolean register(@NotNull String label, @NotNull String fallbackPrefix, @NotNull 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 - */ - public boolean register(@NotNull String fallbackPrefix, @NotNull 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 - */ - public boolean dispatch(@NotNull CommandSender sender, @NotNull String cmdLine) throws CommandException; - - /** - * Clears all registered commands. - */ - public 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 - */ - @Nullable - public Command getCommand(@NotNull 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 - */ - @Nullable - public List tabComplete(@NotNull CommandSender sender, @NotNull String cmdLine) throws IllegalArgumentException; - - /** - * 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. - * @param location The position looked at by the sender, or null if none - * @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 - */ - @Nullable - public List tabComplete(@NotNull CommandSender sender, @NotNull String cmdLine, @Nullable Location location) throws IllegalArgumentException; - - // Paper start - Expose Known Commands - /** - * Return a Map of known commands - * - * @return known commands - */ - @NotNull - public java.util.Map getKnownCommands(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/command/CommandSender.java b/api/src/main/java/org/bukkit/command/CommandSender.java deleted file mode 100644 index be11d52a0..000000000 --- a/api/src/main/java/org/bukkit/command/CommandSender.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.bukkit.command; - -import org.bukkit.Server; -import org.bukkit.permissions.Permissible; -import org.jetbrains.annotations.NotNull; - -public interface CommandSender extends Permissible { - - /** - * Sends this sender a message - * - * @param message Message to be displayed - */ - public void sendMessage(@NotNull String message); - - /** - * Sends this sender multiple messages - * - * @param messages An array of messages to be displayed - */ - public void sendMessage(@NotNull String[] messages); - - /** - * Returns the server instance that this command is running on - * - * @return Server instance - */ - @NotNull - public Server getServer(); - - /** - * Gets the name of this command sender - * - * @return Name of the sender - */ - @NotNull - public String getName(); - - // Spigot start - public class Spigot - { - - /** - * Sends this sender a chat component. - * - * @param component the components to send - */ - public void sendMessage(@NotNull 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 sender. - * - * @param components the components to send - */ - public void sendMessage(@NotNull net.md_5.bungee.api.chat.BaseComponent... components) { - throw new UnsupportedOperationException("Not supported yet."); - } - } - - @NotNull - Spigot spigot(); - // Spigot end - - // 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(@NotNull 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(@NotNull 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/api/src/main/java/org/bukkit/command/ConsoleCommandSender.java b/api/src/main/java/org/bukkit/command/ConsoleCommandSender.java deleted file mode 100644 index f309c2ed3..000000000 --- a/api/src/main/java/org/bukkit/command/ConsoleCommandSender.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.command; - -import org.bukkit.conversations.Conversable; - -public interface ConsoleCommandSender extends CommandSender, Conversable { -} diff --git a/api/src/main/java/org/bukkit/command/FormattedCommandAlias.java b/api/src/main/java/org/bukkit/command/FormattedCommandAlias.java deleted file mode 100644 index 9d4f553c0..000000000 --- a/api/src/main/java/org/bukkit/command/FormattedCommandAlias.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.bukkit.command; - -import java.util.ArrayList; -import java.util.regex.Matcher; // Paper -import java.util.regex.Pattern; // Paper - -import org.bukkit.Bukkit; -import org.jetbrains.annotations.NotNull; - -public class FormattedCommandAlias extends Command { - private final String[] formatStrings; - - public FormattedCommandAlias(@NotNull String alias, @NotNull String[] formatStrings) { - super(alias); - timings = co.aikar.timings.TimingsManager.getCommandTiming("minecraft", this); // Spigot - this.formatStrings = formatStrings; - } - - @Override - public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { - boolean result = false; - ArrayList commands = new ArrayList(); - for (String formatString : formatStrings) { - try { - commands.add(buildCommand(sender, formatString, args)); // Paper - } 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(@NotNull CommandSender sender, @NotNull String formatString, @NotNull String[] args) { // Paper - if (formatString.contains("$sender")) { // Paper - formatString = formatString.replaceAll(Pattern.quote("$sender"), Matcher.quoteReplacement(sender.getName())); // Paper - } // Paper - 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; - } - - @NotNull - @Override // Paper - public String getTimingName() {return "Command Forwarder - " + super.getTimingName();} // Paper - - private static boolean inRange(int i, int j, int k) { - return i >= j && i <= k; - } -} diff --git a/api/src/main/java/org/bukkit/command/MessageCommandSender.java b/api/src/main/java/org/bukkit/command/MessageCommandSender.java deleted file mode 100644 index ca1893e9f..000000000 --- a/api/src/main/java/org/bukkit/command/MessageCommandSender.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.bukkit.command; - -import org.apache.commons.lang.NotImplementedException; -import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionAttachment; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.Plugin; - -import java.util.Set; -import org.jetbrains.annotations.NotNull; - -/** - * For when all you care about is just messaging - */ -public interface MessageCommandSender extends CommandSender { - - @Override - default void sendMessage(@NotNull String[] messages) { - for (String message : messages) { - sendMessage(message); - } - } - - @NotNull - @Override - default Server getServer() { - return Bukkit.getServer(); - } - - @NotNull - @Override - default String getName() { - throw new NotImplementedException(); - } - - @Override - default boolean isOp() { - throw new NotImplementedException(); - } - - @Override - default void setOp(boolean value) { - throw new NotImplementedException(); - } - - @Override - default boolean isPermissionSet(@NotNull String name) { - throw new NotImplementedException(); - } - - @Override - default boolean isPermissionSet(@NotNull Permission perm) { - throw new NotImplementedException(); - } - - @Override - default boolean hasPermission(@NotNull String name) { - throw new NotImplementedException(); - } - - @Override - default boolean hasPermission(@NotNull Permission perm) { - throw new NotImplementedException(); - } - - @NotNull - @Override - default PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value) { - throw new NotImplementedException(); - } - - @NotNull - @Override - default PermissionAttachment addAttachment(@NotNull Plugin plugin) { - throw new NotImplementedException(); - } - - @NotNull - @Override - default PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value, int ticks) { - throw new NotImplementedException(); - } - - @NotNull - @Override - default PermissionAttachment addAttachment(@NotNull Plugin plugin, int ticks) { - throw new NotImplementedException(); - } - - @Override - default void removeAttachment(@NotNull PermissionAttachment attachment) { - throw new NotImplementedException(); - } - - @Override - default void recalculatePermissions() { - throw new NotImplementedException(); - } - - @NotNull - @Override - default Set getEffectivePermissions() { - throw new NotImplementedException(); - } - - @NotNull - @Override - default Spigot spigot() { - throw new NotImplementedException(); - } - -} diff --git a/api/src/main/java/org/bukkit/command/MultipleCommandAlias.java b/api/src/main/java/org/bukkit/command/MultipleCommandAlias.java deleted file mode 100644 index 8487bfe33..000000000 --- a/api/src/main/java/org/bukkit/command/MultipleCommandAlias.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.command; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents a command that delegates to one or more other commands - */ -public class MultipleCommandAlias extends Command { - private Command[] commands; - - public MultipleCommandAlias(@NotNull String name, @NotNull Command[] commands) { - super(name); - this.commands = commands; - } - - /** - * Gets the commands associated with the multi-command alias. - * - * @return commands associated with alias - */ - @NotNull - public Command[] getCommands() { - return commands; - } - - @Override - public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { - boolean result = false; - - for (Command command : commands) { - result |= command.execute(sender, commandLabel, args); - } - - return result; - } -} diff --git a/api/src/main/java/org/bukkit/command/PluginCommand.java b/api/src/main/java/org/bukkit/command/PluginCommand.java deleted file mode 100644 index 1e126487d..000000000 --- a/api/src/main/java/org/bukkit/command/PluginCommand.java +++ /dev/null @@ -1,167 +0,0 @@ -package org.bukkit.command; - -import java.util.List; -import org.apache.commons.lang.Validate; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull String name, @NotNull 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(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { - boolean success = false; - - if (!owningPlugin.isEnabled()) { - throw new CommandException("Cannot execute command '" + commandLabel + "' in plugin " + owningPlugin.getDescription().getFullName() + " - plugin is disabled."); - } - - 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(@Nullable CommandExecutor executor) { - this.executor = executor == null ? owningPlugin : executor; - } - - /** - * Gets the {@link CommandExecutor} associated with this command - * - * @return CommandExecutor object linked to this command - */ - @NotNull - 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(@Nullable TabCompleter completer) { - this.completer = completer; - } - - /** - * Gets the {@link TabCompleter} associated with this command. - * - * @return TabCompleter object linked to this command - */ - @Nullable - public TabCompleter getTabCompleter() { - return completer; - } - - /** - * Gets the owner of this PluginCommand - * - * @return Plugin that owns this command - */ - @Override - @NotNull - 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 - */ - @NotNull - @Override - public java.util.List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) 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); - } - if (completions == null && executor instanceof TabCompleter) { - completions = ((TabCompleter) executor).onTabComplete(sender, this, alias, args); - } - } 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) { - if (!sender.getServer().suggestPlayerNamesWhenNullTabCompletions()) return com.google.common.collect.ImmutableList.of(); // Paper - allow preventing player name suggestions by default - return super.tabComplete(sender, alias, args); - } - return completions; - } - - @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/api/src/main/java/org/bukkit/command/PluginCommandYamlParser.java b/api/src/main/java/org/bukkit/command/PluginCommandYamlParser.java deleted file mode 100644 index a542c4bb3..000000000 --- a/api/src/main/java/org/bukkit/command/PluginCommandYamlParser.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bukkit.command; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -public class PluginCommandYamlParser { - - @NotNull - public static List parse(@NotNull 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/api/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java b/api/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java deleted file mode 100644 index d51e0fd60..000000000 --- a/api/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.command; - -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - @NotNull - public Plugin getPlugin(); -} diff --git a/api/src/main/java/org/bukkit/command/ProxiedCommandSender.java b/api/src/main/java/org/bukkit/command/ProxiedCommandSender.java deleted file mode 100644 index fcc34b640..000000000 --- a/api/src/main/java/org/bukkit/command/ProxiedCommandSender.java +++ /dev/null @@ -1,24 +0,0 @@ - -package org.bukkit.command; - -import org.jetbrains.annotations.NotNull; - -public interface ProxiedCommandSender extends CommandSender { - - /** - * Returns the CommandSender which triggered this proxied command - * - * @return the caller which triggered the command - */ - @NotNull - CommandSender getCaller(); - - /** - * Returns the CommandSender which is being used to call the command - * - * @return the caller which the command is being run as - */ - @NotNull - CommandSender getCallee(); - -} diff --git a/api/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java b/api/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java deleted file mode 100644 index dc3bc1d1a..000000000 --- a/api/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.bukkit.command; - -public interface RemoteConsoleCommandSender extends CommandSender { -} diff --git a/api/src/main/java/org/bukkit/command/SimpleCommandMap.java b/api/src/main/java/org/bukkit/command/SimpleCommandMap.java deleted file mode 100644 index 460fda05a..000000000 --- a/api/src/main/java/org/bukkit/command/SimpleCommandMap.java +++ /dev/null @@ -1,307 +0,0 @@ -package org.bukkit.command; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.destroystokyo.paper.event.server.ServerExceptionEvent; -import com.destroystokyo.paper.exception.ServerCommandException; -import com.destroystokyo.paper.exception.ServerTabCompleteException; -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.command.defaults.BukkitCommand; -import org.bukkit.command.defaults.HelpCommand; -import org.bukkit.command.defaults.PluginsCommand; -import org.bukkit.command.defaults.ReloadCommand; -import org.bukkit.command.defaults.VersionCommand; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class SimpleCommandMap implements CommandMap { - protected final Map knownCommands = new HashMap(); - private final Server server; - - public SimpleCommandMap(@NotNull final Server server) { - this.server = server; - setDefaultCommands(); - } - - private void setDefaultCommands() { - register("bukkit", new VersionCommand("version")); - register("bukkit", new ReloadCommand("reload")); - register("bukkit", new PluginsCommand("plugins")); - register("bukkit", new co.aikar.timings.TimingsCommand("timings")); // Paper - } - - public void setFallbackCommands() { - register("bukkit", new HelpCommand()); - } - - /** - * {@inheritDoc} - */ - @Override - public void registerAll(@NotNull String fallbackPrefix, @NotNull List commands) { - if (commands != null) { - for (Command c : commands) { - register(fallbackPrefix, c); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean register(@NotNull String fallbackPrefix, @NotNull Command command) { - return register(command.getName(), fallbackPrefix, command); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean register(@NotNull String label, @NotNull String fallbackPrefix, @NotNull Command command) { - command.timings = co.aikar.timings.TimingsManager.getCommandTiming(fallbackPrefix, command); // Paper - label = label.toLowerCase(java.util.Locale.ENGLISH).trim(); - fallbackPrefix = fallbackPrefix.toLowerCase(java.util.Locale.ENGLISH).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(@NotNull String label, @NotNull Command command, boolean isAlias, @NotNull String fallbackPrefix) { - knownCommands.put(fallbackPrefix + ":" + label, command); - if ((command instanceof BukkitCommand || 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; - } - - boolean registered = true; - - // 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 registered; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean dispatch(@NotNull CommandSender sender, @NotNull String commandLine) throws CommandException { - String[] args = commandLine.split(" "); - - if (args.length == 0) { - return false; - } - - String sentCommandLabel = args[0].toLowerCase(java.util.Locale.ENGLISH); - Command target = getCommand(sentCommandLabel); - - if (target == null) { - return false; - } - - // Paper start - Plugins do weird things to workaround normal registration - if (target.timings == null) { - target.timings = co.aikar.timings.TimingsManager.getCommandTiming(null, target); - } - // Paper end - - try { - try (co.aikar.timings.Timing ignored = target.timings.startTiming()) { // Paper - use try with resources - // 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)); - } // target.timings.stopTiming(); // Spigot // Paper - } catch (CommandException ex) { - server.getPluginManager().callEvent(new ServerExceptionEvent(new ServerCommandException(ex, target, sender, args))); // Paper - //target.timings.stopTiming(); // Spigot // Paper - throw ex; - } catch (Throwable ex) { - //target.timings.stopTiming(); // Spigot // Paper - String msg = "Unhandled exception executing '" + commandLine + "' in " + target; - server.getPluginManager().callEvent(new ServerExceptionEvent(new ServerCommandException(ex, target, sender, args))); // Paper - throw new CommandException(msg, ex); - } - - // return true as command was handled - return true; - } - - @Override - public synchronized void clearCommands() { - for (Map.Entry entry : knownCommands.entrySet()) { - entry.getValue().unregister(this); - } - knownCommands.clear(); - setDefaultCommands(); - } - - @Override - @Nullable - public Command getCommand(@NotNull String name) { - Command target = knownCommands.get(name.toLowerCase(java.util.Locale.ENGLISH)); - return target; - } - - @Override - @Nullable - public List tabComplete(@NotNull CommandSender sender, @NotNull String cmdLine) { - return tabComplete(sender, cmdLine, null); - } - - @Override - @Nullable - public List tabComplete(@NotNull CommandSender sender, @NotNull String cmdLine, @Nullable 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); - } - } - - Collections.sort(completions, 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[] args = cmdLine.substring(spaceIndex + 1, cmdLine.length()).split(" ", -1); - - try { - return target.tabComplete(sender, commandName, args, location); - } catch (CommandException ex) { - throw ex; - } catch (Throwable ex) { - String msg = "Unhandled exception executing tab-completer for '" + cmdLine + "' in " + target; - server.getPluginManager().callEvent(new ServerExceptionEvent(new ServerTabCompleteException(msg, ex, target, sender, args))); // Paper - throw new CommandException(msg, ex); - } - } - - @NotNull - public Collection getCommands() { - return Collections.unmodifiableCollection(knownCommands.values()); - } - - public void registerServerAliases() { - Map values = server.getCommandAliases(); - - for (Map.Entry entry : values.entrySet()) { - String alias = entry.getKey(); - if (alias.contains(" ")) { - server.getLogger().warning("Could not register alias " + alias + " because it contains illegal characters"); - continue; - } - - String[] commandStrings = entry.getValue(); - 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) { - server.getLogger().warning("Could not register alias " + alias + " because it contains commands that do not exist: " + bad); - continue; - } - - // We register these as commands so they have absolute priority. - if (targets.size() > 0) { - knownCommands.put(alias.toLowerCase(java.util.Locale.ENGLISH), new FormattedCommandAlias(alias.toLowerCase(java.util.Locale.ENGLISH), targets.toArray(new String[targets.size()]))); - } else { - knownCommands.remove(alias.toLowerCase(java.util.Locale.ENGLISH)); - } - } - } - - // Paper start - Expose Known Commands - @NotNull - public Map getKnownCommands() { - return knownCommands; - } - // Paper end -} diff --git a/api/src/main/java/org/bukkit/command/TabCompleter.java b/api/src/main/java/org/bukkit/command/TabCompleter.java deleted file mode 100644 index e9cf71f5c..000000000 --- a/api/src/main/java/org/bukkit/command/TabCompleter.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.command; - -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. For players tab-completing a - * command inside of a command block, this will be the player, not - * the command block. - * @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 - */ - @Nullable - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args); -} diff --git a/api/src/main/java/org/bukkit/command/TabExecutor.java b/api/src/main/java/org/bukkit/command/TabExecutor.java deleted file mode 100644 index 6b8e3fb2a..000000000 --- a/api/src/main/java/org/bukkit/command/TabExecutor.java +++ /dev/null @@ -1,8 +0,0 @@ -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/api/src/main/java/org/bukkit/command/defaults/BukkitCommand.java b/api/src/main/java/org/bukkit/command/defaults/BukkitCommand.java deleted file mode 100644 index cb032d038..000000000 --- a/api/src/main/java/org/bukkit/command/defaults/BukkitCommand.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit.command.defaults; - -import java.util.List; -import org.bukkit.command.Command; -import org.jetbrains.annotations.NotNull; - -public abstract class BukkitCommand extends Command { - protected BukkitCommand(@NotNull String name) { - super(name); - } - - protected BukkitCommand(@NotNull String name, @NotNull String description, @NotNull String usageMessage, @NotNull List aliases) { - super(name, description, usageMessage, aliases); - } -} diff --git a/api/src/main/java/org/bukkit/command/defaults/HelpCommand.java b/api/src/main/java/org/bukkit/command/defaults/HelpCommand.java deleted file mode 100644 index 3ec11eb29..000000000 --- a/api/src/main/java/org/bukkit/command/defaults/HelpCommand.java +++ /dev/null @@ -1,230 +0,0 @@ -package org.bukkit.command.defaults; - -import com.google.common.collect.ImmutableList; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class HelpCommand extends BukkitCommand { - 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(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull 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; - } - - @NotNull - @Override - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull 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(); - } - - @Nullable - protected HelpTopic findPossibleMatches(@NotNull 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(@Nullable String s1, @Nullable 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/api/src/main/java/org/bukkit/command/defaults/PluginsCommand.java b/api/src/main/java/org/bukkit/command/defaults/PluginsCommand.java deleted file mode 100644 index 6cfd9f3c6..000000000 --- a/api/src/main/java/org/bukkit/command/defaults/PluginsCommand.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bukkit.command.defaults; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -public class PluginsCommand extends BukkitCommand { - public PluginsCommand(@NotNull 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(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull String[] args) { - if (!testPermission(sender)) return true; - - sender.sendMessage("Plugins " + getPluginList()); - return true; - } - - @NotNull - @Override - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException { - return Collections.emptyList(); - } - - @NotNull - private String getPluginList() { - // Paper start - TreeMap plugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - // Paper start - Add an asterisk to legacy plugins (so admins are aware) - String pluginName = plugin.getDescription().getName(); - if (org.bukkit.UnsafeValues.isLegacyPlugin(plugin)) { - pluginName += "*"; - } - - plugins.put(pluginName, plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED); - // Paper end - } - - StringBuilder pluginList = new StringBuilder(); - for (Map.Entry entry : plugins.entrySet()) { - if (pluginList.length() > 0) { - pluginList.append(ChatColor.WHITE); - pluginList.append(", "); - } - pluginList.append(entry.getValue()); - pluginList.append(entry.getKey()); - } - - return "(" + plugins.size() + "): " + pluginList.toString(); - // Paper end - } -} diff --git a/api/src/main/java/org/bukkit/command/defaults/ReloadCommand.java b/api/src/main/java/org/bukkit/command/defaults/ReloadCommand.java deleted file mode 100644 index af8ab73fe..000000000 --- a/api/src/main/java/org/bukkit/command/defaults/ReloadCommand.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.bukkit.command.defaults; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; - -public class ReloadCommand extends BukkitCommand { - public ReloadCommand(@NotNull String name) { - super(name); - this.description = "Reloads the server configuration and plugins"; - this.usageMessage = "/reload [permissions|commands|confirm]"; // Paper - this.setPermission("bukkit.command.reload"); - this.setAliases(Arrays.asList("rl")); - } - - @Override - public boolean execute(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull String[] args) { // Paper - if (!testPermission(sender)) return true; - - // Paper start - Reload permissions.yml & require confirm - boolean confirmed = System.getProperty("LetMeReload") != null; - if (args.length == 1) { - if (args[0].equalsIgnoreCase("permissions")) { - Bukkit.getServer().reloadPermissions(); - Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Permissions successfully reloaded."); - return true; - } else if ("commands".equalsIgnoreCase(args[0])) { - if (Bukkit.getServer().reloadCommandAliases()) { - Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Command aliases successfully reloaded."); - } else { - Command.broadcastCommandMessage(sender, ChatColor.RED + "An error occurred while trying to reload command aliases."); - } - return true; - } else if ("confirm".equalsIgnoreCase(args[0])) { - confirmed = true; - } else { - Command.broadcastCommandMessage(sender, ChatColor.RED + "Usage: " + usageMessage); - return true; - } - } - if (!confirmed) { - Command.broadcastCommandMessage(sender, ChatColor.RED + "Are you sure you wish to reload your server? Doing so may cause bugs and memory leaks. It is recommended to restart instead of using /reload. To confirm, please type " + ChatColor.YELLOW + "/reload confirm"); - return true; - } - // Paper end - - 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; - } - - @NotNull - @Override - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException { - return java.util.Collections.singletonList("permissions"); // Paper - } -} diff --git a/api/src/main/java/org/bukkit/command/defaults/VersionCommand.java b/api/src/main/java/org/bukkit/command/defaults/VersionCommand.java deleted file mode 100644 index 0486abd19..000000000 --- a/api/src/main/java/org/bukkit/command/defaults/VersionCommand.java +++ /dev/null @@ -1,286 +0,0 @@ -package org.bukkit.command.defaults; - -import com.destroystokyo.paper.util.VersionFetcher; // Paper - version supplier -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableList; -import com.google.common.io.Resources; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; -import java.io.BufferedReader; -import java.io.IOException; -import java.net.URL; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.locks.ReentrantLock; -import org.apache.commons.lang.Validate; -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 org.jetbrains.annotations.NotNull; - -public class VersionCommand extends BukkitCommand { - private VersionFetcher versionFetcher; - private VersionFetcher getVersionFetcher() { // lazy load because unsafe isn't available at command registration - if (versionFetcher == null) { - versionFetcher = Bukkit.getUnsafe().getVersionFetcher(); - } - - return versionFetcher; - } - - public VersionCommand(@NotNull String name) { - super(name); - - this.description = "Gets the version of this server including any plugins in use"; - this.usageMessage = "/version [plugin name]"; - this.setPermission("bukkit.command.version"); - this.setAliases(Arrays.asList("ver", "about")); - } - - @Override - public boolean execute(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull String[] args) { - if (!testPermission(sender)) return true; - - if (args.length == 0) { - sender.sendMessage("This server is running " + Bukkit.getName() + " version " + Bukkit.getVersion() + " (Implementing API version " + Bukkit.getBukkitVersion() + ")"); - sendVersion(sender); - } else { - 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 true; - } - - boolean found = false; - pluginName = pluginName.toLowerCase(java.util.Locale.ENGLISH); - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - if (plugin.getName().toLowerCase(java.util.Locale.ENGLISH).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 true; - } - - private void describeToSender(@NotNull Plugin plugin, @NotNull 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)); - } - } - } - - @NotNull - private String getAuthors(@NotNull 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(); - } - - @NotNull - @Override - public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull 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 completions = new ArrayList(); - String toComplete = args[0].toLowerCase(java.util.Locale.ENGLISH); - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - if (StringUtil.startsWithIgnoreCase(plugin.getName(), toComplete)) { - completions.add(plugin.getName()); - } - } - return completions; - } - return ImmutableList.of(); - } - - private final ReentrantLock versionLock = new ReentrantLock(); - private boolean hasVersion = false; - private String versionMessage = null; - private final Set versionWaiters = new HashSet(); - private boolean versionTaskStarted = false; - private long lastCheck = 0; - - private void sendVersion(@NotNull CommandSender sender) { - if (hasVersion) { - if (System.currentTimeMillis() - lastCheck > getVersionFetcher().getCacheTime()) { // Paper - use version supplier - lastCheck = System.currentTimeMillis(); - hasVersion = false; - } else { - sendMessages(versionMessage, sender); // Paper - allow \n for multiple messages - return; - } - } - versionLock.lock(); - try { - if (hasVersion) { - sendMessages(versionMessage, sender); // Paper - allow \n for multiple messages - return; - } - versionWaiters.add(sender); - sender.sendMessage("Checking version, please wait..."); - if (!versionTaskStarted) { - versionTaskStarted = true; - new Thread(new Runnable() { - - @Override - public void run() { - obtainVersion(); - } - }).start(); - } - } finally { - versionLock.unlock(); - } - } - - private void obtainVersion() { - String version = Bukkit.getVersion(); - // Paper start - if (version.startsWith("null")) { // running from ide? - setVersionMessage("Unknown version, custom build?"); - return; - } - /* - if (version.startsWith("git-Spigot-")) { - String[] parts = version.substring("git-Spigot-".length()).split("-"); - int cbVersions = getDistance("craftbukkit", parts[1].substring(0, parts[1].indexOf(' '))); - int spigotVersions = getDistance("spigot", parts[0]); - if (cbVersions == -1 || spigotVersions == -1) { - setVersionMessage("Error obtaining version information"); - } else { - if (cbVersions == 0 && spigotVersions == 0) { - setVersionMessage("You are running the latest version"); - } else { - setVersionMessage("You are " + (cbVersions + spigotVersions) + " version(s) behind"); - } - } - - } else if (version.startsWith("git-Bukkit-")) { - version = version.substring("git-Bukkit-".length()); - int cbVersions = getDistance("craftbukkit", version.substring(0, version.indexOf(' '))); - if (cbVersions == -1) { - setVersionMessage("Error obtaining version information"); - } else { - if (cbVersions == 0) { - setVersionMessage("You are running the latest version"); - } else { - setVersionMessage("You are " + cbVersions + " version(s) behind"); - } - } - } else { - setVersionMessage("Unknown version, custom build?"); - } - */ - setVersionMessage(getVersionFetcher().getVersionMessage(version)); - // Paper end - } - - private void setVersionMessage(@NotNull String msg) { - lastCheck = System.currentTimeMillis(); - versionMessage = msg; - versionLock.lock(); - try { - hasVersion = true; - versionTaskStarted = false; - // Paper - allow \n for multiple messages - String[] messages = versionMessage.split("\n"); - for (CommandSender sender : versionWaiters) { - for (String message : messages) { - sender.sendMessage(message); - } - // Paper end - } - versionWaiters.clear(); - } finally { - versionLock.unlock(); - } - } - - // Paper start - private void sendMessages(String toSplit, CommandSender target) { - String[] messages = toSplit.split("\n"); - for (String message : messages) { - target.sendMessage(message); - } - } - // Paper end - - private static int getDistance(@NotNull String repo, @NotNull String hash) { - try { - BufferedReader reader = Resources.asCharSource( - new URL("https://hub.spigotmc.org/stash/rest/api/1.0/projects/SPIGOT/repos/" + repo + "/commits?since=" + URLEncoder.encode(hash, "UTF-8") + "&withCounts=true"), - Charsets.UTF_8 - ).openBufferedStream(); - try { - JsonObject obj = new Gson().fromJson(reader, JsonObject.class); - return obj.get("totalCount").getAsInt(); - } catch (JsonSyntaxException ex) { - ex.printStackTrace(); - return -1; - } finally { - reader.close(); - } - } catch (IOException e) { - e.printStackTrace(); - return -1; - } - } -} diff --git a/api/src/main/java/org/bukkit/configuration/Configuration.java b/api/src/main/java/org/bukkit/configuration/Configuration.java deleted file mode 100644 index f12a98b1b..000000000 --- a/api/src/main/java/org/bukkit/configuration/Configuration.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.bukkit.configuration; - -import java.util.Map; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - @Override - public void addDefault(@NotNull String path, @Nullable 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. - */ - public void addDefaults(@NotNull 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(org.bukkit.configuration.Configuration)}. - * - * @param defaults A configuration holding a list of defaults to copy. - * @throws IllegalArgumentException Thrown if defaults is null or this. - */ - public void addDefaults(@NotNull 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. - */ - public void setDefaults(@NotNull 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. - */ - @Nullable - public Configuration getDefaults(); - - /** - * Gets the {@link ConfigurationOptions} for this {@link Configuration}. - *

- * All setters through this method are chainable. - * - * @return Options for this configuration - */ - @NotNull - public ConfigurationOptions options(); -} diff --git a/api/src/main/java/org/bukkit/configuration/ConfigurationOptions.java b/api/src/main/java/org/bukkit/configuration/ConfigurationOptions.java deleted file mode 100644 index 356bad6bc..000000000 --- a/api/src/main/java/org/bukkit/configuration/ConfigurationOptions.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.bukkit.configuration; - -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Configuration configuration) { - this.configuration = configuration; - } - - /** - * Returns the {@link Configuration} that this object is responsible for. - * - * @return Parent configuration - */ - @NotNull - 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 - */ - @NotNull - 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(java.lang.String)} will always - * return the same value as {@link - * ConfigurationSection#isSet(java.lang.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(java.lang.String)} will always - * return the same value as {@link - * ConfigurationSection#isSet(java.lang.String)}. The default value is - * false. - * - * @param value Whether or not defaults are directly copied - * @return This object, for chaining - */ - @NotNull - public ConfigurationOptions copyDefaults(boolean value) { - this.copyDefaults = value; - return this; - } -} diff --git a/api/src/main/java/org/bukkit/configuration/ConfigurationSection.java b/api/src/main/java/org/bukkit/configuration/ConfigurationSection.java deleted file mode 100644 index 5a6e621d5..000000000 --- a/api/src/main/java/org/bukkit/configuration/ConfigurationSection.java +++ /dev/null @@ -1,988 +0,0 @@ -package org.bukkit.configuration; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.bukkit.Color; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - @NotNull - public 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. - */ - @NotNull - public 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. - */ - public boolean contains(@NotNull String path); - - /** - * Checks if this {@link ConfigurationSection} contains the given path. - *

- * If the value for the requested path does not exist, the boolean parameter - * of true has been specified, a default value for the path exists, this - * will return true. - *

- * If a boolean parameter of false has been specified, true will only be - * returned if there is a set value for the specified path. - * - * @param path Path to check for existence. - * @param ignoreDefault Whether or not to ignore if a default value for the - * specified path exists. - * @return True if this section contains the requested path, or if a default - * value exist and the boolean parameter for this method is true. - * @throws IllegalArgumentException Thrown when path is null. - */ - public boolean contains(@NotNull String path, boolean ignoreDefault); - - /** - * 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. - */ - public boolean isSet(@NotNull 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 - */ - @Nullable - public 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 - */ - @NotNull - public 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. - */ - @Nullable - public 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. - */ - @Nullable - public 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. - */ - @Nullable - public Object get(@NotNull 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. - */ - @Nullable - public Object get(@NotNull String path, @Nullable 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(java.lang.String)} for that. - * - * @param path Path of the object to set. - * @param value New value to set the path to. - */ - public void set(@NotNull String path, @Nullable 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 - */ - @NotNull - public ConfigurationSection createSection(@NotNull 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 - */ - @NotNull - public ConfigurationSection createSection(@NotNull String path, @NotNull 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. - */ - @Nullable - public String getString(@NotNull 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. - */ - @Nullable - public String getString(@NotNull String path, @Nullable 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. - */ - public boolean isString(@NotNull 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. - */ - public int getInt(@NotNull 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. - */ - public int getInt(@NotNull 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. - */ - public boolean isInt(@NotNull 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. - */ - public boolean getBoolean(@NotNull 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. - */ - public boolean getBoolean(@NotNull 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. - */ - public boolean isBoolean(@NotNull 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. - */ - public double getDouble(@NotNull 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. - */ - public double getDouble(@NotNull 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. - */ - public boolean isDouble(@NotNull String path); - - /** - * 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. - */ - public long getLong(@NotNull 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. - */ - public long getLong(@NotNull 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. - */ - public boolean isLong(@NotNull 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. - */ - @Nullable - public List getList(@NotNull 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. - */ - @Nullable - public List getList(@NotNull String path, @Nullable 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. - */ - public boolean isList(@NotNull 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. - */ - @NotNull - public List getStringList(@NotNull 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. - */ - @NotNull - public List getIntegerList(@NotNull 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. - */ - @NotNull - public List getBooleanList(@NotNull 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. - */ - @NotNull - public List getDoubleList(@NotNull 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. - */ - @NotNull - public List getFloatList(@NotNull 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. - */ - @NotNull - public List getLongList(@NotNull 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. - */ - @NotNull - public List getByteList(@NotNull 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. - */ - @NotNull - public List getCharacterList(@NotNull 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. - */ - @NotNull - public List getShortList(@NotNull 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. - */ - @NotNull - public List> getMapList(@NotNull String path); - - // Bukkit - /** - * Gets the requested object at the given 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. - * - * Note: For example #getObject(path, String.class) is not - * equivalent to {@link #getString(String) #getString(path)} because - * {@link #getString(String) #getString(path)} converts internally all - * Objects to Strings. However, #getObject(path, Boolean.class) is - * equivalent to {@link #getBoolean(String) #getBoolean(path)} for example. - * - * @param the type of the requested object - * @param path the path to the object. - * @param clazz the type of the requested object - * @return Requested object - */ - @Nullable - public T getObject(@NotNull String path, @NotNull Class clazz); - - /** - * Gets the requested object at the given 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}. - * - * Note: For example #getObject(path, String.class, def) is - * not equivalent to - * {@link #getString(String, String) #getString(path, def)} because - * {@link #getString(String, String) #getString(path, def)} converts - * internally all Objects to Strings. However, #getObject(path, - * Boolean.class, def) is equivalent to {@link #getBoolean(String, boolean) #getBoolean(path, - * def)} for example. - * - * @param the type of the requested object - * @param path the path to the object. - * @param clazz the type of the requested object - * @param def the default object to return if the object is not present at - * the path - * @return Requested object - */ - @Nullable - public T getObject(@NotNull String path, @NotNull Class clazz, @Nullable T def); - - /** - * Gets the requested {@link ConfigurationSerializable} object at the given - * 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 the type of {@link ConfigurationSerializable} - * @param path the path to the object. - * @param clazz the type of {@link ConfigurationSerializable} - * @return Requested {@link ConfigurationSerializable} object - */ - @Nullable - public T getSerializable(@NotNull String path, @NotNull Class clazz); - - /** - * Gets the requested {@link ConfigurationSerializable} object at the given - * 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 the type of {@link ConfigurationSerializable} - * @param path the path to the object. - * @param clazz the type of {@link ConfigurationSerializable} - * @param def the default object to return if the object is not present at - * the path - * @return Requested {@link ConfigurationSerializable} object - */ - @Nullable - public T getSerializable(@NotNull String path, @NotNull Class clazz, @Nullable T def); - - /** - * 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. - */ - @Nullable - public Vector getVector(@NotNull 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. - */ - @Nullable - public Vector getVector(@NotNull String path, @Nullable 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. - */ - public boolean isVector(@NotNull 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. - */ - @Nullable - public OfflinePlayer getOfflinePlayer(@NotNull 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. - */ - @Nullable - public OfflinePlayer getOfflinePlayer(@NotNull String path, @Nullable 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. - */ - public boolean isOfflinePlayer(@NotNull 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. - */ - @Nullable - public ItemStack getItemStack(@NotNull 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. - */ - @Nullable - public ItemStack getItemStack(@NotNull String path, @Nullable 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. - */ - public boolean isItemStack(@NotNull 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. - */ - @Nullable - public Color getColor(@NotNull 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. - */ - @Nullable - public Color getColor(@NotNull String path, @Nullable 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. - */ - public boolean isColor(@NotNull String path); - - /** - * Gets the requested Location by path. - *

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

- * If the Location 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 Location to get. - * @param def The default value to return if the path is not found or is not - * a Location. - * @return Requested Location. - */ - @Nullable - public Location getLocation(@NotNull String path, @Nullable Location def); - - /** - * Checks if the specified path is a Location. - *

- * If the path exists but is not a Location, 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 Location and return appropriately. - * - * @param path Path of the Location to check. - * @return Whether or not the specified path is a Location. - */ - public boolean isLocation(@NotNull 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. - */ - @Nullable - public ConfigurationSection getConfigurationSection(@NotNull 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. - */ - public boolean isConfigurationSection(@NotNull 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 - */ - @Nullable - public 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. - */ - public void addDefault(@NotNull String path, @Nullable Object value); -} diff --git a/api/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java b/api/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java deleted file mode 100644 index d23480e59..000000000 --- a/api/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java +++ /dev/null @@ -1,45 +0,0 @@ -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/api/src/main/java/org/bukkit/configuration/MemoryConfiguration.java b/api/src/main/java/org/bukkit/configuration/MemoryConfiguration.java deleted file mode 100644 index 010a97fee..000000000 --- a/api/src/main/java/org/bukkit/configuration/MemoryConfiguration.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.bukkit.configuration; - -import java.util.Map; -import org.apache.commons.lang.Validate; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@Nullable Configuration defaults) { - this.defaults = defaults; - } - - @Override - public void addDefault(@NotNull String path, @Nullable Object value) { - Validate.notNull(path, "Path may not be null"); - - if (defaults == null) { - defaults = new MemoryConfiguration(); - } - - defaults.set(path, value); - } - - @Override - public void addDefaults(@NotNull Map defaults) { - Validate.notNull(defaults, "Defaults may not be null"); - - for (Map.Entry entry : defaults.entrySet()) { - addDefault(entry.getKey(), entry.getValue()); - } - } - - @Override - public void addDefaults(@NotNull Configuration defaults) { - Validate.notNull(defaults, "Defaults may not be null"); - - addDefaults(defaults.getValues(true)); - } - - @Override - public void setDefaults(@NotNull Configuration defaults) { - Validate.notNull(defaults, "Defaults may not be null"); - - this.defaults = defaults; - } - - @Override - @Nullable - public Configuration getDefaults() { - return defaults; - } - - @Nullable - @Override - public ConfigurationSection getParent() { - return null; - } - - @Override - @NotNull - public MemoryConfigurationOptions options() { - if (options == null) { - options = new MemoryConfigurationOptions(this); - } - - return options; - } -} diff --git a/api/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java b/api/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java deleted file mode 100644 index ead85f6fa..000000000 --- a/api/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.configuration; - -import org.jetbrains.annotations.NotNull; - -/** - * Various settings for controlling the input and output of a {@link - * MemoryConfiguration} - */ -public class MemoryConfigurationOptions extends ConfigurationOptions { - protected MemoryConfigurationOptions(@NotNull MemoryConfiguration configuration) { - super(configuration); - } - - @NotNull - @Override - public MemoryConfiguration configuration() { - return (MemoryConfiguration) super.configuration(); - } - - @NotNull - @Override - public MemoryConfigurationOptions copyDefaults(boolean value) { - super.copyDefaults(value); - return this; - } - - @NotNull - @Override - public MemoryConfigurationOptions pathSeparator(char value) { - super.pathSeparator(value); - return this; - } -} diff --git a/api/src/main/java/org/bukkit/configuration/MemorySection.java b/api/src/main/java/org/bukkit/configuration/MemorySection.java deleted file mode 100644 index e9b6a12a8..000000000 --- a/api/src/main/java/org/bukkit/configuration/MemorySection.java +++ /dev/null @@ -1,963 +0,0 @@ -package org.bukkit.configuration; - -import static org.bukkit.util.NumberConversions.*; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.commons.lang.Validate; -import org.bukkit.Color; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull ConfigurationSection parent, @NotNull 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); - } - - @Override - @NotNull - 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; - } - - @Override - @NotNull - 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; - } - - @Override - public boolean contains(@NotNull String path) { - return contains(path, false); - } - - @Override - public boolean contains(@NotNull String path, boolean ignoreDefault) { - return ((ignoreDefault) ? get(path, null) : get(path)) != null; - } - - @Override - public boolean isSet(@NotNull String path) { - Configuration root = getRoot(); - if (root == null) { - return false; - } - if (root.options().copyDefaults()) { - return contains(path); - } - return get(path, null) != null; - } - - @Override - @NotNull - public String getCurrentPath() { - return fullPath; - } - - @Override - @NotNull - public String getName() { - return path; - } - - @Override - @Nullable - public Configuration getRoot() { - return root; - } - - @Override - @Nullable - public ConfigurationSection getParent() { - return parent; - } - - @Override - public void addDefault(@NotNull String path, @Nullable 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); - } - - @Override - @Nullable - 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; - } - - @Override - public void set(@NotNull String path, @Nullable 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) { - if (value == null) { - // no need to create missing sub-sections if we want to remove the value: - return; - } - 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); - } - } - - @Override - @Nullable - public Object get(@NotNull String path) { - return get(path, getDefault(path)); - } - - @Override - @Nullable - public Object get(@NotNull String path, @Nullable 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); - } - - @Override - @NotNull - public ConfigurationSection createSection(@NotNull 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); - } - - @Override - @NotNull - public ConfigurationSection createSection(@NotNull String path, @NotNull 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 - @Override - @Nullable - public String getString(@NotNull String path) { - Object def = getDefault(path); - return getString(path, def != null ? def.toString() : null); - } - - @Override - @Nullable - public String getString(@NotNull String path, @Nullable String def) { - Object val = get(path, def); - return (val != null) ? val.toString() : def; - } - - @Override - public boolean isString(@NotNull String path) { - Object val = get(path); - return val instanceof String; - } - - @Override - public int getInt(@NotNull String path) { - Object def = getDefault(path); - return getInt(path, (def instanceof Number) ? toInt(def) : 0); - } - - @Override - public int getInt(@NotNull String path, int def) { - Object val = get(path, def); - return (val instanceof Number) ? toInt(val) : def; - } - - @Override - public boolean isInt(@NotNull String path) { - Object val = get(path); - return val instanceof Integer; - } - - @Override - public boolean getBoolean(@NotNull String path) { - Object def = getDefault(path); - return getBoolean(path, (def instanceof Boolean) ? (Boolean) def : false); - } - - @Override - public boolean getBoolean(@NotNull String path, boolean def) { - Object val = get(path, def); - return (val instanceof Boolean) ? (Boolean) val : def; - } - - @Override - public boolean isBoolean(@NotNull String path) { - Object val = get(path); - return val instanceof Boolean; - } - - @Override - public double getDouble(@NotNull String path) { - Object def = getDefault(path); - return getDouble(path, (def instanceof Number) ? toDouble(def) : 0); - } - - @Override - public double getDouble(@NotNull String path, double def) { - Object val = get(path, def); - return (val instanceof Number) ? toDouble(val) : def; - } - - @Override - public boolean isDouble(@NotNull String path) { - Object val = get(path); - return val instanceof Double; - } - - @Override - public long getLong(@NotNull String path) { - Object def = getDefault(path); - return getLong(path, (def instanceof Number) ? toLong(def) : 0); - } - - @Override - public long getLong(@NotNull String path, long def) { - Object val = get(path, def); - return (val instanceof Number) ? toLong(val) : def; - } - - @Override - public boolean isLong(@NotNull String path) { - Object val = get(path); - return val instanceof Long; - } - - // Java - @Override - @Nullable - public List getList(@NotNull String path) { - Object def = getDefault(path); - return getList(path, (def instanceof List) ? (List) def : null); - } - - @Override - @Nullable - public List getList(@NotNull String path, @Nullable List def) { - Object val = get(path, def); - return (List) ((val instanceof List) ? val : def); - } - - @Override - public boolean isList(@NotNull String path) { - Object val = get(path); - return val instanceof List; - } - - @Override - @NotNull - public List getStringList(@NotNull 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; - } - - @Override - @NotNull - public List getIntegerList(@NotNull 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 ex) { - } - } else if (object instanceof Character) { - result.add((int) ((Character) object).charValue()); - } else if (object instanceof Number) { - result.add(((Number) object).intValue()); - } - } - - return result; - } - - @Override - @NotNull - public List getBooleanList(@NotNull 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; - } - - @Override - @NotNull - public List getDoubleList(@NotNull 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 ex) { - } - } else if (object instanceof Character) { - result.add((double) ((Character) object).charValue()); - } else if (object instanceof Number) { - result.add(((Number) object).doubleValue()); - } - } - - return result; - } - - @Override - @NotNull - public List getFloatList(@NotNull 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 ex) { - } - } else if (object instanceof Character) { - result.add((float) ((Character) object).charValue()); - } else if (object instanceof Number) { - result.add(((Number) object).floatValue()); - } - } - - return result; - } - - @Override - @NotNull - public List getLongList(@NotNull 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 ex) { - } - } else if (object instanceof Character) { - result.add((long) ((Character) object).charValue()); - } else if (object instanceof Number) { - result.add(((Number) object).longValue()); - } - } - - return result; - } - - @Override - @NotNull - public List getByteList(@NotNull 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 ex) { - } - } else if (object instanceof Character) { - result.add((byte) ((Character) object).charValue()); - } else if (object instanceof Number) { - result.add(((Number) object).byteValue()); - } - } - - return result; - } - - @Override - @NotNull - public List getCharacterList(@NotNull 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; - } - - @Override - @NotNull - public List getShortList(@NotNull 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 ex) { - } - } else if (object instanceof Character) { - result.add((short) ((Character) object).charValue()); - } else if (object instanceof Number) { - result.add(((Number) object).shortValue()); - } - } - - return result; - } - - @Override - @NotNull - public List> getMapList(@NotNull 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 - @Nullable - @Override - public T getObject(@NotNull String path, @NotNull Class clazz) { - Validate.notNull(clazz, "Class cannot be null"); - Object def = getDefault(path); - return getObject(path, clazz, (def != null && clazz.isInstance(def)) ? clazz.cast(def) : null); - } - - @Nullable - @Override - public T getObject(@NotNull String path, @NotNull Class clazz, @Nullable T def) { - Validate.notNull(clazz, "Class cannot be null"); - Object val = get(path, def); - return (val != null && clazz.isInstance(val)) ? clazz.cast(val) : def; - } - - @Nullable - @Override - public T getSerializable(@NotNull String path, @NotNull Class clazz) { - return getObject(path, clazz); - } - - @Nullable - @Override - public T getSerializable(@NotNull String path, @NotNull Class clazz, @Nullable T def) { - return getObject(path, clazz, def); - } - - @Override - @Nullable - public Vector getVector(@NotNull String path) { - return getSerializable(path, Vector.class); - } - - @Override - @Nullable - public Vector getVector(@NotNull String path, @Nullable Vector def) { - return getSerializable(path, Vector.class, def); - } - - @Override - public boolean isVector(@NotNull String path) { - return getSerializable(path, Vector.class) != null; - } - - @Override - @Nullable - public OfflinePlayer getOfflinePlayer(@NotNull String path) { - return getSerializable(path, OfflinePlayer.class); - } - - @Override - @Nullable - public OfflinePlayer getOfflinePlayer(@NotNull String path, @Nullable OfflinePlayer def) { - return getSerializable(path, OfflinePlayer.class, def); - } - - @Override - public boolean isOfflinePlayer(@NotNull String path) { - return getSerializable(path, OfflinePlayer.class) != null; - } - - @Override - @Nullable - public ItemStack getItemStack(@NotNull String path) { - return getSerializable(path, ItemStack.class); - } - - @Override - @Nullable - public ItemStack getItemStack(@NotNull String path, @Nullable ItemStack def) { - return getSerializable(path, ItemStack.class, def); - } - - @Override - public boolean isItemStack(@NotNull String path) { - return getSerializable(path, ItemStack.class) != null; - } - - @Override - @Nullable - public Color getColor(@NotNull String path) { - return getSerializable(path, Color.class); - } - - @Override - @Nullable - public Color getColor(@NotNull String path, @Nullable Color def) { - return getSerializable(path, Color.class, def); - } - - @Override - public boolean isColor(@NotNull String path) { - return getSerializable(path, Color.class) != null; - } - - @Override - @Nullable - public Location getLocation(@NotNull String path) { - return getSerializable(path, Location.class); - } - - @Override - @Nullable - public Location getLocation(@NotNull String path, @Nullable Location def) { - return getSerializable(path, Location.class, def); - } - - @Override - public boolean isLocation(@NotNull String path) { - return getSerializable(path, Location.class) != null; - } - - @Override - @Nullable - public ConfigurationSection getConfigurationSection(@NotNull 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; - } - - @Override - public boolean isConfigurationSection(@NotNull String path) { - Object val = get(path); - return val instanceof ConfigurationSection; - } - - protected boolean isPrimitiveWrapper(@Nullable 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; - } - - @Nullable - protected Object getDefault(@NotNull 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(@NotNull Set output, @NotNull 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(@NotNull Map output, @NotNull ConfigurationSection section, boolean deep) { - if (section instanceof MemorySection) { - MemorySection sec = (MemorySection) section; - - for (Map.Entry entry : sec.map.entrySet()) { - // Because of the copyDefaults call potentially copying out of order, we must remove and then add in our saved order - // This means that default values we haven't set end up getting placed first - // See SPIGOT-4558 for an example using spigot.yml - watch subsections move around to default order - String childPath = createPath(section, entry.getKey(), this); - output.remove(childPath); - output.put(childPath, 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. - */ - @NotNull - public static String createPath(@NotNull ConfigurationSection section, @Nullable 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. - */ - @NotNull - public static String createPath(@NotNull ConfigurationSection section, @Nullable String key, @Nullable 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/api/src/main/java/org/bukkit/configuration/file/FileConfiguration.java b/api/src/main/java/org/bukkit/configuration/file/FileConfiguration.java deleted file mode 100644 index 581889ffa..000000000 --- a/api/src/main/java/org/bukkit/configuration/file/FileConfiguration.java +++ /dev/null @@ -1,226 +0,0 @@ -package org.bukkit.configuration.file; - -import com.google.common.base.Charsets; -import com.google.common.io.Files; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; -import org.apache.commons.lang.Validate; -import org.bukkit.configuration.Configuration; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.MemoryConfiguration; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * This is a base class for all File based implementations of {@link - * Configuration} - */ -public abstract class FileConfiguration extends MemoryConfiguration { - - /** - * 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(@Nullable 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(@NotNull File file) throws IOException { - Validate.notNull(file, "File cannot be null"); - - Files.createParentDirs(file); - - String data = saveToString(); - - Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8); - - 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(@NotNull 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. - */ - @NotNull - 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. - * - * @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(@NotNull File file) throws FileNotFoundException, IOException, InvalidConfigurationException { - Validate.notNull(file, "File cannot be null"); - - final FileInputStream stream = new FileInputStream(file); - - load(new InputStreamReader(stream, Charsets.UTF_8)); - } - - /** - * 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(@NotNull 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(@NotNull 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(@NotNull 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 - */ - @NotNull - protected abstract String buildHeader(); - - @NotNull - @Override - public FileConfigurationOptions options() { - if (options == null) { - options = new FileConfigurationOptions(this); - } - - return (FileConfigurationOptions) options; - } -} diff --git a/api/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java b/api/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java deleted file mode 100644 index eaa0aface..000000000 --- a/api/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.bukkit.configuration.file; - -import org.bukkit.configuration.MemoryConfiguration; -import org.bukkit.configuration.MemoryConfigurationOptions; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull MemoryConfiguration configuration) { - super(configuration); - } - - @NotNull - @Override - public FileConfiguration configuration() { - return (FileConfiguration) super.configuration(); - } - - @NotNull - @Override - public FileConfigurationOptions copyDefaults(boolean value) { - super.copyDefaults(value); - return this; - } - - @NotNull - @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 - */ - @Nullable - 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 - */ - @NotNull - public FileConfigurationOptions header(@Nullable 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(org.bukkit.configuration.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(org.bukkit.configuration.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 - */ - @NotNull - public FileConfigurationOptions copyHeader(boolean value) { - copyHeader = value; - - return this; - } -} diff --git a/api/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java b/api/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java deleted file mode 100644 index dc8cb1937..000000000 --- a/api/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.bukkit.configuration.file; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -import java.util.Map; -import java.util.logging.Level; -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.jetbrains.annotations.NotNull; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.error.YAMLException; -import org.yaml.snakeyaml.representer.Representer; - -/** - * 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(), yamlRepresenter, yamlOptions); - - @NotNull - @Override - public String saveToString() { - yamlOptions.setIndent(options().indent()); - yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - - String header = buildHeader(); - String dump = yaml.dump(getValues(false)); - - if (dump.equals(BLANK_CONFIG)) { - dump = ""; - } - - return header + dump; - } - - @Override - public void loadFromString(@NotNull String contents) throws InvalidConfigurationException { - Validate.notNull(contents, "Contents cannot be null"); - - Map input; - try { - input = (Map) 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(@NotNull Map input, @NotNull 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); - } - } - } - - @NotNull - protected String parseHeader(@NotNull 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(); - } - - @NotNull - @Override - protected String buildHeader() { - String header = options().header(); - - if (options().copyHeader()) { - Configuration def = getDefaults(); - - if ((def != null) && (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(); - } - - @NotNull - @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 - */ - @NotNull - public static YamlConfiguration loadConfiguration(@NotNull File file) { - Validate.notNull(file, "File cannot be null"); - - YamlConfiguration config = new YamlConfiguration(); - - try { - config.load(file); - } catch (FileNotFoundException ex) { - } catch (IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); - } catch (InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, 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 - */ - @NotNull - public static YamlConfiguration loadConfiguration(@NotNull Reader reader) { - Validate.notNull(reader, "Stream cannot be null"); - - YamlConfiguration config = new YamlConfiguration(); - - try { - config.load(reader); - } catch (IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); - } catch (InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); - } - - return config; - } -} diff --git a/api/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java b/api/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java deleted file mode 100644 index b2bf9785a..000000000 --- a/api/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.bukkit.configuration.file; - -import org.apache.commons.lang.Validate; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Various settings for controlling the input and output of a {@link - * YamlConfiguration} - */ -public class YamlConfigurationOptions extends FileConfigurationOptions { - private int indent = 2; - - protected YamlConfigurationOptions(@NotNull YamlConfiguration configuration) { - super(configuration); - } - - @NotNull - @Override - public YamlConfiguration configuration() { - return (YamlConfiguration) super.configuration(); - } - - @NotNull - @Override - public YamlConfigurationOptions copyDefaults(boolean value) { - super.copyDefaults(value); - return this; - } - - @NotNull - @Override - public YamlConfigurationOptions pathSeparator(char value) { - super.pathSeparator(value); - return this; - } - - @NotNull - @Override - public YamlConfigurationOptions header(@Nullable String value) { - super.header(value); - return this; - } - - @NotNull - @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 - */ - @NotNull - 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/api/src/main/java/org/bukkit/configuration/file/YamlConstructor.java b/api/src/main/java/org/bukkit/configuration/file/YamlConstructor.java deleted file mode 100644 index c8466a29a..000000000 --- a/api/src/main/java/org/bukkit/configuration/file/YamlConstructor.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.configuration.file; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.bukkit.configuration.serialization.ConfigurationSerialization; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.yaml.snakeyaml.constructor.SafeConstructor; -import org.yaml.snakeyaml.error.YAMLException; -import org.yaml.snakeyaml.nodes.Node; -import org.yaml.snakeyaml.nodes.Tag; - -public class YamlConstructor extends SafeConstructor { - - public YamlConstructor() { - this.yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); - } - - private class ConstructCustomObject extends ConstructYamlMap { - - @Nullable - @Override - public Object construct(@NotNull 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(@NotNull Node node, @NotNull Object object) { - throw new YAMLException("Unexpected referential mapping structure. Node: " + node); - } - } -} diff --git a/api/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java b/api/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java deleted file mode 100644 index f03da3622..000000000 --- a/api/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.configuration.file; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.ConfigurationSerialization; -import org.jetbrains.annotations.NotNull; -import org.yaml.snakeyaml.nodes.Node; -import org.yaml.snakeyaml.representer.Representer; - -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 { - - @NotNull - @Override - public Node representData(@NotNull Object data) { - return super.representData(((ConfigurationSection) data).getValues(false)); - } - } - - private class RepresentConfigurationSerializable extends RepresentMap { - - @NotNull - @Override - public Node representData(@NotNull 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/api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java b/api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java deleted file mode 100644 index 177944d4e..000000000 --- a/api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.configuration.serialization; - -import java.util.Map; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public Map serialize(); -} diff --git a/api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java b/api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java deleted file mode 100644 index 8c9b4f696..000000000 --- a/api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java +++ /dev/null @@ -1,299 +0,0 @@ -package org.bukkit.configuration.serialization; - -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; -import org.apache.commons.lang.Validate; -import org.bukkit.Color; -import org.bukkit.FireworkEffect; -import org.bukkit.Location; -import org.bukkit.attribute.AttributeModifier; -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.BoundingBox; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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); - registerClass(AttributeModifier.class); - registerClass(BoundingBox.class); - } - - protected ConfigurationSerialization(@NotNull Class clazz) { - this.clazz = clazz; - } - - @Nullable - protected Method getMethod(@NotNull 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 ex) { - return null; - } catch (SecurityException ex) { - return null; - } - } - - @Nullable - protected Constructor getConstructor() { - try { - return clazz.getConstructor(Map.class); - } catch (NoSuchMethodException ex) { - return null; - } catch (SecurityException ex) { - return null; - } - } - - @Nullable - protected ConfigurationSerializable deserializeViaMethod(@NotNull Method method, @NotNull 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; - } - - @Nullable - protected ConfigurationSerializable deserializeViaCtor(@NotNull Constructor ctor, @NotNull 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; - } - - @Nullable - public ConfigurationSerializable deserialize(@NotNull 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 - */ - @Nullable - public static ConfigurationSerializable deserializeObject(@NotNull Map args, @NotNull 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 - */ - @Nullable - public static ConfigurationSerializable deserializeObject(@NotNull 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(@NotNull 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(@NotNull Class clazz, @NotNull String alias) { - aliases.put(alias, clazz); - } - - /** - * Unregisters the specified alias to a {@link ConfigurationSerializable} - * - * @param alias Alias to unregister - */ - public static void unregisterClass(@NotNull String alias) { - aliases.remove(alias); - } - - /** - * Unregisters any aliases for the specified {@link - * ConfigurationSerializable} class - * - * @param clazz Class to unregister - */ - public static void unregisterClass(@NotNull 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 - */ - @Nullable - public static Class getClassByAlias(@NotNull 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 - */ - @NotNull - public static String getAlias(@NotNull 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/api/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java b/api/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java deleted file mode 100644 index 138396116..000000000 --- a/api/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java +++ /dev/null @@ -1,24 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public Class value(); -} diff --git a/api/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java b/api/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java deleted file mode 100644 index 725685ed3..000000000 --- a/api/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java +++ /dev/null @@ -1,36 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - @NotNull - public String value(); -} diff --git a/api/src/main/java/org/bukkit/conversations/BooleanPrompt.java b/api/src/main/java/org/bukkit/conversations/BooleanPrompt.java deleted file mode 100644 index 95d054436..000000000 --- a/api/src/main/java/org/bukkit/conversations/BooleanPrompt.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.conversations; - -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.BooleanUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull ConversationContext context, @NotNull String input) { - String[] accepted = {/* Apache values: */"true", "false", "on", "off", "yes", "no",/* Additional values: */ "y", "n", "1", "0", "right", "wrong", "correct", "incorrect", "valid", "invalid"}; - return ArrayUtils.contains(accepted, input.toLowerCase()); - } - - @Nullable - @Override - protected Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { - if (input.equalsIgnoreCase("y") || input.equals("1") || input.equalsIgnoreCase("right") || input.equalsIgnoreCase("correct") || input.equalsIgnoreCase("valid")) input = "true"; - 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. - */ - @Nullable - protected abstract Prompt acceptValidatedInput(@NotNull ConversationContext context, boolean input); -} diff --git a/api/src/main/java/org/bukkit/conversations/Conversable.java b/api/src/main/java/org/bukkit/conversations/Conversable.java deleted file mode 100644 index 914c6388e..000000000 --- a/api/src/main/java/org/bukkit/conversations/Conversable.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - public 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 - */ - public void acceptConversationInput(@NotNull 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 - */ - public boolean beginConversation(@NotNull Conversation conversation); - - /** - * Abandons an active conversation. - * - * @param conversation The conversation to abandon - */ - public void abandonConversation(@NotNull Conversation conversation); - - /** - * Abandons an active conversation. - * - * @param conversation The conversation to abandon - * @param details Details about why the conversation was abandoned - */ - public void abandonConversation(@NotNull Conversation conversation, @NotNull ConversationAbandonedEvent details); - - /** - * Sends this sender a message raw - * - * @param message Message to be displayed - */ - public void sendRawMessage(@NotNull String message); -} diff --git a/api/src/main/java/org/bukkit/conversations/Conversation.java b/api/src/main/java/org/bukkit/conversations/Conversation.java deleted file mode 100644 index bf2407c83..000000000 --- a/api/src/main/java/org/bukkit/conversations/Conversation.java +++ /dev/null @@ -1,303 +0,0 @@ -package org.bukkit.conversations; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@Nullable Plugin plugin, @NotNull Conversable forWhom, @Nullable 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(@Nullable Plugin plugin, @NotNull Conversable forWhom, @Nullable Prompt firstPrompt, @NotNull 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. - */ - @NotNull - 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. - */ - @NotNull - public ConversationPrefix getPrefix() { - return prefix; - } - - /** - * Sets the {@link ConversationPrefix} that prepends all output from this - * conversation. - * - * @param prefix The ConversationPrefix to use. - */ - void setPrefix(@NotNull ConversationPrefix prefix) { - this.prefix = prefix; - } - - /** - * Adds a {@link ConversationCanceller} to the cancellers collection. - * - * @param canceller The {@link ConversationCanceller} to add. - */ - void addConversationCanceller(@NotNull ConversationCanceller canceller) { - canceller.setConversation(this); - this.cancellers.add(canceller); - } - - /** - * Gets the list of {@link ConversationCanceller}s - * - * @return The list. - */ - @NotNull - public List getCancellers() { - return cancellers; - } - - /** - * Returns the Conversation's {@link ConversationContext}. - * - * @return The ConversationContext. - */ - @NotNull - 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. - */ - @NotNull - 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(@NotNull String input) { - 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(); - } - } - - /** - * Adds a {@link ConversationAbandonedListener}. - * - * @param listener The listener to add. - */ - public synchronized void addConversationAbandonedListener(@NotNull ConversationAbandonedListener listener) { - abandonedListeners.add(listener); - } - - /** - * Removes a {@link ConversationAbandonedListener}. - * - * @param listener The listener to remove. - */ - public synchronized void removeConversationAbandonedListener(@NotNull 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(@NotNull 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/api/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java b/api/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java deleted file mode 100644 index 0d67fe0c0..000000000 --- a/api/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.bukkit.conversations; - -import java.util.EventObject; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * ConversationAbandonedEvent contains information about an abandoned - * conversation. - */ -public class ConversationAbandonedEvent extends EventObject { - - private ConversationContext context; - private ConversationCanceller canceller; - - public ConversationAbandonedEvent(@NotNull Conversation conversation) { - this(conversation, null); - } - - public ConversationAbandonedEvent(@NotNull Conversation conversation, @Nullable 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. - */ - @Nullable - public ConversationCanceller getCanceller() { - return canceller; - } - - /** - * Gets the abandoned conversation's conversation context. - * - * @return The abandoned conversation's conversation context. - */ - @NotNull - 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/api/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java b/api/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java deleted file mode 100644 index 451121e7d..000000000 --- a/api/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bukkit.conversations; - -import java.util.EventListener; -import org.jetbrains.annotations.NotNull; - -/** - */ -public interface ConversationAbandonedListener extends EventListener { - /** - * Called whenever a {@link Conversation} is abandoned. - * - * @param abandonedEvent Contains details about the abandoned - * conversation. - */ - public void conversationAbandoned(@NotNull ConversationAbandonedEvent abandonedEvent); -} diff --git a/api/src/main/java/org/bukkit/conversations/ConversationCanceller.java b/api/src/main/java/org/bukkit/conversations/ConversationCanceller.java deleted file mode 100644 index bacac1409..000000000 --- a/api/src/main/java/org/bukkit/conversations/ConversationCanceller.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - public void setConversation(@NotNull 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. - */ - public boolean cancelBasedOnInput(@NotNull ConversationContext context, @NotNull 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. - */ - @NotNull - public ConversationCanceller clone(); -} diff --git a/api/src/main/java/org/bukkit/conversations/ConversationContext.java b/api/src/main/java/org/bukkit/conversations/ConversationContext.java deleted file mode 100644 index 5bc0d36fe..000000000 --- a/api/src/main/java/org/bukkit/conversations/ConversationContext.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.conversations; - -import java.util.Map; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 final Conversable forWhom; - private final Map sessionData; - private final 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(@Nullable Plugin plugin, @NotNull Conversable forWhom, @NotNull Map initialSessionData) { - this.plugin = plugin; - this.forWhom = forWhom; - this.sessionData = initialSessionData; - } - - /** - * Gets the plugin that owns this conversation. - * - * @return The owning plugin. - */ - @Nullable - public Plugin getPlugin() { - return plugin; - } - - /** - * Gets the subject of the conversation. - * - * @return The subject of the conversation. - */ - @NotNull - public Conversable getForWhom() { - return forWhom; - } - - /** - * Gets the underlying sessionData map. - * - * May be directly modified to manipulate session data. - * - * @return The full sessionData map. - */ - @NotNull - 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. - */ - @Nullable - public Object getSessionData(@NotNull 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(@NotNull Object key, @Nullable Object value) { - sessionData.put(key, value); - } -} diff --git a/api/src/main/java/org/bukkit/conversations/ConversationFactory.java b/api/src/main/java/org/bukkit/conversations/ConversationFactory.java deleted file mode 100644 index 58009e1e7..000000000 --- a/api/src/main/java/org/bukkit/conversations/ConversationFactory.java +++ /dev/null @@ -1,240 +0,0 @@ -package org.bukkit.conversations; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull 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. - */ - @NotNull - 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. - */ - @NotNull - 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. - */ - @NotNull - public ConversationFactory withPrefix(@NotNull 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. - */ - @NotNull - 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. - */ - @NotNull - public ConversationFactory withFirstPrompt(@Nullable 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. - */ - @NotNull - public ConversationFactory withInitialSessionData(@NotNull 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. - */ - @NotNull - public ConversationFactory withEscapeSequence(@NotNull String escapeSequence) { - return withConversationCanceller(new ExactMatchConversationCanceller(escapeSequence)); - } - - /** - * Adds a {@link ConversationCanceller} to constructed conversations. - * - * @param canceller The {@link ConversationCanceller} to add. - * @return This object. - */ - @NotNull - public ConversationFactory withConversationCanceller(@NotNull 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. - */ - @NotNull - public ConversationFactory thatExcludesNonPlayersWithMessage(@Nullable 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. - */ - @NotNull - public ConversationFactory addConversationAbandonedListener(@NotNull 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. - */ - @NotNull - public Conversation buildConversation(@NotNull 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 { - - @Override - @NotNull - public String getPromptText(@NotNull ConversationContext context) { - return playerOnlyMessage; - } - - @Nullable - @Override - protected Prompt getNextPrompt(@NotNull ConversationContext context) { - return Prompt.END_OF_CONVERSATION; - } - } -} diff --git a/api/src/main/java/org/bukkit/conversations/ConversationPrefix.java b/api/src/main/java/org/bukkit/conversations/ConversationPrefix.java deleted file mode 100644 index 0c65f3365..000000000 --- a/api/src/main/java/org/bukkit/conversations/ConversationPrefix.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - @NotNull - String getPrefix(@NotNull ConversationContext context); -} diff --git a/api/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java b/api/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java deleted file mode 100644 index 6b54ee877..000000000 --- a/api/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull String escapeSequence) { - this.escapeSequence = escapeSequence; - } - - @Override - public void setConversation(@NotNull Conversation conversation) {} - - @Override - public boolean cancelBasedOnInput(@NotNull ConversationContext context, @NotNull String input) { - return input.equals(escapeSequence); - } - - @Override - @NotNull - public ConversationCanceller clone() { - return new ExactMatchConversationCanceller(escapeSequence); - } -} diff --git a/api/src/main/java/org/bukkit/conversations/FixedSetPrompt.java b/api/src/main/java/org/bukkit/conversations/FixedSetPrompt.java deleted file mode 100644 index 9bf3336fa..000000000 --- a/api/src/main/java/org/bukkit/conversations/FixedSetPrompt.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bukkit.conversations; - -import java.util.Arrays; -import java.util.List; -import org.apache.commons.lang.StringUtils; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull String... fixedSet) { - super(); - this.fixedSet = Arrays.asList(fixedSet); - } - - private FixedSetPrompt() {} - - @Override - protected boolean isInputValid(@NotNull ConversationContext context, @NotNull 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 - */ - @NotNull - protected String formatFixedSet() { - return "[" + StringUtils.join(fixedSet, ", ") + "]"; - } -} diff --git a/api/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java b/api/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java deleted file mode 100644 index fd8daa020..000000000 --- a/api/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.bukkit.conversations; - -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Plugin plugin, int timeoutSeconds) { - this.plugin = plugin; - this.timeoutSeconds = timeoutSeconds; - } - - @Override - public void setConversation(@NotNull Conversation conversation) { - this.conversation = conversation; - startTimer(); - } - - @Override - public boolean cancelBasedOnInput(@NotNull ConversationContext context, @NotNull String input) { - // Reset the inactivity timer - stopTimer(); - startTimer(); - return false; - } - - @Override - @NotNull - public ConversationCanceller clone() { - return new InactivityConversationCanceller(plugin, timeoutSeconds); - } - - /** - * Starts an inactivity timer. - */ - private void startTimer() { - taskId = plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - 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(@NotNull Conversation conversation) { - - } -} diff --git a/api/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java b/api/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java deleted file mode 100644 index 0a289564a..000000000 --- a/api/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; - -/** - * 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 { - @Override - public void setConversation(@NotNull Conversation conversation) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean cancelBasedOnInput(@NotNull ConversationContext context, @NotNull String input) { - throw new UnsupportedOperationException(); - } - - @Override - @NotNull - public ConversationCanceller clone() { - throw new UnsupportedOperationException(); - } -} diff --git a/api/src/main/java/org/bukkit/conversations/MessagePrompt.java b/api/src/main/java/org/bukkit/conversations/MessagePrompt.java deleted file mode 100644 index e066166e5..000000000 --- a/api/src/main/java/org/bukkit/conversations/MessagePrompt.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - @Override - public boolean blocksForInput(@NotNull 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. - */ - @Override - @Nullable - public Prompt acceptInput(@NotNull ConversationContext context, @Nullable 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. - */ - @Nullable - protected abstract Prompt getNextPrompt(@NotNull ConversationContext context); -} diff --git a/api/src/main/java/org/bukkit/conversations/NullConversationPrefix.java b/api/src/main/java/org/bukkit/conversations/NullConversationPrefix.java deleted file mode 100644 index 6ee8ebb1e..000000000 --- a/api/src/main/java/org/bukkit/conversations/NullConversationPrefix.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - @Override - @NotNull - public String getPrefix(@NotNull ConversationContext context) { - return ""; - } -} diff --git a/api/src/main/java/org/bukkit/conversations/NumericPrompt.java b/api/src/main/java/org/bukkit/conversations/NumericPrompt.java deleted file mode 100644 index 5da28a3b4..000000000 --- a/api/src/main/java/org/bukkit/conversations/NumericPrompt.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.bukkit.conversations; - -import org.apache.commons.lang.math.NumberUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull ConversationContext context, @NotNull 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(@NotNull ConversationContext context, @NotNull Number input) { - return true; - } - - @Nullable - @Override - protected Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull 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. - */ - @Nullable - protected abstract Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull Number input); - - @Nullable - @Override - protected String getFailedValidationText(@NotNull ConversationContext context, @NotNull 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. - */ - @Nullable - protected String getInputNotNumericText(@NotNull ConversationContext context, @NotNull 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. - */ - @Nullable - protected String getFailedValidationText(@NotNull ConversationContext context, @NotNull Number invalidInput) { - return null; - } -} diff --git a/api/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java b/api/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java deleted file mode 100644 index 86d51c488..000000000 --- a/api/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.conversations; - -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull Plugin plugin) { - super(); - this.plugin = plugin; - } - - @Override - protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { - return plugin.getServer().getPlayer(input) != null; - } - - @Nullable - @Override - protected Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull 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. - */ - @Nullable - protected abstract Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull Player input); -} diff --git a/api/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java b/api/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java deleted file mode 100644 index 5911944fe..000000000 --- a/api/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.conversations; - -import org.bukkit.ChatColor; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Plugin plugin) { - this(plugin, " > ", ChatColor.LIGHT_PURPLE); - } - - public PluginNameConversationPrefix(@NotNull Plugin plugin, @NotNull String separator, @NotNull 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. - */ - @Override - @NotNull - public String getPrefix(@NotNull ConversationContext context) { - return cachedPrefix; - } -} diff --git a/api/src/main/java/org/bukkit/conversations/Prompt.java b/api/src/main/java/org/bukkit/conversations/Prompt.java deleted file mode 100644 index fcca208c0..000000000 --- a/api/src/main/java/org/bukkit/conversations/Prompt.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - static final 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. - */ - @NotNull - String getPromptText(@NotNull 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. If false, {@link #acceptInput(ConversationContext, String)} will be called immediately with {@code null} input. - */ - boolean blocksForInput(@NotNull 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. - */ - @Nullable - Prompt acceptInput(@NotNull ConversationContext context, @Nullable String input); -} diff --git a/api/src/main/java/org/bukkit/conversations/RegexPrompt.java b/api/src/main/java/org/bukkit/conversations/RegexPrompt.java deleted file mode 100644 index 6b3f1e459..000000000 --- a/api/src/main/java/org/bukkit/conversations/RegexPrompt.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.conversations; - -import java.util.regex.Pattern; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull String regex) { - this(Pattern.compile(regex)); - } - - public RegexPrompt(@NotNull Pattern pattern) { - super(); - this.pattern = pattern; - } - - private RegexPrompt() {} - - @Override - protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { - return pattern.matcher(input).matches(); - } -} diff --git a/api/src/main/java/org/bukkit/conversations/StringPrompt.java b/api/src/main/java/org/bukkit/conversations/StringPrompt.java deleted file mode 100644 index f9b86d6d5..000000000 --- a/api/src/main/java/org/bukkit/conversations/StringPrompt.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.conversations; - -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - @Override - public boolean blocksForInput(@NotNull ConversationContext context) { - return true; - } -} diff --git a/api/src/main/java/org/bukkit/conversations/ValidatingPrompt.java b/api/src/main/java/org/bukkit/conversations/ValidatingPrompt.java deleted file mode 100644 index c57b6cb47..000000000 --- a/api/src/main/java/org/bukkit/conversations/ValidatingPrompt.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.bukkit.conversations; - -import org.bukkit.ChatColor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - @Override - @Nullable - public Prompt acceptInput(@NotNull ConversationContext context, @Nullable 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. - */ - @Override - public boolean blocksForInput(@NotNull 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(@NotNull ConversationContext context, @NotNull 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. - */ - @Nullable - protected abstract Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull 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. - */ - @Nullable - protected String getFailedValidationText(@NotNull ConversationContext context, @NotNull String invalidInput) { - return null; - } -} diff --git a/api/src/main/java/org/bukkit/enchantments/Enchantment.java b/api/src/main/java/org/bukkit/enchantments/Enchantment.java deleted file mode 100644 index d1885f178..000000000 --- a/api/src/main/java/org/bukkit/enchantments/Enchantment.java +++ /dev/null @@ -1,387 +0,0 @@ -package org.bukkit.enchantments; - -import java.util.HashMap; -import java.util.Map; -import org.bukkit.Keyed; -import org.bukkit.NamespacedKey; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * The various type of enchantments that may be added to armour or weapons - */ -public abstract class Enchantment implements Keyed { - /** - * Provides protection against environmental damage - */ - public static final Enchantment PROTECTION_ENVIRONMENTAL = new EnchantmentWrapper("protection"); - - /** - * Provides protection against fire damage - */ - public static final Enchantment PROTECTION_FIRE = new EnchantmentWrapper("fire_protection"); - - /** - * Provides protection against fall damage - */ - public static final Enchantment PROTECTION_FALL = new EnchantmentWrapper("feather_falling"); - - /** - * Provides protection against explosive damage - */ - public static final Enchantment PROTECTION_EXPLOSIONS = new EnchantmentWrapper("blast_protection"); - - /** - * Provides protection against projectile damage - */ - public static final Enchantment PROTECTION_PROJECTILE = new EnchantmentWrapper("projectile_protection"); - - /** - * Decreases the rate of air loss whilst underwater - */ - public static final Enchantment OXYGEN = new EnchantmentWrapper("respiration"); - - /** - * Increases the speed at which a player may mine underwater - */ - public static final Enchantment WATER_WORKER = new EnchantmentWrapper("aqua_affinity"); - - /** - * Damages the attacker - */ - public static final Enchantment THORNS = new EnchantmentWrapper("thorns"); - - /** - * Increases walking speed while in water - */ - public static final Enchantment DEPTH_STRIDER = new EnchantmentWrapper("depth_strider"); - - /** - * Freezes any still water adjacent to ice / frost which player is walking on - */ - public static final Enchantment FROST_WALKER = new EnchantmentWrapper("frost_walker"); - - /** - * Item cannot be removed - */ - public static final Enchantment BINDING_CURSE = new EnchantmentWrapper("binding_curse"); - - /** - * Increases damage against all targets - */ - public static final Enchantment DAMAGE_ALL = new EnchantmentWrapper("sharpness"); - - /** - * Increases damage against undead targets - */ - public static final Enchantment DAMAGE_UNDEAD = new EnchantmentWrapper("smite"); - - /** - * Increases damage against arthropod targets - */ - public static final Enchantment DAMAGE_ARTHROPODS = new EnchantmentWrapper("bane_of_arthropods"); - - /** - * All damage to other targets will knock them back when hit - */ - public static final Enchantment KNOCKBACK = new EnchantmentWrapper("knockback"); - - /** - * When attacking a target, has a chance to set them on fire - */ - public static final Enchantment FIRE_ASPECT = new EnchantmentWrapper("fire_aspect"); - - /** - * Provides a chance of gaining extra loot when killing monsters - */ - public static final Enchantment LOOT_BONUS_MOBS = new EnchantmentWrapper("looting"); - - /** - * Increases damage against targets when using a sweep attack - */ - public static final Enchantment SWEEPING_EDGE = new EnchantmentWrapper("sweeping"); - - /** - * Increases the rate at which you mine/dig - */ - public static final Enchantment DIG_SPEED = new EnchantmentWrapper("efficiency"); - - /** - * Allows blocks to drop themselves instead of fragments (for example, - * stone instead of cobblestone) - */ - public static final Enchantment SILK_TOUCH = new EnchantmentWrapper("silk_touch"); - - /** - * Decreases the rate at which a tool looses durability - */ - public static final Enchantment DURABILITY = new EnchantmentWrapper("unbreaking"); - - /** - * Provides a chance of gaining extra loot when destroying blocks - */ - public static final Enchantment LOOT_BONUS_BLOCKS = new EnchantmentWrapper("fortune"); - - /** - * Provides extra damage when shooting arrows from bows - */ - public static final Enchantment ARROW_DAMAGE = new EnchantmentWrapper("power"); - - /** - * Provides a knockback when an entity is hit by an arrow from a bow - */ - public static final Enchantment ARROW_KNOCKBACK = new EnchantmentWrapper("punch"); - - /** - * Sets entities on fire when hit by arrows shot from a bow - */ - public static final Enchantment ARROW_FIRE = new EnchantmentWrapper("flame"); - - /** - * Provides infinite arrows when shooting a bow - */ - public static final Enchantment ARROW_INFINITE = new EnchantmentWrapper("infinity"); - - /** - * Decreases odds of catching worthless junk - */ - public static final Enchantment LUCK = new EnchantmentWrapper("luck_of_the_sea"); - - /** - * Increases rate of fish biting your hook - */ - public static final Enchantment LURE = new EnchantmentWrapper("lure"); - - /** - * Causes a thrown trident to return to the player who threw it - */ - public static final Enchantment LOYALTY = new EnchantmentWrapper("loyalty"); - - /** - * Deals more damage to mobs that live in the ocean - */ - public static final Enchantment IMPALING = new EnchantmentWrapper("impaling"); - - /** - * When it is rainy, launches the player in the direction their trident is thrown - */ - public static final Enchantment RIPTIDE = new EnchantmentWrapper("riptide"); - - /** - * Strikes lightning when a mob is hit with a trident if conditions are - * stormy - */ - public static final Enchantment CHANNELING = new EnchantmentWrapper("channeling"); - - /** - * Shoot multiple arrows from crossbows - */ - public static final Enchantment MULTISHOT = new EnchantmentWrapper("multishot"); - - /** - * Charges crossbows quickly - */ - public static final Enchantment QUICK_CHARGE = new EnchantmentWrapper("quick_charge"); - - /** - * Crossbow projectiles pierce entities - */ - public static final Enchantment PIERCING = new EnchantmentWrapper("piercing"); - - /** - * Allows mending the item using experience orbs - */ - public static final Enchantment MENDING = new EnchantmentWrapper("mending"); - - /** - * Item disappears instead of dropping - */ - public static final Enchantment VANISHING_CURSE = new EnchantmentWrapper("vanishing_curse"); - - private static final Map byKey = new HashMap(); - private static final Map byName = new HashMap(); - private static boolean acceptingNew = true; - private final NamespacedKey key; - - public Enchantment(@NotNull NamespacedKey key) { - this.key = key; - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - - /** - * Gets the unique name of this enchantment - * - * @return Unique name - * @deprecated enchantments are badly named, use {@link #getKey()}. - */ - @NotNull - @Deprecated - 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 - */ - @NotNull - public abstract EnchantmentTarget getItemTarget(); - - /** - * Checks if this enchantment is a treasure enchantment. - *
- * Treasure enchantments can only be received via looting, trading, or - * fishing. - * - * @return true if the enchantment is a treasure enchantment - */ - public abstract boolean isTreasure(); - - /** - * Checks if this enchantment is a cursed enchantment - *
- * Cursed enchantments are found the same way treasure enchantments are - * - * @return true if the enchantment is cursed - * @deprecated cursed enchantments are no longer special. Will return true - * only for {@link Enchantment#BINDING_CURSE} and - * {@link Enchantment#VANISHING_CURSE}. - */ - @Deprecated - public abstract boolean isCursed(); - - /** - * 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(@NotNull 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(@NotNull 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.key.equals(other.key)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - return key.hashCode(); - } - - @Override - public String toString() { - return "Enchantment[" + key + ", " + 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(@NotNull Enchantment enchantment) { - if (byKey.containsKey(enchantment.key) || 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)"); - } - - byKey.put(enchantment.key, 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; - } - - /** - * Gets the Enchantment at the specified key - * - * @param key key to fetch - * @return Resulting Enchantment, or null if not found - */ - @Contract("null -> null") - @Nullable - public static Enchantment getByKey(@Nullable NamespacedKey key) { - return byKey.get(key); - } - - /** - * Gets the Enchantment at the specified name - * - * @param name Name to fetch - * @return Resulting Enchantment, or null if not found - * @deprecated enchantments are badly named, use {@link #getByKey(org.bukkit.NamespacedKey)}. - */ - @Deprecated - @Contract("null -> null") - @Nullable - public static Enchantment getByName(@Nullable String name) { - return byName.get(name); - } - - /** - * Gets an array of all the registered {@link Enchantment}s - * - * @return Array of enchantments - */ - @NotNull - public static Enchantment[] values() { - return byName.values().toArray(new Enchantment[byName.size()]); - } -} diff --git a/api/src/main/java/org/bukkit/enchantments/EnchantmentOffer.java b/api/src/main/java/org/bukkit/enchantments/EnchantmentOffer.java deleted file mode 100644 index 76761b4b4..000000000 --- a/api/src/main/java/org/bukkit/enchantments/EnchantmentOffer.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.bukkit.enchantments; - -import org.apache.commons.lang.Validate; -import org.jetbrains.annotations.NotNull; - -/** - * A class for the available enchantment offers in the enchantment table. - */ -public class EnchantmentOffer { - - private Enchantment enchantment; - private int enchantmentLevel; - private int cost; - - public EnchantmentOffer(@NotNull Enchantment enchantment, int enchantmentLevel, int cost) { - this.enchantment = enchantment; - this.enchantmentLevel = enchantmentLevel; - this.cost = cost; - } - - /** - * Get the type of the enchantment. - * - * @return type of enchantment - */ - @NotNull - public Enchantment getEnchantment() { - return enchantment; - } - - /** - * Sets the type of the enchantment. - * - * @param enchantment type of the enchantment - */ - public void setEnchantment(@NotNull Enchantment enchantment) { - Validate.notNull(enchantment, "The enchantment may not be null!"); - - this.enchantment = enchantment; - } - - /** - * Gets the level of the enchantment. - * - * @return level of the enchantment - */ - public int getEnchantmentLevel() { - return enchantmentLevel; - } - - /** - * Sets the level of the enchantment. - * - * @param enchantmentLevel level of the enchantment - */ - public void setEnchantmentLevel(int enchantmentLevel) { - Validate.isTrue(enchantmentLevel > 0, "The enchantment level must be greater than 0!"); - - this.enchantmentLevel = enchantmentLevel; - } - - /** - * Gets the cost (minimum level) which is displayed as a number on the right - * hand side of the enchantment offer. - * - * @return cost for this enchantment - */ - public int getCost() { - return cost; - } - - /** - * Sets the cost (minimum level) which is displayed as a number on the right - * hand side of the enchantment offer. - * - * @param cost cost for this enchantment - */ - public void setCost(int cost) { - Validate.isTrue(cost > 0, "The cost must be greater than 0!"); - - this.cost = cost; - } -} diff --git a/api/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java b/api/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java deleted file mode 100644 index 8ff0901cf..000000000 --- a/api/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java +++ /dev/null @@ -1,223 +0,0 @@ -package org.bukkit.enchantments; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Material item) { - return true; - } - }, - - /** - * Allows the Enchantment to be placed on armor - */ - ARMOR { - @Override - public boolean includes(@NotNull 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(@NotNull 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.GOLDEN_BOOTS); - } - }, - - /** - * Allows the Enchantment to be placed on leg slot armor - */ - ARMOR_LEGS { - @Override - public boolean includes(@NotNull 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.GOLDEN_LEGGINGS); - } - }, - - /** - * Allows the Enchantment to be placed on torso slot armor - */ - ARMOR_TORSO { - @Override - public boolean includes(@NotNull 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.GOLDEN_CHESTPLATE); - } - }, - - /** - * Allows the Enchantment to be placed on head slot armor - */ - ARMOR_HEAD { - @Override - public boolean includes(@NotNull 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.GOLDEN_HELMET); - } - }, - - /** - * Allows the Enchantment to be placed on weapons (swords) - */ - WEAPON { - @Override - public boolean includes(@NotNull Material item) { - return item.equals(Material.WOODEN_SWORD) - || item.equals(Material.STONE_SWORD) - || item.equals(Material.IRON_SWORD) - || item.equals(Material.DIAMOND_SWORD) - || item.equals(Material.GOLDEN_SWORD); - } - }, - - /** - * Allows the Enchantment to be placed on tools (spades, pickaxe, hoes, - * axes) - */ - TOOL { - @Override - public boolean includes(@NotNull Material item) { - return item.equals(Material.WOODEN_SHOVEL) - || item.equals(Material.STONE_SHOVEL) - || item.equals(Material.IRON_SHOVEL) - || item.equals(Material.DIAMOND_SHOVEL) - || item.equals(Material.GOLDEN_SHOVEL) - || item.equals(Material.WOODEN_PICKAXE) - || item.equals(Material.STONE_PICKAXE) - || item.equals(Material.IRON_PICKAXE) - || item.equals(Material.DIAMOND_PICKAXE) - || item.equals(Material.GOLDEN_PICKAXE) - || item.equals(Material.WOODEN_HOE) - || item.equals(Material.STONE_HOE) - || item.equals(Material.IRON_HOE) - || item.equals(Material.DIAMOND_HOE) - || item.equals(Material.GOLDEN_HOE) - || item.equals(Material.WOODEN_AXE) - || item.equals(Material.STONE_AXE) - || item.equals(Material.IRON_AXE) - || item.equals(Material.DIAMOND_AXE) - || item.equals(Material.GOLDEN_AXE) - || item.equals(Material.SHEARS) - || item.equals(Material.FLINT_AND_STEEL); - } - }, - - /** - * Allows the Enchantment to be placed on bows. - */ - BOW { - @Override - public boolean includes(@NotNull Material item) { - return item.equals(Material.BOW); - } - }, - - /** - * Allows the Enchantment to be placed on fishing rods. - */ - FISHING_ROD { - @Override - public boolean includes(@NotNull Material item) { - return item.equals(Material.FISHING_ROD); - } - }, - - /** - * Allows the enchantment to be placed on items with durability. - */ - BREAKABLE { - @Override - public boolean includes(@NotNull Material item) { - return item.getMaxDurability() > 0 && item.getMaxStackSize() == 1; - } - }, - - /** - * Allows the enchantment to be placed on wearable items. - */ - WEARABLE { - @Override - public boolean includes(@NotNull Material item) { - return ARMOR.includes(item) - || item.equals(Material.ELYTRA) - || item.equals(Material.PUMPKIN) - || item.equals(Material.CARVED_PUMPKIN) - || item.equals(Material.JACK_O_LANTERN) - || item.equals(Material.SKELETON_SKULL) - || item.equals(Material.WITHER_SKELETON_SKULL) - || item.equals(Material.ZOMBIE_HEAD) - || item.equals(Material.PLAYER_HEAD) - || item.equals(Material.CREEPER_HEAD) - || item.equals(Material.DRAGON_HEAD); - } - }, - - /** - * Allow the Enchantment to be placed on tridents. - */ - TRIDENT { - @Override - public boolean includes(@NotNull Material item) { - return item.equals(Material.TRIDENT); - } - }, - - /** - * Allow the Enchantment to be placed on crossbows. - */ - CROSSBOW { - @Override - public boolean includes(@NotNull Material item) { - return item.equals(Material.CROSSBOW); - } - }; - - /** - * 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(@NotNull 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(@NotNull ItemStack item) { - return includes(item.getType()); - } -} diff --git a/api/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java b/api/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java deleted file mode 100644 index 9566e4306..000000000 --- a/api/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.bukkit.enchantments; - -import org.bukkit.NamespacedKey; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * A simple wrapper for ease of selecting {@link Enchantment}s - */ -public class EnchantmentWrapper extends Enchantment { - public EnchantmentWrapper(@NotNull String name) { - super(NamespacedKey.minecraft(name)); - } - - /** - * Gets the enchantment bound to this wrapper - * - * @return Enchantment - */ - @NotNull - public Enchantment getEnchantment() { - return Enchantment.getByKey(getKey()); - } - - @Override - public int getMaxLevel() { - return getEnchantment().getMaxLevel(); - } - - @Override - public int getStartLevel() { - return getEnchantment().getStartLevel(); - } - - @NotNull - @Override - public EnchantmentTarget getItemTarget() { - return getEnchantment().getItemTarget(); - } - - @Override - public boolean canEnchantItem(@NotNull ItemStack item) { - return getEnchantment().canEnchantItem(item); - } - - @NotNull - @Override - public String getName() { - return getEnchantment().getName(); - } - - @Override - public boolean isTreasure() { - return getEnchantment().isTreasure(); - } - - @Override - public boolean isCursed() { - return getEnchantment().isCursed(); - } - - @Override - public boolean conflictsWith(@NotNull Enchantment other) { - return getEnchantment().conflictsWith(other); - } -} diff --git a/api/src/main/java/org/bukkit/entity/AbstractArrow.java b/api/src/main/java/org/bukkit/entity/AbstractArrow.java deleted file mode 100644 index b2bf62a50..000000000 --- a/api/src/main/java/org/bukkit/entity/AbstractArrow.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents an arrow. - */ -public interface AbstractArrow 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 - */ - public int getKnockbackStrength(); - - /** - * Sets the knockback strength for an arrow. - * - * @param knockbackStrength the knockback strength value - */ - public void setKnockbackStrength(int knockbackStrength); - - /** - * Gets the base amount of damage this arrow will do. - * - * Defaults to 2.0 for a normal arrow with - * 0.5 * (1 + power level) added for arrows fired from - * enchanted bows. - * - * @return base damage amount - */ - public double getDamage(); - - /** - * Sets the base amount of damage this arrow will do. - * - * @param damage new damage amount - */ - public void setDamage(double damage); - - /** - * Gets the number of times this arrow can pierce through an entity. - * - * @return pierce level - */ - public int getPierceLevel(); - - /** - * Sets the number of times this arrow can pierce through an entity. - * - * Must be between 0 and 127 times. - * - * @param pierceLevel new pierce level - */ - public void setPierceLevel(int pierceLevel); - - /** - * 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 - */ - public boolean isCritical(); - - /** - * Sets whether or not this arrow should be critical. - * - * @param critical whether or not it should be critical - */ - public void setCritical(boolean critical); - - /** - * Gets whether this arrow is in a block or not. - *

- * Arrows in a block are motionless and may be picked up by players. - * - * @return true if in a block - */ - public boolean isInBlock(); - - /** - * Gets the block to which this arrow is attached. - * - * @return the attached block or null if not attached - */ - @Nullable - public Block getAttachedBlock(); - - /** - * Gets the current pickup status of this arrow. - * - * @return the pickup status of this arrow. - */ - @NotNull - public PickupStatus getPickupStatus(); - - /** - * Sets the current pickup status of this arrow. - * - * @param status new pickup status of this arrow. - */ - public void setPickupStatus(@NotNull PickupStatus status); - - /** - * Represents the pickup status of this arrow. - */ - public enum PickupStatus { - /** - * The arrow cannot be picked up. - */ - DISALLOWED, - /** - * The arrow can be picked up. - */ - ALLOWED, - /** - * The arrow can only be picked up by players in creative mode. - */ - CREATIVE_ONLY - } - - // Paper start - /** - * Gets the {@link PickupRule} for this arrow. - * - *

This is generally {@link PickupRule#ALLOWED} only if the arrow was - * not fired from a bow with the infinity enchantment.

- * - * @return The pickup rule - * @deprecated Use {@link Arrow#getPickupStatus()} as an upstream compatible replacement for this function - */ - @Deprecated - default PickupRule getPickupRule() { - return PickupRule.valueOf(this.getPickupStatus().name()); - } - - /** - * Set the rule for which players can pickup this arrow as an item. - * - * @param rule The pickup rule - * @deprecated Use {@link Arrow#setPickupStatus(PickupStatus)} with {@link PickupStatus} as an upstream compatible replacement for this function - */ - @Deprecated - default void setPickupRule(PickupRule rule) { - this.setPickupStatus(PickupStatus.valueOf(rule.name())); - } - - @Deprecated - enum PickupRule { - DISALLOWED, - ALLOWED, - CREATIVE_ONLY; - } - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/AbstractHorse.java b/api/src/main/java/org/bukkit/entity/AbstractHorse.java deleted file mode 100644 index 87f3c1f22..000000000 --- a/api/src/main/java/org/bukkit/entity/AbstractHorse.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.inventory.AbstractHorseInventory; -import org.bukkit.inventory.InventoryHolder; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Horse-like creature. - */ -public interface AbstractHorse extends Animals, Vehicle, InventoryHolder, Tameable { - - /** - * 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 Horse.Variant} representing the horse's variant - * @deprecated different variants are different classes - */ - @Deprecated - @NotNull - public Horse.Variant getVariant(); - - /** - * @param variant variant - * @deprecated you are required to spawn a different entity - */ - @Deprecated - @Contract("_ -> fail") - public void setVariant(Horse.Variant variant); - - /** - * 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 - */ - public 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 - */ - public 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 - */ - public 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 - */ - public 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 - */ - public 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 - */ - public void setJumpStrength(double strength); - - @NotNull - @Override - public AbstractHorseInventory getInventory(); -} diff --git a/api/src/main/java/org/bukkit/entity/AbstractVillager.java b/api/src/main/java/org/bukkit/entity/AbstractVillager.java deleted file mode 100644 index 8fde1f4bb..000000000 --- a/api/src/main/java/org/bukkit/entity/AbstractVillager.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.Merchant; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a villager NPC - */ -public interface AbstractVillager extends Ageable, NPC, InventoryHolder, Merchant { - - /** - * Gets this villager's inventory. - *
- * Note that this inventory is not the Merchant inventory, rather, it is the - * items that a villager might have collected (from harvesting crops, etc.) - * - * {@inheritDoc} - */ - @NotNull - @Override - Inventory getInventory(); -} diff --git a/api/src/main/java/org/bukkit/entity/Ageable.java b/api/src/main/java/org/bukkit/entity/Ageable.java deleted file mode 100644 index 3756a9730..000000000 --- a/api/src/main/java/org/bukkit/entity/Ageable.java +++ /dev/null @@ -1,67 +0,0 @@ -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 - */ - public int getAge(); - - /** - * Sets the age of this animal. - * - * @param age New age - */ - public 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 - */ - public void setAgeLock(boolean lock); - - /** - * Gets the current agelock. - * - * @return the current agelock - */ - public boolean getAgeLock(); - - /** - * Sets the age of the animal to a baby - */ - public void setBaby(); - - /** - * Sets the age of the animal to an adult - */ - public void setAdult(); - - /** - * Returns true if the animal is an adult. - * - * @return return true if the animal is an adult - */ - public boolean isAdult(); - - /** - * Return the ability to breed of the animal. - * - * @return the ability to breed of the animal - */ - public 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 - */ - public void setBreed(boolean breed); -} diff --git a/api/src/main/java/org/bukkit/entity/Ambient.java b/api/src/main/java/org/bukkit/entity/Ambient.java deleted file mode 100644 index 613830a74..000000000 --- a/api/src/main/java/org/bukkit/entity/Ambient.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents an ambient mob - */ -public interface Ambient extends Mob {} diff --git a/api/src/main/java/org/bukkit/entity/AnimalTamer.java b/api/src/main/java/org/bukkit/entity/AnimalTamer.java deleted file mode 100644 index 2e17b2d4f..000000000 --- a/api/src/main/java/org/bukkit/entity/AnimalTamer.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.entity; - -import java.util.UUID; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -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 - */ - @Nullable - public String getName(); - - /** - * This is the UUID of the specified AnimalTamer. - * - * @return The UUID to reference on tamed animals - */ - @NotNull - public UUID getUniqueId(); -} diff --git a/api/src/main/java/org/bukkit/entity/Animals.java b/api/src/main/java/org/bukkit/entity/Animals.java deleted file mode 100644 index 1047481e4..000000000 --- a/api/src/main/java/org/bukkit/entity/Animals.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.entity; - -import java.util.UUID; -import org.jetbrains.annotations.Nullable; - -/** - * Represents an Animal. - */ -public interface Animals extends Ageable { - - /** - * Get the UUID of the entity that caused this entity to enter the - * {@link #canBreed()} state. - * - * @return uuid if set, or null - */ - @Nullable - UUID getBreedCause(); - - /** - * Set the UUID of the entity that caused this entity to enter the - * {@link #canBreed()} state. - * - * @param uuid new uuid, or null - */ - void setBreedCause(@Nullable UUID uuid); - - /** - * Get whether or not this entity is in love mode and will produce - * offspring with another entity in love mode. Will return true if - * and only if {@link #getLoveModeTicks()} is greater than 0. - * - * @return true if in love mode, false otherwise - */ - boolean isLoveMode(); - - /** - * Get the amount of ticks remaining for this entity in love mode. - * If the entity is not in love mode, 0 will be returned. - * - * @return the remaining love mode ticks - */ - int getLoveModeTicks(); - - /** - * Set the amount of ticks for which this entity should be in love mode. - * Setting the love mode ticks to 600 is the equivalent of a player - * feeding the entity their breeding item of choice. - * - * @param ticks the love mode ticks. Must be positive - */ - void setLoveModeTicks(int ticks); -} diff --git a/api/src/main/java/org/bukkit/entity/AreaEffectCloud.java b/api/src/main/java/org/bukkit/entity/AreaEffectCloud.java deleted file mode 100644 index bca9d3659..000000000 --- a/api/src/main/java/org/bukkit/entity/AreaEffectCloud.java +++ /dev/null @@ -1,243 +0,0 @@ -package org.bukkit.entity; - -import java.util.List; -import org.bukkit.Color; -import org.bukkit.Particle; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.projectiles.ProjectileSource; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents an area effect cloud which will imbue a potion effect onto - * entities which enter it. - */ -public interface AreaEffectCloud extends Entity { - - /** - * Gets the duration which this cloud will exist for (in ticks). - * - * @return cloud duration - */ - int getDuration(); - - /** - * Sets the duration which this cloud will exist for (in ticks). - * - * @param duration cloud duration - */ - void setDuration(int duration); - - /** - * Gets the time which an entity has to be exposed to the cloud before the - * effect is applied. - * - * @return wait time - */ - int getWaitTime(); - - /** - * Sets the time which an entity has to be exposed to the cloud before the - * effect is applied. - * - * @param waitTime wait time - */ - void setWaitTime(int waitTime); - - /** - * Gets the time that an entity will be immune from subsequent exposure. - * - * @return reapplication delay - */ - int getReapplicationDelay(); - - /** - * Sets the time that an entity will be immune from subsequent exposure. - * - * @param delay reapplication delay - */ - void setReapplicationDelay(int delay); - - /** - * Gets the amount that the duration of this cloud will decrease by when it - * applies an effect to an entity. - * - * @return duration on use delta - */ - int getDurationOnUse(); - - /** - * Sets the amount that the duration of this cloud will decrease by when it - * applies an effect to an entity. - * - * @param duration duration on use delta - */ - void setDurationOnUse(int duration); - - /** - * Gets the initial radius of the cloud. - * - * @return radius - */ - float getRadius(); - - /** - * Sets the initial radius of the cloud. - * - * @param radius radius - */ - void setRadius(float radius); - - /** - * Gets the amount that the radius of this cloud will decrease by when it - * applies an effect to an entity. - * - * @return radius on use delta - */ - float getRadiusOnUse(); - - /** - * Sets the amount that the radius of this cloud will decrease by when it - * applies an effect to an entity. - * - * @param radius radius on use delta - */ - void setRadiusOnUse(float radius); - - /** - * Gets the amount that the radius of this cloud will decrease by each tick. - * - * @return radius per tick delta - */ - float getRadiusPerTick(); - - /** - * Gets the amount that the radius of this cloud will decrease by each tick. - * - * @param radius per tick delta - */ - void setRadiusPerTick(float radius); - - /** - * Gets the particle which this cloud will be composed of - * - * @return particle the set particle type - */ - @NotNull - Particle getParticle(); - - /** - * Sets the particle which this cloud will be composed of - * - * @param particle the new particle type - */ - void setParticle(@NotNull Particle particle); - - /** - * Sets the particle which this cloud will be composed of - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the new particle type - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param the particle data type // Paper - */ - void setParticle(@NotNull Particle particle, @Nullable T data); - - /** - * Sets the underlying potion data - * - * @param data PotionData to set the base potion state to - */ - void setBasePotionData(@NotNull PotionData data); - - /** - * Returns the potion data about the base potion - * - * @return a PotionData object - */ - @NotNull - PotionData getBasePotionData(); - - /** - * 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 cloud. - *

- * Plugins should check that hasCustomEffects() returns true before calling - * this method. - * - * @return the immutable list of custom potion effects - */ - @NotNull - List getCustomEffects(); - - /** - * Adds a custom potion effect to this cloud. - * - * @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 effect was added as a result of this call - */ - boolean addCustomEffect(@NotNull PotionEffect effect, boolean overwrite); - - /** - * Removes a custom potion effect from this cloud. - * - * @param type the potion effect type to remove - * @return true if the an effect was removed as a result of this call - */ - boolean removeCustomEffect(@NotNull PotionEffectType type); - - /** - * Checks for a specific custom potion effect type on this cloud. - * - * @param type the potion effect type to check for - * @return true if the potion has this effect - */ - boolean hasCustomEffect(@Nullable PotionEffectType type); - - /** - * Removes all custom potion effects from this cloud. - */ - void clearCustomEffects(); - - /** - * Gets the color of this cloud. Will be applied as a tint to its particles. - * - * @return cloud color - */ - @NotNull - Color getColor(); - - /** - * Sets the color of this cloud. Will be applied as a tint to its particles. - * - * @param color cloud color - */ - void setColor(@NotNull Color color); - - /** - * Retrieve the original source of this cloud. - * - * @return the {@link ProjectileSource} that threw the LingeringPotion - */ - @Nullable - public ProjectileSource getSource(); - - /** - * Set the original source of this cloud. - * - * @param source the {@link ProjectileSource} that threw the LingeringPotion - */ - public void setSource(@Nullable ProjectileSource source); -} diff --git a/api/src/main/java/org/bukkit/entity/ArmorStand.java b/api/src/main/java/org/bukkit/entity/ArmorStand.java deleted file mode 100644 index e7f71e65e..000000000 --- a/api/src/main/java/org/bukkit/entity/ArmorStand.java +++ /dev/null @@ -1,385 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.EulerAngle; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface ArmorStand extends LivingEntity { - - /** - * Returns the item the armor stand is - * currently holding - * - * @return the held item - // Paper start - Deprecate in favor of setItemInMainHand - * @deprecated use {@link ArmorStand#getItem(EquipmentSlot)} instead - * @see ArmorStand#getItem(EquipmentSlot) - // Paper end - */ - @NotNull - @Deprecated // Paper - ItemStack getItemInHand(); - - /** - * Sets the item the armor stand is currently - * holding - * - * @param item the item to hold - // Paper start - Deprecate in favor of setItemInMainHand - * @deprecated use {@link ArmorStand#setItem(EquipmentSlot, ItemStack)} instead - * @see ArmorStand#setItem(EquipmentSlot, ItemStack) - // Paper end - */ - @Deprecated // Paper - void setItemInHand(@Nullable ItemStack item); - - /** - * Returns the item currently being worn - * by the armor stand on its feet - * - * @return the worn item - */ - @NotNull - ItemStack getBoots(); - - /** - * Sets the item currently being worn - * by the armor stand on its feet - * - * @param item the item to wear - */ - void setBoots(@Nullable ItemStack item); - - /** - * Returns the item currently being worn - * by the armor stand on its legs - * - * @return the worn item - */ - @NotNull - ItemStack getLeggings(); - - /** - * Sets the item currently being worn - * by the armor stand on its legs - * - * @param item the item to wear - */ - void setLeggings(@Nullable ItemStack item); - - /** - * Returns the item currently being worn - * by the armor stand on its chest - * - * @return the worn item - */ - @NotNull - ItemStack getChestplate(); - - /** - * Sets the item currently being worn - * by the armor stand on its chest - * - * @param item the item to wear - */ - void setChestplate(@Nullable ItemStack item); - - /** - * Returns the item currently being worn - * by the armor stand on its head - * - * @return the worn item - */ - @NotNull - ItemStack getHelmet(); - - /** - * Sets the item currently being worn - * by the armor stand on its head - * - * @param item the item to wear - */ - void setHelmet(@Nullable ItemStack item); - - /** - * Returns the armor stand's body's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @return the current pose - */ - @NotNull - EulerAngle getBodyPose(); - - /** - * Sets the armor stand's body's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @param pose the current pose - */ - void setBodyPose(@NotNull EulerAngle pose); - - /** - * Returns the armor stand's left arm's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @return the current pose - */ - @NotNull - EulerAngle getLeftArmPose(); - - /** - * Sets the armor stand's left arm's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @param pose the current pose - */ - void setLeftArmPose(@NotNull EulerAngle pose); - - /** - * Returns the armor stand's right arm's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @return the current pose - */ - @NotNull - EulerAngle getRightArmPose(); - - /** - * Sets the armor stand's right arm's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @param pose the current pose - */ - void setRightArmPose(@NotNull EulerAngle pose); - - /** - * Returns the armor stand's left leg's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @return the current pose - */ - @NotNull - EulerAngle getLeftLegPose(); - - /** - * Sets the armor stand's left leg's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @param pose the current pose - */ - void setLeftLegPose(@NotNull EulerAngle pose); - - /** - * Returns the armor stand's right leg's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @return the current pose - */ - @NotNull - EulerAngle getRightLegPose(); - - /** - * Sets the armor stand's right leg's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @param pose the current pose - */ - void setRightLegPose(@NotNull EulerAngle pose); - - /** - * Returns the armor stand's head's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @return the current pose - */ - @NotNull - EulerAngle getHeadPose(); - - /** - * Sets the armor stand's head's - * current pose as a {@link org.bukkit.util.EulerAngle} - * - * @param pose the current pose - */ - void setHeadPose(@NotNull 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 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); - - // Paper start - /** - * Tests if this armor stand can move. - * - *

The default value is {@code true}.

- * - * @return {@code true} if this armour stand can move, {@code false} otherwise - */ - boolean canMove(); - - /** - * Sets if this armor stand can move. - * - * @param move {@code true} if this armour stand can move, {@code false} otherwise - */ - void setCanMove(boolean move); - - /** - * Tests if this armor stand can tick. - * - *

The default value is defined in {@code paper.yml}.

- * - * @return {@code true} if this armour stand can tick, {@code false} otherwise - */ - boolean canTick(); - - /** - * Sets if this armor stand can tick. - * - * @param tick {@code true} if this armour stand can tick, {@code false} otherwise - */ - void setCanTick(final boolean tick); - - /** - * Returns the item the armor stand has - * equip in the given equipment slot - * - * @param slot the equipment slot to get - * @return the ItemStack in the equipment slot - */ - @NotNull - ItemStack getItem(@NotNull final org.bukkit.inventory.EquipmentSlot slot); - - /** - * Sets the item the armor stand has - * equip in the given equipment slot - * - * @param slot the equipment slot to set - * @param item the item to hold - */ - void setItem(@NotNull final org.bukkit.inventory.EquipmentSlot slot, @Nullable final ItemStack item); - - /** - * Get the list of disabled slots - * - * @return list of disabled slots - */ - @NotNull - java.util.Set getDisabledSlots(); - - /** - * Set the disabled slots - * - * This makes it so a player is unable to interact with the Armor Stand to place, remove, or replace an item in the given slot(s) - * Note: Once a slot is disabled, the only way to get an item back it to break the armor stand. - * - * @param slots var-arg array of slots to lock - */ - void setDisabledSlots(@NotNull org.bukkit.inventory.EquipmentSlot... slots); - - /** - * Disable specific slots, adding them - * to the currently disabled slots - * - * This makes it so a player is unable to interact with the Armor Stand to place, remove, or replace an item in the given slot(s) - * Note: Once a slot is disabled, the only way to get an item back it to break the armor stand. - * - * @param slots var-arg array of slots to lock - */ - void addDisabledSlots(@NotNull final org.bukkit.inventory.EquipmentSlot... slots); - - /** - * Remove the given slots from the disabled - * slots list, enabling them. - * - * This makes it so a player is able to interact with the Armor Stand to place, remove, or replace an item in the given slot(s) - * - * @param slots var-arg array of slots to unlock - */ - void removeDisabledSlots(@NotNull final org.bukkit.inventory.EquipmentSlot... slots); - - /** - * Check if a specific slot is disabled - * - * @param slot The slot to check - * @return {@code true} if the slot is disabled, else {@code false}. - */ - boolean isSlotDisabled(@NotNull org.bukkit.inventory.EquipmentSlot slot); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Arrow.java b/api/src/main/java/org/bukkit/entity/Arrow.java deleted file mode 100644 index ec8443b67..000000000 --- a/api/src/main/java/org/bukkit/entity/Arrow.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.bukkit.entity; - -import java.util.List; -import org.bukkit.Color; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface Arrow extends AbstractArrow { - - /** - * Sets the underlying potion data - * - * @param data PotionData to set the base potion state to - */ - void setBasePotionData(@NotNull PotionData data); - - /** - * Returns the potion data about the base potion - * - * @return a PotionData object - */ - @NotNull - PotionData getBasePotionData(); - - /** - * Gets the color of this arrow. - * - * @return arrow color - */ - @NotNull - Color getColor(); - - /** - * Sets the color of this arrow. Will be applied as a tint to its particles. - * - * @param color arrow color - */ - void setColor(@NotNull Color color); - - /** - * 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 arrow. - *

- * Plugins should check that hasCustomEffects() returns true before calling - * this method. - * - * @return the immutable list of custom potion effects - */ - @NotNull - List getCustomEffects(); - - /** - * Adds a custom potion effect to this arrow. - * - * @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 effect was added as a result of this call - */ - boolean addCustomEffect(@NotNull PotionEffect effect, boolean overwrite); - - /** - * Removes a custom potion effect from this arrow. - * - * @param type the potion effect type to remove - * @return true if the an effect was removed as a result of this call - * @throws IllegalArgumentException if this operation would leave the Arrow - * in a state with no Custom Effects and PotionType.UNCRAFTABLE - */ - boolean removeCustomEffect(@NotNull PotionEffectType type); - - /** - * Checks for a specific custom potion effect type on this arrow. - * - * @param type the potion effect type to check for - * @return true if the potion has this effect - */ - boolean hasCustomEffect(@Nullable PotionEffectType type); - - /** - * Removes all custom potion effects from this arrow. - * - * @throws IllegalArgumentException if this operation would leave the Arrow - * in a state with no Custom Effects and PotionType.UNCRAFTABLE - */ - void clearCustomEffects(); -} diff --git a/api/src/main/java/org/bukkit/entity/Bat.java b/api/src/main/java/org/bukkit/entity/Bat.java deleted file mode 100644 index bd73f22ef..000000000 --- a/api/src/main/java/org/bukkit/entity/Bat.java +++ /dev/null @@ -1,27 +0,0 @@ -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/api/src/main/java/org/bukkit/entity/Blaze.java b/api/src/main/java/org/bukkit/entity/Blaze.java deleted file mode 100644 index 7a5505b7f..000000000 --- a/api/src/main/java/org/bukkit/entity/Blaze.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Blaze monster - */ -public interface Blaze extends Monster { - -} diff --git a/api/src/main/java/org/bukkit/entity/Boat.java b/api/src/main/java/org/bukkit/entity/Boat.java deleted file mode 100644 index 24751b5c4..000000000 --- a/api/src/main/java/org/bukkit/entity/Boat.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.TreeSpecies; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a boat entity. - */ -public interface Boat extends Vehicle { - - /** - * Gets the wood type of the boat. - * - * @return the wood type - */ - @NotNull - TreeSpecies getWoodType(); - - /** - * Sets the wood type of the boat. - * - * @param species the new wood type - */ - void setWoodType(@NotNull TreeSpecies species); - - /** - * Gets the maximum speed of a boat. The speed is unrelated to the - * velocity. - * - * @return The max speed. - * @deprecated boats are complex and many of these methods do not work correctly across multiple versions. - */ - @Deprecated - public double getMaxSpeed(); - - /** - * Sets the maximum speed of a boat. Must be nonnegative. Default is 0.4D. - * - * @param speed The max speed. - * @deprecated boats are complex and many of these methods do not work correctly across multiple versions. - */ - @Deprecated - public void setMaxSpeed(double speed); - - /** - * Gets the deceleration rate (newSpeed = curSpeed * rate) of occupied - * boats. The default is 0.2. - * - * @return The rate of deceleration - * @deprecated boats are complex and many of these methods do not work correctly across multiple versions. - */ - @Deprecated - public 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 - * @deprecated boats are complex and many of these methods do not work correctly across multiple versions. - */ - @Deprecated - public 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 - * @deprecated boats are complex and many of these methods do not work correctly across multiple versions. - */ - @Deprecated - public 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 - * @deprecated boats are complex and many of these methods do not work correctly across multiple versions. - */ - @Deprecated - public void setUnoccupiedDeceleration(double rate); - - /** - * Get whether boats can work on land. - * - * @return whether boats can work on land - * @deprecated boats are complex and many of these methods do not work correctly across multiple versions. - */ - @Deprecated - public boolean getWorkOnLand(); - - /** - * Set whether boats can work on land. - * - * @param workOnLand whether boats can work on land - * @deprecated boats are complex and many of these methods do not work correctly across multiple versions. - */ - @Deprecated - public void setWorkOnLand(boolean workOnLand); -} diff --git a/api/src/main/java/org/bukkit/entity/Boss.java b/api/src/main/java/org/bukkit/entity/Boss.java deleted file mode 100644 index ba459279c..000000000 --- a/api/src/main/java/org/bukkit/entity/Boss.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.boss.BossBar; -import org.jetbrains.annotations.Nullable; - -/** - * Represents the Boss Entity. - */ -public interface Boss extends Entity { - - /** - * Returns the {@link BossBar} of the {@link Boss} - * - * @return the {@link BossBar} of the entity - */ - @Nullable - BossBar getBossBar(); -} diff --git a/api/src/main/java/org/bukkit/entity/Cat.java b/api/src/main/java/org/bukkit/entity/Cat.java deleted file mode 100644 index a29aefeaa..000000000 --- a/api/src/main/java/org/bukkit/entity/Cat.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.DyeColor; -import org.jetbrains.annotations.NotNull; - -/** - * Meow. - */ -public interface Cat extends Animals, Tameable, Sittable { - - /** - * Gets the current type of this cat. - * - * @return Type of the cat. - */ - @NotNull - public Type getCatType(); - - /** - * Sets the current type of this cat. - * - * @param type New type of this cat. - */ - public void setCatType(@NotNull Type type); - - /** - * Get the collar color of this cat - * - * @return the color of the collar - */ - @NotNull - public DyeColor getCollarColor(); - - /** - * Set the collar color of this cat - * - * @param color the color to apply - */ - public void setCollarColor(@NotNull DyeColor color); - - /** - * Represents the various different cat types there are. - */ - public enum Type { - TABBY, - BLACK, - RED, - SIAMESE, - BRITISH_SHORTHAIR, - CALICO, - PERSIAN, - RAGDOLL, - WHITE, - JELLIE, - ALL_BLACK; - } -} diff --git a/api/src/main/java/org/bukkit/entity/CaveSpider.java b/api/src/main/java/org/bukkit/entity/CaveSpider.java deleted file mode 100644 index 9c3764699..000000000 --- a/api/src/main/java/org/bukkit/entity/CaveSpider.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Spider. - */ -public interface CaveSpider extends Spider {} diff --git a/api/src/main/java/org/bukkit/entity/ChestedHorse.java b/api/src/main/java/org/bukkit/entity/ChestedHorse.java deleted file mode 100644 index 24780af64..000000000 --- a/api/src/main/java/org/bukkit/entity/ChestedHorse.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents Horse-like creatures which can carry an inventory. - */ -public interface ChestedHorse extends AbstractHorse { - - /** - * Gets whether the horse has a chest equipped. - * - * @return true if the horse has chest storage - */ - public 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 - */ - public void setCarryingChest(boolean chest); -} diff --git a/api/src/main/java/org/bukkit/entity/Chicken.java b/api/src/main/java/org/bukkit/entity/Chicken.java deleted file mode 100644 index cb3ec6ef6..000000000 --- a/api/src/main/java/org/bukkit/entity/Chicken.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Chicken. - */ -public interface Chicken extends Animals {} diff --git a/api/src/main/java/org/bukkit/entity/Cod.java b/api/src/main/java/org/bukkit/entity/Cod.java deleted file mode 100644 index 191ce6c0e..000000000 --- a/api/src/main/java/org/bukkit/entity/Cod.java +++ /dev/null @@ -1,7 +0,0 @@ - -package org.bukkit.entity; - -/** - * Represents a cod fish. - */ -public interface Cod extends Fish { } diff --git a/api/src/main/java/org/bukkit/entity/ComplexEntityPart.java b/api/src/main/java/org/bukkit/entity/ComplexEntityPart.java deleted file mode 100644 index 937f53499..000000000 --- a/api/src/main/java/org/bukkit/entity/ComplexEntityPart.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public ComplexLivingEntity getParent(); -} diff --git a/api/src/main/java/org/bukkit/entity/ComplexLivingEntity.java b/api/src/main/java/org/bukkit/entity/ComplexLivingEntity.java deleted file mode 100644 index 2151e3bac..000000000 --- a/api/src/main/java/org/bukkit/entity/ComplexLivingEntity.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.entity; - -import java.util.Set; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public Set getParts(); -} diff --git a/api/src/main/java/org/bukkit/entity/Cow.java b/api/src/main/java/org/bukkit/entity/Cow.java deleted file mode 100644 index cd4ed4de0..000000000 --- a/api/src/main/java/org/bukkit/entity/Cow.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Cow. - */ -public interface Cow extends Animals {} diff --git a/api/src/main/java/org/bukkit/entity/Creature.java b/api/src/main/java/org/bukkit/entity/Creature.java deleted file mode 100644 index 6c9c5e85e..000000000 --- a/api/src/main/java/org/bukkit/entity/Creature.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Creature. Creatures are non-intelligent monsters or animals - * which have very simple abilities. - */ -public interface Creature extends Mob {} diff --git a/api/src/main/java/org/bukkit/entity/Creeper.java b/api/src/main/java/org/bukkit/entity/Creeper.java deleted file mode 100644 index faaeb44a9..000000000 --- a/api/src/main/java/org/bukkit/entity/Creeper.java +++ /dev/null @@ -1,97 +0,0 @@ -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 - */ - public boolean isPowered(); - - /** - * Sets the Powered status of this Creeper - * - * @param value New Powered status - */ - public void setPowered(boolean value); - - /** - * Set the maximum fuse ticks for this Creeper, where the maximum ticks - * is the amount of time in which a creeper is allowed to be in the - * primed state before exploding. - * - * @param ticks the new maximum fuse ticks - */ - public void setMaxFuseTicks(int ticks); - - /** - * Get the maximum fuse ticks for this Creeper, where the maximum ticks - * is the amount of time in which a creeper is allowed to be in the - * primed state before exploding. - * - * @return the maximum fuse ticks - */ - public int getMaxFuseTicks(); - - /** - * Set the explosion radius in which this Creeper's explosion will affect. - * - * @param radius the new explosion radius - */ - public void setExplosionRadius(int radius); - - /** - * Get the explosion radius in which this Creeper's explosion will affect. - * - * @return the explosion radius - */ - public int getExplosionRadius(); - - /** - * Makes this Creeper explode instantly. - * - * The resulting explosion can be cancelled by an - * {@link org.bukkit.event.entity.ExplosionPrimeEvent} and obeys the mob - * griefing gamerule. - */ - public void explode(); - - /** - * Ignites this Creeper, beginning its fuse. - * - * The amount of time the Creeper takes to explode will depend on what - * {@link #setMaxFuseTicks} is set as. - * - * The resulting explosion can be cancelled by an - * {@link org.bukkit.event.entity.ExplosionPrimeEvent} and obeys the mob - * griefing gamerule. - */ - public void ignite(); - // Paper start - - /** - * Set whether creeper is ignited or not (armed to explode) - * - * @param ignited New ignited state - */ - public void setIgnited(boolean ignited); - - /** - * Check if creeper is ignited or not (armed to explode) - * - * @return Ignited state - */ - public boolean isIgnited(); - - /** - * Get the number of ticks this creeper has been ignited (armed to explode) - * - * @return Ticks creeper has been ignited - */ - public int getFuseTicks(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Damageable.java b/api/src/main/java/org/bukkit/entity/Damageable.java deleted file mode 100644 index fc4d3bcd9..000000000 --- a/api/src/main/java/org/bukkit/entity/Damageable.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.attribute.Attribute; -import org.jetbrains.annotations.Nullable; - -/** - * 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); - - /** - * 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, @Nullable 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(); - - /** - * 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); - - /** - * Gets the entity's absorption amount. - * - * @return absorption amount from 0 - */ - double getAbsorptionAmount(); - - /** - * Sets the entity's absorption amount. - * - * @param amount new absorption amount from 0 - * @throws IllegalArgumentException thrown if health is {@literal < 0} or - * non-finite. - */ - void setAbsorptionAmount(double amount); - - /** - * Gets the maximum health this entity has. - * - * @return Maximum health - * @deprecated use {@link Attribute#GENERIC_MAX_HEALTH}. - */ - @Deprecated - double 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 - * @deprecated use {@link Attribute#GENERIC_MAX_HEALTH}. - */ - @Deprecated - void setMaxHealth(double health); - - /** - * Resets the max health to the original amount. - * @deprecated use {@link Attribute#GENERIC_MAX_HEALTH}. - */ - @Deprecated - void resetMaxHealth(); -} diff --git a/api/src/main/java/org/bukkit/entity/Dolphin.java b/api/src/main/java/org/bukkit/entity/Dolphin.java deleted file mode 100644 index f00eaadcd..000000000 --- a/api/src/main/java/org/bukkit/entity/Dolphin.java +++ /dev/null @@ -1,3 +0,0 @@ -package org.bukkit.entity; - -public interface Dolphin extends WaterMob { } diff --git a/api/src/main/java/org/bukkit/entity/Donkey.java b/api/src/main/java/org/bukkit/entity/Donkey.java deleted file mode 100644 index b554e3309..000000000 --- a/api/src/main/java/org/bukkit/entity/Donkey.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Donkey - variant of {@link ChestedHorse}. - */ -public interface Donkey extends ChestedHorse { } diff --git a/api/src/main/java/org/bukkit/entity/DragonFireball.java b/api/src/main/java/org/bukkit/entity/DragonFireball.java deleted file mode 100644 index 6c475a372..000000000 --- a/api/src/main/java/org/bukkit/entity/DragonFireball.java +++ /dev/null @@ -1,3 +0,0 @@ -package org.bukkit.entity; - -public interface DragonFireball extends Fireball {} diff --git a/api/src/main/java/org/bukkit/entity/Drowned.java b/api/src/main/java/org/bukkit/entity/Drowned.java deleted file mode 100644 index 1dee177ae..000000000 --- a/api/src/main/java/org/bukkit/entity/Drowned.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Drowned zombie. - */ -public interface Drowned extends Zombie { } diff --git a/api/src/main/java/org/bukkit/entity/Egg.java b/api/src/main/java/org/bukkit/entity/Egg.java deleted file mode 100644 index 2dcc00b94..000000000 --- a/api/src/main/java/org/bukkit/entity/Egg.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a thrown egg. - */ -public interface Egg extends Projectile {} diff --git a/api/src/main/java/org/bukkit/entity/ElderGuardian.java b/api/src/main/java/org/bukkit/entity/ElderGuardian.java deleted file mode 100644 index 5ca1d4c9f..000000000 --- a/api/src/main/java/org/bukkit/entity/ElderGuardian.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents an ElderGuardian - variant of {@link Guardian}. - */ -public interface ElderGuardian extends Guardian { } diff --git a/api/src/main/java/org/bukkit/entity/EnderCrystal.java b/api/src/main/java/org/bukkit/entity/EnderCrystal.java deleted file mode 100644 index febc7b3f4..000000000 --- a/api/src/main/java/org/bukkit/entity/EnderCrystal.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.Location; -import org.jetbrains.annotations.Nullable; - -/** - * A crystal that heals nearby EnderDragons - */ -public interface EnderCrystal extends Entity { - - /** - * Return whether or not this end crystal is showing the - * bedrock slate underneath it. - * - * @return true if the bottom is being shown - */ - boolean isShowingBottom(); - - /** - * Sets whether or not this end crystal is showing the - * bedrock slate underneath it. - * - * @param showing whether the bedrock slate should be shown - */ - void setShowingBottom(boolean showing); - - /** - * Gets the location that this end crystal is pointing its beam to. - * - * @return the location that the beam is pointed to, or null if the beam is not shown - */ - @Nullable - Location getBeamTarget(); - - /** - * Sets the location that this end crystal is pointing to. Passing a null - * value will remove the current beam. - * - * @param location the location to point the beam to - * @throws IllegalArgumentException for differing worlds - */ - void setBeamTarget(@Nullable Location location); -} diff --git a/api/src/main/java/org/bukkit/entity/EnderDragon.java b/api/src/main/java/org/bukkit/entity/EnderDragon.java deleted file mode 100644 index ddef550bb..000000000 --- a/api/src/main/java/org/bukkit/entity/EnderDragon.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents an Ender Dragon - */ -public interface EnderDragon extends ComplexLivingEntity, Boss, org.bukkit.entity.Mob { // Paper - add Mob - - /** - * Represents a phase or action that an Ender Dragon can perform. - */ - enum Phase { - /** - * The dragon will circle outside the ring of pillars if ender - * crystals remain or inside the ring if not. - */ - CIRCLING, - /** - * The dragon will fly towards a targeted player and shoot a - * fireball when within 64 blocks. - */ - STRAFING, - /** - * The dragon will fly towards the empty portal (approaching - * from the other side, if applicable). - */ - FLY_TO_PORTAL, - /** - * The dragon will land on on the portal. If the dragon is not near - * the portal, it will fly to it before mounting. - */ - LAND_ON_PORTAL, - /** - * The dragon will leave the portal. - */ - LEAVE_PORTAL, - /** - * The dragon will attack with dragon breath at its current location. - */ - BREATH_ATTACK, - /** - * The dragon will search for a player to attack with dragon breath. - * If no player is close enough to the dragon for 5 seconds, the - * dragon will charge at a player within 150 blocks or will take off - * and begin circling if no player is found. - */ - SEARCH_FOR_BREATH_ATTACK_TARGET, - /** - * The dragon will roar before performing a breath attack. - */ - ROAR_BEFORE_ATTACK, - /** - * The dragon will charge a player. - */ - CHARGE_PLAYER, - /** - * The dragon will fly to the vicinity of the portal and die. - */ - DYING, - /** - * The dragon will hover at its current location, not performing any actions. - */ - HOVER - } - - /** - * Gets the current phase that the dragon is performing. - * - * @return the current phase - */ - @NotNull - Phase getPhase(); - - /** - * Sets the next phase for the dragon to perform. - * - * @param phase the next phase - */ - void setPhase(@NotNull Phase phase); -} diff --git a/api/src/main/java/org/bukkit/entity/EnderDragonPart.java b/api/src/main/java/org/bukkit/entity/EnderDragonPart.java deleted file mode 100644 index d0ac89bab..000000000 --- a/api/src/main/java/org/bukkit/entity/EnderDragonPart.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents an ender dragon part - */ -public interface EnderDragonPart extends ComplexEntityPart, Damageable { - @Override - @NotNull - public EnderDragon getParent(); -} diff --git a/api/src/main/java/org/bukkit/entity/EnderPearl.java b/api/src/main/java/org/bukkit/entity/EnderPearl.java deleted file mode 100644 index db18a90ba..000000000 --- a/api/src/main/java/org/bukkit/entity/EnderPearl.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a thrown Ender Pearl entity - */ -public interface EnderPearl extends Projectile { - -} diff --git a/api/src/main/java/org/bukkit/entity/EnderSignal.java b/api/src/main/java/org/bukkit/entity/EnderSignal.java deleted file mode 100644 index e90bca822..000000000 --- a/api/src/main/java/org/bukkit/entity/EnderSignal.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.Location; -import org.jetbrains.annotations.NotNull; - -/** - * Represents an EnderSignal, which is created upon throwing an ender eye. - */ -public interface EnderSignal extends Entity { - - /** - * Get the location this EnderSignal is moving towards. - * - * @return the {@link Location} this EnderSignal is moving towards. - */ - @NotNull - public Location getTargetLocation(); - - /** - * Set the {@link Location} this EnderSignal is moving towards. - *
- * When setting a new target location, the {@link #getDropItem()} resets to - * a random value and the despawn timer gets set back to 0. - * - * @param location the new target location - */ - public void setTargetLocation(@NotNull Location location); - - /** - * Gets if the EnderSignal should drop an item on death.
- * If {@code true}, it will drop an item. If {@code false}, it will shatter. - * - * @return true if the EnderSignal will drop an item on death, or false if - * it will shatter - */ - public boolean getDropItem(); - - /** - * Sets if the EnderSignal should drop an item on death; or if it should - * shatter. - * - * @param drop true if the EnderSignal should drop an item on death, or - * false if it should shatter. - */ - public void setDropItem(boolean drop); - - /** - * Gets the amount of time this entity has been alive (in ticks). - *
- * When this number is greater than 80, it will despawn on the next tick. - * - * @return the number of ticks this EnderSignal has been alive. - */ - public int getDespawnTimer(); - - /** - * Set how long this entity has been alive (in ticks). - *
- * When this number is greater than 80, it will despawn on the next tick. - * - * @param timer how long (in ticks) this EnderSignal has been alive. - */ - public void setDespawnTimer(int timer); -} diff --git a/api/src/main/java/org/bukkit/entity/Enderman.java b/api/src/main/java/org/bukkit/entity/Enderman.java deleted file mode 100644 index 821c690f8..000000000 --- a/api/src/main/java/org/bukkit/entity/Enderman.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.block.data.BlockData; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents an Enderman. - */ -public interface Enderman extends Monster { - - // Paper start - /** - * Try to teleport the enderman to a random nearby location. - * - * May conditionally fail if the random location was not valid - * @return If the enderman teleported successfully or not - */ - - public boolean teleportRandomly(); - // Paper end - - /** - * Gets the id and data of the block that the Enderman is carrying. - * - * @return MaterialData containing the id and data of the block - */ - @NotNull - public MaterialData getCarriedMaterial(); - - /** - * Sets the id and data of the block that the Enderman is carrying. - * - * @param material data to set the carried block to - */ - public void setCarriedMaterial(@NotNull MaterialData material); - - /** - * Gets the data of the block that the Enderman is carrying. - * - * @return BlockData containing the carried block, or null if none - */ - @Nullable - public BlockData getCarriedBlock(); - - /** - * Sets the data of the block that the Enderman is carrying. - * - * @param blockData data to set the carried block to, or null to remove - */ - public void setCarriedBlock(@Nullable BlockData blockData); -} diff --git a/api/src/main/java/org/bukkit/entity/Endermite.java b/api/src/main/java/org/bukkit/entity/Endermite.java deleted file mode 100644 index d9be83961..000000000 --- a/api/src/main/java/org/bukkit/entity/Endermite.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.entity; - -public interface Endermite extends Monster { - - /** - * Gets whether this Endermite was spawned by a player. - * - * An Endermite spawned by a player will be attacked by nearby Enderman. - * - * @return player spawned status - */ - boolean isPlayerSpawned(); - - /** - * Sets whether this Endermite was spawned by a player. - * - * An Endermite spawned by a player will be attacked by nearby Enderman. - * - * @param playerSpawned player spawned status - */ - void setPlayerSpawned(boolean playerSpawned); -} diff --git a/api/src/main/java/org/bukkit/entity/Entity.java b/api/src/main/java/org/bukkit/entity/Entity.java deleted file mode 100644 index 98b26cd93..000000000 --- a/api/src/main/java/org/bukkit/entity/Entity.java +++ /dev/null @@ -1,673 +0,0 @@ -package org.bukkit.entity; - -import java.util.List; -import java.util.Set; -import java.util.UUID; -import org.bukkit.Chunk; // Paper -import org.bukkit.EntityEffect; -import org.bukkit.Location; -import org.bukkit.Nameable; -import org.bukkit.Server; -import org.bukkit.World; -import org.bukkit.block.BlockFace; -import org.bukkit.block.PistonMoveReaction; -import org.bukkit.command.CommandSender; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.material.Directional; -import org.bukkit.metadata.Metadatable; -import org.bukkit.persistence.PersistentDataHolder; -import org.bukkit.util.BoundingBox; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a base entity in the world - */ -public interface Entity extends Metadatable, CommandSender, Nameable, PersistentDataHolder { - - /* - * Gets the entity's current position - * - * @return a new copy of Location containing the position of this entity - */ - @NotNull - public 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 - */ - @Contract("null -> null; !null -> !null") - @Nullable - public Location getLocation(@Nullable Location loc); - - /** - * Sets this entity's velocity - * - * @param velocity New velocity to travel with - */ - public void setVelocity(@NotNull Vector velocity); - - /** - * Gets this entity's current velocity - * - * @return Current traveling velocity of this entity - */ - @NotNull - public Vector getVelocity(); - - /** - * Gets the entity's height - * - * @return height of entity - */ - public double getHeight(); - - /** - * Gets the entity's width - * - * @return width of entity - */ - public double getWidth(); - - /** - * Gets the entity's current bounding box. - *

- * The returned bounding box reflects the entity's current location and - * size. - * - * @return the entity's current bounding box - */ - @NotNull - public BoundingBox getBoundingBox(); - - /** - * 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. - */ - public boolean isOnGround(); - - /** - * Gets the current world this entity resides in - * - * @return World - */ - @NotNull - public World getWorld(); - - /** - * Sets the entity's rotation. - *

- * Note that if the entity is affected by AI, it may override this rotation. - * - * @param yaw the yaw - * @param pitch the pitch - * @throws UnsupportedOperationException if used for players - * @deprecated draft API - */ - @Deprecated - public void setRotation(float yaw, float pitch); - - /** - * 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 - */ - public boolean teleport(@NotNull 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 - */ - public boolean teleport(@NotNull Location location, @NotNull 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 - */ - public boolean teleport(@NotNull 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 - */ - public boolean teleport(@NotNull Entity destination, @NotNull TeleportCause cause); - - // Paper start - /** - * Loads/Generates(in 1.13+) the Chunk asynchronously, and then teleports the entity when the chunk is ready. - * @param loc Location to teleport to - * @return A future that will be completed with the result of the teleport - */ - @NotNull - public default java.util.concurrent.CompletableFuture teleportAsync(@NotNull Location loc) { - return teleportAsync(loc, TeleportCause.PLUGIN); - } - /** - * Loads/Generates(in 1.13+) the Chunk asynchronously, and then teleports the entity when the chunk is ready. - * @param loc Location to teleport to - * @param cause Reason for teleport - * @return A future that will be completed with the result of the teleport - */ - @NotNull - public default java.util.concurrent.CompletableFuture teleportAsync(@NotNull Location loc, @NotNull TeleportCause cause) { - java.util.concurrent.CompletableFuture future = new java.util.concurrent.CompletableFuture<>(); - loc.getWorld().getChunkAtAsync(loc).thenAccept((chunk) -> future.complete(teleport(loc, cause))); - return future; - } - // Paper end - - /** - * 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 - */ - @NotNull - public List getNearbyEntities(double x, double y, double z); - - /** - * Returns a unique id for this entity - * - * @return Entity id - */ - public int getEntityId(); - - /** - * Returns the entity's current fire ticks (ticks before the entity stops - * being on fire). - * - * @return int fireTicks - */ - public int getFireTicks(); - - /** - * Returns the entity's maximum fire ticks. - * - * @return int maxFireTicks - */ - public int getMaxFireTicks(); - - /** - * Sets the entity's current fire ticks (ticks before the entity stops - * being on fire). - * - * @param ticks Current ticks remaining - */ - public void setFireTicks(int ticks); - - /** - * Mark the entity's removal. - */ - public void remove(); - - /** - * Returns true if this entity has been marked for removal. - * - * @return True if it is dead. - */ - public boolean isDead(); - - /** - * Returns false if the entity has died or been despawned for some other - * reason. - * - * @return True if valid. - */ - public boolean isValid(); - - /** - * Gets the {@link Server} that contains this Entity - * - * @return Server instance running this Entity - */ - @Override - @NotNull - public Server getServer(); - - /** - * Returns true if the entity gets persisted. - *

- * By default all entities are persistent. An entity will also not get - * persisted, if it is riding an entity that is not persistent. - *

- * The persistent flag on players controls whether or not to save their - * playerdata file when they quit. If a player is directly or indirectly - * riding a non-persistent entity, the vehicle at the root and all its - * passengers won't get persisted. - *

- * This should not be confused with - * {@link LivingEntity#setRemoveWhenFarAway(boolean)} which controls - * despawning of living entities. - * - * @return true if this entity is persistent - * @deprecated draft API - */ - @Deprecated - public boolean isPersistent(); - - /** - * Sets whether or not the entity gets persisted. - * - * @param persistent the persistence status - * @see #isPersistent() - * @deprecated draft API - */ - @Deprecated - public void setPersistent(boolean persistent); - - /** - * Gets the primary passenger of a vehicle. For vehicles that could have - * multiple passengers, this will only return the primary passenger. - * - * @return an entity - * @deprecated entities may have multiple passengers, use - * {@link #getPassengers()} - */ - @Deprecated - @Nullable - public Entity getPassenger(); - - /** - * Set the passenger of a vehicle. - * - * @param passenger The new passenger. - * @return false if it could not be done for whatever reason - * @deprecated entities may have multiple passengers, use - * {@link #getPassengers()} - */ - @Deprecated - public boolean setPassenger(@NotNull Entity passenger); - - /** - * Gets a list of passengers of this vehicle. - *

- * The returned list will not be directly linked to the entity's current - * passengers, and no guarantees are made as to its mutability. - * - * @return list of entities corresponding to current passengers. - */ - @NotNull - public List getPassengers(); - - /** - * Add a passenger to the vehicle. - * - * @param passenger The passenger to add - * @return false if it could not be done for whatever reason - */ - public boolean addPassenger(@NotNull Entity passenger); - - /** - * Remove a passenger from the vehicle. - * - * @param passenger The passenger to remove - * @return false if it could not be done for whatever reason - */ - public boolean removePassenger(@NotNull Entity passenger); - - /** - * Check if a vehicle has passengers. - * - * @return True if the vehicle has no passengers. - */ - public boolean isEmpty(); - - /** - * Eject any passenger. - * - * @return True if there was a passenger. - */ - public boolean eject(); - - /** - * Returns the distance this entity has fallen - * - * @return The distance. - */ - public float getFallDistance(); - - /** - * Sets the fall distance for this entity - * - * @param distance The new distance. - */ - public void setFallDistance(float distance); - - /** - * Record the last {@link EntityDamageEvent} inflicted on this entity - * - * @param event a {@link EntityDamageEvent} - */ - public void setLastDamageCause(@Nullable 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 - */ - @Nullable - public EntityDamageEvent getLastDamageCause(); - - /** - * Returns a unique and persistent id for this entity - * - * @return unique id - */ - @NotNull - public UUID getUniqueId(); - - /** - * Gets the amount of ticks this entity has lived for. - *

- * This is the equivalent to "age" in entities. - * - * @return Age of entity - */ - public 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 - */ - public void setTicksLived(int value); - - /** - * Performs the specified {@link EntityEffect} for this entity. - *

- * This will be viewable to all players near the entity. - *

- * If the effect is not applicable to this class of entity, it will not play. - * - * @param type Effect to play. - */ - public void playEffect(@NotNull EntityEffect type); - - /** - * Get the type of the entity. - * - * @return The entity type. - */ - @NotNull - public EntityType getType(); - - /** - * Returns whether this entity is inside a vehicle. - * - * @return True if the entity is in a vehicle. - */ - public 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. - */ - public boolean leaveVehicle(); - - /** - * Get the vehicle that this player is inside. If there is no vehicle, - * null will be returned. - * - * @return The current vehicle. - */ - @Nullable - public Entity getVehicle(); - - /** - * 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 - */ - public 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 - */ - public boolean isCustomNameVisible(); - - /** - * Sets whether the entity has a team colored (default: white) glow. - * - * nb: this refers to the 'Glowing' entity property, not whether a - * glowing potion effect is applied - * - * @param flag if the entity is glowing - */ - void setGlowing(boolean flag); - - /** - * Gets whether the entity is glowing or not. - * - * nb: this refers to the 'Glowing' entity property, not whether a - * glowing potion effect is applied - * - * @return whether the entity is glowing - */ - boolean isGlowing(); - - /** - * Sets whether the entity is invulnerable or not. - *

- * When an entity is invulnerable it can only be damaged by players in - * creative mode. - * - * @param flag if the entity is invulnerable - */ - public void setInvulnerable(boolean flag); - - /** - * Gets whether the entity is invulnerable or not. - * - * @return whether the entity is - */ - public boolean isInvulnerable(); - - /** - * Gets whether the entity is silent or not. - * - * @return whether the entity is silent. - */ - public boolean isSilent(); - - /** - * Sets whether the entity is silent or not. - *

- * When an entity is silent it will not produce any sound. - * - * @param flag if the entity is silent - */ - public void setSilent(boolean flag); - - /** - * Returns whether gravity applies to this entity. - * - * @return whether gravity applies - */ - boolean hasGravity(); - - /** - * Sets whether gravity applies to this entity. - * - * @param gravity whether gravity should apply - */ - void setGravity(boolean gravity); - - /** - * Gets the period of time (in ticks) before this entity can use a portal. - * - * @return portal cooldown ticks - */ - int getPortalCooldown(); - - /** - * Sets the period of time (in ticks) before this entity can use a portal. - * - * @param cooldown portal cooldown ticks - */ - void setPortalCooldown(int cooldown); - - /** - * Returns a set of tags for this entity. - *
- * Entities can have no more than 1024 tags. - * - * @return a set of tags for this entity - */ - @NotNull - Set getScoreboardTags(); - - /** - * Add a tag to this entity. - *
- * Entities can have no more than 1024 tags. - * - * @param tag the tag to add - * @return true if the tag was successfully added - */ - boolean addScoreboardTag(@NotNull String tag); - - /** - * Removes a given tag from this entity. - * - * @param tag the tag to remove - * @return true if the tag was successfully removed - */ - boolean removeScoreboardTag(@NotNull String tag); - - /** - * Returns the reaction of the entity when moved by a piston. - * - * @return reaction - */ - @NotNull - PistonMoveReaction getPistonMoveReaction(); - - /** - * Get the closest cardinal {@link BlockFace} direction an entity is - * currently facing. - *
- * This will not return any non-cardinal directions such as - * {@link BlockFace#UP} or {@link BlockFace#DOWN}. - *
- * {@link Hanging} entities will override this call and thus their behavior - * may be different. - * - * @return the entity's current cardinal facing. - * @see Hanging - * @see Directional#getFacing() - */ - @NotNull - BlockFace getFacing(); - - /** - * Gets the entity's current pose. - * - * Note that the pose is only updated at the end of a tick, so may be - * inconsistent with other methods. eg {@link Player#isSneaking()} being - * true does not imply the current pose will be {@link Pose#SNEAKING} - * - * @return current pose - */ - @NotNull - Pose getPose(); - - // Spigot start - public class Spigot extends CommandSender.Spigot - { - - /** - * Returns whether this entity is invulnerable. - * - * @return True if the entity is invulnerable. - * @deprecated {@link Entity#isInvulnerable()} - */ - @Deprecated - public boolean isInvulnerable() - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - } - - @NotNull - @Override - Spigot spigot(); - // Spigot end - - // Paper start - /** - * Gets the location where this entity originates from. - *

- * This value can be null if the entity hasn't yet been added to the world. - * - * @return Location where entity originates or null if not yet added - */ - @Nullable - Location getOrigin(); - - /** - * Returns whether this entity was spawned from a mob spawner. - * - * @return True if entity spawned from a mob spawner - */ - boolean fromMobSpawner(); - - /** - * Gets the latest chunk an entity is currently or was in. - * - * @return The current, or most recent chunk if the entity is invalid (which may load the chunk) - */ - @NotNull - Chunk getChunk(); - - /** - * @return The {@link org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason} that spawned this entity. - */ - @NotNull - org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason getEntitySpawnReason(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/EntityType.java b/api/src/main/java/org/bukkit/entity/EntityType.java deleted file mode 100644 index 527cb045f..000000000 --- a/api/src/main/java/org/bukkit/entity/EntityType.java +++ /dev/null @@ -1,406 +0,0 @@ -package org.bukkit.entity; - -import com.google.common.base.Preconditions; -import java.util.HashMap; -import java.util.Map; -import org.bukkit.Keyed; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.World; -import org.bukkit.entity.minecart.CommandMinecart; -import org.bukkit.entity.minecart.ExplosiveMinecart; -import org.bukkit.entity.minecart.HopperMinecart; -import org.bukkit.entity.minecart.PoweredMinecart; -import org.bukkit.entity.minecart.RideableMinecart; -import org.bukkit.entity.minecart.SpawnerMinecart; -import org.bukkit.entity.minecart.StorageMinecart; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public enum EntityType implements Keyed { - - // 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("experience_orb", ExperienceOrb.class, 2), - /** - * @see AreaEffectCloud - */ - AREA_EFFECT_CLOUD("area_effect_cloud", AreaEffectCloud.class, 3), - /** - * @see ElderGuardian - */ - ELDER_GUARDIAN("elder_guardian", ElderGuardian.class, 4), - /** - * @see WitherSkeleton - */ - WITHER_SKELETON("wither_skeleton", WitherSkeleton.class, 5), - /** - * @see Stray - */ - STRAY("stray", Stray.class, 6), - /** - * A flying chicken egg. - */ - EGG("egg", Egg.class, 7), - /** - * A leash attached to a fencepost. - */ - LEASH_HITCH("leash_knot", 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("small_fireball", SmallFireball.class, 13), - /** - * A flying ender pearl. - */ - ENDER_PEARL("ender_pearl", EnderPearl.class, 14), - /** - * An ender eye signal. - */ - ENDER_SIGNAL("eye_of_ender", EnderSignal.class, 15), - /** - * A flying splash potion. - */ - SPLASH_POTION("potion", ThrownPotion.class, 16, false), - /** - * A flying experience bottle. - */ - THROWN_EXP_BOTTLE("experience_bottle", ThrownExpBottle.class, 17), - /** - * An item frame on a wall. - */ - ITEM_FRAME("item_frame", ItemFrame.class, 18), - /** - * A flying wither skull projectile. - */ - WITHER_SKULL("wither_skull", WitherSkull.class, 19), - /** - * Primed TNT that is about to explode. - */ - PRIMED_TNT("tnt", TNTPrimed.class, 20), - /** - * A block that is going to or is about to fall. - */ - FALLING_BLOCK("falling_block", FallingBlock.class, 21, false), - /** - * Internal representation of a Firework once it has been launched. - */ - FIREWORK("firework_rocket", Firework.class, 22, false), - /** - * @see Husk - */ - HUSK("husk", Husk.class, 23), - /** - * Like {@link #ARROW} but causes the {@link PotionEffectType#GLOWING} effect on all team members. - */ - SPECTRAL_ARROW("spectral_arrow", SpectralArrow.class, 24), - /** - * Bullet fired by {@link #SHULKER}. - */ - SHULKER_BULLET("shulker_bullet", ShulkerBullet.class, 25), - /** - * Like {@link #FIREBALL} but with added effects. - */ - DRAGON_FIREBALL("dragon_fireball", DragonFireball.class, 26), - /** - * @see ZombieVillager - */ - ZOMBIE_VILLAGER("zombie_villager", ZombieVillager.class, 27), - /** - * @see SkeletonHorse - */ - SKELETON_HORSE("skeleton_horse", SkeletonHorse.class, 28), - /** - * @see ZombieHorse - */ - ZOMBIE_HORSE("zombie_horse", ZombieHorse.class, 29), - /** - * Mechanical entity with an inventory for placing weapons / armor into. - */ - ARMOR_STAND("armor_stand", ArmorStand.class, 30), - /** - * @see Donkey - */ - DONKEY("donkey", Donkey.class, 31), - /** - * @see Mule - */ - MULE("mule", Mule.class, 32), - /** - * @see EvokerFangs - */ - EVOKER_FANGS("evoker_fangs", EvokerFangs.class, 33), - /** - * @see Evoker - */ - EVOKER("evoker", Evoker.class, 34), - /** - * @see Vex - */ - VEX("vex", Vex.class, 35), - /** - * @see Vindicator - */ - VINDICATOR("vindicator", Vindicator.class, 36), - /** - * @see Illusioner - */ - ILLUSIONER("illusioner", Illusioner.class, 37), - /** - * @see CommandMinecart - */ - MINECART_COMMAND("command_block_minecart", CommandMinecart.class, 40), - /** - * A placed boat. - */ - BOAT("boat", Boat.class, 41), - /** - * @see RideableMinecart - */ - MINECART("minecart", RideableMinecart.class, 42), - /** - * @see StorageMinecart - */ - MINECART_CHEST("chest_minecart", StorageMinecart.class, 43), - /** - * @see PoweredMinecart - */ - MINECART_FURNACE("furnace_minecart", PoweredMinecart.class, 44), - /** - * @see ExplosiveMinecart - */ - MINECART_TNT("tnt_minecart", ExplosiveMinecart.class, 45), - /** - * @see HopperMinecart - */ - MINECART_HOPPER("hopper_minecart", HopperMinecart.class, 46), - /** - * @see SpawnerMinecart - */ - MINECART_MOB_SPAWNER("spawner_minecart", SpawnerMinecart.class, 47), - 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("zombie_pigman", PigZombie.class, 57), - ENDERMAN("enderman", Enderman.class, 58), - CAVE_SPIDER("cave_spider", CaveSpider.class, 59), - SILVERFISH("silverfish", Silverfish.class, 60), - BLAZE("blaze", Blaze.class, 61), - MAGMA_CUBE("magma_cube", MagmaCube.class, 62), - ENDER_DRAGON("ender_dragon", EnderDragon.class, 63), - WITHER("wither", Wither.class, 64), - BAT("bat", Bat.class, 65), - WITCH("witch", Witch.class, 66), - ENDERMITE("endermite", Endermite.class, 67), - GUARDIAN("guardian", Guardian.class, 68), - SHULKER("shulker", Shulker.class, 69), - 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("mooshroom", MushroomCow.class, 96), - SNOWMAN("snow_golem", Snowman.class, 97), - OCELOT("ocelot", Ocelot.class, 98), - IRON_GOLEM("iron_golem", IronGolem.class, 99), - HORSE("horse", Horse.class, 100), - RABBIT("rabbit", Rabbit.class, 101), - POLAR_BEAR("polar_bear", PolarBear.class, 102), - LLAMA("llama", Llama.class, 103), - LLAMA_SPIT("llama_spit", LlamaSpit.class, 104), - PARROT("parrot", Parrot.class, 105), - VILLAGER("villager", Villager.class, 120), - ENDER_CRYSTAL("end_crystal", EnderCrystal.class, 200), - TURTLE("turtle", Turtle.class, -1), - PHANTOM("phantom", Phantom.class, -1), - TRIDENT("trident", Trident.class, -1), - COD("cod", Cod.class, -1), - SALMON("salmon", Salmon.class, -1), - PUFFERFISH("pufferfish", PufferFish.class, -1), - TROPICAL_FISH("tropical_fish", TropicalFish.class, -1), - DROWNED("drowned", Drowned.class, -1), - DOLPHIN("dolphin", Dolphin.class, -1), - CAT("cat", Cat.class, -1), - PANDA("panda", Panda.class, -1), - PILLAGER("pillager", Pillager.class, -1), - RAVAGER("ravager", Ravager.class, -1), - TRADER_LLAMA("trader_llama", TraderLlama.class, -1), - WANDERING_TRADER("wandering_trader", WanderingTrader.class, -1), - FOX("fox", Fox.class, -1), - /** - * A fishing line and bobber. - */ - FISHING_HOOK("fishing_bobber", FishHook.class, -1, false), - /** - * A bolt of lightning. - *

- * Spawn with {@link World#strikeLightning(Location)}. - */ - LIGHTNING("lightning_bolt", LightningStrike.class, -1, false), - PLAYER("player", Player.class, -1, false), - /** - * An unknown entity without an Entity Class - */ - UNKNOWN(null, null, -1, false); - - private final String name; - private final Class clazz; - private final short typeId; - private final boolean independent, living; - private final NamespacedKey key; - - private static final Map NAME_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(java.util.Locale.ENGLISH), type); - } - if (type.typeId > 0) { - ID_MAP.put(type.typeId, type); - } - } - - // Add legacy names - NAME_MAP.put("xp_orb", EXPERIENCE_ORB); - NAME_MAP.put("eye_of_ender_signal", ENDER_SIGNAL); - NAME_MAP.put("xp_bottle", THROWN_EXP_BOTTLE); - NAME_MAP.put("fireworks_rocket", FIREWORK); - NAME_MAP.put("evocation_fangs", EVOKER_FANGS); - NAME_MAP.put("evocation_illager", EVOKER); - NAME_MAP.put("vindication_illager", VINDICATOR); - NAME_MAP.put("illusion_illager", ILLUSIONER); - NAME_MAP.put("commandblock_minecart", MINECART_COMMAND); - NAME_MAP.put("snowman", SNOWMAN); - NAME_MAP.put("villager_golem", IRON_GOLEM); - NAME_MAP.put("ender_crystal", ENDER_CRYSTAL); - } - - private EntityType(/*@Nullable*/ String name, /*@Nullable*/ Class clazz, int typeId) { - this(name, clazz, typeId, true); - } - - private EntityType(/*@Nullable*/ String name, /*@Nullable*/ Class clazz, int typeId, boolean independent) { - this.name = name; - this.clazz = clazz; - this.typeId = (short) typeId; - this.independent = independent; - this.living = clazz != null && LivingEntity.class.isAssignableFrom(clazz); - this.key = (name == null) ? null : NamespacedKey.minecraft(name); - } - - /** - * - * @return the entity type's name - * @deprecated Magic value - */ - @Deprecated - @Nullable - public String getName() { - return name; - } - - @NotNull - @Override - public NamespacedKey getKey() { - Preconditions.checkArgument(key != null, "EntityType doesn't have key! Is it UNKNOWN?"); - - return key; - } - - @Nullable - public Class getEntityClass() { - return clazz; - } - - /** - * - * @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 - @Contract("null -> null") - @Nullable - public static EntityType fromName(@Nullable String name) { - if (name == null) { - return null; - } - return NAME_MAP.get(name.toLowerCase(java.util.Locale.ENGLISH)); - } - - /** - * - * @param id the raw type id - * @return the matching entity type or null - * @deprecated Magic value - */ - @Deprecated - @Nullable - 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/api/src/main/java/org/bukkit/entity/Evoker.java b/api/src/main/java/org/bukkit/entity/Evoker.java deleted file mode 100644 index f8d173adc..000000000 --- a/api/src/main/java/org/bukkit/entity/Evoker.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents an Evoker "Illager". - */ -public interface Evoker extends Spellcaster { - - /** - * Represents the current spell the Evoker is using. - * - * @deprecated future versions of Minecraft have additional spell casting - * entities. - */ - @Deprecated - public enum Spell { - - /** - * No spell is being evoked. - */ - NONE, - /** - * The spell that summons Vexes. - */ - SUMMON, - /** - * The spell that summons Fangs. - */ - FANGS, - /** - * The "wololo" spell. - */ - WOLOLO, - /** - * The spell that makes the casting entity invisible. - */ - DISAPPEAR, - /** - * The spell that makes the target blind. - */ - BLINDNESS; - } - - /** - * Gets the {@link Spell} the Evoker is currently using. - * - * @return the current spell - * @deprecated future versions of Minecraft have additional spell casting - * entities. - * - */ - @Deprecated - @NotNull - Spell getCurrentSpell(); - - /** - * Sets the {@link Spell} the Evoker is currently using. - * - * @param spell the spell the evoker should be using - * @deprecated future versions of Minecraft have additional spell casting - * entities. - */ - @Deprecated - void setCurrentSpell(@Nullable Spell spell); -} diff --git a/api/src/main/java/org/bukkit/entity/EvokerFangs.java b/api/src/main/java/org/bukkit/entity/EvokerFangs.java deleted file mode 100644 index 7cc1dcdab..000000000 --- a/api/src/main/java/org/bukkit/entity/EvokerFangs.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.Nullable; - -/** - * Represents Evoker Fangs. - */ -public interface EvokerFangs extends Entity { - - /** - * Gets the {@link LivingEntity} which summoned the fangs. - * - * @return the {@link LivingEntity} which summoned the fangs - */ - @Nullable - LivingEntity getOwner(); - - /** - * Sets the {@link LivingEntity} which summoned the fangs. - * - * @param owner the {@link LivingEntity} which summoned the fangs - */ - void setOwner(@Nullable LivingEntity owner); -} diff --git a/api/src/main/java/org/bukkit/entity/ExperienceOrb.java b/api/src/main/java/org/bukkit/entity/ExperienceOrb.java deleted file mode 100644 index dec70bbfa..000000000 --- a/api/src/main/java/org/bukkit/entity/ExperienceOrb.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; // Paper - -/** - * Represents an Experience Orb. - */ -public interface ExperienceOrb extends Entity { - - /** - * Gets how much experience is contained within this orb - * - * @return Amount of experience - */ - public int getExperience(); - - /** - * Sets how much experience is contained within this orb - * - * @param value Amount of experience - */ - public void setExperience(int value); - - // Paper start - /** - * Check if this orb was spawned from a {@link ThrownExpBottle} - * - * @return if orb was spawned from a bottle - * @deprecated Use getSpawnReason() == EXP_BOTTLE - */ - @Deprecated - default boolean isFromBottle() { - return getSpawnReason() == SpawnReason.EXP_BOTTLE; - } - - /** - * Reasons for why this Experience Orb was spawned - */ - enum SpawnReason { - /** - * Spawned by a player dying - */ - PLAYER_DEATH, - /** - * Spawned by an entity dying after being damaged by a player - */ - ENTITY_DEATH, - /** - * Spawned by player using a furnace - */ - FURNACE, - /** - * Spawned by player breeding animals - */ - BREED, - /** - * Spawned by player trading with a villager - */ - VILLAGER_TRADE, - /** - * Spawned by player fishing - */ - FISHING, - /** - * Spawned by player breaking a block that gives experience points such as Diamond Ore - */ - BLOCK_BREAK, - /** - * Spawned by Bukkit API - */ - CUSTOM, - /** - * Spawned by a player throwing an experience points bottle - */ - EXP_BOTTLE, - /** - * Spawned by a player using a grindstone - */ - GRINDSTONE, - /** - * We do not know why it was spawned - */ - UNKNOWN - } - - /** - * If this experience orb was triggered to be spawned by - * an entity such as a player, due to events such as killing entity, - * breaking blocks, smelting in a furnace, etc, this will return the UUID - * of the entity that triggered this orb to drop. - * - * In the case of an entity being killed, this will be the killers UUID. - * - * @return UUID of the player that triggered this orb to drop, or null if unknown/no triggering entity - */ - @Nullable java.util.UUID getTriggerEntityId(); - - /** - * If this experience orb was spawned in relation to another - * entity, such as a player or other living entity death, or breeding, - * return the source entity UUID. - * - * In the case of breeding, this will be the new baby entities UUID. - * In the case of an entity being killed, this will be the dead entities UUID. - * - * @return The UUID of the entity that sourced this experience orb - */ - @Nullable java.util.UUID getSourceEntityId(); - - /** - * Gets the reason that this experience orb was spawned. For any case that we - * do not know, such as orbs spawned before this API was added, UNKNOWN is returned. - * @return The reason for this orb being spawned. - */ - @NotNull - SpawnReason getSpawnReason(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Explosive.java b/api/src/main/java/org/bukkit/entity/Explosive.java deleted file mode 100644 index 48650f6ab..000000000 --- a/api/src/main/java/org/bukkit/entity/Explosive.java +++ /dev/null @@ -1,35 +0,0 @@ -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 - */ - public void setYield(float yield); - - /** - * Return the radius or yield of this explosive's explosion - * - * @return the radius of blocks affected - */ - public float getYield(); - - /** - * Set whether or not this explosive's explosion causes fire - * - * @param isIncendiary Whether it should cause fire - */ - public void setIsIncendiary(boolean isIncendiary); - - /** - * Return whether or not this explosive creates a fire when exploding - * - * @return true if the explosive creates fire, false otherwise - */ - public boolean isIncendiary(); -} diff --git a/api/src/main/java/org/bukkit/entity/FallingBlock.java b/api/src/main/java/org/bukkit/entity/FallingBlock.java deleted file mode 100644 index 14cb0d770..000000000 --- a/api/src/main/java/org/bukkit/entity/FallingBlock.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a falling block - */ -public interface FallingBlock extends Entity { - - /** - * Get the Material of the falling block - * - * @return Material of the block - * @deprecated use {@link #getBlockData()} - */ - @Deprecated - @NotNull - Material getMaterial(); - - /** - * Get the data for the falling block - * - * @return data of the block - */ - @NotNull - BlockData 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 FallingBlock - * - * @return the source block location the FallingBlock was spawned from - * @deprecated replaced by {@link Entity#getOrigin()} - */ - @Deprecated - default org.bukkit.Location getSourceLoc() { - return this.getOrigin(); - } -} diff --git a/api/src/main/java/org/bukkit/entity/Fireball.java b/api/src/main/java/org/bukkit/entity/Fireball.java deleted file mode 100644 index 7a44707f2..000000000 --- a/api/src/main/java/org/bukkit/entity/Fireball.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - public void setDirection(@NotNull Vector direction); - - /** - * Retrieve the direction this fireball is heading toward - * - * @return the direction - */ - @NotNull - public Vector getDirection(); - -} diff --git a/api/src/main/java/org/bukkit/entity/Firework.java b/api/src/main/java/org/bukkit/entity/Firework.java deleted file mode 100644 index e8c04c138..000000000 --- a/api/src/main/java/org/bukkit/entity/Firework.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.inventory.meta.FireworkMeta; -import org.jetbrains.annotations.NotNull; - -import java.util.UUID; -import org.jetbrains.annotations.Nullable; - -public interface Firework extends Entity { - - /** - * Get a copy of the fireworks meta - * - * @return A copy of the current Firework meta - */ - @NotNull - FireworkMeta getFireworkMeta(); - - /** - * Apply the provided meta to the fireworks - * - * @param meta The FireworkMeta to apply - */ - void setFireworkMeta(@NotNull FireworkMeta meta); - - /** - * Cause this firework to explode at earliest opportunity, as if it has no - * remaining fuse. - */ - void detonate(); - - /** - * Gets if the firework was shot at an angle (i.e. from a crossbow). - * - * A firework which was not shot at an angle will fly straight upwards. - * - * @return shot at angle status - */ - boolean isShotAtAngle(); - - /** - * Sets if the firework was shot at an angle (i.e. from a crossbow). - * - * A firework which was not shot at an angle will fly straight upwards. - * - * @param shotAtAngle the new shotAtAngle - */ - void setShotAtAngle(boolean shotAtAngle); - - // Paper start - @Nullable - public UUID getSpawningEntity(); - /** - * If this firework is boosting an entity, return it - * @return The entity being boosted - */ - @Nullable - public LivingEntity getBoostedEntity(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Fish.java b/api/src/main/java/org/bukkit/entity/Fish.java deleted file mode 100644 index 82e390b21..000000000 --- a/api/src/main/java/org/bukkit/entity/Fish.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a fish entity. - */ -public interface Fish extends WaterMob { } diff --git a/api/src/main/java/org/bukkit/entity/FishHook.java b/api/src/main/java/org/bukkit/entity/FishHook.java deleted file mode 100644 index fdd48d0f1..000000000 --- a/api/src/main/java/org/bukkit/entity/FishHook.java +++ /dev/null @@ -1,32 +0,0 @@ -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 - * @deprecated has no effect in newer Minecraft versions - */ - @Deprecated - public 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 - * @deprecated has no effect in newer Minecraft versions - */ - @Deprecated - public void setBiteChance(double chance) throws IllegalArgumentException; -} diff --git a/api/src/main/java/org/bukkit/entity/Flying.java b/api/src/main/java/org/bukkit/entity/Flying.java deleted file mode 100644 index 580ce18bf..000000000 --- a/api/src/main/java/org/bukkit/entity/Flying.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Flying Entity. - */ -public interface Flying extends Mob {} diff --git a/api/src/main/java/org/bukkit/entity/Fox.java b/api/src/main/java/org/bukkit/entity/Fox.java deleted file mode 100644 index 89f65032d..000000000 --- a/api/src/main/java/org/bukkit/entity/Fox.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * What does the fox say? - */ -public interface Fox extends Animals, Sittable { - - /** - * Gets the current type of this fox. - * - * @return Type of the fox. - */ - @NotNull - public Type getFoxType(); - - /** - * Sets the current type of this fox. - * - * @param type New type of this fox. - */ - public void setFoxType(@NotNull Type type); - - /** - * Checks if this animal is crouching - * - * @return true if crouching - */ - boolean isCrouching(); - - /** - * Sets if this animal is crouching. - * - * @param crouching true if crouching - */ - void setCrouching(boolean crouching); - - /** - * Sets if this animal is sleeping. - * - * @param sleeping true if sleeping - */ - void setSleeping(boolean sleeping); - - /** - * Represents the various different fox types there are. - */ - public enum Type { - RED, - SNOW; - } -} diff --git a/api/src/main/java/org/bukkit/entity/Ghast.java b/api/src/main/java/org/bukkit/entity/Ghast.java deleted file mode 100644 index 3f5edf76c..000000000 --- a/api/src/main/java/org/bukkit/entity/Ghast.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Ghast. - */ -public interface Ghast extends Flying {} diff --git a/api/src/main/java/org/bukkit/entity/Giant.java b/api/src/main/java/org/bukkit/entity/Giant.java deleted file mode 100644 index 610de5779..000000000 --- a/api/src/main/java/org/bukkit/entity/Giant.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Giant. - */ -public interface Giant extends Monster {} diff --git a/api/src/main/java/org/bukkit/entity/Golem.java b/api/src/main/java/org/bukkit/entity/Golem.java deleted file mode 100644 index 4b43c3631..000000000 --- a/api/src/main/java/org/bukkit/entity/Golem.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -/** - * A mechanical creature that may harm enemies. - */ -public interface Golem extends Creature { - -} diff --git a/api/src/main/java/org/bukkit/entity/Guardian.java b/api/src/main/java/org/bukkit/entity/Guardian.java deleted file mode 100644 index 4da9f3c5f..000000000 --- a/api/src/main/java/org/bukkit/entity/Guardian.java +++ /dev/null @@ -1,20 +0,0 @@ -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 - * @deprecated should check if instance of {@link ElderGuardian}. - */ - @Deprecated - public boolean isElder(); - - /** - * @param shouldBeElder shouldBeElder - * @deprecated Must spawn a new {@link ElderGuardian}. - */ - @Deprecated - public void setElder(boolean shouldBeElder); -} diff --git a/api/src/main/java/org/bukkit/entity/Hanging.java b/api/src/main/java/org/bukkit/entity/Hanging.java deleted file mode 100644 index 2f07efac0..000000000 --- a/api/src/main/java/org/bukkit/entity/Hanging.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.block.BlockFace; -import org.bukkit.material.Attachable; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - public boolean setFacingDirection(@NotNull BlockFace face, boolean force); -} diff --git a/api/src/main/java/org/bukkit/entity/Horse.java b/api/src/main/java/org/bukkit/entity/Horse.java deleted file mode 100644 index 9e1bb136c..000000000 --- a/api/src/main/java/org/bukkit/entity/Horse.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.inventory.HorseInventory; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Horse. - */ -public interface Horse extends AbstractHorse { - - /** - * @deprecated different variants are differing classes - */ - @Deprecated - public enum Variant { - /** - * A normal horse - */ - HORSE, - /** - * A donkey - */ - DONKEY, - /** - * A mule - */ - MULE, - /** - * An undead horse - */ - UNDEAD_HORSE, - /** - * A skeleton horse - */ - SKELETON_HORSE, - /** - * Not really a horse :) - */ - LLAMA - ; - } - - /** - * Represents the base color that the horse has. - */ - public 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. - */ - public 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 color. - *

- * Colors only apply to horses, not to donkeys, mules, skeleton horses - * or undead horses. - * - * @return a {@link Color} representing the horse's group - */ - @NotNull - public 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 - */ - public void setColor(@NotNull 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 - */ - @NotNull - public 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 - */ - public void setStyle(@NotNull Style style); - - /** - * @return carrying chest status - * @deprecated see {@link ChestedHorse} - */ - @Deprecated - public boolean isCarryingChest(); - - /** - * @param chest chest - * @deprecated see {@link ChestedHorse} - */ - @Deprecated - public void setCarryingChest(boolean chest); - - @NotNull - @Override - public HorseInventory getInventory(); -} diff --git a/api/src/main/java/org/bukkit/entity/HumanEntity.java b/api/src/main/java/org/bukkit/entity/HumanEntity.java deleted file mode 100644 index f25c73155..000000000 --- a/api/src/main/java/org/bukkit/entity/HumanEntity.java +++ /dev/null @@ -1,479 +0,0 @@ -package org.bukkit.entity; - -import java.util.Collection; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.MainHand; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.PlayerInventory; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a human entity, such as an NPC or a player - */ -public interface HumanEntity extends LivingEntity, AnimalTamer, InventoryHolder { - - /** - * Returns the name of this player - * - * @return Player name - */ - @NotNull - @Override - public String getName(); - - /** - * Get the player's inventory. - * - * @return The inventory of the player, this also contains the armor - * slots. - */ - @NotNull - @Override - public PlayerInventory getInventory(); - - /** - * Get the player's EnderChest inventory - * - * @return The EnderChest of the player - */ - @NotNull - public Inventory getEnderChest(); - - /** - * Gets the player's selected main hand - * - * @return the players main hand - */ - @NotNull - public MainHand getMainHand(); - - /** - * 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. - */ - public boolean setWindowProperty(@NotNull 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. - */ - @NotNull - public 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 - */ - @Nullable - public InventoryView openInventory(@NotNull 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. - */ - @Nullable - public InventoryView openWorkbench(@Nullable 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. - */ - @Nullable - public InventoryView openEnchanting(@Nullable Location location, boolean force); - - /** - * Opens an inventory window to the specified inventory view. - * - * @param inventory The view to open - */ - public void openInventory(@NotNull InventoryView inventory); - - /** - * Starts a trade between the player and the villager. - * - * Note that only one player may trade with a villager at once. You must use - * the force parameter for this. - * - * @param trader The merchant to trade with. Cannot be null. - * @param force whether to force the trade even if another player is trading - * @return The newly opened inventory view, or null if it could not be - * opened. - */ - @Nullable - public InventoryView openMerchant(@NotNull Villager trader, boolean force); - - /** - * Starts a trade between the player and the merchant. - * - * Note that only one player may trade with a merchant at once. You must use - * the force parameter for this. - * - * @param merchant The merchant to trade with. Cannot be null. - * @param force whether to force the trade even if another player is trading - * @return The newly opened inventory view, or null if it could not be - * opened. - */ - @Nullable - public InventoryView openMerchant(@NotNull Merchant merchant, boolean force); - - /** - * Force-closes the currently open inventory view for this player, if any. - */ - public void closeInventory(); - - // Paper start - /** - * Force-closes the currently open inventory view for this player, if any. - * - * @param reason why the inventory is closing - */ - public void closeInventory(@NotNull org.bukkit.event.inventory.InventoryCloseEvent.Reason reason); - // Paper end - - /** - * Returns the ItemStack currently in your hand, can be empty. - * - * @return The ItemStack of the item you are currently holding. - * @deprecated Humans may now dual wield in their off hand, use explicit - * methods in {@link PlayerInventory}. - */ - @Deprecated - @NotNull - public 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 - * @deprecated Humans may now dual wield in their off hand, use explicit - * methods in {@link PlayerInventory}. - */ - @Deprecated - public void setItemInHand(@Nullable 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. - */ - @NotNull - public 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 - */ - public void setItemOnCursor(@Nullable ItemStack item); - - /** - * Check whether a cooldown is active on the specified material. - * - * @param material the material to check - * @return if a cooldown is active on the material - */ - public boolean hasCooldown(@NotNull Material material); - - /** - * Get the cooldown time in ticks remaining for the specified material. - * - * @param material the material to check - * @return the remaining cooldown time in ticks - */ - public int getCooldown(@NotNull Material material); - - /** - * Set a cooldown on the specified material for a certain amount of ticks. - * ticks. 0 ticks will result in the removal of the cooldown. - *

- * Cooldowns are used by the server for items such as ender pearls and - * shields to prevent them from being used repeatedly. - *

- * Note that cooldowns will not by themselves stop an item from being used - * for attacking. - * - * @param material the material to set the cooldown for - * @param ticks the amount of ticks to set or 0 to remove - */ - public void setCooldown(@NotNull Material material, int ticks); - - /** - * Get the sleep ticks of the player. This value may be capped. - * - * @return slumber ticks - */ - public int getSleepTicks(); - - /** - * 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. - */ - @Nullable - public Location getBedSpawnLocation(); - - /** - * Sets the Location where the player will spawn at their bed. - * - * @param location where to set the respawn location - */ - public void setBedSpawnLocation(@Nullable 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 - */ - public void setBedSpawnLocation(@Nullable Location location, boolean force); - - /** - * Attempts to make the entity sleep at the given location. - *
- * The location must be in the current world and have a bed placed at the - * location. The game may also enforce other requirements such as proximity - * to bed, monsters, and dimension type if force is not set. - * - * @param location the location of the bed - * @param force whether to try and sleep at the location even if not - * normally possible - * @return whether the sleep was successful - */ - public boolean sleep(@NotNull Location location, boolean force); - - /** - * Causes the player to wakeup if they are currently sleeping. - * - * @param setSpawnLocation whether to set their spawn location to the bed - * they are currently sleeping in - * @throws IllegalStateException if not sleeping - */ - public void wakeup(boolean setSpawnLocation); - - /** - * Gets the location of the bed the player is currently sleeping in - * - * @return location - * @throws IllegalStateException if not sleeping - */ - @NotNull - public Location getBedLocation(); - - /** - * Gets this human's current {@link GameMode} - * - * @return Current game mode - */ - @NotNull - public GameMode getGameMode(); - - /** - * Sets this human's current {@link GameMode} - * - * @param mode New game mode - */ - public void setGameMode(@NotNull GameMode mode); - - /** - * Check if the player is currently blocking (ie with a shield). - * - * @return Whether they are blocking. - */ - public boolean isBlocking(); - - /** - * Check if the player currently has their hand raised (ie about to begin - * blocking). - * - * @return Whether their hand is raised - */ - public boolean isHandRaised(); - - /** - * Get the total amount of experience required for the player to level - * - * @return Experience required to level up - */ - public int getExpToLevel(); - - // Paper start - /** - * If there is an Entity on this entities left shoulder, it will be released to the world and returned. - * If no Entity is released, null will be returned. - * - * @return The released entity, or null - */ - @Nullable - public Entity releaseLeftShoulderEntity(); - - /** - * If there is an Entity on this entities left shoulder, it will be released to the world and returned. - * If no Entity is released, null will be returned. - * - * @return The released entity, or null - */ - @Nullable - public Entity releaseRightShoulderEntity(); - // Paper end - - /** - * Discover a recipe for this player such that it has not already been - * discovered. This method will add the key's associated recipe to the - * player's recipe book. - * - * @param recipe the key of the recipe to discover - * - * @return whether or not the recipe was newly discovered - */ - public boolean discoverRecipe(@NotNull NamespacedKey recipe); - - /** - * Discover a collection of recipes for this player such that they have not - * already been discovered. This method will add the keys' associated - * recipes to the player's recipe book. If a recipe in the provided - * collection has already been discovered, it will be silently ignored. - * - * @param recipes the keys of the recipes to discover - * - * @return the amount of newly discovered recipes where 0 indicates that - * none were newly discovered and a number equal to {@code recipes.size()} - * indicates that all were new - */ - public int discoverRecipes(@NotNull Collection recipes); - - /** - * Undiscover a recipe for this player such that it has already been - * discovered. This method will remove the key's associated recipe from the - * player's recipe book. - * - * @param recipe the key of the recipe to undiscover - * - * @return whether or not the recipe was successfully undiscovered (i.e. it - * was previously discovered) - */ - public boolean undiscoverRecipe(@NotNull NamespacedKey recipe); - - /** - * Undiscover a collection of recipes for this player such that they have - * already been discovered. This method will remove the keys' associated - * recipes from the player's recipe book. If a recipe in the provided - * collection has not yet been discovered, it will be silently ignored. - * - * @param recipes the keys of the recipes to undiscover - * - * @return the amount of undiscovered recipes where 0 indicates that none - * were undiscovered and a number equal to {@code recipes.size()} indicates - * that all were undiscovered - */ - public int undiscoverRecipes(@NotNull Collection recipes); - - /** - * Gets the entity currently perched on the left shoulder or null if no - * entity. - *
- * The returned entity will not be spawned within the world, so most - * operations are invalid unless the entity is first spawned in. - * - * @return left shoulder entity - * @deprecated There are currently no well defined semantics regarding - * serialized entities in Bukkit. Use with care. - */ - @Deprecated - @Nullable - public Entity getShoulderEntityLeft(); - - /** - * Sets the entity currently perched on the left shoulder, or null to - * remove. This method will remove the entity from the world. - *
- * Note that only a copy of the entity will be set to display on the - * shoulder. - *
- * Also note that the client will currently only render {@link Parrot} - * entities. - * - * @param entity left shoulder entity - * @deprecated There are currently no well defined semantics regarding - * serialized entities in Bukkit. Use with care. - */ - @Deprecated - public void setShoulderEntityLeft(@Nullable Entity entity); - - /** - * Gets the entity currently perched on the right shoulder or null if no - * entity. - *
- * The returned entity will not be spawned within the world, so most - * operations are invalid unless the entity is first spawned in. - * - * @return right shoulder entity - * @deprecated There are currently no well defined semantics regarding - * serialized entities in Bukkit. Use with care. - */ - @Deprecated - @Nullable - public Entity getShoulderEntityRight(); - - /** - * Sets the entity currently perched on the right shoulder, or null to - * remove. This method will remove the entity from the world. - *
- * Note that only a copy of the entity will be set to display on the - * shoulder. - *
- * Also note that the client will currently only render {@link Parrot} - * entities. - * - * @param entity right shoulder entity - * @deprecated There are currently no well defined semantics regarding - * serialized entities in Bukkit. Use with care. - */ - @Deprecated - public void setShoulderEntityRight(@Nullable Entity entity); - - // Paper start - Add method to open already placed sign - /** - * Opens an editor window for the specified sign - * - * @param sign The sign to open - */ - void openSign(@NotNull org.bukkit.block.Sign sign); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Husk.java b/api/src/main/java/org/bukkit/entity/Husk.java deleted file mode 100644 index 85ada1c67..000000000 --- a/api/src/main/java/org/bukkit/entity/Husk.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Husk - variant of {@link Zombie}. - */ -public interface Husk extends Zombie { - - /** - * Get if this entity is in the process of converting to a Zombie as a - * result of being underwater. - * - * @return conversion status - */ - @Override - boolean isConverting(); - - /** - * Gets the amount of ticks until this entity will be converted to a Zombie - * as a result of being underwater. - * - * When this reaches 0, the entity will be converted. - * - * @return conversion time - * @throws IllegalStateException if {@link #isConverting()} is false. - */ - @Override - int getConversionTime(); - - /** - * Sets the amount of ticks until this entity will be converted to a Zombie - * as a result of being underwater. - * - * When this reaches 0, the entity will be converted. A value of less than 0 - * will stop the current conversion process without converting the current - * entity. - * - * @param time new conversion time - */ - @Override - void setConversionTime(int time); -} diff --git a/api/src/main/java/org/bukkit/entity/Illager.java b/api/src/main/java/org/bukkit/entity/Illager.java deleted file mode 100644 index a288dfa26..000000000 --- a/api/src/main/java/org/bukkit/entity/Illager.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a type of "Illager". - */ -public interface Illager extends Raider { } diff --git a/api/src/main/java/org/bukkit/entity/Illusioner.java b/api/src/main/java/org/bukkit/entity/Illusioner.java deleted file mode 100644 index 14e6c5ee0..000000000 --- a/api/src/main/java/org/bukkit/entity/Illusioner.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.bukkit.entity; - -import com.destroystokyo.paper.entity.RangedEntity; - -/** - * Represents an Illusioner "Illager". - */ -public interface Illusioner extends Spellcaster, RangedEntity { // Paper - -} diff --git a/api/src/main/java/org/bukkit/entity/IronGolem.java b/api/src/main/java/org/bukkit/entity/IronGolem.java deleted file mode 100644 index 655e37cb3..000000000 --- a/api/src/main/java/org/bukkit/entity/IronGolem.java +++ /dev/null @@ -1,22 +0,0 @@ -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 - */ - public 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. - */ - public void setPlayerCreated(boolean playerCreated); -} diff --git a/api/src/main/java/org/bukkit/entity/Item.java b/api/src/main/java/org/bukkit/entity/Item.java deleted file mode 100644 index a15f70ff4..000000000 --- a/api/src/main/java/org/bukkit/entity/Item.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -// Paper start -import java.util.UUID; -// Paper end - -/** - * Represents a dropped item. - */ -public interface Item extends Entity { - - /** - * Gets the item stack associated with this item drop. - * - * @return An item stack. - */ - @NotNull - public ItemStack getItemStack(); - - /** - * Sets the item stack associated with this item drop. - * - * @param stack An item stack. - */ - public void setItemStack(@Nullable ItemStack stack); - - /** - * Gets the delay before this Item is available to be picked up by players - * - * @return Remaining delay - */ - public int getPickupDelay(); - - /** - * Sets the delay before this Item is available to be picked up by players - * - * @param delay New delay - */ - public void setPickupDelay(int delay); - - // Paper Start - /** - * Gets if non-player entities can pick this Item up - * - * @return True if non-player entities can pickup - */ - public boolean canMobPickup(); - - /** - * Sets if non-player entities can pick this Item up - * - * @param canMobPickup True to allow non-player entity pickup - */ - public void setCanMobPickup(boolean canMobPickup); - - /** - * The owner of this item. Only the owner can pick up the item until it is within 10 seconds of despawning - * - * @return The owner's UUID - */ - @Nullable - public UUID getOwner(); - - /** - * Set the owner of this item. Only the owner can pick up the item until it is within 10 seconds of despawning - * - * @param owner The owner's UUID - */ - public void setOwner(@Nullable UUID owner); - - /** - * Get the thrower of this item. - * - * @return The thrower's UUID - */ - @Nullable - public UUID getThrower(); - - /** - * Set the thrower of this item. - * - * @param thrower The thrower's UUID - */ - public void setThrower(@Nullable UUID thrower); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/ItemFrame.java b/api/src/main/java/org/bukkit/entity/ItemFrame.java deleted file mode 100644 index e876bd20a..000000000 --- a/api/src/main/java/org/bukkit/entity/ItemFrame.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.Rotation; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @NotNull - public ItemStack getItem(); - - /** - * Set the item in this frame - * - * @param item the new item - */ - public void setItem(@Nullable ItemStack item); - - /** - * Set the item in this frame - * - * @param item the new item - * @param playSound whether or not to play the item placement sound - */ - public void setItem(@Nullable ItemStack item, boolean playSound); - - /** - * Get the rotation of the frame's item - * - * @return the direction - */ - @NotNull - public Rotation getRotation(); - - /** - * Set the rotation of the frame's item - * - * @param rotation the new rotation - * @throws IllegalArgumentException if rotation is null - */ - public void setRotation(@NotNull Rotation rotation) throws IllegalArgumentException; -} diff --git a/api/src/main/java/org/bukkit/entity/LargeFireball.java b/api/src/main/java/org/bukkit/entity/LargeFireball.java deleted file mode 100644 index fc3a1093c..000000000 --- a/api/src/main/java/org/bukkit/entity/LargeFireball.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a large {@link Fireball} - */ -public interface LargeFireball extends Fireball { -} diff --git a/api/src/main/java/org/bukkit/entity/LeashHitch.java b/api/src/main/java/org/bukkit/entity/LeashHitch.java deleted file mode 100644 index 9ac04c182..000000000 --- a/api/src/main/java/org/bukkit/entity/LeashHitch.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Leash Hitch on a fence - */ -public interface LeashHitch extends Hanging { -} diff --git a/api/src/main/java/org/bukkit/entity/LightningStrike.java b/api/src/main/java/org/bukkit/entity/LightningStrike.java deleted file mode 100644 index 5904ed87a..000000000 --- a/api/src/main/java/org/bukkit/entity/LightningStrike.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents an instance of a lightning strike. May or may not do damage. - */ -public interface LightningStrike extends Entity { - - /** - * Returns whether the strike is an effect that does no damage. - * - * @return whether the strike is an effect - */ - public boolean isEffect(); - - // Spigot start - public 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." ); - } - } - - @NotNull - @Override - Spigot spigot(); - // Spigot end -} diff --git a/api/src/main/java/org/bukkit/entity/LingeringPotion.java b/api/src/main/java/org/bukkit/entity/LingeringPotion.java deleted file mode 100644 index f124b35ec..000000000 --- a/api/src/main/java/org/bukkit/entity/LingeringPotion.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a thrown lingering potion bottle - * - * @deprecated lingering status depends on only on the potion item. - */ -public interface LingeringPotion extends ThrownPotion { } diff --git a/api/src/main/java/org/bukkit/entity/LivingEntity.java b/api/src/main/java/org/bukkit/entity/LivingEntity.java deleted file mode 100644 index a78f390d7..000000000 --- a/api/src/main/java/org/bukkit/entity/LivingEntity.java +++ /dev/null @@ -1,684 +0,0 @@ -package org.bukkit.entity; - -import java.util.Collection; -import java.util.List; -import java.util.Set; -import org.bukkit.FluidCollisionMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.attribute.Attributable; -import org.bukkit.block.Block; -import org.bukkit.entity.memory.MemoryKey; -import org.bukkit.inventory.EntityEquipment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.projectiles.ProjectileSource; -import org.bukkit.util.RayTraceResult; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a living entity, such as a monster or player - */ -public interface LivingEntity extends Attributable, 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 - */ - public double getEyeHeight(); - - /** - * Gets the height of the living entity's eyes above its Location. - * - * @param ignorePose if set to true, the effects of pose changes, eg - * sneaking and gliding will be ignored - * @return height of the living entity's eyes above its location - */ - public double getEyeHeight(boolean ignorePose); - - /** - * Get a Location detailing the current eye position of the living entity. - * - * @return a location at the eyes of the living entity - */ - @NotNull - public 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. This method considers all blocks as 1x1x1 in size. - * - * @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 - */ - @NotNull - public List getLineOfSight(@Nullable Set transparent, int maxDistance); - - /** - * Gets the block that the living entity has targeted. - *

- * This method considers all blocks as 1x1x1 in size. To take exact block - * collision shapes into account, see {@link #getTargetBlockExact(int, - * FluidCollisionMode)}. - * - * @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 - */ - @NotNull - public Block getTargetBlock(@Nullable Set transparent, int maxDistance); - - // Paper start - /** - * Gets the block that the living entity has targeted, ignoring fluids - * - * @param maxDistance this is the maximum distance to scan - * @return block that the living entity has targeted, - * or null if no block is within maxDistance - */ - @Nullable - public default Block getTargetBlock(int maxDistance) { - return getTargetBlock(maxDistance, com.destroystokyo.paper.block.TargetBlockInfo.FluidMode.NEVER); - } - - /** - * Gets the block that the living entity has targeted - * - * @param maxDistance this is the maximum distance to scan - * @param fluidMode whether to check fluids or not - * @return block that the living entity has targeted, - * or null if no block is within maxDistance - */ - @Nullable - public Block getTargetBlock(int maxDistance, @NotNull com.destroystokyo.paper.block.TargetBlockInfo.FluidMode fluidMode); - - /** - * Gets the blockface of that block that the living entity has targeted, ignoring fluids - * - * @param maxDistance this is the maximum distance to scan - * @return blockface of the block that the living entity has targeted, - * or null if no block is targeted - */ - @Nullable - public default org.bukkit.block.BlockFace getTargetBlockFace(int maxDistance) { - return getTargetBlockFace(maxDistance, com.destroystokyo.paper.block.TargetBlockInfo.FluidMode.NEVER); - } - - /** - * Gets the blockface of that block that the living entity has targeted - * - * @param maxDistance this is the maximum distance to scan - * @param fluidMode whether to check fluids or not - * @return blockface of the block that the living entity has targeted, - * or null if no block is targeted - */ - @Nullable - public org.bukkit.block.BlockFace getTargetBlockFace(int maxDistance, @NotNull com.destroystokyo.paper.block.TargetBlockInfo.FluidMode fluidMode); - - /** - * Gets information about the block the living entity has targeted, ignoring fluids - * - * @param maxDistance this is the maximum distance to scan - * @return TargetBlockInfo about the block the living entity has targeted, - * or null if no block is targeted - */ - @Nullable - public default com.destroystokyo.paper.block.TargetBlockInfo getTargetBlockInfo(int maxDistance) { - return getTargetBlockInfo(maxDistance, com.destroystokyo.paper.block.TargetBlockInfo.FluidMode.NEVER); - } - - /** - * Gets information about the block the living entity has targeted - * - * @param maxDistance this is the maximum distance to scan - * @param fluidMode whether to check fluids or not - * @return TargetBlockInfo about the block the living entity has targeted, - * or null if no block is targeted - */ - @Nullable - public com.destroystokyo.paper.block.TargetBlockInfo getTargetBlockInfo(int maxDistance, @NotNull com.destroystokyo.paper.block.TargetBlockInfo.FluidMode fluidMode); - - /** - * Gets information about the entity being targeted - * - * @param maxDistance this is the maximum distance to scan - * @return entity being targeted, or null if no entity is targeted - */ - @Nullable - public default Entity getTargetEntity(int maxDistance) { - return getTargetEntity(maxDistance, false); - } - - /** - * Gets information about the entity being targeted - * - * @param maxDistance this is the maximum distance to scan - * @param ignoreBlocks true to scan through blocks - * @return entity being targeted, or null if no entity is targeted - */ - @Nullable - public Entity getTargetEntity(int maxDistance, boolean ignoreBlocks); - - /** - * Gets information about the entity being targeted - * - * @param maxDistance this is the maximum distance to scan - * @return TargetEntityInfo about the entity being targeted, - * or null if no entity is targeted - */ - @Nullable - public default com.destroystokyo.paper.entity.TargetEntityInfo getTargetEntityInfo(int maxDistance) { - return getTargetEntityInfo(maxDistance, false); - } - - /** - * Gets information about the entity being targeted - * - * @param maxDistance this is the maximum distance to scan - * @param ignoreBlocks true to scan through blocks - * @return TargetEntityInfo about the entity being targeted, - * or null if no entity is targeted - */ - @Nullable - public com.destroystokyo.paper.entity.TargetEntityInfo getTargetEntityInfo(int maxDistance, boolean ignoreBlocks); - // Paper end - - /** - * Gets the last two blocks along the living entity's line of sight. - *

- * The target block will be the last block in the list. This method - * considers all blocks as 1x1x1 in size. - * - * @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 - */ - @NotNull - public List getLastTwoTargetBlocks(@Nullable Set transparent, int maxDistance); - - /** - * Gets the block that the living entity has targeted. - *

- * This takes the blocks' precise collision shapes into account. Fluids are - * ignored. - *

- * This may cause loading of chunks! Some implementations may impose - * artificial restrictions on the maximum distance. - * - * @param maxDistance the maximum distance to scan - * @return block that the living entity has targeted - * @see #getTargetBlockExact(int, org.bukkit.FluidCollisionMode) - */ - @Nullable - public Block getTargetBlockExact(int maxDistance); - - /** - * Gets the block that the living entity has targeted. - *

- * This takes the blocks' precise collision shapes into account. - *

- * This may cause loading of chunks! Some implementations may impose - * artificial restrictions on the maximum distance. - * - * @param maxDistance the maximum distance to scan - * @param fluidCollisionMode the fluid collision mode - * @return block that the living entity has targeted - * @see #rayTraceBlocks(double, FluidCollisionMode) - */ - @Nullable - public Block getTargetBlockExact(int maxDistance, @NotNull FluidCollisionMode fluidCollisionMode); - - /** - * Performs a ray trace that provides information on the targeted block. - *

- * This takes the blocks' precise collision shapes into account. Fluids are - * ignored. - *

- * This may cause loading of chunks! Some implementations may impose - * artificial restrictions on the maximum distance. - * - * @param maxDistance the maximum distance to scan - * @return information on the targeted block, or null if there - * is no targeted block in range - * @see #rayTraceBlocks(double, FluidCollisionMode) - */ - @Nullable - public RayTraceResult rayTraceBlocks(double maxDistance); - - /** - * Performs a ray trace that provides information on the targeted block. - *

- * This takes the blocks' precise collision shapes into account. - *

- * This may cause loading of chunks! Some implementations may impose - * artificial restrictions on the maximum distance. - * - * @param maxDistance the maximum distance to scan - * @param fluidCollisionMode the fluid collision mode - * @return information on the targeted block, or null if there - * is no targeted block in range - * @see World#rayTraceBlocks(Location, Vector, double, FluidCollisionMode) - */ - @Nullable - public RayTraceResult rayTraceBlocks(double maxDistance, @NotNull FluidCollisionMode fluidCollisionMode); - - /** - * Returns the amount of air that the living entity has remaining, in - * ticks. - * - * @return amount of air remaining - */ - public int getRemainingAir(); - - /** - * Sets the amount of air that the living entity has remaining, in ticks. - * - * @param ticks amount of air remaining - */ - public void setRemainingAir(int ticks); - - /** - * Returns the maximum amount of air the living entity can have, in ticks. - * - * @return maximum amount of air - */ - public int getMaximumAir(); - - /** - * Sets the maximum amount of air the living entity can have, in ticks. - * - * @param ticks maximum amount of air - */ - public 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 - */ - public int getMaximumNoDamageTicks(); - - /** - * Sets the living entity's current maximum no damage ticks. - * - * @param ticks maximum amount of no damage ticks - */ - public 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 - */ - public double getLastDamage(); - - /** - * Sets the damage dealt within the current no damage ticks time period. - * - * @param damage amount of damage - */ - public void setLastDamage(double damage); - - /** - * Returns the living entity's current no damage ticks. - * - * @return amount of no damage ticks - */ - public int getNoDamageTicks(); - - /** - * Sets the living entity's current no damage ticks. - * - * @param ticks amount of no damage ticks - */ - public 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 - */ - @Nullable - public Player getKiller(); - - // Paper start - /** - * Sets the player identified as the killer of the living entity. - * - * @param killer player - */ - public void setKiller(@Nullable Player killer); - // Paper end - - /** - * Adds the given {@link PotionEffect} to the living entity. - *

- * Only one potion effect can be present for a given {@link - * PotionEffectType}. - * - * @param effect PotionEffect to be added - * @return whether the effect could be added - */ - public boolean addPotionEffect(@NotNull PotionEffect effect); - - /** - * Adds the given {@link PotionEffect} to the living entity. - *

- * Only one potion effect can be present for a given {@link - * PotionEffectType}. - * - * @param effect PotionEffect to be added - * @param force whether conflicting effects should be removed - * @return whether the effect could be added - */ - public boolean addPotionEffect(@NotNull PotionEffect effect, boolean force); - - /** - * Attempts to add all of the given {@link PotionEffect} to the living - * entity. - * - * @param effects the effects to add - * @return whether all of the effects could be added - */ - public boolean addPotionEffects(@NotNull Collection effects); - - /** - * Returns whether the living entity already has an existing effect of - * the given {@link PotionEffectType} applied to it. - * - * @param type the potion type to check - * @return whether the living entity has this potion effect active on them - */ - public boolean hasPotionEffect(@NotNull PotionEffectType type); - - /** - * Returns the active {@link PotionEffect} of the specified type. - *

- * If the effect is not present on the entity then null will be returned. - * - * @param type the potion type to check - * @return the effect active on this entity, or null if not active. - */ - @Nullable - public PotionEffect getPotionEffect(@NotNull PotionEffectType type); - - /** - * Removes any effects present of the given {@link PotionEffectType}. - * - * @param type the potion type to remove - */ - public void removePotionEffect(@NotNull PotionEffectType type); - - /** - * Returns all currently active {@link PotionEffect}s on the living - * entity. - * - * @return a collection of {@link PotionEffect}s - */ - @NotNull - public 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 - */ - public boolean hasLineOfSight(@NotNull 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 - */ - public boolean getRemoveWhenFarAway(); - - /** - * Sets whether or not the living entity despawns when away from players - * or not. - * - * @param remove the removal status - */ - public void setRemoveWhenFarAway(boolean remove); - - /** - * Gets the inventory with the equipment worn by the living entity. - * - * @return the living entity's inventory - */ - @Nullable - public EntityEquipment getEquipment(); - - /** - * Sets whether or not the living entity can pick up items. - * - * @param pickup whether or not the living entity can pick up items - */ - public void setCanPickupItems(boolean pickup); - - /** - * Gets if the living entity can pick up items. - * - * @return whether or not the living entity can pick up items - */ - public boolean getCanPickupItems(); - - /** - * Returns whether the entity is currently leashed. - * - * @return whether the entity is leashed - */ - public boolean isLeashed(); - - /** - * Gets the entity that is currently leading this entity. - * - * @return the entity holding the leash - * @throws IllegalStateException if not currently leashed - */ - @NotNull - public 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, or null to unleash - * @return whether the operation was successful - */ - public boolean setLeashHolder(@Nullable Entity holder); - - /** - * Checks to see if an entity is gliding, such as using an Elytra. - * @return True if this entity is gliding. - */ - public boolean isGliding(); - - /** - * Makes entity start or stop gliding. This will work even if an Elytra - * is not equipped, but will be reverted by the server immediately after - * unless an event-cancelling mechanism is put in place. - * @param gliding True if the entity is gliding. - */ - public void setGliding(boolean gliding); - - /** - * Checks to see if an entity is swimming. - * - * @return True if this entity is swimming. - */ - public boolean isSwimming(); - - /** - * Makes entity start or stop swimming. - * - * This may have unexpected results if the entity is not in water. - * - * @param swimming True if the entity is swimming. - */ - public void setSwimming(boolean swimming); - - /** - * Checks to see if an entity is currently using the Riptide enchantment. - * - * @return True if this entity is currently riptiding. - */ - public boolean isRiptiding(); - - /** - * Returns whether this entity is slumbering. - * - * @return slumber state - */ - public boolean isSleeping(); - - /** - * Sets whether an entity will have AI. - * - * @param ai whether the mob will have AI or not. - */ - void setAI(boolean ai); - - /** - * Checks whether an entity has AI. - * - * @return true if the entity has AI, otherwise false. - */ - boolean hasAI(); - - /** - * Set if this entity will be subject to collisions other entities. - *

- * Note that collisions are bidirectional, so this method would need to be - * set to false on both the collidee and the collidant to ensure no - * collisions take place. - * - * @param collidable collision status - */ - void setCollidable(boolean collidable); - - /** - * Gets if this entity is subject to collisions with other entities. - *

- * Please note that this method returns only the custom collidable state, - * not whether the entity is non-collidable for other reasons such as being - * dead. - * - * @return collision status - */ - boolean isCollidable(); - - /** - * Returns the value of the memory specified. - *

- * Note that the value is null when the specific entity does not have that - * value by default. - * - * @param memoryKey memory to access - * @param the type of the return value - * @return a instance of the memory section value or null if not present - */ - @Nullable - T getMemory(@NotNull MemoryKey memoryKey); - - /** - * Sets the value of the memory specified. - *

- * Note that the value will not be persisted when the specific entity does - * not have that value by default. - * - * @param memoryKey the memory to access - * @param memoryValue a typed memory value - * @param the type of the passed value - */ - void setMemory(@NotNull MemoryKey memoryKey, @Nullable T memoryValue); - - // Paper start - /** - * Get the number of arrows stuck in this entity - * @return Number of arrows stuck - */ - int getArrowsStuck(); - - /** - * Set the number of arrows stuck in this entity - * - * @param arrows Number of arrows to stick in this entity - */ - void setArrowsStuck(int arrows); - - /** - * Get the delay (in ticks) before blocking is effective for this entity - * - * @return Delay in ticks - */ - int getShieldBlockingDelay(); - - /** - * Set the delay (in ticks) before blocking is effective for this entity - * - * @param delay Delay in ticks - */ - void setShieldBlockingDelay(int delay); - - /** - * Get's the item being actively "used" or consumed. - * @return The item. Will be null if no active item. - */ - @Nullable - ItemStack getActiveItem(); - - /** - * Get's remaining time a player needs to keep hands raised with an item to finish using it. - * @return Remaining ticks to use the item - */ - int getItemUseRemainingTime(); - - /** - * Get how long the players hands have been raised (Charging Bow attack, using a potion, etc) - * - * @return Get how long the players hands have been raised (Charging Bow attack, using a potion, etc) - */ - int getHandRaisedTime(); - - /** - * Whether or not this entity is using or charging an attack (Bow pulled back, drinking potion, eating food) - * - * @return Whether or not this entity is using or charging an attack (Bow pulled back, drinking potion, eating food) - */ - boolean isHandRaised(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Llama.java b/api/src/main/java/org/bukkit/entity/Llama.java deleted file mode 100644 index d23226ccb..000000000 --- a/api/src/main/java/org/bukkit/entity/Llama.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.bukkit.entity; - -import com.destroystokyo.paper.entity.RangedEntity; -import org.bukkit.inventory.LlamaInventory; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Llama. - */ -public interface Llama extends ChestedHorse, RangedEntity { // Paper - - /** - * Represents the base color that the llama has. - */ - public enum Color { - - /** - * A cream-colored llama. - */ - CREAMY, - /** - * A white llama. - */ - WHITE, - /** - * A brown llama. - */ - BROWN, - /** - * A gray llama. - */ - GRAY; - } - - /** - * Gets the llama's color. - * - * @return a {@link Color} representing the llama's color - */ - @NotNull - Color getColor(); - - /** - * Sets the llama's color. - * - * @param color a {@link Color} for this llama - */ - void setColor(@NotNull Color color); - - /** - * Gets the llama's strength. A higher strength llama will have more - * inventory slots and be more threatening to entities. - * - * @return llama strength [1,5] - */ - int getStrength(); - - /** - * Sets the llama's strength. A higher strength llama will have more - * inventory slots and be more threatening to entities. Inventory slots are - * equal to strength * 3. - * - * @param strength llama strength [1,5] - */ - void setStrength(int strength); - - @NotNull - @Override - LlamaInventory getInventory(); -} diff --git a/api/src/main/java/org/bukkit/entity/LlamaSpit.java b/api/src/main/java/org/bukkit/entity/LlamaSpit.java deleted file mode 100644 index 9890dffe7..000000000 --- a/api/src/main/java/org/bukkit/entity/LlamaSpit.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents Llama spit. - */ -public interface LlamaSpit extends Projectile { } diff --git a/api/src/main/java/org/bukkit/entity/MagmaCube.java b/api/src/main/java/org/bukkit/entity/MagmaCube.java deleted file mode 100644 index 714b4426d..000000000 --- a/api/src/main/java/org/bukkit/entity/MagmaCube.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a MagmaCube. - */ -public interface MagmaCube extends Slime { -} diff --git a/api/src/main/java/org/bukkit/entity/Minecart.java b/api/src/main/java/org/bukkit/entity/Minecart.java deleted file mode 100644 index 95c79c5fa..000000000 --- a/api/src/main/java/org/bukkit/entity/Minecart.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.block.data.BlockData; -import org.bukkit.material.MaterialData; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a minecart entity. - */ -public interface Minecart extends Vehicle { - - /** - * Sets a minecart's damage. - * - * @param damage over 40 to "kill" a minecart - */ - public void setDamage(double damage); - - /** - * Gets a minecart's damage. - * - * @return The damage - */ - public double getDamage(); - - /** - * Gets the maximum speed of a minecart. The speed is unrelated to the - * velocity. - * - * @return The max speed - */ - public double getMaxSpeed(); - - /** - * Sets the maximum speed of a minecart. Must be nonnegative. Default is - * 0.4D. - * - * @param speed The max speed - */ - public void setMaxSpeed(double speed); - - /** - * Returns whether this minecart will slow down faster without a passenger - * occupying it - * - * @return Whether it decelerates faster - */ - public boolean isSlowWhenEmpty(); - - /** - * Sets whether this minecart will slow down faster without a passenger - * occupying it - * - * @param slow Whether it will decelerate faster - */ - public 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 - */ - @NotNull - public 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 - */ - public void setFlyingVelocityMod(@NotNull 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 - */ - @NotNull - public 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 - */ - public void setDerailedVelocityMod(@NotNull 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. - */ - public void setDisplayBlock(@Nullable 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. - */ - @NotNull - public MaterialData getDisplayBlock(); - - /** - * Sets the display block for this minecart. - * Passing a null value will set the minecart to have no display block. - * - * @param blockData the material to set as display block. - */ - public void setDisplayBlockData(@Nullable BlockData blockData); - - /** - * 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. - */ - @NotNull - public BlockData getDisplayBlockData(); - - /** - * Sets the offset of the display block. - * - * @param offset the block offset to set for this minecart. - */ - public void setDisplayBlockOffset(int offset); - - /** - * Gets the offset of the display block. - * - * @return the current block offset for this minecart. - */ - public int getDisplayBlockOffset(); -} diff --git a/api/src/main/java/org/bukkit/entity/Mob.java b/api/src/main/java/org/bukkit/entity/Mob.java deleted file mode 100644 index 784db447d..000000000 --- a/api/src/main/java/org/bukkit/entity/Mob.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.loot.Lootable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a Mob. Mobs are living entities with simple AI. - */ -public interface Mob extends LivingEntity, Lootable { - - // Paper start - /** - * Enables access to control the pathing of an Entity - * @return Pathfinding Manager for this entity - */ - @NotNull - com.destroystokyo.paper.entity.Pathfinder getPathfinder(); - - /** - * Check if this mob is exposed to daylight - * - * @return True if mob is exposed to daylight - */ - boolean isInDaylight(); - // Paper end - - /** - * Instructs this Mob 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 - */ - public void setTarget(@Nullable LivingEntity target); - - /** - * Gets the current target of this Mob - * - * @return Current target of this creature, or null if none exists - */ - @Nullable - public LivingEntity getTarget(); -} diff --git a/api/src/main/java/org/bukkit/entity/Monster.java b/api/src/main/java/org/bukkit/entity/Monster.java deleted file mode 100644 index fce2efd82..000000000 --- a/api/src/main/java/org/bukkit/entity/Monster.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Monster. - */ -public interface Monster extends Creature {} diff --git a/api/src/main/java/org/bukkit/entity/Mule.java b/api/src/main/java/org/bukkit/entity/Mule.java deleted file mode 100644 index 4f5efb36b..000000000 --- a/api/src/main/java/org/bukkit/entity/Mule.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Mule - variant of {@link ChestedHorse}. - */ -public interface Mule extends ChestedHorse { } diff --git a/api/src/main/java/org/bukkit/entity/MushroomCow.java b/api/src/main/java/org/bukkit/entity/MushroomCow.java deleted file mode 100644 index 939a3dbfc..000000000 --- a/api/src/main/java/org/bukkit/entity/MushroomCow.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents a mushroom {@link Cow} - */ -public interface MushroomCow extends Cow { - - /** - * Get the variant of this cow. - * - * @return cow variant - */ - @NotNull - public Variant getVariant(); - - /** - * Set the variant of this cow. - * - * @param variant cow variant - */ - public void setVariant(@NotNull Variant variant); - - /** - * Represents the variant of a cow - ie its color. - */ - public enum Variant { - /** - * Red mushroom cow. - */ - RED, - /** - * Brown mushroom cow. - */ - BROWN; - } -} diff --git a/api/src/main/java/org/bukkit/entity/NPC.java b/api/src/main/java/org/bukkit/entity/NPC.java deleted file mode 100644 index 0c6b175b5..000000000 --- a/api/src/main/java/org/bukkit/entity/NPC.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a non-player character - */ -public interface NPC extends Creature { - -} diff --git a/api/src/main/java/org/bukkit/entity/Ocelot.java b/api/src/main/java/org/bukkit/entity/Ocelot.java deleted file mode 100644 index c20b8e559..000000000 --- a/api/src/main/java/org/bukkit/entity/Ocelot.java +++ /dev/null @@ -1,76 +0,0 @@ - -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * A wild tameable cat - */ -public interface Ocelot extends Animals { - - /** - * Gets the current type of this cat. - * - * @return Type of the cat. - */ - @NotNull - public Type getCatType(); - - /** - * Sets the current type of this cat. - * - * @param type New type of this cat. - */ - public void setCatType(@NotNull Type type); - - /** - * Represents the various different cat types there are. - * - * @deprecated Cats are now a separate entity. - */ - @Deprecated - public 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; - } - } - - private 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 - @Nullable - public static Type getType(int id) { - return (id >= types.length) ? null : types[id]; - } - } -} diff --git a/api/src/main/java/org/bukkit/entity/Painting.java b/api/src/main/java/org/bukkit/entity/Painting.java deleted file mode 100644 index 19e958201..000000000 --- a/api/src/main/java/org/bukkit/entity/Painting.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.Art; -import org.bukkit.event.hanging.HangingBreakEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Painting. - */ -public interface Painting extends Hanging { - - /** - * Get the art on this painting - * - * @return The art - */ - @NotNull - public 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 - */ - public boolean setArt(@NotNull 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 HangingBreakEvent}. - * @return False if force was false and the new art won't fit at the - * painting's current location - */ - public boolean setArt(@NotNull Art art, boolean force); -} diff --git a/api/src/main/java/org/bukkit/entity/Panda.java b/api/src/main/java/org/bukkit/entity/Panda.java deleted file mode 100644 index a6a7429ed..000000000 --- a/api/src/main/java/org/bukkit/entity/Panda.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * Panda entity. - */ -public interface Panda extends Animals { - - /** - * Gets this Panda's main gene. - * - * @return main gene - */ - @NotNull - Gene getMainGene(); - - /** - * Sets this Panda's main gene. - * - * @param gene main gene - */ - void setMainGene(@NotNull Gene gene); - - /** - * Gets this Panda's hidden gene. - * - * @return hidden gene - */ - @NotNull - Gene getHiddenGene(); - - /** - * Sets this Panda's hidden gene. - * - * @param gene hidden gene - */ - void setHiddenGene(@NotNull Gene gene); - - public enum Gene { - - NORMAL(false), - LAZY(false), - WORRIED(false), - PLAYFUL(false), - BROWN(true), - WEAK(true), - AGGRESSIVE(false); - - private final boolean recessive; - - private Gene(boolean recessive) { - this.recessive = recessive; - } - - /** - * Gets whether this gene is recessive, i.e. required in both parents to - * propagate to children. - * - * @return recessive status - */ - public boolean isRecessive() { - return recessive; - } - } -} diff --git a/api/src/main/java/org/bukkit/entity/Parrot.java b/api/src/main/java/org/bukkit/entity/Parrot.java deleted file mode 100644 index 95d95cdcc..000000000 --- a/api/src/main/java/org/bukkit/entity/Parrot.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Parrot. - */ -public interface Parrot extends Animals, Tameable, Sittable { - - /** - * Get the variant of this parrot. - * - * @return parrot variant - */ - @NotNull - public Variant getVariant(); - - /** - * Set the variant of this parrot. - * - * @param variant parrot variant - */ - public void setVariant(@NotNull Variant variant); - - /** - * Represents the variant of a parrot - ie its color. - */ - public enum Variant { - /** - * Classic parrot - red with colored wingtips. - */ - RED, - /** - * Royal blue colored parrot. - */ - BLUE, - /** - * Green colored parrot. - */ - GREEN, - /** - * Cyan colored parrot. - */ - CYAN, - /** - * Gray colored parrot. - */ - GRAY; - } -} diff --git a/api/src/main/java/org/bukkit/entity/Phantom.java b/api/src/main/java/org/bukkit/entity/Phantom.java deleted file mode 100644 index ed4d417c2..000000000 --- a/api/src/main/java/org/bukkit/entity/Phantom.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a phantom. - */ -public interface Phantom extends Flying { - - /** - * @return The size of the phantom - */ - public int getSize(); - - /** - * @param sz The new size of the phantom. - */ - public void setSize(int sz); - - // Paper start - /** - * Get the UUID of the entity that caused this phantom to spawn - * - * @return UUID - */ - @Nullable - public java.util.UUID getSpawningEntity(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Pig.java b/api/src/main/java/org/bukkit/entity/Pig.java deleted file mode 100644 index 28f59f2c2..000000000 --- a/api/src/main/java/org/bukkit/entity/Pig.java +++ /dev/null @@ -1,21 +0,0 @@ -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. - */ - public boolean hasSaddle(); - - /** - * Sets if the pig has a saddle or not - * - * @param saddled set if the pig has a saddle or not. - */ - public void setSaddle(boolean saddled); -} diff --git a/api/src/main/java/org/bukkit/entity/PigZombie.java b/api/src/main/java/org/bukkit/entity/PigZombie.java deleted file mode 100644 index ae9eaaa8e..000000000 --- a/api/src/main/java/org/bukkit/entity/PigZombie.java +++ /dev/null @@ -1,60 +0,0 @@ -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(); - - /** - * Not applicable to this entity - * - * @return false - */ - @Override - public boolean isConverting(); - - /** - * Not applicable to this entity - * - * @return UnsuppotedOperationException - */ - @Override - public int getConversionTime(); - - /** - * Not applicable to this entity - * - * @param time unused - */ - @Override - public void setConversionTime(int time); -} diff --git a/api/src/main/java/org/bukkit/entity/Pillager.java b/api/src/main/java/org/bukkit/entity/Pillager.java deleted file mode 100644 index 9a2252fef..000000000 --- a/api/src/main/java/org/bukkit/entity/Pillager.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.inventory.InventoryHolder; - -/** - * Illager entity. - */ -public interface Pillager extends Illager, InventoryHolder { } diff --git a/api/src/main/java/org/bukkit/entity/Player.java b/api/src/main/java/org/bukkit/entity/Player.java deleted file mode 100644 index 8d8d89576..000000000 --- a/api/src/main/java/org/bukkit/entity/Player.java +++ /dev/null @@ -1,2099 +0,0 @@ -package org.bukkit.entity; - -import java.net.InetSocketAddress; -import java.util.Date; // Paper - -import com.destroystokyo.paper.Title; -import com.destroystokyo.paper.profile.PlayerProfile; -import org.bukkit.Achievement; -import org.bukkit.BanEntry; // Paper -import org.bukkit.BanList; // Paper -import org.bukkit.Bukkit; // Paper -import org.bukkit.DyeColor; -import org.bukkit.Effect; -import org.bukkit.GameMode; -import org.bukkit.Instrument; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Note; -import org.bukkit.OfflinePlayer; -import org.bukkit.Particle; -import org.bukkit.Sound; -import org.bukkit.SoundCategory; -import org.bukkit.Statistic; -import org.bukkit.WeatherType; -import org.bukkit.advancement.Advancement; -import org.bukkit.advancement.AdvancementProgress; -import org.bukkit.block.data.BlockData; -import org.bukkit.conversations.Conversable; -import org.bukkit.event.player.PlayerResourcePackStatusEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.map.MapView; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.messaging.PluginMessageRecipient; -import org.bukkit.scoreboard.Scoreboard; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a player, connected or not - */ -public interface Player extends HumanEntity, Conversable, OfflinePlayer, PluginMessageRecipient, com.destroystokyo.paper.network.NetworkClient { // Paper - Extend NetworkClient - - /** - * 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 - */ - @NotNull - public String getDisplayName(); - - /** - * 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. - */ - public void setDisplayName(@Nullable String name); - - /** - * Gets the name that is shown on the player list. - * - * @return the player list name - */ - @NotNull - public String getPlayerListName(); - - /** - * Sets the name that is shown on the in-game player list. - *

- * If the value is null, the name will be identical to {@link #getName()}. - * - * @param name new player list name - */ - public void setPlayerListName(@Nullable String name); - - /** - * Gets the currently displayed player list header for this player. - * - * @return player list header or null - */ - @Nullable - public String getPlayerListHeader(); - - /** - * Gets the currently displayed player list footer for this player. - * - * @return player list header or null - */ - @Nullable - public String getPlayerListFooter(); - - /** - * Sets the currently displayed player list header for this player. - * - * @param header player list header, null for empty - */ - public void setPlayerListHeader(@Nullable String header); - - /** - * Sets the currently displayed player list footer for this player. - * - * @param footer player list footer, null for empty - */ - public void setPlayerListFooter(@Nullable String footer); - - /** - * Sets the currently displayed player list header and footer for this - * player. - * - * @param header player list header, null for empty - * @param footer player list footer, null for empty - */ - public void setPlayerListHeaderFooter(@Nullable String header, @Nullable String footer); - - /** - * Set the target of the player's compass. - * - * @param loc Location to point to - */ - public void setCompassTarget(@NotNull Location loc); - - /** - * Get the previously set compass target. - * - * @return location of the target - */ - @NotNull - public Location getCompassTarget(); - - /** - * Gets the socket address of this player - * - * @return the player's address - */ - @Nullable - public InetSocketAddress getAddress(); - - /** - * Sends this sender a message raw - * - * @param message Message to be displayed - */ - @Override - public void sendRawMessage(@NotNull String message); - - /** - * Kicks player with custom kick message. - * - * @param message kick message - */ - public void kickPlayer(@Nullable String message); - - /** - * Says a message (or runs a command). - * - * @param msg message to print - */ - public void chat(@NotNull String msg); - - /** - * Makes the player perform the given command - * - * @param command Command to perform - * @return true if the command was successful, otherwise false - */ - public boolean performCommand(@NotNull String command); - - /** - * Returns if the player is in sneak mode - * - * @return true if player is in sneak mode - */ - public boolean isSneaking(); - - /** - * Sets the sneak mode the player - * - * @param sneak true if player should appear sneaking - */ - public void setSneaking(boolean sneak); - - /** - * Gets whether the player is sprinting or not. - * - * @return true if player is sprinting. - */ - public boolean isSprinting(); - - /** - * Sets whether the player is sprinting or not. - * - * @param sprinting true if the player should be sprinting - */ - public 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 - */ - public 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. - */ - public 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. - */ - public void setSleepingIgnored(boolean isSleeping); - - /** - * Returns whether the player is sleeping ignored. - * - * @return Whether player is ignoring sleep. - */ - public 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 - public void playNote(@NotNull 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 - */ - public void playNote(@NotNull Location loc, @NotNull Instrument instrument, @NotNull 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 - */ - public void playSound(@NotNull Location location, @NotNull 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 - */ - public void playSound(@NotNull Location location, @NotNull String 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. - * - * @param location The location to play the sound - * @param sound The sound to play - * @param category The category of the sound - * @param volume The volume of the sound - * @param pitch The pitch of the sound - */ - public void playSound(@NotNull Location location, @NotNull Sound sound, @NotNull SoundCategory category, 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 category The category of the sound - * @param volume the volume of the sound - * @param pitch the pitch of the sound - */ - public void playSound(@NotNull Location location, @NotNull String sound, @NotNull SoundCategory category, float volume, float pitch); - - /** - * Stop the specified sound from playing. - * - * @param sound the sound to stop - */ - public void stopSound(@NotNull Sound sound); - - /** - * Stop the specified sound from playing. - * - * @param sound the sound to stop - */ - public void stopSound(@NotNull String sound); - - /** - * Stop the specified sound from playing. - * - * @param sound the sound to stop - * @param category the category of the sound - */ - public void stopSound(@NotNull Sound sound, @Nullable SoundCategory category); - - /** - * Stop the specified sound from playing. - * - * @param sound the sound to stop - * @param category the category of the sound - */ - public void stopSound(@NotNull String sound, @Nullable SoundCategory category); - - /** - * 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 - public void playEffect(@NotNull Location loc, @NotNull 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 - */ - public void playEffect(@NotNull Location loc, @NotNull Effect effect, @Nullable 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 - public void sendBlockChange(@NotNull Location loc, @NotNull Material material, 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 block The new block - */ - public void sendBlockChange(@NotNull Location loc, @NotNull BlockData block); - - /** - * 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 - public boolean sendChunkChange(@NotNull Location loc, int sx, int sy, int sz, @NotNull 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(org.bukkit.Location, org.bukkit.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 - */ - public void sendSignChange(@NotNull Location loc, @Nullable String[] lines) throws IllegalArgumentException; - - - /** - * 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(org.bukkit.Location, org.bukkit.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 - * @param dyeColor the color of the sign - * @throws IllegalArgumentException if location is null - * @throws IllegalArgumentException if dyeColor is null - * @throws IllegalArgumentException if lines is non-null and has a length less than 4 - */ - public void sendSignChange(@NotNull Location loc, @Nullable String[] lines, @NotNull DyeColor dyeColor) 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 - */ - public void sendMap(@NotNull MapView map); - - // Paper start - /** - * Permanently Bans the Profile and IP address currently used by the player. - * - * @param reason Reason for ban - * @return Ban Entry - */ - // For reference, Bukkit defines this as nullable, while they impl isn't, we'll follow API. - @Nullable - public default BanEntry banPlayerFull(@Nullable String reason) { - return banPlayerFull(reason, null, null); - } - - /** - * Permanently Bans the Profile and IP address currently used by the player. - * - * @param reason Reason for ban - * @param source Source of ban, or null for default - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerFull(@Nullable String reason, @Nullable String source) { - return banPlayerFull(reason, null, source); - } - - /** - * Bans the Profile and IP address currently used by the player. - * - * @param reason Reason for Ban - * @param expires When to expire the ban - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerFull(@Nullable String reason, @Nullable Date expires) { - return banPlayerFull(reason, expires, null); - } - - /** - * Bans the Profile and IP address currently used by the player. - * - * @param reason Reason for Ban - * @param expires When to expire the ban - * @param source Source of the ban, or null for default - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerFull(@Nullable String reason, @Nullable Date expires, @Nullable String source) { - banPlayer(reason, expires, source); - return banPlayerIP(reason, expires, source, true); - } - - /** - * Permanently Bans the IP address currently used by the player. - * Does not ban the Profile, use {@link #banPlayerFull(String, Date, String)} - * - * @param reason Reason for ban - * @param kickPlayer Whether or not to kick the player afterwards - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerIP(@Nullable String reason, boolean kickPlayer) { - return banPlayerIP(reason, null, null, kickPlayer); - } - - /** - * Permanently Bans the IP address currently used by the player. - * Does not ban the Profile, use {@link #banPlayerFull(String, Date, String)} - * @param reason Reason for ban - * @param source Source of ban, or null for default - * @param kickPlayer Whether or not to kick the player afterwards - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerIP(@Nullable String reason, @Nullable String source, boolean kickPlayer) { - return banPlayerIP(reason, null, source, kickPlayer); - } - - /** - * Bans the IP address currently used by the player. - * Does not ban the Profile, use {@link #banPlayerFull(String, Date, String)} - * @param reason Reason for Ban - * @param expires When to expire the ban - * @param kickPlayer Whether or not to kick the player afterwards - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerIP(@Nullable String reason, @Nullable Date expires, boolean kickPlayer) { - return banPlayerIP(reason, expires, null, kickPlayer); - } - - /** - * Permanently Bans the IP address currently used by the player. - * Does not ban the Profile, use {@link #banPlayerFull(String, Date, String)} - * - * @param reason Reason for ban - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerIP(@Nullable String reason) { - return banPlayerIP(reason, null, null); - } - - /** - * Permanently Bans the IP address currently used by the player. - * Does not ban the Profile, use {@link #banPlayerFull(String, Date, String)} - * @param reason Reason for ban - * @param source Source of ban, or null for default - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerIP(@Nullable String reason, @Nullable String source) { - return banPlayerIP(reason, null, source); - } - - /** - * Bans the IP address currently used by the player. - * Does not ban the Profile, use {@link #banPlayerFull(String, Date, String)} - * @param reason Reason for Ban - * @param expires When to expire the ban - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerIP(@Nullable String reason, @Nullable Date expires) { - return banPlayerIP(reason, expires, null); - } - - /** - * Bans the IP address currently used by the player. - * Does not ban the Profile, use {@link #banPlayerFull(String, Date, String)} - * @param reason Reason for Ban - * @param expires When to expire the ban - * @param source Source of the banm or null for default - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerIP(@Nullable String reason, @Nullable Date expires, @Nullable String source) { - return banPlayerIP(reason, expires, source, true); - } - - /** - * Bans the IP address currently used by the player. - * Does not ban the Profile, use {@link #banPlayerFull(String, Date, String)} - * @param reason Reason for Ban - * @param expires When to expire the ban - * @param source Source of the banm or null for default - * @param kickPlayer if the targeted player should be kicked - * @return Ban Entry - */ - @Nullable - public default BanEntry banPlayerIP(@Nullable String reason, @Nullable Date expires, @Nullable String source, boolean kickPlayer) { - BanEntry banEntry = Bukkit.getServer().getBanList(BanList.Type.IP).addBan(getAddress().getAddress().getHostAddress(), reason, expires, source); - if (kickPlayer && isOnline()) { - getPlayer().kickPlayer(reason); - } - - return banEntry; - } - - /** - * Sends an Action Bar message to the client. - * - * Use Section symbols for legacy color codes to send formatting. - * - * @param message The message to send - */ - public void sendActionBar(@NotNull String message); - - /** - * Sends an Action Bar message to the client. - * - * Use supplied alternative character to the section symbol to represent legacy color codes. - * - * @param alternateChar Alternate symbol such as '&' - * @param message The message to send - */ - public void sendActionBar(char alternateChar, @NotNull String message); - - /** - * Sends the component to the player - * - * @param component the components to send - */ - @Override - public default void sendMessage(@NotNull net.md_5.bungee.api.chat.BaseComponent component) { - spigot().sendMessage(component); - } - - /** - * Sends an array of components as a single message to the player - * - * @param components the components to send - */ - @Override - public default void sendMessage(@NotNull net.md_5.bungee.api.chat.BaseComponent... components) { - spigot().sendMessage(components); - } - - /** - * Sends an array of components as a single message to the specified screen position of this player - * - * @deprecated This is unlikely the API you want to use. See {@link #sendActionBar(String)} for a more proper Action Bar API. This deprecated API may send unsafe items to the client. - * @param position the screen position - * @param components the components to send - */ - @Deprecated - public default void sendMessage(net.md_5.bungee.api.ChatMessageType position, net.md_5.bungee.api.chat.BaseComponent... components) { - spigot().sendMessage(position, 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 - */ - public void setPlayerListHeaderFooter(@Nullable net.md_5.bungee.api.chat.BaseComponent[] header, @Nullable 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 - */ - public void setPlayerListHeaderFooter(@Nullable net.md_5.bungee.api.chat.BaseComponent header, @Nullable 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 - public void setTitleTimes(int fadeInTicks, int stayTicks, int fadeOutTicks); - - /** - * Update the subtitle of titles displayed to the player - * - * @param subtitle Subtitle to set - * @deprecated Use {@link #updateTitle(Title)} - */ - @Deprecated - public void setSubtitle(net.md_5.bungee.api.chat.BaseComponent[] subtitle); - - /** - * Update the subtitle of titles displayed to the player - * - * @param subtitle Subtitle to set - * @deprecated Use {@link #updateTitle(Title)} - */ - @Deprecated - public 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 - * - * @param title Title to set - * @deprecated Use {@link #sendTitle(Title)} or {@link #updateTitle(Title)} - */ - @Deprecated - public void showTitle(@Nullable 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 - * - * @param title Title to set - * @deprecated Use {@link #sendTitle(Title)} or {@link #updateTitle(Title)} - */ - @Deprecated - public void showTitle(@Nullable 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 - public void showTitle(@Nullable net.md_5.bungee.api.chat.BaseComponent[] title, @Nullable 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 - public void showTitle(@Nullable net.md_5.bungee.api.chat.BaseComponent title, @Nullable 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(@NotNull 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(@NotNull Title title); - - /** - * Hide any title that is currently visible to the player - */ - public void hideTitle(); - // Paper end - - /** - * Forces an update of the player's entire inventory. - * - */ - //@Deprecated // Spigot - undeprecate - public 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 - * @deprecated future versions of Minecraft do not have achievements - */ - @Deprecated - public void awardAchievement(@NotNull 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 - * @deprecated future versions of Minecraft do not have achievements - */ - @Deprecated - public void removeAchievement(@NotNull 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 - * @deprecated future versions of Minecraft do not have achievements - */ - @Deprecated - public boolean hasAchievement(@NotNull 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 - */ - public void incrementStatistic(@NotNull 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 - */ - public void decrementStatistic(@NotNull 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 - */ - public void incrementStatistic(@NotNull 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 - */ - public void decrementStatistic(@NotNull 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 - */ - public void setStatistic(@NotNull 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 - */ - public int getStatistic(@NotNull 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 - */ - public void incrementStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void decrementStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public int getStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void incrementStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void decrementStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void setStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void incrementStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void decrementStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public int getStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void incrementStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void decrementStatistic(@NotNull Statistic statistic, @NotNull 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 - */ - public void setStatistic(@NotNull Statistic statistic, @NotNull 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. - */ - public void setPlayerTime(long time, boolean relative); - - /** - * Returns the player's current timestamp. - * - * @return The player's time - */ - public 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 - */ - public 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. - */ - public boolean isPlayerTimeRelative(); - - /** - * Restores the normal condition where the player's time is synchronized - * with the server time. - *

- * Equivalent to calling setPlayerTime(0, true). - */ - public 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 - */ - public void setPlayerWeather(@NotNull 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. - */ - @Nullable - public WeatherType getPlayerWeather(); - - /** - * Restores the normal condition where the player's weather is controlled - * by server conditions. - */ - public void resetPlayerWeather(); - - // Paper start - /** - * Gives the player the amount of experience specified. - * - * @param amount Exp amount to give - */ - public default void giveExp(int amount) { - giveExp(amount, false); - } - /** - * Gives the player the amount of experience specified. - * - * @param amount Exp amount to give - * @param applyMending Mend players items with mending, with same behavior as picking up orbs. calls {@link #applyMending(int)} - */ - public void giveExp(int amount, boolean applyMending); - - /** - * Applies the mending effect to any items just as picking up an orb would. - * - * Can also be called with {@link #giveExp(int, boolean)} by passing true to applyMending - * - * @param amount Exp to apply - * @return the remaining experience - */ - public int applyMending(int amount); - // Paper end - - /** - * 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 - */ - public 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 - */ - public 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 - */ - public void setExp(float exp); - - /** - * Gets the players current experience level - * - * @return Current experience level - */ - public int getLevel(); - - /** - * Sets the players current experience level - * - * @param level New experience level - */ - public void setLevel(int level); - - /** - * Gets the players total experience points. - *
- * This refers to the total amount of experience the player has collected - * over time and is only displayed as the player's "score" upon dying. - * - * @return Current total experience points - */ - public int getTotalExperience(); - - /** - * Sets the players current experience points. - *
- * This refers to the total amount of experience the player has collected - * over time and is only displayed as the player's "score" upon dying. - * - * @param exp New total experience points - */ - public 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 - */ - public float getExhaustion(); - - /** - * Sets the players current exhaustion level - * - * @param value Exhaustion level - */ - public 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 - */ - public float getSaturation(); - - /** - * Sets the players current saturation level - * - * @param value Saturation level - */ - public void setSaturation(float value); - - /** - * Gets the players current food level - * - * @return Food level - */ - public int getFoodLevel(); - - /** - * Sets the players current food level - * - * @param value New food level - */ - public void setFoodLevel(int value); - - /** - * 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. - */ - public 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. - */ - public void setAllowFlight(boolean flight); - - /** - * Hides a player from this player - * - * @param player Player to hide - * @deprecated see {@link #hidePlayer(Plugin, Player)} - */ - @Deprecated - public void hidePlayer(@NotNull Player player); - - /** - * Hides a player from this player - * - * @param plugin Plugin that wants to hide the player - * @param player Player to hide - */ - public void hidePlayer(@NotNull Plugin plugin, @NotNull Player player); - - /** - * Allows this player to see a player that was previously hidden - * - * @param player Player to show - * @deprecated see {@link #showPlayer(Plugin, Player)} - */ - @Deprecated - public void showPlayer(@NotNull Player player); - - /** - * Allows this player to see a player that was previously hidden. If - * another another plugin had hidden the player too, then the player will - * remain hidden until the other plugin calls this method too. - * - * @param plugin Plugin that wants to show the player - * @param player Player to show - */ - public void showPlayer(@NotNull Plugin plugin, @NotNull 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 - */ - public boolean canSee(@NotNull Player player); - - /** - * Checks to see if this player is currently flying or not. - * - * @return True if the player is flying, else false. - */ - public boolean isFlying(); - - /** - * Makes this player start or stop flying. - * - * @param value True to fly. - */ - public 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 - */ - public 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 - */ - public 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 - */ - public float getFlySpeed(); - - /** - * Gets the current allowed speed that a client can walk. - * - * @return The current allowed speed, from -1 to 1 - */ - public 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 file size check against - * the response content 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. Use the - * {@link PlayerResourcePackStatusEvent} to figure out whether or not - * the player loaded the pack! - *
  • There is no concept of resetting texture packs back to default - * within Minecraft, so players will have to relog to do so or you - * have to send an empty pack. - *
  • The request is send with "null" as the hash. This might result - * in newer versions not loading the pack correctly. - *
- * - * @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 - public void setTexturePack(@NotNull 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 file size check against - * the response content 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. Use the - * {@link PlayerResourcePackStatusEvent} to figure out whether or not - * the player loaded the pack! - *
  • There is no concept of resetting resource packs back to default - * within Minecraft, so players will have to relog to do so or you - * have to send an empty pack. - *
  • The request is send with "null" as the hash. This might result - * in newer versions not loading the pack correctly. - *
- * - * @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 {@link #setResourcePack(String, String)} - */ - @Deprecated // Paper - public void setResourcePack(@NotNull 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 a - * resource pack with the same hash in the past it will not download but - * directly apply the cached pack. 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. Use the - * {@link PlayerResourcePackStatusEvent} to figure out whether or not - * the player loaded the pack! - *
  • There is no concept of resetting resource packs back to default - * within Minecraft, so players will have to relog to do so or you - * have to send an empty pack. - *
- * - * @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. - * @param hash The sha1 hash sum of the resource pack file which is used - * to apply a cached version of the pack directly without downloading - * if it is available. Hast to be 20 bytes long! - * @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. - * @throws IllegalArgumentException Thrown if the hash is null. - * @throws IllegalArgumentException Thrown if the hash is not 20 bytes - * long. - */ - public void setResourcePack(@NotNull String url, @NotNull byte[] hash); - - /** - * Gets the Scoreboard displayed to this player - * - * @return The current scoreboard seen by this player - */ - @NotNull - public 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 - */ - public void setScoreboard(@NotNull 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) - */ - public 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 - */ - public 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 - */ - public 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) - */ - public 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. - */ - @Nullable - public 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} - */ - public void setSpectatorTarget(@Nullable 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. The titles will be displayed with the client's default timings. - * - * @param title Title text - * @param subtitle Subtitle text - * @deprecated API behavior subject to change - */ - @Deprecated - public void sendTitle(@Nullable String title, @Nullable String subtitle); - - /** - * 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. All timings values may take a value of -1 to indicate that they - * will use the last value sent (or the defaults if no title has been - * displayed). - * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeIn time in ticks for titles to fade in. Defaults to 10. - * @param stay time in ticks for titles to stay. Defaults to 70. - * @param fadeOut time in ticks for titles to fade out. Defaults to 20. - */ - public void sendTitle(@Nullable String title, @Nullable String subtitle, int fadeIn, int stay, int fadeOut); - - /** - * Resets the title displayed to the player. This will clear the displayed - * title / subtitle and reset timings to their default values. - */ - public void resetTitle(); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. - * - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. - * - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, @Nullable T data); - - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, @Nullable T data); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ, @Nullable T data); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, @Nullable T data); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ, double extra); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param location the location to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, @NotNull Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, @Nullable T data); - - /** - * Spawns the particle (the number of times specified by count) - * at the target location. The position of each particle will be - * randomized positively and negatively by the offset parameters - * on each axis. - * - * @param type of particle data (see {@link Particle#getDataType()} - * @param particle the particle to spawn - * @param x the position on the x axis to spawn at - * @param y the position on the y axis to spawn at - * @param z the position on the z axis to spawn at - * @param count the number of particles - * @param offsetX the maximum random offset on the X axis - * @param offsetY the maximum random offset on the Y axis - * @param offsetZ the maximum random offset on the Z axis - * @param extra the extra data for this particle, depends on the - * particle used (normally speed) - * @param data the data to use for the particle or null, - * the type of this depends on {@link Particle#getDataType()} - * @param Type - */ - public void spawnParticle(@NotNull Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, @Nullable T data); - - /** - * Return the player's progression on the specified advancement. - * - * @param advancement advancement - * @return object detailing the player's progress - */ - @NotNull - public AdvancementProgress getAdvancementProgress(@NotNull Advancement advancement); - - /** - * Get the player's current client side view distance. - *
- * Will default to the server view distance if the client has not yet - * communicated this information, - * - * @return client view distance as above - */ - public int getClientViewDistance(); - - /** - * Gets the player's current locale. - * - * The value of the locale String is not defined properly. - *
- * The vanilla Minecraft client will use lowercase language / country pairs - * separated by an underscore, but custom resource packs may use any format - * they wish. - * - * @return the player's locale - */ - @NotNull - public String getLocale(); - - // Paper start - /** - * Get whether the player can affect mob spawning - * - * @return if the player can affect mob spawning - */ - public boolean getAffectsSpawning(); - - /** - * Set whether the player can affect mob spawning - * - * @param affects Whether the player can affect mob spawning - */ - public void setAffectsSpawning(boolean affects); - - /** - * Gets the view distance for this player - * - * @return the player's view distance - */ - public int getViewDistance(); - - /** - * Sets the view distance for this player - * - * @param viewDistance the player's view distance - */ - public void setViewDistance(int viewDistance); - // Paper end - - /** - * Update the list of commands sent to the client. - *
- * Generally useful to ensure the client has a complete list of commands - * after permission changes are done. - */ - public void updateCommands(); - - /** - * Open a {@link Material#WRITTEN_BOOK} for a Player - * - * @param book The book to open for this player - */ - public void openBook(@NotNull ItemStack book); - - // Paper start - /** - * 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. - * @param hash A 40 character hexadecimal and lowercase SHA-1 digest of - * the resource pack file. - * @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. - */ - void setResourcePack(@NotNull String url, @NotNull String hash); - - /** - * @return the most recent resource pack status received from the player, - * or null if no status has ever been received from this player. - */ - @Nullable - org.bukkit.event.player.PlayerResourcePackStatusEvent.Status getResourcePackStatus(); - - /** - * @return the most recent resource pack hash received from the player, - * or null if no hash has ever been received from this player. - * - * @deprecated This is no longer sent from the client and will always be null - */ - @Nullable - @Deprecated - String getResourcePackHash(); - - /** - * @return true if the last resource pack status received from this player - * was {@link org.bukkit.event.player.PlayerResourcePackStatusEvent.Status#SUCCESSFULLY_LOADED} - */ - boolean hasResourcePack(); - - /** - * Gets a copy of this players profile - * @return The players profile object - */ - @NotNull - PlayerProfile getPlayerProfile(); - - /** - * Changes the PlayerProfile for this player. This will cause this player - * to be reregistered to all clients that can currently see this player - * @param profile The new profile to use - */ - void setPlayerProfile(@NotNull PlayerProfile profile); - - /** - * Returns the amount of ticks the current cooldown lasts - * - * @return Amount of ticks cooldown will last - */ - float getCooldownPeriod(); - - /** - * Returns the percentage of attack power available based on the cooldown (zero to one). - * - * @param adjustTicks Amount of ticks to add to cooldown counter for this calculation - * @return Percentage of attack power available - */ - float getCooledAttackStrength(float adjustTicks); - - /** - * Reset the cooldown counter to 0, effectively starting the cooldown period. - */ - void resetCooldown(); - // Paper end - - // Spigot start - public 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 - */ - @NotNull - public InetSocketAddress getRawAddress() - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - - /** - * Gets whether the player collides with entities - * - * @return the player's collision toggle state - * @deprecated see {@link LivingEntity#isCollidable()} - */ - @Deprecated - 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. - * @deprecated {@link LivingEntity#setCollidable(boolean)} - */ - @Deprecated - 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 - * @deprecated Use {@link Player#getLocale()} - */ - @Deprecated - @NotNull - public String getLocale() - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - - /** - * Gets all players hidden with {@link #hidePlayer(org.bukkit.entity.Player)}. - * - * @return a Set with all hidden players - */ - @NotNull - public java.util.Set getHiddenPlayers() - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - - @Override - public void sendMessage(@NotNull net.md_5.bungee.api.chat.BaseComponent component) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendMessage(@NotNull net.md_5.bungee.api.chat.BaseComponent... components) { - throw new UnsupportedOperationException("Not supported yet."); - } - - /** - * Sends the component to the specified screen position of this player - * - * @deprecated This is unlikely the API you want to use. See {@link #sendActionBar(String)} for a more proper Action Bar API. This deprecated API may send unsafe items to the client. - * @param position the screen position - * @param component the components to send - */ - @Deprecated - public void sendMessage(@NotNull net.md_5.bungee.api.ChatMessageType position, @NotNull 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 specified screen position of this player - * - * @deprecated This is unlikely the API you want to use. See {@link #sendActionBar(String)} for a more proper Action Bar API. This deprecated API may send unsafe items to the client. - * @param position the screen position - * @param components the components to send - */ - @Deprecated - public void sendMessage(@NotNull net.md_5.bungee.api.ChatMessageType position, @NotNull net.md_5.bungee.api.chat.BaseComponent... components) { - throw new UnsupportedOperationException("Not supported yet."); - } - - public int getPing() - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - } - - @NotNull - @Override - Spigot spigot(); - // Spigot end -} diff --git a/api/src/main/java/org/bukkit/entity/PolarBear.java b/api/src/main/java/org/bukkit/entity/PolarBear.java deleted file mode 100644 index 479f7a7c5..000000000 --- a/api/src/main/java/org/bukkit/entity/PolarBear.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a polar bear. - */ -public interface PolarBear extends Animals {} diff --git a/api/src/main/java/org/bukkit/entity/Pose.java b/api/src/main/java/org/bukkit/entity/Pose.java deleted file mode 100644 index b6e0c6f53..000000000 --- a/api/src/main/java/org/bukkit/entity/Pose.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents an entity body pose. - */ -public enum Pose { - - /** - * Entity is standing normally. - * - */ - STANDING, - /** - * Entity is gliding. - */ - FALL_FLYING, - /** - * Entity is sleeping. - */ - SLEEPING, - /** - * Entity is swimming. - */ - SWIMMING, - /** - * Entity is riptiding with a trident. - */ - SPIN_ATTACK, - /** - * Entity is sneaking. - */ - SNEAKING, - /** - * Entity is dead. - */ - DYING; -} diff --git a/api/src/main/java/org/bukkit/entity/Projectile.java b/api/src/main/java/org/bukkit/entity/Projectile.java deleted file mode 100644 index c854860c1..000000000 --- a/api/src/main/java/org/bukkit/entity/Projectile.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.projectiles.ProjectileSource; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a shootable entity. - */ -public interface Projectile extends Entity { - - /** - * Retrieve the shooter of this projectile. - * - * @return the {@link ProjectileSource} that shot this projectile - */ - @Nullable - public ProjectileSource getShooter(); - - /** - * Set the shooter of this projectile. - * - * @param source the {@link ProjectileSource} that shot this projectile - */ - public void setShooter(@Nullable 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. - */ - public boolean doesBounce(); - - /** - * Set whether or not this projectile should bounce or not when it hits - * something. - * - * @param doesBounce whether or not it should bounce. - */ - public void setBounce(boolean doesBounce); -} diff --git a/api/src/main/java/org/bukkit/entity/PufferFish.java b/api/src/main/java/org/bukkit/entity/PufferFish.java deleted file mode 100644 index 2d26c19b5..000000000 --- a/api/src/main/java/org/bukkit/entity/PufferFish.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a puffer fish. - */ -public interface PufferFish extends Fish { - - /** - * Returns the current puff state of this fish (i.e. how inflated it is). - * - * @return current puff state - */ - int getPuffState(); - - /** - * Sets the current puff state of this fish (i.e. how inflated it is). - * - * @param state new puff state - */ - void setPuffState(int state); -} diff --git a/api/src/main/java/org/bukkit/entity/Rabbit.java b/api/src/main/java/org/bukkit/entity/Rabbit.java deleted file mode 100644 index e88154283..000000000 --- a/api/src/main/java/org/bukkit/entity/Rabbit.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -public interface Rabbit extends Animals { - - /** - * @return The type of rabbit. - */ - @NotNull - public Type getRabbitType(); - - /** - * @param type Sets the type of rabbit for this entity. - */ - public void setRabbitType(@NotNull Type type); - - /** - * Represents the various types a Rabbit might be. - */ - public 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/api/src/main/java/org/bukkit/entity/Raider.java b/api/src/main/java/org/bukkit/entity/Raider.java deleted file mode 100644 index ac73eaf36..000000000 --- a/api/src/main/java/org/bukkit/entity/Raider.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.block.Block; -import org.jetbrains.annotations.Nullable; - -public interface Raider extends Monster { - - /** - * Gets the block the raider is targeting to patrol. - * - * @return target block or null - */ - @Nullable - Block getPatrolTarget(); - - /** - * Sets the block the raider is targeting to patrol. - * - * @param block target block or null. Must be in same world as the entity - */ - void setPatrolTarget(@Nullable Block block); - - /** - * Gets whether this entity is a patrol leader. - * - * @return patrol leader status - */ - boolean isPatrolLeader(); - - /** - * Sets whether this entity is a patrol leader. - * - * @param leader patrol leader status - */ - void setPatrolLeader(boolean leader); -} diff --git a/api/src/main/java/org/bukkit/entity/Ravager.java b/api/src/main/java/org/bukkit/entity/Ravager.java deleted file mode 100644 index 4374d5206..000000000 --- a/api/src/main/java/org/bukkit/entity/Ravager.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Illager beast. - */ -public interface Ravager extends Raider { } diff --git a/api/src/main/java/org/bukkit/entity/Salmon.java b/api/src/main/java/org/bukkit/entity/Salmon.java deleted file mode 100644 index a52a7af21..000000000 --- a/api/src/main/java/org/bukkit/entity/Salmon.java +++ /dev/null @@ -1,7 +0,0 @@ - -package org.bukkit.entity; - -/** - * Represents a salmon fish. - */ -public interface Salmon extends Fish { } diff --git a/api/src/main/java/org/bukkit/entity/Sheep.java b/api/src/main/java/org/bukkit/entity/Sheep.java deleted file mode 100644 index f4ce312cc..000000000 --- a/api/src/main/java/org/bukkit/entity/Sheep.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.material.Colorable; - -/** - * Represents a Sheep. - */ -public interface Sheep extends Animals, Colorable { - - /** - * @return Whether the sheep is sheared. - */ - public boolean isSheared(); - - /** - * @param flag Whether to shear the sheep - */ - public void setSheared(boolean flag); -} diff --git a/api/src/main/java/org/bukkit/entity/Shulker.java b/api/src/main/java/org/bukkit/entity/Shulker.java deleted file mode 100644 index 3441bdb7f..000000000 --- a/api/src/main/java/org/bukkit/entity/Shulker.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.material.Colorable; - -public interface Shulker extends Golem, Colorable {} diff --git a/api/src/main/java/org/bukkit/entity/ShulkerBullet.java b/api/src/main/java/org/bukkit/entity/ShulkerBullet.java deleted file mode 100644 index 4623e0d76..000000000 --- a/api/src/main/java/org/bukkit/entity/ShulkerBullet.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.Nullable; - -public interface ShulkerBullet extends Projectile { - - /** - * Retrieve the target of this bullet. - * - * @return the targeted entity - */ - @Nullable - Entity getTarget(); - - /** - * Sets the target of this bullet - * - * @param target the entity to target - */ - void setTarget(@Nullable Entity target); -} diff --git a/api/src/main/java/org/bukkit/entity/Silverfish.java b/api/src/main/java/org/bukkit/entity/Silverfish.java deleted file mode 100644 index fe01007fb..000000000 --- a/api/src/main/java/org/bukkit/entity/Silverfish.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Silverfish. - */ -public interface Silverfish extends Monster {} diff --git a/api/src/main/java/org/bukkit/entity/Sittable.java b/api/src/main/java/org/bukkit/entity/Sittable.java deleted file mode 100644 index ea6ee26fc..000000000 --- a/api/src/main/java/org/bukkit/entity/Sittable.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.entity; - -/** - * An animal that can sit still. - */ -public interface Sittable { - - /** - * Checks if this animal is sitting - * - * @return true if sitting - */ - boolean isSitting(); - - /** - * Sets if this animal is sitting. Will remove any path that the animal - * was following beforehand. - * - * @param sitting true if sitting - */ - void setSitting(boolean sitting); - -} diff --git a/api/src/main/java/org/bukkit/entity/Skeleton.java b/api/src/main/java/org/bukkit/entity/Skeleton.java deleted file mode 100644 index 1c367f78e..000000000 --- a/api/src/main/java/org/bukkit/entity/Skeleton.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import com.destroystokyo.paper.entity.RangedEntity; - -/** - * Represents a Skeleton. - */ -public interface Skeleton extends Monster, RangedEntity { // Paper - - /** - * Gets the current type of this skeleton. - * - * @return Current type - * @deprecated should check what class instance this is - */ - @Deprecated - @NotNull - public SkeletonType getSkeletonType(); - - /** - * @param type type - * @deprecated Must spawn a new subtype variant - */ - @Deprecated - @Contract("_ -> fail") - public void setSkeletonType(SkeletonType type); - - /* - * @deprecated classes are different types - */ - @Deprecated - public enum SkeletonType { - - /** - * Standard skeleton type. - */ - NORMAL, - /** - * Wither skeleton. Generally found in Nether fortresses. - */ - WITHER, - /** - * Stray skeleton. Generally found in ice biomes. Shoots tipped arrows. - */ - STRAY; - } -} diff --git a/api/src/main/java/org/bukkit/entity/SkeletonHorse.java b/api/src/main/java/org/bukkit/entity/SkeletonHorse.java deleted file mode 100644 index ba9983463..000000000 --- a/api/src/main/java/org/bukkit/entity/SkeletonHorse.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a SkeletonHorse - variant of {@link AbstractHorse}. - */ -public interface SkeletonHorse extends AbstractHorse { - // Paper start - int getTrapTime(); - - boolean isTrap(); - - void setTrap(boolean trap); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Slime.java b/api/src/main/java/org/bukkit/entity/Slime.java deleted file mode 100644 index c4791f95d..000000000 --- a/api/src/main/java/org/bukkit/entity/Slime.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Slime. - */ -public interface Slime extends Mob { - - /** - * @return The size of the slime - */ - public int getSize(); - - /** - * @param sz The new size of the slime. - */ - public void setSize(int sz); - - // Paper start - /** - * Get whether this slime can randomly wander/jump around on its own - * - * @return true if can wander - */ - public boolean canWander(); - - /** - * Set whether this slime can randomly wander/jump around on its own - * - * @param canWander true if can wander - */ - public void setWander(boolean canWander); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/SmallFireball.java b/api/src/main/java/org/bukkit/entity/SmallFireball.java deleted file mode 100644 index 33f54d3ef..000000000 --- a/api/src/main/java/org/bukkit/entity/SmallFireball.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a small {@link Fireball} - */ -public interface SmallFireball extends Fireball { - -} diff --git a/api/src/main/java/org/bukkit/entity/Snowball.java b/api/src/main/java/org/bukkit/entity/Snowball.java deleted file mode 100644 index 8c6b43339..000000000 --- a/api/src/main/java/org/bukkit/entity/Snowball.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a snowball. - */ -public interface Snowball extends Projectile {} diff --git a/api/src/main/java/org/bukkit/entity/Snowman.java b/api/src/main/java/org/bukkit/entity/Snowman.java deleted file mode 100644 index 10f8f6d45..000000000 --- a/api/src/main/java/org/bukkit/entity/Snowman.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.entity; - -import com.destroystokyo.paper.entity.RangedEntity; - -/** - * Represents a snowman entity - */ -public interface Snowman extends Golem, RangedEntity { // Paper - - /** - * Gets whether this snowman is in "derp mode", meaning it is not wearing a - * pumpkin. - * - * @return True if the snowman is bald, false if it is wearing a pumpkin - */ - boolean isDerp(); - - /** - * Sets whether this snowman is in "derp mode", meaning it is not wearing a - * pumpkin. NOTE: This value is not persisted to disk and will therefore - * reset when the chunk is reloaded. - * - * @param derpMode True to remove the pumpkin, false to add a pumpkin - */ - void setDerp(boolean derpMode); -} diff --git a/api/src/main/java/org/bukkit/entity/SpectralArrow.java b/api/src/main/java/org/bukkit/entity/SpectralArrow.java deleted file mode 100644 index b02ec168b..000000000 --- a/api/src/main/java/org/bukkit/entity/SpectralArrow.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a spectral arrow. - */ -public interface SpectralArrow extends AbstractArrow { - - /** - * Returns the amount of time that this arrow will apply - * the glowing effect for. - * - * @return the glowing effect ticks - */ - int getGlowingTicks(); - - /** - * Sets the amount of time to apply the glowing effect for. - * - * @param duration the glowing effect ticks - */ - void setGlowingTicks(int duration); -} diff --git a/api/src/main/java/org/bukkit/entity/Spellcaster.java b/api/src/main/java/org/bukkit/entity/Spellcaster.java deleted file mode 100644 index d5c107d4f..000000000 --- a/api/src/main/java/org/bukkit/entity/Spellcaster.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents a spell casting "Illager". - */ -public interface Spellcaster extends Illager { - - /** - * Represents the current spell the entity is using. - */ - public enum Spell { - - /** - * No spell is being used.. - */ - NONE, - /** - * The spell that summons Vexes. - */ - SUMMON_VEX, - /** - * The spell that summons Fangs. - */ - FANGS, - /** - * The "wololo" spell. - */ - WOLOLO, - /** - * The spell that makes the casting entity invisible. - */ - DISAPPEAR, - /** - * The spell that makes the target blind. - */ - BLINDNESS; - } - - /** - * Gets the {@link Spell} the entity is currently using. - * - * @return the current spell - */ - @NotNull - Spell getSpell(); - - /** - * Sets the {@link Spell} the entity is currently using. - * - * @param spell the spell the entity should be using - */ - void setSpell(@NotNull Spell spell); -} diff --git a/api/src/main/java/org/bukkit/entity/Spider.java b/api/src/main/java/org/bukkit/entity/Spider.java deleted file mode 100644 index f9ee8cc75..000000000 --- a/api/src/main/java/org/bukkit/entity/Spider.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Spider. - */ -public interface Spider extends Monster {} diff --git a/api/src/main/java/org/bukkit/entity/SplashPotion.java b/api/src/main/java/org/bukkit/entity/SplashPotion.java deleted file mode 100644 index 9cb08fe72..000000000 --- a/api/src/main/java/org/bukkit/entity/SplashPotion.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a thrown splash potion bottle - * - * @deprecated splash status depends on only on the potion item. - */ -@Deprecated -public interface SplashPotion extends ThrownPotion { } diff --git a/api/src/main/java/org/bukkit/entity/Squid.java b/api/src/main/java/org/bukkit/entity/Squid.java deleted file mode 100644 index fb47968ef..000000000 --- a/api/src/main/java/org/bukkit/entity/Squid.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Squid. - */ -public interface Squid extends WaterMob {} diff --git a/api/src/main/java/org/bukkit/entity/Stray.java b/api/src/main/java/org/bukkit/entity/Stray.java deleted file mode 100644 index 9c83f98e9..000000000 --- a/api/src/main/java/org/bukkit/entity/Stray.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Stray - variant of {@link Skeleton}. - */ -public interface Stray extends Skeleton { } diff --git a/api/src/main/java/org/bukkit/entity/TNTPrimed.java b/api/src/main/java/org/bukkit/entity/TNTPrimed.java deleted file mode 100644 index 3022b4a27..000000000 --- a/api/src/main/java/org/bukkit/entity/TNTPrimed.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.Location; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - public 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 - */ - public 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. The source entity may be invalid if for example - * it has since died or been unloaded. Callers should check - * {@link Entity#isValid()}. - * - * @return the source of this primed TNT - */ - @Nullable - public Entity getSource(); - - /** - * Gets the source block location of the TNTPrimed - * - * @return the source block location the TNTPrimed was spawned from - * @deprecated replaced by {@link Entity#getOrigin()} - */ - @Deprecated - default org.bukkit.Location getSourceLoc() { - return this.getOrigin(); - } -} diff --git a/api/src/main/java/org/bukkit/entity/Tameable.java b/api/src/main/java/org/bukkit/entity/Tameable.java deleted file mode 100644 index be436f8df..000000000 --- a/api/src/main/java/org/bukkit/entity/Tameable.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface Tameable extends Entity { - - /** - * 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 - */ - public 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 - */ - public void setTamed(boolean tame); - - // Paper start - /** - * Gets the owners UUID - * - * @return the owners UUID, or null if not owned - */ - @NotNull - public java.util.UUID getOwnerUniqueId(); - // Paper end - - /** - * Gets the current owning AnimalTamer - * - * @see #getOwnerUniqueId() Recommended to use UUID version instead of this for performance. - * This method will cause OfflinePlayer to be loaded from disk if the owner is not online. - * - * @return the owning AnimalTamer, or null if not owned - */ - @Nullable - public 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 - */ - public void setOwner(@Nullable AnimalTamer tamer); - -} diff --git a/api/src/main/java/org/bukkit/entity/ThrownExpBottle.java b/api/src/main/java/org/bukkit/entity/ThrownExpBottle.java deleted file mode 100644 index 671282ed2..000000000 --- a/api/src/main/java/org/bukkit/entity/ThrownExpBottle.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a thrown Experience bottle. - */ -public interface ThrownExpBottle extends Projectile { - -} diff --git a/api/src/main/java/org/bukkit/entity/ThrownPotion.java b/api/src/main/java/org/bukkit/entity/ThrownPotion.java deleted file mode 100644 index 10a3c297b..000000000 --- a/api/src/main/java/org/bukkit/entity/ThrownPotion.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.entity; - -import java.util.Collection; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a thrown potion bottle - */ -public interface ThrownPotion extends Projectile { - - /** - * Returns the effects that are applied by this potion. - * - * @return The potion effects - */ - @NotNull - public 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. - */ - @NotNull - public ItemStack getItem(); - - /** - * Set the ItemStack for this thrown potion. - *

- * The ItemStack must be of type {@link org.bukkit.Material#SPLASH_POTION} - * or {@link org.bukkit.Material#LINGERING_POTION}, otherwise an exception - * is thrown. - * - * @param item New ItemStack - */ - public void setItem(@NotNull ItemStack item); -} diff --git a/api/src/main/java/org/bukkit/entity/TippedArrow.java b/api/src/main/java/org/bukkit/entity/TippedArrow.java deleted file mode 100644 index 3193cc8a0..000000000 --- a/api/src/main/java/org/bukkit/entity/TippedArrow.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.entity; - -/** - * @deprecated tipped status depends only on base potion type not being - * UNCRAFTABLE and effects being empty. - */ -@Deprecated -public interface TippedArrow extends Arrow { } diff --git a/api/src/main/java/org/bukkit/entity/TraderLlama.java b/api/src/main/java/org/bukkit/entity/TraderLlama.java deleted file mode 100644 index 78966d19c..000000000 --- a/api/src/main/java/org/bukkit/entity/TraderLlama.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a trader Llama. - */ -public interface TraderLlama extends Llama { } diff --git a/api/src/main/java/org/bukkit/entity/Trident.java b/api/src/main/java/org/bukkit/entity/Trident.java deleted file mode 100644 index 3379ef9ba..000000000 --- a/api/src/main/java/org/bukkit/entity/Trident.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a thrown trident. - */ -public interface Trident extends AbstractArrow { } diff --git a/api/src/main/java/org/bukkit/entity/TropicalFish.java b/api/src/main/java/org/bukkit/entity/TropicalFish.java deleted file mode 100644 index bc5055f2d..000000000 --- a/api/src/main/java/org/bukkit/entity/TropicalFish.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.DyeColor; -import org.jetbrains.annotations.NotNull; - -/** - * Tropical fish. - */ -public interface TropicalFish extends Fish { - - /** - * Gets the color of the fish's pattern. - * - * @return pattern color - */ - @NotNull - DyeColor getPatternColor(); - - /** - * Sets the color of the fish's pattern - * - * @param color pattern color - */ - void setPatternColor(@NotNull DyeColor color); - - /** - * Gets the color of the fish's body. - * - * @return pattern color - */ - @NotNull - DyeColor getBodyColor(); - - /** - * Sets the color of the fish's body - * - * @param color body color - */ - void setBodyColor(@NotNull DyeColor color); - - /** - * Gets the fish's pattern. - * - * @return pattern - */ - @NotNull - Pattern getPattern(); - - /** - * Sets the fish's pattern - * - * @param pattern new pattern - */ - void setPattern(@NotNull Pattern pattern); - - /** - * Enumeration of all different fish patterns. Refer to the - * Minecraft Wiki - * for pictures. - */ - public static enum Pattern { - - KOB, - SUNSTREAK, - SNOOPER, - DASHER, - BRINELY, - SPOTTY, - FLOPPER, - STRIPEY, - GLITTER, - BLOCKFISH, - BETTY, - CLAYFISH; - } -} diff --git a/api/src/main/java/org/bukkit/entity/Turtle.java b/api/src/main/java/org/bukkit/entity/Turtle.java deleted file mode 100644 index 5375ea140..000000000 --- a/api/src/main/java/org/bukkit/entity/Turtle.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.Location; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a turtle. - */ -public interface Turtle extends Animals { - // Paper start - - /** - * Get the turtle's home location - * - * @return Home location - */ - @NotNull - Location getHome(); - - /** - * Set the turtle's home location - * - * @param location Home location - */ - void setHome(@NotNull Location location); - - /** - * Check if turtle is currently pathfinding to it's home - * - * @return True if going home - */ - boolean isGoingHome(); - - /** - * Get if turtle is digging to lay eggs - * - * @return True if digging - */ - boolean isDigging(); - - /** - * Get if turtle is carrying egg - * - * @return True if carrying egg - */ - boolean hasEgg(); - - /** - * Set if turtle is carrying egg - * - * @param hasEgg True if carrying egg - */ - void setHasEgg(boolean hasEgg); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Vehicle.java b/api/src/main/java/org/bukkit/entity/Vehicle.java deleted file mode 100644 index 771a27304..000000000 --- a/api/src/main/java/org/bukkit/entity/Vehicle.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a vehicle entity. - */ -public interface Vehicle extends Entity { - - /** - * Gets the vehicle's velocity. - * - * @return velocity vector - */ - @Override - @NotNull - public Vector getVelocity(); - - /** - * Sets the vehicle's velocity. - * - * @param vel velocity vector - */ - @Override - public void setVelocity(@NotNull Vector vel); -} diff --git a/api/src/main/java/org/bukkit/entity/Vex.java b/api/src/main/java/org/bukkit/entity/Vex.java deleted file mode 100644 index c34a3ea7b..000000000 --- a/api/src/main/java/org/bukkit/entity/Vex.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.Nullable; - -/** - * Represents a Vex. - */ -public interface Vex extends Monster { - - /** - * Gets the charging state of this entity. - * - * When this entity is charging it will having a glowing red texture. - * - * @return charging state - */ - boolean isCharging(); - - /** - * Sets the charging state of this entity. - * - * When this entity is charging it will having a glowing red texture. - * - * @param charging new state - */ - void setCharging(boolean charging); - - // Paper start - /** - * Get the Mob that summoned this vex - * - * @return Mob that summoned this vex - */ - @Nullable - Mob getSummoner(); - - /** - * Set the summoner of this vex - * - * @param summoner New summoner - */ - void setSummoner(@Nullable Mob summoner); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Villager.java b/api/src/main/java/org/bukkit/entity/Villager.java deleted file mode 100644 index ef48ad9b2..000000000 --- a/api/src/main/java/org/bukkit/entity/Villager.java +++ /dev/null @@ -1,213 +0,0 @@ -package org.bukkit.entity; - -import java.util.Locale; -import org.bukkit.Keyed; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a villager NPC - */ -public interface Villager extends AbstractVillager { - - /** - * Gets the current profession of this villager. - * - * @return Current profession. - */ - @NotNull - public Profession getProfession(); - - /** - * Sets the new profession of this villager. - * - * @param profession New profession. - */ - public void setProfession(@NotNull Profession profession); - - /** - * Gets the current type of this villager. - * - * @return Current type. - */ - @NotNull - public Type getVillagerType(); - - /** - * Sets the new type of this villager. - * - * @param type New type. - */ - public void setVillagerType(@NotNull Type type); - - /** - * Gets the level of this villager. - * - * A villager with a level of 1 and no experience is liable to lose its - * profession. - * - * @return this villager's level - */ - public int getVillagerLevel(); - - /** - * Sets the level of this villager. - * - * A villager with a level of 1 and no experience is liable to lose its - * profession. - * - * @param level the new level - * @throws IllegalArgumentException if level not between [1, 5] - */ - public void setVillagerLevel(int level); - - /** - * Gets the trading experience of this villager. - * - * @return trading experience - */ - public int getVillagerExperience(); - - /** - * Sets the trading experience of this villager. - * - * @param experience new experience - * @throws IllegalArgumentException if experience < 0 - */ - public void setVillagerExperience(int experience); - - /** - * Attempts to make this villager sleep at the given location. - *
- * The location must be in the current world and have a bed placed at the - * location. The villager will put its head on the specified block while - * sleeping. - * - * @param location the location of the bed - * @return whether the sleep was successful - */ - public boolean sleep(@NotNull Location location); - - /** - * Causes this villager to wake up if he's currently sleeping. - * - * @throws IllegalStateException if not sleeping - */ - public void wakeup(); - - /** - * Represents Villager type, usually corresponding to what biome they spawn - * in. - */ - public enum Type implements Keyed { - - DESERT, - JUNGLE, - PLAINS, - SAVANNA, - SNOW, - SWAMP, - TAIGA; - private final NamespacedKey key; - - private Type() { - this.key = NamespacedKey.minecraft(this.name().toLowerCase(Locale.ROOT)); - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - } - - /** - * Represents the various different Villager professions there may be. - * Villagers have different trading options depending on their profession, - */ - public enum Profession implements Keyed { - NONE, - /** - * Armorer profession. Wears a black apron. Armorers primarily trade for - * iron armor, chainmail armor, and sometimes diamond armor. - */ - ARMORER, - /** - * Butcher profession. Wears a white apron. Butchers primarily trade for - * raw and cooked food. - */ - BUTCHER, - /** - * Cartographer profession. Wears a white robe. Cartographers primarily - * trade for explorer maps and some paper. - */ - CARTOGRAPHER, - /** - * Cleric profession. Wears a purple robe. Clerics primarily trade for - * rotten flesh, gold ingot, redstone, lapis, ender pearl, glowstone, - * and bottle o' enchanting. - */ - CLERIC, - /** - * Farmer profession. Wears a brown robe. Farmers primarily trade for - * food-related items. - */ - FARMER, - /** - * Fisherman profession. Wears a brown robe. Fisherman primarily trade - * for fish, as well as possibly selling string and/or coal. - */ - FISHERMAN, - /** - * Fletcher profession. Wears a brown robe. Fletchers primarily trade - * for string, bows, and arrows. - */ - FLETCHER, - /** - * Leatherworker profession. Wears a white apron. Leatherworkers - * primarily trade for leather, and leather armor, as well as saddles. - */ - LEATHERWORKER, - /** - * Librarian profession. Wears a white robe. Librarians primarily trade - * for paper, books, and enchanted books. - */ - LIBRARIAN, - /** - * Mason profession. - */ - MASON, - /** - * Nitwit profession. Wears a green apron, cannot trade. Nitwit - * villagers do not do anything. They do not have any trades by default. - */ - NITWIT, - /** - * Sheperd profession. Wears a brown robe. Shepherds primarily trade for - * wool items, and shears. - */ - SHEPHERD, - /** - * Toolsmith profession. Wears a black apron. Tool smiths primarily - * trade for iron and diamond tools. - */ - TOOLSMITH, - /** - * Weaponsmith profession. Wears a black apron. Weapon smiths primarily - * trade for iron and diamond weapons, sometimes enchanted. - */ - WEAPONSMITH; - private final NamespacedKey key; - - private Profession() { - this.key = NamespacedKey.minecraft(this.name().toLowerCase(Locale.ROOT)); - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - } -} diff --git a/api/src/main/java/org/bukkit/entity/Vindicator.java b/api/src/main/java/org/bukkit/entity/Vindicator.java deleted file mode 100644 index c5d9e76a6..000000000 --- a/api/src/main/java/org/bukkit/entity/Vindicator.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Vindicator. - */ -public interface Vindicator extends Illager { - // Paper start - /** - * Check if this Vindicator is set to Johnny mode. - *

- * When in Johnny mode the Vindicator will be hostile to any kind of mob, except - * for evokers, ghasts, illusioners and other vindicators. It will even be hostile - * to vexes. All mobs, except for endermites, phantoms, guardians, slimes and - * magma cubes, will try to attack the vindicator in return. - * - * @return True if in Johnny mode - */ - boolean isJohnny(); - - /** - * Set this Vindicator's Johnny mode. - *

- * When in Johnny mode the Vindicator will be hostile to any kind of mob, except - * for evokers, ghasts, illusioners and other vindicators. It will even be hostile - * to vexes. All mobs, except for endermites, phantoms, guardians, slimes and - * magma cubes, will try to attack the vindicator in return. - * - * @param johnny True to enable Johnny mode - */ - void setJohnny(boolean johnny); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/WanderingTrader.java b/api/src/main/java/org/bukkit/entity/WanderingTrader.java deleted file mode 100644 index 3547e159b..000000000 --- a/api/src/main/java/org/bukkit/entity/WanderingTrader.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a wandering trader NPC - */ -public interface WanderingTrader extends AbstractVillager { } diff --git a/api/src/main/java/org/bukkit/entity/WaterMob.java b/api/src/main/java/org/bukkit/entity/WaterMob.java deleted file mode 100644 index 62b4e89d0..000000000 --- a/api/src/main/java/org/bukkit/entity/WaterMob.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a Water Mob - */ -public interface WaterMob extends Creature {} diff --git a/api/src/main/java/org/bukkit/entity/Witch.java b/api/src/main/java/org/bukkit/entity/Witch.java deleted file mode 100644 index cd8d0a20e..000000000 --- a/api/src/main/java/org/bukkit/entity/Witch.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.entity; - -import com.destroystokyo.paper.entity.RangedEntity; - -// Paper start -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; -// Paper end - -/** - * Represents a Witch - */ -public interface Witch extends Raider, RangedEntity { // Paper - // Paper start - /** - * Check if Witch is drinking a potion - * - * @return True if drinking a potion - */ - boolean isDrinkingPotion(); - - /** - * Get time remaining (in ticks) the Witch is drinking a potion - * - * @return Time remaining (in ticks) - */ - int getPotionUseTimeLeft(); - - /** - * Get the potion the Witch is drinking - * - * @return The potion the witch is drinking - */ - @Nullable - ItemStack getDrinkingPotion(); - - /** - * Set the potion the Witch should drink - * - * @param potion Potion to drink - */ - void setDrinkingPotion(@Nullable ItemStack potion); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/Wither.java b/api/src/main/java/org/bukkit/entity/Wither.java deleted file mode 100644 index 426d36933..000000000 --- a/api/src/main/java/org/bukkit/entity/Wither.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bukkit.entity; - -import com.destroystokyo.paper.entity.RangedEntity; - -/** - * Represents a Wither boss - */ -public interface Wither extends Monster, Boss, RangedEntity { // Paper -} diff --git a/api/src/main/java/org/bukkit/entity/WitherSkeleton.java b/api/src/main/java/org/bukkit/entity/WitherSkeleton.java deleted file mode 100644 index 7045014e6..000000000 --- a/api/src/main/java/org/bukkit/entity/WitherSkeleton.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a WitherSkeleton - variant of {@link Skeleton}. - */ -public interface WitherSkeleton extends Skeleton { } diff --git a/api/src/main/java/org/bukkit/entity/WitherSkull.java b/api/src/main/java/org/bukkit/entity/WitherSkull.java deleted file mode 100644 index 33d20abc0..000000000 --- a/api/src/main/java/org/bukkit/entity/WitherSkull.java +++ /dev/null @@ -1,21 +0,0 @@ -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 - */ - public void setCharged(boolean charged); - - /** - * Gets whether or not the wither skull is charged. - * - * @return whether the wither skull is charged - */ - public boolean isCharged(); -} diff --git a/api/src/main/java/org/bukkit/entity/Wolf.java b/api/src/main/java/org/bukkit/entity/Wolf.java deleted file mode 100644 index 0390558b8..000000000 --- a/api/src/main/java/org/bukkit/entity/Wolf.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.DyeColor; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Wolf - */ -public interface Wolf extends Animals, Tameable, Sittable { - - /** - * Checks if this wolf is angry - * - * @return Anger true if angry - */ - public boolean isAngry(); - - /** - * Sets the anger of this wolf. - *

- * An angry wolf can not be fed or tamed. - * - * @param angry true if angry - * @see #setTarget(org.bukkit.entity.LivingEntity) - */ - public void setAngry(boolean angry); - - /** - * Get the collar color of this wolf - * - * @return the color of the collar - */ - @NotNull - public DyeColor getCollarColor(); - - /** - * Set the collar color of this wolf - * - * @param color the color to apply - */ - public void setCollarColor(@NotNull DyeColor color); -} diff --git a/api/src/main/java/org/bukkit/entity/Zombie.java b/api/src/main/java/org/bukkit/entity/Zombie.java deleted file mode 100644 index fa7a43c35..000000000 --- a/api/src/main/java/org/bukkit/entity/Zombie.java +++ /dev/null @@ -1,140 +0,0 @@ -package org.bukkit.entity; - -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a Zombie. - */ -public interface Zombie extends Monster { - - /** - * Gets whether the zombie is a baby - * - * @return Whether the zombie is a baby - */ - public boolean isBaby(); - - /** - * Sets whether the zombie is a baby - * - * @param flag Whether the zombie is a baby - */ - public void setBaby(boolean flag); - - /** - * Gets whether the zombie is a villager - * - * @return Whether the zombie is a villager - * @deprecated check if instanceof {@link ZombieVillager}. - */ - @Deprecated - public boolean isVillager(); - - /** - * @param flag flag - * @deprecated must spawn {@link ZombieVillager}. - */ - @Deprecated - @Contract("_ -> fail") - public void setVillager(boolean flag); - - /** - * @param profession profession - * @see ZombieVillager#getVillagerProfession() - */ - @Deprecated - @Contract("_ -> fail") - public void setVillagerProfession(Villager.Profession profession); - - /** - * @return profession - * @see ZombieVillager#getVillagerProfession() - */ - @Deprecated - @Nullable - @Contract("-> null") - public Villager.Profession getVillagerProfession(); - - /** - * Get if this entity is in the process of converting to a Drowned as a - * result of being underwater. - * - * @return conversion status - */ - boolean isConverting(); - - /** - * Gets the amount of ticks until this entity will be converted to a Drowned - * as a result of being underwater. - * - * When this reaches 0, the entity will be converted. - * - * @return conversion time - * @throws IllegalStateException if {@link #isConverting()} is false. - */ - int getConversionTime(); - - /** - * Sets the amount of ticks until this entity will be converted to a Drowned - * as a result of being underwater. - * - * When this reaches 0, the entity will be converted. A value of less than 0 - * will stop the current conversion process without converting the current - * entity. - * - * @param time new conversion time - */ - void setConversionTime(int time); - // Paper start - /** - * Check if zombie is drowning - * - * @return True if zombie conversion process has begun - */ - boolean isDrowning(); - - /** - * Make zombie start drowning - * - * @param drownedConversionTime Amount of time until zombie converts from drowning - * - * @deprecated See {@link #setConversionTime(int)} - */ - @Deprecated - void startDrowning(int drownedConversionTime); - - /** - * Stop a zombie from starting the drowning conversion process - */ - void stopDrowning(); - - /** - * Set if zombie has its arms raised - * - * @param raised True to raise arms - */ - void setArmsRaised(boolean raised); - - /** - * Check if zombie has arms raised - * - * @return True if arms are raised - */ - boolean isArmsRaised(); - - /** - * Check if this zombie will burn in the sunlight - * - * @return True if zombie will burn in sunlight - */ - boolean shouldBurnInDay(); - - /** - * Set if this zombie should burn in the sunlight - * - * @param shouldBurnInDay True to burn in sunlight - */ - void setShouldBurnInDay(boolean shouldBurnInDay); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/entity/ZombieHorse.java b/api/src/main/java/org/bukkit/entity/ZombieHorse.java deleted file mode 100644 index 4179b68bd..000000000 --- a/api/src/main/java/org/bukkit/entity/ZombieHorse.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.entity; - -/** - * Represents a ZombieHorse - variant of {@link AbstractHorse}. - */ -public interface ZombieHorse extends AbstractHorse { } diff --git a/api/src/main/java/org/bukkit/entity/ZombieVillager.java b/api/src/main/java/org/bukkit/entity/ZombieVillager.java deleted file mode 100644 index a8ec860ea..000000000 --- a/api/src/main/java/org/bukkit/entity/ZombieVillager.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bukkit.entity; - -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a {@link Zombie} which was once a {@link Villager}. - */ -public interface ZombieVillager extends Zombie { - - /** - * Sets the villager profession of this zombie. - */ - @Override - void setVillagerProfession(@Nullable Villager.Profession profession); - - /** - * Returns the villager profession of this zombie. - * - * @return the profession or null - */ - @Override - @Nullable - Villager.Profession getVillagerProfession(); - - /** - * Get if this entity is in the process of converting to a Villager as a - * result of being cured. - * - * @return conversion status - */ - @Override - boolean isConverting(); - - /** - * Gets the amount of ticks until this entity will be converted to a - * Villager as a result of being cured. - * - * When this reaches 0, the entity will be converted. - * - * @return conversion time - * @throws IllegalStateException if {@link #isConverting()} is false. - */ - @Override - int getConversionTime(); - - /** - * Sets the amount of ticks until this entity will be converted to a - * Villager as a result of being cured. - * - * When this reaches 0, the entity will be converted. A value of less than 0 - * will stop the current conversion process without converting the current - * entity. - * - * @param time new conversion time - */ - @Override - void setConversionTime(int time); - - /** - * Gets the player who initiated the conversion. - * - * @return the player, or null if the player is unknown or the - * entity isn't converting currently - */ - @Nullable - OfflinePlayer getConversionPlayer(); - - /** - * Sets the player who initiated the conversion. - *

- * This has no effect if this entity isn't converting currently. - * - * @param conversionPlayer the player - */ - void setConversionPlayer(@Nullable OfflinePlayer conversionPlayer); -} diff --git a/api/src/main/java/org/bukkit/entity/memory/MemoryKey.java b/api/src/main/java/org/bukkit/entity/memory/MemoryKey.java deleted file mode 100644 index dd33800d9..000000000 --- a/api/src/main/java/org/bukkit/entity/memory/MemoryKey.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.bukkit.entity.memory; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import org.bukkit.Keyed; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a key used for accessing memory values of a - * {@link org.bukkit.entity.LivingEntity}. - * - * @param the class type of the memory value - */ -public final class MemoryKey implements Keyed { - - private final NamespacedKey namespacedKey; - private final Class tClass; - - private MemoryKey(NamespacedKey namespacedKey, Class tClass) { - this.namespacedKey = namespacedKey; - this.tClass = tClass; - MEMORY_KEYS.put(namespacedKey, this); - } - - @NotNull - @Override - public NamespacedKey getKey() { - return namespacedKey; - } - - /** - * Gets the class of values associated with this memory. - * - * @return the class of value objects - */ - @NotNull - public Class getMemoryClass() { - return tClass; - } - - private static final Map MEMORY_KEYS = new HashMap<>(); - // - public static final MemoryKey HOME = new MemoryKey<>(NamespacedKey.minecraft("home"), Location.class); - public static final MemoryKey MEETING_POINT = new MemoryKey<>(NamespacedKey.minecraft("meeting_point"), Location.class); - public static final MemoryKey JOB_SITE = new MemoryKey<>(NamespacedKey.minecraft("job_site"), Location.class); - public static final MemoryKey LAST_SLEPT = new MemoryKey<>(NamespacedKey.minecraft("last_slept"), Long.class); - public static final MemoryKey LAST_WORKED_AT_POI = new MemoryKey<>(NamespacedKey.minecraft("last_worked_at_poi"), Long.class); - - /** - * Returns a {@link MemoryKey} by a {@link NamespacedKey}. - * - * @param namespacedKey the {@link NamespacedKey} referencing a - * {@link MemoryKey} - * @return the {@link MemoryKey} or null when no {@link MemoryKey} is - * available under that key - */ - @Nullable - public static MemoryKey getByKey(@NotNull NamespacedKey namespacedKey) { - return MEMORY_KEYS.get(namespacedKey); - } - - /** - * Returns the set of all MemoryKeys. - * - * @return the memoryKeys - */ - @NotNull - public static Set values() { - return new HashSet<>(MEMORY_KEYS.values()); - } -} diff --git a/api/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java b/api/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java deleted file mode 100644 index 63c80b4ee..000000000 --- a/api/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.entity.minecart; - -import org.bukkit.entity.Minecart; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface CommandMinecart extends Minecart { - - /** - * 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. - */ - @NotNull - public 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. - */ - public void setCommand(@Nullable 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. - */ - public void setName(@Nullable String name); - -} diff --git a/api/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java b/api/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java deleted file mode 100644 index a4411daca..000000000 --- a/api/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java +++ /dev/null @@ -1,9 +0,0 @@ -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/api/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java b/api/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java deleted file mode 100644 index db69687a7..000000000 --- a/api/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.entity.minecart; - -import com.destroystokyo.paper.loottable.LootableEntityInventory; -import org.bukkit.entity.Minecart; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.loot.Lootable; - -/** - * Represents a Minecart with a Hopper inside it - */ -public interface HopperMinecart extends Minecart, InventoryHolder, LootableEntityInventory { - - /** - * Checks whether or not this Minecart will pick up - * items into its inventory. - * - * @return true if the Minecart will pick up items - */ - boolean isEnabled(); - - /** - * Sets whether this Minecart will pick up items. - * - * @param enabled new enabled state - */ - void setEnabled(boolean enabled); -} diff --git a/api/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java b/api/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java deleted file mode 100644 index 57e8b1d59..000000000 --- a/api/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java +++ /dev/null @@ -1,10 +0,0 @@ -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/api/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java b/api/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java deleted file mode 100644 index 1b8264573..000000000 --- a/api/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java +++ /dev/null @@ -1,14 +0,0 @@ -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/api/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java b/api/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java deleted file mode 100644 index 0ce3592ec..000000000 --- a/api/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java +++ /dev/null @@ -1,10 +0,0 @@ -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/api/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java b/api/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java deleted file mode 100644 index 238d118f7..000000000 --- a/api/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.entity.minecart; - -import com.destroystokyo.paper.loottable.LootableEntityInventory; -import org.bukkit.entity.Minecart; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.loot.Lootable; - -/** - * 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, LootableEntityInventory { // Paper -} diff --git a/api/src/main/java/org/bukkit/event/Cancellable.java b/api/src/main/java/org/bukkit/event/Cancellable.java deleted file mode 100644 index 799b0b0f3..000000000 --- a/api/src/main/java/org/bukkit/event/Cancellable.java +++ /dev/null @@ -1,20 +0,0 @@ -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 - */ - public 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 - */ - public void setCancelled(boolean cancel); -} diff --git a/api/src/main/java/org/bukkit/event/Event.java b/api/src/main/java/org/bukkit/event/Event.java deleted file mode 100644 index 8ec56cd6b..000000000 --- a/api/src/main/java/org/bukkit/event/Event.java +++ /dev/null @@ -1,118 +0,0 @@ -package org.bukkit.event; - -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; -import org.jetbrains.annotations.NotNull; - -/** - * 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; - } - - // Paper start - /** - * Calls the event and tests if cancelled. - * - * @return false if event was cancelled, if cancellable. otherwise true. - */ - public boolean callEvent() { - org.bukkit.Bukkit.getPluginManager().callEvent(this); - if (this instanceof Cancellable) { - return !((Cancellable) this).isCancelled(); - } else { - return true; - } - } - // 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 - */ - @NotNull - public String getEventName() { - if (name == null) { - name = getClass().getSimpleName(); - } - return name; - } - - @NotNull - 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 - * java.lang.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/api/src/main/java/org/bukkit/event/EventException.java b/api/src/main/java/org/bukkit/event/EventException.java deleted file mode 100644 index 84638e852..000000000 --- a/api/src/main/java/org/bukkit/event/EventException.java +++ /dev/null @@ -1,53 +0,0 @@ -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/api/src/main/java/org/bukkit/event/EventHandler.java b/api/src/main/java/org/bukkit/event/EventHandler.java deleted file mode 100644 index cc06f480b..000000000 --- a/api/src/main/java/org/bukkit/event/EventHandler.java +++ /dev/null @@ -1,41 +0,0 @@ -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/api/src/main/java/org/bukkit/event/EventPriority.java b/api/src/main/java/org/bukkit/event/EventPriority.java deleted file mode 100644 index 61ffa50f2..000000000 --- a/api/src/main/java/org/bukkit/event/EventPriority.java +++ /dev/null @@ -1,47 +0,0 @@ -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; - - private EventPriority(int slot) { - this.slot = slot; - } - - public int getSlot() { - return slot; - } -} diff --git a/api/src/main/java/org/bukkit/event/HandlerList.java b/api/src/main/java/org/bukkit/event/HandlerList.java deleted file mode 100644 index ed78cca71..000000000 --- a/api/src/main/java/org/bukkit/event/HandlerList.java +++ /dev/null @@ -1,238 +0,0 @@ -package org.bukkit.event; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map.Entry; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredListener; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - public static ArrayList getRegisteredListeners(@NotNull 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") - @NotNull - public static ArrayList getHandlerLists() { - synchronized (allLists) { - return (ArrayList) allLists.clone(); - } - } -} diff --git a/api/src/main/java/org/bukkit/event/Listener.java b/api/src/main/java/org/bukkit/event/Listener.java deleted file mode 100644 index ff083e62d..000000000 --- a/api/src/main/java/org/bukkit/event/Listener.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.event; - -/** - * Simple interface for tagging all EventListeners - */ -public interface Listener {} diff --git a/api/src/main/java/org/bukkit/event/block/Action.java b/api/src/main/java/org/bukkit/event/block/Action.java deleted file mode 100644 index 25d26e3fe..000000000 --- a/api/src/main/java/org/bukkit/event/block/Action.java +++ /dev/null @@ -1,33 +0,0 @@ -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/api/src/main/java/org/bukkit/event/block/BlockBreakEvent.java b/api/src/main/java/org/bukkit/event/block/BlockBreakEvent.java deleted file mode 100644 index c05cd9cad..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockBreakEvent.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.jetbrains.annotations.NotNull; - -/** - * 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 dropItems; - private boolean cancel; - - public BlockBreakEvent(@NotNull final Block theBlock, @NotNull final Player player) { - super(theBlock, 0); - - this.player = player; - this.dropItems = true; // Defaults to dropping items as it normally would - } - - /** - * Gets the Player that is breaking the block involved in this event. - * - * @return The Player that is breaking the block involved in this event - */ - @NotNull - public Player getPlayer() { - return player; - } - - /** - * Sets whether or not the block will drop items as it normally would. - * - * @param dropItems Whether or not the block will drop items - */ - public void setDropItems(boolean dropItems) { - this.dropItems = dropItems; - } - - /** - * Gets whether or not the block will drop items. - * - * @return Whether or not the block will drop items - */ - public boolean isDropItems() { - return this.dropItems; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockBurnEvent.java b/api/src/main/java/org/bukkit/event/block/BlockBurnEvent.java deleted file mode 100644 index c0c38df36..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockBurnEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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; - private final Block ignitingBlock; - - @Deprecated - public BlockBurnEvent(@NotNull final Block block) { - this(block, null); - } - - public BlockBurnEvent(@NotNull final Block block, @Nullable final Block ignitingBlock) { - super(block); - this.ignitingBlock = ignitingBlock; - } - - /** - * Gets the block which ignited this block. - * - * @return The Block that ignited and burned this block, or null if no - * source block exists - */ - @Nullable - public Block getIgnitingBlock() { - return ignitingBlock; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java b/api/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java deleted file mode 100644 index 977eb8d39..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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()} instead. - *
- */ -public class BlockCanBuildEvent extends BlockEvent { - private static final HandlerList handlers = new HandlerList(); - protected boolean buildable; - - protected BlockData blockData; - private final Player player; - - @Deprecated - public BlockCanBuildEvent(@NotNull final Block block, @NotNull final BlockData type, final boolean canBuild) { - this(block, null, type, canBuild); - } - - /** - * - * @param block the block involved in this event - * @param player the player placing the block - * @param type the id of the block to place - * @param canBuild whether we can build - */ - public BlockCanBuildEvent(@NotNull final Block block, @Nullable final Player player, @NotNull final BlockData type, final boolean canBuild) { - super(block); - this.player = player; - this.buildable = canBuild; - this.blockData = type; - } - - /** - * 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 - */ - @NotNull - public Material getMaterial() { - return blockData.getMaterial(); - } - - /** - * Gets the BlockData that we are trying to place. - * - * @return The BlockData that we are trying to place - */ - @NotNull - public BlockData getBlockData() { - return blockData; - } - - /** - * Gets the player who placed the block involved in this event. - *
- * May be null for legacy calls of the event. - * - * @return The Player who placed the block involved in this event - */ - @Nullable - public Player getPlayer() { - return player; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockCookEvent.java b/api/src/main/java/org/bukkit/event/block/BlockCookEvent.java deleted file mode 100644 index be7af5440..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockCookEvent.java +++ /dev/null @@ -1,74 +0,0 @@ -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.jetbrains.annotations.NotNull; - -/** - * Called when an ItemStack is successfully cooked in a block. - */ -public class BlockCookEvent extends BlockEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private final ItemStack source; - private ItemStack result; - private boolean cancelled; - - public BlockCookEvent(@NotNull final Block block, @NotNull final ItemStack source, @NotNull final ItemStack result) { - super(block); - this.source = source; - this.result = result; - this.cancelled = false; - } - - /** - * Gets the smelted ItemStack for this event - * - * @return smelting source ItemStack - */ - @NotNull - public ItemStack getSource() { - return source; - } - - /** - * Gets the resultant ItemStack for this event - * - * @return smelting result ItemStack - */ - @NotNull - public ItemStack getResult() { - return result; - } - - /** - * Sets the resultant ItemStack for this event - * - * @param result new result ItemStack - */ - public void setResult(@NotNull ItemStack result) { - this.result = result; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockDamageEvent.java b/api/src/main/java/org/bukkit/event/block/BlockDamageEvent.java deleted file mode 100644 index f70871e1a..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockDamageEvent.java +++ /dev/null @@ -1,90 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final Block block, @NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - public ItemStack getItemInHand() { - return itemstack; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/block/BlockDispenseArmorEvent.java b/api/src/main/java/org/bukkit/event/block/BlockDispenseArmorEvent.java deleted file mode 100644 index 57b831979..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockDispenseArmorEvent.java +++ /dev/null @@ -1,34 +0,0 @@ -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; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java b/api/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java deleted file mode 100644 index 6e8be28f6..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java +++ /dev/null @@ -1,91 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Block block, @NotNull final ItemStack dispensed, @NotNull 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(org.bukkit.inventory.ItemStack)} instead. - * - * @return An ItemStack for the item being dispensed - */ - @NotNull - public ItemStack getItem() { - return item.clone(); - } - - /** - * Sets the item being dispensed. - * - * @param item the item being dispensed - */ - public void setItem(@NotNull ItemStack item) { - this.item = item; - } - - /** - * Gets the velocity. - *

- * Note: Modifying the returned Vector will not change the velocity, you - * must use {@link #setVelocity(org.bukkit.util.Vector)} instead. - * - * @return A Vector for the dispensed item's velocity - */ - @NotNull - 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(@NotNull Vector vel) { - velocity = vel; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockDropItemEvent.java b/api/src/main/java/org/bukkit/event/block/BlockDropItemEvent.java deleted file mode 100644 index 129b412ee..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockDropItemEvent.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.bukkit.event.block; - -import java.util.List; -import org.bukkit.Warning; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Item; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called if a block broken by a player drops an item. - * - * If the block break is cancelled, this event won't be called. - * - * If isDropItems in BlockBreakEvent is set to false, this event won't be - * called. - * - * This event will also be called if the player breaks a multi block structure, - * for example a torch on top of a stone. Both items will have an event call. - * - * The Block is already broken as this event is called, so #getBlock() will be - * AIR in most cases. Use #getBlockState() for more Information about the broken - * block. - * - * @deprecated draft API - */ -@Deprecated -@Warning(false) -public class BlockDropItemEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private final Player player; - private boolean cancel; - private final BlockState blockState; - private final List items; - - public BlockDropItemEvent(@NotNull Block block, @NotNull BlockState blockState, @NotNull Player player, @NotNull List items) { - super(block); - this.blockState = blockState; - this.player = player; - this.items = items; - } - - /** - * Gets the Player that is breaking the block involved in this event. - * - * @return The Player that is breaking the block involved in this event - */ - @NotNull - public Player getPlayer() { - return player; - } - - /** - * Gets the BlockState of the block involved in this event before it was - * broken. - * - * @return The BlockState of the block involved in this event - */ - @NotNull - public BlockState getBlockState() { - return blockState; - } - - /** - * Gets list of the Item drops caused by the block break. - * - * This list is mutable - removing an item from it will cause it to not - * drop. It is not legal however to add new items to the list. - * - * @return The Item the block caused to drop - */ - @NotNull - public List getItems() { - return items; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/block/BlockEvent.java b/api/src/main/java/org/bukkit/event/block/BlockEvent.java deleted file mode 100644 index 62a4d1345..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.event.Event; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a block related event. - */ -public abstract class BlockEvent extends Event { - protected Block block; - - public BlockEvent(@NotNull final Block theBlock) { - block = theBlock; - } - - /** - * Gets the block involved in this event. - * - * @return The Block which block is involved in this event - */ - @NotNull - public final Block getBlock() { - return block; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockExpEvent.java b/api/src/main/java/org/bukkit/event/block/BlockExpEvent.java deleted file mode 100644 index 21b902655..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockExpEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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; - } - - @Override - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockExplodeEvent.java b/api/src/main/java/org/bukkit/event/block/BlockExplodeEvent.java deleted file mode 100644 index 44f7f6939..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockExplodeEvent.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.bukkit.event.block; - -import java.util.List; -import org.bukkit.block.Block; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Block what, @NotNull final List blocks, final float yield) { - super(what); - this.blocks = blocks; - this.yield = yield; - this.cancel = false; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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 - */ - @NotNull - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockFadeEvent.java b/api/src/main/java/org/bukkit/event/block/BlockFadeEvent.java deleted file mode 100644 index 362643de4..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockFadeEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - *
  • Coral fading to dead coral due to lack of water
  • - *
  • Turtle Egg bursting when a turtle hatches
  • - *
- *

- * 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(@NotNull final Block block, @NotNull 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 - */ - @NotNull - public BlockState getNewState() { - return newState; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockFertilizeEvent.java b/api/src/main/java/org/bukkit/event/block/BlockFertilizeEvent.java deleted file mode 100644 index 695309b4b..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockFertilizeEvent.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.bukkit.event.block; - -import java.util.List; -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.event.world.StructureGrowEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called with the block changes resulting from a player fertilizing a given - * block with bonemeal. Will be called after the applicable - * {@link StructureGrowEvent}. - */ -public class BlockFertilizeEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - // - private final Player player; - private final List blocks; - - public BlockFertilizeEvent(@NotNull Block theBlock, @Nullable Player player, @NotNull List blocks) { - super(theBlock); - this.player = player; - this.blocks = blocks; - } - - /** - * Gets the player that triggered the fertilization. - * - * @return triggering player, or null if not applicable - */ - @Nullable - public Player getPlayer() { - return player; - } - - /** - * Gets a list of all blocks changed by the fertilization. - * - * @return list of all changed blocks - */ - @NotNull - public List getBlocks() { - return blocks; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockFormEvent.java b/api/src/main/java/org/bukkit/event/block/BlockFormEvent.java deleted file mode 100644 index 010678041..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockFormEvent.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - *
  • Obsidian / Cobblestone forming due to contact with water. - *
  • Concrete forming due to mixing of concrete powder and water. - *
- *

- * If a Block Form event is cancelled, the block will not be formed. - * - * @see BlockSpreadEvent - */ -public class BlockFormEvent extends BlockGrowEvent { - private static final HandlerList handlers = new HandlerList(); - - public BlockFormEvent(@NotNull final Block block, @NotNull final BlockState newState) { - super(block, newState); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockFromToEvent.java b/api/src/main/java/org/bukkit/event/block/BlockFromToEvent.java deleted file mode 100644 index 1af392805..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockFromToEvent.java +++ /dev/null @@ -1,78 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Block block, @NotNull final BlockFace face) { - super(block); - this.face = face; - this.cancel = false; - } - - public BlockFromToEvent(@NotNull final Block block, @NotNull 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 - */ - @NotNull - public BlockFace getFace() { - return face; - } - - /** - * Convenience method for getting the faced Block. - * - * @return The faced Block - */ - @NotNull - public Block getToBlock() { - if (to == null) { - to = block.getRelative(face); - } - return to; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/block/BlockGrowEvent.java b/api/src/main/java/org/bukkit/event/block/BlockGrowEvent.java deleted file mode 100644 index 73d5375d2..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockGrowEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a block grows naturally in the world. - *

- * Examples: - *

    - *
  • Wheat - *
  • Sugar Cane - *
  • Cactus - *
  • Watermelon - *
  • Pumpkin - *
  • Turtle Egg - *
- *

- * 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(@NotNull final Block block, @NotNull 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 - */ - @NotNull - public BlockState getNewState() { - return newState; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @Override - @NotNull - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java b/api/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java deleted file mode 100644 index 1593c3716..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java +++ /dev/null @@ -1,143 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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; - - public BlockIgniteEvent(@NotNull final Block theBlock, @NotNull final IgniteCause cause, @NotNull final Entity ignitingEntity) { - this(theBlock, cause, ignitingEntity, null); - } - - public BlockIgniteEvent(@NotNull final Block theBlock, @NotNull final IgniteCause cause, @NotNull final Block ignitingBlock) { - this(theBlock, cause, null, ignitingBlock); - } - - public BlockIgniteEvent(@NotNull final Block theBlock, @NotNull final IgniteCause cause, @Nullable final Entity ignitingEntity, @Nullable final Block ignitingBlock) { - super(theBlock); - this.cause = cause; - this.ignitingEntity = ignitingEntity; - this.ignitingBlock = ignitingBlock; - this.cancel = false; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - /** - * Gets the cause of block ignite. - * - * @return An IgniteCause value detailing the cause of block ignition - */ - @NotNull - 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. - */ - @Nullable - 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. - */ - @Nullable - public Entity getIgnitingEntity() { - return ignitingEntity; - } - - /** - * Gets the block which ignited this block - * - * @return The Block that placed/ignited the fire block, or null if not ignited by a Block. - */ - @Nullable - 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, - /** - * Block ignition caused by a flaming arrow. - */ - ARROW, - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java b/api/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java deleted file mode 100644 index fe2ec79dd..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.event.block; - -import com.google.common.collect.ImmutableList; -import java.util.List; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull List states, @NotNull Block clicked, @NotNull ItemStack itemInHand, @NotNull 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 - */ - @NotNull - public List getReplacedBlockStates() { - return states; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java b/api/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java deleted file mode 100644 index c382f9fc2..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Thrown when a block physics check is called. - *
- * This event is a high frequency event, it may be called thousands of times per - * a second on a busy server. Plugins are advised to listen to the event with - * caution and only perform lightweight checks when using it. - *
- * In addition to this, cancelling the event is liable to leave the world in an - * inconsistent state. For example if you use the event to leave a block - * floating in mid air when that block has a requirement to be attached to - * something, there is no guarantee that the floating block will persist across - * server restarts or map upgrades. - *
- * Plugins should also note that where possible this event may only called for - * the "root" block of physics updates in order to limit event spam. Physics - * updates that cause other blocks to change their state may not result in an - * event for each of those blocks (usually adjacent). If you are concerned about - * monitoring these changes then you should check adjacent blocks yourself. - */ -public class BlockPhysicsEvent extends BlockEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private final BlockData changed; - private final Block sourceBlock; - private boolean cancel = false; - - // Paper start - Legacy constructor, use #BlockPhysicsEvent(Block, BlockData, Block) - @Deprecated - public BlockPhysicsEvent(final Block block, final BlockData changed, final int sourceX, final int sourceY, final int sourceZ) { - this(block, changed, block.getWorld().getBlockAt(sourceX, sourceY, sourceZ)); - } - // Paper end - - public BlockPhysicsEvent(@NotNull final Block block, @NotNull final BlockData changed) { - this(block, changed, block); - } - - public BlockPhysicsEvent(@NotNull final Block block, @NotNull final BlockData changed, @NotNull final Block sourceBlock) { - super(block); - this.changed = changed; - this.sourceBlock = sourceBlock; - } - - /** - * Gets the source block that triggered this event. - * - * Note: This will default to block if not set. - * - * @return The source block - */ - @NotNull - public Block getSourceBlock() { - return sourceBlock; - } - - /** - * Gets the type of block that changed, causing this event - * - * @return Changed block's type - */ - @NotNull - public Material getChangedType() { - return changed.getMaterial(); - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/block/BlockPistonEvent.java b/api/src/main/java/org/bukkit/event/block/BlockPistonEvent.java deleted file mode 100644 index 2cdf2919e..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockPistonEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.event.Cancellable; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a piston block is triggered - */ -public abstract class BlockPistonEvent extends BlockEvent implements Cancellable { - private boolean cancelled; - private final BlockFace direction; - - public BlockPistonEvent(@NotNull final Block block, @NotNull final BlockFace direction) { - super(block); - this.direction = direction; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - 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.STICKY_PISTON || block.getType() == Material.MOVING_PISTON; - } - - /** - * Return the direction in which the piston will operate. - * - * @return direction of the piston - */ - @NotNull - 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/api/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java b/api/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java deleted file mode 100644 index 40ddc3649..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit.event.block; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Block block, final int length, @NotNull final BlockFace direction) { - super(block, direction); - - this.length = length; - } - - public BlockPistonExtendEvent(@NotNull final Block block, @NotNull final List blocks, @NotNull 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. - */ - @NotNull - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java b/api/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java deleted file mode 100644 index 340fa397e..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.event.block; - -import java.util.List; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a piston retracts - */ -public class BlockPistonRetractEvent extends BlockPistonEvent { - private static final HandlerList handlers = new HandlerList(); - private List blocks; - - public BlockPistonRetractEvent(@NotNull final Block block, @NotNull final List blocks, @NotNull 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 - @NotNull - 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. - */ - @NotNull - public List getBlocks() { - return blocks; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java b/api/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java deleted file mode 100644 index be0a2d1f2..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java +++ /dev/null @@ -1,148 +0,0 @@ -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.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * 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; - protected EquipmentSlot hand; - - @Deprecated - public BlockPlaceEvent(@NotNull final Block placedBlock, @NotNull final BlockState replacedBlockState, @NotNull final Block placedAgainst, @NotNull final ItemStack itemInHand, @NotNull final Player thePlayer, final boolean canBuild) { - this(placedBlock, replacedBlockState, placedAgainst, itemInHand, thePlayer, canBuild, EquipmentSlot.HAND); - } - - public BlockPlaceEvent(@NotNull final Block placedBlock, @NotNull final BlockState replacedBlockState, @NotNull final Block placedAgainst, @NotNull final ItemStack itemInHand, @NotNull final Player thePlayer, final boolean canBuild, @NotNull final EquipmentSlot hand) { - super(placedBlock); - this.placedAgainst = placedAgainst; - this.itemInHand = itemInHand; - this.player = thePlayer; - this.replacedBlockState = replacedBlockState; - this.canBuild = canBuild; - this.hand = hand; - cancel = false; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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 - */ - @NotNull - 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 - */ - @NotNull - 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. - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - public ItemStack getItemInHand() { - return itemInHand; - } - - /** - * Gets the hand which placed the block - * @return Main or off-hand, depending on which hand was used to place the block - */ - @NotNull - public EquipmentSlot getHand() { - return this.hand; - } - - /** - * 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java b/api/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java deleted file mode 100644 index e46419b8c..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockShearEntityEvent.java b/api/src/main/java/org/bukkit/event/block/BlockShearEntityEvent.java deleted file mode 100644 index 71c0af937..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockShearEntityEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * Event fired when a dispenser shears a nearby sheep. - */ -public class BlockShearEntityEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private final Entity sheared; - private final ItemStack tool; - private boolean cancelled; - - public BlockShearEntityEvent(@NotNull Block dispenser, @NotNull Entity sheared, @NotNull ItemStack tool) { - super(dispenser); - this.sheared = sheared; - this.tool = tool; - } - - /** - * Gets the entity that was sheared. - * - * @return the entity that was sheared. - */ - @NotNull - public Entity getEntity() { - return sheared; - } - - /** - * Gets the item used to shear this sheep. - * - * @return the item used to shear this sheep. - */ - @NotNull - public ItemStack getTool() { - return tool.clone(); - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java b/api/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java deleted file mode 100644 index e9239caec..000000000 --- a/api/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Block block, @NotNull final Block source, @NotNull 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. - */ - @NotNull - public Block getSource() { - return source; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/CauldronLevelChangeEvent.java b/api/src/main/java/org/bukkit/event/block/CauldronLevelChangeEvent.java deleted file mode 100644 index 4aaa78afd..000000000 --- a/api/src/main/java/org/bukkit/event/block/CauldronLevelChangeEvent.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.bukkit.event.block; - -import com.google.common.base.Preconditions; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class CauldronLevelChangeEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - // - private final Entity entity; - private final ChangeReason reason; - private final int oldLevel; - private int newLevel; - - public CauldronLevelChangeEvent(@NotNull Block block, @Nullable Entity entity, @NotNull ChangeReason reason, int oldLevel, int newLevel) { - super(block); - this.entity = entity; - this.reason = reason; - this.oldLevel = oldLevel; - this.newLevel = newLevel; - } - - /** - * Get entity which did this. May be null. - * - * @return acting entity - */ - @Nullable - public Entity getEntity() { - return entity; - } - - @NotNull - public ChangeReason getReason() { - return reason; - } - - public int getOldLevel() { - return oldLevel; - } - - public int getNewLevel() { - return newLevel; - } - - public void setNewLevel(int newLevel) { - Preconditions.checkArgument(0 <= newLevel && newLevel <= 3, "Cauldron level out of bounds 0 <= %s <= 3", newLevel); - this.newLevel = newLevel; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - public enum ChangeReason { - /** - * Player emptying the cauldron by filling their bucket. - */ - BUCKET_FILL, - /** - * Player filling the cauldron by emptying their bucket. - */ - BUCKET_EMPTY, - /** - * Player emptying the cauldron by filling their bottle. - */ - BOTTLE_FILL, - /** - * Player filling the cauldron by emptying their bottle. - */ - BOTTLE_EMPTY, - /** - * Player cleaning their banner. - */ - BANNER_WASH, - /** - * Player cleaning their armor. - */ - ARMOR_WASH, - /** - * Entity being extinguished. - */ - EXTINGUISH, - /** - * Evaporating due to biome dryness. - */ - EVAPORATE, - /** - * Unknown. - */ - UNKNOWN - } -} diff --git a/api/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java b/api/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java deleted file mode 100644 index 3baed1c43..000000000 --- a/api/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a block is formed by entities. - *

- * Examples: - *

    - *
  • Snow formed by a {@link org.bukkit.entity.Snowman}. - *
  • Frosted Ice formed by the Frost Walker enchantment. - *
- */ -public class EntityBlockFormEvent extends BlockFormEvent { - private final Entity entity; - - public EntityBlockFormEvent(@NotNull final Entity entity, @NotNull final Block block, @NotNull final BlockState blockstate) { - super(block, blockstate); - - this.entity = entity; - } - - /** - * Get the entity that formed the block. - * - * @return Entity involved in event - */ - @NotNull - public Entity getEntity() { - return entity; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/FluidLevelChangeEvent.java b/api/src/main/java/org/bukkit/event/block/FluidLevelChangeEvent.java deleted file mode 100644 index 9bd0440c3..000000000 --- a/api/src/main/java/org/bukkit/event/block/FluidLevelChangeEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.bukkit.event.block; - -import com.google.common.base.Preconditions; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when the fluid level of a block changes due to changes in adjacent - * blocks. - */ -public class FluidLevelChangeEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - // - private BlockData newData; - - public FluidLevelChangeEvent(@NotNull Block theBlock, @NotNull BlockData newData) { - super(theBlock); - this.newData = newData; - } - - /** - * Gets the new data of the changed block. - * - * @return new data - */ - @NotNull - public BlockData getNewData() { - return newData; - } - - /** - * Sets the new data of the changed block. Must be of the same Material as - * the old one. - * - * @param newData the new data - */ - public void setNewData(@NotNull BlockData newData) { - Preconditions.checkArgument(newData != null, "newData null"); - Preconditions.checkArgument(this.newData.getMaterial().equals(newData.getMaterial()), "Cannot change fluid type"); - - this.newData = newData; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java b/api/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java deleted file mode 100644 index c33f9cb80..000000000 --- a/api/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.event.block; - -import org.bukkit.block.Block; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Block block) { - super(block); - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/block/MoistureChangeEvent.java b/api/src/main/java/org/bukkit/event/block/MoistureChangeEvent.java deleted file mode 100644 index bf5de52e7..000000000 --- a/api/src/main/java/org/bukkit/event/block/MoistureChangeEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * Called when the moisture level of a soil block changes. - */ -public class MoistureChangeEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final BlockState newState; - - public MoistureChangeEvent(@NotNull final Block block, @NotNull final BlockState newState) { - super(block); - this.newState = newState; - this.cancelled = false; - } - - /** - * Gets the new state of the affected block. - * - * @return new block state - */ - @NotNull - public BlockState getNewState() { - return newState; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/NotePlayEvent.java b/api/src/main/java/org/bukkit/event/block/NotePlayEvent.java deleted file mode 100644 index a3887067d..000000000 --- a/api/src/main/java/org/bukkit/event/block/NotePlayEvent.java +++ /dev/null @@ -1,93 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Block block, @NotNull Instrument instrument, @NotNull Note note) { - super(block); - this.instrument = instrument; - this.note = note; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - /** - * Gets the {@link Instrument} to be used. - * - * @return the Instrument - */ - @NotNull - public Instrument getInstrument() { - return instrument; - } - - /** - * Gets the {@link Note} to be played. - * - * @return the Note - */ - @NotNull - public Note getNote() { - return note; - } - - /** - * Overrides the {@link Instrument} to be used. - * - * @param instrument the Instrument. Has no effect if null. - * @deprecated no effect on newer Minecraft versions - */ - @Deprecated - public void setInstrument(@NotNull Instrument instrument) { - if (instrument != null) { - this.instrument = instrument; - } - } - - /** - * Overrides the {@link Note} to be played. - * - * @param note the Note. Has no effect if null. - * @deprecated no effect on newer Minecraft versions - */ - @Deprecated - public void setNote(@NotNull Note note) { - if (note != null) { - this.note = note; - } - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/block/SignChangeEvent.java b/api/src/main/java/org/bukkit/event/block/SignChangeEvent.java deleted file mode 100644 index 7190db11e..000000000 --- a/api/src/main/java/org/bukkit/event/block/SignChangeEvent.java +++ /dev/null @@ -1,93 +0,0 @@ -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.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull final Block theBlock, @NotNull final Player thePlayer, @NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - 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} - */ - @Nullable - 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, @Nullable String line) throws IndexOutOfBoundsException { - lines[index] = line; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/block/SpongeAbsorbEvent.java b/api/src/main/java/org/bukkit/event/block/SpongeAbsorbEvent.java deleted file mode 100644 index 7029cfcd0..000000000 --- a/api/src/main/java/org/bukkit/event/block/SpongeAbsorbEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bukkit.event.block; - -import java.util.List; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a sponge absorbs water from the world. - *
- * The world will be in its previous state, and {@link #getBlocks()} will - * represent the changes to be made to the world, if the event is not cancelled. - *
- * As this is a physics based event it may be called multiple times for "the - * same" changes. - */ -public class SpongeAbsorbEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final List blocks; - - public SpongeAbsorbEvent(@NotNull Block block, @NotNull List waterblocks) { - super(block); - this.blocks = waterblocks; - } - - /** - * Get a list of all blocks to be removed by the sponge. - *
- * This list is mutable and contains the blocks in their removed state, i.e. - * having a type of {@link Material#AIR}. - * - * @return list of the to be removed blocks. - */ - @NotNull - public List getBlocks() { - return blocks; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/command/UnknownCommandEvent.java b/api/src/main/java/org/bukkit/event/command/UnknownCommandEvent.java deleted file mode 100644 index 251342c3c..000000000 --- a/api/src/main/java/org/bukkit/event/command/UnknownCommandEvent.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.bukkit.event.command; - -import org.bukkit.command.CommandSender; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Event; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Thrown when a player executes a command that is not defined - */ -public class UnknownCommandEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - @NotNull private CommandSender sender; - @NotNull private String commandLine; - @Nullable private String message; - - public UnknownCommandEvent(@NotNull final CommandSender sender, @NotNull final String commandLine, @Nullable final String message) { - super(false); - this.sender = sender; - this.commandLine = commandLine; - this.message = message; - } - - /** - * Gets the CommandSender or ConsoleCommandSender - *

- * - * @return Sender of the command - */ - @NotNull - public CommandSender getSender() { - return sender; - } - - /** - * Gets the command that was send - *

- * - * @return Command sent - */ - @NotNull - public String getCommandLine() { - return commandLine; - } - - /** - * Gets message that will be returned - *

- * - * @return Unknown command message - */ - @Nullable - public String getMessage() { - return message; - } - - - /** - * Sets message that will be returned - *

- * Set to null to avoid any message being sent - * - * @param message the message to be returned, or null - */ - public void setMessage(@Nullable String message) { - this.message = message; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} - diff --git a/api/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java b/api/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java deleted file mode 100644 index 69b74647e..000000000 --- a/api/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.bukkit.event.enchantment; - -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang.Validate; -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 org.jetbrains.annotations.NotNull; - -/** - * 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 final int button; - - public EnchantItemEvent(@NotNull final Player enchanter, @NotNull final InventoryView view, @NotNull final Block table, @NotNull final ItemStack item, final int level, @NotNull 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 - */ - @NotNull - public Player getEnchanter() { - return enchanter; - } - - /** - * Gets the block being used to enchant the item - * - * @return the block used for enchanting - */ - @NotNull - public Block getEnchantBlock() { - return table; - } - - /** - * Gets the item to be enchanted (can be modified) - * - * @return ItemStack of item - */ - @NotNull - public ItemStack getItem() { - return item; - } - - /** - * Gets the cost (minimum level) which is displayed as a number on the right - * hand side of the enchantment offer. - * - * @return experience level cost - */ - public int getExpLevelCost() { - return level; - } - - /** - * Sets the cost (minimum level) which is displayed as a number on the right - * hand side of the enchantment offer. - * - * @param level - cost in levels - */ - public void setExpLevelCost(int level) { - Validate.isTrue(level > 0, "The cost must be greater than 0!"); - - 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 - */ - @NotNull - 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; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java b/api/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java deleted file mode 100644 index 2ff1b1308..000000000 --- a/api/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.bukkit.event.enchantment; - -import org.bukkit.block.Block; -import org.bukkit.enchantments.EnchantmentOffer; -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 org.jetbrains.annotations.NotNull; - -/** - * 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 EnchantmentOffer[] offers; - private final int bonus; - private boolean cancelled; - private final Player enchanter; - - public PrepareItemEnchantEvent(@NotNull final Player enchanter, @NotNull InventoryView view, @NotNull final Block table, @NotNull final ItemStack item, @NotNull final EnchantmentOffer[] offers, final int bonus) { - super(view); - this.enchanter = enchanter; - this.table = table; - this.item = item; - this.offers = offers; - this.bonus = bonus; - } - - /** - * Gets the player enchanting the item - * - * @return enchanting player - */ - @NotNull - public Player getEnchanter() { - return enchanter; - } - - /** - * Gets the block being used to enchant the item - * - * @return the block used for enchanting - */ - @NotNull - public Block getEnchantBlock() { - return table; - } - - /** - * Gets the item to be enchanted. - * - * @return ItemStack of item - */ - @NotNull - public ItemStack getItem() { - return item; - } - - /** - * Get a list of offered experience level costs of the enchantment. - * - * @return experience level costs offered - * @deprecated Use {@link #getOffers()} instead of this method - */ - @NotNull - public int[] getExpLevelCostsOffered() { - int[] levelOffers = new int[offers.length]; - for (int i = 0; i < offers.length; i++) { - levelOffers[i] = offers[i] != null ? offers[i].getCost() : 0; - } - return levelOffers; - } - - /** - * Get a list of available {@link EnchantmentOffer} for the player. You can - * modify the values to change the available offers for the player. An offer - * may be null, if there isn't a enchantment offer at a specific slot. There - * are 3 slots in the enchantment table available to modify. - * - * @return list of available enchantment offers - */ - @NotNull - public EnchantmentOffer[] getOffers() { - return offers; - } - - /** - * Get enchantment bonus in effect - corresponds to number of bookshelves - * - * @return enchantment bonus - */ - public int getEnchantmentBonus() { - return bonus; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/AreaEffectCloudApplyEvent.java b/api/src/main/java/org/bukkit/event/entity/AreaEffectCloudApplyEvent.java deleted file mode 100644 index a37febd0d..000000000 --- a/api/src/main/java/org/bukkit/event/entity/AreaEffectCloudApplyEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.bukkit.event.entity; - -import java.util.List; -import org.bukkit.entity.AreaEffectCloud; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a lingering potion applies it's effects. Happens - * once every 5 ticks - */ -public class AreaEffectCloudApplyEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private final List affectedEntities; - private boolean cancelled = false; - - public AreaEffectCloudApplyEvent(@NotNull final AreaEffectCloud entity, @NotNull final List affectedEntities) { - super(entity); - this.affectedEntities = affectedEntities; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @Override - @NotNull - public AreaEffectCloud getEntity() { - return (AreaEffectCloud) entity; - } - - /** - * Retrieves a mutable list of the effected entities - *

- * It is important to note that not every entity in this list - * is guaranteed to be effected. The cloud may die during the - * application of its effects due to the depletion of {@link AreaEffectCloud#getDurationOnUse()} - * or {@link AreaEffectCloud#getRadiusOnUse()} - * - * @return the affected entity list - */ - @NotNull - public List getAffectedEntities() { - return affectedEntities; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/BatToggleSleepEvent.java b/api/src/main/java/org/bukkit/event/entity/BatToggleSleepEvent.java deleted file mode 100644 index 5a5615d17..000000000 --- a/api/src/main/java/org/bukkit/event/entity/BatToggleSleepEvent.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Bat; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a bat attempts to sleep or wake up from its slumber. - *

- * If a Bat Toggle Sleep event is cancelled, the Bat will not toggle its sleep - * state. - */ -public class BatToggleSleepEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - - private boolean cancel = false; - private final boolean awake; - - public BatToggleSleepEvent(@NotNull Bat what, boolean awake) { - super(what); - this.awake = awake; - } - - /** - * Get whether or not the bat is attempting to awaken. - * - * @return true if trying to awaken, false otherwise - */ - public boolean isAwake() { - return awake; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java b/api/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java deleted file mode 100644 index f7049face..000000000 --- a/api/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java +++ /dev/null @@ -1,181 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Chunk; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.world.ChunkLoadEvent; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final LivingEntity spawnee, @NotNull final SpawnReason spawnReason) { - super(spawnee); - this.spawnReason = spawnReason; - } - - @NotNull - @Override - public LivingEntity getEntity() { - return (LivingEntity) entity; - } - - /** - * Gets the reason for why the creature is being spawned. - * - * @return A SpawnReason value detailing the reason for the creature being - * spawned - */ - @NotNull - 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 - * - * @deprecated no longer called, chunks are generated with entities - * already existing. Consider using {@link ChunkLoadEvent}, - * {@link ChunkLoadEvent#isNewChunk()} and {@link Chunk#getEntities()} - * for similar effect. - */ - @Deprecated - 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 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 an entity spawns as a trap for players approaching - */ - TRAP, - /** - * When an entity is spawned as a result of ender pearl usage - */ - ENDER_PEARL, - /** - * When an entity is spawned as a result of the entity it is being - * perched on jumping or being damaged - */ - SHOULDER_ENTITY, - /** - * When a creature is spawned by another entity drowning - */ - DROWNED, - /** - * When an cow is spawned by shearing a mushroom cow - */ - SHEARED, - /** - * When eg an effect cloud is spawned as a result of a creeper exploding - */ - EXPLOSION, - /** - * When an entity is spawned as part of a raid - */ - RAID, - /** - * When an entity is spawned as part of a patrol - */ - PATROL, - /** - * When a creature is spawned by plugins - */ - CUSTOM, - /** - * When an entity is missing a SpawnReason - */ - DEFAULT - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java b/api/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java deleted file mode 100644 index 4295baf51..000000000 --- a/api/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java +++ /dev/null @@ -1,102 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull final Creeper creeper, @NotNull final LightningStrike bolt, @NotNull final PowerCause cause) { - this(creeper, cause); - this.bolt = bolt; - } - - public CreeperPowerEvent(@NotNull final Creeper creeper, @NotNull final PowerCause cause) { - super(creeper); - this.cause = cause; - } - - @Override - public boolean isCancelled() { - return canceled; - } - - @Override - public void setCancelled(boolean cancel) { - canceled = cancel; - } - - @NotNull - @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 - */ - @Nullable - 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. - */ - @NotNull - public PowerCause getCause() { - return cause; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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/api/src/main/java/org/bukkit/event/entity/EnderDragonChangePhaseEvent.java b/api/src/main/java/org/bukkit/event/entity/EnderDragonChangePhaseEvent.java deleted file mode 100644 index 631ca54dc..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EnderDragonChangePhaseEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.bukkit.event.entity; - -import org.apache.commons.lang.Validate; -import org.bukkit.entity.EnderDragon; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when an EnderDragon switches controller phase. - */ -public class EnderDragonChangePhaseEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancel; - private final EnderDragon.Phase currentPhase; - private EnderDragon.Phase newPhase; - - public EnderDragonChangePhaseEvent(@NotNull EnderDragon enderDragon, @Nullable EnderDragon.Phase currentPhase, @NotNull EnderDragon.Phase newPhase) { - super(enderDragon); - this.currentPhase = currentPhase; - this.setNewPhase(newPhase); - } - - @NotNull - @Override - public EnderDragon getEntity() { - return (EnderDragon) entity; - } - - /** - * Gets the current phase that the dragon is in. This method will return null - * when a dragon is first spawned and hasn't yet been assigned a phase. - * - * @return the current dragon phase - */ - @Nullable - public EnderDragon.Phase getCurrentPhase() { - return currentPhase; - } - - /** - * Gets the new phase that the dragon will switch to. - * - * @return the new dragon phase - */ - @NotNull - public EnderDragon.Phase getNewPhase() { - return newPhase; - } - - /** - * Sets the new phase for the ender dragon. - * - * @param newPhase the new dragon phase - */ - public void setNewPhase(@NotNull EnderDragon.Phase newPhase) { - Validate.notNull(newPhase, "New dragon phase cannot be null"); - this.newPhase = newPhase; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/entity/EntityAirChangeEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityAirChangeEvent.java deleted file mode 100644 index cd20a4aa4..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityAirChangeEvent.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when the amount of air an entity has remaining changes. - */ -public class EntityAirChangeEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private int amount; - // - private boolean cancelled; - - public EntityAirChangeEvent(@NotNull Entity what, int amount) { - super(what); - this.amount = amount; - } - - /** - * Gets the amount of air the entity has left (measured in ticks). - * - * @return amount of air remaining - */ - public int getAmount() { - return amount; - } - - /** - * Sets the amount of air remaining for the entity (measured in ticks. - * - * @param amount amount of air remaining - */ - public void setAmount(int amount) { - this.amount = amount; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java deleted file mode 100644 index 30b9bdca8..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java +++ /dev/null @@ -1,24 +0,0 @@ -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.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final LivingEntity entity, @NotNull final Block targetBlock) { - super(entity, targetBlock, Material.AIR.createBlockData()); - } - - @NotNull - @Override - public LivingEntity getEntity() { - return (LivingEntity) entity; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityBreedEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityBreedEvent.java deleted file mode 100644 index ded0693f9..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityBreedEvent.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.bukkit.event.entity; - -import org.apache.commons.lang.Validate; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when one Entity breeds with another Entity. - */ -public class EntityBreedEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private final LivingEntity mother; - private final LivingEntity father; - private final LivingEntity breeder; - private final ItemStack bredWith; - private int experience; - // - private boolean cancel; - - public EntityBreedEvent(@NotNull LivingEntity child, @NotNull LivingEntity mother, @NotNull LivingEntity father, @Nullable LivingEntity breeder, @Nullable ItemStack bredWith, int experience) { - super(child); - - Validate.notNull(child, "Cannot have null child"); - Validate.notNull(mother, "Cannot have null mother"); - Validate.notNull(father, "Cannot have null father"); - - // Breeder can be null in the case of spontaneous conception - this.mother = mother; - this.father = father; - this.breeder = breeder; - this.bredWith = bredWith; - - setExperience(experience); - } - - @NotNull - @Override - public LivingEntity getEntity() { - return (LivingEntity) entity; - } - - /** - * Gets the parent creating this entity. - * - * @return The "birth" parent - */ - @NotNull - public LivingEntity getMother() { - return mother; - } - - /** - * Gets the other parent of the newly born entity. - * - * @return the other parent - */ - @NotNull - public LivingEntity getFather() { - return father; - } - - /** - * Gets the Entity responsible for breeding. Breeder is null for spontaneous - * conception. - * - * @return The Entity who initiated breeding. - */ - @Nullable - public LivingEntity getBreeder() { - return breeder; - } - - /** - * The ItemStack that was used to initiate breeding, if present. - * - * @return ItemStack used to initiate breeding. - */ - @Nullable - public ItemStack getBredWith() { - return bredWith; - } - - /** - * Get the amount of experience granted by breeding. - * - * @return experience amount - */ - public int getExperience() { - return experience; - } - - /** - * Set the amount of experience granted by breeding. - * - * @param experience experience amount - */ - public void setExperience(int experience) { - Validate.isTrue(experience >= 0, "Experience cannot be negative"); - this.experience = experience; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java deleted file mode 100644 index e79fc76bb..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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 BlockData to; - - public EntityChangeBlockEvent(@NotNull final Entity what, @NotNull final Block block, @NotNull final BlockData to) { - super(what); - this.block = block; - this.cancel = false; - this.to = to; - } - - /** - * Gets the block the entity is changing - * - * @return the block that is changing - */ - @NotNull - public Block getBlock() { - return block; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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 - */ - @NotNull - public Material getTo() { - return to.getMaterial(); - } - - /** - * Gets the data for the block that would be changed into - * - * @return the data for the block that would be changed into - */ - @NotNull - public BlockData getBlockData() { - return to; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java deleted file mode 100644 index 5886ee448..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a block causes an entity to combust. - */ -public class EntityCombustByBlockEvent extends EntityCombustEvent { - private final Block combuster; - - public EntityCombustByBlockEvent(@Nullable final Block combuster, @NotNull 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. - */ - @Nullable - public Block getCombuster() { - return combuster; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java deleted file mode 100644 index 0b67364e1..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an entity causes another entity to combust. - */ -public class EntityCombustByEntityEvent extends EntityCombustEvent { - private final Entity combuster; - - public EntityCombustByEntityEvent(@NotNull final Entity combuster, @NotNull 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. - */ - @NotNull - public Entity getCombuster() { - return combuster; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java deleted file mode 100644 index eea9aa7bf..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Entity combustee, final int duration) { - super(combustee); - this.duration = duration; - this.cancel = false; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java deleted file mode 100644 index 397baaefd..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bukkit.event.entity; - -import java.util.List; -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 org.bukkit.event.world.PortalCreateEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Thrown when a Living Entity creates a portal in a world. - * - * @deprecated Use {@link PortalCreateEvent} - */ -@Deprecated -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(@NotNull final LivingEntity what, @NotNull final List blocks, @NotNull final PortalType type) { - super(what); - - this.blocks = blocks; - this.type = type; - } - - @NotNull - @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. - */ - @NotNull - public List getBlocks() { - return blocks; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - /** - * Gets the type of portal that is trying to be created. - * - * @return Type of portal. - */ - @NotNull - public PortalType getPortalType() { - return type; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java deleted file mode 100644 index 461727dc7..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.event.entity; - -import com.google.common.base.Function; -import java.util.Map; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when an entity is damaged by a block - */ -public class EntityDamageByBlockEvent extends EntityDamageEvent { - private final Block damager; - - public EntityDamageByBlockEvent(@Nullable final Block damager, @NotNull final Entity damagee, @NotNull final DamageCause cause, final double damage) { - super(damagee, cause, damage); - this.damager = damager; - } - - public EntityDamageByBlockEvent(@Nullable final Block damager, @NotNull final Entity damagee, @NotNull final DamageCause cause, @NotNull final Map modifiers, @NotNull final Map> modifierFunctions) { - super(damagee, cause, modifiers, modifierFunctions); - this.damager = damager; - } - - /** - * Returns the block that damaged the player. - * - * @return Block that damaged the player - */ - @Nullable - public Block getDamager() { - return damager; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java deleted file mode 100644 index 869bad740..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.event.entity; - -import com.google.common.base.Function; -import java.util.Map; -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an entity is damaged by an entity - */ -public class EntityDamageByEntityEvent extends EntityDamageEvent { - private final Entity damager; - - public EntityDamageByEntityEvent(@NotNull final Entity damager, @NotNull final Entity damagee, @NotNull final DamageCause cause, final double damage) { - super(damagee, cause, damage); - this.damager = damager; - } - - public EntityDamageByEntityEvent(@NotNull final Entity damager, @NotNull final Entity damagee, @NotNull final DamageCause cause, @NotNull final Map modifiers, @NotNull final Map> modifierFunctions) { - super(damagee, cause, modifiers, modifierFunctions); - this.damager = damager; - } - - /** - * Returns the entity that damaged the defender. - * - * @return Entity that damaged the defender. - */ - @NotNull - public Entity getDamager() { - return damager; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java deleted file mode 100644 index 4d1b4d1f8..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java +++ /dev/null @@ -1,434 +0,0 @@ -package org.bukkit.event.entity; - -import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.collect.ImmutableMap; -import java.util.EnumMap; -import java.util.Map; -import org.apache.commons.lang.Validate; -import org.bukkit.Material; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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 cancelled; - private final DamageCause cause; - - public EntityDamageEvent(@NotNull final Entity damagee, @NotNull 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(@NotNull final Entity damagee, @NotNull final DamageCause cause, @NotNull final Map modifiers, @NotNull final Map> modifierFunctions) { - 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; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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; - } - - /** - * 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); - } - - /** - * Gets the cause of the damage. - * - * @return A DamageCause value detailing the cause of the damage. - */ - @NotNull - public DamageCause getCause() { - return cause; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * An enum to specify the types of modifier - * - * @deprecated This API is responsible for a large number of implementation - * problems and is in general unsustainable to maintain. It is likely to be - * removed very soon in a subsequent release. Please see - * https://www.spigotmc.org/threads/194446/ for more information. - */ - @Deprecated - 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 an entity attacks another entity in a sweep attack. - *

- * Damage: variable - */ - ENTITY_SWEEP_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, - /** - * Damage caused by a dragon breathing fire. - *

- * Damage: variable - */ - DRAGON_BREATH, - /** - * Custom damage. - *

- * Damage: variable - */ - CUSTOM, - /** - * Damage caused when an entity runs into a wall. - *

- * Damage: variable - */ - FLY_INTO_WALL, - /** - * Damage caused when an entity steps on {@link Material#MAGMA_BLOCK}. - *

- * Damage: 1 - */ - HOT_FLOOR, - /** - * Damage caused when an entity is colliding with too many entities due - * to the maxEntityCramming game rule. - *

- * Damage: 6 - */ - CRAMMING, - /** - * Damage caused when an entity that should be in water is not. - *

- * Damage: 1 - */ - DRYOUT - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java deleted file mode 100644 index e19a3df9a..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java +++ /dev/null @@ -1,217 +0,0 @@ -package org.bukkit.event.entity; - -import java.util.List; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Thrown whenever a LivingEntity dies - */ -public class EntityDeathEvent extends EntityEvent implements org.bukkit.event.Cancellable { // Paper - make cancellable - private static final HandlerList handlers = new HandlerList(); - private final List drops; - private int dropExp = 0; - // Paper start - make cancellable - private boolean cancelled; - private double reviveHealth = 0; - private boolean shouldPlayDeathSound; - @Nullable private org.bukkit.Sound deathSound; - @Nullable private org.bukkit.SoundCategory deathSoundCategory; - private float deathSoundVolume; - private float deathSoundPitch; - // Paper end - - public EntityDeathEvent(@NotNull final LivingEntity entity, @NotNull final List drops) { - this(entity, drops, 0); - } - - public EntityDeathEvent(@NotNull final LivingEntity what, @NotNull final List drops, final int droppedExp) { - super(what); - this.drops = drops; - this.dropExp = droppedExp; - } - - @NotNull - @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 - */ - @NotNull - public List getDrops() { - return drops; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - // Paper start - make cancellable - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - /** - * Get the amount of health that the entity should revive with after cancelling the event. - * Set to the entity's max health by default. - * - * @return The amount of health - */ - public double getReviveHealth() { - return reviveHealth; - } - - /** - * Set the amount of health that the entity should revive with after cancelling the event. - * Revive health value must be between 0 (exclusive) and the entity's max health (inclusive). - * - * @param reviveHealth The amount of health - * @throws IllegalArgumentException Thrown if the health is {@literal <= 0 or >} max health - */ - public void setReviveHealth(double reviveHealth) throws IllegalArgumentException { - double maxHealth = ((LivingEntity) entity).getAttribute(org.bukkit.attribute.Attribute.GENERIC_MAX_HEALTH).getValue(); - if ((maxHealth != 0 && reviveHealth <= 0) || (reviveHealth > maxHealth)) { - throw new IllegalArgumentException("Health must be between 0 (exclusive) and " + maxHealth + " (inclusive), but was " + reviveHealth); - } - this.reviveHealth = reviveHealth; - } - - - /** - * Whether or not the death sound should play when the entity dies. If the event is cancelled it does not play! - * - * @return Whether or not the death sound should play. Event is called with this set to false if the entity is silent. - */ - public boolean shouldPlayDeathSound() { - return shouldPlayDeathSound; - } - - /** - * Set whether or not the death sound should play when the entity dies. If the event is cancelled it does not play! - * - * @param playDeathSound Enable or disable the death sound - */ - public void setShouldPlayDeathSound(boolean playDeathSound) { - this.shouldPlayDeathSound = playDeathSound; - } - - /** - * Get the sound that the entity makes when dying - * - * @return The sound that the entity makes - */ - @Nullable - public org.bukkit.Sound getDeathSound() { - return deathSound; - } - - /** - * Set the sound that the entity makes when dying - * - * @param sound The sound that the entity should make when dying - */ - public void setDeathSound(@Nullable org.bukkit.Sound sound) { - deathSound = sound; - } - - /** - * Get the sound category that the death sound should play in - * - * @return The sound category - */ - @Nullable - public org.bukkit.SoundCategory getDeathSoundCategory() { - return deathSoundCategory; - } - - /** - * Set the sound category that the death sound should play in. - * - * @param soundCategory The sound category - */ - public void setDeathSoundCategory(@Nullable org.bukkit.SoundCategory soundCategory) { - this.deathSoundCategory = soundCategory; - } - - /** - * Get the volume that the death sound will play at. - * - * @return The volume the death sound will play at - */ - public float getDeathSoundVolume() { - return deathSoundVolume; - } - - /** - * Set the volume the death sound should play at. If the event is cancelled this will not play the sound! - * - * @param volume The volume the death sound should play at - */ - public void setDeathSoundVolume(float volume) { - this.deathSoundVolume = volume; - } - - /** - * Get the pitch that the death sound will play with. - * - * @return The pitch the death sound will play with - */ - public float getDeathSoundPitch() { - return deathSoundPitch; - } - - /** - * GSetet the pitch that the death sound should play with. - * - * @param pitch The pitch the death sound should play with - */ - public void setDeathSoundPitch(float pitch) { - this.deathSoundPitch = pitch; - } - // Paper end -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityDropItemEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityDropItemEvent.java deleted file mode 100644 index 3ccdcc755..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityDropItemEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Item; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Thrown when an entity creates an item drop. - */ -public class EntityDropItemEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private final Item drop; - private boolean cancel = false; - - public EntityDropItemEvent(@NotNull final Entity entity, @NotNull final Item drop) { - super(entity); - this.drop = drop; - } - - /** - * Gets the Item created by the entity - * - * @return Item created by the entity - */ - @NotNull - public Item getItemDrop() { - return drop; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/entity/EntityEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityEvent.java deleted file mode 100644 index e3a9e3293..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityEvent.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.event.Event; -import org.jetbrains.annotations.NotNull; - -/** - * Represents an Entity-related event - */ -public abstract class EntityEvent extends Event { - protected Entity entity; - - public EntityEvent(@NotNull final Entity what) { - entity = what; - } - - /** - * Returns the Entity involved in this event - * - * @return Entity who is involved in this event - */ - @NotNull - public Entity getEntity() { - return entity; - } - - /** - * Gets the EntityType of the Entity involved in this event. - * - * @return EntityType of the Entity involved in this event - */ - @NotNull - public EntityType getEntityType() { - return entity.getType(); - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java deleted file mode 100644 index 10d0e18df..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.bukkit.event.entity; - -import java.util.List; -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 org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Entity what, @NotNull final Location location, @NotNull final List blocks, final float yield) { - super(what); - this.location = location; - this.blocks = blocks; - this.yield = yield; - this.cancel = false; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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 - */ - @NotNull - 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 - */ - @NotNull - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java deleted file mode 100644 index e2c0cb339..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Entity entity, @NotNull final Block block) { - super(entity); - this.block = block; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - /** - * Returns the involved block - * - * @return the block clicked with this item. - */ - @NotNull - public Block getBlock() { - return block; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java deleted file mode 100644 index c866df03d..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -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; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/entity/EntityPlaceEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityPlaceEvent.java deleted file mode 100644 index ea21069b9..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityPlaceEvent.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Warning; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Triggered when a entity is created in the world by a player "placing" an item - * on a block. - *
- * Note that this event is currently only fired for three specific placements: - * armor stands, minecarts, and end crystals. - * - * @deprecated draft API - */ -@Deprecated -@Warning(false) -public class EntityPlaceEvent extends EntityEvent 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 EntityPlaceEvent(@NotNull final Entity entity, @Nullable final Player player, @NotNull final Block block, @NotNull final BlockFace blockFace) { - super(entity); - this.player = player; - this.block = block; - this.blockFace = blockFace; - } - - /** - * Returns the player placing the entity - * - * @return the player placing the entity - */ - @Nullable - public Player getPlayer() { - return player; - } - - /** - * Returns the block that the entity was placed on - * - * @return the block that the entity was placed on - */ - @NotNull - public Block getBlock() { - return block; - } - - /** - * Returns the face of the block that the entity was placed on - * - * @return the face of the block that the entity was placed on - */ - @NotNull - public BlockFace getBlockFace() { - return blockFace; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java deleted file mode 100644 index 6818e9f0b..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Entity entity, @NotNull final Location location) { - super(entity); - this.location = location; - } - - /** - * Gets the portal block the entity is touching - * - * @return The portal block the entity is touching - */ - @NotNull - public Location getLocation() { - return location; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java deleted file mode 100644 index 7fdfe3c5a..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(); - - public EntityPortalEvent(@NotNull final Entity entity, @NotNull final Location from, @Nullable final Location to) { - super(entity, from, to); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java deleted file mode 100644 index 869ad3b12..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.event.HandlerList; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Entity entity, @NotNull final Location from, @NotNull final Location to, @NotNull final Vector before, @NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - 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(@NotNull Vector after) { - this.after = after.clone(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityPoseChangeEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityPoseChangeEvent.java deleted file mode 100644 index 6fb2b02ac..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityPoseChangeEvent.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Pose; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an entity changes its pose. - * - * @see Entity#getPose() - */ -public class EntityPoseChangeEvent extends EntityEvent { - - private static final HandlerList handlers = new HandlerList(); - // - private final Pose pose; - - public EntityPoseChangeEvent(@NotNull Entity who, @NotNull Pose pose) { - super(who); - this.pose = pose; - } - - /** - * Gets the entity's new pose. - * - * @return the new pose - */ - @NotNull - public Pose getPose() { - return pose; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityPotionEffectEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityPotionEffectEvent.java deleted file mode 100644 index d5f8bde3b..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityPotionEffectEvent.java +++ /dev/null @@ -1,249 +0,0 @@ -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; -import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a potion effect is modified on an entity. - *

- * If the event is cancelled, no change will be made on the entity. - */ -public class EntityPotionEffectEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancel; - private final PotionEffect oldEffect; - private final PotionEffect newEffect; - private final Cause cause; - private final Action action; - private boolean override; - - @Contract("_, null, null, _, _, _ -> fail") - public EntityPotionEffectEvent(@NotNull LivingEntity livingEntity, @Nullable PotionEffect oldEffect, @Nullable PotionEffect newEffect, @NotNull Cause cause, @NotNull Action action, boolean override) { - super(livingEntity); - this.oldEffect = oldEffect; - this.newEffect = newEffect; - this.cause = cause; - this.action = action; - this.override = override; - } - - /** - * Gets the old potion effect of the changed type, which will be removed. - * - * @return The old potion effect or null if the entity did not have the - * changed effect type. - */ - @Nullable - public PotionEffect getOldEffect() { - return oldEffect; - } - - /** - * Gets new potion effect of the changed type to be applied. - * - * @return The new potion effect or null if the effect of the changed type - * will be removed. - */ - @Nullable - public PotionEffect getNewEffect() { - return newEffect; - } - - /** - * Gets the cause why the effect has changed. - * - * @return A Cause value why the effect has changed. - */ - @NotNull - public Cause getCause() { - return cause; - } - - /** - * Gets the action which will be performed on the potion effect type. - * - * @return An action to be performed on the potion effect type. - */ - @NotNull - public Action getAction() { - return action; - } - - /** - * Gets the modified potion effect type. - * - * @return The effect type which will be modified on the entity. - */ - @NotNull - public PotionEffectType getModifiedType() { - return (oldEffect == null) ? ((newEffect == null) ? null : newEffect.getType()) : oldEffect.getType(); - } - - /** - * Returns if the new potion effect will override the old potion effect - * (Only applicable for the CHANGED Action). - * - * @return If the new effect will override the old one. - */ - public boolean isOverride() { - return override; - } - - /** - * Sets if the new potion effect will override the old potion effect (Only - * applicable for the CHANGED action). - * - * @param override If the new effect will override the old one. - */ - public void setOverride(boolean override) { - this.override = override; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * An enum to specify the action to be performed. - */ - public enum Action { - - /** - * When the potion effect is added because the entity didn't have it's - * type. - */ - ADDED, - /** - * When the entity already had the potion effect type, but the effect is - * changed. - */ - CHANGED, - /** - * When the effect is removed due to all effects being removed. - */ - CLEARED, - /** - * When the potion effect type is completely removed. - */ - REMOVED - } - - /** - * An enum to specify the cause why an effect was changed. - */ - public enum Cause { - - /** - * When the entity stands inside an area effect cloud. - */ - AREA_EFFECT_CLOUD, - /** - * When the entity is hit by an spectral or tipped arrow. - */ - ARROW, - /** - * When the entity is inflicted with a potion effect due to an entity - * attack (e.g. a cave spider or a shulker bullet). - */ - ATTACK, - /** - * When beacon effects get applied due to the entity being nearby. - */ - BEACON, - /** - * When a potion effect is changed due to the /effect command. - */ - COMMAND, - /** - * When the entity gets the effect from a conduit. - */ - CONDUIT, - /** - * When a conversion from a villager zombie to a villager is started or - * finished. - */ - CONVERSION, - /** - * When all effects are removed due to death (Note: This is called on - * respawn, so it's player only!) - */ - DEATH, - /** - * When the entity gets the effect from a dolphin. - */ - DOLPHIN, - /** - * When the effect was removed due to expiration. - */ - EXPIRATION, - /** - * When an effect is inflicted due to food (e.g. when a player eats or a - * cookie is given to a parrot). - */ - FOOD, - /** - * When an illusion illager makes himself disappear. - */ - ILLUSION, - /** - * When all effects are removed due to a bucket of milk. - */ - MILK, - /** - * When a potion effect is modified through the plugin methods. - */ - PLUGIN, - /** - * When the entity drinks a potion. - */ - POTION_DRINK, - /** - * When the entity is inflicted with an effect due to a splash potion. - */ - POTION_SPLASH, - /** - * When a spider gets effects when spawning on hard difficulty. - */ - SPIDER_SPAWN, - /** - * When the entity gets effects from a totem item saving it's life. - */ - TOTEM, - /** - * When the entity gets water breathing by wearing a turtle helmet. - */ - TURTLE_HELMET, - /** - * When the Cause is missing. - */ - UNKNOWN, - /** - * When a villager gets regeneration after a trade. - */ - VILLAGER_TRADE - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java deleted file mode 100644 index d51d2ec1d..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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; - private final boolean isFastRegen; // Paper - - public EntityRegainHealthEvent(@NotNull final Entity entity, final double amount, @NotNull final RegainReason regainReason) { - // Paper start - Forward - this(entity, amount, regainReason, false); - } - - public EntityRegainHealthEvent(@NotNull final Entity entity, final double amount, @NotNull final RegainReason regainReason, boolean isFastRegen) { - // Paper end - super(entity); - this.amount = amount; - this.regainReason = regainReason; - this.isFastRegen = isFastRegen; // Paper - } - - // Paper start - Add getter for isFastRegen - /** - * Is this event a result of the fast regeneration mechanic - * - * @return Whether the event is the result of a fast regeneration mechanic - */ - public boolean isFastRegen() { - return isFastRegen; - } - // Paper end - - /** - * Gets the amount of regained health - * - * @return The amount of health regained - */ - public double getAmount() { - return amount; - } - - /** - * Sets the amount of regained health - * - * @param amount the amount of health the entity will regain - */ - public void setAmount(double amount) { - this.amount = 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 - */ - @NotNull - public RegainReason getRegainReason() { - return regainReason; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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/api/src/main/java/org/bukkit/event/entity/EntityResurrectEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityResurrectEvent.java deleted file mode 100644 index fa6b6c3b0..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityResurrectEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an entity dies and may have the opportunity to be resurrected. - * Will be called in a cancelled state if the entity does not have a totem - * equipped. - */ -public class EntityResurrectEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private boolean cancelled; - - public EntityResurrectEvent(@NotNull LivingEntity what) { - super(what); - } - - @NotNull - @Override - public LivingEntity getEntity() { - return (LivingEntity) entity; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java deleted file mode 100644 index 37dbc12eb..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Projectile; // Paper -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 boolean cancelled; - // Paper start - private boolean consumeArrow = true; - private final ItemStack arrowItem; - public void setConsumeArrow(boolean consumeArrow) { - this.consumeArrow = consumeArrow; - } - public boolean getConsumeArrow() { - return consumeArrow; - } - - @NotNull - public ItemStack getArrowItem() { - return arrowItem; - } - - @Deprecated - public EntityShootBowEvent(@NotNull final LivingEntity shooter, @Nullable final ItemStack bow, @NotNull final Entity projectile, final float force) { - this(shooter, bow, new ItemStack(org.bukkit.Material.AIR), projectile, force); - } - - public EntityShootBowEvent(@NotNull final LivingEntity shooter, @Nullable final ItemStack bow, @NotNull ItemStack arrowItem, @NotNull final Entity projectile, final float force) { - super(shooter); - this.arrowItem = arrowItem; - // Paper end - this.bow = bow; - this.projectile = projectile; - this.force = force; - } - - @NotNull - @Override - public LivingEntity getEntity() { - return (LivingEntity) entity; - } - - /** - * Gets the bow ItemStack used to fire the arrow. - * - * @return the bow involved in this event - */ - @Nullable - public ItemStack getBow() { - return bow; - } - - /** - * Gets the projectile which will be launched by this event - * - * @return the launched projectile - */ - @NotNull - public Entity getProjectile() { - return projectile; - } - - /** - * Replaces the projectile which will be launched - * - * @param projectile the new projectile - */ - public void setProjectile(@NotNull 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; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntitySpawnEvent.java b/api/src/main/java/org/bukkit/event/entity/EntitySpawnEvent.java deleted file mode 100644 index 961ee5113..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntitySpawnEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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 Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean canceled; - - public EntitySpawnEvent(@NotNull final Entity spawnee) { - super(spawnee); - } - - @Override - public boolean isCancelled() { - return canceled; - } - - @Override - 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 - */ - @NotNull - public Location getLocation() { - return getEntity().getLocation(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityTameEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityTameEvent.java deleted file mode 100644 index c410b48c2..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityTameEvent.java +++ /dev/null @@ -1,58 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final LivingEntity entity, @NotNull final AnimalTamer owner) { - super(entity); - this.owner = owner; - } - - @NotNull - @Override - public LivingEntity getEntity() { - return (LivingEntity) entity; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - /** - * Gets the owning AnimalTamer - * - * @return the owning AnimalTamer - */ - @NotNull - public AnimalTamer getOwner() { - return owner; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java deleted file mode 100644 index dee186e99..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java +++ /dev/null @@ -1,167 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull final Entity entity, @Nullable final Entity target, @NotNull final TargetReason reason) { - super(entity); - this.target = target; - this.reason = reason; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - /** - * Returns the reason for the targeting - * - * @return The reason - */ - @NotNull - 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 - */ - @Nullable - 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(@Nullable Entity target) { - this.target = target; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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. - * - * @deprecated obsoleted by {@link #TARGET_ATTACKED_NEARBY_ENTITY} - */ - @Deprecated - PIG_ZOMBIE_TARGET, - /** - * When the target is forgotten for whatever reason. - */ - 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, - /** - * When a raiding entity selects the same target as one of its compatriots. - */ - FOLLOW_LEADER, - /** - * When another entity tempts this entity by having a desired item such - * as wheat in it's hand. - */ - TEMPT, - /** - * A currently unknown reason for the entity changing target. - */ - UNKNOWN; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java deleted file mode 100644 index 6fe47c8cc..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when an Entity targets a {@link LivingEntity} and can only target - * LivingEntity's. - */ -public class EntityTargetLivingEntityEvent extends EntityTargetEvent{ - public EntityTargetLivingEntityEvent(@NotNull final Entity entity, @Nullable final LivingEntity target, @Nullable final TargetReason reason) { - super(entity, target, reason); - } - - @Override - @Nullable - 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 - */ - @Override - public void setTarget(@Nullable Entity target) { - if (target == null || target instanceof LivingEntity) { - super.setTarget(target); - } - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java deleted file mode 100644 index a7918049a..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Thrown when a non-player entity is teleported from one location to another. - *
- * This may be as a result of natural causes (Enderman, Shulker), pathfinding - * (Wolf), or commands (/teleport). - */ -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(@NotNull Entity what, @NotNull Location from, @Nullable Location to) { - super(what); - this.from = from; - this.to = to; - this.cancel = false; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - /** - * Gets the location that this entity moved from - * - * @return Location this entity moved from - */ - @NotNull - public Location getFrom() { - return from; - } - - /** - * Sets the location that this entity moved from - * - * @param from New location this entity moved from - */ - public void setFrom(@NotNull Location from) { - this.from = from; - } - - /** - * Gets the location that this entity moved to - * - * @return Location the entity moved to - */ - @Nullable - public Location getTo() { - return to; - } - - /** - * Sets the location that this entity moved to - * - * @param to New Location this entity moved to - */ - public void setTo(@Nullable Location to) { - this.to = to; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityToggleGlideEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityToggleGlideEvent.java deleted file mode 100644 index 1478cdbb4..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityToggleGlideEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Sent when an entity's gliding status is toggled with an Elytra. - * Examples of when this event would be called: - *

    - *
  • Player presses the jump key while in midair and using an Elytra
  • - *
  • Player lands on ground while they are gliding (with an Elytra)
  • - *
- * This can be visually estimated by the animation in which a player turns horizontal. - */ -public class EntityToggleGlideEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - private boolean cancel = false; - private final boolean isGliding; - - public EntityToggleGlideEvent(@NotNull LivingEntity who, final boolean isGliding) { - super(who); - this.isGliding = isGliding; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - public boolean isGliding() { - return isGliding; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityToggleSwimEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityToggleSwimEvent.java deleted file mode 100644 index 7b3fc4cad..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityToggleSwimEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Sent when an entity's swimming status is toggled. - */ -public class EntityToggleSwimEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - private boolean cancel = false; - private final boolean isSwimming; - - public EntityToggleSwimEvent(@NotNull LivingEntity who, final boolean isSwimming) { - super(who); - this.isSwimming = isSwimming; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - public boolean isSwimming() { - return isSwimming; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityTransformEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityTransformEvent.java deleted file mode 100644 index 1370380ae..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityTransformEvent.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bukkit.event.entity; - -import java.util.Collections; -import java.util.List; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an entity is about to be replaced by another entity. - */ -public class EntityTransformEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final Entity converted; - private final List convertedList; - private final TransformReason transformReason; - - public EntityTransformEvent(@NotNull Entity original, @NotNull List convertedList, @NotNull TransformReason transformReason) { - super(original); - this.convertedList = Collections.unmodifiableList(convertedList); - this.converted = convertedList.get(0); - this.transformReason = transformReason; - } - - /** - * Gets the entity that the original entity was transformed to. - * - * This returns the first entity in the transformed entity list. - * - * @return The transformed entity. - * @see #getTransformedEntities() - */ - @NotNull - public Entity getTransformedEntity() { - return converted; - } - - /** - * Gets the entities that the original entity was transformed to. - * - * @return The transformed entities. - */ - @NotNull - public List getTransformedEntities() { - return convertedList; - } - - /** - * Gets the reason for the conversion that has occurred. - * - * @return The reason for conversion that has occurred. - */ - @NotNull - public TransformReason getTransformReason() { - return transformReason; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - public enum TransformReason { - /** - * When a zombie gets cured and a villager is spawned. - */ - CURED, - /** - * When a villager gets infected and a zombie villager spawns. - */ - INFECTION, - /** - * When a entity drowns in water and a new entity spawns. - */ - DROWNED, - /** - * When a mooshroom (or MUSHROOM_COW) is sheared and a cow spawns. - */ - SHEARED, - /** - * When lightning strikes a entity. - */ - LIGHTNING, - /** - * When a slime splits into multiple smaller slimes. - */ - SPLIT - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java b/api/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java deleted file mode 100644 index a33986a0c..000000000 --- a/api/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Entity entity, @NotNull UnleashReason reason) { - super(entity); - this.reason = reason; - } - - /** - * Returns the reason for the unleashing. - * - * @return The reason - */ - @NotNull - public UnleashReason getReason() { - return reason; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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/api/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java b/api/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java deleted file mode 100644 index 6417c2fd4..000000000 --- a/api/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.ThrownExpBottle; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final ThrownExpBottle bottle, final int exp) { - super(bottle); - this.exp = exp; - } - - @NotNull - @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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java b/api/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java deleted file mode 100644 index 6db5dad71..000000000 --- a/api/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java +++ /dev/null @@ -1,85 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Entity what, final float radius, final boolean fire) { - super(what); - this.cancel = false; - this.radius = radius; - this.fire = fire; - } - - public ExplosionPrimeEvent(@NotNull final Explosive explosive) { - this(explosive, explosive.getYield(), explosive.isIncendiary()); - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/FireworkExplodeEvent.java b/api/src/main/java/org/bukkit/event/entity/FireworkExplodeEvent.java deleted file mode 100644 index 51ad0e6bf..000000000 --- a/api/src/main/java/org/bukkit/event/entity/FireworkExplodeEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Firework; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a firework explodes. - */ -public class FireworkExplodeEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancel; - - public FireworkExplodeEvent(@NotNull 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; - } - - @NotNull - @Override - public Firework getEntity() { - return (Firework) super.getEntity(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java b/api/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java deleted file mode 100644 index 7f4c5ea86..000000000 --- a/api/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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; - private final ItemStack item; - - public FoodLevelChangeEvent(@NotNull final HumanEntity what, final int level) { - this(what, level, null); - } - - public FoodLevelChangeEvent(@NotNull final HumanEntity what, final int level, @Nullable final ItemStack item) { - super(what); - this.level = level; - this.item = item; - } - - @NotNull - @Override - public HumanEntity getEntity() { - return (HumanEntity) entity; - } - - /** - * Gets the item that triggered this event, if any. - * - * @return an ItemStack for the item being consumed - */ - @Nullable - public ItemStack getItem() { - return (item == null) ? null : item.clone(); - } - - /** - * 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 < 0) level = 0; - - this.level = level; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java b/api/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java deleted file mode 100644 index 65b1ddb2b..000000000 --- a/api/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.AbstractHorse; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final AbstractHorse horse, final float power) { - super(horse); - this.power = power; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - /** - * @deprecated horse jumping was moved client side. - */ - @Override - @Deprecated - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public AbstractHorse getEntity() { - return (AbstractHorse) 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 - * AbstractHorse#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 - * @deprecated horse jumping was moved client side. - */ - @Deprecated - public void setPower(float power) { - this.power = power; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java b/api/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java deleted file mode 100644 index 6fc66197e..000000000 --- a/api/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Item; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * This event is called when a {@link org.bukkit.entity.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(@NotNull final Item despawnee, @NotNull final Location loc) { - super(despawnee); - location = loc; - } - - @Override - public boolean isCancelled() { - return canceled; - } - - @Override - public void setCancelled(boolean cancel) { - canceled = cancel; - } - - @NotNull - @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 - */ - @NotNull - public Location getLocation() { - return location; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/ItemMergeEvent.java b/api/src/main/java/org/bukkit/event/entity/ItemMergeEvent.java deleted file mode 100644 index e378cc29b..000000000 --- a/api/src/main/java/org/bukkit/event/entity/ItemMergeEvent.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Item; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -public class ItemMergeEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final Item target; - - public ItemMergeEvent(@NotNull Item item, @NotNull Item target) { - super(item); - this.target = target; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public Item getEntity() { - return (Item) entity; - } - - /** - * Gets the Item entity the main Item is being merged into. - * - * @return The Item being merged with - */ - @NotNull - public Item getTarget() { - return target; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java b/api/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java deleted file mode 100644 index faf98bb59..000000000 --- a/api/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.Location; -import org.bukkit.entity.Item; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an item is spawned into a world - */ -public class ItemSpawnEvent extends EntitySpawnEvent { - - @Deprecated - public ItemSpawnEvent(@NotNull final Item spawnee, final Location loc) { - this(spawnee); - } - - public ItemSpawnEvent(@NotNull final Item spawnee) { - super(spawnee); - } - - @NotNull - @Override - public Item getEntity() { - return (Item) entity; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/LingeringPotionSplashEvent.java b/api/src/main/java/org/bukkit/event/entity/LingeringPotionSplashEvent.java deleted file mode 100644 index a10dab167..000000000 --- a/api/src/main/java/org/bukkit/event/entity/LingeringPotionSplashEvent.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.AreaEffectCloud; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a splash potion hits an area - */ -public class LingeringPotionSplashEvent extends ProjectileHitEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final AreaEffectCloud entity; - - public LingeringPotionSplashEvent(@NotNull final ThrownPotion potion, @NotNull final AreaEffectCloud entity) { - super(potion); - this.entity = entity; - } - - @NotNull - @Override - public ThrownPotion getEntity() { - return (ThrownPotion) super.getEntity(); - } - - /** - * Gets the AreaEffectCloud spawned - * - * @return The spawned AreaEffectCloud - */ - @NotNull - public AreaEffectCloud getAreaEffectCloud() { - return entity; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/PigZapEvent.java b/api/src/main/java/org/bukkit/event/entity/PigZapEvent.java deleted file mode 100644 index d3949edfc..000000000 --- a/api/src/main/java/org/bukkit/event/entity/PigZapEvent.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.bukkit.event.entity; - -import java.util.Collections; -import org.bukkit.entity.Entity; -import com.destroystokyo.paper.event.entity.EntityZapEvent; -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; -import org.jetbrains.annotations.NotNull; - -/** - * Stores data for pigs being zapped - */ -public class PigZapEvent extends EntityZapEvent implements Cancellable { - //private static final HandlerList handlers = new HandlerList(); - private boolean canceled; - private final PigZombie pigzombie; - private final LightningStrike bolt; - - public PigZapEvent(@NotNull final Pig pig, @NotNull final LightningStrike bolt, @NotNull final PigZombie pigzombie) { - super(pig, bolt, pigzombie); - this.bolt = bolt; - this.pigzombie = pigzombie; - } - - @Override - public boolean isCancelled() { - return canceled; - } - - @Override - public void setCancelled(boolean cancel) { - canceled = cancel; - } - - @NotNull - @Override - public Pig getEntity() { - return (Pig) entity; - } - - /** - * Gets the bolt which is striking the pig. - * - * @return lightning entity - */ - @NotNull - public LightningStrike getLightning() { - return bolt; - } - - /** - * Gets the zombie pig that will replace the pig, provided the event is - * not cancelled first. - * - * @return resulting entity - * @deprecated use {@link EntityTransformEvent#getTransformedEntity()} - */ - @NotNull - @Deprecated - public PigZombie getPigZombie() { - return pigzombie; - } - - // Paper start - /* - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - */ - // Paper end -} diff --git a/api/src/main/java/org/bukkit/event/entity/PigZombieAngerEvent.java b/api/src/main/java/org/bukkit/event/entity/PigZombieAngerEvent.java deleted file mode 100644 index bb4f13bbb..000000000 --- a/api/src/main/java/org/bukkit/event/entity/PigZombieAngerEvent.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.PigZombie; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a Pig Zombie is angered by another entity. - *

- * If the event is cancelled, the pig zombie will not be angered. - */ -public class PigZombieAngerEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean canceled; - private final Entity target; - private int newAnger; - - public PigZombieAngerEvent(@NotNull final PigZombie pigZombie, @Nullable final Entity target, final int newAnger) { - super(pigZombie); - this.target = target; - this.newAnger = newAnger; - } - - /** - * Gets the entity (if any) which triggered this anger update. - * - * @return triggering entity, or null - */ - @Nullable - public Entity getTarget() { - return target; - } - - /** - * Gets the new anger resulting from this event. - * - * @return new anger - * @see PigZombie#getAnger() - */ - public int getNewAnger() { - return newAnger; - } - - /** - * Sets the new anger resulting from this event. - * - * @param newAnger the new anger - * @see PigZombie#setAnger(int) - */ - public void setNewAnger(int newAnger) { - this.newAnger = newAnger; - } - - @NotNull - @Override - public PigZombie getEntity() { - return (PigZombie) entity; - } - - @Override - public boolean isCancelled() { - return canceled; - } - - @Override - public void setCancelled(boolean cancel) { - canceled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java b/api/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java deleted file mode 100644 index 1e97d04b3..000000000 --- a/api/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java +++ /dev/null @@ -1,202 +0,0 @@ -package org.bukkit.event.entity; - -import java.util.List; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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; - - // Paper start - private List itemsToKeep = new java.util.ArrayList<>(); - - /** - * A mutable collection to add items that the player should retain in their inventory on death (Similar to KeepInventory game rule) - * - * You MUST remove the item from the .getDrops() collection too or it will duplicate! - *

{@code
-     *    {@literal @EventHandler(ignoreCancelled = true)}
-     *     public void onPlayerDeath(PlayerDeathEvent event) {
-     *         for (Iterator iterator = event.getDrops().iterator(); iterator.hasNext(); ) {
-     *             ItemStack drop = iterator.next();
-     *             List lore = drop.getLore();
-     *             if (lore != null && !lore.isEmpty()) {
-     *                 if (lore.get(0).contains("(SOULBOUND)")) {
-     *                     iterator.remove();
-     *                     event.getItemsToKeep().add(drop);
-     *                 }
-     *             }
-     *         }
-     *     }
-     * }
- * - * Adding an item to this list that the player did not previously have will give them the item on death. - * An example case could be a "Note" that "You died at X/Y/Z coordinates" - * - * @return The list to hold items to keep - */ - @NotNull - public List getItemsToKeep() { - return itemsToKeep; - } - // Paper end - - public PlayerDeathEvent(@NotNull final Player player, @NotNull final List drops, final int droppedExp, @Nullable final String deathMessage) { - this(player, drops, droppedExp, 0, deathMessage); - } - - public PlayerDeathEvent(@NotNull final Player player, @NotNull final List drops, final int droppedExp, final int newExp, @Nullable final String deathMessage) { - this(player, drops, droppedExp, newExp, 0, 0, deathMessage); - } - - public PlayerDeathEvent(@NotNull final Player player, @NotNull final List drops, final int droppedExp, final int newExp, final int newTotalExp, final int newLevel, @Nullable final String deathMessage) { - super(player, drops, droppedExp); - this.newExp = newExp; - this.newTotalExp = newTotalExp; - this.newLevel = newLevel; - this.deathMessage = deathMessage; - } - - @NotNull - @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(@Nullable 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. - */ - @Nullable - 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. - *

- * This doesn't prevent prevent the items from dropping. - * {@code getDrops().clear()} should be used stop the - * items from dropping. - * - * @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/api/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java b/api/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java deleted file mode 100644 index cbf0c736b..000000000 --- a/api/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java +++ /dev/null @@ -1,76 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Entity what, @NotNull Entity leashHolder, @NotNull Player leasher) { - this.leashHolder = leashHolder; - this.entity = what; - this.player = leasher; - } - - /** - * Returns the entity that is holding the leash. - * - * @return The leash holder - */ - @NotNull - public Entity getLeashHolder() { - return leashHolder; - } - - /** - * Returns the entity being leashed. - * - * @return The entity - */ - @NotNull - public Entity getEntity() { - return entity; - } - - /** - * Returns the player involved in this event - * - * @return Player who is involved in this event - */ - @NotNull - public final Player getPlayer() { - return player; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java b/api/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java deleted file mode 100644 index 90d7e8141..000000000 --- a/api/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.bukkit.event.entity; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -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 org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final ThrownPotion potion, @NotNull final Map affectedEntities) { - super(potion); - - this.affectedEntities = affectedEntities; - } - - @NotNull - @Override - public ThrownPotion getEntity() { - return (ThrownPotion) entity; - } - - /** - * Gets the potion which caused this event - * - * @return The thrown potion entity - */ - @NotNull - public ThrownPotion getPotion() { - return (ThrownPotion) getEntity(); - } - - /** - * Retrieves a list of all effected entities - * - * @return A fresh copy of the affected entity list - */ - @NotNull - 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(@NotNull 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(@NotNull 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)); - } - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java b/api/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java deleted file mode 100644 index 809c1098c..000000000 --- a/api/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Projectile; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a projectile hits an object - */ -public class ProjectileHitEvent extends EntityEvent { - private static final HandlerList handlers = new HandlerList(); - private final Entity hitEntity; - private final Block hitBlock; - private final BlockFace hitFace; - - public ProjectileHitEvent(@NotNull final Projectile projectile) { - this(projectile, null, null); - } - - public ProjectileHitEvent(@NotNull final Projectile projectile, @Nullable Entity hitEntity) { - this(projectile, hitEntity, null); - } - - public ProjectileHitEvent(@NotNull final Projectile projectile, @Nullable Block hitBlock) { - this(projectile, null, hitBlock); - } - - public ProjectileHitEvent(@NotNull final Projectile projectile, @Nullable Entity hitEntity, @Nullable Block hitBlock) { - this(projectile, hitEntity, hitBlock, null); - } - - public ProjectileHitEvent(@NotNull final Projectile projectile, @Nullable Entity hitEntity, @Nullable Block hitBlock, @Nullable BlockFace hitFace) { - super(projectile); - this.hitEntity = hitEntity; - this.hitBlock = hitBlock; - this.hitFace = hitFace; - } - - @NotNull - @Override - public Projectile getEntity() { - return (Projectile) entity; - } - - /** - * Gets the block that was hit, if it was a block that was hit. - * - * @return hit block or else null - */ - @Nullable - public Block getHitBlock() { - return hitBlock; - } - - /** - * Gets the block face that was hit, if it was a block that was hit and the - * face was provided in the vent. - * - * @return hit face or else null - */ - @Nullable - public BlockFace getHitBlockFace() { - return hitFace; - } - - /** - * Gets the entity that was hit, if it was an entity that was hit. - * - * @return hit entity or else null - */ - @Nullable - public Entity getHitEntity() { - return hitEntity; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - -} diff --git a/api/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java b/api/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java deleted file mode 100644 index c5fc3c558..000000000 --- a/api/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Projectile; -import org.bukkit.event.Cancellable; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a projectile is launched. - */ -public class ProjectileLaunchEvent extends EntitySpawnEvent implements Cancellable { - private boolean cancelled; - - public ProjectileLaunchEvent(@NotNull Entity what) { - super(what); - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public Projectile getEntity() { - return (Projectile) entity; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java b/api/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java deleted file mode 100644 index 4db826e4d..000000000 --- a/api/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.DyeColor; -import org.bukkit.entity.Sheep; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Sheep sheep, @NotNull final DyeColor color) { - super(sheep); - this.cancel = false; - this.color = color; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - @NotNull - @Override - public Sheep getEntity() { - return (Sheep) entity; - } - - /** - * Gets the DyeColor the sheep is being dyed - * - * @return the DyeColor the sheep is being dyed - */ - @NotNull - 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(@NotNull DyeColor color) { - this.color = color; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - -} diff --git a/api/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java b/api/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java deleted file mode 100644 index 05264b31a..000000000 --- a/api/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Sheep; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Sheep sheep) { - super(sheep); - this.cancel = false; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - @NotNull - @Override - public Sheep getEntity() { - return (Sheep) entity; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - -} diff --git a/api/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java b/api/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java deleted file mode 100644 index 02b659847..000000000 --- a/api/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Slime; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Slime slime, final int count) { - super(slime); - this.count = count; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - @NotNull - @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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/SpawnerSpawnEvent.java b/api/src/main/java/org/bukkit/event/entity/SpawnerSpawnEvent.java deleted file mode 100644 index 9353f0d09..000000000 --- a/api/src/main/java/org/bukkit/event/entity/SpawnerSpawnEvent.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.block.CreatureSpawner; -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Entity spawnee, @NotNull final CreatureSpawner spawner) { - super(spawnee); - this.spawner = spawner; - } - - @NotNull - public CreatureSpawner getSpawner() { - return spawner; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/VillagerAcquireTradeEvent.java b/api/src/main/java/org/bukkit/event/entity/VillagerAcquireTradeEvent.java deleted file mode 100644 index 58155105d..000000000 --- a/api/src/main/java/org/bukkit/event/entity/VillagerAcquireTradeEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.AbstractVillager; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.MerchantRecipe; -import org.jetbrains.annotations.NotNull; - -/** - * Called whenever a villager acquires a new trade. - */ -public class VillagerAcquireTradeEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - // - private MerchantRecipe recipe; - - public VillagerAcquireTradeEvent(@NotNull AbstractVillager what, @NotNull MerchantRecipe recipe) { - super(what); - this.recipe = recipe; - } - - /** - * Get the recipe to be acquired. - * - * @return the new recipe - */ - @NotNull - public MerchantRecipe getRecipe() { - return recipe; - } - - /** - * Set the recipe to be acquired. - * - * @param recipe the new recipe - */ - public void setRecipe(@NotNull MerchantRecipe recipe) { - this.recipe = recipe; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public AbstractVillager getEntity() { - return (AbstractVillager) super.getEntity(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/VillagerCareerChangeEvent.java b/api/src/main/java/org/bukkit/event/entity/VillagerCareerChangeEvent.java deleted file mode 100644 index b550029cf..000000000 --- a/api/src/main/java/org/bukkit/event/entity/VillagerCareerChangeEvent.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.Villager; -import org.bukkit.entity.Villager.Profession; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -public class VillagerCareerChangeEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private Profession profession; - private final ChangeReason reason; - - public VillagerCareerChangeEvent(@NotNull Villager what, @NotNull Profession profession, @NotNull ChangeReason reason) { - super(what); - this.profession = profession; - this.reason = reason; - } - - @NotNull - @Override - public Villager getEntity() { - return (Villager) super.getEntity(); - } - - /** - * Gets the future profession of the villager. - * - * @return The profession the villager will change to - */ - @NotNull - public Profession getProfession() { - return profession; - } - - /** - * Sets the profession the villager will become from this event. - * - * @param profession new profession - */ - public void setProfession(@NotNull Profession profession) { - this.profession = profession; - } - - /** - * Gets the reason for why the villager's career is changing. - * - * @return Reason for villager's profession changing - */ - @NotNull - public ChangeReason getReason() { - return reason; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(@NotNull boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Reasons for the villager's profession changing. - */ - public enum ChangeReason { - - /** - * Villager lost their job due to too little experience. - */ - LOSING_JOB, - /** - * Villager gained employment. - */ - EMPLOYED; - } -} diff --git a/api/src/main/java/org/bukkit/event/entity/VillagerReplenishTradeEvent.java b/api/src/main/java/org/bukkit/event/entity/VillagerReplenishTradeEvent.java deleted file mode 100644 index ff5f484cf..000000000 --- a/api/src/main/java/org/bukkit/event/entity/VillagerReplenishTradeEvent.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.bukkit.event.entity; - -import org.bukkit.entity.AbstractVillager; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.MerchantRecipe; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a villager's trade's maximum uses is increased, due to a player's - * trade. - * - * @see MerchantRecipe#getMaxUses() - */ -public class VillagerReplenishTradeEvent extends EntityEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - // - private MerchantRecipe recipe; - private int bonus; - - public VillagerReplenishTradeEvent(@NotNull AbstractVillager what, @NotNull MerchantRecipe recipe, int bonus) { - super(what); - this.recipe = recipe; - this.bonus = bonus; - } - - /** - * Get the recipe to replenish. - * - * @return the replenished recipe - */ - @NotNull - public MerchantRecipe getRecipe() { - return recipe; - } - - /** - * Set the recipe to replenish. - * - * @param recipe the replenished recipe - */ - public void setRecipe(@NotNull MerchantRecipe recipe) { - this.recipe = recipe; - } - - /** - * Get the bonus uses added. The maximum uses of the recipe will be - * increased by this number. - * - * @return the extra uses added - */ - public int getBonus() { - return bonus; - } - - /** - * Set the bonus uses added. - * - * @see VillagerReplenishTradeEvent#getBonus() - * @param bonus the extra uses added - */ - public void setBonus(int bonus) { - this.bonus = bonus; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public AbstractVillager getEntity() { - return (AbstractVillager) super.getEntity(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java b/api/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java deleted file mode 100644 index 68517811f..000000000 --- a/api/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.event.hanging; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Hanging; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Triggered when a hanging entity is removed by an entity - */ -public class HangingBreakByEntityEvent extends HangingBreakEvent { - private final Entity remover; - - public HangingBreakByEntityEvent(@NotNull final Hanging hanging, @Nullable final Entity remover) { - this(hanging, remover, HangingBreakEvent.RemoveCause.ENTITY); - } - - public HangingBreakByEntityEvent(@NotNull final Hanging hanging, @Nullable final Entity remover, @NotNull final HangingBreakEvent.RemoveCause cause) { - super(hanging, cause); - this.remover = remover; - } - - /** - * Gets the entity that removed the hanging entity. - * May be null, for example when broken by an explosion. - * - * @return the entity that removed the hanging entity - */ - @Nullable - public Entity getRemover() { - return remover; - } -} diff --git a/api/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java b/api/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java deleted file mode 100644 index 16d8196e1..000000000 --- a/api/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bukkit.event.hanging; - -import org.bukkit.entity.Hanging; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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 HangingBreakEvent.RemoveCause cause; - - public HangingBreakEvent(@NotNull final Hanging hanging, @NotNull final HangingBreakEvent.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 - */ - @NotNull - public HangingBreakEvent.RemoveCause getCause() { - return cause; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - 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, - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/hanging/HangingEvent.java b/api/src/main/java/org/bukkit/event/hanging/HangingEvent.java deleted file mode 100644 index f01a1a0f0..000000000 --- a/api/src/main/java/org/bukkit/event/hanging/HangingEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.event.hanging; - -import org.bukkit.entity.Hanging; -import org.bukkit.event.Event; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a hanging entity-related event. - */ -public abstract class HangingEvent extends Event { - protected Hanging hanging; - - protected HangingEvent(@NotNull final Hanging painting) { - this.hanging = painting; - } - - /** - * Gets the hanging entity involved in this event. - * - * @return the hanging entity - */ - @NotNull - public Hanging getEntity() { - return hanging; - } -} diff --git a/api/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java b/api/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java deleted file mode 100644 index 959b9f3fb..000000000 --- a/api/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java +++ /dev/null @@ -1,79 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull final Hanging hanging, @Nullable final Player player, @NotNull final Block block, @NotNull 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 - */ - @Nullable - 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 - */ - @NotNull - 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 - */ - @NotNull - public BlockFace getBlockFace() { - return blockFace; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/BrewEvent.java b/api/src/main/java/org/bukkit/event/inventory/BrewEvent.java deleted file mode 100644 index 8fbfad91b..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/BrewEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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 int fuelLevel; - private boolean cancelled; - - public BrewEvent(@NotNull Block brewer, @NotNull BrewerInventory contents, int fuelLevel) { - super(brewer); - this.contents = contents; - this.fuelLevel = fuelLevel; - } - - /** - * Gets the contents of the Brewing Stand. - * - * @return the contents - */ - @NotNull - public BrewerInventory getContents() { - return contents; - } - - /** - * Gets the remaining fuel level. - * - * @return the remaining fuel - */ - public int getFuelLevel() { - return fuelLevel; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/BrewingStandFuelEvent.java b/api/src/main/java/org/bukkit/event/inventory/BrewingStandFuelEvent.java deleted file mode 100644 index 633ec5187..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/BrewingStandFuelEvent.java +++ /dev/null @@ -1,96 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an ItemStack is about to increase the fuel level of a brewing - * stand. - */ -public class BrewingStandFuelEvent extends BlockEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private final ItemStack fuel; - private int fuelPower; - private boolean cancelled; - private boolean consuming = true; - - public BrewingStandFuelEvent(@NotNull Block brewingStand, @NotNull ItemStack fuel, int fuelPower) { - super(brewingStand); - this.fuel = fuel; - this.fuelPower = fuelPower; - } - - /** - * Gets the ItemStack of the fuel before the amount was subtracted. - * - * @return the fuel ItemStack - */ - @NotNull - public ItemStack getFuel() { - return fuel; - } - - /** - * Gets the fuel power for this fuel. Each unit of power can fuel one - * brewing operation. - * - * @return the fuel power for this fuel - */ - public int getFuelPower() { - return fuelPower; - } - - /** - * Sets the fuel power for this fuel. Each unit of power can fuel one - * brewing operation. - * - * @param fuelPower the fuel power for this fuel - */ - public void setFuelPower(int fuelPower) { - this.fuelPower = fuelPower; - } - - /** - * Gets whether the brewing stand's fuel will be reduced / consumed or not. - * - * @return whether the fuel will be reduced or not - */ - public boolean isConsuming() { - return consuming; - } - - /** - * Sets whether the brewing stand's fuel will be reduced / consumed or not. - * - * @param consuming whether the fuel will be reduced or not - */ - public void setConsuming(boolean consuming) { - this.consuming = consuming; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/ClickType.java b/api/src/main/java/org/bukkit/event/inventory/ClickType.java deleted file mode 100644 index a7440aac9..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/ClickType.java +++ /dev/null @@ -1,115 +0,0 @@ -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/api/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java b/api/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java deleted file mode 100644 index cab13877f..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java +++ /dev/null @@ -1,38 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * Called when the recipe of an Item is completed inside a crafting matrix. - */ -public class CraftItemEvent extends InventoryClickEvent { - private Recipe recipe; - - public CraftItemEvent(@NotNull Recipe recipe, @NotNull InventoryView what, @NotNull SlotType type, int slot, @NotNull ClickType click, @NotNull InventoryAction action) { - super(what, type, slot, click, action); - this.recipe = recipe; - } - - public CraftItemEvent(@NotNull Recipe recipe, @NotNull InventoryView what, @NotNull SlotType type, int slot, @NotNull ClickType click, @NotNull 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. - */ - @NotNull - public Recipe getRecipe() { - return recipe; - } - - @NotNull - @Override - public CraftingInventory getInventory() { - return (CraftingInventory) super.getInventory(); - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/DragType.java b/api/src/main/java/org/bukkit/event/inventory/DragType.java deleted file mode 100644 index 72c2bed95..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/DragType.java +++ /dev/null @@ -1,17 +0,0 @@ -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/api/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java b/api/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java deleted file mode 100644 index bc71bc2d3..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java +++ /dev/null @@ -1,94 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Block furnace, @NotNull final ItemStack fuel, final int burnTime) { - super(furnace); - this.fuel = fuel; - this.burnTime = burnTime; - this.cancelled = false; - this.burning = true; - } - - /** - * Gets the fuel ItemStack for this event - * - * @return the fuel ItemStack - */ - @NotNull - 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; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java b/api/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java deleted file mode 100644 index 020739697..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Player player, @NotNull Block block, @NotNull 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 - */ - @NotNull - public Player getPlayer() { - return player; - } - - /** - * Get the Material of the item being retrieved - * - * @return the material of the item - */ - @NotNull - 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/api/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java b/api/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java deleted file mode 100644 index 066e7dd9a..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bukkit.event.inventory; - -import org.bukkit.block.Block; -import org.bukkit.event.block.BlockCookEvent; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an ItemStack is successfully smelted in a furnace. - */ -public class FurnaceSmeltEvent extends BlockCookEvent { - - public FurnaceSmeltEvent(@NotNull final Block furnace, @NotNull final ItemStack source, @NotNull final ItemStack result) { - super(furnace, source, result); - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryAction.java b/api/src/main/java/org/bukkit/event/inventory/InventoryAction.java deleted file mode 100644 index a7bc694bd..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryAction.java +++ /dev/null @@ -1,91 +0,0 @@ -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/api/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java deleted file mode 100644 index 02766d933..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java +++ /dev/null @@ -1,244 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 SlotType slot_type; - private int whichSlot; - private int rawSlot; - private ItemStack current = null; - private int hotbarKey = -1; - - public InventoryClickEvent(@NotNull InventoryView view, @NotNull SlotType type, int slot, @NotNull ClickType click, @NotNull InventoryAction action) { - super(view); - this.slot_type = type; - this.rawSlot = slot; - this.whichSlot = view.convertSlot(slot); - this.click = click; - this.action = action; - } - - public InventoryClickEvent(@NotNull InventoryView view, @NotNull SlotType type, int slot, @NotNull ClickType click, @NotNull InventoryAction action, int key) { - this(view, type, slot, click, action); - this.hotbarKey = key; - } - - /** - * Gets the type of slot that was clicked. - * - * @return the slot type - */ - @NotNull - public SlotType getSlotType() { - return slot_type; - } - - /** - * Gets the current ItemStack on the cursor. - * - * @return the cursor ItemStack - */ - @Nullable - public ItemStack getCursor() { - return getView().getCursor(); - } - - /** - * Gets the ItemStack currently in the clicked slot. - * - * @return the item in the clicked - */ - @Nullable - 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(@Nullable 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(@Nullable ItemStack stack) { - if (slot_type == SlotType.OUTSIDE) { - current = stack; - } else { - getView().setItem(rawSlot, stack); - } - } - - /** - * Gets the inventory corresponding to the clicked slot. - * - * @see InventoryView#getInventory(int) - * @return inventory, or null if clicked outside - */ - @Nullable - public Inventory getClickedInventory() { - return getView().getInventory(rawSlot); - } - - /** - * 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. - */ - @NotNull - 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 - */ - @NotNull - public ClickType getClick() { - return click; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java deleted file mode 100644 index 21ad8888c..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java +++ /dev/null @@ -1,90 +0,0 @@ - -package org.bukkit.event.inventory; - -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.InventoryView; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a player related inventory event - */ -public class InventoryCloseEvent extends InventoryEvent { - private static final HandlerList handlers = new HandlerList(); - // Paper start - private final Reason reason; - @NotNull - public Reason getReason() { - return reason; - } - - public enum Reason { - /** - * Unknown reason - */ - UNKNOWN, - /** - * Player is teleporting - */ - TELEPORT, - /** - * Player is no longer permitted to use this inventory - */ - CANT_USE, - /** - * The chunk the inventory was in was unloaded - */ - UNLOADED, - /** - * Opening new inventory instead - */ - OPEN_NEW, - /** - * Closed - */ - PLAYER, - /** - * Closed due to disconnect - */ - DISCONNECT, - /** - * The player died - */ - DEATH, - /** - * Closed by Bukkit API - */ - PLUGIN, - } - - public InventoryCloseEvent(@NotNull InventoryView transaction) { - this(transaction, Reason.UNKNOWN); - } - - public InventoryCloseEvent(@NotNull InventoryView transaction, @NotNull Reason reason) { - super(transaction); - this.reason = reason; - // Paper end - } - - /** - * Returns the player involved in this event - * - * @return Player who is involved in this event - */ - @NotNull - public final HumanEntity getPlayer() { - return transaction.getPlayer(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java deleted file mode 100644 index 9c6db8be4..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit.event.inventory; - -import org.bukkit.event.inventory.InventoryType.SlotType; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull InventoryView what, @NotNull SlotType type, int slot, @NotNull ItemStack newItem) { - super(what, type, slot, ClickType.CREATIVE, InventoryAction.PLACE_ALL); - this.item = newItem; - } - - @Override - @NotNull - public ItemStack getCursor() { - return item; - } - - @Override - public void setCursor(@NotNull ItemStack item) { - this.item = item; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java deleted file mode 100644 index 856e945c5..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java +++ /dev/null @@ -1,172 +0,0 @@ -package org.bukkit.event.inventory; - -import com.google.common.collect.ImmutableSet; -import java.util.Collections; -import java.util.Map; -import java.util.Set; -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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull InventoryView what, @Nullable ItemStack newCursor, @NotNull ItemStack oldCursor, boolean right, @NotNull 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 - */ - @NotNull - 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) - */ - @NotNull - public Set getRawSlots() { - return addedItems.keySet(); - } - - /** - * Gets the slots to be changed in this drag. - * - * @return list of converted slot ids, suitable for {@link - * org.bukkit.inventory.Inventory#getItem(int)}. - */ - @NotNull - public Set getInventorySlots() { - return containerSlots; - } - - /** - * Gets the result cursor after the drag is done. The returned value is - * mutable. - * - * @return the result cursor - */ - @Nullable - 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(@Nullable 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 - */ - @NotNull - 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 - */ - @NotNull - public DragType getType() { - return type; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryEvent.java deleted file mode 100644 index 5d3fe64ab..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryEvent.java +++ /dev/null @@ -1,64 +0,0 @@ - -package org.bukkit.event.inventory; - -import java.util.List; -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 org.jetbrains.annotations.NotNull; - -/** - * Represents a player related inventory event - */ -public class InventoryEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - protected InventoryView transaction; - - public InventoryEvent(@NotNull InventoryView transaction) { - this.transaction = transaction; - } - - /** - * Gets the primary Inventory involved in this transaction - * - * @return The upper inventory. - */ - @NotNull - 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. - */ - @NotNull - public List getViewers() { - return transaction.getTopInventory().getViewers(); - } - - /** - * Gets the view object itself - * - * @return InventoryView - */ - @NotNull - public InventoryView getView() { - return transaction; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java deleted file mode 100644 index 707b4381e..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.bukkit.event.inventory; - -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.Cancellable; -import org.bukkit.inventory.InventoryView; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull InventoryView transaction) { - super(transaction); - } - - /** - * Gets the player who performed the click. - * - * @return The clicking player. - */ - @NotNull - 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 org.bukkit.event.Event.Result} for this event - */ - public void setResult(@NotNull Result newResult) { - result = newResult; - } - - /** - * Gets the {@link org.bukkit.event.Event.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. - */ - @NotNull - 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 - */ - @Override - public boolean isCancelled() { - return getResult() == Result.DENY; - } - - /** - * Proxy method to {@link #setResult(org.bukkit.event.Event.Result)} for the Cancellable - * interface. {@link #setResult(org.bukkit.event.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 - */ - @Override - public void setCancelled(boolean toCancel) { - setResult(toCancel ? Result.DENY : Result.ALLOW); - } - -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java deleted file mode 100644 index 04d4a83bf..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java +++ /dev/null @@ -1,121 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Inventory sourceInventory, @NotNull final ItemStack itemStack, @NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - 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(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - public Inventory getInitiator() { - return didSourceInitiate ? sourceInventory : destinationInventory; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java deleted file mode 100644 index 9013d0435..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull InventoryView transaction) { - super(transaction); - this.cancelled = false; - } - - /** - * Returns the player involved in this event - * - * @return Player who is involved in this event - */ - @NotNull - 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 - */ - @Override - 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 - */ - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java b/api/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java deleted file mode 100644 index 1ffac4d58..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Inventory inventory, @NotNull final Item item) { - super(); - this.inventory = inventory; - this.item = item; - } - - /** - * Gets the Inventory that picked up the item - * - * @return Inventory - */ - @NotNull - public Inventory getInventory() { - return inventory; - } - - /** - * Gets the Item entity that was picked up - * - * @return Item - */ - @NotNull - public Item getItem() { - return item; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/InventoryType.java b/api/src/main/java/org/bukkit/event/inventory/InventoryType.java deleted file mode 100644 index 75e719ae8..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/InventoryType.java +++ /dev/null @@ -1,196 +0,0 @@ -package org.bukkit.event.inventory; - -import org.bukkit.inventory.InventoryHolder; -import org.jetbrains.annotations.NotNull; - -/** - * Represents the different kinds of inventories available in Bukkit. - *
- * Only InventoryTypes marked {@link #isCreatable()} can be created. - *
- * The current list of inventories that cannot be created via - * {@link org.bukkit.Bukkit#createInventory} are:
- *

- * {@link InventoryType#CREATIVE}, {@link InventoryType#CRAFTING} and - * {@link InventoryType#MERCHANT} - *
- * - * See {@link org.bukkit.Bukkit#createInventory} for more information. - * - * @see org.bukkit.Bukkit#createInventory(InventoryHolder, InventoryType) - */ -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", false), - /** - * An enchantment table inventory, with two CRAFTING slots and three - * enchanting buttons. - */ - ENCHANTING(2,"Enchanting"), - /** - * A brewing stand inventory, with one FUEL slot and four CRAFTING slots. - */ - BREWING(5,"Brewing"), - /** - * A player's inventory, with 9 QUICKBAR slots, 27 CONTAINER slots, 4 ARMOR - * slots and 1 offhand slot. The ARMOR and offhand slots may not be visible - * to the player, though. - */ - PLAYER(41,"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", false), - /** - * The merchant inventory, with 2 CRAFTING slots, and 1 RESULT slot. - */ - MERCHANT(3,"Villager", false), - /** - * 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"), - /** - * A shulker box inventory, with 27 slots of type CONTAINER. - */ - SHULKER_BOX(27, "Shulker Box"), - /** - * A barrel box inventory, with 27 slots of type CONTAINER. - */ - BARREL(27, "Barrel"), - /** - * A blast furnace inventory, with a RESULT slot, a CRAFTING slot, and a - * FUEL slot. - */ - BLAST_FURNACE(3, "Blast Furnace"), - /** - * A lectern inventory, with 1 BOOK slot. - */ - LECTERN(1, "Lectern"), - /** - * A smoker inventory, with a RESULT slot, a CRAFTING slot, and a FUEL slot. - */ - SMOKER(3, "Smoker"), - /** - * Loom inventory, with 3 CRAFTING slots, and 1 RESULT slot. - */ - LOOM(4, "Loom"), - /** - * Cartography inventory with 2 CRAFTING slots, and 1 RESULT slot. - */ - CARTOGRAPHY(3, "Cartography Table"), - /** - * Grindstone inventory with 2 CRAFTING slots, and 1 RESULT slot. - */ - GRINDSTONE(3, "Repair & Disenchant"), - /** - * Stonecutter inventory with 1 CRAFTING slot, and 1 RESULT slot. - */ - STONECUTTER(2, "Stonecutter") - ; - - private final int size; - private final String title; - private final boolean isCreatable; - - private InventoryType(int defaultSize, /*@NotNull*/ String defaultTitle) { - this(defaultSize, defaultTitle, true); - } - - private InventoryType(int defaultSize, /*@NotNull*/ String defaultTitle, boolean isCreatable) { - size = defaultSize; - title = defaultTitle; - this.isCreatable = isCreatable; - } - - public int getDefaultSize() { - return size; - } - - @NotNull - public String getDefaultTitle() { - return title; - } - - /** - * Denotes that this InventoryType can be created via the normal - * {@link org.bukkit.Bukkit#createInventory} methods. - * - * @return if this InventoryType can be created and shown to a player - */ - public boolean isCreatable() { - return isCreatable; - } - - public enum SlotType { - /** - * A result slot in a furnace or crafting inventory. - */ - RESULT, - /** - * A slot in the crafting matrix, or an 'input' 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/api/src/main/java/org/bukkit/event/inventory/PrepareAnvilEvent.java b/api/src/main/java/org/bukkit/event/inventory/PrepareAnvilEvent.java deleted file mode 100644 index 77109a07f..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/PrepareAnvilEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.event.inventory; - -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.AnvilInventory; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when an item is put in a slot for repair by an anvil. - */ -public class PrepareAnvilEvent extends InventoryEvent { - - private static final HandlerList handlers = new HandlerList(); - private ItemStack result; - - public PrepareAnvilEvent(@NotNull InventoryView inventory, @Nullable ItemStack result) { - super(inventory); - this.result = result; - } - - @NotNull - @Override - public AnvilInventory getInventory() { - return (AnvilInventory) super.getInventory(); - } - - /** - * Get result item, may be null. - * - * @return result item - */ - @Nullable - public ItemStack getResult() { - return result; - } - - public void setResult(@Nullable ItemStack result) { - this.result = result; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java b/api/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java deleted file mode 100644 index efd29d198..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java +++ /dev/null @@ -1,62 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class PrepareItemCraftEvent extends InventoryEvent { - private static final HandlerList handlers = new HandlerList(); - private boolean repair; - private CraftingInventory matrix; - - public PrepareItemCraftEvent(@NotNull CraftingInventory what, @NotNull 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. - */ - @Nullable - public Recipe getRecipe() { - return matrix.getRecipe(); - } - - /** - * @return The crafting inventory on which the recipe was formed. - */ - @NotNull - @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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/inventory/TradeSelectEvent.java b/api/src/main/java/org/bukkit/event/inventory/TradeSelectEvent.java deleted file mode 100644 index 3bddf946d..000000000 --- a/api/src/main/java/org/bukkit/event/inventory/TradeSelectEvent.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bukkit.event.inventory; - -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.MerchantInventory; -import org.jetbrains.annotations.NotNull; - -/** - * This event is called whenever a player clicks a new trade on the trades - * sidebar. - *

- * This event allows the user to get the index of the trade, letting them get - * the MerchantRecipe via the Merchant. - */ -public class TradeSelectEvent extends InventoryInteractEvent { - - private static final HandlerList handlers = new HandlerList(); - // - private final int index; - - public TradeSelectEvent(@NotNull InventoryView transaction, int newIndex) { - super(transaction); - this.index = newIndex; - } - - /** - * Used to get the index of the trade the player clicked on. - * - * @return The index of the trade clicked by the player - */ - public int getIndex() { - return index; - } - - @NotNull - @Override - public MerchantInventory getInventory() { - return (MerchantInventory) super.getInventory(); - } - - /** - * Get the Merchant involved. - * - * @return the Merchant - */ - @NotNull - public Merchant getMerchant() { - return getInventory().getMerchant(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java b/api/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java deleted file mode 100644 index ab129b058..000000000 --- a/api/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java +++ /dev/null @@ -1,147 +0,0 @@ -package org.bukkit.event.player; - -import java.util.IllegalFormatException; -import java.util.Set; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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, @NotNull final Player who, @NotNull final String message, @NotNull 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 - */ - @NotNull - 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(@NotNull 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 - */ - @NotNull - 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(@NotNull 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 - */ - @NotNull - public Set getRecipients() { - return recipients; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java b/api/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java deleted file mode 100644 index 76c4a1a6e..000000000 --- a/api/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java +++ /dev/null @@ -1,237 +0,0 @@ -package org.bukkit.event.player; - -import java.net.InetAddress; -import java.util.UUID; - -import com.destroystokyo.paper.profile.PlayerProfile; -import org.bukkit.Bukkit; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final String name, @NotNull final InetAddress ipAddress) { - this(name, ipAddress, null); - } - - public AsyncPlayerPreLoginEvent(@NotNull final String name, @NotNull final InetAddress ipAddress, @NotNull final UUID uniqueId) { - // Paper start - this(name, ipAddress, uniqueId, Bukkit.createProfile(uniqueId, name)); - } - private PlayerProfile profile; - - /** - * Gets the PlayerProfile of the player logging in - * @return The Profile - */ - @NotNull - public PlayerProfile getPlayerProfile() { - return profile; - } - - /* * Changes the PlayerProfile the player will login as - * @param profile The profile to use - */ - public void setPlayerProfile(@NotNull PlayerProfile profile) { - this.profile = profile; - } - - public AsyncPlayerPreLoginEvent(@NotNull final String name, @NotNull final InetAddress ipAddress, @NotNull final UUID uniqueId, @NotNull PlayerProfile profile) { - super(true); - this.profile = profile; - // Paper end - 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 - */ - @NotNull - 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 - @NotNull - 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(@NotNull 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(@NotNull 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 - */ - @NotNull - public String getKickMessage() { - return message; - } - - /** - * Sets the kick message to display if getResult() != Result.ALLOWED - * - * @param message New kick message - */ - public void setKickMessage(@NotNull 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(@NotNull final Result result, @NotNull 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(@NotNull final PlayerPreLoginEvent.Result result, @NotNull 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 - */ - @NotNull - public String getName() { - return name; - } - - /** - * Gets the player IP address. - * - * @return The IP address - */ - @NotNull - public InetAddress getAddress() { - return ipAddress; - } - - /** - * Gets the player's unique ID. - * - * @return The unique ID - */ - @NotNull - public UUID getUniqueId() { - return uniqueId; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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 - @NotNull - private PlayerPreLoginEvent.Result old() { - return PlayerPreLoginEvent.Result.valueOf(name()); - } - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java deleted file mode 100644 index 07fa439a4..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.Achievement; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player earns an achievement. - * @deprecated future versions of Minecraft do not have achievements - */ -@Deprecated -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; - } - - @Override - public boolean isCancelled() { - return isCancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.isCancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerAdvancementDoneEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerAdvancementDoneEvent.java deleted file mode 100644 index 21ff095af..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerAdvancementDoneEvent.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.advancement.Advancement; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player has completed all criteria in an advancement. - */ -public class PlayerAdvancementDoneEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - // - private final Advancement advancement; - - public PlayerAdvancementDoneEvent(@NotNull Player who, @NotNull Advancement advancement) { - super(who); - this.advancement = advancement; - } - - /** - * Get the advancement which has been completed. - * - * @return completed advancement - */ - @NotNull - public Advancement getAdvancement() { - return advancement; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java deleted file mode 100644 index 6cd236cd1..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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 - */ - @NotNull - public PlayerAnimationType getAnimationType() { - return animationType; - } - - @Override - public boolean isCancelled() { - return this.isCancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.isCancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerAnimationType.java b/api/src/main/java/org/bukkit/event/player/PlayerAnimationType.java deleted file mode 100644 index ea4bf26f0..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerAnimationType.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.event.player; - -/** - * Different types of player animations - */ -public enum PlayerAnimationType { - ARM_SWING -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerArmorStandManipulateEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerArmorStandManipulateEvent.java deleted file mode 100644 index f72dd3ccf..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerArmorStandManipulateEvent.java +++ /dev/null @@ -1,82 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player who, @NotNull final ArmorStand clickedEntity, @NotNull final ItemStack playerItem, @NotNull final ItemStack armorStandItem, @NotNull 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. - */ - @NotNull - 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. - */ - @NotNull - 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. - */ - @NotNull - public EquipmentSlot getSlot() { - return this.slot; - } - - @NotNull - @Override - public ArmorStand getRightClicked() { - return (ArmorStand) this.clickedEntity; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerAttemptPickupItemEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerAttemptPickupItemEvent.java deleted file mode 100644 index fb5cb3dc4..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerAttemptPickupItemEvent.java +++ /dev/null @@ -1,89 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * Thrown when a player attempts to pick an item up from the ground - */ -public class PlayerAttemptPickupItemEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - @NotNull private final Item item; - private final int remaining; - private boolean flyAtPlayer = true; - private boolean isCancelled = false; - - @Deprecated // Remove in 1.13 // Remove in 1.14? - public PlayerAttemptPickupItemEvent(@NotNull final Player player, @NotNull final Item item) { - this(player, item, 0); - } - - public PlayerAttemptPickupItemEvent(@NotNull final Player player, @NotNull final Item item, final int remaining) { - super(player); - this.item = item; - this.remaining = remaining; - } - - /** - * Gets the Item attempted by the player. - * - * @return Item - */ - @NotNull - public Item getItem() { - return item; - } - - /** - * Gets the amount that will remain on the ground, if any - * - * @return amount that will remain on the ground - */ - public int getRemaining() { - return remaining; - } - - /** - * Set if the item will fly at the player - *

Cancelling the event will set this value to false.

- * - * @param flyAtPlayer True for item to fly at player - */ - public void setFlyAtPlayer(boolean flyAtPlayer) { - this.flyAtPlayer = flyAtPlayer; - } - - /** - * Gets if the item will fly at the player - * - * @return True if the item will fly at the player - */ - public boolean getFlyAtPlayer() { - return this.flyAtPlayer; - } - - - @Override - public boolean isCancelled() { - return this.isCancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.isCancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java deleted file mode 100644 index c7d57e286..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java +++ /dev/null @@ -1,160 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * This event is fired when the player is almost about to enter the bed. - */ -public class PlayerBedEnterEvent extends PlayerEvent implements Cancellable { - - /** - * Represents the default possible outcomes of this event. - */ - public enum BedEnterResult { - /** - * The player will enter the bed. - */ - OK, - /** - * The world doesn't allow sleeping (ex. Nether or The End). Entering - * the bed is prevented and the bed explodes. - */ - NOT_POSSIBLE_HERE, - /** - * Entering the bed is prevented due to it not being night nor - * thundering currently. - *

- * If the event is forcefully allowed during daytime, the player will - * enter the bed (and set its bed location), but might get immediately - * thrown out again. - */ - NOT_POSSIBLE_NOW, - /** - * Entering the bed is prevented due to the player being too far away. - */ - TOO_FAR_AWAY, - /** - * Entering the bed is prevented due to there being monsters nearby. - */ - NOT_SAFE, - /** - * Entering the bed is prevented due to there being some other problem. - */ - OTHER_PROBLEM; - } - - private static final HandlerList handlers = new HandlerList(); - private final Block bed; - private final BedEnterResult bedEnterResult; - private Result useBed = Result.DEFAULT; - - public PlayerBedEnterEvent(@NotNull Player who, @NotNull Block bed, @NotNull BedEnterResult bedEnterResult) { - super(who); - this.bed = bed; - this.bedEnterResult = bedEnterResult; - } - - @Deprecated - public PlayerBedEnterEvent(@NotNull Player who, @NotNull Block bed) { - this(who, bed, BedEnterResult.OK); - } - - /** - * This describes the default outcome of this event. - * - * @return the bed enter result representing the default outcome of this event - */ - @NotNull - public BedEnterResult getBedEnterResult() { - return bedEnterResult; - } - - /** - * This controls the action to take with the bed that was clicked on. - *

- * In case of {@link org.bukkit.event.Event.Result#DEFAULT}, the default outcome is described by - * {@link #getBedEnterResult()}. - * - * @return the action to take with the interacted bed - * @see #setUseBed(org.bukkit.event.Event.Result) - */ - @NotNull - public Result useBed() { - return useBed; - } - - /** - * Sets the action to take with the interacted bed. - *

- * {@link org.bukkit.event.Event.Result#ALLOW} will result in the player sleeping, regardless of - * the default outcome described by {@link #getBedEnterResult()}. - *
- * {@link org.bukkit.event.Event.Result#DENY} will prevent the player from sleeping. This has the - * same effect as canceling the event via {@link #setCancelled(boolean)}. - *
- * {@link org.bukkit.event.Event.Result#DEFAULT} will result in the outcome described by - * {@link #getBedEnterResult()}. - * - * @param useBed the action to take with the interacted bed - * @see #useBed() - */ - public void setUseBed(@NotNull Result useBed) { - this.useBed = useBed; - } - - /** - * Gets the cancellation state of this event. Set to true if you want to - * prevent the player from sleeping. - *

- * Canceling the event has the same effect as setting {@link #useBed()} to - * {@link org.bukkit.event.Event.Result#DENY}. - *

- * For backwards compatibility reasons this also returns true if - * {@link #useBed()} is {@link org.bukkit.event.Event.Result#DEFAULT} and the - * {@link #getBedEnterResult() default action} is to prevent bed entering. - * - * @return boolean cancellation state - */ - @Override - public boolean isCancelled() { - return (useBed == Result.DENY || useBed == Result.DEFAULT && bedEnterResult != BedEnterResult.OK); - } - - /** - * 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 the bed. - * - * @param cancel true if you wish to cancel this event - */ - @Override - public void setCancelled(boolean cancel) { - setUseBed(cancel ? Result.DENY : useBed() == Result.DENY ? Result.DEFAULT : useBed()); - } - - /** - * Returns the bed block involved in this event. - * - * @return the bed block involved in this event - */ - @NotNull - public Block getBed() { - return bed; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java deleted file mode 100644 index 8244bf09c..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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; - private boolean setBedSpawn; - - public PlayerBedLeaveEvent(@NotNull final Player who, @NotNull final Block bed, boolean setBedSpawn) { - super(who); - this.bed = bed; - this.setBedSpawn = setBedSpawn; - } - - /** - * Returns the bed block involved in this event. - * - * @return the bed block involved in this event - */ - @NotNull - public Block getBed() { - return bed; - } - - /** - * Get if this event should set the new spawn location for the - * {@link Player}. - *
- * This does not remove any existing spawn location, only prevent it from - * being changed (if true). - *
- * To change a {@link Player}'s spawn location, use - * {@link Player#setBedSpawnLocation(Location)}. - * - * @return true if the spawn location will be changed - */ - public boolean shouldSetSpawnLocation() { - return setBedSpawn; - } - - /** - * Set if this event should set the new spawn location for the - * {@link Player}. - *
- * This will not remove any existing spawn location, only prevent it from - * being changed (if true). - *
- * To change a {@link Player}'s spawn location, use - * {@link Player#setBedSpawnLocation(Location)}. - * - * @param setBedSpawn true to change the new spawn location - */ - public void setSpawnLocation(boolean setBedSpawn) { - this.setBedSpawn = setBedSpawn; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java deleted file mode 100644 index 25bd8153e..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java +++ /dev/null @@ -1,47 +0,0 @@ -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.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player empties a bucket - */ -public class PlayerBucketEmptyEvent extends PlayerBucketEvent { - private static final HandlerList handlers = new HandlerList(); - - @Deprecated - public PlayerBucketEmptyEvent(@NotNull final Player who, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand) { - super(who, blockClicked, blockFace, bucket, itemInHand); - } - - public PlayerBucketEmptyEvent(@NotNull final Player who, @NotNull final Block block, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand) { - super(who, block, blockClicked, blockFace, bucket, itemInHand); - } - // Paper start - add EquipmentSlot - @Deprecated - public PlayerBucketEmptyEvent(@NotNull final Player who, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand, @org.jetbrains.annotations.Nullable final EquipmentSlot hand) { - super(who, blockClicked, blockFace, bucket, itemInHand, hand); - } - - public PlayerBucketEmptyEvent(@NotNull final Player who, @NotNull final Block block, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand, @org.jetbrains.annotations.Nullable final EquipmentSlot hand) { - super(who, block, blockClicked, blockFace, bucket, itemInHand, hand); - } - // Paper end - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java deleted file mode 100644 index 1e0f7ee7d..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java +++ /dev/null @@ -1,131 +0,0 @@ -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.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 block; - private final Block blockClicked; - private final BlockFace blockFace; - private final Material bucket; - private final EquipmentSlot hand; // Paper - add EquipmentSlot - - @Deprecated - public PlayerBucketEvent(@NotNull final Player who, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand) { - this(who, null, blockClicked.getRelative(blockFace), blockFace, bucket, itemInHand); - } - - public PlayerBucketEvent(@NotNull final Player who, @NotNull final Block block, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand) { - // Paper start - add EquipmentSlot - this(who, block, blockClicked, blockFace, bucket, itemInHand, null); - } - - @Deprecated - public PlayerBucketEvent(@NotNull final Player who,@NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand, @Nullable final EquipmentSlot hand) { - this(who, null, blockClicked, blockFace, bucket, itemInHand, hand); - } - - public PlayerBucketEvent(@NotNull final Player who, @NotNull final Block block, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand, @Nullable final EquipmentSlot hand) { - // Paper end - super(who); - this.block = block; - this.blockClicked = blockClicked; - this.blockFace = blockFace; - this.itemStack = itemInHand; - this.bucket = bucket; - this.hand = hand == null ? player.getInventory().getItemInMainHand().equals(itemInHand) ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND : hand; // Paper - add EquipmentSlot - } - - /** - * Returns the bucket used in this event - * - * @return the used bucket - */ - @NotNull - public Material getBucket() { - return bucket; - } - - /** - * Get the resulting item in hand after the bucket event - * - * @return ItemStack hold in hand after the event. - */ - @Nullable - 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(@Nullable ItemStack itemStack) { - this.itemStack = itemStack; - } - - /** - * Gets the block involved in this event. - * - * @return The Block which block is involved in this event - */ - @NotNull - public final Block getBlock() { - return block; - } - - /** - * Return the block clicked - * - * @return the clicked block - */ - @NotNull - public Block getBlockClicked() { - return blockClicked; - } - - /** - * Get the face on the clicked block - * - * @return the clicked face - */ - @NotNull - public BlockFace getBlockFace() { - return blockFace; - } - - // Paper start - /** - * The hand used to perform this action. - * - * @return the hand used - */ - @NotNull - public EquipmentSlot getHand() { - return hand; - } - // Paper end - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java deleted file mode 100644 index 56f1cc2d7..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -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.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player fills a bucket - */ -public class PlayerBucketFillEvent extends PlayerBucketEvent { - private static final HandlerList handlers = new HandlerList(); - - @Deprecated - public PlayerBucketFillEvent(@NotNull final Player who, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand) { - super(who, blockClicked, blockFace, bucket, itemInHand); - } - - public PlayerBucketFillEvent(@NotNull final Player who, @NotNull final Block block, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand) { - super(who, block, blockClicked, blockFace, bucket, itemInHand); - } - - // Paper start - add EquipmentSlot - @Deprecated - public PlayerBucketFillEvent(@NotNull final Player who, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand, @org.jetbrains.annotations.Nullable final EquipmentSlot hand) { - super(who, blockClicked, blockFace, bucket, itemInHand, hand); - } - - // Paper start - add EquipmentSlot - public PlayerBucketFillEvent(@NotNull final Player who, @NotNull Block block, @NotNull final Block blockClicked, @NotNull final BlockFace blockFace, @NotNull final Material bucket, @NotNull final ItemStack itemInHand, @org.jetbrains.annotations.Nullable final EquipmentSlot hand) { - super(who, block, blockClicked, blockFace, bucket, itemInHand, hand); - } - // Paper end - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerChangedMainHandEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerChangedMainHandEvent.java deleted file mode 100644 index 6070b1323..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerChangedMainHandEvent.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.MainHand; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player changes their main hand in the client settings. - */ -public class PlayerChangedMainHandEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - // - private final MainHand mainHand; - - public PlayerChangedMainHandEvent(@NotNull Player who, @NotNull MainHand mainHand) { - super(who); - this.mainHand = mainHand; - } - - /** - * Gets the new main hand of the player. The old hand is still momentarily - * available via {@link Player#getMainHand()}. - * - * @return the new {@link MainHand} of the player - */ - @NotNull - public MainHand getMainHand() { - return mainHand; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java deleted file mode 100644 index f1d1d1e9b..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final World from) { - super(player); - this.from = from; - } - - /** - * Gets the world the player is switching from. - * - * @return player's previous world - */ - @NotNull - public World getFrom() { - return from; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java deleted file mode 100644 index 9316a525f..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final String channel) { - super(player); - this.channel = channel; - } - - @NotNull - public final String getChannel() { - return channel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerChatEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerChatEvent.java deleted file mode 100644 index 26966167b..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerChatEvent.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.bukkit.event.player; - -import java.util.HashSet; -import java.util.Set; -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 org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final String message) { - super(player); - this.message = message; - this.format = "<%1$s> %2$s"; - this.recipients = new HashSet(player.getServer().getOnlinePlayers()); - } - - public PlayerChatEvent(@NotNull final Player player, @NotNull final String message, @NotNull final String format, @NotNull final Set recipients) { - super(player); - this.message = message; - this.format = format; - this.recipients = recipients; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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 - */ - @NotNull - 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(@NotNull 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(@NotNull 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 - */ - @NotNull - 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(@NotNull 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 - */ - @NotNull - public Set getRecipients() { - return recipients; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java deleted file mode 100644 index 0b99c7fb2..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.bukkit.event.player; - -import java.util.Collection; -import org.apache.commons.lang.Validate; -import org.bukkit.Warning; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player attempts to tab-complete a chat message. - * - * @deprecated This event is no longer fired due to client changes - */ -@Deprecated -@Warning(reason = "This event is no longer fired due to client changes") -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(@NotNull final Player who, @NotNull final String message, @NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - public String getLastToken() { - return lastToken; - } - - /** - * This is the collection of completions for this event. - * - * @return the current completions - */ - @NotNull - public Collection getTabCompletions() { - return completions; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java deleted file mode 100644 index a6dae9107..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java +++ /dev/null @@ -1,145 +0,0 @@ -package org.bukkit.event.player; - -import java.util.HashSet; -import java.util.Set; -import org.apache.commons.lang.Validate; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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 final Set recipients; - - public PlayerCommandPreprocessEvent(@NotNull final Player player, @NotNull final String message) { - super(player); - this.recipients = new HashSet(player.getServer().getOnlinePlayers()); - this.message = message; - } - - public PlayerCommandPreprocessEvent(@NotNull final Player player, @NotNull final String message, @NotNull final Set recipients) { - super(player); - this.recipients = recipients; - this.message = message; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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 - */ - @NotNull - 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(@NotNull 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(@NotNull final Player player) throws IllegalArgumentException { - Validate.notNull(player, "Player cannot be null"); - this.player = player; - } - - /** - * 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 - */ - @NotNull - @Deprecated - public Set getRecipients() { - return recipients; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerCommandSendEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerCommandSendEvent.java deleted file mode 100644 index 762825997..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerCommandSendEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.event.player; - -import java.util.Collection; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * This event is called when the list of available server commands is sent to - * the player. - *
- * Commands may be removed from display using this event, but implementations - * are not required to securely remove all traces of the command. If secure - * removal of commands is required, then the command should be assigned a - * permission which is not granted to the player. - */ -public class PlayerCommandSendEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - private final Collection commands; - - public PlayerCommandSendEvent(@NotNull final Player player, @NotNull final Collection commands) { - super(player); - this.commands = commands; - } - - /** - * Returns a mutable collection of all top level commands to be sent. - *
- * It is not legal to add entries to this collection, only remove them. - * Behaviour of adding entries is undefined. - * - * @return collection of all commands - */ - @NotNull - public Collection getCommands() { - return commands; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java deleted file mode 100644 index aca500f32..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final Item drop) { - super(player); - this.drop = drop; - } - - /** - * Gets the ItemDrop created by the player - * - * @return ItemDrop created by the player - */ - @NotNull - public Item getItemDrop() { - return drop; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java deleted file mode 100644 index c8fda418b..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java +++ /dev/null @@ -1,134 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Player who, int slot, @NotNull BookMeta previousBookMeta, @NotNull BookMeta newBookMeta, boolean isSigning) { - super(who); - - Validate.isTrue(slot >= -1 && slot <= 8, "Slot must be in range (-1)-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 - */ - @NotNull - 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 - */ - @NotNull - 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, or -1 for - * off hand. - * - * @return the inventory slot number that the book item occupies - * @deprecated books may be signed from off hand - */ - @Deprecated - 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(@NotNull 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java deleted file mode 100644 index 1712dae89..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Egg; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final Egg egg, final boolean hatching, final byte numHatches, @NotNull final EntityType hatchingType) { - super(player); - this.egg = egg; - this.hatching = hatching; - this.numHatches = numHatches; - this.hatchType = hatchingType; - } - - /** - * Gets the egg involved in this event. - * - * @return the egg involved in this event - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - public void setHatchingType(@NotNull 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerEvent.java deleted file mode 100644 index 793b661b6..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a player related event - */ -public abstract class PlayerEvent extends Event { - protected Player player; - - public PlayerEvent(@NotNull final Player who) { - player = who; - } - - PlayerEvent(@NotNull final Player who, boolean async) { - super(async); - player = who; - - } - - /** - * Returns the player involved in this event - * - * @return Player who is involved in this event - */ - @NotNull - public final Player getPlayer() { - return player; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java deleted file mode 100644 index 7c340f539..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Entity; // Paper -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -import org.jetbrains.annotations.Nullable; // Paper - -/** - * Called when a players experience changes naturally - */ -public class PlayerExpChangeEvent extends PlayerEvent { - private static final HandlerList handlers = new HandlerList(); - // Paper start - @Nullable - private final Entity source; - private int exp; - - public PlayerExpChangeEvent(@NotNull final Player player, final int expAmount) { - this(player, null, expAmount); - } - - public PlayerExpChangeEvent(@NotNull final Player player, @Nullable final Entity sourceEntity, final int expAmount) { - super(player); - source = sourceEntity; - exp = expAmount; - } - - /** - * Get the source that provided the experience. - * - * @return The source of the experience - */ - @Nullable - public Entity getSource() { - return source; - } - // Paper end - - /** - * 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerFishEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerFishEvent.java deleted file mode 100644 index 4d3ff7b29..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerFishEvent.java +++ /dev/null @@ -1,148 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.FishHook; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 FishHook hookEntity; - - public PlayerFishEvent(@NotNull final Player player, @Nullable final Entity entity, @NotNull final FishHook hookEntity, @NotNull 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 - */ - @Nullable - public Entity getCaught() { - return entity; - } - - /** - * Gets the fishing hook. - * - * @return the entity representing the fishing hook/bobber. - */ - @NotNull - public FishHook getHook() { - return hookEntity; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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 - */ - @NotNull - public State getState() { - return state; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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. In - * this instance, a "fish" is any item retrieved from water as a result - * of fishing, ie an item, but not necessarily a fish. - */ - CAUGHT_FISH, - /** - * When a player has successfully caught an entity. This refers to any - * already spawned entity in the world that has been hooked directly by - * the rod. - */ - CAUGHT_ENTITY, - /** - * When a bobber is stuck in the ground. - */ - IN_GROUND, - /** - * When a player fails to catch a bite while fishing usually due to - * poor timing. - */ - FAILED_ATTEMPT, - /** - * When a player reels in their hook without receiving any bites. - */ - REEL_IN, - /** - * Called when there is a bite on the hook and it is ready to be reeled - * in. - */ - BITE - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java deleted file mode 100644 index 4b96e0573..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.GameMode; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final GameMode newGameMode) { - super(player); - this.newGameMode = newGameMode; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - /** - * Gets the GameMode the player is switched to. - * - * @return player's new GameMode - */ - @NotNull - public GameMode getNewGameMode() { - return newGameMode; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerInteractAtEntityEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerInteractAtEntityEvent.java deleted file mode 100644 index 3f24d302e..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerInteractAtEntityEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; - -/** - * Represents an event that is called when a player right clicks an entity that - * also contains the location where the entity was clicked. - *
- * Note that the client may sometimes spuriously send this packet in addition to {@link PlayerInteractEntityEvent}. - * Users are advised to listen to this (parent) class unless specifically required. - *
- * Note that interacting with Armor Stands fires this event only and not its parent and as such users are expressly required - * to listen to this event for that scenario. - */ -public class PlayerInteractAtEntityEvent extends PlayerInteractEntityEvent { - private static final HandlerList handlers = new HandlerList(); - private final Vector position; - - public PlayerInteractAtEntityEvent(@NotNull Player who, @NotNull Entity clickedEntity, @NotNull Vector position) { - this(who, clickedEntity, position, EquipmentSlot.HAND); - } - - public PlayerInteractAtEntityEvent(@NotNull Player who, @NotNull Entity clickedEntity, @NotNull Vector position, @NotNull EquipmentSlot hand) { - super(who, clickedEntity, hand); - this.position = position; - } - - @NotNull - public Vector getClickedPosition() { - return position.clone(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java deleted file mode 100644 index 1d3d62969..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -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; -import org.bukkit.inventory.EquipmentSlot; -import org.jetbrains.annotations.NotNull; - -/** - * 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; - private EquipmentSlot hand; - - public PlayerInteractEntityEvent(@NotNull final Player who, @NotNull final Entity clickedEntity) { - this(who, clickedEntity, EquipmentSlot.HAND); - } - - public PlayerInteractEntityEvent(@NotNull final Player who, @NotNull final Entity clickedEntity, @NotNull final EquipmentSlot hand) { - super(who); - this.clickedEntity = clickedEntity; - this.hand = hand; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - /** - * Gets the entity that was right-clicked by the player. - * - * @return entity right clicked by player - */ - @NotNull - public Entity getRightClicked() { - return this.clickedEntity; - } - - /** - * The hand used to perform this interaction. - * - * @return the hand used to interact - */ - @NotNull - public EquipmentSlot getHand() { - return hand; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java deleted file mode 100644 index 1208e1f8c..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java +++ /dev/null @@ -1,234 +0,0 @@ -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.event.block.BlockCanBuildEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents an event that is called when a player interacts with an object or - * air, potentially fired once for each hand. The hand can be determined using - * {@link #getHand()}. - *

- * This event will fire as cancelled if the vanilla behavior is to do nothing - * (e.g interacting with air). For the purpose of avoiding doubt, this means - * that the event will only be in the cancelled state if it is fired as a result - * of some prediction made by the server where no subsequent code will run, - * rather than when the subsequent interaction activity (e.g. placing a block in - * an illegal position ({@link BlockCanBuildEvent}) will fail. - */ -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; - private EquipmentSlot hand; - - public PlayerInteractEvent(@NotNull final Player who, @NotNull final Action action, @Nullable final ItemStack item, @Nullable final Block clickedBlock, @NotNull final BlockFace clickedFace) { - this(who, action, item, clickedBlock, clickedFace, EquipmentSlot.HAND); - } - - public PlayerInteractEvent(@NotNull final Player who, @NotNull final Action action, @Nullable final ItemStack item, @Nullable final Block clickedBlock, @NotNull final BlockFace clickedFace, @Nullable final EquipmentSlot hand) { - super(who); - this.action = action; - this.item = item; - this.blockClicked = clickedBlock; - this.blockFace = clickedFace; - this.hand = hand; - - useItemInHand = Result.DEFAULT; - useClickedBlock = clickedBlock == null ? Result.DENY : Result.ALLOW; - } - - /** - * Returns the action type - * - * @return Action returns the type of interaction - */ - @NotNull - 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 - * @deprecated This event has two possible cancellation states, one for - * {@link #useInteractedBlock()} and one for {@link #useItemInHand()}. It is - * possible a call might have the former false, but the latter true, eg in - * the case of using a firework whilst gliding. Callers should check the - * relevant methods individually. - */ - @Deprecated - @Override - public boolean isCancelled() { - return useInteractedBlock() == Result.DENY; - } - - /** - * 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 - */ - @Override - 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 - */ - @Nullable - 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 - */ - @NotNull - 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. - */ - @Nullable - public Block getClickedBlock() { - return blockClicked; - } - - /** - * Returns the face of the block that was clicked - * - * @return BlockFace returns the face of the block that was clicked - */ - @NotNull - public BlockFace getBlockFace() { - return blockFace; - } - - /** - * 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 - */ - @NotNull - public Result useInteractedBlock() { - return useClickedBlock; - } - - /** - * @param useInteractedBlock the action to take with the interacted block - */ - public void setUseInteractedBlock(@NotNull 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 - */ - @NotNull - public Result useItemInHand() { - return useItemInHand; - } - - /** - * @param useItemInHand the action to take with the item in hand - */ - public void setUseItemInHand(@NotNull Result useItemInHand) { - this.useItemInHand = useItemInHand; - } - - /** - * The hand used to perform this interaction. May be null in the case of - * {@link Action#PHYSICAL}. - * - * @return the hand used to interact. May be null. - */ - @Nullable - public EquipmentSlot getHand() { - return hand; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java deleted file mode 100644 index a16c9f576..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final ItemStack brokenItem) { - super(player); - this.brokenItem = brokenItem; - } - - /** - * Gets the item that broke - * - * @return The broken item - */ - @NotNull - public ItemStack getBrokenItem() { - return brokenItem; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java deleted file mode 100644 index 373f4b5b5..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java +++ /dev/null @@ -1,105 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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; - @Nullable private ItemStack replacement; // Paper - - /** - * @param player the player consuming - * @param item the ItemStack being consumed - */ - public PlayerItemConsumeEvent(@NotNull final Player player, @NotNull 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(org.bukkit.inventory.ItemStack)} instead. - * - * @return an ItemStack for the item being consumed - */ - @NotNull - public ItemStack getItem() { - return item.clone(); - } - - /** - * Set the item being consumed - * - * @param item the item being consumed - */ - public void setItem(@Nullable ItemStack item) { - if (item == null) { - this.item = new ItemStack(Material.AIR); - } else { - this.item = item; - } - } - - // Paper start - /** - * Return the custom item stack that will replace the consumed item, or null if no - * custom replacement has been set (which means the default replacement will be used). - * - * @return The custom item stack that will replace the consumed item or null - */ - @Nullable - public ItemStack getReplacement() { - return this.replacement; - } - - /** - * Set a custom item stack to replace the consumed item. Pass null to clear any custom - * stack that has been set and use the default replacement. - * - * @param replacement Replacement item to set, null to clear any custom stack and use default - */ - public void setReplacement(@Nullable ItemStack replacement) { - this.replacement = replacement; - } - // Paper end - - @Override - public boolean isCancelled() { - return this.isCancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.isCancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerItemDamageEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerItemDamageEvent.java deleted file mode 100644 index 2d0496339..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerItemDamageEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an item used by the player takes durability damage as a result of - * being used. - */ -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(@NotNull Player player, @NotNull ItemStack what, int damage) { - super(player); - this.item = what; - this.damage = damage; - } - - /** - * Gets the item being damaged. - * - * @return the item - */ - @NotNull - 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; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java deleted file mode 100644 index 39048573a..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/player/PlayerItemMendEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerItemMendEvent.java deleted file mode 100644 index 2f0cbf928..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerItemMendEvent.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.ExperienceOrb; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * Represents when a player has an item repaired via the Mending enchantment. - *
- * This event is fired directly before the {@link PlayerExpChangeEvent}, and the - * results of this event directly affect the {@link PlayerExpChangeEvent}. - */ -public class PlayerItemMendEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private final ItemStack item; - private final ExperienceOrb experienceOrb; - private int repairAmount; - private boolean cancelled; - - public PlayerItemMendEvent(@NotNull Player who, @NotNull ItemStack item, @NotNull ExperienceOrb experienceOrb, int repairAmount) { - super(who); - this.item = item; - this.experienceOrb = experienceOrb; - this.repairAmount = repairAmount; - } - - /** - * Get the {@link ItemStack} to be repaired. - * - * This is not necessarily the item the player is holding. - * - * @return the item to be repaired - */ - @NotNull - public ItemStack getItem() { - return item; - } - - /** - * Get the experience orb triggering the event. - * - * @return the experience orb - */ - @NotNull - public ExperienceOrb getExperienceOrb() { - return experienceOrb; - } - - /** - * Get the amount the item is to be repaired. - * - * The default value is twice the value of the consumed experience orb - * or the remaining damage left on the item, whichever is smaller. - * - * @return how much damage will be repaired by the experience orb - */ - public int getRepairAmount() { - return repairAmount; - } - - /** - * Set the amount the item will be repaired. - * - * Half of this value will be subtracted from the experience orb which initiated this event. - * - * @param amount how much damage will be repaired on the item - */ - public void setRepairAmount(int amount) { - this.repairAmount = amount; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java deleted file mode 100644 index d06684aba..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a player joins a server - */ -public class PlayerJoinEvent extends PlayerEvent { - private static final HandlerList handlers = new HandlerList(); - private String joinMessage; - - public PlayerJoinEvent(@NotNull final Player playerJoined, @Nullable final String joinMessage) { - super(playerJoined); - this.joinMessage = joinMessage; - } - - /** - * Gets the join message to send to all online players - * - * @return string join message. Can be null - */ - @Nullable - public String getJoinMessage() { - return joinMessage; - } - - /** - * Sets the join message to send to all online players - * - * @param joinMessage join message. If null, no message will be sent - */ - public void setJoinMessage(@Nullable String joinMessage) { - this.joinMessage = joinMessage; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerKickEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerKickEvent.java deleted file mode 100644 index 14c337f15..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerKickEvent.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player playerKicked, @NotNull final String kickReason, @NotNull 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 - */ - @NotNull - public String getReason() { - return kickReason; - } - - /** - * Gets the leave message send to all online players - * - * @return string kick reason - */ - @NotNull - public String getLeaveMessage() { - return leaveMessage; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - /** - * Sets the reason why the player is getting kicked - * - * @param kickReason kick reason - */ - public void setReason(@NotNull String kickReason) { - this.kickReason = kickReason; - } - - /** - * Sets the leave message send to all online players - * - * @param leaveMessage leave message - */ - public void setLeaveMessage(@NotNull String leaveMessage) { - this.leaveMessage = leaveMessage; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java deleted file mode 100644 index 00481d733..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerLocaleChangeEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerLocaleChangeEvent.java deleted file mode 100644 index 1db386bb7..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerLocaleChangeEvent.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player changes their locale in the client settings. - */ -public class PlayerLocaleChangeEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - // - private final String locale; - - public PlayerLocaleChangeEvent(@NotNull Player who, @NotNull String locale) { - super(who); - this.locale = locale; - } - - /** - * @see Player#getLocale() - * - * @return the player's new locale - */ - @NotNull - public String getLocale() { - return locale; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java deleted file mode 100644 index 084ca8cfc..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java +++ /dev/null @@ -1,195 +0,0 @@ -package org.bukkit.event.player; - -import java.net.InetAddress; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Stores details for players attempting to log in. - *
- * Note that this event is called early in the player initialization - * process. It is recommended that most options involving the Player - * entity be postponed to the {@link PlayerJoinEvent} instead. - */ -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 - - /** - * 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 - * @param realAddress the actual, unspoofed connecting address - */ - public PlayerLoginEvent(@NotNull final Player player, @NotNull final String hostname, @NotNull final InetAddress address, final @NotNull InetAddress realAddress) { // Spigot - super(player); - this.hostname = hostname; - this.address = address; - // Spigot start - this.realAddress = realAddress; - } - - public PlayerLoginEvent(@NotNull final Player player, @NotNull final String hostname, @NotNull final InetAddress address) { - this(player, hostname, address, address); - // Spigot end - } - - /** - * 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 - * @param realAddress the actual, unspoofed connecting address - */ - public PlayerLoginEvent(@NotNull final Player player, @NotNull String hostname, @NotNull final InetAddress address, @NotNull final Result result, @NotNull final String message, @NotNull 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 - */ - @NotNull - public InetAddress getRealAddress() { - return realAddress; - } - // Spigot end - - /** - * Gets the current result of the login, as an enum - * - * @return Current Result of the login - */ - @NotNull - public Result getResult() { - return result; - } - - /** - * Sets the new result of the login, as an enum - * - * @param result New result to set - */ - public void setResult(@NotNull final Result result) { - this.result = result; - } - - /** - * Gets the current kick message that will be used if getResult() != - * Result.ALLOWED - * - * @return Current kick message - */ - @NotNull - public String getKickMessage() { - return message; - } - - /** - * Sets the kick message to display if getResult() != Result.ALLOWED - * - * @param message New kick message - */ - public void setKickMessage(@NotNull 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 - */ - @NotNull - 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(@NotNull final Result result, @NotNull 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. - */ - @NotNull - public InetAddress getAddress() { - return address; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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/api/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java deleted file mode 100644 index 1a58734d9..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java +++ /dev/null @@ -1,111 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull final Player player, @NotNull final Location from, @Nullable 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 - */ - @Override - 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 - */ - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - /** - * Gets the location this player moved from - * - * @return Location the player moved from - */ - @NotNull - 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(@NotNull Location from) { - validateLocation(from); - this.from = from; - } - - /** - * Gets the location this player moved to - * - * @return Location the player moved to - */ - @NotNull // Paper - 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(@NotNull Location to) { - validateLocation(to); - this.to = to; - } - - private void validateLocation(@NotNull Location loc) { - Preconditions.checkArgument(loc != null, "Cannot use null location!"); - Preconditions.checkArgument(loc.getWorld() != null, "Cannot use null location with null world!"); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerPickupArrowEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerPickupArrowEvent.java deleted file mode 100644 index c9a866394..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerPickupArrowEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.Item; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -/** - * Thrown when a player picks up an arrow from the ground. - */ -public class PlayerPickupArrowEvent extends PlayerPickupItemEvent { - - private final AbstractArrow arrow; - - public PlayerPickupArrowEvent(@NotNull final Player player, @NotNull final Item item, @NotNull final AbstractArrow arrow) { - super(player, item, 0); - this.arrow = arrow; - } - - /** - * Get the arrow being picked up by the player - * - * @return The arrow being picked up - */ - @NotNull - public AbstractArrow getArrow() { - return arrow; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java deleted file mode 100644 index 18d82c111..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.Warning; -import org.bukkit.entity.Item; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.entity.EntityPickupItemEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Thrown when a player picks an item up from the ground - * @deprecated {@link EntityPickupItemEvent} - */ -@Deprecated -@Warning(false) -public class PlayerPickupItemEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private final Item item; - private boolean flyAtPlayer = true; // Paper - private boolean cancel = false; - private final int remaining; - - public PlayerPickupItemEvent(@NotNull final Player player, @NotNull final Item item, final int remaining) { - super(player); - this.item = item; - this.remaining = remaining; - } - - /** - * Gets the Item picked up by the player. - * - * @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; - } - - // Paper Start - /** - * Set if the item will fly at the player - *

Cancelling the event will set this value to false.

- * - * @param flyAtPlayer True for item to fly at player - */ - public void setFlyAtPlayer(boolean flyAtPlayer) { - this.flyAtPlayer = flyAtPlayer; - } - - /** - * Gets if the item will fly at the player - * - * @return True if the item will fly at the player - */ - public boolean getFlyAtPlayer() { - return flyAtPlayer; - } - // Paper End - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - this.flyAtPlayer = !cancel; // Paper - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java deleted file mode 100644 index 5b7550781..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(); - - public PlayerPortalEvent(@NotNull final Player player, @NotNull final Location from, @Nullable final Location to) { - super(player, from, to); - } - - public PlayerPortalEvent(@NotNull Player player, @NotNull Location from, @Nullable Location to, @NotNull TeleportCause cause) { - super(player, from, to, cause); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java deleted file mode 100644 index 63a963202..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.bukkit.event.player; - -import java.net.InetAddress; -import java.util.UUID; -import org.bukkit.Warning; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final String name, @NotNull final InetAddress ipAddress) { - this(name, ipAddress, null); - } - - public PlayerPreLoginEvent(@NotNull final String name, @NotNull final InetAddress ipAddress, @NotNull 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 - */ - @NotNull - public Result getResult() { - return result; - } - - /** - * Sets the new result of the login, as an enum - * - * @param result New result to set - */ - public void setResult(@NotNull final Result result) { - this.result = result; - } - - /** - * Gets the current kick message that will be used if getResult() != - * Result.ALLOWED - * - * @return Current kick message - */ - @NotNull - public String getKickMessage() { - return message; - } - - /** - * Sets the kick message to display if getResult() != Result.ALLOWED - * - * @param message New kick message - */ - public void setKickMessage(@NotNull 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(@NotNull final Result result, @NotNull final String message) { - this.result = result; - this.message = message; - } - - /** - * Gets the player's name. - * - * @return the player's name - */ - @NotNull - public String getName() { - return name; - } - - /** - * Gets the player IP address. - * - * @return The IP address - */ - @NotNull - public InetAddress getAddress() { - return ipAddress; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - /** - * Gets the player's unique ID. - * - * @return The unique ID - */ - @NotNull - public UUID getUniqueId() { - return uniqueId; - } - - @NotNull - 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/api/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java deleted file mode 100644 index d70c25f40..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a player leaves a server - */ -public class PlayerQuitEvent extends PlayerEvent { - private static final HandlerList handlers = new HandlerList(); - private String quitMessage; - - public PlayerQuitEvent(@NotNull final Player who, @Nullable final String quitMessage) { - super(who); - this.quitMessage = quitMessage; - } - - /** - * Gets the quit message to send to all online players - * - * @return string quit message - */ - @Nullable - public String getQuitMessage() { - return quitMessage; - } - - /** - * Sets the quit message to send to all online players - * - * @param quitMessage quit message - */ - public void setQuitMessage(@Nullable String quitMessage) { - this.quitMessage = quitMessage; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerRecipeDiscoverEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerRecipeDiscoverEvent.java deleted file mode 100644 index f41c29e98..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerRecipeDiscoverEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.NamespacedKey; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player discovers a new recipe in the recipe book. - */ -public class PlayerRecipeDiscoverEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - - private boolean cancel = false; - private final NamespacedKey recipe; - - public PlayerRecipeDiscoverEvent(@NotNull Player who, @NotNull NamespacedKey recipe) { - super(who); - this.recipe = recipe; - } - - /** - * Get the namespaced key of the discovered recipe. - * - * @return the discovered recipe - */ - @NotNull - public NamespacedKey getRecipe() { - return recipe; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java deleted file mode 100644 index 97ae244fa..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -/** - * This is called immediately after a player registers for a plugin channel. - */ -public class PlayerRegisterChannelEvent extends PlayerChannelEvent { - - public PlayerRegisterChannelEvent(@NotNull final Player player, @NotNull final String channel) { - super(player, channel); - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerResourcePackStatusEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerResourcePackStatusEvent.java deleted file mode 100644 index 4c2102a11..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerResourcePackStatusEvent.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a player takes action on a resource pack request sent via - * {@link Player#setResourcePack(java.lang.String)}. - */ -public class PlayerResourcePackStatusEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - @Deprecated - private final String hash; // Paper - private final Status status; - - public PlayerResourcePackStatusEvent(@NotNull final Player who, @NotNull Status resourcePackStatus) { - super(who); - this.hash = null; // Paper - this.status = resourcePackStatus; - } - - @Deprecated // Paper - public PlayerResourcePackStatusEvent(final Player who, Status resourcePackStatus, String hash) { - super(who); - this.hash = hash; // Paper - this.status = resourcePackStatus; - } - - @Deprecated - /** - * @deprecated Hash does not seem to ever be set - */ - public String getHash() { - return this.hash; - } - // Paper end - - /** - * Gets the status of this pack. - * - * @return the current status - */ - @NotNull - public Status getStatus() { - return status; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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/api/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java deleted file mode 100644 index 71b566e44..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java +++ /dev/null @@ -1,64 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player respawnPlayer, @NotNull final Location respawnLocation, final boolean isBedSpawn) { - super(respawnPlayer); - this.respawnLocation = respawnLocation; - this.isBedSpawn = isBedSpawn; - } - - /** - * Gets the current respawn location - * - * @return Location current respawn location - */ - @NotNull - public Location getRespawnLocation() { - return this.respawnLocation; - } - - /** - * Sets the new respawn location - * - * @param respawnLocation new location for the respawn - */ - public void setRespawnLocation(@NotNull 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerRiptideEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerRiptideEvent.java deleted file mode 100644 index c23142a72..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerRiptideEvent.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * This event is fired when the player activates the riptide enchantment, using - * their trident to propel them through the air. - *
- * N.B. the riptide action is currently performed client side, so manipulating - * the player in this event may have undesired effects. - */ -public class PlayerRiptideEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - private final ItemStack item; - - public PlayerRiptideEvent(@NotNull final Player who, @NotNull final ItemStack item) { - super(who); - this.item = item; - } - - /** - * Gets the item containing the used enchantment. - * - * @return held enchanted item - */ - @NotNull - public ItemStack getItem() { - return item; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java deleted file mode 100644 index 93429c533..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player who, @NotNull final Entity what) { - super(who); - this.cancel = false; - this.what = what; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - /** - * Gets the entity the player is shearing - * - * @return the entity the player is shearing - */ - @NotNull - public Entity getEntity() { - return what; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java deleted file mode 100644 index f971844bf..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java +++ /dev/null @@ -1,125 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a player statistic is incremented. - *

- * This event is not called for some high frequency statistics, e.g. 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(@NotNull Player player, @NotNull 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(@NotNull Player player, @NotNull Statistic statistic, int initialValue, int newValue, @NotNull EntityType entityType) { - super(player); - this.statistic = statistic; - this.initialValue = initialValue; - this.newValue = newValue; - this.entityType = entityType; - this.material = null; - } - - public PlayerStatisticIncrementEvent(@NotNull Player player, @NotNull Statistic statistic, int initialValue, int newValue, @NotNull 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 - */ - @NotNull - 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 - */ - @Nullable - 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 - */ - @Nullable - public Material getMaterial() { - return material; - } - - @Override - public boolean isCancelled() { - return isCancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.isCancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerSwapHandItemsEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerSwapHandItemsEvent.java deleted file mode 100644 index 9f592317c..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerSwapHandItemsEvent.java +++ /dev/null @@ -1,87 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a player swap items between main hand and off hand using the - * hotkey. - */ -public class PlayerSwapHandItemsEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private ItemStack mainHandItem; - private ItemStack offHandItem; - private boolean cancelled; - - public PlayerSwapHandItemsEvent(@NotNull Player player, @NotNull ItemStack mainHandItem, @NotNull ItemStack offHandItem) { - super(player); - - this.mainHandItem = mainHandItem; - this.offHandItem = offHandItem; - } - - /** - * Gets the item switched to the main hand. - * - * @return item in the main hand - */ - @Nullable - public ItemStack getMainHandItem() { - return mainHandItem; - } - - /** - * Sets the item in the main hand. - * - * @param mainHandItem new item in the main hand - */ - public void setMainHandItem(@Nullable ItemStack mainHandItem) { - this.mainHandItem = mainHandItem; - } - - /** - * Gets the item switched to the off hand. - * - * @return item in the off hand - */ - @Nullable - public ItemStack getOffHandItem() { - return offHandItem; - } - - /** - * Sets the item in the off hand. - * - * @param offHandItem new item in the off hand - */ - public void setOffHandItem(@Nullable ItemStack offHandItem) { - this.offHandItem = offHandItem; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerTakeLecternBookEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerTakeLecternBookEvent.java deleted file mode 100644 index 5ef664a65..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerTakeLecternBookEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.block.Lectern; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * This event is called when a player clicks the button to take a book of a - * Lectern. If this event is cancelled the book remains on the lectern. - */ -public class PlayerTakeLecternBookEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private boolean cancelled; - private final Lectern lectern; - - public PlayerTakeLecternBookEvent(@NotNull Player who, @NotNull Lectern lectern) { - super(who); - this.lectern = lectern; - } - - /** - * Gets the lectern involved. - * - * @return the Lectern - */ - @NotNull - public Lectern getLectern() { - return lectern; - } - - /** - * Gets the current ItemStack on the lectern. - * - * @return the ItemStack on the Lectern - */ - @Nullable - public ItemStack getBook() { - return lectern.getInventory().getItem(0); - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java deleted file mode 100644 index 553d77404..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull final Player player, @NotNull final Location from, @Nullable final Location to) { - super(player, from, to); - } - - public PlayerTeleportEvent(@NotNull final Player player, @NotNull final Location from, @Nullable final Location to, @NotNull final TeleportCause cause) { - this(player, from, to); - - this.cause = cause; - } - - /** - * Gets the cause of this teleportation event - * - * @return Cause of the event - */ - @NotNull - 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 spectator menu - */ - SPECTATE, - /** - * Indicates the teleportation was caused by a player entering an End - * gateway - */ - END_GATEWAY, - /** - * Indicates the teleportation was caused by a player consuming chorus - * fruit - */ - CHORUS_FRUIT, - /** - * Indicates the teleportation was caused by an event not covered by - * this enum - */ - UNKNOWN; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java deleted file mode 100644 index 9c200f8ac..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java deleted file mode 100644 index 348e5b5e5..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java deleted file mode 100644 index dc8cf2197..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java deleted file mode 100644 index cf78950b5..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Entity entity, @NotNull Player player) { - super(entity, UnleashReason.PLAYER_UNLEASH); - this.player = player; - } - - /** - * Returns the player who is unleashing the entity. - * - * @return The player - */ - @NotNull - public Player getPlayer() { - return player; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java deleted file mode 100644 index b22bc21f5..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.event.player; - -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -/** - * This is called immediately after a player unregisters for a plugin channel. - */ -public class PlayerUnregisterChannelEvent extends PlayerChannelEvent { - - public PlayerUnregisterChannelEvent(@NotNull final Player player, @NotNull final String channel) { - super(player, channel); - } -} diff --git a/api/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java b/api/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java deleted file mode 100644 index dee4a8e6f..000000000 --- a/api/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player player, @NotNull final Vector velocity) { - super(player); - this.velocity = velocity; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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 - */ - @NotNull - 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(@NotNull Vector velocity) { - this.velocity = velocity; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/raid/RaidEvent.java b/api/src/main/java/org/bukkit/event/raid/RaidEvent.java deleted file mode 100644 index b2ff4bc33..000000000 --- a/api/src/main/java/org/bukkit/event/raid/RaidEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.event.raid; - -import org.bukkit.Raid; -import org.bukkit.World; -import org.bukkit.event.world.WorldEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Represents events related to raids. - */ -public abstract class RaidEvent extends WorldEvent { - - private final Raid raid; - - protected RaidEvent(@NotNull Raid raid, @NotNull World world) { - super(world); - this.raid = raid; - } - - /** - * Returns the raid involved with this event. - * - * @return Raid - */ - @NotNull - public Raid getRaid() { - return raid; - } -} diff --git a/api/src/main/java/org/bukkit/event/raid/RaidFinishEvent.java b/api/src/main/java/org/bukkit/event/raid/RaidFinishEvent.java deleted file mode 100644 index f0d280b8c..000000000 --- a/api/src/main/java/org/bukkit/event/raid/RaidFinishEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bukkit.event.raid; - -import java.util.Collections; -import java.util.List; -import org.bukkit.Raid; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * This event is called when a {@link Raid} was complete with a clear result. - */ -public class RaidFinishEvent extends RaidEvent { - - private static final HandlerList handlers = new HandlerList(); - // - private final List winners; - - public RaidFinishEvent(@NotNull Raid raid, @NotNull World world, @NotNull List winners) { - super(raid, world); - this.winners = winners; - } - - /** - * Returns an immutable list contains all winners. - *
- * Note: Players who are considered as heroes but were not online at the - * end would not be included in this list. - * - * @return winners - */ - @NotNull - public List getWinners() { - return Collections.unmodifiableList(winners); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/raid/RaidSpawnWaveEvent.java b/api/src/main/java/org/bukkit/event/raid/RaidSpawnWaveEvent.java deleted file mode 100644 index cd58dd7de..000000000 --- a/api/src/main/java/org/bukkit/event/raid/RaidSpawnWaveEvent.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.bukkit.event.raid; - -import java.util.Collections; -import java.util.List; -import org.bukkit.Raid; -import org.bukkit.World; -import org.bukkit.entity.Raider; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a raid wave spawns. - */ -public class RaidSpawnWaveEvent extends RaidEvent { - - private static final HandlerList handlers = new HandlerList(); - // - private final List raiders; - private final Raider leader; - - public RaidSpawnWaveEvent(@NotNull Raid raid, @NotNull World world, @Nullable Raider leader, @NotNull List raiders) { - super(raid, world); - this.raiders = raiders; - this.leader = leader; - } - - /** - * Returns the patrol leader. - * - * @return {@link Raider} - */ - @Nullable - public Raider getPatrolLeader() { - return leader; - } - - /** - * Returns all {@link Raider} that spawned in this wave. - * - * @return an immutable list of raiders - */ - @NotNull - public List getRaiders() { - return Collections.unmodifiableList(raiders); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/raid/RaidStopEvent.java b/api/src/main/java/org/bukkit/event/raid/RaidStopEvent.java deleted file mode 100644 index 9e852ac97..000000000 --- a/api/src/main/java/org/bukkit/event/raid/RaidStopEvent.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.bukkit.event.raid; - -import org.bukkit.Raid; -import org.bukkit.World; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a {@link Raid} is stopped. - */ -public class RaidStopEvent extends RaidEvent { - - private static final HandlerList handlers = new HandlerList(); - // - private final Reason reason; - - public RaidStopEvent(@NotNull Raid raid, @NotNull World world, @NotNull Reason reason) { - super(raid, world); - this.reason = reason; - } - - /** - * Returns the stop reason. - * - * @return Reason - */ - @NotNull - public Reason getReason() { - return reason; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - public enum Reason { - - /** - * Because the difficulty has been changed to peaceful. - */ - PEACE, - /** - * The raid took a long time without a final result. - */ - TIMEOUT, - /** - * Finished the raid. - */ - FINISHED, - /** - * Couldn't find a suitable place to spawn raiders. - */ - UNSPAWNABLE, - /** - * The place where the raid occurs no longer be a village. - */ - NOT_IN_VILLAGE - } -} diff --git a/api/src/main/java/org/bukkit/event/raid/RaidTriggerEvent.java b/api/src/main/java/org/bukkit/event/raid/RaidTriggerEvent.java deleted file mode 100644 index 128e43cf1..000000000 --- a/api/src/main/java/org/bukkit/event/raid/RaidTriggerEvent.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.event.raid; - -import org.bukkit.Raid; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a {@link Raid} is triggered (e.g: a player with Bad Omen effect - * enters a village). - */ -public class RaidTriggerEvent extends RaidEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private final Player player; - private boolean cancel; - - public RaidTriggerEvent(@NotNull Raid raid, @NotNull World world, @NotNull Player player) { - super(raid, world); - this.player = player; - } - - /** - * Returns the player who triggered the raid. - * - * @return triggering player - */ - @NotNull - public Player getPlayer() { - return player; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - 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/api/src/main/java/org/bukkit/event/server/BroadcastMessageEvent.java b/api/src/main/java/org/bukkit/event/server/BroadcastMessageEvent.java deleted file mode 100644 index 03bfca9d3..000000000 --- a/api/src/main/java/org/bukkit/event/server/BroadcastMessageEvent.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.bukkit.event.server; - -import java.util.Set; -import org.bukkit.command.CommandSender; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.jetbrains.annotations.NotNull; - -/** - * Event triggered for server broadcast messages such as from - * {@link org.bukkit.Server#broadcast(String, String)}. - * - * This event behaves similarly to {@link AsyncPlayerChatEvent} in that it - * should be async if fired from an async thread. Please see that event for - * further information. - */ -public class BroadcastMessageEvent extends ServerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private String message; - private final Set recipients; - private boolean cancelled = false; - - @Deprecated - public BroadcastMessageEvent(@NotNull String message, @NotNull Set recipients) { - this(false, message, recipients); - } - - public BroadcastMessageEvent(boolean isAsync, @NotNull String message, @NotNull Set recipients) { - super(isAsync); - this.message = message; - this.recipients = recipients; - } - - /** - * Get the message to broadcast. - * - * @return Message to broadcast - */ - @NotNull - public String getMessage() { - return message; - } - - /** - * Set the message to broadcast. - * - * @param message New message to broadcast - */ - public void setMessage(@NotNull String message) { - this.message = message; - } - - /** - * 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 CommandSenders who will see this chat message - */ - @NotNull - public Set getRecipients() { - return recipients; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/MapInitializeEvent.java b/api/src/main/java/org/bukkit/event/server/MapInitializeEvent.java deleted file mode 100644 index dc7440d2e..000000000 --- a/api/src/main/java/org/bukkit/event/server/MapInitializeEvent.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.event.HandlerList; -import org.bukkit.map.MapView; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a map is initialized. - */ -public class MapInitializeEvent extends ServerEvent { - private static final HandlerList handlers = new HandlerList(); - private final MapView mapView; - - public MapInitializeEvent(@NotNull final MapView mapView) { - this.mapView = mapView; - } - - /** - * Gets the map initialized in this event. - * - * @return Map for this event - */ - @NotNull - public MapView getMap() { - return mapView; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/PluginDisableEvent.java b/api/src/main/java/org/bukkit/event/server/PluginDisableEvent.java deleted file mode 100644 index a4fe2d7b8..000000000 --- a/api/src/main/java/org/bukkit/event/server/PluginDisableEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a plugin is disabled. - */ -public class PluginDisableEvent extends PluginEvent { - private static final HandlerList handlers = new HandlerList(); - - public PluginDisableEvent(@NotNull final Plugin plugin) { - super(plugin); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/PluginEnableEvent.java b/api/src/main/java/org/bukkit/event/server/PluginEnableEvent.java deleted file mode 100644 index fe78757d6..000000000 --- a/api/src/main/java/org/bukkit/event/server/PluginEnableEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a plugin is enabled. - */ -public class PluginEnableEvent extends PluginEvent { - private static final HandlerList handlers = new HandlerList(); - - public PluginEnableEvent(@NotNull final Plugin plugin) { - super(plugin); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/PluginEvent.java b/api/src/main/java/org/bukkit/event/server/PluginEvent.java deleted file mode 100644 index 89487b359..000000000 --- a/api/src/main/java/org/bukkit/event/server/PluginEvent.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * Used for plugin enable and disable events - */ -public abstract class PluginEvent extends ServerEvent { - private final Plugin plugin; - - public PluginEvent(@NotNull final Plugin plugin) { - this.plugin = plugin; - } - - /** - * Gets the plugin involved in this event - * - * @return Plugin for this event - */ - @NotNull - public Plugin getPlugin() { - return plugin; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java b/api/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java deleted file mode 100644 index 2dac594c5..000000000 --- a/api/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.command.CommandSender; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * This event is called when a command is received 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(@NotNull final CommandSender sender, @NotNull final String command) { - super(sender, command); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/ServerCommandEvent.java b/api/src/main/java/org/bukkit/event/server/ServerCommandEvent.java deleted file mode 100644 index 617459afa..000000000 --- a/api/src/main/java/org/bukkit/event/server/ServerCommandEvent.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.command.CommandSender; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * This event is called when a command is run by a non-player. 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(@NotNull final CommandSender sender, @NotNull 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 - */ - @NotNull - 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(@NotNull String message) { - this.command = message; - } - - /** - * Get the command sender. - * - * @return The sender - */ - @NotNull - public CommandSender getSender() { - return sender; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/ServerEvent.java b/api/src/main/java/org/bukkit/event/server/ServerEvent.java deleted file mode 100644 index 05167fb34..000000000 --- a/api/src/main/java/org/bukkit/event/server/ServerEvent.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.Bukkit; -import org.bukkit.event.Event; - -/** - * Miscellaneous server events - */ -public abstract class ServerEvent extends Event { - - public ServerEvent() { - super(!Bukkit.isPrimaryThread()); // Paper - } - - public ServerEvent(boolean isAsync) { - super(isAsync); - } -} diff --git a/api/src/main/java/org/bukkit/event/server/ServerListPingEvent.java b/api/src/main/java/org/bukkit/event/server/ServerListPingEvent.java deleted file mode 100644 index 7a2a58bac..000000000 --- a/api/src/main/java/org/bukkit/event/server/ServerListPingEvent.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.bukkit.event.server; - -import java.net.InetAddress; -import java.util.Iterator; -import org.apache.commons.lang.Validate; -import org.bukkit.UndefinedNullability; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.util.CachedServerIcon; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final InetAddress address, @NotNull final String motd, final int numPlayers, final int maxPlayers) { - super(true); - 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(@NotNull final InetAddress address, @NotNull final String motd, final int maxPlayers) { - super(true); - 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 - */ - @NotNull - public InetAddress getAddress() { - return address; - } - - /** - * Get the message of the day message. - * - * @return the message of the day - */ - @NotNull - public String getMotd() { - return motd; - } - - /** - * Change the message of the day message. - * - * @param motd the message of the day - */ - public void setMotd(@NotNull 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(@UndefinedNullability("implementation dependent") CachedServerIcon icon) throws IllegalArgumentException, UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - 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 - */ - @NotNull - @Override - public Iterator iterator() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } -} diff --git a/api/src/main/java/org/bukkit/event/server/ServerLoadEvent.java b/api/src/main/java/org/bukkit/event/server/ServerLoadEvent.java deleted file mode 100644 index c9a252d7e..000000000 --- a/api/src/main/java/org/bukkit/event/server/ServerLoadEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * This event is called when either the server startup or reload has completed. - */ -public class ServerLoadEvent extends ServerEvent { - - /** - * Represents the context in which the enclosing event has been completed. - */ - public enum LoadType { - STARTUP, RELOAD; - } - - private static final HandlerList handlers = new HandlerList(); - private final LoadType type; - - /** - * Creates a {@code ServerLoadEvent} with a given loading type. - * - * @param type the context in which the server was loaded - */ - public ServerLoadEvent(@NotNull LoadType type) { - this.type = type; - } - - /** - * Gets the context in which the server was loaded. - * - * @return the context in which the server was loaded - */ - @NotNull - public LoadType getType() { - return type; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/ServiceEvent.java b/api/src/main/java/org/bukkit/event/server/ServiceEvent.java deleted file mode 100644 index 55e278cd0..000000000 --- a/api/src/main/java/org/bukkit/event/server/ServiceEvent.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.plugin.RegisteredServiceProvider; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final RegisteredServiceProvider provider) { - this.provider = provider; - } - - @NotNull - public RegisteredServiceProvider getProvider() { - return provider; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java b/api/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java deleted file mode 100644 index d7f9227ef..000000000 --- a/api/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull RegisteredServiceProvider registeredProvider) { - super(registeredProvider); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java b/api/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java deleted file mode 100644 index f286799ee..000000000 --- a/api/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.event.server; - -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull RegisteredServiceProvider serviceProvider) { - super(serviceProvider); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/server/TabCompleteEvent.java b/api/src/main/java/org/bukkit/event/server/TabCompleteEvent.java deleted file mode 100644 index f96c4ba53..000000000 --- a/api/src/main/java/org/bukkit/event/server/TabCompleteEvent.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.bukkit.event.server; - -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.lang.Validate; -import org.bukkit.command.CommandSender; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerCommandSendEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Called when a {@link CommandSender} of any description (ie: player or - * console) attempts to tab complete. - *
- * Note that due to client changes, if the sender is a Player, this event will - * only begin to fire once command arguments are specified, not commands - * themselves. Plugins wishing to remove commands from tab completion are - * advised to ensure the client does not have permission for the relevant - * commands, or use {@link PlayerCommandSendEvent}. - */ -public class TabCompleteEvent extends Event implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - // - private final CommandSender sender; - private final String buffer; - private List completions; - private boolean cancelled; - - public TabCompleteEvent(@NotNull CommandSender sender, @NotNull String buffer, @NotNull List completions) { - // Paper start - this(sender, buffer, completions, sender instanceof org.bukkit.command.ConsoleCommandSender || buffer.startsWith("/"), null); - } - public TabCompleteEvent(@NotNull CommandSender sender, @NotNull String buffer, @NotNull List completions, boolean isCommand, @Nullable org.bukkit.Location location) { - this.isCommand = isCommand; - this.loc = location; - // Paper end - Validate.notNull(sender, "sender"); - Validate.notNull(buffer, "buffer"); - Validate.notNull(completions, "completions"); - - this.sender = sender; - this.buffer = buffer; - this.completions = completions; - } - - /** - * Get the sender completing this command. - * - * @return the {@link CommandSender} instance - */ - @NotNull - public CommandSender getSender() { - return sender; - } - - /** - * Return the entire buffer which formed the basis of this completion. - * - * @return command buffer, as entered - */ - @NotNull - public String getBuffer() { - return buffer; - } - - /** - * The list of completions which will be offered to the sender, in order. - * This list is mutable and reflects what will be offered. - * - * @return a list of offered completions - */ - @NotNull - public List getCompletions() { - return completions; - } - - // Paper start - private final boolean isCommand; - private final org.bukkit.Location loc; - /** - * @return True if it is a command being tab completed, false if it is a chat message. - */ - public boolean isCommand() { - return isCommand; - } - - /** - * @return The position looked at by the sender, or null if none - */ - @Nullable - public org.bukkit.Location getLocation() { - return loc; - } - // Paper end - - /** - * Set the completions offered, overriding any already set. - * - * The passed collection will be cloned to a new List. You must call {{@link #getCompletions()}} to mutate from here - * - * @param completions the new completions - */ - public void setCompletions(@NotNull List completions) { - Validate.notNull(completions); - this.completions = new ArrayList<>(completions); // Paper - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java deleted file mode 100644 index 316f625aa..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.event.vehicle; - -import org.bukkit.block.Block; -import org.bukkit.entity.Vehicle; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Vehicle vehicle, @NotNull final Block block) { - super(vehicle); - this.block = block; - } - - /** - * Gets the block the vehicle collided with - * - * @return the block the vehicle collided with - */ - @NotNull - public Block getBlock() { - return block; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java deleted file mode 100644 index 9d493c155..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.bukkit.event.vehicle; - -import org.bukkit.entity.Vehicle; -import org.jetbrains.annotations.NotNull; - -/** - * Raised when a vehicle collides. - */ -public abstract class VehicleCollisionEvent extends VehicleEvent { - public VehicleCollisionEvent(@NotNull final Vehicle vehicle) { - super(vehicle); - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java deleted file mode 100644 index c1f107db9..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.event.vehicle; - -import org.bukkit.entity.Vehicle; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Raised when a vehicle is created. - */ -public class VehicleCreateEvent extends VehicleEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - - public VehicleCreateEvent(@NotNull final Vehicle vehicle) { - super(vehicle); - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java deleted file mode 100644 index 45da51d59..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java +++ /dev/null @@ -1,73 +0,0 @@ -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.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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; - - public VehicleDamageEvent(@NotNull final Vehicle vehicle, @Nullable 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 - */ - @Nullable - public Entity getAttacker() { - return attacker; - } - - /** - * Gets the damage done to the vehicle - * - * @return the damage done to the vehicle - */ - public double getDamage() { - return damage; - } - - /** - * Sets the damage done to the vehicle - * - * @param damage The damage - */ - public void setDamage(double damage) { - this.damage = damage; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java deleted file mode 100644 index 26bc6898f..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java +++ /dev/null @@ -1,55 +0,0 @@ -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.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull final Vehicle vehicle, @Nullable 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 - */ - @Nullable - public Entity getAttacker() { - return attacker; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java deleted file mode 100644 index 64f21f684..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -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.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Vehicle vehicle, @NotNull final Entity entered) { - super(vehicle); - this.entered = entered; - } - - /** - * Gets the Entity that entered the vehicle. - * - * @return the Entity that entered the vehicle - */ - @NotNull - public Entity getEntered() { - return entered; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java deleted file mode 100644 index 6bafc62e2..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -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.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Vehicle vehicle, @NotNull final Entity entity) { - super(vehicle); - this.entity = entity; - } - - @NotNull - public Entity getEntity() { - return entity; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java deleted file mode 100644 index 63df27056..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.event.vehicle; - -import org.bukkit.entity.Vehicle; -import org.bukkit.event.Event; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a vehicle-related event. - */ -public abstract class VehicleEvent extends Event { - protected Vehicle vehicle; - - public VehicleEvent(@NotNull final Vehicle vehicle) { - this.vehicle = vehicle; - } - - /** - * Get the vehicle. - * - * @return the vehicle - */ - @NotNull - public final Vehicle getVehicle() { - return vehicle; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java deleted file mode 100644 index a976c32de..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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; - private final boolean isCancellable; // Paper - - public VehicleExitEvent(@NotNull final Vehicle vehicle, @NotNull final LivingEntity exited, boolean isCancellable) { // Paper - super(vehicle); - this.exited = exited; - // Paper start - this.isCancellable = isCancellable; - } - - public VehicleExitEvent(@NotNull final Vehicle vehicle, @NotNull final LivingEntity exited) { - this(vehicle, exited, true); - // Paper end - } - - /** - * Get the living entity that exited the vehicle. - * - * @return The entity. - */ - @NotNull - public LivingEntity getExited() { - return exited; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - // Paper start - if (cancel && !isCancellable) { - return; - } - this.cancelled = cancel; - } - - public boolean isCancellable() { - return isCancellable; - // paper end - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java deleted file mode 100644 index 7bfb84d39..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.bukkit.event.vehicle; - -import org.bukkit.Location; -import org.bukkit.entity.Vehicle; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Vehicle vehicle, @NotNull final Location from, @NotNull final Location to) { - super(vehicle); - - this.from = from; - this.to = to; - } - - /** - * Get the previous position. - * - * @return Old position. - */ - @NotNull - public Location getFrom() { - return from; - } - - /** - * Get the next position. - * - * @return New position. - */ - @NotNull - public Location getTo() { - return to; - } - - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java b/api/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java deleted file mode 100644 index 098192a5e..000000000 --- a/api/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.event.vehicle; - -import org.bukkit.entity.Vehicle; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a vehicle updates - */ -public class VehicleUpdateEvent extends VehicleEvent { - private static final HandlerList handlers = new HandlerList(); - - public VehicleUpdateEvent(@NotNull final Vehicle vehicle) { - super(vehicle); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java b/api/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java deleted file mode 100644 index 418f9391d..000000000 --- a/api/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.bukkit.event.weather; - -import org.bukkit.World; -import org.bukkit.entity.LightningStrike; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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; - private final Cause cause; - - @Deprecated - public LightningStrikeEvent(@NotNull final World world, @NotNull final LightningStrike bolt) { - this(world, bolt, Cause.UNKNOWN); - } - - public LightningStrikeEvent(@NotNull final World world, @NotNull final LightningStrike bolt, @NotNull final Cause cause) { - super(world); - this.bolt = bolt; - this.cause = cause; - } - - @Override - public boolean isCancelled() { - return canceled; - } - - @Override - public void setCancelled(boolean cancel) { - canceled = cancel; - } - - /** - * Gets the bolt which is striking the earth. - * - * @return lightning entity - */ - @NotNull - public LightningStrike getLightning() { - return bolt; - } - - /** - * Gets the cause of this lightning strike. - * - * @return strike cause - */ - @NotNull - public Cause getCause() { - return cause; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - public enum Cause { - /** - * Triggered by the /summon command. - */ - COMMAND, - /** - * Triggered by an enchanted trident. - */ - TRIDENT, - /** - * Triggered by a skeleton horse trap. - */ - TRAP, - /** - * Triggered by weather. - */ - WEATHER, - /** - * Unknown trigger. - */ - UNKNOWN; - } -} diff --git a/api/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java b/api/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java deleted file mode 100644 index 6cdf83476..000000000 --- a/api/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.event.weather; - -import org.bukkit.World; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final World world, final boolean to) { - super(world); - this.to = to; - } - - @Override - public boolean isCancelled() { - return canceled; - } - - @Override - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java b/api/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java deleted file mode 100644 index d562d87e7..000000000 --- a/api/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.event.weather; - -import org.bukkit.World; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final World world, final boolean to) { - super(world); - this.to = to; - } - - @Override - public boolean isCancelled() { - return canceled; - } - - @Override - 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/weather/WeatherEvent.java b/api/src/main/java/org/bukkit/event/weather/WeatherEvent.java deleted file mode 100644 index e1854d807..000000000 --- a/api/src/main/java/org/bukkit/event/weather/WeatherEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.event.weather; - -import org.bukkit.World; -import org.bukkit.event.Event; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Weather-related event - */ -public abstract class WeatherEvent extends Event { - protected World world; - - public WeatherEvent(@NotNull final World where) { - world = where; - } - - /** - * Returns the World where this event is occurring - * - * @return World this event is occurring in - */ - @NotNull - public final World getWorld() { - return world; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/ChunkEvent.java b/api/src/main/java/org/bukkit/event/world/ChunkEvent.java deleted file mode 100644 index 7ffc6a77b..000000000 --- a/api/src/main/java/org/bukkit/event/world/ChunkEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.Chunk; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Chunk related event - */ -public abstract class ChunkEvent extends WorldEvent { - protected Chunk chunk; - - protected ChunkEvent(@NotNull final Chunk chunk) { - super(chunk.getWorld()); - this.chunk = chunk; - } - - /** - * Gets the chunk being loaded/unloaded - * - * @return Chunk that triggered this event - */ - @NotNull - public Chunk getChunk() { - return chunk; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java b/api/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java deleted file mode 100644 index ae8ef3392..000000000 --- a/api/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.Chunk; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a chunk is loaded - */ -public class ChunkLoadEvent extends ChunkEvent { - private static final HandlerList handlers = new HandlerList(); - private final boolean newChunk; - - public ChunkLoadEvent(@NotNull 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; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java b/api/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java deleted file mode 100644 index 46d91403c..000000000 --- a/api/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.Chunk; -import org.bukkit.event.HandlerList; -import org.bukkit.generator.BlockPopulator; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Chunk chunk) { - super(chunk); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java b/api/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java deleted file mode 100644 index 5d8271626..000000000 --- a/api/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.Chunk; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a chunk is unloaded - */ -public class ChunkUnloadEvent extends ChunkEvent { - private static final HandlerList handlers = new HandlerList(); - private boolean saveChunk; - - public ChunkUnloadEvent(@NotNull final Chunk chunk) { - this(chunk, true); - } - - public ChunkUnloadEvent(@NotNull Chunk chunk, boolean save) { - super(chunk); - this.saveChunk = save; - } - - /** - * Return whether this chunk will be saved to disk. - * - * @return chunk save status - */ - public boolean isSaveChunk() { - return saveChunk; - } - - /** - * Set whether this chunk will be saved to disk. - * - * @param saveChunk chunk save status - */ - public void setSaveChunk(boolean saveChunk) { - this.saveChunk = saveChunk; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/PortalCreateEvent.java b/api/src/main/java/org/bukkit/event/world/PortalCreateEvent.java deleted file mode 100644 index 579f01747..000000000 --- a/api/src/main/java/org/bukkit/event/world/PortalCreateEvent.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.bukkit.event.world; - -import java.util.List; -import org.bukkit.World; -import org.bukkit.block.BlockState; -import org.bukkit.entity.Entity; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 List blocks; - private final Entity entity; - private final CreateReason reason; - - @Deprecated - public PortalCreateEvent(@NotNull final List blocks, @NotNull final World world, @NotNull CreateReason reason) { - this(blocks, world, null, reason); - } - - public PortalCreateEvent(@NotNull final List blocks, @NotNull final World world, @Nullable Entity entity, @NotNull CreateReason reason) { - super(world); - - this.blocks = blocks; - this.entity = entity; - 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 - */ - @NotNull - public List getBlocks() { - return this.blocks; - } - - /** - * Returns the Entity that triggered this portal creation (if available) - * - * @return Entity involved in this event - */ - @Nullable - public Entity getEntity() { - return entity; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - /** - * Gets the reason for the portal's creation - * - * @return CreateReason for the portal's creation - */ - @NotNull - public CreateReason getReason() { - return reason; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * An enum to specify the various reasons for a portal's creation - */ - public enum CreateReason { - /** - * When the blocks inside a portal are created due to a portal frame - * being set on fire. - */ - FIRE, - /** - * When a nether portal frame and portal is created at the exit of an - * entered nether portal. - */ - NETHER_PAIR, - /** - * When the target end platform is created as a result of a player - * entering an end portal. - */ - END_PLATFORM - } -} diff --git a/api/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java b/api/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java deleted file mode 100644 index 9ce93d009..000000000 --- a/api/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final World world, @NotNull final Location previousLocation) { - super(world); - this.previousLocation = previousLocation; - } - - /** - * Gets the previous spawn location - * - * @return Location that used to be spawn - */ - @NotNull - public Location getPreviousLocation() { - return previousLocation; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/StructureGrowEvent.java b/api/src/main/java/org/bukkit/event/world/StructureGrowEvent.java deleted file mode 100644 index 7af8d6e51..000000000 --- a/api/src/main/java/org/bukkit/event/world/StructureGrowEvent.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.bukkit.event.world; - -import java.util.List; -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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull final Location location, @NotNull final TreeType species, final boolean bonemeal, @Nullable final Player player, @NotNull 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 - */ - @NotNull - public Location getLocation() { - return location; - } - - /** - * Gets the species type (birch, normal, pine, red mushroom, brown - * mushroom) - * - * @return Structure species - */ - @NotNull - 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 - */ - @Nullable - public Player getPlayer() { - return player; - } - - /** - * Gets a list of all blocks associated with the structure. - * - * @return list of all blocks associated with the structure. - */ - @NotNull - public List getBlocks() { - return blocks; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/WorldEvent.java b/api/src/main/java/org/bukkit/event/world/WorldEvent.java deleted file mode 100644 index cffeff33f..000000000 --- a/api/src/main/java/org/bukkit/event/world/WorldEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.World; -import org.bukkit.event.Event; -import org.jetbrains.annotations.NotNull; - -/** - * Represents events within a world - */ -public abstract class WorldEvent extends Event { - private final World world; - - public WorldEvent(@NotNull final World world) { - this.world = world; - } - - /** - * Gets the world primarily involved with this event - * - * @return World which caused this event - */ - @NotNull - public World getWorld() { - return world; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/WorldInitEvent.java b/api/src/main/java/org/bukkit/event/world/WorldInitEvent.java deleted file mode 100644 index 8b521deda..000000000 --- a/api/src/main/java/org/bukkit/event/world/WorldInitEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.World; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a World is initializing - */ -public class WorldInitEvent extends WorldEvent { - private static final HandlerList handlers = new HandlerList(); - - public WorldInitEvent(@NotNull final World world) { - super(world); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/WorldLoadEvent.java b/api/src/main/java/org/bukkit/event/world/WorldLoadEvent.java deleted file mode 100644 index 552e15cd4..000000000 --- a/api/src/main/java/org/bukkit/event/world/WorldLoadEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.World; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a World is loaded - */ -public class WorldLoadEvent extends WorldEvent { - private static final HandlerList handlers = new HandlerList(); - - public WorldLoadEvent(@NotNull final World world) { - super(world); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/WorldSaveEvent.java b/api/src/main/java/org/bukkit/event/world/WorldSaveEvent.java deleted file mode 100644 index 9a9bb1362..000000000 --- a/api/src/main/java/org/bukkit/event/world/WorldSaveEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.World; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * Called when a World is saved. - */ -public class WorldSaveEvent extends WorldEvent { - private static final HandlerList handlers = new HandlerList(); - - public WorldSaveEvent(@NotNull final World world) { - super(world); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java b/api/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java deleted file mode 100644 index 8eeeada87..000000000 --- a/api/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.event.world; - -import org.bukkit.World; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final World world) { - super(world); - } - - @Override - public boolean isCancelled() { - return this.isCancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.isCancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/java/org/bukkit/generator/BlockPopulator.java b/api/src/main/java/org/bukkit/generator/BlockPopulator.java deleted file mode 100644 index e5e3a6a54..000000000 --- a/api/src/main/java/org/bukkit/generator/BlockPopulator.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.generator; - -import java.util.Random; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull World world, @NotNull Random random, @NotNull Chunk source); -} diff --git a/api/src/main/java/org/bukkit/generator/ChunkGenerator.java b/api/src/main/java/org/bukkit/generator/ChunkGenerator.java deleted file mode 100644 index 3fe6a22e0..000000000 --- a/api/src/main/java/org/bukkit/generator/ChunkGenerator.java +++ /dev/null @@ -1,313 +0,0 @@ -package org.bukkit.generator; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -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.block.data.BlockData; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * A chunk generator is responsible for the initial shaping of an entire - * chunk. For example, the nether chunk generator should shape netherrack and - * soulsand. - * - * By default only one thread will call - * {@link #generateChunkData(org.bukkit.World, java.util.Random, int, int, org.bukkit.generator.ChunkGenerator.BiomeGrid)} - * at a time, although this may not necessarily be the main server thread. - * - * If your generator is capable of fully asynchronous generation, then - * {@link #isParallelCapable()} should be overriden accordingly to allow - * multiple concurrent callers. - */ -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 - */ - @NotNull - 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, @NotNull Biome bio); - } - - /** - * 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(org.bukkit.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 - */ - @NotNull - public ChunkData generateChunkData(@NotNull World world, @NotNull Random random, int x, int z, @NotNull BiomeGrid biome) { - // Paper start - More helpful custom chunk gen exceptions - final String generatorClass = world.getGenerator() != null ? world.getGenerator().getClass().getName() : "null"; - throw new UnsupportedOperationException("Custom generator is missing required method generateChunkData: " + generatorClass); - // Paper end - } - - /** - * Create a ChunkData for a world. - * @param world the world the ChunkData is for - * @return a new ChunkData for world - */ - @NotNull - protected final ChunkData createChunkData(@NotNull 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(@NotNull 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 - */ - @NotNull - public List getDefaultPopulators(@NotNull 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 - */ - @Nullable - public Location getFixedSpawnLocation(@NotNull World world, @NotNull Random random) { - return null; - } - - /** - * Gets if this ChunkGenerator is parallel capable. - * - * See {@link ChunkGenerator} for more information. - * - * @return parallel capable status - */ - public boolean isParallelCapable() { - return false; - } - - /** - * Data for a Chunk. - */ - public static interface ChunkData { - /** - * Get the maximum height for the chunk. - * - * Setting blocks at or above this height will do nothing. - * - * @return the maximum height - */ - public 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 - */ - public void setBlock(int x, int y, int z, @NotNull 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 - */ - public void setBlock(int x, int y, int z, @NotNull MaterialData 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 blockData the type to set the block to - */ - public void setBlock(int x, int y, int z, @NotNull BlockData blockData); - - /** - * 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 - */ - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, @NotNull 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 - */ - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, @NotNull 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 blockData the type to set the blocks to - */ - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, @NotNull BlockData blockData); - - /** - * 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 - */ - @NotNull - public 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 - */ - @NotNull - public MaterialData getTypeAndData(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 data of the block or the BlockData for air if x, y or z are outside the chunk's bounds - */ - @NotNull - public BlockData getBlockData(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 - public byte getData(int x, int y, int z); - } -} diff --git a/api/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java b/api/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java deleted file mode 100644 index 1d862c23d..000000000 --- a/api/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java +++ /dev/null @@ -1,79 +0,0 @@ -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.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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 - StringBuilder sb = new StringBuilder(); - - 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(); - } - - @Override - public boolean canSee(@NotNull CommandSender sender) { - if (!command.isRegistered()) { - // Unregistered commands should not show up in the help - return false; - } - - if (sender instanceof ConsoleCommandSender) { - return true; - } - - if (amendedPermission != null) { - return sender.hasPermission(amendedPermission); - } else { - return command.testPermissionSilent(sender); - } - } -} diff --git a/api/src/main/java/org/bukkit/help/HelpMap.java b/api/src/main/java/org/bukkit/help/HelpMap.java deleted file mode 100644 index 48997b5c8..000000000 --- a/api/src/main/java/org/bukkit/help/HelpMap.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.bukkit.help; - -import java.util.Collection; -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - @Nullable - public HelpTopic getHelpTopic(@NotNull String topicName); - - /** - * Returns a collection of all the registered help topics. - * - * @return All the registered help topics. - */ - @NotNull - public Collection getHelpTopics(); - - /** - * Adds a topic to the server's help index. - * - * @param topic The new help topic to add. - */ - public void addTopic(@NotNull HelpTopic topic); - - /** - * Clears out the contents of the help index. Normally called during - * server reload. - */ - public 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. - */ - public void registerHelpTopicFactory(@NotNull Class commandClass, @NotNull 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. - */ - @NotNull - public List getIgnoredPlugins(); -} diff --git a/api/src/main/java/org/bukkit/help/HelpTopic.java b/api/src/main/java/org/bukkit/help/HelpTopic.java deleted file mode 100644 index 2e2e1af50..000000000 --- a/api/src/main/java/org/bukkit/help/HelpTopic.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.bukkit.help; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 = null; - - /** - * 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(@NotNull 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(org.bukkit.command.CommandSender)} function. - * - * @param amendedPermission The permission node the server administrator - * wishes to apply to this topic. - */ - public void amendCanSee(@Nullable String amendedPermission) { - this.amendedPermission = amendedPermission; - } - - /** - * Returns the name of this help topic. - * - * @return The topic name. - */ - @NotNull - public String getName() { - return name; - } - - /** - * Returns a brief description that will be displayed in the topic index. - * - * @return A brief topic description. - */ - @NotNull - 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. - */ - @NotNull - public String getFullText(@NotNull 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(@Nullable String amendedShortText, @Nullable 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(). - */ - @NotNull - protected String applyAmendment(@NotNull String baseText, @Nullable String amendment) { - if (amendment == null) { - return baseText; - } else { - return amendment.replaceAll("", baseText); - } - } -} diff --git a/api/src/main/java/org/bukkit/help/HelpTopicComparator.java b/api/src/main/java/org/bukkit/help/HelpTopicComparator.java deleted file mode 100644 index 75bb69283..000000000 --- a/api/src/main/java/org/bukkit/help/HelpTopicComparator.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.help; - -import java.util.Comparator; -import org.jetbrains.annotations.NotNull; - -/** - * 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 final class HelpTopicComparator implements Comparator { - - // Singleton implementations - private static final TopicNameComparator tnc = new TopicNameComparator(); - @NotNull - public static TopicNameComparator topicNameComparatorInstance() { - return tnc; - } - - private static final HelpTopicComparator htc = new HelpTopicComparator(); - @NotNull - public static HelpTopicComparator helpTopicComparatorInstance() { - return htc; - } - - private HelpTopicComparator() {} - - @Override - public int compare(@NotNull HelpTopic lhs, @NotNull HelpTopic rhs) { - return tnc.compare(lhs.getName(), rhs.getName()); - } - - public static final class TopicNameComparator implements Comparator { - private TopicNameComparator(){} - - @Override - public int compare(@NotNull String lhs, @NotNull 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/api/src/main/java/org/bukkit/help/HelpTopicFactory.java b/api/src/main/java/org/bukkit/help/HelpTopicFactory.java deleted file mode 100644 index b85da3f6d..000000000 --- a/api/src/main/java/org/bukkit/help/HelpTopicFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.help; - -import org.bukkit.command.Command; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - @Nullable - public HelpTopic createTopic(@NotNull TCommand command); -} diff --git a/api/src/main/java/org/bukkit/help/IndexHelpTopic.java b/api/src/main/java/org/bukkit/help/IndexHelpTopic.java deleted file mode 100644 index 88a812d66..000000000 --- a/api/src/main/java/org/bukkit/help/IndexHelpTopic.java +++ /dev/null @@ -1,118 +0,0 @@ -package org.bukkit.help; - -import java.util.Collection; -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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull String name, @Nullable String shortText, @Nullable String permission, @NotNull Collection topics) { - this(name, shortText, permission, topics, null); - } - - public IndexHelpTopic(@NotNull String name, @Nullable String shortText, @Nullable String permission, @NotNull Collection topics, @Nullable String preamble) { - this.name = name; - this.shortText = (shortText == null) ? "" : shortText; - this.permission = permission; - this.preamble = (preamble == null) ? "" : preamble; - setTopicsCollection(topics); - } - - /** - * Sets the contents of the internal allTopics collection. - * - * @param topics The topics to set. - */ - protected void setTopicsCollection(@NotNull Collection topics) { - this.allTopics = topics; - } - - @Override - public boolean canSee(@NotNull CommandSender sender) { - if (sender instanceof ConsoleCommandSender) { - return true; - } - if (permission == null) { - return true; - } - return sender.hasPermission(permission); - } - - @Override - public void amendCanSee(@Nullable String amendedPermission) { - permission = amendedPermission; - } - - @Override - @NotNull - public String getFullText(@NotNull 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, 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. - */ - @NotNull - protected String buildPreamble(@NotNull 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. - */ - @NotNull - protected String buildIndexLine(@NotNull CommandSender sender, @NotNull 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/api/src/main/java/org/bukkit/inventory/AbstractHorseInventory.java b/api/src/main/java/org/bukkit/inventory/AbstractHorseInventory.java deleted file mode 100644 index 93c1158f8..000000000 --- a/api/src/main/java/org/bukkit/inventory/AbstractHorseInventory.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.entity.AbstractHorse; -import org.jetbrains.annotations.Nullable; - -/** - * An interface to the inventory of an {@link AbstractHorse}. - */ -public interface AbstractHorseInventory extends Inventory { - - /** - * Gets the item in the horse's saddle slot. - * - * @return the saddle item - */ - @Nullable - ItemStack getSaddle(); - - /** - * Sets the item in the horse's saddle slot. - * - * @param stack the new item - */ - void setSaddle(@Nullable ItemStack stack); -} diff --git a/api/src/main/java/org/bukkit/inventory/AnvilInventory.java b/api/src/main/java/org/bukkit/inventory/AnvilInventory.java deleted file mode 100644 index 4af562426..000000000 --- a/api/src/main/java/org/bukkit/inventory/AnvilInventory.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.Nullable; - -/** - * Interface to the inventory of an Anvil. - */ -public interface AnvilInventory extends Inventory { - - /** - * Get the name to be applied to the repaired item. An empty string denotes - * the default item name. - * - * @return the rename text - */ - @Nullable - String getRenameText(); - - /** - * Get the experience cost (in levels) to complete the current repair. - * - * @return the experience cost - */ - int getRepairCost(); - - /** - * Set the experience cost (in levels) to complete the current repair. - * - * @param levels the experience cost - */ - void setRepairCost(int levels); - - /** - * Get the maximum experience cost (in levels) to be allowed by the current - * repair. If the result of {@link #getRepairCost()} exceeds the returned - * value, the repair result will be air to due being "too expensive". - *

- * By default, this level is set to 40. Players in creative mode ignore the - * maximum repair cost. - * - * @return the maximum experience cost - */ - int getMaximumRepairCost(); - - /** - * Set the maximum experience cost (in levels) to be allowed by the current - * repair. The default value set by vanilla Minecraft is 40. - * - * @param levels the maximum experience cost - */ - void setMaximumRepairCost(int levels); -} diff --git a/api/src/main/java/org/bukkit/inventory/ArmoredHorseInventory.java b/api/src/main/java/org/bukkit/inventory/ArmoredHorseInventory.java deleted file mode 100644 index 163ffe8ff..000000000 --- a/api/src/main/java/org/bukkit/inventory/ArmoredHorseInventory.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.Nullable; - -public interface ArmoredHorseInventory extends AbstractHorseInventory { - - /** - * Gets the item in the horse's armor slot. - * - * @return the armor item - */ - @Nullable - ItemStack getArmor(); - - /** - * Sets the item in the horse's armor slot. - * - * @param stack the new item - */ - void setArmor(@Nullable ItemStack stack); -} diff --git a/api/src/main/java/org/bukkit/inventory/BeaconInventory.java b/api/src/main/java/org/bukkit/inventory/BeaconInventory.java deleted file mode 100644 index bd2289b18..000000000 --- a/api/src/main/java/org/bukkit/inventory/BeaconInventory.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.Nullable; - -/** - * 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(@Nullable ItemStack item); - - /** - * Get the item powering the beacon. - * - * @return The current item. - */ - @Nullable - ItemStack getItem(); -} diff --git a/api/src/main/java/org/bukkit/inventory/BlastingRecipe.java b/api/src/main/java/org/bukkit/inventory/BlastingRecipe.java deleted file mode 100644 index 74a025a90..000000000 --- a/api/src/main/java/org/bukkit/inventory/BlastingRecipe.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a campfire recipe. - */ -public class BlastingRecipe extends CookingRecipe { - - public BlastingRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull Material source, float experience, int cookingTime) { - super(key, result, source, experience, cookingTime); - } - - public BlastingRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull RecipeChoice input, float experience, int cookingTime) { - super(key, result, input, experience, cookingTime); - } -} diff --git a/api/src/main/java/org/bukkit/inventory/BlockInventoryHolder.java b/api/src/main/java/org/bukkit/inventory/BlockInventoryHolder.java deleted file mode 100644 index 86fbc1be4..000000000 --- a/api/src/main/java/org/bukkit/inventory/BlockInventoryHolder.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a block inventory holder - either a BlockState, or a regular - * Block. - */ -public interface BlockInventoryHolder extends InventoryHolder { - - /** - * Gets the block associated with this holder. - * - * @return the block associated with this holder - * @throws IllegalStateException if the holder is a block state and is not - * placed - */ - @NotNull - Block getBlock(); -} diff --git a/api/src/main/java/org/bukkit/inventory/BrewerInventory.java b/api/src/main/java/org/bukkit/inventory/BrewerInventory.java deleted file mode 100644 index d8a52b59e..000000000 --- a/api/src/main/java/org/bukkit/inventory/BrewerInventory.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.Material; -import org.bukkit.block.BrewingStand; -import org.jetbrains.annotations.Nullable; - -/** - * Interface to the inventory of a Brewing Stand. - */ -public interface BrewerInventory extends Inventory { - - /** - * Get the current ingredient for brewing. - * - * @return The ingredient. - */ - @Nullable - ItemStack getIngredient(); - - /** - * Set the current ingredient for brewing. - * - * @param ingredient The ingredient - */ - void setIngredient(@Nullable ItemStack ingredient); - - /** - * Get the current fuel for brewing. - * - * @return The fuel - */ - @Nullable - ItemStack getFuel(); - - /** - * Set the current fuel for brewing. Generally only - * {@link Material#BLAZE_POWDER} will be of use. - * - * @param fuel The fuel - */ - void setFuel(@Nullable ItemStack fuel); - - @Override - @Nullable - BrewingStand getHolder(); -} diff --git a/api/src/main/java/org/bukkit/inventory/CampfireRecipe.java b/api/src/main/java/org/bukkit/inventory/CampfireRecipe.java deleted file mode 100644 index a1bd3a68d..000000000 --- a/api/src/main/java/org/bukkit/inventory/CampfireRecipe.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a campfire recipe. - */ -public class CampfireRecipe extends CookingRecipe { - - public CampfireRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull Material source, float experience, int cookingTime) { - super(key, result, source, experience, cookingTime); - } - - public CampfireRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull RecipeChoice input, float experience, int cookingTime) { - super(key, result, input, experience, cookingTime); - } -} diff --git a/api/src/main/java/org/bukkit/inventory/CartographyInventory.java b/api/src/main/java/org/bukkit/inventory/CartographyInventory.java deleted file mode 100644 index 29c9b2682..000000000 --- a/api/src/main/java/org/bukkit/inventory/CartographyInventory.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.inventory; - -/** - * Interface to the inventory of a Cartography table. - */ -public interface CartographyInventory extends Inventory { } diff --git a/api/src/main/java/org/bukkit/inventory/CookingRecipe.java b/api/src/main/java/org/bukkit/inventory/CookingRecipe.java deleted file mode 100644 index 6f251252a..000000000 --- a/api/src/main/java/org/bukkit/inventory/CookingRecipe.java +++ /dev/null @@ -1,173 +0,0 @@ -package org.bukkit.inventory; - -import com.google.common.base.Preconditions; -import java.util.Collections; -import org.bukkit.Keyed; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a cooking recipe. - * @param type of recipe - */ -public abstract class CookingRecipe implements Recipe, Keyed { - private final NamespacedKey key; - private ItemStack output; - private RecipeChoice ingredient; - private float experience; - private int cookingTime; - private String group = ""; - - /** - * Create a cooking recipe to craft the specified ItemStack. - * - * @param key The unique recipe key - * @param result The item you want the recipe to create. - * @param source The input material. - * @param experience The experience given by this recipe - * @param cookingTime The cooking time (in ticks) - */ - public CookingRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull Material source, float experience, int cookingTime) { - this(key, result, new RecipeChoice.MaterialChoice(Collections.singletonList(source)), experience, cookingTime); - } - - /** - * Create a cooking recipe to craft the specified ItemStack. - * - * @param key The unique recipe key - * @param result The item you want the recipe to create. - * @param input The input choices. - * @param experience The experience given by this recipe - * @param cookingTime The cooking time (in ticks) - */ - public CookingRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull RecipeChoice input, float experience, int cookingTime) { - Preconditions.checkArgument(result.getType() != Material.AIR, "Recipe must have non-AIR result."); - this.key = key; - this.output = new ItemStack(result); - this.ingredient = input; - this.experience = experience; - this.cookingTime = cookingTime; - } - - /** - * Sets the input of this cooking recipe. - * - * @param input The input material. - * @return The changed recipe, so you can chain calls. - */ - @NotNull - public CookingRecipe setInput(@NotNull Material input) { - this.ingredient = new RecipeChoice.MaterialChoice(Collections.singletonList(input)); - return this; - } - - /** - * Get the input material. - * - * @return The input material. - */ - @NotNull - public ItemStack getInput() { - return this.ingredient.getItemStack(); - } - - /** - * Sets the input of this cooking recipe. - * - * @param input The input choice. - * @return The changed recipe, so you can chain calls. - */ - @NotNull - public T setInputChoice(@NotNull RecipeChoice input) { - this.ingredient = input; - return (T) this; - } - - /** - * Get the input choice. - * - * @return The input choice. - */ - @NotNull - public RecipeChoice getInputChoice() { - return this.ingredient.clone(); - } - - /** - * Get the result of this recipe. - * - * @return The resulting stack. - */ - @NotNull - @Override - public ItemStack getResult() { - return output.clone(); - } - - /** - * Sets the experience given by this recipe. - * - * @param experience the experience level - */ - public void setExperience(float experience) { - this.experience = experience; - } - - /** - * Get the experience given by this recipe. - * - * @return experience level - */ - public float getExperience() { - return experience; - } - - /** - * Set the cooking time for this recipe in ticks. - * - * @param cookingTime new cooking time - */ - public void setCookingTime(int cookingTime) { - Preconditions.checkArgument(cookingTime >= 0, "cookingTime must be >= 0"); - this.cookingTime = cookingTime; - } - - /** - * Get the cooking time for this recipe in ticks. - * - * @return cooking time - */ - public int getCookingTime() { - return cookingTime; - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - - /** - * Get the group of this recipe. Recipes with the same group may be grouped - * together when displayed in the client. - * - * @return recipe group. An empty string denotes no group. May not be null. - */ - @NotNull - public String getGroup() { - return group; - } - - /** - * Set the group of this recipe. Recipes with the same group may be grouped - * together when displayed in the client. - * - * @param group recipe group. An empty string denotes no group. May not be - * null. - */ - public void setGroup(@NotNull String group) { - Preconditions.checkArgument(group != null, "group"); - this.group = group; - } -} diff --git a/api/src/main/java/org/bukkit/inventory/CraftingInventory.java b/api/src/main/java/org/bukkit/inventory/CraftingInventory.java deleted file mode 100644 index df81bac9e..000000000 --- a/api/src/main/java/org/bukkit/inventory/CraftingInventory.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - @Nullable - ItemStack getResult(); - - /** - * Get the contents of the crafting matrix. - * - * @return The contents. Individual entries may be null. - */ - @NotNull - ItemStack[] getMatrix(); - - /** - * Set the item in the result slot of the crafting inventory. - * - * @param newResult The new result item. - */ - void setResult(@Nullable ItemStack newResult); - - /** - * Replace the contents of the crafting matrix - * - * @param contents The new contents. Individual entries may be null. - * @throws IllegalArgumentException if the length of contents is greater - * than the size of the crafting matrix. - */ - void setMatrix(@NotNull 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. - */ - @Nullable - Recipe getRecipe(); -} diff --git a/api/src/main/java/org/bukkit/inventory/DoubleChestInventory.java b/api/src/main/java/org/bukkit/inventory/DoubleChestInventory.java deleted file mode 100644 index 6d0067cbc..000000000 --- a/api/src/main/java/org/bukkit/inventory/DoubleChestInventory.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.block.DoubleChest; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @NotNull - Inventory getLeftSide(); - - /** - * Get the right side of this double chest. - * - * @return The right side inventory - */ - @NotNull - Inventory getRightSide(); - - @Override - @Nullable - DoubleChest getHolder(); -} diff --git a/api/src/main/java/org/bukkit/inventory/EnchantingInventory.java b/api/src/main/java/org/bukkit/inventory/EnchantingInventory.java deleted file mode 100644 index ea47af00c..000000000 --- a/api/src/main/java/org/bukkit/inventory/EnchantingInventory.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.Nullable; - -/** - * 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(@Nullable ItemStack item); - - /** - * Get the item being enchanted. - * - * @return The current item. - */ - @Nullable - ItemStack getItem(); - - /** - * Set the secondary item being used for the enchant. - * - * @param item The new item - */ - void setSecondary(@Nullable ItemStack item); - - /** - * Get the secondary item being used for the enchant. - * - * @return The second item - */ - @Nullable - ItemStack getSecondary(); -} diff --git a/api/src/main/java/org/bukkit/inventory/EntityEquipment.java b/api/src/main/java/org/bukkit/inventory/EntityEquipment.java deleted file mode 100644 index 1fd9f79de..000000000 --- a/api/src/main/java/org/bukkit/inventory/EntityEquipment.java +++ /dev/null @@ -1,334 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * An interface to a creatures inventory - */ -public interface EntityEquipment { - - /** - * Gets a copy of the item the entity is currently holding - * in their main hand. - * - * @return the currently held item - */ - @NotNull - ItemStack getItemInMainHand(); - - /** - * Sets the item the entity is holding in their main hand. - * - * @param item The item to put into the entities hand - */ - void setItemInMainHand(@Nullable ItemStack item); - - /** - * Gets a copy of the item the entity is currently holding - * in their off hand. - * - * @return the currently held item - */ - @NotNull - ItemStack getItemInOffHand(); - - /** - * Sets the item the entity is holding in their off hand. - * - * @param item The item to put into the entities hand - */ - void setItemInOffHand(@Nullable ItemStack item); - - /** - * Gets a copy of the item the entity is currently holding - * - * @deprecated entities can duel wield now use the methods for the - * specific hand instead - * @see #getItemInMainHand() - * @see #getItemInOffHand() - * @return the currently held item - */ - @Deprecated - @NotNull - ItemStack getItemInHand(); - - /** - * Sets the item the entity is holding - * - * @deprecated entities can duel wield now use the methods for the - * specific hand instead - * @see #setItemInMainHand(ItemStack) - * @see #setItemInOffHand(ItemStack) - * @param stack The item to put into the entities hand - */ - @Deprecated - void setItemInHand(@Nullable ItemStack stack); - - /** - * Gets a copy of the helmet currently being worn by the entity - * - * @return The helmet being worn - */ - @Nullable - ItemStack getHelmet(); - - /** - * Sets the helmet worn by the entity - * - * @param helmet The helmet to put on the entity - */ - void setHelmet(@Nullable ItemStack helmet); - - /** - * Gets a copy of the chest plate currently being worn by the entity - * - * @return The chest plate being worn - */ - @Nullable - ItemStack getChestplate(); - - /** - * Sets the chest plate worn by the entity - * - * @param chestplate The chest plate to put on the entity - */ - void setChestplate(@Nullable ItemStack chestplate); - - /** - * Gets a copy of the leggings currently being worn by the entity - * - * @return The leggings being worn - */ - @Nullable - ItemStack getLeggings(); - - /** - * Sets the leggings worn by the entity - * - * @param leggings The leggings to put on the entity - */ - void setLeggings(@Nullable ItemStack leggings); - - /** - * Gets a copy of the boots currently being worn by the entity - * - * @return The boots being worn - */ - @Nullable - ItemStack getBoots(); - - /** - * Sets the boots worn by the entity - * - * @param boots The boots to put on the entity - */ - void setBoots(@Nullable ItemStack boots); - - /** - * Gets a copy of all worn armor - * - * @return The array of worn armor. Individual items may be null. - */ - @NotNull - ItemStack[] getArmorContents(); - - /** - * Sets the entities armor to the provided array of ItemStacks - * - * @param items The items to set the armor as. Individual items may be null. - */ - void setArmorContents(@NotNull ItemStack[] items); - - /** - * Clears the entity of all armor and held items - */ - void clear(); - - /** - * @deprecated entities can duel wield now use the methods for the specific - * hand instead - * @see #getItemInMainHandDropChance() - * @see #getItemInOffHandDropChance() - * @return drop chance - */ - @Deprecated - float getItemInHandDropChance(); - - /** - * @deprecated entities can duel wield now use the methods for the specific - * hand instead - * @see #setItemInMainHandDropChance(float) - * @see #setItemInOffHandDropChance(float) - * @param chance drop chance - */ - @Deprecated - void setItemInHandDropChance(float chance); - - /** - * Gets the chance of the main hand item being dropped upon this creature's - * death. - * - *

    - *
  • A drop chance of 0.0F will never drop - *
  • A drop chance of 1.0F will always drop - *
- * - * @return chance of the currently held item being dropped (1 for players) - */ - float getItemInMainHandDropChance(); - - /** - * Sets the chance of the item this creature is currently holding in their - * main hand being dropped upon this creature's death. - * - *
    - *
  • A drop chance of 0.0F will never drop - *
  • A drop chance of 1.0F will always drop - *
- * - * @param chance the chance of the main hand item being dropped - * @throws UnsupportedOperationException when called on players - */ - void setItemInMainHandDropChance(float chance); - - /** - * Gets the chance of the off hand item being dropped upon this creature's - * death. - * - *
    - *
  • A drop chance of 0.0F will never drop - *
  • A drop chance of 1.0F will always drop - *
- * - * @return chance of the off hand item being dropped (1 for players) - */ - float getItemInOffHandDropChance(); - - /** - * Sets the chance of the off hand item being dropped upon this creature's - * death. - * - *
    - *
  • A drop chance of 0.0F will never drop - *
  • A drop chance of 1.0F will always drop - *
- * - * @param chance the chance of off hand item being dropped - * @throws UnsupportedOperationException when called on players - */ - void setItemInOffHandDropChance(float chance); - - /** - * Gets the chance of the helmet being dropped upon this creature's death. - * - *
    - *
  • A drop chance of 0.0F will never drop - *
  • A drop chance of 1.0F 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 0.0F will never drop - *
  • A drop chance of 1.0F 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 0.0F will never drop - *
  • A drop chance of 1.0F 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 0.0F will never drop - *
  • A drop chance of 1.0F 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 0.0F will never drop - *
  • A drop chance of 1.0F 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 0.0F will never drop - *
  • A drop chance of 1.0F 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 0.0F will never drop - *
  • A drop chance of 1.0F 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 0.0F will never drop - *
  • A drop chance of 1.0F 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 - */ - @Nullable - Entity getHolder(); -} diff --git a/api/src/main/java/org/bukkit/inventory/EquipmentSlot.java b/api/src/main/java/org/bukkit/inventory/EquipmentSlot.java deleted file mode 100644 index 1e7d77118..000000000 --- a/api/src/main/java/org/bukkit/inventory/EquipmentSlot.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bukkit.inventory; - -public enum EquipmentSlot { - - HAND, - OFF_HAND, - FEET, - LEGS, - CHEST, - HEAD -} diff --git a/api/src/main/java/org/bukkit/inventory/FurnaceInventory.java b/api/src/main/java/org/bukkit/inventory/FurnaceInventory.java deleted file mode 100644 index 3f46259c1..000000000 --- a/api/src/main/java/org/bukkit/inventory/FurnaceInventory.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.block.Furnace; -import org.jetbrains.annotations.Nullable; - -/** - * Interface to the inventory of a Furnace. - */ -public interface FurnaceInventory extends Inventory { - - /** - * Get the current item in the result slot. - * - * @return The item - */ - @Nullable - ItemStack getResult(); - - /** - * Get the current fuel. - * - * @return The item - */ - @Nullable - ItemStack getFuel(); - - /** - * Get the item currently smelting. - * - * @return The item - */ - @Nullable - ItemStack getSmelting(); - - /** - * Set the current fuel. - * - * @param stack The item - */ - void setFuel(@Nullable ItemStack stack); - - /** - * Set the current item in the result slot. - * - * @param stack The item - */ - void setResult(@Nullable ItemStack stack); - - /** - * Set the item currently smelting. - * - * @param stack The item - */ - void setSmelting(@Nullable ItemStack stack); - - @Override - @Nullable - Furnace getHolder(); -} diff --git a/api/src/main/java/org/bukkit/inventory/FurnaceRecipe.java b/api/src/main/java/org/bukkit/inventory/FurnaceRecipe.java deleted file mode 100644 index 1d442dc16..000000000 --- a/api/src/main/java/org/bukkit/inventory/FurnaceRecipe.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.bukkit.inventory; - -import java.util.Collections; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a furnace recipe. - */ -public class FurnaceRecipe extends CookingRecipe { - - @Deprecated - public FurnaceRecipe(@NotNull ItemStack result, @NotNull Material source) { - this(NamespacedKey.randomKey(), result, source, 0, 0, 200); - } - - @Deprecated - public FurnaceRecipe(@NotNull ItemStack result, @NotNull MaterialData source) { - this(NamespacedKey.randomKey(), result, source.getItemType(), source.getData(), 0, 200); - } - - @Deprecated - public FurnaceRecipe(@NotNull ItemStack result, @NotNull MaterialData source, float experience) { - this(NamespacedKey.randomKey(), result, source.getItemType(), source.getData(), experience, 200); - } - - @Deprecated - public FurnaceRecipe(@NotNull ItemStack result, @NotNull Material source, int data) { - this(NamespacedKey.randomKey(), result, source, data, 0, 200); - } - - /** - * Create a furnace recipe to craft the specified ItemStack. - * - * @param key The unique recipe key - * @param result The item you want the recipe to create. - * @param source The input material. - * @param experience The experience given by this recipe - * @param cookingTime The cooking time (in ticks) - */ - public FurnaceRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull Material source, float experience, int cookingTime) { - this(key, result, source, 0, experience, cookingTime); - } - - @Deprecated - public FurnaceRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull Material source, int data, float experience, int cookingTime) { - this(key, result, new RecipeChoice.MaterialChoice(Collections.singletonList(source)), experience, cookingTime); - } - - /** - * Create a furnace recipe to craft the specified ItemStack. - * - * @param key The unique recipe key - * @param result The item you want the recipe to create. - * @param input The input choices. - * @param experience The experience given by this recipe - * @param cookingTime The cooking time (in ticks) - */ - public FurnaceRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull RecipeChoice input, float experience, int cookingTime) { - super(key, result, input, experience, cookingTime); - } - - /** - * Sets the input of this furnace recipe. - * - * @param input The input material. - * @return The changed recipe, so you can chain calls. - */ - @NotNull - public FurnaceRecipe setInput(@NotNull MaterialData input) { - return setInput(input.getItemType(), input.getData()); - } - - @NotNull - @Override - public FurnaceRecipe setInput(@NotNull Material input) { - return (FurnaceRecipe) super.setInput(input); - } - - /** - * 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(@NotNull Material input, int data) { - return setInputChoice(new RecipeChoice.MaterialChoice(Collections.singletonList(input))); - } - - @NotNull - @Override - public FurnaceRecipe setInputChoice(@NotNull RecipeChoice input) { - return (FurnaceRecipe) super.setInputChoice(input); - } -} diff --git a/api/src/main/java/org/bukkit/inventory/GrindstoneInventory.java b/api/src/main/java/org/bukkit/inventory/GrindstoneInventory.java deleted file mode 100644 index 9048892c8..000000000 --- a/api/src/main/java/org/bukkit/inventory/GrindstoneInventory.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.inventory; - -/** - * Interface to the inventory of a Grindstone. - */ -public interface GrindstoneInventory extends Inventory { } diff --git a/api/src/main/java/org/bukkit/inventory/HorseInventory.java b/api/src/main/java/org/bukkit/inventory/HorseInventory.java deleted file mode 100644 index 53498debe..000000000 --- a/api/src/main/java/org/bukkit/inventory/HorseInventory.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.Nullable; - -/** - * An interface to the inventory of a Horse. - */ -public interface HorseInventory extends AbstractHorseInventory, ArmoredHorseInventory {} diff --git a/api/src/main/java/org/bukkit/inventory/Inventory.java b/api/src/main/java/org/bukkit/inventory/Inventory.java deleted file mode 100644 index 01fe217df..000000000 --- a/api/src/main/java/org/bukkit/inventory/Inventory.java +++ /dev/null @@ -1,403 +0,0 @@ -package org.bukkit.inventory; - -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.inventory.InventoryType; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Interface to the various inventories. Behavior relating to {@link - * Material#AIR} is unspecified. - * - *
- * Note that whilst {@link #iterator()} deals with the entire inventory, add - * / contains / remove methods deal only with the storage contents. - *
- * Consider using {@link #getContents()} and {@link #getStorageContents()} for - * specific iteration. - * - * @see #getContents() - * @see #getStorageContents() - */ -public interface Inventory extends Iterable { - - /** - * Returns the size of the inventory - * - * @return The size of the inventory - */ - public int getSize(); - - /** - * Returns the maximum stack size for an ItemStack in this inventory. - * - * @return The maximum size for an ItemStack in this inventory. - */ - public 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. - */ - public void setMaxStackSize(int size); - - /** - * 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 - */ - @Nullable - public 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 - */ - public void setItem(int index, @Nullable 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. - *

- * It is known that in some implementations this method will also set - * the inputted argument amount to the number of that item not placed in - * slots. - * - * @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 - */ - @NotNull - public HashMap addItem(@NotNull 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. - *

- * It is known that in some implementations this method will also set the - * inputted argument amount to the number of that item not removed from - * slots. - * - * @param items The ItemStacks to remove - * @return A HashMap containing items that couldn't be removed. - * @throws IllegalArgumentException if items is null - */ - @NotNull - public HashMap removeItem(@NotNull ItemStack... items) throws IllegalArgumentException; - - // Paper start - /** - * Searches all possible inventory slots in order to remove the given ItemStacks. - *

- * Similar to {@link Inventory#removeItem(ItemStack...)} in behavior, except this - * method will check all possible slots in the inventory, rather than just the main - * storage contents. - *

- * 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. - *

- * It is known that in some implementations this method will also set the - * inputted argument amount to the number of that item not removed from - * slots. - * - * @param items The ItemStacks to remove - * @return A HashMap containing items that couldn't be removed. - * @throws IllegalArgumentException if items is null - */ - @NotNull - public HashMap removeItemAnySlot(@NotNull ItemStack... items) throws IllegalArgumentException; - // Paper end - - /** - * Returns all ItemStacks from the inventory - * - * @return An array of ItemStacks from the inventory. Individual items may be null. - */ - @NotNull - public 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. - */ - public void setContents(@NotNull ItemStack[] items) throws IllegalArgumentException; - - /** - * Return the contents from the section of the inventory where items can - * reasonably be expected to be stored. In most cases this will represent - * the entire inventory, but in some cases it may exclude armor or result - * slots. - *
- * It is these contents which will be used for add / contains / remove - * methods which look for a specific stack. - * - * @return inventory storage contents. Individual items may be null. - */ - @NotNull - public ItemStack[] getStorageContents(); - - /** - * Put the given ItemStacks into the storage slots - * - * @param items The ItemStacks to use as storage contents - * @throws IllegalArgumentException If the array has more items than the - * inventory. - */ - public void setStorageContents(@NotNull ItemStack[] items) throws IllegalArgumentException; - - /** - * 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 - */ - public boolean contains(@NotNull 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 - */ - @Contract("null -> false") - public boolean contains(@Nullable ItemStack item); - - /** - * 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 - */ - public boolean contains(@NotNull 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) - */ - @Contract("null, _ -> false") - public boolean contains(@Nullable 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 - */ - @Contract("null, _ -> false") - public boolean containsAtLeast(@Nullable ItemStack item, int amount); - - /** - * 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 - */ - @NotNull - public HashMap all(@NotNull 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 - */ - @NotNull - public HashMap all(@Nullable ItemStack item); - - /** - * 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 - */ - public int first(@NotNull 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 - */ - public int first(@NotNull ItemStack item); - - /** - * Returns the first empty Slot. - * - * @return The first empty Slot found, or -1 if no empty slots. - */ - public int firstEmpty(); - - /** - * Removes all stacks in the inventory matching the given material. - * - * @param material The material to remove - * @throws IllegalArgumentException if material is null - */ - public void remove(@NotNull 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 - */ - public void remove(@NotNull ItemStack item); - - /** - * Clears out a particular slot in the index. - * - * @param index The index to empty. - */ - public void clear(int index); - - /** - * Clears out the whole Inventory. - */ - public 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. - */ - @NotNull - public List getViewers(); - - /** - * Returns what type of inventory this is. - * - * @return The InventoryType representing the type of inventory. - */ - @NotNull - public InventoryType getType(); - - /** - * Gets the block or entity belonging to the open inventory - * - * @return The holder of the inventory; null if it has no holder. - */ - @Nullable - public InventoryHolder getHolder(); - - @NotNull - @Override - public 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. - */ - @NotNull - public ListIterator iterator(int index); - - /** - * Get the location of the block or entity which corresponds to this inventory. May return null if this container - * was custom created or is a virtual / subcontainer. - * - * @return location or null if not applicable. - */ - @Nullable - public Location getLocation(); -} diff --git a/api/src/main/java/org/bukkit/inventory/InventoryHolder.java b/api/src/main/java/org/bukkit/inventory/InventoryHolder.java deleted file mode 100644 index c7b17eabf..000000000 --- a/api/src/main/java/org/bukkit/inventory/InventoryHolder.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.NotNull; - -public interface InventoryHolder { - - /** - * Get the object's inventory. - * - * @return The inventory. - */ - @NotNull - public Inventory getInventory(); -} diff --git a/api/src/main/java/org/bukkit/inventory/InventoryView.java b/api/src/main/java/org/bukkit/inventory/InventoryView.java deleted file mode 100644 index 62d79142a..000000000 --- a/api/src/main/java/org/bukkit/inventory/InventoryView.java +++ /dev/null @@ -1,447 +0,0 @@ -package org.bukkit.inventory; - -import com.google.common.base.Preconditions; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.inventory.InventoryType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 static final 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 flame in a furnace inventory. - */ - BURN_TIME(0, InventoryType.FURNACE), - /** - * How many total ticks the current fuel should last. - */ - TICKS_FOR_CURRENT_FUEL(1, InventoryType.FURNACE), - /** - * The progress of the right-pointing arrow in a furnace inventory. - */ - COOK_TIME(2, InventoryType.FURNACE), - /** - * How many total ticks the current smelting should last. - */ - TICKS_FOR_CURRENT_SMELTING(3, 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), - /** - * In an enchanting inventory, the first four bits of the player's xpSeed. - */ - ENCHANT_XP_SEED(3, InventoryType.ENCHANTING), - /** - * In an enchanting inventory, the top button's enchantment's id - */ - ENCHANT_ID1(4, InventoryType.ENCHANTING), - /** - * In an enchanting inventory, the middle button's enchantment's id - */ - ENCHANT_ID2(5, InventoryType.ENCHANTING), - /** - * In an enchanting inventory, the bottom button's enchantment's id - */ - ENCHANT_ID3(6, InventoryType.ENCHANTING), - /** - * In an enchanting inventory, the top button's level value. - */ - ENCHANT_LEVEL1(7, InventoryType.ENCHANTING), - /** - * In an enchanting inventory, the middle button's level value. - */ - ENCHANT_LEVEL2(8, InventoryType.ENCHANTING), - /** - * In an enchanting inventory, the bottom button's level value. - */ - ENCHANT_LEVEL3(9, InventoryType.ENCHANTING), - /** - * In an beacon inventory, the levels of the beacon - */ - LEVELS(0, InventoryType.BEACON), - /** - * In an beacon inventory, the primary potion effect - */ - PRIMARY_EFFECT(1, InventoryType.BEACON), - /** - * In an beacon inventory, the secondary potion effect - */ - SECONDARY_EFFECT(2, InventoryType.BEACON), - /** - * The repair's cost in xp levels - */ - REPAIR_COST(0, InventoryType.ANVIL), - /** - * The lectern's current open book page - */ - BOOK_PAGE(0, InventoryType.LECTERN); - int id; - InventoryType style; - private Property(int id, /*@NotNull*/ InventoryType appliesTo) { - this.id = id; - style = appliesTo; - } - - @NotNull - 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 - */ - @NotNull - public abstract Inventory getTopInventory(); - - /** - * Get the lower inventory involved in this transaction. - * - * @return the inventory - */ - @NotNull - public abstract Inventory getBottomInventory(); - - /** - * Get the player viewing. - * - * @return the player - */ - @NotNull - 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 - */ - @NotNull - 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, @Nullable ItemStack item) { - Inventory inventory = getInventory(slot); - if (inventory != null) { - inventory.setItem(convertSlot(slot), item); - } else if (item != null) { - 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. - */ - @Nullable - public ItemStack getItem(int slot) { - Inventory inventory = getInventory(slot); - return (inventory == null) ? null : inventory.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(@Nullable 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. - */ - @Nullable - public final ItemStack getCursor() { - return getPlayer().getItemOnCursor(); - } - - /** - * Gets the inventory corresponding to the given raw slot ID. - * - * If the slot ID is {@link #OUTSIDE} null will be returned, otherwise - * behaviour for illegal and negative slot IDs is undefined. - * - * May be used with {@link #convertSlot(int)} to directly index an - * underlying inventory. - * - * @param rawSlot The raw slot ID. - * @return corresponding inventory, or null - */ - @Nullable - public final Inventory getInventory(int rawSlot) { - // Slot may be -1 if not properly detected due to client bug - // e.g. dropping an item into part of the enchantment list section of an enchanting table - if (rawSlot == OUTSIDE || rawSlot == -1) { - return null; - } - Preconditions.checkArgument(rawSlot >= 0, "Negative, non outside slot %s", rawSlot); - Preconditions.checkArgument(rawSlot < countSlots(), "Slot %s greater than inventory slot count", rawSlot); - - if (rawSlot < getTopInventory().getSize()) { - return getTopInventory(); - } else { - return getBottomInventory(); - } - } - - /** - * 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(); - // Index from the top inventory as having slots from [0,size] - if (rawSlot < numInTop) { - return rawSlot; - } - - // Move down the slot index by the top size - int slot = rawSlot - numInTop; - - // Player crafting slots are indexed differently. The matrix is caught by the first return. - // Creative mode is the same, except that you can't see the crafting slots (but the IDs are still used) - if (getType() == InventoryType.CRAFTING || getType() == InventoryType.CREATIVE) { - /** - * Raw Slots: - * - * 5 1 2 0 - * 6 3 4 - * 7 - * 8 45 - * 9 10 11 12 13 14 15 16 17 - * 18 19 20 21 22 23 24 25 26 - * 27 28 29 30 31 32 33 34 35 - * 36 37 38 39 40 41 42 43 44 - */ - - /** - * Converted Slots: - * - * 39 1 2 0 - * 38 3 4 - * 37 - * 36 40 - * 9 10 11 12 13 14 15 16 17 - * 18 19 20 21 22 23 24 25 26 - * 27 28 29 30 31 32 33 34 35 - * 0 1 2 3 4 5 6 7 8 - */ - - if (slot < 4) { - // Send [5,8] to [39,36] - return 39 - slot; - } else if (slot > 39) { - // Slot lives in the extra slot section - return slot; - } else { - // Reset index so 9 -> 0 - slot -= 4; - } - } - - // 27 = 36 - 9 - if (slot >= 27) { - // Put into hotbar section - slot -= 27; - } else { - // Take out of hotbar section - // 9 = 36 - 27 - slot += 9; - } - - return slot; - } - - /** - * Determine the type of the slot by its raw slot ID. - *

- * If the type of the slot is unknown, then - * {@link InventoryType.SlotType#CONTAINER} will be returned. - * - * @param slot The raw slot ID - * @return the slot type - */ - @NotNull - public final InventoryType.SlotType getSlotType(int slot) { - InventoryType.SlotType type = InventoryType.SlotType.CONTAINER; - if (slot >= 0 && slot < this.getTopInventory().getSize()) { - switch(this.getType()) { - case BLAST_FURNACE: - case FURNACE: - case SMOKER: - if (slot == 2) { - type = InventoryType.SlotType.RESULT; - } else if(slot == 1) { - type = InventoryType.SlotType.FUEL; - } else { - type = InventoryType.SlotType.CRAFTING; - } - break; - case BREWING: - if (slot == 3) { - type = InventoryType.SlotType.FUEL; - } else { - type = InventoryType.SlotType.CRAFTING; - } - break; - case ENCHANTING: - type = InventoryType.SlotType.CRAFTING; - break; - case WORKBENCH: - case CRAFTING: - if (slot == 0) { - type = InventoryType.SlotType.RESULT; - } else { - type = InventoryType.SlotType.CRAFTING; - } - break; - case BEACON: - type = InventoryType.SlotType.CRAFTING; - break; - case ANVIL: - case CARTOGRAPHY: - case GRINDSTONE: - case MERCHANT: - if (slot == 2) { - type = InventoryType.SlotType.RESULT; - } else { - type = InventoryType.SlotType.CRAFTING; - } - break; - case STONECUTTER: - if (slot == 1) { - type = InventoryType.SlotType.RESULT; - } else { - type = InventoryType.SlotType.CRAFTING; - } - break; - case LOOM: - if (slot == 3) { - type = InventoryType.SlotType.RESULT; - } else { - type = InventoryType.SlotType.CRAFTING; - } - break; - default: - // Nothing to do, it's a CONTAINER slot - } - } else { - if (slot < 0) { - type = InventoryType.SlotType.OUTSIDE; - } else if (this.getType() == InventoryType.CRAFTING) { // Also includes creative inventory - if (slot < 9) { - type = InventoryType.SlotType.ARMOR; - } else if (slot > 35) { - type = InventoryType.SlotType.QUICKBAR; - } - } else if (slot >= (this.countSlots() - (9 + 4 + 1))) { // Quickbar, Armor, Offhand - type = InventoryType.SlotType.QUICKBAR; - } - } - return type; - } - - /** - * 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(@NotNull Property prop, int value) { - return getPlayer().setWindowProperty(prop, value); - } - - /** - * Get the title of this inventory window. - * - * @return The title. - */ - @NotNull - public abstract String getTitle(); -} diff --git a/api/src/main/java/org/bukkit/inventory/ItemFactory.java b/api/src/main/java/org/bukkit/inventory/ItemFactory.java deleted file mode 100644 index 03ba22659..000000000 --- a/api/src/main/java/org/bukkit/inventory/ItemFactory.java +++ /dev/null @@ -1,169 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.UndefinedNullability; -import org.bukkit.inventory.meta.BookMeta; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.SkullMeta; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @UndefinedNullability // Paper - ItemMeta getItemMeta(@NotNull 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(@Nullable final ItemMeta meta, @Nullable 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(@Nullable final ItemMeta meta, @Nullable 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(@Nullable final ItemMeta meta1, @Nullable 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 - */ - @Nullable - ItemMeta asMetaFor(@NotNull final ItemMeta meta, @NotNull 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 - */ - @Nullable - ItemMeta asMetaFor(@NotNull final ItemMeta meta, @NotNull final Material material) throws IllegalArgumentException; - - /** - * Returns the default color for all leather armor. - * - * @return the default color for leather armor - */ - @NotNull - Color getDefaultLeatherColor(); - - /** - * Apply a material change for an item meta. Do not use under any - * circumstances. - * - * @param meta meta - * @param material material - * @return updated material - * @throws IllegalArgumentException if bad material or data - * @deprecated for internal use only - */ - @Deprecated - @NotNull - Material updateMaterial(@NotNull final ItemMeta meta, @NotNull final Material material) throws IllegalArgumentException; - // Paper start - /** - * Minecart updates are converting simple item stacks into more complex NBT oriented Item Stacks. - * - * Use this method to to ensure any desired data conversions are processed. - * The input itemstack will not be the same as the returned itemstack. - * - * @param item The item to process conversions on - * @return A potentially Data Converted ItemStack - */ - @NotNull - ItemStack ensureServerConversions(@NotNull ItemStack item); - - /** - * Gets the Display name as seen in the Client. - * Currently the server only supports the English language. To override this, - * You must replace the language file embedded in the server jar. - * - * @param item Item to return Display name of - * @return Display name of Item - */ - @Nullable - String getI18NDisplayName(@Nullable ItemStack item); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/inventory/ItemFlag.java b/api/src/main/java/org/bukkit/inventory/ItemFlag.java deleted file mode 100644 index 2a8af7ba8..000000000 --- a/api/src/main/java/org/bukkit/inventory/ItemFlag.java +++ /dev/null @@ -1,32 +0,0 @@ -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/api/src/main/java/org/bukkit/inventory/ItemStack.java b/api/src/main/java/org/bukkit/inventory/ItemStack.java deleted file mode 100644 index 495161f62..000000000 --- a/api/src/main/java/org/bukkit/inventory/ItemStack.java +++ /dev/null @@ -1,753 +0,0 @@ -package org.bukkit.inventory; - -import com.google.common.collect.ImmutableMap; -import java.util.LinkedHashMap; -import java.util.List; // Paper -import java.util.Map; -import java.util.Set; // Paper -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.UndefinedNullability; -import org.bukkit.Utility; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a stack of item - */ -public class ItemStack implements Cloneable, ConfigurationSerializable { - private Material type = Material.AIR; - private int amount = 0; - private MaterialData data = null; - private ItemMeta meta; - - @Utility - protected ItemStack() {} - - /** - * Defaults stack size to 1, with no extra data - * - * @param type item material - */ - public ItemStack(@NotNull final Material type) { - this(type, 1); - } - - /** - * An item stack with no extra data - * - * @param type item material - * @param amount stack size - */ - public ItemStack(@NotNull final Material type, final int amount) { - this(type, amount, (short) 0); - } - - /** - * An item stack with the specified damage / durability - * - * @param type item material - * @param amount stack size - * @param damage durability / damage - * @deprecated see {@link #setDurability(short)} - */ - public ItemStack(@NotNull final Material type, final int amount, final short damage) { - this(type, amount, damage, null); - } - - /** - * @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(@NotNull final Material type, final int amount, final short damage, @Nullable final Byte data) { - Validate.notNull(type, "Material cannot be null"); - this.type = type; - this.amount = amount; - if (damage != 0) { - setDurability(damage); - } - if (data != null) { - createData(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(@NotNull final ItemStack stack) throws IllegalArgumentException { - Validate.notNull(stack, "Cannot copy null stack"); - this.type = stack.getType(); - this.amount = stack.getAmount(); - this.data = stack.getData(); - if (stack.hasItemMeta()) { - setItemMeta0(stack.getItemMeta(), type); - } - } - - /** - * Gets the type of this item - * - * @return Type of the items in this stack - */ - @Utility - @NotNull - public Material getType() { - return type; - } - - /** - * 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(@NotNull Material type) { - Validate.notNull(type, "Material cannot be null"); - this.type = type; - if (this.meta != null) { - this.meta = Bukkit.getItemFactory().asMetaFor(meta, type); - } - if (type.isLegacy()) { - createData((byte) 0); - } else { - this.data = null; - } - } - - /** - * Gets the amount of items in this stack - * - * @return Amount of items in this stack - */ - 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 - */ - @Nullable - public MaterialData getData() { - Material mat = Bukkit.getUnsafe().toLegacy(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(@Nullable MaterialData data) { - Material mat = Bukkit.getUnsafe().toLegacy(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 - * @deprecated durability is now part of ItemMeta. To avoid confusion and - * misuse, {@link #getItemMeta()}, {@link #setItemMeta(ItemMeta)} and - * {@link Damageable#setDamage(int)} should be used instead. This is because - * any call to this method will be overwritten by subsequent setting of - * ItemMeta which was created before this call. - */ - @Deprecated - public void setDurability(final short durability) { - ItemMeta meta = getItemMeta(); - if (meta != null) { - ((Damageable) meta).setDamage(durability); - setItemMeta(meta); - } - } - - /** - * Gets the durability of this item - * - * @return Durability of this item - * @deprecated see {@link #setDurability(short)} - */ - @Deprecated - public short getDurability() { - ItemMeta meta = getItemMeta(); - return (meta == null) ? 0 : (short) ((Damageable) meta).getDamage(); - } - - /** - * 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) { - this.data = type.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(@Nullable ItemStack stack) { - if (stack == null) { - return false; - } - if (stack == this) { - return true; - } - Material comparisonType = (this.type.isLegacy()) ? Bukkit.getUnsafe().fromLegacy(this.getData(), true) : this.type; // This may be called from legacy item stacks, try to get the right material - return comparisonType == stack.getType() && getDurability() == stack.getDurability() && hasItemMeta() == stack.hasItemMeta() && (hasItemMeta() ? Bukkit.getItemFactory().equals(getItemMeta(), stack.getItemMeta()) : true); - } - - @NotNull - @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 int hashCode() { - int hash = 1; - - hash = hash * 31 + getType().hashCode(); - 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(@NotNull 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(@NotNull 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. - */ - @NotNull - 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(org.bukkit.enchantments.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(@NotNull 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(@NotNull 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(org.bukkit.enchantments.Enchantment, int)} for - * each element of the map. - * - * @param enchantments Enchantments to add - */ - @Utility - public void addUnsafeEnchantments(@NotNull 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(@NotNull Enchantment ench, int level) { - ItemMeta itemMeta = (meta == null ? meta = Bukkit.getItemFactory().getItemMeta(type) : meta); - if (itemMeta != null) { - itemMeta.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(@NotNull Enchantment ench) { - int level = getEnchantmentLevel(ench); - if (level == 0 || meta == null) { - return level; - } - meta.removeEnchant(ench); - return level; - } - - @Override - @NotNull - @Utility - public Map serialize() { - Map result = new LinkedHashMap(); - - result.put("v", Bukkit.getUnsafe().getDataVersion()); // Include version to indicate we are using modern material names (or LEGACY prefix) - result.put("type", getType().name()); - - 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 - */ - @NotNull - public static ItemStack deserialize(@NotNull Map args) { - int version = (args.containsKey("v")) ? ((Number) args.get("v")).intValue() : -1; - short damage = 0; - int amount = 1; - - if (args.containsKey("damage")) { - damage = ((Number) args.get("damage")).shortValue(); - } - - Material type; - if (version < 0) { - type = Material.getMaterial(Material.LEGACY_PREFIX + (String) args.get("type")); - - byte dataVal = (type != null && type.getMaxDurability() == 0) ? (byte) damage : 0; // Actually durable items get a 0 passed into conversion - type = Bukkit.getUnsafe().fromLegacy(new MaterialData(type, dataVal), true); - - // We've converted now so the data val isn't a thing and can be reset - if (dataVal != 0) { - damage = 0; - } - } else { - type = Bukkit.getUnsafe().getMaterial((String) args.get("type"), version); - } - - 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) { - ((ItemMeta) raw).setVersion(version); - result.setItemMeta((ItemMeta) raw); - } - } - - if (version < 0) { - // Set damage again incase meta overwrote it - if (args.containsKey("damage")) { - result.setDurability(damage); - } - } - - return result.ensureServerConversions(); // Paper - } - - /** - * Get a copy of this ItemStack's {@link ItemMeta}. - * - * @return a copy of the current ItemStack's ItemData - */ - @UndefinedNullability // Paper - public ItemMeta getItemMeta() { - return this.meta == null ? Bukkit.getItemFactory().getItemMeta(this.type) : 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(@Nullable ItemMeta itemMeta) { - return setItemMeta0(itemMeta, type); - } - - /* - * Cannot be overridden, so it's safe for constructor call - */ - private boolean setItemMeta0(@Nullable ItemMeta itemMeta, @NotNull 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); - - Material newType = Bukkit.getItemFactory().updateMaterial(meta, material); - if (this.type != newType) { - this.type = newType; - } - - if (this.meta == itemMeta) { - this.meta = itemMeta.clone(); - } - - return true; - } - - // Paper start - /** - * Minecart updates are converting simple item stacks into more complex NBT oriented Item Stacks. - * - * Use this method to to ensure any desired data conversions are processed. - * The input itemstack will not be the same as the returned itemstack. - * - * @return A potentially Data Converted ItemStack - */ - @NotNull - public ItemStack ensureServerConversions() { - return Bukkit.getServer().getItemFactory().ensureServerConversions(this); - } - - /** - * Gets the Display name as seen in the Client. - * Currently the server only supports the English language. To override this, - * You must replace the language file embedded in the server jar. - * - * @return Display name of Item - */ - @Nullable - public String getI18NDisplayName() { - return Bukkit.getServer().getItemFactory().getI18NDisplayName(this); - } - - public int getMaxItemUseDuration() { - if (type == null || type == Material.AIR || !type.isItem()) { - return 0; - } - // Requires access to NMS - return ensureServerConversions().getMaxItemUseDuration(); - } - - /** - * Clones the itemstack and returns it a single quantity. - * @return The new itemstack with 1 quantity - */ - @NotNull - public ItemStack asOne() { - return asQuantity(1); - } - - /** - * Clones the itemstack and returns it as the specified quantity - * @param qty The quantity of the cloned item - * @return The new itemstack with specified quantity - */ - @NotNull - public ItemStack asQuantity(int qty) { - ItemStack clone = clone(); - clone.setAmount(qty); - return clone; - } - - /** - * Adds 1 to this itemstack. Will not go over the items max stack size. - * @return The same item (not a clone) - */ - @NotNull - public ItemStack add() { - return add(1); - } - - /** - * Adds quantity to this itemstack. Will not go over the items max stack size. - * - * @param qty The amount to add - * @return The same item (not a clone) - */ - @NotNull - public ItemStack add(int qty) { - setAmount(Math.min(getMaxStackSize(), getAmount() + qty)); - return this; - } - - /** - * Subtracts 1 to this itemstack. Going to 0 or less will invalidate the item. - * @return The same item (not a clone) - */ - @NotNull - public ItemStack subtract() { - return subtract(1); - } - - /** - * Subtracts quantity to this itemstack. Going to 0 or less will invalidate the item. - * - * @param qty The amount to add - * @return The same item (not a clone) - */ - @NotNull - public ItemStack subtract(int qty) { - setAmount(Math.max(0, getAmount() - qty)); - return this; - } - - /** - * If the item has lore, returns it, else it will return null - * @return The lore, or null - */ - @Nullable - public List getLore() { - if (!hasItemMeta()) { - return null; - } - ItemMeta itemMeta = getItemMeta(); - if (!itemMeta.hasLore()) { - return null; - } - return itemMeta.getLore(); - } - - /** - * Sets the lore for this item. - * Removes lore when given null. - * - * @param lore the lore that will be set - */ - public void setLore(@Nullable List lore) { - ItemMeta itemMeta = getItemMeta(); - itemMeta.setLore(lore); - setItemMeta(itemMeta); - } - - /** - * 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 - */ - public void addItemFlags(@NotNull ItemFlag... itemFlags) { - ItemMeta itemMeta = getItemMeta(); - itemMeta.addItemFlags(itemFlags); - setItemMeta(itemMeta); - } - - /** - * 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 - */ - public void removeItemFlags(@NotNull ItemFlag... itemFlags) { - ItemMeta itemMeta = getItemMeta(); - itemMeta.removeItemFlags(itemFlags); - setItemMeta(itemMeta); - } - - /** - * Get current set itemFlags. The collection returned is unmodifiable. - * - * @return A set of all itemFlags set - */ - @NotNull - public Set getItemFlags() { - ItemMeta itemMeta = getItemMeta(); - return itemMeta.getItemFlags(); - } - - /** - * Check if the specified flag is present on this item. - * - * @param flag the flag to check - * @return if it is present - */ - public boolean hasItemFlag(@NotNull ItemFlag flag) { - ItemMeta itemMeta = getItemMeta(); - return itemMeta.hasItemFlag(flag); - } - // Paper end -} diff --git a/api/src/main/java/org/bukkit/inventory/LecternInventory.java b/api/src/main/java/org/bukkit/inventory/LecternInventory.java deleted file mode 100644 index 4a0c43acc..000000000 --- a/api/src/main/java/org/bukkit/inventory/LecternInventory.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.block.Lectern; -import org.jetbrains.annotations.Nullable; - -/** - * Interface to the inventory of a Lectern. - */ -public interface LecternInventory extends Inventory { - - @Nullable - @Override - public Lectern getHolder(); -} diff --git a/api/src/main/java/org/bukkit/inventory/LlamaInventory.java b/api/src/main/java/org/bukkit/inventory/LlamaInventory.java deleted file mode 100644 index 5ac1afb8a..000000000 --- a/api/src/main/java/org/bukkit/inventory/LlamaInventory.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.entity.Llama; -import org.jetbrains.annotations.Nullable; - -/** - * An interface to the inventory of a {@link Llama}. - */ -public interface LlamaInventory extends SaddledHorseInventory { - - /** - * Gets the item in the llama's decor slot. - * - * @return the decor item - */ - @Nullable - ItemStack getDecor(); - - /** - * Sets the item in the llama's decor slot. - * - * @param stack the new item - */ - void setDecor(@Nullable ItemStack stack); -} diff --git a/api/src/main/java/org/bukkit/inventory/LoomInventory.java b/api/src/main/java/org/bukkit/inventory/LoomInventory.java deleted file mode 100644 index 9801b59e2..000000000 --- a/api/src/main/java/org/bukkit/inventory/LoomInventory.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.inventory; - -/** - * Interface to the inventory of a Loom. - */ -public interface LoomInventory extends Inventory { } diff --git a/api/src/main/java/org/bukkit/inventory/MainHand.java b/api/src/main/java/org/bukkit/inventory/MainHand.java deleted file mode 100644 index 75f12f156..000000000 --- a/api/src/main/java/org/bukkit/inventory/MainHand.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.bukkit.inventory; - -/** - * Represents the chosen main hand of a player - */ -public enum MainHand { - LEFT, - RIGHT -} diff --git a/api/src/main/java/org/bukkit/inventory/Merchant.java b/api/src/main/java/org/bukkit/inventory/Merchant.java deleted file mode 100644 index 9861bcedd..000000000 --- a/api/src/main/java/org/bukkit/inventory/Merchant.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit.inventory; - -import java.util.List; -import org.bukkit.entity.HumanEntity; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a merchant. A merchant is a special type of inventory which can - * facilitate custom trades between items. - */ -public interface Merchant { - - /** - * Get a list of trades currently available from this merchant. - * - * @return an immutable list of trades - */ - @NotNull - List getRecipes(); - - /** - * Set the list of trades currently available from this merchant. - *
- * This will not change the selected trades of players currently trading - * with this merchant. - * - * @param recipes a list of recipes - */ - void setRecipes(@NotNull List recipes); - - /** - * Get the recipe at a certain index of this merchant's trade list. - * - * @param i the index - * @return the recipe - * @throws IndexOutOfBoundsException if recipe index out of bounds - */ - @NotNull - MerchantRecipe getRecipe(int i) throws IndexOutOfBoundsException; - - /** - * Set the recipe at a certain index of this merchant's trade list. - * - * @param i the index - * @param recipe the recipe - * @throws IndexOutOfBoundsException if recipe index out of bounds - */ - void setRecipe(int i, @NotNull MerchantRecipe recipe) throws IndexOutOfBoundsException; - - /** - * Get the number of trades this merchant currently has available. - * - * @return the recipe count - */ - int getRecipeCount(); - - /** - * Gets whether this merchant is currently trading. - * - * @return whether the merchant is trading - */ - boolean isTrading(); - - /** - * Gets the player this merchant is trading with, or null if it is not - * currently trading. - * - * @return the trader, or null - */ - @Nullable - HumanEntity getTrader(); -} diff --git a/api/src/main/java/org/bukkit/inventory/MerchantInventory.java b/api/src/main/java/org/bukkit/inventory/MerchantInventory.java deleted file mode 100644 index 808635602..000000000 --- a/api/src/main/java/org/bukkit/inventory/MerchantInventory.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a trading inventory between a player and a merchant. - *
- * The holder of this Inventory is the owning Villager, or null if the player is - * trading with a merchant created by a plugin. - */ -public interface MerchantInventory extends Inventory { - - /** - * Get the index of the currently selected recipe. - * - * @return the index of the currently selected recipe - */ - int getSelectedRecipeIndex(); - - /** - * Get the currently active recipe. - *

- * This will be null if the items provided by the player do - * not match the ingredients of the selected recipe. This does not - * necessarily match the recipe selected by the player: If the player has - * selected the first recipe, the merchant will search all of its offers - * for a matching recipe to activate. - * - * @return the currently active recipe - */ - @Nullable - MerchantRecipe getSelectedRecipe(); - - /** - * Gets the Merchant associated with this inventory. - * - * @return merchant - */ - @NotNull - Merchant getMerchant(); -} diff --git a/api/src/main/java/org/bukkit/inventory/MerchantRecipe.java b/api/src/main/java/org/bukkit/inventory/MerchantRecipe.java deleted file mode 100644 index 1fb4a1c53..000000000 --- a/api/src/main/java/org/bukkit/inventory/MerchantRecipe.java +++ /dev/null @@ -1,175 +0,0 @@ -package org.bukkit.inventory; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.List; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a merchant's trade. - * - * Trades can take one or two ingredients, and provide one result. The - * ingredients' ItemStack amounts are respected in the trade. - *
- * A trade has a limited number of uses, after which the trade can no longer be - * used, unless the player uses a different trade, which will cause its maximum - * uses to increase. - *
- * A trade may or may not reward experience for being completed. - * - * @see org.bukkit.event.entity.VillagerReplenishTradeEvent - */ -public class MerchantRecipe implements Recipe { - - private ItemStack result; - private List ingredients = new ArrayList(); - private int uses; - private int maxUses; - private boolean experienceReward; - private int villagerExperience; - private float priceMultiplier; - - public MerchantRecipe(@NotNull ItemStack result, int maxUses) { - this(result, 0, maxUses, false); - } - - public MerchantRecipe(@NotNull ItemStack result, int uses, int maxUses, boolean experienceReward) { - this(result, uses, maxUses, experienceReward, 0, 0.0F); - } - - public MerchantRecipe(@NotNull ItemStack result, int uses, int maxUses, boolean experienceReward, int villagerExperience, float priceMultiplier) { - this.result = result; - this.uses = uses; - this.maxUses = maxUses; - this.experienceReward = experienceReward; - this.villagerExperience = villagerExperience; - this.priceMultiplier = priceMultiplier; - } - - @NotNull - @Override - public ItemStack getResult() { - return result; - } - - public void addIngredient(@NotNull ItemStack item) { - Preconditions.checkState(ingredients.size() < 2, "MerchantRecipe can only have maximum 2 ingredients"); - ingredients.add(item.clone()); - } - - public void removeIngredient(int index) { - ingredients.remove(index); - } - - public void setIngredients(@NotNull List ingredients) { - Preconditions.checkState(ingredients.size() <= 2, "MerchantRecipe can only have maximum 2 ingredients"); - this.ingredients = new ArrayList(); - for (ItemStack item : ingredients) { - this.ingredients.add(item.clone()); - } - } - - @NotNull - public List getIngredients() { - List copy = new ArrayList(); - for (ItemStack item : ingredients) { - copy.add(item.clone()); - } - return copy; - } - - /** - * Get the number of times this trade has been used. - * - * @return the number of uses - */ - public int getUses() { - return uses; - } - - /** - * Set the number of times this trade has been used. - * - * @param uses the number of uses - */ - public void setUses(int uses) { - this.uses = uses; - } - - /** - * Get the maximum number of uses this trade has. - *
- * The maximum uses of this trade may increase when a player trades with the - * owning merchant. - * - * @return the maximum number of uses - */ - public int getMaxUses() { - return maxUses; - } - - /** - * Set the maximum number of uses this trade has. - * - * @param maxUses the maximum number of time this trade can be used - */ - public void setMaxUses(int maxUses) { - this.maxUses = maxUses; - } - - /** - * Whether to reward experience to the player for the trade. - * - * @return whether to reward experience to the player for completing this - * trade - */ - public boolean hasExperienceReward() { - return experienceReward; - } - - /** - * Set whether to reward experience to the player for the trade. - * - * @param flag whether to reward experience to the player for completing - * this trade - */ - public void setExperienceReward(boolean flag) { - this.experienceReward = flag; - } - - /** - * Gets the amount of experience the villager earns from this trade. - * - * @return villager experience - */ - public int getVillagerExperience() { - return villagerExperience; - } - - /** - * Sets the amount of experience the villager earns from this trade. - * - * @param villagerExperience new experience amount - */ - public void setVillagerExperience(int villagerExperience) { - this.villagerExperience = villagerExperience; - } - - /** - * Gets the additive price multiplier for the cost of this trade. - * - * @return price multiplier - */ - public float getPriceMultiplier() { - return priceMultiplier; - } - - /** - * Sets the additive price multiplier for the cost of this trade. - * - * @param priceMultiplier new price multiplier - */ - public void setPriceMultiplier(float priceMultiplier) { - this.priceMultiplier = priceMultiplier; - } -} diff --git a/api/src/main/java/org/bukkit/inventory/PlayerInventory.java b/api/src/main/java/org/bukkit/inventory/PlayerInventory.java deleted file mode 100644 index 96916ec95..000000000 --- a/api/src/main/java/org/bukkit/inventory/PlayerInventory.java +++ /dev/null @@ -1,237 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.entity.HumanEntity; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Interface to the inventory of a Player, including the four armor slots and any extra slots. - */ -public interface PlayerInventory extends Inventory { - - /** - * Get all ItemStacks from the armor slots - * - * @return All the ItemStacks from the armor slots. Individual items can be null. - */ - @NotNull - public ItemStack[] getArmorContents(); - - /** - * Get all additional ItemStacks stored in this inventory. - *
- * NB: What defines an extra slot is up to the implementation, however it - * will not be contained within {@link #getStorageContents()} or - * {@link #getArmorContents()} - * - * @return All additional ItemStacks. Individual items can be null. - */ - @NotNull - public ItemStack[] getExtraContents(); - - /** - * Return the ItemStack from the helmet slot - * - * @return The ItemStack in the helmet slot - */ - @Nullable - public ItemStack getHelmet(); - - /** - * Return the ItemStack from the chestplate slot - * - * @return The ItemStack in the chestplate slot - */ - @Nullable - public ItemStack getChestplate(); - - /** - * Return the ItemStack from the leg slot - * - * @return The ItemStack in the leg slot - */ - @Nullable - public ItemStack getLeggings(); - - /** - * Return the ItemStack from the boots slot - * - * @return The ItemStack in the boots slot - */ - @Nullable - public 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. - *

- * Index 40 refers to the off hand (shield) item slot. Though you can set off hand with this method using this index, - * you are encouraged to use the provided method for this slot. - *

- * If you attempt to use this method with an index less than 0 or greater than 40, 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 > 40 - * @see #setBoots(ItemStack) - * @see #setChestplate(ItemStack) - * @see #setHelmet(ItemStack) - * @see #setLeggings(ItemStack) - * @see #setItemInOffHand(ItemStack) - */ - @Override - public void setItem(int index, @Nullable ItemStack item); - - /** - * Put the given ItemStacks into the armor slots - * - * @param items The ItemStacks to use as armour - */ - public void setArmorContents(@Nullable ItemStack[] items); - - /** - * Put the given ItemStacks into the extra slots - *
- * See {@link #getExtraContents()} for an explanation of extra slots. - * - * @param items The ItemStacks to use as extra - */ - public void setExtraContents(@Nullable 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 - */ - public void setHelmet(@Nullable 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 - */ - public void setChestplate(@Nullable 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 - */ - public void setLeggings(@Nullable 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 - */ - public void setBoots(@Nullable ItemStack boots); - - /** - * Gets a copy of the item the player is currently holding - * in their main hand. - * - * @return the currently held item - */ - @NotNull - ItemStack getItemInMainHand(); - - /** - * Sets the item the player is holding in their main hand. - * - * @param item The item to put into the player's hand - */ - void setItemInMainHand(@Nullable ItemStack item); - - /** - * Gets a copy of the item the player is currently holding - * in their off hand. - * - * @return the currently held item - */ - @NotNull - ItemStack getItemInOffHand(); - - /** - * Sets the item the player is holding in their off hand. - * - * @param item The item to put into the player's hand - */ - void setItemInOffHand(@Nullable ItemStack item); - - /** - * Gets a copy of the item the player is currently holding - * - * @deprecated players can duel wield now use the methods for the - * specific hand instead - * @see #getItemInMainHand() - * @see #getItemInOffHand() - * @return the currently held item - */ - @Deprecated - @NotNull - public ItemStack getItemInHand(); - - /** - * Sets the item the player is holding - * - * @deprecated players can duel wield now use the methods for the - * specific hand instead - * @see #setItemInMainHand(ItemStack) - * @see #setItemInOffHand(ItemStack) - * @param stack The item to put into the player's hand - */ - @Deprecated - public void setItemInHand(@Nullable ItemStack stack); - - /** - * Get the slot number of the currently held item - * - * @return Held item slot number - */ - public 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 - */ - public void setHeldItemSlot(int slot); - - @Override - @Nullable - public HumanEntity getHolder(); - - // Paper start - /** - * Gets the {@link ItemStack} found in the slot. - * - * @param slot The slot - * @return The item stack in the slot - */ - @Nullable - ItemStack getItem(@NotNull EquipmentSlot slot); - - /** - * Sets the {@link ItemStack} at the given {@link EquipmentSlot}. - * - * @param slot The slot for the stack - * @param stack The item stack to set - */ - void setItem(@NotNull EquipmentSlot slot, @Nullable ItemStack stack); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/inventory/Recipe.java b/api/src/main/java/org/bukkit/inventory/Recipe.java deleted file mode 100644 index 4927a7ddc..000000000 --- a/api/src/main/java/org/bukkit/inventory/Recipe.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.inventory; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents some type of crafting recipe. - */ -public interface Recipe { - - /** - * Get the result of this recipe. - * - * @return The result stack - */ - @NotNull - ItemStack getResult(); -} diff --git a/api/src/main/java/org/bukkit/inventory/RecipeChoice.java b/api/src/main/java/org/bukkit/inventory/RecipeChoice.java deleted file mode 100644 index 3d325cab6..000000000 --- a/api/src/main/java/org/bukkit/inventory/RecipeChoice.java +++ /dev/null @@ -1,241 +0,0 @@ -package org.bukkit.inventory; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; -import org.bukkit.Material; -import org.bukkit.Tag; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a potential item match within a recipe. All choices within a - * recipe must be satisfied for it to be craftable. - * - * This class is not legal for implementation by plugins! - */ -public interface RecipeChoice extends Predicate, Cloneable { - - /** - * Gets a single item stack representative of this stack choice. - * - * @return a single representative item - * @deprecated for compatability only - */ - @Deprecated - @NotNull - ItemStack getItemStack(); - - @NotNull - RecipeChoice clone(); - - @Override - boolean test(@NotNull ItemStack itemStack); - - /** - * Represents a choice of multiple matching Materials. - */ - public static class MaterialChoice implements RecipeChoice { - - private List choices; - - public MaterialChoice(@NotNull Material choice) { - this(Arrays.asList(choice)); - } - - public MaterialChoice(@NotNull Material... choices) { - this(Arrays.asList(choices)); - } - - /** - * Constructs a MaterialChoice with the current values of the specified - * tag. - * - * @param choices the tag - */ - public MaterialChoice(@NotNull Tag choices) { - Preconditions.checkArgument(choices != null, "choices"); - this.choices = new ArrayList<>(choices.getValues()); - } - - public MaterialChoice(@NotNull List choices) { - Preconditions.checkArgument(choices != null, "choices"); - Preconditions.checkArgument(!choices.isEmpty(), "Must have at least one choice"); - for (Material choice : choices) { - Preconditions.checkArgument(choice != null, "Cannot have null choice"); - } - - this.choices = new ArrayList<>(choices); - } - - @Override - public boolean test(@NotNull ItemStack t) { - for (Material match : choices) { - if (t.getType() == match) { - return true; - } - } - - return false; - } - - @NotNull - @Override - public ItemStack getItemStack() { - ItemStack stack = new ItemStack(choices.get(0)); - - // For compat - if (choices.size() > 1) { - stack.setDurability(Short.MAX_VALUE); - } - - return stack; - } - - @NotNull - public List getChoices() { - return Collections.unmodifiableList(choices); - } - - @NotNull - @Override - public MaterialChoice clone() { - try { - MaterialChoice clone = (MaterialChoice) super.clone(); - clone.choices = new ArrayList<>(choices); - return clone; - } catch (CloneNotSupportedException ex) { - throw new AssertionError(ex); - } - } - - @Override - public int hashCode() { - int hash = 3; - hash = 37 * hash + Objects.hashCode(this.choices); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final MaterialChoice other = (MaterialChoice) obj; - if (!Objects.equals(this.choices, other.choices)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "MaterialChoice{" + "choices=" + choices + '}'; - } - } - - /** - * Represents a choice that will be valid only one of the stacks is exactly - * matched (aside from stack size). - *
- * Only valid for shaped recipes - * - * @deprecated draft API - */ - @Deprecated - public static class ExactChoice implements RecipeChoice { - - private List choices; - - public ExactChoice(@NotNull ItemStack stack) { - this(Arrays.asList(stack)); - } - - public ExactChoice(@NotNull ItemStack... stacks) { - this(Arrays.asList(stacks)); - } - - public ExactChoice(@NotNull List choices) { - Preconditions.checkArgument(choices != null, "choices"); - Preconditions.checkArgument(!choices.isEmpty(), "Must have at least one choice"); - for (ItemStack choice : choices) { - Preconditions.checkArgument(choice != null, "Cannot have null choice"); - } - - this.choices = new ArrayList<>(choices); - } - - @NotNull - @Override - public ItemStack getItemStack() { - return choices.get(0).clone(); - } - - @NotNull - public List getChoices() { - return Collections.unmodifiableList(choices); - } - - @NotNull - @Override - public ExactChoice clone() { - try { - ExactChoice clone = (ExactChoice) super.clone(); - clone.choices = new ArrayList<>(choices); - return clone; - } catch (CloneNotSupportedException ex) { - throw new AssertionError(ex); - } - } - - @Override - public boolean test(@NotNull ItemStack t) { - for (ItemStack match : choices) { - if (t.isSimilar(match)) { - return true; - } - } - - return false; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 41 * hash + Objects.hashCode(this.choices); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ExactChoice other = (ExactChoice) obj; - if (!Objects.equals(this.choices, other.choices)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "ExactChoice{" + "choices=" + choices + '}'; - } - } -} diff --git a/api/src/main/java/org/bukkit/inventory/SaddledHorseInventory.java b/api/src/main/java/org/bukkit/inventory/SaddledHorseInventory.java deleted file mode 100644 index 7944f26a3..000000000 --- a/api/src/main/java/org/bukkit/inventory/SaddledHorseInventory.java +++ /dev/null @@ -1,3 +0,0 @@ -package org.bukkit.inventory; - -public interface SaddledHorseInventory extends AbstractHorseInventory {} diff --git a/api/src/main/java/org/bukkit/inventory/ShapedRecipe.java b/api/src/main/java/org/bukkit/inventory/ShapedRecipe.java deleted file mode 100644 index 222a12baa..000000000 --- a/api/src/main/java/org/bukkit/inventory/ShapedRecipe.java +++ /dev/null @@ -1,236 +0,0 @@ -package org.bukkit.inventory; - -import com.google.common.base.Preconditions; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang.Validate; -import org.bukkit.Keyed; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a shaped (ie normal) crafting recipe. - */ -public class ShapedRecipe implements Recipe, Keyed { - private final NamespacedKey key; - private final ItemStack output; - private String[] rows; - private Map ingredients = new HashMap<>(); - private String group = ""; - - @Deprecated - public ShapedRecipe(@NotNull ItemStack result) { - Preconditions.checkArgument(result.getType() != Material.AIR, "Recipe must have non-AIR result."); - this.key = NamespacedKey.randomKey(); - new Throwable("Warning: A plugin is creating a recipe using a Deprecated method. This will cause you to receive warnings stating 'Tried to load unrecognized recipe: bukkit:'. Please ask the author to give their recipe a static key using NamespacedKey.").printStackTrace(); - this.output = new ItemStack(result); - } - - /** - * 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 key the unique recipe key - * @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(@NotNull NamespacedKey key, @NotNull ItemStack result) { - Preconditions.checkArgument(key != null, "key"); - Preconditions.checkArgument(result.getType() != Material.AIR, "Recipe must have non-AIR result."); - - this.key = key; - 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. - */ - @NotNull - public ShapedRecipe shape(@NotNull final String... shape) { - Validate.notNull(shape, "Must provide a shape"); - Validate.isTrue(shape.length > 0 && shape.length < 4, "Crafting recipes should be 1, 2 or 3 rows, not ", shape.length); - - int lastLen = -1; - 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()); - - Validate.isTrue(lastLen == -1 || lastLen == row.length(), "Crafting recipes must be rectangular"); - lastLen = 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. - */ - @NotNull - public ShapedRecipe setIngredient(char key, @NotNull 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. - */ - @NotNull - public ShapedRecipe setIngredient(char key, @NotNull 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 - @NotNull - public ShapedRecipe setIngredient(char key, @NotNull 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 RecipeChoice.MaterialChoice(Collections.singletonList(ingredient))); - return this; - } - - @NotNull - public ShapedRecipe setIngredient(char key, @NotNull RecipeChoice ingredient) { - Validate.isTrue(ingredients.containsKey(key), "Symbol does not appear in the shape:", key); - - ingredients.put(key, ingredient); - return this; - } - - // Paper start - @NotNull - public ShapedRecipe setIngredient(char key, @NotNull ItemStack item) { - return setIngredient(key, new RecipeChoice.ExactChoice(item)); - } - // Paper end - - /** - * Get a copy of the ingredients map. - * - * @return The mapping of character to ingredients. - */ - @NotNull - 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().getItemStack().clone()); - } - } - return result; - } - - @NotNull - public Map getChoiceMap() { - Map 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. - * @throws NullPointerException when not set yet - */ - @NotNull - public String[] getShape() { - return rows.clone(); - } - - /** - * Get the result. - * - * @return The result stack. - */ - @Override - @NotNull - public ItemStack getResult() { - return output.clone(); - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - - /** - * Get the group of this recipe. Recipes with the same group may be grouped - * together when displayed in the client. - * - * @return recipe group. An empty string denotes no group. May not be null. - */ - @NotNull - public String getGroup() { - return group; - } - - /** - * Set the group of this recipe. Recipes with the same group may be grouped - * together when displayed in the client. - * - * @param group recipe group. An empty string denotes no group. May not be - * null. - */ - public void setGroup(@NotNull String group) { - Preconditions.checkArgument(group != null, "group"); - this.group = group; - } -} diff --git a/api/src/main/java/org/bukkit/inventory/ShapelessRecipe.java b/api/src/main/java/org/bukkit/inventory/ShapelessRecipe.java deleted file mode 100644 index ddcf84e66..000000000 --- a/api/src/main/java/org/bukkit/inventory/ShapelessRecipe.java +++ /dev/null @@ -1,350 +0,0 @@ -package org.bukkit.inventory; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import org.apache.commons.lang.Validate; -import org.bukkit.Keyed; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a shapeless recipe, where the arrangement of the ingredients on - * the crafting grid does not matter. - */ -public class ShapelessRecipe implements Recipe, Keyed { - private final NamespacedKey key; - private final ItemStack output; - private final List ingredients = new ArrayList<>(); - private String group = ""; - - @Deprecated - public ShapelessRecipe(@NotNull ItemStack result) { - Preconditions.checkArgument(result.getType() != Material.AIR, "Recipe must have non-AIR result."); - this.key = NamespacedKey.randomKey(); - new Throwable("Warning: A plugin is creating a recipe using a Deprecated method. This will cause you to receive warnings stating 'Tried to load unrecognized recipe: bukkit:'. Please ask the author to give their recipe a static key using NamespacedKey.").printStackTrace(); - this.output = new ItemStack(result); - } - - /** - * 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 key the unique recipe key - * @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(@NotNull NamespacedKey key, @NotNull ItemStack result) { - Preconditions.checkArgument(result.getType() != Material.AIR, "Recipe must have non-AIR result."); - this.key = key; - this.output = new ItemStack(result); - } - - /** - * Adds the specified ingredient. - * - * @param ingredient The ingredient to add. - * @return The changed recipe, so you can chain calls. - */ - @NotNull - public ShapelessRecipe addIngredient(@NotNull 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. - */ - @NotNull - public ShapelessRecipe addIngredient(@NotNull 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 - @NotNull - public ShapelessRecipe addIngredient(@NotNull 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. - */ - @NotNull - public ShapelessRecipe addIngredient(int count, @NotNull 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. - */ - @NotNull - public ShapelessRecipe addIngredient(int count, @NotNull 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 - @NotNull - public ShapelessRecipe addIngredient(int count, @NotNull 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 RecipeChoice.MaterialChoice(Collections.singletonList(ingredient))); - } - return this; - } - - @NotNull - public ShapelessRecipe addIngredient(@NotNull RecipeChoice ingredient) { - Validate.isTrue(ingredients.size() + 1 <= 9, "Shapeless recipes cannot have more than 9 ingredients"); - - ingredients.add(ingredient); - return this; - } - - // Paper start - @NotNull - public ShapelessRecipe addIngredient(@NotNull ItemStack item) { - return addIngredient(1, item); - } - - @NotNull - public ShapelessRecipe addIngredient(int count, @NotNull ItemStack item) { - Validate.isTrue(ingredients.size() + count <= 9, "Shapeless recipes cannot have more than 9 ingredients"); - while (count-- > 0) { - ingredients.add(new RecipeChoice.ExactChoice(item)); - } - return this; - } - - @NotNull - public ShapelessRecipe removeIngredient(@NotNull ItemStack item) { - return removeIngredient(1, item); - } - - @NotNull - public ShapelessRecipe removeIngredient(int count, @NotNull ItemStack item) { - Iterator iterator = ingredients.iterator(); - while (count > 0 && iterator.hasNext()) { - ItemStack stack = iterator.next().getItemStack(); - if (stack.equals(item)) { - iterator.remove(); - count--; - } - } - return this; - } - // Paper end - - /** - * Removes an ingredient from the list. - * - * @param ingredient The ingredient to remove - * @return The changed recipe. - */ - @NotNull - public ShapelessRecipe removeIngredient(@NotNull RecipeChoice ingredient) { - ingredients.remove(ingredient); - - 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. - */ - @NotNull - public ShapelessRecipe removeIngredient(@NotNull 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. - */ - @NotNull - public ShapelessRecipe removeIngredient(@NotNull 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. - */ - @NotNull - public ShapelessRecipe removeIngredient(int count, @NotNull 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. - */ - @NotNull - public ShapelessRecipe removeIngredient(int count, @NotNull 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 - @NotNull - public ShapelessRecipe removeIngredient(@NotNull 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 - @NotNull - public ShapelessRecipe removeIngredient(int count, @NotNull Material ingredient, int rawdata) { - Iterator iterator = ingredients.iterator(); - while (count > 0 && iterator.hasNext()) { - ItemStack stack = iterator.next().getItemStack(); - if (stack.getType() == ingredient && stack.getDurability() == rawdata) { - iterator.remove(); - count--; - } - } - return this; - } - - /** - * Get the result of this recipe. - * - * @return The result stack. - */ - @Override - @NotNull - public ItemStack getResult() { - return output.clone(); - } - - /** - * Get the list of ingredients used for this recipe. - * - * @return The input list - */ - @NotNull - public List getIngredientList() { - ArrayList result = new ArrayList(ingredients.size()); - for (RecipeChoice ingredient : ingredients) { - result.add(ingredient.getItemStack().clone()); - } - return result; - } - - @NotNull - public List getChoiceList() { - List result = new ArrayList<>(ingredients.size()); - for (RecipeChoice ingredient : ingredients) { - result.add(ingredient.clone()); - } - return result; - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - - /** - * Get the group of this recipe. Recipes with the same group may be grouped - * together when displayed in the client. - * - * @return recipe group. An empty string denotes no group. May not be null. - */ - @NotNull - public String getGroup() { - return group; - } - - /** - * Set the group of this recipe. Recipes with the same group may be grouped - * together when displayed in the client. - * - * @param group recipe group. An empty string denotes no group. May not be - * null. - */ - public void setGroup(@NotNull String group) { - Preconditions.checkArgument(group != null, "group"); - this.group = group; - } -} diff --git a/api/src/main/java/org/bukkit/inventory/SmokingRecipe.java b/api/src/main/java/org/bukkit/inventory/SmokingRecipe.java deleted file mode 100644 index 1073d9aec..000000000 --- a/api/src/main/java/org/bukkit/inventory/SmokingRecipe.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.inventory; - -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a campfire recipe. - */ -public class SmokingRecipe extends CookingRecipe { - - public SmokingRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull Material source, float experience, int cookingTime) { - super(key, result, source, experience, cookingTime); - } - - public SmokingRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull RecipeChoice input, float experience, int cookingTime) { - super(key, result, input, experience, cookingTime); - } -} diff --git a/api/src/main/java/org/bukkit/inventory/StonecutterInventory.java b/api/src/main/java/org/bukkit/inventory/StonecutterInventory.java deleted file mode 100644 index dbb034fae..000000000 --- a/api/src/main/java/org/bukkit/inventory/StonecutterInventory.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.bukkit.inventory; - -/** - * Interface to the inventory of a Stonecutter. - */ -public interface StonecutterInventory extends Inventory { } diff --git a/api/src/main/java/org/bukkit/inventory/StonecuttingRecipe.java b/api/src/main/java/org/bukkit/inventory/StonecuttingRecipe.java deleted file mode 100644 index d8ef781d6..000000000 --- a/api/src/main/java/org/bukkit/inventory/StonecuttingRecipe.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.bukkit.inventory; - -import com.google.common.base.Preconditions; -import java.util.Collections; -import org.bukkit.Keyed; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a Stonecutting recipe. - */ -public class StonecuttingRecipe implements Recipe, Keyed { - private final NamespacedKey key; - private ItemStack output; - private RecipeChoice ingredient; - private String group = ""; - - /** - * Create a Stonecutting recipe to craft the specified ItemStack. - * - * @param key The unique recipe key - * @param result The item you want the recipe to create. - * @param source The input material. - */ - public StonecuttingRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull Material source) { - this(key, result, new RecipeChoice.MaterialChoice(Collections.singletonList(source))); - } - - /** - * Create a cooking recipe to craft the specified ItemStack. - * - * @param key The unique recipe key - * @param result The item you want the recipe to create. - * @param input The input choices. - */ - public StonecuttingRecipe(@NotNull NamespacedKey key, @NotNull ItemStack result, @NotNull RecipeChoice input) { - Preconditions.checkArgument(result.getType() != Material.AIR, "Recipe must have non-AIR result."); - this.key = key; - this.output = new ItemStack(result); - this.ingredient = input; - } - - /** - * Sets the input of this cooking recipe. - * - * @param input The input material. - * @return The changed recipe, so you can chain calls. - */ - @NotNull - public StonecuttingRecipe setInput(@NotNull Material input) { - this.ingredient = new RecipeChoice.MaterialChoice(Collections.singletonList(input)); - return this; - } - - /** - * Get the input material. - * - * @return The input material. - */ - @NotNull - public ItemStack getInput() { - return this.ingredient.getItemStack(); - } - - /** - * Sets the input of this cooking recipe. - * - * @param input The input choice. - * @return The changed recipe, so you can chain calls. - */ - @NotNull - public StonecuttingRecipe setInputChoice(@NotNull RecipeChoice input) { - this.ingredient = input; - return (StonecuttingRecipe) this; - } - - /** - * Get the input choice. - * - * @return The input choice. - */ - @NotNull - public RecipeChoice getInputChoice() { - return this.ingredient.clone(); - } - - /** - * Get the result of this recipe. - * - * @return The resulting stack. - */ - @NotNull - @Override - public ItemStack getResult() { - return output.clone(); - } - - @NotNull - @Override - public NamespacedKey getKey() { - return key; - } - - /** - * Get the group of this recipe. Recipes with the same group may be grouped - * together when displayed in the client. - * - * @return recipe group. An empty string denotes no group. May not be null. - */ - @NotNull - public String getGroup() { - return group; - } - - /** - * Set the group of this recipe. Recipes with the same group may be grouped - * together when displayed in the client. - * - * @param group recipe group. An empty string denotes no group. May not be - * null. - */ - public void setGroup(@NotNull String group) { - Preconditions.checkArgument(group != null, "group"); - this.group = group; - } -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/BannerMeta.java b/api/src/main/java/org/bukkit/inventory/meta/BannerMeta.java deleted file mode 100644 index 4739d2ecc..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/BannerMeta.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.bukkit.inventory.meta; - -import java.util.List; -import org.bukkit.DyeColor; -import org.bukkit.block.banner.Pattern; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface BannerMeta extends ItemMeta { - - /** - * Returns the base color for this banner - * - * @return the base color - * @deprecated banner color is now stored as the data value, not meta. - */ - @Deprecated - @Nullable - DyeColor getBaseColor(); - - /** - * Sets the base color for this banner - * - * @param color the base color - * @deprecated banner color is now stored as the data value, not meta. - */ - @Deprecated - void setBaseColor(@Nullable DyeColor color); - - /** - * Returns a list of patterns on this banner - * - * @return the patterns - */ - @NotNull - List getPatterns(); - - /** - * Sets the patterns used on this banner - * - * @param patterns the new list of patterns - */ - void setPatterns(@NotNull List patterns); - - /** - * Adds a new pattern on top of the existing - * patterns - * - * @param pattern the new pattern to add - */ - void addPattern(@NotNull Pattern pattern); - - /** - * Returns the pattern at the specified index - * - * @param i the index - * @return the pattern - * @throws IndexOutOfBoundsException when index is not in [0, numberOfPatterns()) range - */ - @NotNull - Pattern getPattern(int i); - - /** - * Removes the pattern at the specified index - * - * @param i the index - * @return the removed pattern - * @throws IndexOutOfBoundsException when index is not in [0, numberOfPatterns()) range - */ - @NotNull - Pattern removePattern(int i); - - /** - * Sets the pattern at the specified index - * - * @param i the index - * @param pattern the new pattern - * @throws IndexOutOfBoundsException when index is not in [0, numberOfPatterns()) range - */ - void setPattern(int i, @NotNull Pattern pattern); - - /** - * Returns the number of patterns on this - * banner - * - * @return the number of patterns - */ - int numberOfPatterns(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/BlockDataMeta.java b/api/src/main/java/org/bukkit/inventory/meta/BlockDataMeta.java deleted file mode 100644 index 473c72dcd..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/BlockDataMeta.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.inventory.meta; - -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.jetbrains.annotations.NotNull; - -public interface BlockDataMeta extends ItemMeta { - - /** - * Returns whether the item has block data currently attached to it. - * - * @return whether block data is already attached - */ - boolean hasBlockData(); - - /** - * Returns the currently attached block data 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 #setBlockData(org.bukkit.block.data.BlockData)} - * - * @param material the material we wish to get this data in the context of - * @return the attached data or new data - */ - @NotNull - BlockData getBlockData(@NotNull Material material); - - /** - * Attaches a copy of the passed block data to the item. - * - * @param blockData the block data to attach to the block. - * @throws IllegalArgumentException if the blockData is null or invalid for - * this item. - */ - void setBlockData(@NotNull BlockData blockData); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/BlockStateMeta.java b/api/src/main/java/org/bukkit/inventory/meta/BlockStateMeta.java deleted file mode 100644 index e7d905b11..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/BlockStateMeta.java +++ /dev/null @@ -1,37 +0,0 @@ - -package org.bukkit.inventory.meta; - -import org.bukkit.block.BlockState; -import org.jetbrains.annotations.NotNull; - -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(org.bukkit.block.BlockState)} - * - * @return the attached state or a new state - */ - @NotNull - 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(@NotNull BlockState blockState); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/BookMeta.java b/api/src/main/java/org/bukkit/inventory/meta/BookMeta.java deleted file mode 100644 index 43fb418a8..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/BookMeta.java +++ /dev/null @@ -1,263 +0,0 @@ -package org.bukkit.inventory.meta; - -import java.util.List; -import net.md_5.bungee.api.chat.BaseComponent; -import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a book ({@link Material#WRITABLE_BOOK} or {@link - * Material#WRITTEN_BOOK}) that can have a title, an author, and pages. - */ -public interface BookMeta extends ItemMeta { - - /** - * Represents the generation (or level of copying) of a written book - */ - enum Generation { - /** - * Book written into a book-and-quill. Can be copied. (Default value) - */ - ORIGINAL, - /** - * Book that was copied from an original. Can be copied. - */ - COPY_OF_ORIGINAL, - /** - * Book that was copied from a copy of an original. Can't be copied. - */ - COPY_OF_COPY, - /** - * Unused; unobtainable by players. Can't be copied. - */ - TATTERED; - } - - /** - * 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 - */ - @Nullable - 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(@Nullable String title); - - /** - * Checks for the existence of an author in the book. - * - * @return true if the book has an author - */ - 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 - */ - @Nullable - String getAuthor(); - - /** - * Sets the author of the book. Removes author when given null. - * - * @param author the author to set - */ - void setAuthor(@Nullable String author); - - /** - * Checks for the existence of generation level in the book. - * - * @return true if the book has a generation level - */ - boolean hasGeneration(); - - /** - * Gets the generation of the book. - *

- * Plugins should check that hasGeneration() returns true before calling - * this method. - * - * @return the generation of the book - */ - @Nullable - Generation getGeneration(); - - /** - * Sets the generation of the book. Removes generation when given null. - * - * @param generation the generation to set - */ - void setGeneration(@Nullable Generation generation); - - /** - * 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. - *

- * Pages are 1-indexed. - * - * @param page the page number to get, in range [1, getPageCount()] - * @return the page from the book - */ - @NotNull - 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. - *

- * Pages are 1-indexed. - * - * @param page the page number to set, in range [1, getPageCount()] - * @param data the data to set for that page - */ - void setPage(int page, @NotNull String data); - - /** - * Gets all the pages in the book. - * - * @return list of all the pages in the book - */ - @NotNull - 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(@NotNull 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(@NotNull 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(@NotNull String... pages); - - /** - * Gets the number of pages in the book. - * - * @return the number of pages in the book - */ - int getPageCount(); - - @Override - @NotNull - BookMeta clone(); - - // Spigot start - public class Spigot extends ItemMeta.Spigot { - - /** - * 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 - */ - @NotNull - public BaseComponent[] getPage(int page) { - throw new UnsupportedOperationException("Not supported yet."); - } - - /** - * 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 - */ - public void setPage(int page, @Nullable BaseComponent... data) { - throw new UnsupportedOperationException("Not supported yet."); - } - - /** - * Gets all the pages in the book. - * - * @return list of all the pages in the book - */ - @NotNull - public List getPages() { - throw new UnsupportedOperationException("Not supported yet."); - } - - /** - * 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 - */ - public void setPages(@NotNull List pages) { - throw new UnsupportedOperationException("Not supported yet."); - } - - /** - * 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 component arrays, each being a page - */ - public void setPages(@NotNull BaseComponent[]... pages) { - throw new UnsupportedOperationException("Not supported yet."); - } - - /** - * 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 component arrays, each being a page - */ - public void addPage(@NotNull BaseComponent[]... pages) { - throw new UnsupportedOperationException("Not supported yet."); - } - } - - @NotNull - @Override - Spigot spigot(); - // Spigot end -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/CrossbowMeta.java b/api/src/main/java/org/bukkit/inventory/meta/CrossbowMeta.java deleted file mode 100644 index 35c6594fd..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/CrossbowMeta.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.inventory.meta; - -import java.util.List; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface CrossbowMeta extends ItemMeta { - - /** - * Returns whether the item has any charged projectiles. - * - * @return whether charged projectiles are present - */ - boolean hasChargedProjectiles(); - - /** - * Returns an immutable list of the projectiles charged on this item. - * - * @return charged projectiles - */ - @NotNull - List getChargedProjectiles(); - - /** - * Sets the projectiles charged on this item. - * - * Removes all projectiles when given null. - * - * @param projectiles the projectiles to set - * @throws IllegalArgumentException if one of the projectiles is not an - * arrow or firework rocket - */ - void setChargedProjectiles(@Nullable List projectiles); - - /** - * Adds a charged projectile to this item. - * - * @param item projectile - * @throws IllegalArgumentException if the projectile is not an arrow or - * firework rocket - */ - void addChargedProjectile(@NotNull ItemStack item); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/Damageable.java b/api/src/main/java/org/bukkit/inventory/meta/Damageable.java deleted file mode 100644 index 6392362b9..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/Damageable.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.inventory.meta; - -import org.jetbrains.annotations.NotNull; - -/** - * Represents an item that has durability and can take damage. - */ -public interface Damageable { - - /** - * Checks to see if this item has damage - * - * @return true if this has damage - */ - boolean hasDamage(); - - /** - * Gets the damage - * - * @return the damage - */ - int getDamage(); - - /** - * Sets the damage - * - * @param damage item damage - */ - void setDamage(int damage); - - @NotNull - Damageable clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java b/api/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java deleted file mode 100644 index aae2ed2ec..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.bukkit.inventory.meta; - -import java.util.Map; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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(@NotNull Enchantment ench); - - /** - * Gets a copy the stored enchantments in this ItemMeta. - * - * @return An immutable copy of the stored enchantments - */ - @NotNull - 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(@NotNull 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(@NotNull 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(@NotNull Enchantment ench); - - @Override - @NotNull - EnchantmentStorageMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java b/api/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java deleted file mode 100644 index ce0f148d2..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.inventory.meta; - -import org.bukkit.FireworkEffect; -import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a meta that can store a single FireworkEffect. An example - * includes {@link Material#FIREWORK_STAR}. - */ -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(@Nullable 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 - */ - @Nullable - FireworkEffect getEffect(); - - @Override - @NotNull - FireworkEffectMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java b/api/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java deleted file mode 100644 index fe2394817..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.bukkit.inventory.meta; - -import java.util.List; -import org.bukkit.FireworkEffect; -import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a {@link Material#FIREWORK_ROCKET} 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(@NotNull 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(@NotNull 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(@NotNull Iterable effects) throws IllegalArgumentException; - - /** - * Get the effects in this firework. - * - * @return An immutable list of the firework effects - */ - @NotNull - 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; - - @Override - @NotNull - FireworkMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/ItemMeta.java b/api/src/main/java/org/bukkit/inventory/meta/ItemMeta.java deleted file mode 100644 index 595df539b..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/ItemMeta.java +++ /dev/null @@ -1,506 +0,0 @@ -package org.bukkit.inventory.meta; - -import com.google.common.collect.Multimap; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.meta.tags.CustomItemTagContainer; -import org.bukkit.persistence.PersistentDataHolder; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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, PersistentDataHolder { - - /** - * 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 - */ - @NotNull - String getDisplayName(); - - /** - * Sets the display name. - * - * @param name the name to set - */ - void setDisplayName(@Nullable String name); - - /** - * Checks for existence of a localized name. - * - * @return true if this has a localized name - */ - boolean hasLocalizedName(); - - /** - * Gets the localized display name that is set. - *

- * Plugins should check that hasLocalizedName() returns true - * before calling this method. - * - * @return the localized name that is set - */ - @NotNull - String getLocalizedName(); - - /** - * Sets the localized name. - * - * @param name the name to set - */ - void setLocalizedName(@Nullable 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 - */ - @Nullable - List getLore(); - - /** - * Sets the lore for this item. - * Removes lore when given null. - * - * @param lore the lore that will be set - */ - void setLore(@Nullable List lore); - - /** - * Checks for existence of custom model data. - *

- * CustomModelData is an integer that may be associated client side with a - * custom item model. - * - * @return true if this has custom model data - */ - boolean hasCustomModelData(); - - /** - * Gets the custom model data that is set. - *

- * CustomModelData is an integer that may be associated client side with a - * custom item model. - *

- * Plugins should check that hasCustomModelData() returns true - * before calling this method. - * - * @return the localized name that is set - */ - int getCustomModelData(); - - /** - * Sets the custom model data. - *

- * CustomModelData is an integer that may be associated client side with a - * custom item model. - * - * @param data the data to set, or null to clear - */ - void setCustomModelData(@Nullable Integer data); - - /** - * 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(@NotNull 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(@NotNull Enchantment ench); - - /** - * Returns a copy the enchantments in this ItemMeta.
- * Returns an empty map if none. - * - * @return An immutable copy of the enchantments - */ - @NotNull - 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull ItemFlag... itemFlags); - - /** - * Get current set itemFlags. The collection returned is unmodifiable. - * - * @return A set of all itemFlags set - */ - @NotNull - 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(@NotNull ItemFlag flag); - - /** - * Return if the unbreakable tag is true. An unbreakable item will not lose - * durability. - * - * @return true if the unbreakable tag is true - */ - boolean isUnbreakable(); - - /** - * Sets the unbreakable tag. An unbreakable item will not lose durability. - * - * @param unbreakable true if set unbreakable - */ - void setUnbreakable(boolean unbreakable); - - /** - * Checks for the existence of any AttributeModifiers. - * - * @return true if any AttributeModifiers exist - */ - boolean hasAttributeModifiers(); - - /** - * Return an immutable copy of all Attributes and - * their modifiers in this ItemMeta.
- * Returns null if none exist. - * - * @return an immutable {@link Multimap} of Attributes - * and their AttributeModifiers, or null if none exist - */ - @Nullable - Multimap getAttributeModifiers(); - - /** - * Return an immutable copy of all {@link Attribute}s and their - * {@link AttributeModifier}s for a given {@link EquipmentSlot}.
- * Any {@link AttributeModifier} that does have have a given - * {@link EquipmentSlot} will be returned. This is because - * AttributeModifiers without a slot are active in any slot.
- * If there are no attributes set for the given slot, an empty map - * will be returned. - * - * @param slot the {@link EquipmentSlot} to check - * @return the immutable {@link Multimap} with the - * respective Attributes and modifiers, or an empty map - * if no attributes are set. - */ - @NotNull - Multimap getAttributeModifiers(@NotNull EquipmentSlot slot); - - /** - * Return an immutable copy of all {@link AttributeModifier}s - * for a given {@link Attribute} - * - * @param attribute the {@link Attribute} - * @return an immutable collection of {@link AttributeModifier}s - * or null if no AttributeModifiers exist for the Attribute. - * @throws NullPointerException if Attribute is null - */ - @Nullable - Collection getAttributeModifiers(@NotNull Attribute attribute); - - /** - * Add an Attribute and it's Modifier. - * AttributeModifiers can now support {@link EquipmentSlot}s. - * If not set, the {@link AttributeModifier} will be active in ALL slots. - *
- * Two {@link AttributeModifier}s that have the same {@link java.util.UUID} - * cannot exist on the same Attribute. - * - * @param attribute the {@link Attribute} to modify - * @param modifier the {@link AttributeModifier} specifying the modification - * @return true if the Attribute and AttributeModifier were - * successfully added - * @throws NullPointerException if Attribute is null - * @throws NullPointerException if AttributeModifier is null - * @throws IllegalArgumentException if AttributeModifier already exists - */ - boolean addAttributeModifier(@NotNull Attribute attribute, @NotNull AttributeModifier modifier); - - /** - * Set all {@link Attribute}s and their {@link AttributeModifier}s. - * To clear all currently set Attributes and AttributeModifiers use - * null or an empty Multimap. - * If not null nor empty, this will filter all entries that are not-null - * and add them to the ItemStack. - * - * @param attributeModifiers the new Multimap containing the Attributes - * and their AttributeModifiers - */ - void setAttributeModifiers(@Nullable Multimap attributeModifiers); - - /** - * Remove all {@link AttributeModifier}s associated with the given - * {@link Attribute}. - * This will return false if nothing was removed. - * - * @param attribute attribute to remove - * @return true if all modifiers were removed from a given - * Attribute. Returns false if no attributes were - * removed. - * @throws NullPointerException if Attribute is null - */ - boolean removeAttributeModifier(@NotNull Attribute attribute); - - /** - * Remove all {@link Attribute}s and {@link AttributeModifier}s for a - * given {@link EquipmentSlot}.
- * If the given {@link EquipmentSlot} is null, this will remove all - * {@link AttributeModifier}s that do not have an EquipmentSlot set. - * - * @param slot the {@link EquipmentSlot} to clear all Attributes and - * their modifiers for - * @return true if all modifiers were removed that match the given - * EquipmentSlot. - */ - boolean removeAttributeModifier(@NotNull EquipmentSlot slot); - - /** - * Remove a specific {@link Attribute} and {@link AttributeModifier}. - * AttributeModifiers are matched according to their {@link java.util.UUID}. - * - * @param attribute the {@link Attribute} to remove - * @param modifier the {@link AttributeModifier} to remove - * @return if any attribute modifiers were remove - * - * @see AttributeModifier#getUniqueId() - * - * @throws NullPointerException if the Attribute is null - * @throws NullPointerException if the AttributeModifier is null - */ - boolean removeAttributeModifier(@NotNull Attribute attribute, @NotNull AttributeModifier modifier); - - /** - * Returns a public custom tag container capable of storing tags on the - * item. - * - * Those tags will be sent to the client with all of their content, so the - * client is capable of reading them. This will result in the player seeing - * a NBT Tag notification on the item. - * - * These tags can also be modified by the client once in creative mode - * - * @return the custom tag container - * @deprecated this API part has been replaced by the {@link PersistentDataHolder} API. - * Please use {@link PersistentDataHolder#getPersistentDataContainer()} instead of this. - */ - @NotNull - @Deprecated - CustomItemTagContainer getCustomTagContainer(); - - /** - * Internal use only! Do not use under any circumstances! - * - * @param version version - * @deprecated - */ - @Deprecated - void setVersion(int version); - - @SuppressWarnings("javadoc") - @NotNull - ItemMeta clone(); - - // Spigot start - public class Spigot - { - - /** - * Sets the unbreakable tag - * - * @param unbreakable true if set unbreakable - * @deprecated see {@link ItemMeta#setUnbreakable(boolean)} - */ - @Deprecated - 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 - * @deprecated see {@link ItemMeta#isUnbreakable()} - */ - @Deprecated - public boolean isUnbreakable() - { - throw new UnsupportedOperationException( "Not supported yet." ); - } - } - - @NotNull - Spigot spigot(); - // Spigot end - // Paper start - Add an API for CanPlaceOn and CanDestroy NBT values - /** - * Gets set of materials what given item can destroy in {@link org.bukkit.GameMode#ADVENTURE} - * - * @return Set of materials - * @deprecated Minecraft does not limit this to the material enum, Use {@link #getDestroyableKeys()} as a replacement - */ - @Deprecated - Set getCanDestroy(); - - /** - * Sets set of materials what given item can destroy in {@link org.bukkit.GameMode#ADVENTURE} - * - * @param canDestroy Set of materials - * @deprecated Minecraft does not limit this to the material enum, Use {@link #setDestroyableKeys(Collection)} as a replacement - */ - @Deprecated - void setCanDestroy(Set canDestroy); - - /** - * Gets set of materials where given item can be placed on in {@link org.bukkit.GameMode#ADVENTURE} - * - * @return Set of materials - * @deprecated Minecraft does not limit this to the material enum, Use {@link #getPlaceableKeys()} as a replacement - */ - @Deprecated - Set getCanPlaceOn(); - - /** - * Sets set of materials where given item can be placed on in {@link org.bukkit.GameMode#ADVENTURE} - * - * @param canPlaceOn Set of materials - * @deprecated Minecraft does not limit this to the material enum, Use {@link #setPlaceableKeys(Collection)} as a replacement - */ - @Deprecated - void setCanPlaceOn(Set canPlaceOn); - - /** - * Gets the collection of namespaced keys that the item can destroy in {@link org.bukkit.GameMode#ADVENTURE} - * - * @return Set of {@link com.destroystokyo.paper.Namespaced} - */ - @NotNull - Set getDestroyableKeys(); - - /** - * Sets the collection of namespaced keys that the item can destroy in {@link org.bukkit.GameMode#ADVENTURE} - * - * @param canDestroy Collection of {@link com.destroystokyo.paper.Namespaced} - */ - void setDestroyableKeys(@NotNull Collection canDestroy); - - /** - * Gets the collection of namespaced keys that the item can be placed on in {@link org.bukkit.GameMode#ADVENTURE} - * - * @return Set of {@link com.destroystokyo.paper.Namespaced} - */ - @NotNull - Set getPlaceableKeys(); - - /** - * Sets the set of namespaced keys that the item can be placed on in {@link org.bukkit.GameMode#ADVENTURE} - * - * @param canPlaceOn Collection of {@link com.destroystokyo.paper.Namespaced} - */ - @NotNull - void setPlaceableKeys(@NotNull Collection canPlaceOn); - - /** - * Checks for the existence of any keys that the item can be placed on - * - * @return true if this item has placeable keys - */ - boolean hasPlaceableKeys(); - - /** - * Checks for the existence of any keys that the item can destroy - * - * @return true if this item has destroyable keys - */ - boolean hasDestroyableKeys(); - // Paper end -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/KnowledgeBookMeta.java b/api/src/main/java/org/bukkit/inventory/meta/KnowledgeBookMeta.java deleted file mode 100644 index 736c60c71..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/KnowledgeBookMeta.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.inventory.meta; - -import java.util.List; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -public interface KnowledgeBookMeta extends ItemMeta { - - /** - * Checks for the existence of recipes in the book. - * - * @return true if the book has recipes - */ - boolean hasRecipes(); - - /** - * Gets all the recipes in the book. - * - * @return list of all the recipes in the book - */ - @NotNull - List getRecipes(); - - /** - * Clears the existing book recipes, and sets the book to use the provided - * recipes. - * - * @param recipes A list of recipes to set the book to use - */ - void setRecipes(@NotNull List recipes); - - /** - * Adds new recipe to the end of the book. - * - * @param recipes A list of recipe keys - */ - void addRecipe(@NotNull NamespacedKey... recipes); - - @NotNull - @Override - KnowledgeBookMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java b/api/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java deleted file mode 100644 index c1676991c..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.inventory.meta; - -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.inventory.ItemFactory; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @NotNull - 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(@Nullable Color color); - - @Override - @NotNull - LeatherArmorMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/MapMeta.java b/api/src/main/java/org/bukkit/inventory/meta/MapMeta.java deleted file mode 100644 index 8fca3ba23..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/MapMeta.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.bukkit.inventory.meta; - -import org.bukkit.Color; -import org.bukkit.UndefinedNullability; -import org.bukkit.map.MapView; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a map that can be scalable. - */ -public interface MapMeta extends ItemMeta { - - /** - * Checks for existence of a map ID number. - * - * @return true if this has a map ID number. - * @deprecated These methods are poor API: They rely on the caller to pass - * in an only an integer property, and have poorly defined implementation - * behavior if that integer is not a valid map (the current implementation - * for example will generate a new map with a different ID). The xxxMapView - * family of methods should be used instead. - * @see #hasMapView() - */ - @Deprecated - boolean hasMapId(); - - /** - * Gets the map ID that is set. This is used to determine what map is - * displayed. - *

- * Plugins should check that hasMapId() returns true before - * calling this method. - * - * @return the map ID that is set - * @deprecated These methods are poor API: They rely on the caller to pass - * in an only an integer property, and have poorly defined implementation - * behavior if that integer is not a valid map (the current implementation - * for example will generate a new map with a different ID). The xxxMapView - * family of methods should be used instead. - * @see #getMapView() - */ - @Deprecated - int getMapId(); - - /** - * Sets the map ID. This is used to determine what map is displayed. - * - * @param id the map id to set - * @deprecated These methods are poor API: They rely on the caller to pass - * in an only an integer property, and have poorly defined implementation - * behavior if that integer is not a valid map (the current implementation - * for example will generate a new map with a different ID). The xxxMapView - * family of methods should be used instead. - * @see #setMapView(org.bukkit.map.MapView) - */ - @Deprecated - void setMapId(int id); - - /** - * Checks for existence of an associated map. - * - * @return true if this item has an associated map - */ - boolean hasMapView(); - - /** - * Gets the map view that is associated with this map item. - * - *

- * Plugins should check that hasMapView() returns true before - * calling this method. - * - * @return the map view, or null if the item hasMapView(), but this map does - * not exist on the server - */ - @Nullable - MapView getMapView(); - - /** - * Sets the associated map. This is used to determine what map is displayed. - * - *

- * The implementation may allow null to clear the associated map, but - * this is not required and is liable to generate a new (undefined) map when - * the item is first used. - * - * @param map the map to set - */ - void setMapView(@UndefinedNullability("implementation defined") MapView map); - - /** - * 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); - - /** - * Checks for existence of a location name. - * - * @return true if this has a location name - */ - boolean hasLocationName(); - - /** - * Gets the location name that is set. - *

- * Plugins should check that hasLocationName() returns true - * before calling this method. - * - * @return the location name that is set - */ - @Nullable - String getLocationName(); - - /** - * Sets the location name. A custom map color will alter the display of the - * map in an inventory slot. - * - * @param name the name to set - */ - void setLocationName(@Nullable String name); - - /** - * Checks for existence of a map color. - * - * @return true if this has a custom map color - */ - boolean hasColor(); - - /** - * Gets the map color that is set. A custom map color will alter the display - * of the map in an inventory slot. - *

- * Plugins should check that hasColor() returns true before - * calling this method. - * - * @return the map color that is set - */ - @Nullable - Color getColor(); - - /** - * Sets the map color. A custom map color will alter the display of the map - * in an inventory slot. - * - * @param color the color to set - */ - void setColor(@Nullable Color color); - - @Override - @NotNull - MapMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/PotionMeta.java b/api/src/main/java/org/bukkit/inventory/meta/PotionMeta.java deleted file mode 100644 index 1056849dc..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/PotionMeta.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.bukkit.inventory.meta; - -import java.util.List; -import org.bukkit.Color; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a potion or item that can have custom effects. - */ -public interface PotionMeta extends ItemMeta { - - /** - * Sets the underlying potion data - * - * @param data PotionData to set the base potion state to - */ - void setBasePotionData(@NotNull PotionData data); - - /** - * Returns the potion data about the base potion - * - * @return a PotionData object - */ - @NotNull - PotionData getBasePotionData(); - - /** - * 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 - */ - @NotNull - 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(@NotNull 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(@NotNull 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(@NotNull 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 - * @deprecated use {@link org.bukkit.potion.PotionType#PotionType} - */ - @Deprecated - boolean setMainEffect(@NotNull 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(); - - /** - * Checks for existence of a potion color. - * - * @return true if this has a custom potion color - */ - boolean hasColor(); - - /** - * Gets the potion color that is set. A custom potion color will alter the - * display of the potion in an inventory slot. - *

- * Plugins should check that hasColor() returns true before - * calling this method. - * - * @return the potion color that is set - */ - @Nullable - Color getColor(); - - /** - * Sets the potion color. A custom potion color will alter the display of - * the potion in an inventory slot. - * - * @param color the color to set - */ - void setColor(@Nullable Color color); - - @Override - PotionMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/Repairable.java b/api/src/main/java/org/bukkit/inventory/meta/Repairable.java deleted file mode 100644 index 0a1d543db..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/Repairable.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.inventory.meta; - -import org.jetbrains.annotations.NotNull; - -/** - * 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") - @NotNull - Repairable clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/SkullMeta.java b/api/src/main/java/org/bukkit/inventory/meta/SkullMeta.java deleted file mode 100644 index 8b2465ea2..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/SkullMeta.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.bukkit.inventory.meta; - -import com.destroystokyo.paper.profile.PlayerProfile; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - - -/** - * Represents a skull that can have an owner. - */ -public interface SkullMeta extends ItemMeta { - - /** - * Gets the owner of the skull. - * - * @return the owner if the skull - * @deprecated see {@link #setOwningPlayer(org.bukkit.OfflinePlayer)}. - */ - @Deprecated - @Nullable - 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. - * - * @param owner the new owner of the skull - * @return true if the owner was successfully set - * @deprecated see {@link #setOwningPlayer(org.bukkit.OfflinePlayer)}. - */ - @Deprecated - boolean setOwner(@Nullable String owner); - - // Paper start - /** - * Sets this skull to use the supplied Player Profile, which can include textures already prefilled. - * @param profile The profile to set this Skull to use, or null to clear owner - */ - void setPlayerProfile(@Nullable PlayerProfile profile); - - /** - * If the skull has an owner, per {@link #hasOwner()}, return the owners {@link PlayerProfile} - * @return The profile of the owner, if set - */ - @Nullable PlayerProfile getPlayerProfile(); - // Paper end - - /** - * Gets the owner of the skull. - * - * @return the owner if the skull - */ - @Nullable - OfflinePlayer getOwningPlayer(); - - /** - * 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 setOwningPlayer(@Nullable OfflinePlayer owner); - - @Override - @NotNull - SkullMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/SpawnEggMeta.java b/api/src/main/java/org/bukkit/inventory/meta/SpawnEggMeta.java deleted file mode 100644 index 9ae84de43..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/SpawnEggMeta.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.inventory.meta; - -import org.bukkit.entity.EntityType; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a spawn egg and it's spawned type. - */ -public interface SpawnEggMeta extends ItemMeta { - - /** - * Get the type of entity this egg will spawn. - * - * @return The entity type. May be null for implementation specific default. - * @deprecated different types are different items - */ - @Deprecated - @Contract("-> fail") - EntityType getSpawnedType(); - - /** - * Set the type of entity this egg will spawn. - * - * @param type The entity type. May be null for implementation specific - * default. - * @deprecated different types are different items - */ - @Deprecated - @Contract("_ -> fail") - void setSpawnedType(EntityType type); - - @NotNull - @Override - SpawnEggMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/SuspiciousStewMeta.java b/api/src/main/java/org/bukkit/inventory/meta/SuspiciousStewMeta.java deleted file mode 100644 index c2f4282c1..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/SuspiciousStewMeta.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.bukkit.inventory.meta; - -import java.util.List; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a suspicious stew that can have custom effects. - */ -public interface SuspiciousStewMeta 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 suspicious stew. - *

- * Plugins should check that hasCustomEffects() returns true before calling - * this method. - * - * @return the immutable list of custom potion effects - */ - @NotNull - List getCustomEffects(); - - /** - * Adds a custom potion effect to this suspicious stew. - * - * @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 suspicious stew meta changed as a result of this call - */ - boolean addCustomEffect(@NotNull PotionEffect effect, boolean overwrite); - - /** - * Removes a custom potion effect from this suspicious stew. - * - * @param type the potion effect type to remove - * @return true if the suspicious stew meta changed as a result of this call - */ - boolean removeCustomEffect(@NotNull PotionEffectType type); - - /** - * Checks for a specific custom potion effect type on this suspicious stew. - * - * @param type the potion effect type to check for - * @return true if the suspicious stew has this effect - */ - boolean hasCustomEffect(@NotNull PotionEffectType type); - - /** - * Removes all custom potion effects from this suspicious stew. - * - * @return true if the suspicious stew meta changed as a result of this call - */ - boolean clearCustomEffects(); - - @Override - SuspiciousStewMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/TropicalFishBucketMeta.java b/api/src/main/java/org/bukkit/inventory/meta/TropicalFishBucketMeta.java deleted file mode 100644 index 268b92e34..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/TropicalFishBucketMeta.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.bukkit.inventory.meta; - -import org.bukkit.DyeColor; -import org.bukkit.entity.TropicalFish; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a bucket of tropical fish. - */ -public interface TropicalFishBucketMeta extends ItemMeta { - - /** - * Gets the color of the fish's pattern. - *

- * Plugins should check that hasVariant() returns true before - * calling this method. - * - * @return pattern color - */ - @NotNull - DyeColor getPatternColor(); - - /** - * Sets the color of the fish's pattern. - *

- * Setting this when hasVariant() returns false will initialize - * all other values to unspecified defaults. - * - * @param color pattern color - */ - void setPatternColor(@NotNull DyeColor color); - - /** - * Gets the color of the fish's body. - *

- * Plugins should check that hasVariant() returns true before - * calling this method. - * - * @return pattern color - */ - @NotNull - DyeColor getBodyColor(); - - /** - * Sets the color of the fish's body. - *

- * Setting this when hasVariant() returns false will initialize - * all other values to unspecified defaults. - * - * @param color body color - */ - void setBodyColor(@NotNull DyeColor color); - - /** - * Gets the fish's pattern. - *

- * Plugins should check that hasVariant() returns true before - * calling this method. - * - * @return pattern - */ - @NotNull - TropicalFish.Pattern getPattern(); - - /** - * Sets the fish's pattern. - *

- * Setting this when hasVariant() returns false will initialize - * all other values to unspecified defaults. - * - * @param pattern new pattern - */ - void setPattern(@NotNull TropicalFish.Pattern pattern); - - /** - * Checks for existence of a variant tag indicating a specific fish will be - * spawned. - * - * @return if there is a variant - */ - boolean hasVariant(); - - @Override - @NotNull - TropicalFishBucketMeta clone(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/tags/CustomItemTagContainer.java b/api/src/main/java/org/bukkit/inventory/meta/tags/CustomItemTagContainer.java deleted file mode 100644 index f46e2978b..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/tags/CustomItemTagContainer.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.bukkit.inventory.meta.tags; - -import org.bukkit.NamespacedKey; -import org.bukkit.inventory.meta.ItemMeta; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * This interface represents a map like object, capable of storing custom tags - * in it. - * - * @deprecated this API part has been replaced by the - * {@link org.bukkit.persistence.PersistentDataHolder} API. Please use - * {@link org.bukkit.persistence.PersistentDataHolder} instead of this. - */ -@Deprecated -public interface CustomItemTagContainer { - - /** - * Stores a custom value on the {@link ItemMeta}. - * - * This API cannot be used to manipulate minecraft tags, as the values will - * be stored using your namespace. This method will override any existing - * value the meta may have stored under the provided key. - * - * @param key the key this value will be stored under - * @param type the type this item tag uses - * @param value the value stored in the tag - * @param the generic java type of the tag value - * @param the generic type of the object to store - * @throws NullPointerException if the key is null - * @throws NullPointerException if the type is null - * @throws NullPointerException if the value is null. Removing a custom tag - * should be done using {@link #removeCustomTag(org.bukkit.NamespacedKey)} - * @throws IllegalArgumentException if no suitable adapter will be found for - * the {@link ItemTagType#getPrimitiveType()} - */ - void setCustomTag(@NotNull NamespacedKey key, @NotNull ItemTagType type, @NotNull Z value); - - /** - * Returns if the item meta has a custom tag registered matching the - * provided parameters. - * - * This method will only return if the found value has the same primitive - * data type as the provided key. - * - * Storing a value using a custom {@link ItemTagType} implementation will - * not store the complex data type. Therefore storing a UUID (by storing a - * byte[]) will match hasCustomTag("key" , {@link ItemTagType#BYTE_ARRAY}). - * Likewise a stored byte[] will always match your UUID {@link ItemTagType} - * even if it is not 16 bytes long. - * - * This method is only usable for custom object keys. Overwriting existing - * tags, like the the display name, will not work as the values are stored - * using your namespace. - * - * @param key the key the value is stored under - * @param type the type which primitive storage type has to match the value - * @param the generic type of the stored primitive - * @param the generic type of the eventually created complex object - * @return if a value - * @throws NullPointerException if the key to look up is null - * @throws NullPointerException if the type to cast the found object to is - * null - */ - boolean hasCustomTag(@NotNull NamespacedKey key, @NotNull ItemTagType type); - - /** - * Returns the custom tag's value that is stored on the item. - * - * @param key the key to look up in the custom tag map - * @param type the type the value must have and will be casted to - * @param the generic type of the stored primitive - * @param the generic type of the eventually created complex object - * @return the value or {@code null} if no value was mapped under the given - * value - * @throws NullPointerException if the key to look up is null - * @throws NullPointerException if the type to cast the found object to is - * null - * @throws IllegalArgumentException if the value exists under the given key, - * but cannot be access using the given type - * @throws IllegalArgumentException if no suitable adapter will be found for - * the {@link ItemTagType#getPrimitiveType()} - */ - @Nullable - Z getCustomTag(@NotNull NamespacedKey key, @NotNull ItemTagType type); - - /** - * Removes a custom key from the item meta. - * - * @param key the key - * @throws NullPointerException if the provided key is null - */ - void removeCustomTag(@NotNull NamespacedKey key); - - /** - * Returns if the container instance is empty, therefore has no entries - * inside it. - * - * @return the boolean - */ - boolean isEmpty(); - - /** - * Returns the adapter context this tag container uses. - * - * @return the tag context - */ - @NotNull - ItemTagAdapterContext getAdapterContext(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/tags/ItemTagAdapterContext.java b/api/src/main/java/org/bukkit/inventory/meta/tags/ItemTagAdapterContext.java deleted file mode 100644 index 97e6c96ef..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/tags/ItemTagAdapterContext.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.inventory.meta.tags; - -import org.bukkit.persistence.PersistentDataAdapterContext; -import org.bukkit.persistence.PersistentDataHolder; -import org.jetbrains.annotations.NotNull; - -/** - * This interface represents the context in which the {@link ItemTagType} can - * serialize and deserialize the passed values. - * - * @deprecated this API part has been replaced by {@link PersistentDataHolder}. - * Please use {@link PersistentDataAdapterContext} instead of this. - */ -@Deprecated -public interface ItemTagAdapterContext { - - /** - * Creates a new and empty tag container instance. - * - * @return the fresh container instance - */ - @NotNull - CustomItemTagContainer newTagContainer(); -} diff --git a/api/src/main/java/org/bukkit/inventory/meta/tags/ItemTagType.java b/api/src/main/java/org/bukkit/inventory/meta/tags/ItemTagType.java deleted file mode 100644 index 09082d481..000000000 --- a/api/src/main/java/org/bukkit/inventory/meta/tags/ItemTagType.java +++ /dev/null @@ -1,157 +0,0 @@ -package org.bukkit.inventory.meta.tags; - -import org.bukkit.persistence.PersistentDataType; -import org.jetbrains.annotations.NotNull; - -/** - * This class represents an enum with a generic content type. It defines the - * types a custom item tag can have. - *

- * This interface can be used to create your own custom {@link ItemTagType} with - * different complex types. This may be useful for the likes of a - * UUIDItemTagType: - *

- * {@code
- * public class UUIDItemTagType implements ItemTagType {
- *
- *         {@literal @Override}
- *         public Class getPrimitiveType() {
- *             return byte[].class;
- *         }
- *
- *         {@literal @Override}
- *         public Class getComplexType() {
- *             return UUID.class;
- *         }
- *
- *         {@literal @Override}
- *         public byte[] toPrimitive(UUID complex, ItemTagAdapterContext context) {
- *             ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
- *             bb.putLong(complex.getMostSignificantBits());
- *             bb.putLong(complex.getLeastSignificantBits());
- *             return bb.array();
- *         }
- *
- *         {@literal @Override}
- *         public UUID fromPrimitive(byte[] primitive, ItemTagAdapterContext context) {
- *             ByteBuffer bb = ByteBuffer.wrap(primitive);
- *             long firstLong = bb.getLong();
- *             long secondLong = bb.getLong();
- *             return new UUID(firstLong, secondLong);
- *         }
- *     }}
- * - * @param the primary object type that is stored in the given tag - * @param the retrieved object type when applying this item tag type - * - * @deprecated please use {@link PersistentDataType} as this part of the api is being replaced - */ -@Deprecated -public interface ItemTagType { - - /* - The primitive one value types. - */ - ItemTagType BYTE = new PrimitiveTagType<>(Byte.class); - ItemTagType SHORT = new PrimitiveTagType<>(Short.class); - ItemTagType INTEGER = new PrimitiveTagType<>(Integer.class); - ItemTagType LONG = new PrimitiveTagType<>(Long.class); - ItemTagType FLOAT = new PrimitiveTagType<>(Float.class); - ItemTagType DOUBLE = new PrimitiveTagType<>(Double.class); - - /* - String. - */ - ItemTagType STRING = new PrimitiveTagType<>(String.class); - - /* - Primitive Arrays. - */ - ItemTagType BYTE_ARRAY = new PrimitiveTagType<>(byte[].class); - ItemTagType INTEGER_ARRAY = new PrimitiveTagType<>(int[].class); - ItemTagType LONG_ARRAY = new PrimitiveTagType<>(long[].class); - - /* - Nested TagContainer. - */ - ItemTagType TAG_CONTAINER = new PrimitiveTagType<>(CustomItemTagContainer.class); - - /** - * Returns the primitive data type of this tag. - * - * @return the class - */ - @NotNull - Class getPrimitiveType(); - - /** - * Returns the complex object type the primitive value resembles. - * - * @return the class type - */ - @NotNull - Class getComplexType(); - - /** - * Returns the primitive data that resembles the complex object passed to - * this method. - * - * @param complex the complex object instance - * @param context the context this operation is running in - * @return the primitive value - */ - @NotNull - T toPrimitive(@NotNull Z complex, @NotNull ItemTagAdapterContext context); - - /** - * Creates a complex object based of the passed primitive value - * - * @param primitive the primitive value - * @param context the context this operation is running in - * @return the complex object instance - */ - @NotNull - Z fromPrimitive(@NotNull T primitive, @NotNull ItemTagAdapterContext context); - - /** - * A default implementation that simply exists to pass on the retrieved or - * inserted value to the next layer. - * - * This implementation does not add any kind of logic, but is used to - * provide default implementations for the primitive types. - * - * @param the generic type of the primitive objects - */ - class PrimitiveTagType implements ItemTagType { - - private final Class primitiveType; - - PrimitiveTagType(@NotNull Class primitiveType) { - this.primitiveType = primitiveType; - } - - @NotNull - @Override - public Class getPrimitiveType() { - return primitiveType; - } - - @NotNull - @Override - public Class getComplexType() { - return primitiveType; - } - - @NotNull - @Override - public T toPrimitive(@NotNull T complex, @NotNull ItemTagAdapterContext context) { - return complex; - } - - @NotNull - @Override - public T fromPrimitive(@NotNull T primitive, @NotNull ItemTagAdapterContext context) { - return primitive; - } - } -} diff --git a/api/src/main/java/org/bukkit/loot/LootContext.java b/api/src/main/java/org/bukkit/loot/LootContext.java deleted file mode 100644 index e307f9fc4..000000000 --- a/api/src/main/java/org/bukkit/loot/LootContext.java +++ /dev/null @@ -1,178 +0,0 @@ -package org.bukkit.loot; - -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.HumanEntity; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents additional information a {@link LootTable} can use to modify it's - * generated loot. - */ -public final class LootContext { - - public static final int DEFAULT_LOOT_MODIFIER = -1; - - private final Location location; - private final float luck; - private final int lootingModifier; - private final Entity lootedEntity; - private final HumanEntity killer; - - private LootContext(@NotNull Location location, float luck, int lootingModifier, @Nullable Entity lootedEntity, @Nullable HumanEntity killer) { - Validate.notNull(location, "LootContext location cannot be null"); - Validate.notNull(location.getWorld(), "LootContext World cannot be null"); - this.location = location; - this.luck = luck; - this.lootingModifier = lootingModifier; - this.lootedEntity = lootedEntity; - this.killer = killer; - } - - /** - * The {@link Location} to store where the loot will be generated. - * - * @return the Location of where the loot will be generated - */ - @NotNull - public Location getLocation() { - return location; - } - - /** - * Represents the {@link org.bukkit.potion.PotionEffectType#LUCK} that an - * entity can have. The higher the value the better chance of receiving more - * loot. - * - * @return luck - */ - public float getLuck() { - return luck; - } - - /** - * Represents the - * {@link org.bukkit.enchantments.Enchantment#LOOT_BONUS_MOBS} the - * {@link #getKiller()} entity has on their equipped item. - * - * This value is only set via - * {@link LootContext.Builder#lootingModifier(int)}. If not set, the - * {@link #getKiller()} entity's looting level will be used instead. - * - * @return the looting level - */ - public int getLootingModifier() { - return lootingModifier; - } - - /** - * Get the {@link Entity} that was killed. Can be null. - * - * @return the looted entity or null - */ - @Nullable - public Entity getLootedEntity() { - return lootedEntity; - } - - /** - * Get the {@link HumanEntity} who killed the {@link #getLootedEntity()}. - * Can be null. - * - * @return the killer entity, or null. - */ - @Nullable - public HumanEntity getKiller() { - return killer; - } - - /** - * Utility class to make building {@link LootContext} easier. The only - * required argument is {@link Location} with a valid (non-null) - * {@link org.bukkit.World}. - */ - public static class Builder { - - private final Location location; - private float luck; - private int lootingModifier = LootContext.DEFAULT_LOOT_MODIFIER; - private Entity lootedEntity; - private HumanEntity killer; - - /** - * Creates a new LootContext.Builder instance to facilitate easy - * creation of {@link LootContext}s. - * - * @param location the location the LootContext should use - */ - public Builder(@NotNull Location location) { - this.location = location; - } - - /** - * Set how much luck to have when generating loot. - * - * @param luck the luck level - * @return the Builder - */ - @NotNull - public Builder luck(float luck) { - this.luck = luck; - return this; - } - - /** - * Set the {@link org.bukkit.enchantments.Enchantment#LOOT_BONUS_MOBS} - * level equivalent to use when generating loot. Values less than or - * equal to 0 will force the {@link LootTable} to only return a single - * {@link org.bukkit.inventory.ItemStack} per pool. - * - * @param modifier the looting level modifier - * @return the Builder - */ - @NotNull - public Builder lootingModifier(int modifier) { - this.lootingModifier = modifier; - return this; - } - - /** - * The entity that was killed. - * - * @param lootedEntity the looted entity - * @return the Builder - */ - @NotNull - public Builder lootedEntity(@Nullable Entity lootedEntity) { - this.lootedEntity = lootedEntity; - return this; - } - - /** - * Set the {@link org.bukkit.entity.HumanEntity} that killed - * {@link #getLootedEntity()}. This entity will be used to get the - * looting level if {@link #lootingModifier(int)} is not set. - * - * @param killer the killer entity - * @return the Builder - */ - @NotNull - public Builder killer(@Nullable HumanEntity killer) { - this.killer = killer; - return this; - } - - /** - * Create a new {@link LootContext} instance using the supplied - * parameters. - * - * @return a new {@link LootContext} instance - */ - @NotNull - public LootContext build() { - return new LootContext(location, luck, lootingModifier, lootedEntity, killer); - } - } -} diff --git a/api/src/main/java/org/bukkit/loot/LootTable.java b/api/src/main/java/org/bukkit/loot/LootTable.java deleted file mode 100644 index 73aa119b6..000000000 --- a/api/src/main/java/org/bukkit/loot/LootTable.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.loot; - -import java.util.Collection; -import java.util.Random; -import org.bukkit.Keyed; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -/** - * LootTables are technical files that represent what items should be in - * naturally generated containers, what items should be dropped when killing a - * mob, or what items can be fished. - * - * See the - * Minecraft Wiki for more information. - */ -public interface LootTable extends Keyed { - - /** - * Returns a mutable list of loot generated by this LootTable. - * - * @param random the random instance to use to generate loot - * @param context context within to populate loot - * @return a list of ItemStacks - */ - @NotNull - Collection populateLoot(@NotNull Random random, @NotNull LootContext context); - - /** - * Attempt to fill an inventory with this LootTable's loot. - * - * @param inventory the inventory to fill - * @param random the random instance to use to generate loot - * @param context context within to populate loot - */ - void fillInventory(@NotNull Inventory inventory, @NotNull Random random, @NotNull LootContext context); -} diff --git a/api/src/main/java/org/bukkit/loot/LootTables.java b/api/src/main/java/org/bukkit/loot/LootTables.java deleted file mode 100644 index 7e8307399..000000000 --- a/api/src/main/java/org/bukkit/loot/LootTables.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.bukkit.loot; - -import org.bukkit.Bukkit; -import org.bukkit.Keyed; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -/** - * This enum holds a list of all known {@link LootTable}s offered by Mojang. - * This list is not guaranteed to be accurate in future versions. - * - * See the - * - * Minecraft Wiki for more information on loot tables. - */ -public enum LootTables implements Keyed { - - EMPTY("empty"), - // Chests/Dispensers - treasure chests - ABANDONED_MINESHAFT("chests/abandoned_mineshaft"), - BURIED_TREASURE("chests/buried_treasure"), - DESERT_PYRAMID("chests/desert_pyramid"), - END_CITY_TREASURE("chests/end_city_treasure"), - IGLOO_CHEST("chests/igloo_chest"), - JUNGLE_TEMPLE("chests/jungle_temple"), - JUNGLE_TEMPLE_DISPENSER("chests/jungle_temple_dispenser"), - NETHER_BRIDGE("chests/nether_bridge"), - PILLAGER_OUTPOST("chests/pillager_outpost"), - SHIPWRECK_MAP("chests/shipwreck_map"), - SHIPWRECK_SUPPLY("chests/shipwreck_supply"), - SHIPWRECK_TREASURE("chests/shipwreck_treasure"), - SIMPLE_DUNGEON("chests/simple_dungeon"), - SPAWN_BONUS_CHEST("chests/spawn_bonus_chest"), - STRONGHOLD_CORRIDOR("chests/stronghold_corridor"), - STRONGHOLD_CROSSING("chests/stronghold_crossing"), - STRONGHOLD_LIBRARY("chests/stronghold_library"), - UNDERWATER_RUIN_BIG("chests/underwater_ruin_big"), - UNDERWATER_RUIN_SMALL("chests/underwater_ruin_small"), - VILLAGE_ARMORER("chests/village/village_armorer"), - VILLAGE_BUTCHER("chests/village/village_butcher"), - VILLAGE_CARTOGRAPHER("chests/village/village_cartographer"), - VILLAGE_DESERT_HOUSE("chests/village/village_desert_house"), - VILLAGE_FISHER("chests/village/village_fisher"), - VILLAGE_FLETCHER("chests/village/village_fletcher"), - VILLAGE_MASON("chests/village/village_mason"), - VILLAGE_PLAINS_HOUSE("chests/village/village_plains_house"), - VILLAGE_SAVANNA_HOUSE("chests/village/village_savanna_house"), - VILLAGE_SHEPHERD("chests/village/village_shepherd"), - VILLAGE_SNOWY_HOUSE("chests/village/village_snowy_house"), - VILLAGE_TAIGA_HOUSE("chests/village/village_taiga_house"), - VILLAGE_TANNERY("chests/village/village_tannery"), - VILLAGE_TEMPLE("chests/village/village_temple"), - VILLAGE_TOOLSMITH("chests/village/village_toolsmith"), - VILLAGE_WEAPONSMITH("chests/village/village_weaponsmith"), - WOODLAND_MANSION("chests/woodland_mansion"), - // Entities - ARMOR_STAND("entities/armor_stand"), - BAT("entities/bat"), - BLAZE("entities/blaze"), - CAT("entities/cat"), - CAVE_SPIDER("entities/cave_spider"), - CHICKEN("entities/chicken"), - COD("entities/cod"), - COW("entities/cow"), - CREEPER("entities/creeper"), - DOLPHIN("entities/dolphin"), - DONKEY("entities/donkey"), - DROWNED("entities/drowned"), - ELDER_GUARDIAN("entities/elder_guardian"), - ENDERMAN("entities/enderman"), - ENDERMITE("entities/endermite"), - ENDER_DRAGON("entities/ender_dragon"), - EVOKER("entities/evoker"), - FOX("entities/fox"), - GHAST("entities/ghast"), - GIANT("entities/giant"), - GUARDIAN("entities/guardian"), - HORSE("entities/horse"), - HUSK("entities/husk"), - ILLUSIONER("entities/illusioner"), - IRON_GOLEM("entities/iron_golem"), - LLAMA("entities/llama"), - MAGMA_CUBE("entities/magma_cube"), - MOOSHROOM("entities/mooshroom"), - MULE("entities/mule"), - OCELOT("entities/ocelot"), - PANDA("entities/panda"), - PARROT("entities/parrot"), - PHANTOM("entities/phantom"), - PIG("entities/pig"), - PILLAGER("entities/pillager"), - POLAR_BEAR("entities/polar_bear"), - PUFFERFISH("entities/pufferfish"), - RABBIT("entities/rabbit"), - RAVAGER("entities/ravager"), - SALMON("entities/salmon"), - // Sheep entry here, moved below for organizational purposes - SHULKER("entities/shulker"), - SILVERFISH("entities/silverfish"), - SKELETON("entities/skeleton"), - SKELETON_HORSE("entities/skeleton_horse"), - SLIME("entities/slime"), - SNOW_GOLEM("entities/snow_golem"), - SPIDER("entities/spider"), - SQUID("entities/squid"), - STRAY("entities/stray"), - TRADER_LLAMA("entities/trader_llama"), - TROPICAL_FISH("entities/tropical_fish"), - TURTLE("entities/turtle"), - VEX("entities/vex"), - VILLAGER("entities/villager"), - VINDICATOR("entities/vindicator"), - WANDERING_TRADER("entities/wandering_trader"), - WITCH("entities/witch"), - WITHER("entities/wither"), - WITHER_SKELETON("entities/wither_skeleton"), - WOLF("entities/wolf"), - ZOMBIE("entities/zombie"), - ZOMBIE_HORSE("entities/zombie_horse"), - ZOMBIE_PIGMAN("entities/zombie_pigman"), - ZOMBIE_VILLAGER("entities/zombie_villager"), - // Gameplay - ARMORER_GIFT("gameplay/hero_of_the_village/armorer_gift"), - BUTCHER_GIFT("gameplay/hero_of_the_village/butcher_gift"), - CARTOGRAPHER_GIFT("gameplay/hero_of_the_village/cartographer_gift"), - CAT_MORNING_GIFT("gameplay/cat_morning_gift"), - CLERIC_GIFT("gameplay/hero_of_the_village/cleric_gift"), - FARMER_GIFT("gameplay/hero_of_the_village/farmer_gift"), - FISHERMAN_GIFT("gameplay/hero_of_the_village/fisherman_gift"), - FISHING("gameplay/fishing"), - FISHING_FISH("gameplay/fishing/fish"), - FISHING_JUNK("gameplay/fishing/junk"), - FISHING_TREASURE("gameplay/fishing/treasure"), - FLETCHER_GIFT("gameplay/hero_of_the_village/fletcher_gift"), - LEATHERWORKER_GIFT("gameplay/hero_of_the_village/leatherworker_gift"), - LIBRARIAN_GIFT("gameplay/hero_of_the_village/librarian_gift"), - MASON_GIFT("gameplay/hero_of_the_village/mason_gift"), - SHEPHERD_GIFT("gameplay/hero_of_the_village/shepherd_gift"), - TOOLSMITH_GIFT("gameplay/hero_of_the_village/toolsmith_gift"), - WEAPONSMITH_GIFT("gameplay/hero_of_the_village/weaponsmith_gift"), - // Sheep - SHEEP("entities/sheep"), - SHEEP_BLACK("entities/sheep/black"), - SHEEP_BLUE("entities/sheep/blue"), - SHEEP_BROWN("entities/sheep/brown"), - SHEEP_CYAN("entities/sheep/cyan"), - SHEEP_GRAY("entities/sheep/gray"), - SHEEP_GREEN("entities/sheep/green"), - SHEEP_LIGHT_BLUE("entities/sheep/light_blue"), - SHEEP_LIGHT_GRAY("entities/sheep/light_gray"), - SHEEP_LIME("entities/sheep/lime"), - SHEEP_MAGENTA("entities/sheep/magenta"), - SHEEP_ORANGE("entities/sheep/orange"), - SHEEP_PINK("entities/sheep/pink"), - SHEEP_PURPLE("entities/sheep/purple"), - SHEEP_RED("entities/sheep/red"), - SHEEP_WHITE("entities/sheep/white"), - SHEEP_YELLOW("entities/sheep/yellow"), - ; - - private final String location; - - private LootTables(/*@NotNull*/ String location) { - this.location = location; - } - - @NotNull - @Override - public NamespacedKey getKey() { - return NamespacedKey.minecraft(location); - } - - /** - * Get the {@link LootTable} corresponding to this constant. This is - * equivalent to calling {@code Bukkit.getLootTable(this.getKey());}. - * - * @return the associated LootTable - */ - @NotNull - public LootTable getLootTable() { - return Bukkit.getLootTable(getKey()); - } -} diff --git a/api/src/main/java/org/bukkit/loot/Lootable.java b/api/src/main/java/org/bukkit/loot/Lootable.java deleted file mode 100644 index 901db8524..000000000 --- a/api/src/main/java/org/bukkit/loot/Lootable.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.bukkit.loot; - -import org.jetbrains.annotations.Nullable; - -/** - * Represents a {@link org.bukkit.block.Container} or a - * {@link org.bukkit.entity.Mob} that can have a loot table. - *
- * Container loot will only generate upon opening, and only when the container - * is first opened. - *
- * Entities will only generate loot upon death. - */ -public interface Lootable { - - /** - * Set the loot table for a container or entity. - *
- * To remove a loot table use null. Do not use {@link LootTables#EMPTY} to - * clear a LootTable. - * - * @param table the Loot Table this {@link org.bukkit.block.Container} or - * {@link org.bukkit.entity.Mob} will have. - */ - void setLootTable(@Nullable LootTable table); - - /** - * Gets the Loot Table attached to this block or entity. - *
- * - * If an block/entity does not have a loot table, this will return null, NOT - * an empty loot table. - * - * @return the Loot Table attached to this block or entity. - */ - @Nullable - LootTable getLootTable(); - - // Paper start - /** - * Set the loot table and seed for a container or entity at the same time. - * - * @param table the Loot Table this {@link org.bukkit.block.Container} or {@link org.bukkit.entity.Mob} will have. - * @param seed the seed to used to generate loot. Default is 0. - */ - default void setLootTable(@Nullable LootTable table, long seed) { - setLootTable(table); - setSeed(seed); - } - - /** - * Returns whether or not this object has a Loot Table - * @return Has a loot table - */ - default boolean hasLootTable() { - return getLootTable() != null; - } - - /** - * Clears the associated Loot Table to this object - */ - default void clearLootTable() { - setLootTable(null); - } - // Paper end - - /** - * Set the seed used when this Loot Table generates loot. - * - * @param seed the seed to used to generate loot. Default is 0. - */ - void setSeed(long seed); - - /** - * Get the Loot Table's seed. - *
- * The seed is used when generating loot. - * - * @return the seed - */ - long getSeed(); -} diff --git a/api/src/main/java/org/bukkit/map/MapCanvas.java b/api/src/main/java/org/bukkit/map/MapCanvas.java deleted file mode 100644 index cc1714019..000000000 --- a/api/src/main/java/org/bukkit/map/MapCanvas.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.map; - -import java.awt.Image; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - @NotNull - public MapView getMapView(); - - /** - * Get the cursor collection associated with this canvas. - * - * @return The MapCursorCollection associated with this canvas. - */ - @NotNull - public 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. - */ - public void setCursors(@NotNull 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}. - */ - public 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}. - */ - public 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}. - */ - public 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. - */ - public void drawImage(int x, int y, @NotNull 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. - */ - public void drawText(int x, int y, @NotNull MapFont font, @NotNull String text); - -} diff --git a/api/src/main/java/org/bukkit/map/MapCursor.java b/api/src/main/java/org/bukkit/map/MapCursor.java deleted file mode 100644 index 29f979945..000000000 --- a/api/src/main/java/org/bukkit/map/MapCursor.java +++ /dev/null @@ -1,289 +0,0 @@ -package org.bukkit.map; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a cursor on a map. - */ -public final class MapCursor { - private byte x, y; - private byte direction, type; - private boolean visible; - private String caption; - - /** - * 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, y, direction, type, visible, null); - } - - /** - * 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. - */ - public MapCursor(byte x, byte y, byte direction, @NotNull Type type, boolean visible) { - this(x, y, direction, type, visible, null); - } - - /** - * 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. - * @param caption cursor caption - * @deprecated Magic value - */ - @Deprecated - public MapCursor(byte x, byte y, byte direction, byte type, boolean visible, @Nullable String caption) { - this.x = x; - this.y = y; - setDirection(direction); - setRawType(type); - this.visible = visible; - this.caption = caption; - } - - /** - * 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. - * @param caption cursor caption - */ - public MapCursor(byte x, byte y, byte direction, @NotNull Type type, boolean visible, @Nullable String caption) { - this.x = x; - this.y = y; - setDirection(direction); - setType(type); - this.visible = visible; - this.caption = caption; - } - - /** - * 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. - */ - @NotNull - public Type getType() { - // It should be impossible to set type to something without appropriate Type, so this shouldn't return null - 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(@NotNull 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 > 26) { - throw new IllegalArgumentException("Type must be in the range 0-26"); - } - this.type = type; - } - - /** - * Set the visibility status of this cursor. - * - * @param visible True if visible. - */ - public void setVisible(boolean visible) { - this.visible = visible; - } - - /** - * Gets the caption on this cursor. - * - * @return caption - */ - @Nullable - public String getCaption() { - return caption; - } - - /** - * Sets the caption on this cursor. - * - * @param caption new caption - */ - public void setCaption(@Nullable String caption) { - this.caption = caption; - } - - /** - * Represents the standard types of map cursors. More may be made - * available by resource packs - the value is used by the client as an - * index in the file './misc/mapicons.png' from minecraft.jar or from a - * resource pack. - */ - public enum Type { - WHITE_POINTER(0), - GREEN_POINTER(1), - RED_POINTER(2), - BLUE_POINTER(3), - WHITE_CROSS(4), - RED_MARKER(5), - WHITE_CIRCLE(6), - SMALL_WHITE_CIRCLE(7), - MANSION(8), - TEMPLE(9), - BANNER_WHITE(10), - BANNER_ORANGE(11), - BANNER_MAGENTA(12), - BANNER_LIGHT_BLUE(13), - BANNER_YELLOW(14), - BANNER_LIME(15), - BANNER_PINK(16), - BANNER_GRAY(17), - BANNER_LIGHT_GRAY(18), - BANNER_CYAN(19), - BANNER_PURPLE(20), - BANNER_BLUE(21), - BANNER_BROWN(22), - BANNER_GREEN(23), - BANNER_RED(24), - BANNER_BLACK(25), - RED_X(26); - - private byte value; - - private 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 - @Nullable - public static Type byValue(byte value) { - for (Type t : values()) { - if (t.value == value) return t; - } - return null; - } - } - -} diff --git a/api/src/main/java/org/bukkit/map/MapCursorCollection.java b/api/src/main/java/org/bukkit/map/MapCursorCollection.java deleted file mode 100644 index 4dba721ae..000000000 --- a/api/src/main/java/org/bukkit/map/MapCursorCollection.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.bukkit.map; - -import java.util.ArrayList; -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 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. - */ - @NotNull - 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(@NotNull MapCursor cursor) { - return cursors.remove(cursor); - } - - /** - * Add a cursor to the collection. - * - * @param cursor The MapCursor to add. - * @return The MapCursor that was passed. - */ - @NotNull - public MapCursor addCursor(@NotNull 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. - */ - @NotNull - 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 - @NotNull - 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 - @NotNull - public MapCursor addCursor(int x, int y, byte direction, byte type, boolean visible) { - return addCursor(new MapCursor((byte) x, (byte) y, direction, type, visible)); - } - - /** - * 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. - * @param caption banner caption - * @return The newly added MapCursor. - * @deprecated Magic value - */ - @Deprecated - @NotNull - public MapCursor addCursor(int x, int y, byte direction, byte type, boolean visible, @Nullable String caption) { - return addCursor(new MapCursor((byte) x, (byte) y, direction, type, visible, caption)); - } -} diff --git a/api/src/main/java/org/bukkit/map/MapFont.java b/api/src/main/java/org/bukkit/map/MapFont.java deleted file mode 100644 index 2d599c8f3..000000000 --- a/api/src/main/java/org/bukkit/map/MapFont.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.bukkit.map; - -import java.util.HashMap; -import org.bukkit.ChatColor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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, @NotNull 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. - */ - @Nullable - 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(@NotNull 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) { - char ch = text.charAt(i); - if (ch == ChatColor.COLOR_CHAR) continue; - result += chars.get(ch).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(@NotNull String text) { - for (int i = 0; i < text.length(); ++i) { - char ch = text.charAt(i); - if (ch == ChatColor.COLOR_CHAR || 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, @NotNull 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/api/src/main/java/org/bukkit/map/MapPalette.java b/api/src/main/java/org/bukkit/map/MapPalette.java deleted file mode 100644 index 8c3016d47..000000000 --- a/api/src/main/java/org/bukkit/map/MapPalette.java +++ /dev/null @@ -1,263 +0,0 @@ -package org.bukkit.map; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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() {} - - @NotNull - private static Color c(int r, int g, int b) { - return new Color(r, g, b); - } - - private static double getDistance(@NotNull Color c1, @NotNull 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; - } - - @NotNull - 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), - c(147, 124, 113), c(180, 152, 138), c(209, 177, 161), c(110, 93, 85), - c(112, 57, 25), c(137, 70, 31), c(159, 82, 36), c(84, 43, 19), - c(105, 61, 76), c(128, 75, 93), c(149, 87, 108), c(78, 46, 57), - c(79, 76, 97), c(96, 93, 119), c(112, 108, 138), c(59, 57, 73), - c(131, 93, 25), c(160, 114, 31), c(186, 133, 36), c(98, 70, 19), - c(72, 82, 37), c(88, 100, 45), c(103, 117, 53), c(54, 61, 28), - c(112, 54, 55), c(138, 66, 67), c(160, 77, 78), c(84, 40, 41), - c(40, 28, 24), c(49, 35, 30), c(57, 41, 35), c(30, 21, 18), - c(95, 75, 69), c(116, 92, 84), c(135, 107, 98), c(71, 56, 51), - c(61, 64, 64), c(75, 79, 79), c(87, 92, 92), c(46, 48, 48), - c(86, 51, 62), c(105, 62, 75), c(122, 73, 88), c(64, 38, 46), - c(53, 43, 64), c(65, 53, 79), c(76, 62, 92), c(40, 32, 48), - c(53, 35, 24), c(65, 43, 30), c(76, 50, 35), c(40, 26, 18), - c(53, 57, 29), c(65, 70, 36), c(76, 82, 42), c(40, 43, 22), - c(100, 42, 32), c(122, 51, 39), c(142, 60, 46), c(75, 31, 24), - c(26, 15, 11), c(31, 18, 13), c(37, 22, 16), c(19, 11, 8) - }; - - // 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. - */ - @NotNull - public static BufferedImage resizeImage(@Nullable 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 - @NotNull - public static byte[] imageToBytes(@NotNull 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(@NotNull 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 - @NotNull - public static Color getColor(byte index) { - if ((index > -49 && 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/api/src/main/java/org/bukkit/map/MapRenderer.java b/api/src/main/java/org/bukkit/map/MapRenderer.java deleted file mode 100644 index cb7040876..000000000 --- a/api/src/main/java/org/bukkit/map/MapRenderer.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.bukkit.map; - -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - public final boolean isContextual() { - return contextual; - } - - /** - * Initialize this MapRenderer for the given map. - * - * @param map The MapView being initialized. - */ - public void initialize(@NotNull 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. - */ - public abstract void render(@NotNull MapView map, @NotNull MapCanvas canvas, @NotNull Player player); - -} diff --git a/api/src/main/java/org/bukkit/map/MapView.java b/api/src/main/java/org/bukkit/map/MapView.java deleted file mode 100644 index 9b8b68b66..000000000 --- a/api/src/main/java/org/bukkit/map/MapView.java +++ /dev/null @@ -1,210 +0,0 @@ -package org.bukkit.map; - -import java.util.List; -import org.bukkit.World; -import org.bukkit.inventory.meta.MapMeta; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Represents a map item. - */ -public interface MapView { - - /** - * An enum representing all possible scales a map can be set to. - */ - public static enum Scale { - CLOSEST(0), - CLOSE(1), - NORMAL(2), - FAR(3), - FARTHEST(4); - - private byte value; - - private 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 - @Nullable - 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 for use with {@link MapMeta}. - * - * @return The ID of the map. - */ - public int getId(); - - /** - * Check whether this map is virtual. A map is virtual if its lowermost - * MapRenderer is plugin-provided. - * - * @return Whether the map is virtual. - */ - public boolean isVirtual(); - - /** - * Get the scale of this map. - * - * @return The scale of the map. - */ - @NotNull - public Scale getScale(); - - /** - * Set the scale of this map. - * - * @param scale The scale to set. - */ - public void setScale(@NotNull Scale scale); - - /** - * Get the center X position of this map. - * - * @return The center X position. - */ - public int getCenterX(); - - /** - * Get the center Z position of this map. - * - * @return The center Z position. - */ - public int getCenterZ(); - - /** - * Set the center X position of this map. - * - * @param x The center X position. - */ - public void setCenterX(int x); - - /** - * Set the center Z position of this map. - * - * @param z The center Z position. - */ - public 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. - */ - @Nullable - public 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. - */ - public void setWorld(@NotNull World world); - - /** - * Get a list of MapRenderers currently in effect. - * - * @return A {@code List} containing each map renderer. - */ - @NotNull - public List getRenderers(); - - /** - * Add a renderer to this map. - * - * @param renderer The MapRenderer to add. - */ - public void addRenderer(@NotNull MapRenderer renderer); - - /** - * Remove a renderer from this map. - * - * @param renderer The MapRenderer to remove. - * @return True if the renderer was successfully removed. - */ - public boolean removeRenderer(@Nullable MapRenderer renderer); - - /** - * Gets whether a position cursor should be shown when the map is near its - * center. - * - * @return tracking status - */ - boolean isTrackingPosition(); - - /** - * Sets whether a position cursor should be shown when the map is near its - * center. - * - * @param trackingPosition tracking status - */ - void setTrackingPosition(boolean trackingPosition); - - /** - * Whether the map will show a smaller position cursor (true), or no - * position cursor (false) when cursor is outside of map's range. - * - * @return unlimited tracking state - */ - boolean isUnlimitedTracking(); - - /** - * Whether the map will show a smaller position cursor (true), or no - * position cursor (false) when cursor is outside of map's range. - * - * @param unlimited tracking state - */ - void setUnlimitedTracking(boolean unlimited); - - /** - * Gets whether the map is locked or not. - * - * A locked map may not be explored further. - * - * @return lock status - */ - boolean isLocked(); - - /** - * Gets whether the map is locked or not. - * - * A locked map may not be explored further. - * - * @param locked status - */ - void setLocked(boolean locked); -} diff --git a/api/src/main/java/org/bukkit/map/MinecraftFont.java b/api/src/main/java/org/bukkit/map/MinecraftFont.java deleted file mode 100644 index e1c8acc77..000000000 --- a/api/src/main/java/org/bukkit/map/MinecraftFont.java +++ /dev/null @@ -1,331 +0,0 @@ -package org.bukkit.map; - -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - @NotNull - 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/api/src/main/java/org/bukkit/material/Attachable.java b/api/src/main/java/org/bukkit/material/Attachable.java deleted file mode 100644 index 16abdbf92..000000000 --- a/api/src/main/java/org/bukkit/material/Attachable.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.block.BlockFace; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public BlockFace getAttachedFace(); -} diff --git a/api/src/main/java/org/bukkit/material/Banner.java b/api/src/main/java/org/bukkit/material/Banner.java deleted file mode 100644 index 02d5fb67f..000000000 --- a/api/src/main/java/org/bukkit/material/Banner.java +++ /dev/null @@ -1,224 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Banner extends MaterialData implements Attachable { - - public Banner() { - super(Material.LEGACY_BANNER); - } - - public Banner(Material 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); - } - - public boolean isWallBanner() { - return getItemType() == Material.LEGACY_WALL_BANNER; - } - - @Override - 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; - } - } - - @Override - 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(); - } - } - - @Override - 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/api/src/main/java/org/bukkit/material/Bed.java b/api/src/main/java/org/bukkit/material/Bed.java deleted file mode 100644 index c5256129e..000000000 --- a/api/src/main/java/org/bukkit/material/Bed.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a bed. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Bed extends MaterialData implements Directional { - - /** - * Default constructor for a bed. - */ - public Bed() { - super(Material.LEGACY_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); - } - - public Bed(final Material type) { - super(type); - } - - /** - * @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. - */ - @Override - 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 - */ - @Override - 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/api/src/main/java/org/bukkit/material/Button.java b/api/src/main/java/org/bukkit/material/Button.java deleted file mode 100644 index da7d016cf..000000000 --- a/api/src/main/java/org/bukkit/material/Button.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a button - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Button extends SimpleAttachableMaterialData implements Redstone { - public Button() { - super(Material.LEGACY_STONE_BUTTON); - } - - public Button(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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/api/src/main/java/org/bukkit/material/Cake.java b/api/src/main/java/org/bukkit/material/Cake.java deleted file mode 100644 index d39dd4916..000000000 --- a/api/src/main/java/org/bukkit/material/Cake.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Cake extends MaterialData { - public Cake() { - super(Material.LEGACY_CAKE_BLOCK); - } - - public Cake(Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/Cauldron.java b/api/src/main/java/org/bukkit/material/Cauldron.java deleted file mode 100644 index f998396c3..000000000 --- a/api/src/main/java/org/bukkit/material/Cauldron.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents a cauldron - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Cauldron extends MaterialData { - private static final int CAULDRON_FULL = 3; - private static final int CAULDRON_EMPTY = 0; - - public Cauldron() { - super(Material.LEGACY_CAULDRON); - } - - /** - * - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Cauldron(final Material type, final byte data) { - super(type, data); - } - - /** - * - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Cauldron(byte data) { - super(Material.LEGACY_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/api/src/main/java/org/bukkit/material/Chest.java b/api/src/main/java/org/bukkit/material/Chest.java deleted file mode 100644 index 4d120d3c3..000000000 --- a/api/src/main/java/org/bukkit/material/Chest.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a chest - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Chest extends DirectionalContainer { - - public Chest() { - super(Material.LEGACY_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); - } - - public Chest(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/Coal.java b/api/src/main/java/org/bukkit/material/Coal.java deleted file mode 100644 index fb842cfa7..000000000 --- a/api/src/main/java/org/bukkit/material/Coal.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.CoalType; -import org.bukkit.Material; - -/** - * Represents the different types of coals. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Coal extends MaterialData { - public Coal() { - super(Material.LEGACY_COAL); - } - - public Coal(CoalType type) { - this(); - setType(type); - } - - public Coal(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/CocoaPlant.java b/api/src/main/java/org/bukkit/material/CocoaPlant.java deleted file mode 100644 index b1b1c729d..000000000 --- a/api/src/main/java/org/bukkit/material/CocoaPlant.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents the cocoa plant - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class CocoaPlant extends MaterialData implements Directional, Attachable { - - public enum CocoaPlantSize { - SMALL, - MEDIUM, - LARGE - } - - public CocoaPlant() { - super(Material.LEGACY_COCOA); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public CocoaPlant(final Material 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); - } - - @Override - public BlockFace getAttachedFace() { - return getFacing().getOppositeFace(); - } - - @Override - 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); - } - - @Override - 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/api/src/main/java/org/bukkit/material/Colorable.java b/api/src/main/java/org/bukkit/material/Colorable.java deleted file mode 100644 index 7f495e052..000000000 --- a/api/src/main/java/org/bukkit/material/Colorable.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.DyeColor; -import org.bukkit.UndefinedNullability; -import org.jetbrains.annotations.Nullable; - -/** - * An object that can be colored. - */ -public interface Colorable { - - /** - * Gets the color of this object. - *
- * This may be null to represent the default color of an object, if the - * object has a special default color (e.g Shulkers). - * - * @return The DyeColor of this object. - */ - @Nullable - public DyeColor getColor(); - - /** - * Sets the color of this object to the specified DyeColor. - *
- * This may be null to represent the default color of an object, if the - * object has a special default color (e.g Shulkers). - * - * @param color The color of the object, as a DyeColor. - * @throws NullPointerException if argument is null and this implementation does not support null - */ - public void setColor(@UndefinedNullability("defined by subclass") DyeColor color); - -} diff --git a/api/src/main/java/org/bukkit/material/Command.java b/api/src/main/java/org/bukkit/material/Command.java deleted file mode 100644 index bcac1b082..000000000 --- a/api/src/main/java/org/bukkit/material/Command.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents a command block - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Command extends MaterialData implements Redstone { - public Command() { - super(Material.LEGACY_COMMAND); - } - - public Command(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - 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/api/src/main/java/org/bukkit/material/Comparator.java b/api/src/main/java/org/bukkit/material/Comparator.java deleted file mode 100644 index 49d32d544..000000000 --- a/api/src/main/java/org/bukkit/material/Comparator.java +++ /dev/null @@ -1,185 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a comparator in the on or off state, in normal or subtraction mode and facing in a specific direction. - * - * @see Material#LEGACY_REDSTONE_COMPARATOR_OFF - * @see Material#LEGACY_REDSTONE_COMPARATOR_ON - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Comparator extends MaterialData implements Directional, Redstone { - protected static final BlockFace DEFAULT_DIRECTION = BlockFace.NORTH; - protected static final boolean DEFAULT_SUBTRACTION_MODE = false; - protected static final boolean DEFAULT_STATE = false; - - /** - * Constructs a comparator switched off, with the default mode (normal) and facing the default direction (north). - */ - public Comparator() { - this(DEFAULT_DIRECTION, DEFAULT_SUBTRACTION_MODE, false); - } - - /** - * Constructs a comparator switched off, with the default mode (normal) and facing the specified direction. - * - * @param facingDirection the direction the comparator is facing - * - * @see BlockFace - */ - public Comparator(BlockFace facingDirection) { - this(facingDirection, DEFAULT_SUBTRACTION_MODE, DEFAULT_STATE); - } - - /** - * Constructs a comparator switched off, with the specified mode and facing the specified direction. - * - * @param facingDirection the direction the comparator is facing - * @param isSubtraction True if the comparator is in subtraction mode, false for normal comparator operation - * - * @see BlockFace - */ - public Comparator(BlockFace facingDirection, boolean isSubtraction) { - this(facingDirection, isSubtraction, DEFAULT_STATE); - } - - /** - * Constructs a comparator switched on or off, with the specified mode and facing the specified direction. - * - * @param facingDirection the direction the comparator is facing - * @param isSubtraction True if the comparator is in subtraction mode, false for normal comparator operation - * @param state True if the comparator is in the on state - * - * @see BlockFace - */ - public Comparator(BlockFace facingDirection, boolean isSubtraction, boolean state) { - super(state ? Material.LEGACY_REDSTONE_COMPARATOR_ON : Material.LEGACY_REDSTONE_COMPARATOR_OFF); - setFacingDirection(facingDirection); - setSubtractionMode(isSubtraction); - } - - public Comparator(Material type) { - super(type); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Comparator(Material type, byte data) { - super(type, data); - } - - /** - * Sets whether the comparator is in subtraction mode. - * - * @param isSubtraction True if the comparator is in subtraction mode, false for normal comparator operation - */ - public void setSubtractionMode(boolean isSubtraction) { - setData((byte) (getData() & 0xB | (isSubtraction ? 0x4 : 0x0))); - } - - /** - * Checks whether the comparator is in subtraction mode - * - * @return True if the comparator is in subtraction mode, false if normal comparator operation - */ - public boolean isSubtractionMode() { - return (getData() & 0x4) != 0; - } - - /** - * Sets the direction this comparator is facing - * - * @param face The direction to set this comparator to - * - * @see BlockFace - */ - @Override - public void setFacingDirection(BlockFace face) { - int data = getData() & 0xC; - - switch (face) { - case EAST: - data |= 0x1; - break; - - case SOUTH: - data |= 0x2; - break; - - case WEST: - data |= 0x3; - break; - - case NORTH: - default: - data |= 0x0; - } - - setData((byte) data); - } - - /** - * Gets the direction this comparator is facing - * - * @return The direction this comparator is facing - * - * @see BlockFace - */ - @Override - 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() + " in " + (isSubtractionMode() ? "subtraction" : "comparator") + " mode"; - } - - @Override - public Comparator clone() { - return (Comparator) super.clone(); - } - - /** - * Checks if the comparator is powered - * - * @return true if the comparator is powered - */ - @Override - public boolean isPowered() { - return getItemType() == Material.LEGACY_REDSTONE_COMPARATOR_ON; - } - - /** - * Checks if the comparator is being powered - * - * @return true if the comparator is being powered - */ - public boolean isBeingPowered() { - return (getData() & 0x8) != 0; - } -} diff --git a/api/src/main/java/org/bukkit/material/Crops.java b/api/src/main/java/org/bukkit/material/Crops.java deleted file mode 100644 index 4cf3de5fb..000000000 --- a/api/src/main/java/org/bukkit/material/Crops.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.CropState; -import org.bukkit.Material; - -/** - * Represents the different types of crops in different states of growth. - * - * @see Material#LEGACY_CROPS - * @see Material#LEGACY_CARROT - * @see Material#LEGACY_POTATO - * @see Material#LEGACY_BEETROOT_BLOCK - * @see Material#LEGACY_NETHER_WARTS - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Crops extends MaterialData { - protected static final Material DEFAULT_TYPE = Material.LEGACY_CROPS; - protected static final CropState DEFAULT_STATE = CropState.SEEDED; - - /** - * Constructs a wheat crop block in the seeded state. - */ - public Crops() { - this(DEFAULT_TYPE, DEFAULT_STATE); - } - - /** - * Constructs a wheat crop block in the given growth state - * - * @param state The growth state of the crops - */ - public Crops(CropState state) { - this(DEFAULT_TYPE, state); - setState(state); - } - - /** - * Constructs a crop block of the given type and in the given growth state - * - * @param type The type of crops - * @param state The growth state of the crops - */ - public Crops(final Material type, final CropState state) { - super(type); - setState(state); - } - - /** - * Constructs a crop block of the given type and in the seeded state - * - * @param type The type of crops - */ - public Crops(final Material type) { - this(type, DEFAULT_STATE); - } - - /** - * @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 - * - * For crops with only four growth states such as beetroot, only the values SEEDED, SMALL, TALL and RIPE will be - * returned. - * - * @return CropState of this crop - */ - public CropState getState() { - switch (getItemType()) { - case LEGACY_CROPS: - case LEGACY_CARROT: - case LEGACY_POTATO: - // Mask the data just in case top bit set - return CropState.getByData((byte) (getData() & 0x7)); - case LEGACY_BEETROOT_BLOCK: - case LEGACY_NETHER_WARTS: - // Mask the data just in case top bits are set - // Will return SEEDED, SMALL, TALL, RIPE for the three growth data values - return CropState.getByData((byte) (((getData() & 0x3) * 7 + 2) / 3)); - default: - throw new IllegalArgumentException("Block type is not a crop"); - } - } - - /** - * Sets the growth state of this crop - * - * For crops with only four growth states such as beetroot, the 8 CropStates are mapped into four states: - * - * SEEDED, SMALL, TALL and RIPE - * - * GERMINATED will change to SEEDED - * VERY_SMALL will change to SMALL - * MEDIUM will change to TALL - * VERY_TALL will change to RIPE - * - * @param state New growth state of this crop - */ - public void setState(CropState state) { - switch (getItemType()) { - case LEGACY_CROPS: - case LEGACY_CARROT: - case LEGACY_POTATO: - // Preserve the top bit in case it is set - setData((byte) ((getData() & 0x8) | state.getData())); - break; - case LEGACY_NETHER_WARTS: - case LEGACY_BEETROOT_BLOCK: - // Preserve the top bits in case they are set - setData((byte) ((getData() & 0xC) | (state.getData() >> 1))); - break; - default: - throw new IllegalArgumentException("Block type is not a crop"); - } - } - - @Override - public String toString() { - return getState() + " " + super.toString(); - } - - @Override - public Crops clone() { - return (Crops) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/DetectorRail.java b/api/src/main/java/org/bukkit/material/DetectorRail.java deleted file mode 100644 index e8ab29042..000000000 --- a/api/src/main/java/org/bukkit/material/DetectorRail.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents a detector rail - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class DetectorRail extends ExtendedRails implements PressureSensor { - public DetectorRail() { - super(Material.LEGACY_DETECTOR_RAIL); - } - - public DetectorRail(final Material type) { - super(type); - } - - /** - * @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); - } - - @Override - 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/api/src/main/java/org/bukkit/material/Diode.java b/api/src/main/java/org/bukkit/material/Diode.java deleted file mode 100644 index 36a62258b..000000000 --- a/api/src/main/java/org/bukkit/material/Diode.java +++ /dev/null @@ -1,194 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a diode/repeater in the on or off state, with a delay and facing - * in a specific direction. - * - * @see Material#LEGACY_DIODE_BLOCK_OFF - * @see Material#LEGACY_DIODE_BLOCK_ON - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Diode extends MaterialData implements Directional, Redstone { - - protected static final BlockFace DEFAULT_DIRECTION = BlockFace.NORTH; - protected static final int DEFAULT_DELAY = 1; - protected static final boolean DEFAULT_STATE = false; - - /** - * Constructs a diode switched on, with a delay of 1 and facing the default - * direction (north). - * - * By default this constructor creates a diode that is switched on for - * backwards compatibility with past implementations. - */ - public Diode() { - this(DEFAULT_DIRECTION, DEFAULT_DELAY, true); - } - - /** - * Constructs a diode switched off, with a delay of 1 and facing the - * specified direction. - * - * @param facingDirection the direction the diode is facing - * - * @see BlockFace - */ - public Diode(BlockFace facingDirection) { - this(facingDirection, DEFAULT_DELAY, DEFAULT_STATE); - } - - /** - * Constructs a diode switched off, with the specified delay and facing the - * specified direction. - * - * @param facingDirection the direction the diode is facing - * @param delay The number of ticks (1-4) before the diode turns on after - * being powered - * - * @see BlockFace - */ - public Diode(BlockFace facingDirection, int delay) { - this(facingDirection, delay, DEFAULT_STATE); - } - - /** - * Constructs a diode switched on or off, with the specified delay and - * facing the specified direction. - * - * @param facingDirection the direction the diode is facing - * @param delay The number of ticks (1-4) before the diode turns on after - * being powered - * @param state True if the diode is in the on state - * - * @see BlockFace - */ - public Diode(BlockFace facingDirection, int delay, boolean state) { - super(state ? Material.LEGACY_DIODE_BLOCK_ON : Material.LEGACY_DIODE_BLOCK_OFF); - setFacingDirection(facingDirection); - setDelay(delay); - } - - public Diode(Material type) { - super(type); - } - - /** - * @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; - } - - /** - * Sets the direction this diode is facing. - * - * @param face The direction to set this diode to - * - * @see BlockFace - */ - @Override - 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); - } - - /** - * Gets the direction this diode is facing - * - * @return The direction this diode is facing - * - * @see BlockFace - */ - @Override - 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(); - } - - /** - * Checks if the diode is powered. - * - * @return true if the diode is powered - */ - @Override - public boolean isPowered() { - return getItemType() == Material.LEGACY_DIODE_BLOCK_ON; - } -} diff --git a/api/src/main/java/org/bukkit/material/Directional.java b/api/src/main/java/org/bukkit/material/Directional.java deleted file mode 100644 index 8c1c7b0a2..000000000 --- a/api/src/main/java/org/bukkit/material/Directional.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.block.BlockFace; -import org.jetbrains.annotations.NotNull; - -public interface Directional { - - /** - * Sets the direction that this block is facing in - * - * @param face The facing direction - */ - public void setFacingDirection(@NotNull BlockFace face); - - /** - * Gets the direction this block is facing - * - * @return the direction this block is facing - */ - @NotNull - public BlockFace getFacing(); -} diff --git a/api/src/main/java/org/bukkit/material/DirectionalContainer.java b/api/src/main/java/org/bukkit/material/DirectionalContainer.java deleted file mode 100644 index 0190e5f3d..000000000 --- a/api/src/main/java/org/bukkit/material/DirectionalContainer.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a furnace or a dispenser. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class DirectionalContainer extends MaterialData implements Directional { - - public DirectionalContainer(final Material type) { - super(type); - } - - /** - * @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); - } - - @Override - 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); - } - - @Override - 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/api/src/main/java/org/bukkit/material/Dispenser.java b/api/src/main/java/org/bukkit/material/Dispenser.java deleted file mode 100644 index b12993a93..000000000 --- a/api/src/main/java/org/bukkit/material/Dispenser.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a dispenser. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Dispenser extends FurnaceAndDispenser { - - public Dispenser() { - super(Material.LEGACY_DISPENSER); - } - - public Dispenser(BlockFace direction) { - this(); - setFacingDirection(direction); - } - - public Dispenser(final Material type) { - super(type); - } - - /** - * @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); - } - - @Override - 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); - } - - @Override - 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/api/src/main/java/org/bukkit/material/Door.java b/api/src/main/java/org/bukkit/material/Door.java deleted file mode 100644 index d04ece5ab..000000000 --- a/api/src/main/java/org/bukkit/material/Door.java +++ /dev/null @@ -1,327 +0,0 @@ -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#LEGACY_WOODEN_DOOR - * @see Material#LEGACY_IRON_DOOR_BLOCK - * @see Material#LEGACY_SPRUCE_DOOR - * @see Material#LEGACY_BIRCH_DOOR - * @see Material#LEGACY_JUNGLE_DOOR - * @see Material#LEGACY_ACACIA_DOOR - * @see Material#LEGACY_DARK_OAK_DOOR - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -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.LEGACY_WOODEN_DOOR); - */ - @Deprecated - public Door() { - super(Material.LEGACY_WOODEN_DOOR); - } - - 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#LEGACY_WOODEN_DOOR - * @see Material#LEGACY_IRON_DOOR_BLOCK - * @see Material#LEGACY_SPRUCE_DOOR - * @see Material#LEGACY_BIRCH_DOOR - * @see Material#LEGACY_JUNGLE_DOOR - * @see Material#LEGACY_ACACIA_DOOR - * @see Material#LEGACY_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#LEGACY_WOODEN_DOOR - * @see Material#LEGACY_IRON_DOOR_BLOCK - * @see Material#LEGACY_SPRUCE_DOOR - * @see Material#LEGACY_BIRCH_DOOR - * @see Material#LEGACY_JUNGLE_DOOR - * @see Material#LEGACY_ACACIA_DOOR - * @see Material#LEGACY_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#LEGACY_WOODEN_DOOR - * @see Material#LEGACY_IRON_DOOR_BLOCK - * @see Material#LEGACY_SPRUCE_DOOR - * @see Material#LEGACY_BIRCH_DOOR - * @see Material#LEGACY_JUNGLE_DOOR - * @see Material#LEGACY_ACACIA_DOOR - * @see Material#LEGACY_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 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#LEGACY_WOODEN_DOOR - * @see Material#LEGACY_SPRUCE_DOOR - * @see Material#LEGACY_BIRCH_DOOR - * @see Material#LEGACY_JUNGLE_DOOR - * @see Material#LEGACY_ACACIA_DOOR - * @see Material#LEGACY_DARK_OAK_DOOR - */ - public static Material getWoodDoorOfSpecies(TreeSpecies species) { - switch (species) { - default: - case GENERIC: - return Material.LEGACY_WOODEN_DOOR; - case BIRCH: - return Material.LEGACY_BIRCH_DOOR; - case REDWOOD: - return Material.LEGACY_SPRUCE_DOOR; - case JUNGLE: - return Material.LEGACY_JUNGLE_DOOR; - case ACACIA: - return Material.LEGACY_ACACIA_DOOR; - case DARK_OAK: - return Material.LEGACY_DARK_OAK_DOOR; - } - } - - /** - * Result is undefined if isTopHalf() is true. - */ - @Override - public boolean isOpen() { - return ((getData() & 0x4) == 0x4); - } - - /** - * Set whether the door is open. Undefined if isTopHalf() is true. - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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/api/src/main/java/org/bukkit/material/Dye.java b/api/src/main/java/org/bukkit/material/Dye.java deleted file mode 100644 index f34f23da7..000000000 --- a/api/src/main/java/org/bukkit/material/Dye.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.DyeColor; -import org.bukkit.Material; - -/** - * Represents dye - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Dye extends MaterialData implements Colorable { - public Dye() { - super(Material.LEGACY_INK_SACK); - } - - public Dye(final Material type) { - super(type); - } - - /** - * @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.LEGACY_INK_SACK, color.getDyeData()); - } - - /** - * Gets the current color of this dye - * - * @return DyeColor of this dye - */ - @Override - public DyeColor getColor() { - return DyeColor.getByDyeData(getData()); - } - - /** - * Sets the color of this dye - * - * @param color New color of this dye - */ - @Override - 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/api/src/main/java/org/bukkit/material/EnderChest.java b/api/src/main/java/org/bukkit/material/EnderChest.java deleted file mode 100644 index ad232cacd..000000000 --- a/api/src/main/java/org/bukkit/material/EnderChest.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents an ender chest - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class EnderChest extends DirectionalContainer { - - public EnderChest() { - super(Material.LEGACY_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); - } - - public EnderChest(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/ExtendedRails.java b/api/src/main/java/org/bukkit/material/ExtendedRails.java deleted file mode 100644 index 5f70e5bde..000000000 --- a/api/src/main/java/org/bukkit/material/ExtendedRails.java +++ /dev/null @@ -1,61 +0,0 @@ -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 - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class ExtendedRails extends Rails { - - public ExtendedRails(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/FlowerPot.java b/api/src/main/java/org/bukkit/material/FlowerPot.java deleted file mode 100644 index 8aa6918e6..000000000 --- a/api/src/main/java/org/bukkit/material/FlowerPot.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.GrassSpecies; -import org.bukkit.Material; -import org.bukkit.TreeSpecies; - -/** - * Represents a flower pot. - * - * @deprecated Flower pots are now tile entities, use - * {@link org.bukkit.block.FlowerPot}. - */ -@Deprecated -public class FlowerPot extends MaterialData { - - /** - * Default constructor for a flower pot. - */ - public FlowerPot() { - super(Material.LEGACY_FLOWER_POT); - } - - public FlowerPot(final Material type) { - super(type); - } - - /** - * @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.LEGACY_RED_ROSE); - case 2: - return new MaterialData(Material.LEGACY_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.LEGACY_RED_MUSHROOM); - case 8: - return new MaterialData(Material.LEGACY_BROWN_MUSHROOM); - case 9: - return new MaterialData(Material.LEGACY_CACTUS); - case 10: - return new MaterialData(Material.LEGACY_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.LEGACY_RED_ROSE) { - setData((byte) 1); - } else if (mat == Material.LEGACY_YELLOW_FLOWER) { - setData((byte) 2); - } else if (mat == Material.LEGACY_RED_MUSHROOM) { - setData((byte) 7); - } else if (mat == Material.LEGACY_BROWN_MUSHROOM) { - setData((byte) 8); - } else if (mat == Material.LEGACY_CACTUS) { - setData((byte) 9); - } else if (mat == Material.LEGACY_DEAD_BUSH) { - setData((byte) 10); - } else if (mat == Material.LEGACY_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.LEGACY_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/api/src/main/java/org/bukkit/material/Furnace.java b/api/src/main/java/org/bukkit/material/Furnace.java deleted file mode 100644 index 380f7f4b1..000000000 --- a/api/src/main/java/org/bukkit/material/Furnace.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a furnace. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Furnace extends FurnaceAndDispenser { - - public Furnace() { - super(Material.LEGACY_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); - } - - public Furnace(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/FurnaceAndDispenser.java b/api/src/main/java/org/bukkit/material/FurnaceAndDispenser.java deleted file mode 100644 index effa0d8a9..000000000 --- a/api/src/main/java/org/bukkit/material/FurnaceAndDispenser.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents a furnace or dispenser, two types of directional containers - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class FurnaceAndDispenser extends DirectionalContainer { - - public FurnaceAndDispenser(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/Gate.java b/api/src/main/java/org/bukkit/material/Gate.java deleted file mode 100644 index fc67fc59a..000000000 --- a/api/src/main/java/org/bukkit/material/Gate.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a fence gate - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -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.LEGACY_FENCE_GATE); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Gate(final Material type, final byte data) { - super(type, data); - } - - public Gate(byte data) { - super(Material.LEGACY_FENCE_GATE, data); - } - - @Override - 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); - } - - @Override - 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; - } - - @Override - public boolean isOpen() { - return (getData() & OPEN_BIT) > 0; - } - - @Override - 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(); - } -} diff --git a/api/src/main/java/org/bukkit/material/Hopper.java b/api/src/main/java/org/bukkit/material/Hopper.java deleted file mode 100644 index cfd32666c..000000000 --- a/api/src/main/java/org/bukkit/material/Hopper.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a hopper in an active or deactivated state and facing in a - * specific direction. - * - * @see Material#HOPPER - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Hopper extends MaterialData implements Directional, Redstone { - - protected static final BlockFace DEFAULT_DIRECTION = BlockFace.DOWN; - protected static final boolean DEFAULT_ACTIVE = true; - - /** - * Constructs a hopper facing the default direction (down) and initially - * active. - */ - public Hopper() { - this(DEFAULT_DIRECTION, DEFAULT_ACTIVE); - } - - /** - * Constructs a hopper facing the specified direction and initially active. - * - * @param facingDirection the direction the hopper is facing - * - * @see BlockFace - */ - public Hopper(BlockFace facingDirection) { - this(facingDirection, DEFAULT_ACTIVE); - } - - /** - * Constructs a hopper facing the specified direction and either active or - * not. - * - * @param facingDirection the direction the hopper is facing - * @param isActive True if the hopper is initially active, false if - * deactivated - * - * @see BlockFace - */ - public Hopper(BlockFace facingDirection, boolean isActive) { - super(Material.LEGACY_HOPPER); - setFacingDirection(facingDirection); - setActive(isActive); - } - - public Hopper(Material type) { - super(type); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Hopper(Material type, byte data) { - super(type, data); - } - - /** - * Sets whether the hopper is active or not. - * - * @param isActive True if the hopper is active, false if deactivated as if - * powered by redstone - */ - public void setActive(boolean isActive) { - setData((byte) (getData() & 0x7 | (isActive ? 0x0 : 0x8))); - } - - /** - * Checks whether the hopper is active or not. - * - * @return True if the hopper is active, false if deactivated - */ - public boolean isActive() { - return (getData() & 0x8) == 0; - } - - /** - * Sets the direction this hopper is facing - * - * @param face The direction to set this hopper to - * - * @see BlockFace - */ - @Override - public void setFacingDirection(BlockFace face) { - int data = getData() & 0x8; - - switch (face) { - case DOWN: - data |= 0x0; - break; - case NORTH: - data |= 0x2; - break; - case SOUTH: - data |= 0x3; - break; - case WEST: - data |= 0x4; - break; - case EAST: - data |= 0x5; - break; - } - - setData((byte) data); - } - - /** - * Gets the direction this hopper is facing - * - * @return The direction this hopper is facing - * - * @see BlockFace - */ - @Override - public BlockFace getFacing() { - byte data = (byte) (getData() & 0x7); - - switch (data) { - default: - case 0x0: - return BlockFace.DOWN; - case 0x2: - return BlockFace.NORTH; - case 0x3: - return BlockFace.SOUTH; - case 0x4: - return BlockFace.WEST; - case 0x5: - return BlockFace.EAST; - } - } - - @Override - public String toString() { - return super.toString() + " facing " + getFacing(); - } - - @Override - public Hopper clone() { - return (Hopper) super.clone(); - } - - /** - * Checks if the hopper is powered. - * - * @return true if the hopper is powered - */ - @Override - public boolean isPowered() { - return (getData() & 0x8) != 0; - } -} diff --git a/api/src/main/java/org/bukkit/material/Ladder.java b/api/src/main/java/org/bukkit/material/Ladder.java deleted file mode 100644 index de2635308..000000000 --- a/api/src/main/java/org/bukkit/material/Ladder.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents Ladder data - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Ladder extends SimpleAttachableMaterialData { - public Ladder() { - super(Material.LEGACY_LADDER); - } - - public Ladder(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - 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 - */ - @Override - 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/api/src/main/java/org/bukkit/material/Leaves.java b/api/src/main/java/org/bukkit/material/Leaves.java deleted file mode 100644 index 923a794ac..000000000 --- a/api/src/main/java/org/bukkit/material/Leaves.java +++ /dev/null @@ -1,141 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.TreeSpecies; - -/** - * Represents the different types of leaf block that may be permanent or can - * decay when too far from a log. - * - * @see Material#LEGACY_LEAVES - * @see Material#LEGACY_LEAVES_2 - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Leaves extends Wood { - protected static final Material DEFAULT_TYPE = Material.LEGACY_LEAVES; - protected static final boolean DEFAULT_DECAYABLE = true; - - /** - * Constructs a leaf block. - */ - public Leaves() { - this(DEFAULT_TYPE, DEFAULT_SPECIES, DEFAULT_DECAYABLE); - } - - /** - * Constructs a leaf block of the given tree species. - * - * @param species the species of the wood block - */ - public Leaves(TreeSpecies species) { - this(DEFAULT_TYPE, species, DEFAULT_DECAYABLE); - } - - /** - * Constructs a leaf block of the given tree species and flag for whether - * this leaf block will disappear when too far from a log. - * - * @param species the species of the wood block - * @param isDecayable whether the block is permanent or can disappear - */ - public Leaves(TreeSpecies species, boolean isDecayable) { - this(DEFAULT_TYPE, species, isDecayable); - } - - /** - * Constructs a leaf block of the given type. - * - * @param type the type of leaf block - */ - public Leaves(final Material type) { - this(type, DEFAULT_SPECIES, DEFAULT_DECAYABLE); - } - - /** - * Constructs a leaf block of the given type and tree species. - * - * @param type the type of leaf block - * @param species the species of the wood block - */ - public Leaves(final Material type, TreeSpecies species) { - this(type, species, DEFAULT_DECAYABLE); - } - - /** - * Constructs a leaf block of the given type and tree species and flag for - * whether this leaf block will disappear when too far from a log. - * - * @param type the type of leaf block - * @param species the species of the wood block - * @param isDecayable whether the block is permanent or can disappear - */ - public Leaves(final Material type, TreeSpecies species, boolean isDecayable) { - super(type, species); - setDecayable(isDecayable); - } - - /** - * @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); - } - - /** - * Checks if this leaf block is in the process of decaying - * - * @return true if the leaf block is in the process of decaying - */ - public boolean isDecaying() { - return (getData() & 0x8) != 0; - } - - /** - * Set whether this leaf block is in the process of decaying - * - * @param isDecaying whether the block is decaying or not - */ - public void setDecaying(boolean isDecaying) { - setData((byte) ((getData() & 0x3) | (isDecaying - ? 0x8 // Clear the permanent flag to make this a decayable flag and set the decaying flag - : (getData() & 0x4)))); // Only persist the decayable flag if this is not a decaying block - } - - /** - * Checks if this leaf block is permanent or can decay when too far from a - * log - * - * @return true if the leaf block is permanent or can decay when too far - * from a log - */ - public boolean isDecayable() { - return (getData() & 0x4) == 0; - } - - /** - * Set whether this leaf block will disappear when too far from a log - * - * @param isDecayable whether the block is permanent or can disappear - */ - public void setDecayable(boolean isDecayable) { - setData((byte) ((getData() & 0x3) | (isDecayable - ? (getData() & 0x8) // Only persist the decaying flag if this is a decayable block - : 0x4))); - } - - @Override - public String toString() { - return getSpecies() + (isDecayable() ? " DECAYABLE " : " PERMANENT ") + (isDecaying() ? " DECAYING " : " ") + super.toString(); - } - - @Override - public Leaves clone() { - return (Leaves) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/Lever.java b/api/src/main/java/org/bukkit/material/Lever.java deleted file mode 100644 index 09f290f88..000000000 --- a/api/src/main/java/org/bukkit/material/Lever.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a lever - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Lever extends SimpleAttachableMaterialData implements Redstone { - public Lever() { - super(Material.LEGACY_LEVER); - } - - public Lever(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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/api/src/main/java/org/bukkit/material/LongGrass.java b/api/src/main/java/org/bukkit/material/LongGrass.java deleted file mode 100644 index 497857ec3..000000000 --- a/api/src/main/java/org/bukkit/material/LongGrass.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.GrassSpecies; -import org.bukkit.Material; - -/** - * Represents the different types of long grasses. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class LongGrass extends MaterialData { - public LongGrass() { - super(Material.LEGACY_LONG_GRASS); - } - - public LongGrass(GrassSpecies species) { - this(); - setSpecies(species); - } - - public LongGrass(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/MaterialData.java b/api/src/main/java/org/bukkit/material/MaterialData.java deleted file mode 100644 index ccaddb879..000000000 --- a/api/src/main/java/org/bukkit/material/MaterialData.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -/** - * Handles specific metadata for certain items or blocks - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class MaterialData implements Cloneable { - private final Material type; - private byte data = 0; - - public MaterialData(final Material type) { - this(type, (byte) 0); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public MaterialData(final Material type, final byte data) { - this.type = type; - this.data = 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 type; - } - - /** - * Creates a new ItemStack based on this MaterialData - * - * @return New ItemStack containing a copy of this MaterialData - * @deprecated this method creates an ItemStack of size 0 which is not - * generally useful. Consider {@link #toItemStack(int)}. - */ - @Deprecated - 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 ((getItemType().hashCode() << 8) ^ getData()); - } - - @Override - public boolean equals(Object obj) { - if (obj != null && obj instanceof MaterialData) { - MaterialData md = (MaterialData) obj; - - return (md.getItemType() == getItemType() && 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/api/src/main/java/org/bukkit/material/MonsterEggs.java b/api/src/main/java/org/bukkit/material/MonsterEggs.java deleted file mode 100644 index 2fac218f1..000000000 --- a/api/src/main/java/org/bukkit/material/MonsterEggs.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.material; - -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Material; - -/** - * Represents the different types of monster eggs - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class MonsterEggs extends TexturedMaterial { - - private static final List textures = new ArrayList(); - static { - textures.add(Material.LEGACY_STONE); - textures.add(Material.LEGACY_COBBLESTONE); - textures.add(Material.LEGACY_SMOOTH_BRICK); - } - - public MonsterEggs() { - super(Material.LEGACY_MONSTER_EGGS); - } - - public MonsterEggs(final Material type) { - super((textures.contains(type)) ? Material.LEGACY_MONSTER_EGGS : type); - if (textures.contains(type)) { - setMaterial(type); - } - } - - /** - * @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/api/src/main/java/org/bukkit/material/Mushroom.java b/api/src/main/java/org/bukkit/material/Mushroom.java deleted file mode 100644 index 543b76c8a..000000000 --- a/api/src/main/java/org/bukkit/material/Mushroom.java +++ /dev/null @@ -1,286 +0,0 @@ -package org.bukkit.material; - -import java.util.EnumSet; -import java.util.Set; -import org.apache.commons.lang.Validate; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.material.types.MushroomBlockTexture; - -/** - * Represents a huge mushroom block with certain combinations of faces set to - * cap, pores or stem. - * - * @see Material#LEGACY_HUGE_MUSHROOM_1 - * @see Material#LEGACY_HUGE_MUSHROOM_2 - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Mushroom extends MaterialData { - 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; - - /** - * Constructs a brown/red mushroom block with all sides set to pores. - * - * @param shroom A brown or red mushroom material type. - * - * @see Material#LEGACY_HUGE_MUSHROOM_1 - * @see Material#LEGACY_HUGE_MUSHROOM_2 - */ - public Mushroom(Material shroom) { - super(shroom); - Validate.isTrue(shroom == Material.LEGACY_HUGE_MUSHROOM_1 || shroom == Material.LEGACY_HUGE_MUSHROOM_2, "Not a mushroom!"); - } - - /** - * Constructs a brown/red mushroom cap block with the specified face or - * faces set to cap texture. - * - * Setting any of the four sides will also set the top to cap. - * - * To set two side faces at once use e.g. north-west. - * - * Specify self to set all six faces at once. - * - * @param shroom A brown or red mushroom material type. - * @param capFace The face or faces to set to mushroom cap texture. - * - * @see Material#LEGACY_HUGE_MUSHROOM_1 - * @see Material#LEGACY_HUGE_MUSHROOM_2 - * @see BlockFace - */ - public Mushroom(Material shroom, BlockFace capFace) { - this(shroom, MushroomBlockTexture.getCapByFace(capFace)); - } - - /** - * Constructs a brown/red mushroom block with the specified textures. - * - * @param shroom A brown or red mushroom material type. - * @param texture The textured mushroom faces. - * - * @see Material#LEGACY_HUGE_MUSHROOM_1 - * @see Material#LEGACY_HUGE_MUSHROOM_2 - */ - public Mushroom(Material shroom, MushroomBlockTexture texture) { - this(shroom, texture.getData()); - } - - /** - * @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.LEGACY_HUGE_MUSHROOM_1 || shroom == Material.LEGACY_HUGE_MUSHROOM_2, "Not a mushroom!"); - } - - /** - * @return Whether this is a mushroom stem. - */ - public boolean isStem() { - return getData() == MushroomBlockTexture.STEM_SIDES.getData() || getData() == MushroomBlockTexture.ALL_STEM.getData(); - } - - /** - * Sets this to be a mushroom stem. - * - * @see MushroomBlockTexture#STEM_SIDES - * @see MushroomBlockTexture#ALL_STEM - * - * @deprecated Use - * {@link #setBlockTexture(org.bukkit.material.types.MushroomBlockTexture)} - * with {@link MushroomBlockTexture#STEM_SIDES } or - * {@link MushroomBlockTexture#ALL_STEM} - */ - @Deprecated - public void setStem() { - setData((byte) MushroomBlockTexture.STEM_SIDES.getData()); - } - - /** - * Gets the mushroom texture of this block. - * - * @return The mushroom texture of this block - */ - public MushroomBlockTexture getBlockTexture() { - return MushroomBlockTexture.getByData(getData()); - } - - /** - * Sets the mushroom texture of this block. - * - * @param texture The mushroom texture to set - */ - public void setBlockTexture(MushroomBlockTexture texture) { - setData(texture.getData()); - } - - /** - * Checks whether a face of the block is painted with cap texture. - * - * @param face The face to check. - * @return True if it is painted. - */ - public boolean isFacePainted(BlockFace face) { - byte data = getData(); - - if (data == MushroomBlockTexture.ALL_PORES.getData() || data == MushroomBlockTexture.STEM_SIDES.getData() - || data == MushroomBlockTexture.ALL_STEM.getData()) { - 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; - case DOWN: - case SELF: - return data == MushroomBlockTexture.ALL_CAP.getData(); - 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. - * - * @deprecated Use MushroomBlockType cap options - */ - @Deprecated - public void setFacePainted(BlockFace face, boolean painted) { - if (painted == isFacePainted(face)) { - return; - } - - byte data = getData(); - - if (data == MushroomBlockTexture.ALL_PORES.getData() || isStem()) { - data = MushroomBlockTexture.CAP_TOP.getData(); - } - if (data == MushroomBlockTexture.ALL_CAP.getData() && !painted) { - data = MushroomBlockTexture.CAP_TOP.getData(); - face = face.getOppositeFace(); - painted = true; - } - - 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 = MushroomBlockTexture.ALL_PORES.getData(); - } - break; - case SELF: - case DOWN: - if (painted) { - data = MushroomBlockTexture.ALL_CAP.getData(); - } else { - data = MushroomBlockTexture.ALL_PORES.getData(); - } - 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); - } - - if (isFacePainted(BlockFace.DOWN)) { - faces.add(BlockFace.DOWN); - } - - return faces; - } - - @Override - public String toString() { - return getItemType() + (isStem() ? " STEM " : " CAP ") + getPaintedFaces(); - } - - @Override - public Mushroom clone() { - return (Mushroom) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/NetherWarts.java b/api/src/main/java/org/bukkit/material/NetherWarts.java deleted file mode 100644 index 1fed8b937..000000000 --- a/api/src/main/java/org/bukkit/material/NetherWarts.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.NetherWartsState; - -/** - * Represents nether wart - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class NetherWarts extends MaterialData { - public NetherWarts() { - super(Material.LEGACY_NETHER_WARTS); - } - - public NetherWarts(NetherWartsState state) { - this(); - setState(state); - } - - public NetherWarts(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/Observer.java b/api/src/main/java/org/bukkit/material/Observer.java deleted file mode 100644 index 843790b33..000000000 --- a/api/src/main/java/org/bukkit/material/Observer.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents an observer. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Observer extends MaterialData implements Directional, Redstone { - - public Observer() { - super(Material.LEGACY_OBSERVER); - } - - public Observer(BlockFace direction) { - this(); - setFacingDirection(direction); - } - - public Observer(final Material type) { - super(type); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Observer(final Material type, final byte data) { - super(type, data); - } - - @Override - public boolean isPowered() { - return (getData() & 0x8) == 0x8; - } - - @Override - public void setFacingDirection(BlockFace face) { - byte data = (byte) (getData() & 0x8); - - switch (face) { - case DOWN: - data |= 0x0; - break; - case UP: - data |= 0x1; - break; - case SOUTH: - data |= 0x2; - break; - case NORTH: - data |= 0x3; - break; - case EAST: - data |= 0x4; - break; - case WEST: - data |= 0x5; - break; - } - - setData(data); - } - - @Override - public BlockFace getFacing() { - int data = getData() & 0x7; - - switch (data) { - case 0x0: - return BlockFace.DOWN; - case 0x1: - return BlockFace.UP; - case 0x2: - return BlockFace.SOUTH; - case 0x3: - return BlockFace.NORTH; - case 0x4: - return BlockFace.EAST; - case 0x5: - return BlockFace.WEST; - default: - throw new IllegalArgumentException("Illegal facing direction " + data); - } - } - - @Override - public String toString() { - return super.toString() + " facing " + getFacing(); - } - - @Override - public Observer clone() { - return (Observer) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/Openable.java b/api/src/main/java/org/bukkit/material/Openable.java deleted file mode 100644 index 0ae54f973..000000000 --- a/api/src/main/java/org/bukkit/material/Openable.java +++ /dev/null @@ -1,18 +0,0 @@ -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/api/src/main/java/org/bukkit/material/PistonBaseMaterial.java b/api/src/main/java/org/bukkit/material/PistonBaseMaterial.java deleted file mode 100644 index 8165e9433..000000000 --- a/api/src/main/java/org/bukkit/material/PistonBaseMaterial.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Material data for the piston base block - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class PistonBaseMaterial extends MaterialData implements Directional, Redstone { - - public PistonBaseMaterial(final Material type) { - super(type); - } - - /** - * 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.LEGACY_PISTON_STICKY_BASE; - } - - @Override - public PistonBaseMaterial clone() { - return (PistonBaseMaterial) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/PistonExtensionMaterial.java b/api/src/main/java/org/bukkit/material/PistonExtensionMaterial.java deleted file mode 100644 index e7cfc7158..000000000 --- a/api/src/main/java/org/bukkit/material/PistonExtensionMaterial.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Material data for the piston extension block - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class PistonExtensionMaterial extends MaterialData implements Attachable { - - public PistonExtensionMaterial(final Material type) { - super(type); - } - - /** - * @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); - } - - @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; - } - } - - /** - * 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))); - } - - @Override - public BlockFace getAttachedFace() { - return getFacing().getOppositeFace(); - } - - @Override - public PistonExtensionMaterial clone() { - return (PistonExtensionMaterial) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/PoweredRail.java b/api/src/main/java/org/bukkit/material/PoweredRail.java deleted file mode 100644 index feebc5c73..000000000 --- a/api/src/main/java/org/bukkit/material/PoweredRail.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents a powered rail - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class PoweredRail extends ExtendedRails implements Redstone { - public PoweredRail() { - super(Material.LEGACY_POWERED_RAIL); - } - - public PoweredRail(final Material type) { - super(type); - } - - /** - * @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); - } - - @Override - 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/api/src/main/java/org/bukkit/material/PressurePlate.java b/api/src/main/java/org/bukkit/material/PressurePlate.java deleted file mode 100644 index ffababbc1..000000000 --- a/api/src/main/java/org/bukkit/material/PressurePlate.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents a pressure plate - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class PressurePlate extends MaterialData implements PressureSensor { - public PressurePlate() { - super(Material.LEGACY_WOOD_PLATE); - } - - public PressurePlate(Material type) { - super(type); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public PressurePlate(Material type, byte data) { - super(type, data); - } - - @Override - 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/api/src/main/java/org/bukkit/material/PressureSensor.java b/api/src/main/java/org/bukkit/material/PressureSensor.java deleted file mode 100644 index de20bd39c..000000000 --- a/api/src/main/java/org/bukkit/material/PressureSensor.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bukkit.material; - -public interface PressureSensor { - public boolean isPressed(); -} diff --git a/api/src/main/java/org/bukkit/material/Pumpkin.java b/api/src/main/java/org/bukkit/material/Pumpkin.java deleted file mode 100644 index 7c1b5eea0..000000000 --- a/api/src/main/java/org/bukkit/material/Pumpkin.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a pumpkin. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Pumpkin extends MaterialData implements Directional { - - public Pumpkin() { - super(Material.LEGACY_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); - } - - public Pumpkin(final Material type) { - super(type); - } - - /** - * @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.LEGACY_JACK_O_LANTERN; - } - - @Override - 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); - } - - @Override - 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/api/src/main/java/org/bukkit/material/Rails.java b/api/src/main/java/org/bukkit/material/Rails.java deleted file mode 100644 index 0b041ee66..000000000 --- a/api/src/main/java/org/bukkit/material/Rails.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents minecart rails. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Rails extends MaterialData { - - public Rails() { - super(Material.LEGACY_RAILS); - } - - public Rails(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/Redstone.java b/api/src/main/java/org/bukkit/material/Redstone.java deleted file mode 100644 index 3e46603f8..000000000 --- a/api/src/main/java/org/bukkit/material/Redstone.java +++ /dev/null @@ -1,15 +0,0 @@ -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 - */ - public boolean isPowered(); -} diff --git a/api/src/main/java/org/bukkit/material/RedstoneTorch.java b/api/src/main/java/org/bukkit/material/RedstoneTorch.java deleted file mode 100644 index 409569143..000000000 --- a/api/src/main/java/org/bukkit/material/RedstoneTorch.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents a redstone torch - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class RedstoneTorch extends Torch implements Redstone { - public RedstoneTorch() { - super(Material.LEGACY_REDSTONE_TORCH_ON); - } - - public RedstoneTorch(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - public boolean isPowered() { - return getItemType() == Material.LEGACY_REDSTONE_TORCH_ON; - } - - @Override - public String toString() { - return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; - } - - @Override - public RedstoneTorch clone() { - return (RedstoneTorch) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/RedstoneWire.java b/api/src/main/java/org/bukkit/material/RedstoneWire.java deleted file mode 100644 index 8877ef48e..000000000 --- a/api/src/main/java/org/bukkit/material/RedstoneWire.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents redstone wire - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class RedstoneWire extends MaterialData implements Redstone { - public RedstoneWire() { - super(Material.LEGACY_REDSTONE_WIRE); - } - - public RedstoneWire(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - 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/api/src/main/java/org/bukkit/material/Sandstone.java b/api/src/main/java/org/bukkit/material/Sandstone.java deleted file mode 100644 index 8d8673edc..000000000 --- a/api/src/main/java/org/bukkit/material/Sandstone.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.SandstoneType; - -/** - * Represents the different types of sandstone. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Sandstone extends MaterialData { - public Sandstone() { - super(Material.LEGACY_SANDSTONE); - } - - public Sandstone(SandstoneType type) { - this(); - setType(type); - } - - public Sandstone(final Material type) { - super(type); - } - - /** - * @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/api/src/main/java/org/bukkit/material/Sapling.java b/api/src/main/java/org/bukkit/material/Sapling.java deleted file mode 100644 index c615a0022..000000000 --- a/api/src/main/java/org/bukkit/material/Sapling.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.TreeSpecies; - -/** - * Represents the different types of Tree block that face a direction. - * - * @see Material#LEGACY_SAPLING - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Sapling extends Wood { - - /** - * Constructs a sapling. - */ - public Sapling() { - this(DEFAULT_SPECIES); - } - - /** - * Constructs a sapling of the given tree species. - * - * @param species the species of the sapling - */ - public Sapling(TreeSpecies species) { - this(species, false); - } - - /** - * Constructs a sapling of the given tree species and if is it instant - * growable - * - * @param species the species of the tree block - * @param isInstantGrowable true if the Sapling should grow when next ticked with bonemeal - */ - public Sapling(TreeSpecies species, boolean isInstantGrowable) { - this(Material.LEGACY_SAPLING, species, isInstantGrowable); - } - - /** - * Constructs a sapling of the given type. - * - * @param type the type of tree block - */ - public Sapling(final Material type) { - this(type, DEFAULT_SPECIES, false); - } - - /** - * Constructs a sapling of the given type and tree species. - * - * @param type the type of sapling - * @param species the species of the sapling - */ - public Sapling(final Material type, TreeSpecies species) { - this(type, species, false); - } - - /** - * Constructs a sapling of the given type and tree species and if is it - * instant growable - * - * @param type the type of sapling - * @param species the species of the sapling - * @param isInstantGrowable true if the Sapling should grow when next ticked - * with bonemeal - */ - public Sapling(final Material type, TreeSpecies species, boolean isInstantGrowable) { - super(type, species); - setIsInstantGrowable(isInstantGrowable); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Sapling(final Material type, final byte data) { - super(type, data); - } - - /** - * Checks if the Sapling would grow when next ticked with bonemeal - * - * @return true if the Sapling would grow when next ticked with bonemeal - */ - public boolean isInstantGrowable() { - return (getData() & 0x8) == 0x8; - } - - /** - * Set whether this sapling will grow when next ticked with bonemeal - * - * @param isInstantGrowable true if the Sapling should grow when next ticked - * with bonemeal - */ - public void setIsInstantGrowable(boolean isInstantGrowable) { - setData(isInstantGrowable ? (byte) ((getData() & 0x7) | 0x8) : (byte) (getData() & 0x7)); - } - - @Override - public String toString() { - return getSpecies() + " " + (isInstantGrowable() ? " IS_INSTANT_GROWABLE " : "") + " " + super.toString(); - } - - @Override - public Sapling clone() { - return (Sapling) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/Sign.java b/api/src/main/java/org/bukkit/material/Sign.java deleted file mode 100644 index 3b32679b4..000000000 --- a/api/src/main/java/org/bukkit/material/Sign.java +++ /dev/null @@ -1,240 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * MaterialData for signs - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Sign extends MaterialData implements Attachable { - public Sign() { - super(Material.LEGACY_SIGN_POST); - } - - 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 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.LEGACY_WALL_SIGN; - } - - /** - * Gets the face that this block is attached on - * - * @return BlockFace attached to - */ - @Override - 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 - */ - @Override - 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(); - } - } - - @Override - 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/api/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java b/api/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java deleted file mode 100644 index 6267d81ba..000000000 --- a/api/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Simple utility class for attachable MaterialData subclasses - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public abstract class SimpleAttachableMaterialData extends MaterialData implements Attachable { - - public SimpleAttachableMaterialData(Material type, BlockFace direction) { - this(type); - setFacingDirection(direction); - } - - public SimpleAttachableMaterialData(Material type) { - super(type); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public SimpleAttachableMaterialData(Material type, byte data) { - super(type, data); - } - - @Override - 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/api/src/main/java/org/bukkit/material/Skull.java b/api/src/main/java/org/bukkit/material/Skull.java deleted file mode 100644 index a73ad6246..000000000 --- a/api/src/main/java/org/bukkit/material/Skull.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a skull. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Skull extends MaterialData implements Directional { - public Skull() { - super(Material.LEGACY_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); - } - - public Skull(final Material type) { - super(type); - } - - /** - * @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); - } - - @Override - public void setFacingDirection(BlockFace face) { - int data; - - switch (face) { - case SELF: - default: - data = 0x1; - break; - - case NORTH: - data = 0x2; - break; - - case WEST: - data = 0x4; - break; - - case SOUTH: - data = 0x3; - break; - - case EAST: - data = 0x5; - } - - setData((byte) data); - } - - @Override - 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.WEST; - - case 0x5: - return BlockFace.EAST; - } - } - - @Override - public String toString() { - return super.toString() + " facing " + getFacing(); - } - - @Override - public Skull clone() { - return (Skull) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/SmoothBrick.java b/api/src/main/java/org/bukkit/material/SmoothBrick.java deleted file mode 100644 index e4812b7ce..000000000 --- a/api/src/main/java/org/bukkit/material/SmoothBrick.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.bukkit.material; - -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Material; - -/** - * Represents the different types of smooth bricks. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class SmoothBrick extends TexturedMaterial { - - private static final List textures = new ArrayList(); - static { - textures.add(Material.LEGACY_STONE); - textures.add(Material.LEGACY_MOSSY_COBBLESTONE); - textures.add(Material.LEGACY_COBBLESTONE); - textures.add(Material.LEGACY_SMOOTH_BRICK); - } - - public SmoothBrick() { - super(Material.LEGACY_SMOOTH_BRICK); - } - - public SmoothBrick(final Material type) { - super((textures.contains(type)) ? Material.LEGACY_SMOOTH_BRICK : type); - if (textures.contains(type)) { - setMaterial(type); - } - } - - /** - * @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/api/src/main/java/org/bukkit/material/SpawnEgg.java b/api/src/main/java/org/bukkit/material/SpawnEgg.java deleted file mode 100644 index a177021d2..000000000 --- a/api/src/main/java/org/bukkit/material/SpawnEgg.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.bukkit.inventory.meta.SpawnEggMeta; - -/** - * Represents a spawn egg that can be used to spawn mobs - * @deprecated use {@link SpawnEggMeta} - */ -@Deprecated -public class SpawnEgg extends MaterialData { - - public SpawnEgg() { - super(Material.LEGACY_MONSTER_EGG); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public SpawnEgg(final Material type, final byte data) { - super(type, data); - } - - /** - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public SpawnEgg(byte data) { - super(Material.LEGACY_MONSTER_EGG, data); - } - - public SpawnEgg(EntityType type) { - this(); - setSpawnedType(type); - } - - /** - * Get the type of entity this egg will spawn. - * - * @return The entity type. - * @deprecated This is now stored in {@link SpawnEggMeta}. - */ - @Deprecated - public EntityType getSpawnedType() { - return EntityType.fromId(getData()); - } - - /** - * Set the type of entity this egg will spawn. - * - * @param type The entity type. - * @deprecated This is now stored in {@link SpawnEggMeta}. - */ - @Deprecated - 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/api/src/main/java/org/bukkit/material/Stairs.java b/api/src/main/java/org/bukkit/material/Stairs.java deleted file mode 100644 index e5db60bd0..000000000 --- a/api/src/main/java/org/bukkit/material/Stairs.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents stairs. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Stairs extends MaterialData implements Directional { - - public Stairs(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - 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 - */ - @Override - 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/api/src/main/java/org/bukkit/material/Step.java b/api/src/main/java/org/bukkit/material/Step.java deleted file mode 100644 index 8b92ec4e8..000000000 --- a/api/src/main/java/org/bukkit/material/Step.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.bukkit.material; - -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Material; - -/** - * Represents the different types of steps. - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Step extends TexturedMaterial { - private static final List textures = new ArrayList(); - static { - textures.add(Material.LEGACY_STONE); - textures.add(Material.LEGACY_SANDSTONE); - textures.add(Material.LEGACY_WOOD); - textures.add(Material.LEGACY_COBBLESTONE); - textures.add(Material.LEGACY_BRICK); - textures.add(Material.LEGACY_SMOOTH_BRICK); - textures.add(Material.LEGACY_NETHER_BRICK); - textures.add(Material.LEGACY_QUARTZ_BLOCK); - } - - public Step() { - super(Material.LEGACY_STEP); - } - - public Step(final Material type) { - super((textures.contains(type)) ? Material.LEGACY_STEP : type); - if (textures.contains(type)) { - setMaterial(type); - } - } - - /** - * @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/api/src/main/java/org/bukkit/material/TexturedMaterial.java b/api/src/main/java/org/bukkit/material/TexturedMaterial.java deleted file mode 100644 index 6e0a83479..000000000 --- a/api/src/main/java/org/bukkit/material/TexturedMaterial.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.bukkit.material; - -import java.util.List; -import org.bukkit.Material; - -/** - * Represents textured materials like steps and smooth bricks - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public abstract class TexturedMaterial extends MaterialData { - - public TexturedMaterial(Material m) { - super(m); - } - - /** - * @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); // Default 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/api/src/main/java/org/bukkit/material/Torch.java b/api/src/main/java/org/bukkit/material/Torch.java deleted file mode 100644 index a4f0c62dc..000000000 --- a/api/src/main/java/org/bukkit/material/Torch.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * MaterialData for torches - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Torch extends SimpleAttachableMaterialData { - public Torch() { - super(Material.LEGACY_TORCH); - } - - public Torch(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - 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; - } - } - - @Override - 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/api/src/main/java/org/bukkit/material/TrapDoor.java b/api/src/main/java/org/bukkit/material/TrapDoor.java deleted file mode 100644 index effedfc71..000000000 --- a/api/src/main/java/org/bukkit/material/TrapDoor.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a trap door - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class TrapDoor extends SimpleAttachableMaterialData implements Openable { - public TrapDoor() { - super(Material.LEGACY_TRAP_DOOR); - } - - public TrapDoor(final Material type) { - super(type); - } - - /** - * @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); - } - - @Override - public boolean isOpen() { - return ((getData() & 0x4) == 0x4); - } - - @Override - 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); - } - - @Override - 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; - - } - - @Override - 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/api/src/main/java/org/bukkit/material/Tree.java b/api/src/main/java/org/bukkit/material/Tree.java deleted file mode 100644 index e759f5033..000000000 --- a/api/src/main/java/org/bukkit/material/Tree.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.TreeSpecies; -import org.bukkit.block.BlockFace; - -/** - * Represents the different types of Tree block that face a direction. - * - * @see Material#LEGACY_LOG - * @see Material#LEGACY_LOG_2 - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Tree extends Wood { - protected static final Material DEFAULT_TYPE = Material.LEGACY_LOG; - protected static final BlockFace DEFAULT_DIRECTION = BlockFace.UP; - - /** - * Constructs a tree block. - */ - public Tree() { - this(DEFAULT_TYPE, DEFAULT_SPECIES, DEFAULT_DIRECTION); - } - - /** - * Constructs a tree block of the given tree species. - * - * @param species the species of the tree block - */ - public Tree(TreeSpecies species) { - this(DEFAULT_TYPE, species, DEFAULT_DIRECTION); - } - - /** - * Constructs a tree block of the given tree species, and facing the given - * direction. - * - * @param species the species of the tree block - * @param dir the direction the tree block is facing - */ - public Tree(TreeSpecies species, BlockFace dir) { - this(DEFAULT_TYPE, species, dir); - } - - /** - * Constructs a tree block of the given type. - * - * @param type the type of tree block - */ - public Tree(final Material type) { - this(type, DEFAULT_SPECIES, DEFAULT_DIRECTION); - } - - /** - * Constructs a tree block of the given type and tree species. - * - * @param type the type of tree block - * @param species the species of the tree block - */ - public Tree(final Material type, TreeSpecies species) { - this(type, species, DEFAULT_DIRECTION); - } - - /** - * Constructs a tree block of the given type and tree species, and facing - * the given direction. - * - * @param type the type of tree block - * @param species the species of the tree block - * @param dir the direction the tree block is facing - */ - public Tree(final Material type, TreeSpecies species, BlockFace dir) { - super(type, species); - setDirection(dir); - } - - /** - * @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); - } - - /** - * Get direction of the log - * - * @return one of: - *

    - *
  • BlockFace.TOP for upright (default) - *
  • BlockFace.NORTH (east-west) - *
  • BlockFace.WEST (north-south) - *
  • BlockFace.SELF (directionless) - *
- */ - @SuppressWarnings("deprecation") - 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) - */ - @SuppressWarnings("deprecation") - public void setDirection(BlockFace dir) { - int dat; - switch (dir) { - case UP: - case DOWN: - default: - dat = 0; - break; - case WEST: - case EAST: - dat = 4; // 1<<2 - break; - case NORTH: - case SOUTH: - dat = 8; // 2<<2 - break; - case SELF: - dat = 12; // 3<<2 - break; - } - setData((byte) ((getData() & 0x3) | dat)); - } - - @Override - public String toString() { - return getSpecies() + " " + getDirection() + " " + super.toString(); - } - - @Override - public Tree clone() { - return (Tree) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/Tripwire.java b/api/src/main/java/org/bukkit/material/Tripwire.java deleted file mode 100644 index e5ffa4db8..000000000 --- a/api/src/main/java/org/bukkit/material/Tripwire.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; - -/** - * Represents the tripwire - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Tripwire extends MaterialData { - - public Tripwire() { - super(Material.LEGACY_TRIPWIRE); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Tripwire(final Material 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/api/src/main/java/org/bukkit/material/TripwireHook.java b/api/src/main/java/org/bukkit/material/TripwireHook.java deleted file mode 100644 index 80aa1c7bc..000000000 --- a/api/src/main/java/org/bukkit/material/TripwireHook.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents the tripwire hook - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class TripwireHook extends SimpleAttachableMaterialData implements Redstone { - - public TripwireHook() { - super(Material.LEGACY_TRIPWIRE_HOOK); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public TripwireHook(final Material 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); - } - - @Override - 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); - } - - @Override - 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; - } - - @Override - 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/api/src/main/java/org/bukkit/material/Vine.java b/api/src/main/java/org/bukkit/material/Vine.java deleted file mode 100644 index 07a4f3b15..000000000 --- a/api/src/main/java/org/bukkit/material/Vine.java +++ /dev/null @@ -1,200 +0,0 @@ -package org.bukkit.material; - -import java.util.Arrays; -import java.util.EnumSet; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; - -/** - * Represents a vine - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -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; - private static final EnumSet possibleFaces = EnumSet.of(BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST); - - public Vine() { - super(Material.LEGACY_VINE); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Vine(final Material type, final byte data) { - super(type, data); - } - - /** - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Vine(byte data) { - super(Material.LEGACY_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/api/src/main/java/org/bukkit/material/Wood.java b/api/src/main/java/org/bukkit/material/Wood.java deleted file mode 100644 index 5d51c9286..000000000 --- a/api/src/main/java/org/bukkit/material/Wood.java +++ /dev/null @@ -1,181 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.TreeSpecies; - -/** - * Represents wood blocks of different species. - * - * @see Material#LEGACY_WOOD - * @see Material#LEGACY_SAPLING - * @see Material#LEGACY_WOOD_DOUBLE_STEP - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Wood extends MaterialData { - protected static final Material DEFAULT_TYPE = Material.LEGACY_WOOD; - protected static final TreeSpecies DEFAULT_SPECIES = TreeSpecies.GENERIC; - - /** - * Constructs a wood block. - */ - public Wood() { - this(DEFAULT_TYPE, DEFAULT_SPECIES); - } - - /** - * Constructs a wood block of the given tree species. - * - * @param species the species of the wood block - */ - public Wood(TreeSpecies species) { - this(DEFAULT_TYPE, species); - } - - /** - * Constructs a wood block of the given type. - * - * @param type the type of wood block - */ - public Wood(final Material type) { - this(type, DEFAULT_SPECIES); - } - - /** - * Constructs a wood block of the given type and tree species. - * - * @param type the type of wood block - * @param species the species of the wood block - */ - public Wood(final Material type, final TreeSpecies species) { - // Ensure only valid species-type combinations - super(getSpeciesType(type, species)); - setSpecies(species); - } - - /** - * @param type the type - * @param data the raw data value - * @deprecated Magic value - */ - @Deprecated - public Wood(final Material type, final byte data) { - super(type, data); - } - - /** - * Gets the current species of this wood block - * - * @return TreeSpecies of this wood block - */ - public TreeSpecies getSpecies() { - switch (getItemType()) { - case LEGACY_WOOD: - case LEGACY_WOOD_DOUBLE_STEP: - return TreeSpecies.getByData((byte) getData()); - case LEGACY_LOG: - case LEGACY_LEAVES: - return TreeSpecies.getByData((byte) (getData() & 0x3)); - case LEGACY_LOG_2: - case LEGACY_LEAVES_2: - return TreeSpecies.getByData((byte) ((getData() & 0x3) | 0x4)); - case LEGACY_SAPLING: - case LEGACY_WOOD_STEP: - return TreeSpecies.getByData((byte) (getData() & 0x7)); - default: - throw new IllegalArgumentException("Invalid block type for tree species"); - } - } - - /** - * Correct the block type for certain species-type combinations. - * - * @param type The desired type - * @param species The required species - * @return The actual type for this species given the desired type - */ - private static Material getSpeciesType(Material type, TreeSpecies species) { - switch (species) { - case GENERIC: - case REDWOOD: - case BIRCH: - case JUNGLE: - switch (type) { - case LEGACY_LOG_2: - return Material.LEGACY_LOG; - case LEGACY_LEAVES_2: - return Material.LEGACY_LEAVES; - default: - } - break; - case ACACIA: - case DARK_OAK: - switch (type) { - case LEGACY_LOG: - return Material.LEGACY_LOG_2; - case LEGACY_LEAVES: - return Material.LEGACY_LEAVES_2; - default: - } - break; - } - return type; - } - - /** - * Sets the species of this wood block - * - * @param species New species of this wood block - */ - public void setSpecies(final TreeSpecies species) { - boolean firstType = false; - switch (getItemType()) { - case LEGACY_WOOD: - case LEGACY_WOOD_DOUBLE_STEP: - setData(species.getData()); - break; - case LEGACY_LOG: - case LEGACY_LEAVES: - firstType = true; - // fall through to next switch statement below - case LEGACY_LOG_2: - case LEGACY_LEAVES_2: - switch (species) { - case GENERIC: - case REDWOOD: - case BIRCH: - case JUNGLE: - if (!firstType) { - throw new IllegalArgumentException("Invalid tree species for block type, use block type 2 instead"); - } - break; - case ACACIA: - case DARK_OAK: - if (firstType) { - throw new IllegalArgumentException("Invalid tree species for block type 2, use block type instead"); - } - break; - } - setData((byte) ((getData() & 0xC) | (species.getData() & 0x3))); - break; - case LEGACY_SAPLING: - case LEGACY_WOOD_STEP: - setData((byte) ((getData() & 0x8) | species.getData())); - break; - default: - throw new IllegalArgumentException("Invalid block type for tree species"); - } - } - - @Override - public String toString() { - return getSpecies() + " " + super.toString(); - } - - @Override - public Wood clone() { - return (Wood) super.clone(); - } -} diff --git a/api/src/main/java/org/bukkit/material/WoodenStep.java b/api/src/main/java/org/bukkit/material/WoodenStep.java deleted file mode 100644 index b99a9a304..000000000 --- a/api/src/main/java/org/bukkit/material/WoodenStep.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.Material; -import org.bukkit.TreeSpecies; - -/** - * Represents the different types of wooden steps. - * - * @see Material#LEGACY_WOOD_STEP - * - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class WoodenStep extends Wood { - protected static final Material DEFAULT_TYPE = Material.LEGACY_WOOD_STEP; - protected static final boolean DEFAULT_INVERTED = false; - - /** - * Constructs a wooden step. - */ - public WoodenStep() { - this(DEFAULT_SPECIES, DEFAULT_INVERTED); - } - - /** - * Constructs a wooden step of the given tree species. - * - * @param species the species of the wooden step - */ - public WoodenStep(TreeSpecies species) { - this(species, DEFAULT_INVERTED); - } - - /** - * Constructs a wooden step of the given type and tree species, either - * inverted or not. - * - * @param species the species of the wooden step - * @param inv true the step is at the top of the block - */ - public WoodenStep(final TreeSpecies species, boolean inv) { - super(DEFAULT_TYPE, species); - setInverted(inv); - } - - /** - * @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); - } - - /** - * Test if step is inverted - * - * @return true if inverted (top half), false if normal (bottom half) - */ - @SuppressWarnings("deprecation") - 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) - */ - @SuppressWarnings("deprecation") - 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/api/src/main/java/org/bukkit/material/Wool.java b/api/src/main/java/org/bukkit/material/Wool.java deleted file mode 100644 index 3b17409a9..000000000 --- a/api/src/main/java/org/bukkit/material/Wool.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.bukkit.material; - -import org.bukkit.DyeColor; -import org.bukkit.Material; - -/** - * Represents a Wool/Cloth block - * @deprecated all usage of MaterialData is deprecated and subject to removal. - * Use {@link org.bukkit.block.data.BlockData}. - */ -@Deprecated -public class Wool extends MaterialData implements Colorable { - public Wool() { - super(Material.LEGACY_WOOL); - } - - public Wool(DyeColor color) { - this(); - setColor(color); - } - - public Wool(final Material type) { - super(type); - } - - /** - * @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 - */ - @Override - public DyeColor getColor() { - return DyeColor.getByWoolData(getData()); - } - - /** - * Sets the color of this dye - * - * @param color New color of this dye - */ - @Override - 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/api/src/main/java/org/bukkit/material/types/MushroomBlockTexture.java b/api/src/main/java/org/bukkit/material/types/MushroomBlockTexture.java deleted file mode 100644 index 0ea9c6b24..000000000 --- a/api/src/main/java/org/bukkit/material/types/MushroomBlockTexture.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.bukkit.material.types; - -import com.google.common.collect.Maps; -import java.util.Map; -import org.bukkit.block.BlockFace; -import org.jetbrains.annotations.Nullable; - -/** - * Represents the different textured blocks of mushroom. - */ -public enum MushroomBlockTexture { - - /** - * Pores on all faces. - */ - ALL_PORES(0, null), - /** - * Cap texture on the top, north and west faces, pores on remaining sides. - */ - CAP_NORTH_WEST(1, BlockFace.NORTH_WEST), - /** - * Cap texture on the top and north faces, pores on remaining sides. - */ - CAP_NORTH(2, BlockFace.NORTH), - /** - * Cap texture on the top, north and east faces, pores on remaining sides. - */ - CAP_NORTH_EAST(3, BlockFace.NORTH_EAST), - /** - * Cap texture on the top and west faces, pores on remaining sides. - */ - CAP_WEST(4, BlockFace.WEST), - /** - * Cap texture on the top face, pores on remaining sides. - */ - CAP_TOP(5, BlockFace.UP), - /** - * Cap texture on the top and east faces, pores on remaining sides. - */ - CAP_EAST(6, BlockFace.EAST), - /** - * Cap texture on the top, south and west faces, pores on remaining sides. - */ - CAP_SOUTH_WEST(7, BlockFace.SOUTH_WEST), - /** - * Cap texture on the top and south faces, pores on remaining sides. - */ - CAP_SOUTH(8, BlockFace.SOUTH), - /** - * Cap texture on the top, south and east faces, pores on remaining sides. - */ - CAP_SOUTH_EAST(9, BlockFace.SOUTH_EAST), - /** - * Stem texture on the north, east, south and west faces, pores on top and - * bottom. - */ - STEM_SIDES(10, null), - /** - * Cap texture on all faces. - */ - ALL_CAP(14, BlockFace.SELF), - /** - * Stem texture on all faces. - */ - ALL_STEM(15, null); - private static final Map BY_DATA = Maps.newHashMap(); - private static final Map BY_BLOCKFACE = Maps.newHashMap(); - - private final Byte data; - private final BlockFace capFace; - - private MushroomBlockTexture(final int data, /*@Nullable*/ final BlockFace capFace) { - this.data = (byte) data; - this.capFace = capFace; - } - - /** - * Gets the associated data value representing this mushroom block face. - * - * @return A byte containing the data value of this mushroom block face - * @deprecated Magic value - */ - @Deprecated - public byte getData() { - return data; - } - - /** - * Gets the face that has cap texture. - * - * @return The cap face - */ - @Nullable - public BlockFace getCapFace() { - return capFace; - } - - /** - * Gets the MushroomBlockType with the given data value. - * - * @param data Data value to fetch - * @return The {@link MushroomBlockTexture} representing the given value, or - * null if it doesn't exist - * @deprecated Magic value - */ - @Deprecated - @Nullable - public static MushroomBlockTexture getByData(final byte data) { - return BY_DATA.get(data); - } - - /** - * Gets the MushroomBlockType with cap texture on the given block face. - * - * @param face the required block face with cap texture - * @return The {@link MushroomBlockTexture} representing the given block - * face, or null if it doesn't exist - * - * @see BlockFace - */ - @Nullable - public static MushroomBlockTexture getCapByFace(@Nullable final BlockFace face) { - return BY_BLOCKFACE.get(face); - } - - static { - for (MushroomBlockTexture type : values()) { - BY_DATA.put(type.data, type); - BY_BLOCKFACE.put(type.capFace, type); - } - } -} diff --git a/api/src/main/java/org/bukkit/metadata/FixedMetadataValue.java b/api/src/main/java/org/bukkit/metadata/FixedMetadataValue.java deleted file mode 100644 index 4ded65531..000000000 --- a/api/src/main/java/org/bukkit/metadata/FixedMetadataValue.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.metadata; - -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull Plugin owningPlugin, @Nullable final Object value) { - super(owningPlugin); - this.internalValue = value; - } - - @Override - public void invalidate() { - - } - - @Nullable - @Override - public Object value() { - return internalValue; - } -} diff --git a/api/src/main/java/org/bukkit/metadata/LazyMetadataValue.java b/api/src/main/java/org/bukkit/metadata/LazyMetadataValue.java deleted file mode 100644 index 86e0e3767..000000000 --- a/api/src/main/java/org/bukkit/metadata/LazyMetadataValue.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.bukkit.metadata; - -import java.lang.ref.SoftReference; -import java.util.concurrent.Callable; -import org.apache.commons.lang.Validate; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 { - 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(@NotNull Plugin owningPlugin, @NotNull 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(@NotNull Plugin owningPlugin, @NotNull CacheStrategy cacheStrategy, @NotNull 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(@NotNull Plugin owningPlugin) { - super(owningPlugin); - } - - @Override - @Nullable - 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); - } - } - } - - @Override - 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/api/src/main/java/org/bukkit/metadata/MetadataConversionException.java b/api/src/main/java/org/bukkit/metadata/MetadataConversionException.java deleted file mode 100644 index a3def46a4..000000000 --- a/api/src/main/java/org/bukkit/metadata/MetadataConversionException.java +++ /dev/null @@ -1,13 +0,0 @@ -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/api/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java b/api/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java deleted file mode 100644 index 918e7c839..000000000 --- a/api/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java +++ /dev/null @@ -1,13 +0,0 @@ -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/api/src/main/java/org/bukkit/metadata/MetadataStore.java b/api/src/main/java/org/bukkit/metadata/MetadataStore.java deleted file mode 100644 index 29f86fa93..000000000 --- a/api/src/main/java/org/bukkit/metadata/MetadataStore.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.metadata; - -import java.util.List; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -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 - */ - public void setMetadata(@NotNull T subject, @NotNull String metadataKey, @NotNull 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. - */ - @NotNull - public List getMetadata(@NotNull T subject, @NotNull 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. - */ - public boolean hasMetadata(@NotNull T subject, @NotNull 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 - */ - public void removeMetadata(@NotNull T subject, @NotNull String metadataKey, @NotNull 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 - */ - public void invalidateAll(@NotNull Plugin owningPlugin); -} diff --git a/api/src/main/java/org/bukkit/metadata/MetadataStoreBase.java b/api/src/main/java/org/bukkit/metadata/MetadataStoreBase.java deleted file mode 100644 index 0e8cd85c7..000000000 --- a/api/src/main/java/org/bukkit/metadata/MetadataStoreBase.java +++ /dev/null @@ -1,169 +0,0 @@ -package org.bukkit.metadata; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; // Paper -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; -import org.apache.commons.lang.Validate; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -public abstract class MetadataStoreBase { - private Map> metadataMap = new java.util.concurrent.ConcurrentHashMap>(); // Paper - - /** - * 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(@NotNull T subject, @NotNull String metadataKey, @NotNull 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); - } - synchronized (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) - */ - @NotNull - public List getMetadata(@NotNull T subject, @NotNull String metadataKey) { // Paper - String key = disambiguate(subject, metadataKey); - Map entry = metadataMap.get(key); - if (entry != null) { - Collection values = entry.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 boolean hasMetadata(@NotNull T subject, @NotNull String metadataKey) { // Paper - 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, - * org.bukkit.plugin.Plugin) - * @throws IllegalArgumentException If plugin is null - */ - public void removeMetadata(@NotNull T subject, @NotNull String metadataKey, @NotNull Plugin owningPlugin) { // Paper - Validate.notNull(owningPlugin, "Plugin cannot be null"); - String key = disambiguate(subject, metadataKey); - Map entry = metadataMap.get(key); - if (entry == null) { - return; - } - synchronized (entry) { - 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(org.bukkit.plugin.Plugin) - * @throws IllegalArgumentException If plugin is null - */ - public void invalidateAll(@NotNull Plugin owningPlugin) { // Paper - Validate.notNull(owningPlugin, "Plugin cannot be null"); - for (Map values : metadataMap.values()) { - if (values.containsKey(owningPlugin)) { - values.get(owningPlugin).invalidate(); - } - } - } - - /** - * Removes all metadata in the metadata store that originates from the - * given plugin. - * - * @param owningPlugin the plugin requesting the invalidation. - * @throws IllegalArgumentException If plugin is null - */ - public void removeAll(@NotNull Plugin owningPlugin) { - Validate.notNull(owningPlugin, "Plugin cannot be null"); - for (Iterator> iterator = metadataMap.values().iterator(); iterator.hasNext(); ) { - Map values = iterator.next(); - if (values.containsKey(owningPlugin)) { - values.remove(owningPlugin); - } - if (values.isEmpty()) { - iterator.remove(); - } - } - } - - /** - * 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. - */ - @NotNull - protected abstract String disambiguate(@NotNull T subject, @NotNull String metadataKey); -} diff --git a/api/src/main/java/org/bukkit/metadata/MetadataValue.java b/api/src/main/java/org/bukkit/metadata/MetadataValue.java deleted file mode 100644 index 4b4d57924..000000000 --- a/api/src/main/java/org/bukkit/metadata/MetadataValue.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.metadata; - -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface MetadataValue { - - /** - * Fetches the value of this metadata item. - * - * @return the metadata value. - */ - @Nullable - public Object value(); - - /** - * Attempts to convert the value of this metadata item into an int. - * - * @return the value as an int. - */ - public int asInt(); - - /** - * Attempts to convert the value of this metadata item into a float. - * - * @return the value as a float. - */ - public float asFloat(); - - /** - * Attempts to convert the value of this metadata item into a double. - * - * @return the value as a double. - */ - public double asDouble(); - - /** - * Attempts to convert the value of this metadata item into a long. - * - * @return the value as a long. - */ - public long asLong(); - - /** - * Attempts to convert the value of this metadata item into a short. - * - * @return the value as a short. - */ - public short asShort(); - - /** - * Attempts to convert the value of this metadata item into a byte. - * - * @return the value as a byte. - */ - public byte asByte(); - - /** - * Attempts to convert the value of this metadata item into a boolean. - * - * @return the value as a boolean. - */ - public boolean asBoolean(); - - /** - * Attempts to convert the value of this metadata item into a string. - * - * @return the value as a string. - */ - @NotNull - public String asString(); - - /** - * Returns the {@link Plugin} that created this metadata item. - * - * @return the plugin that owns this metadata value. Could be null if the plugin was already unloaded. - */ - @Nullable - public Plugin getOwningPlugin(); - - /** - * Invalidates this metadata item, forcing it to recompute when next - * accessed. - */ - public void invalidate(); -} diff --git a/api/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java b/api/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java deleted file mode 100644 index b90d09f57..000000000 --- a/api/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.bukkit.metadata; - -import java.lang.ref.WeakReference; -import org.apache.commons.lang.Validate; -import org.bukkit.plugin.Plugin; -import org.bukkit.util.NumberConversions; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull Plugin owningPlugin) { - Validate.notNull(owningPlugin, "owningPlugin cannot be null"); - this.owningPlugin = new WeakReference(owningPlugin); - } - - @Override - @Nullable - public Plugin getOwningPlugin() { - return owningPlugin.get(); - } - - @Override - public int asInt() { - return NumberConversions.toInt(value()); - } - - @Override - public float asFloat() { - return NumberConversions.toFloat(value()); - } - - @Override - public double asDouble() { - return NumberConversions.toDouble(value()); - } - - @Override - public long asLong() { - return NumberConversions.toLong(value()); - } - - @Override - public short asShort() { - return NumberConversions.toShort(value()); - } - - @Override - public byte asByte() { - return NumberConversions.toByte(value()); - } - - @Override - 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; - } - - @Override - @NotNull - public String asString() { - Object value = value(); - - if (value == null) { - return ""; - } - return value.toString(); - } - -} diff --git a/api/src/main/java/org/bukkit/metadata/Metadatable.java b/api/src/main/java/org/bukkit/metadata/Metadatable.java deleted file mode 100644 index b35f41a15..000000000 --- a/api/src/main/java/org/bukkit/metadata/Metadatable.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.metadata; - -import java.util.List; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - public void setMetadata(@NotNull String metadataKey, @NotNull 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. - */ - @NotNull - public List getMetadata(@NotNull 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. - */ - public boolean hasMetadata(@NotNull 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 - */ - public void removeMetadata(@NotNull String metadataKey, @NotNull Plugin owningPlugin); -} diff --git a/api/src/main/java/org/bukkit/permissions/Permissible.java b/api/src/main/java/org/bukkit/permissions/Permissible.java deleted file mode 100644 index 228421154..000000000 --- a/api/src/main/java/org/bukkit/permissions/Permissible.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.bukkit.permissions; - -import java.util.Set; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - public boolean isPermissionSet(@NotNull 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 - */ - public boolean isPermissionSet(@NotNull 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 - */ - public boolean hasPermission(@NotNull 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 - */ - public boolean hasPermission(@NotNull 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 - */ - @NotNull - public PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull 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 - */ - @NotNull - public PermissionAttachment addAttachment(@NotNull 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 - */ - @Nullable - public PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull 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 - */ - @Nullable - public PermissionAttachment addAttachment(@NotNull 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 - */ - public void removeAttachment(@NotNull 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. - */ - public void recalculatePermissions(); - - /** - * Gets a set containing all of the permissions currently in effect by - * this object - * - * @return Set of currently effective permissions - */ - @NotNull - public Set getEffectivePermissions(); -} diff --git a/api/src/main/java/org/bukkit/permissions/PermissibleBase.java b/api/src/main/java/org/bukkit/permissions/PermissibleBase.java deleted file mode 100644 index c94e4cdb5..000000000 --- a/api/src/main/java/org/bukkit/permissions/PermissibleBase.java +++ /dev/null @@ -1,273 +0,0 @@ -package org.bukkit.permissions; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Base Permissible for use in any Permissible object via proxy or extension - */ -public class PermissibleBase implements Permissible { - private ServerOperator opable; - private Permissible parent = this; - private final List attachments = new LinkedList(); - private final Map permissions = new HashMap(); - - public PermissibleBase(@Nullable ServerOperator opable) { - this.opable = opable; - - if (opable instanceof Permissible) { - this.parent = (Permissible) opable; - } - - recalculatePermissions(); - } - - @Override - public boolean isOp() { - if (opable == null) { - return false; - } else { - return opable.isOp(); - } - } - - @Override - public void setOp(boolean value) { - if (opable == null) { - throw new UnsupportedOperationException("Cannot change op value as no ServerOperator is set"); - } else { - opable.setOp(value); - } - } - - @Override - public boolean isPermissionSet(@NotNull String name) { - if (name == null) { - throw new IllegalArgumentException("Permission name cannot be null"); - } - - return permissions.containsKey(name.toLowerCase(java.util.Locale.ENGLISH)); - } - - @Override - public boolean isPermissionSet(@NotNull Permission perm) { - if (perm == null) { - throw new IllegalArgumentException("Permission cannot be null"); - } - - return isPermissionSet(perm.getName()); - } - - @Override - public boolean hasPermission(@NotNull String inName) { - if (inName == null) { - throw new IllegalArgumentException("Permission name cannot be null"); - } - - String name = inName.toLowerCase(java.util.Locale.ENGLISH); - - // Paper start - PermissionAttachmentInfo info = permissions.get(name); - if (info != null) { - return info.getValue(); - // Paper end - } else { - Permission perm = Bukkit.getServer().getPluginManager().getPermission(name); - - if (perm != null) { - return perm.getDefault().getValue(isOp()); - } else { - return Permission.DEFAULT_PERMISSION.getValue(isOp()); - } - } - } - - @Override - public boolean hasPermission(@NotNull Permission perm) { - if (perm == null) { - throw new IllegalArgumentException("Permission cannot be null"); - } - - String name = perm.getName().toLowerCase(java.util.Locale.ENGLISH); - - // Paper start - PermissionAttachmentInfo info = permissions.get(name); - if (info != null) { - return info.getValue(); - } - // Paper end - return perm.getDefault().getValue(isOp()); - } - - @Override - @NotNull - public synchronized PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value) { // Paper - synchronized - 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; - } - - @Override - @NotNull - public synchronized PermissionAttachment addAttachment(@NotNull Plugin plugin) { // Paper - synchronized - 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; - } - - @Override - public synchronized void removeAttachment(@NotNull PermissionAttachment attachment) { // Paper - synchronized - 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); - } - } - - @Override - public synchronized void recalculatePermissions() { // Paper - synchronized - clearPermissions(); - Set defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp()); - Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent); - - for (Permission perm : defaults) { - String name = perm.getName().toLowerCase(java.util.Locale.ENGLISH); - 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(@NotNull Map children, boolean invert, @Nullable PermissionAttachment attachment) { - for (Map.Entry entry : children.entrySet()) { - String name = entry.getKey(); - - Permission perm = Bukkit.getServer().getPluginManager().getPermission(name); - boolean value = entry.getValue() ^ invert; - String lname = name.toLowerCase(java.util.Locale.ENGLISH); - - permissions.put(lname, new PermissionAttachmentInfo(parent, lname, attachment, value)); - Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent); - - if (perm != null) { - calculateChildPermissions(perm.getChildren(), !value, attachment); - } - } - } - - @Override - @Nullable - public synchronized PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value, int ticks) { // Paper - 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; - } - - @Override - @Nullable - public synchronized PermissionAttachment addAttachment(@NotNull Plugin plugin, int ticks) { // Paper - synchronized - 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; - } - } - - @Override - @NotNull - public synchronized Set getEffectivePermissions() { // Paper - synchronized - return new HashSet(permissions.values()); - } - - private static class RemoveAttachmentRunnable implements Runnable { - private PermissionAttachment attachment; - - public RemoveAttachmentRunnable(@NotNull PermissionAttachment attachment) { - this.attachment = attachment; - } - - @Override - public void run() { - attachment.remove(); - } - } -} diff --git a/api/src/main/java/org/bukkit/permissions/Permission.java b/api/src/main/java/org/bukkit/permissions/Permission.java deleted file mode 100644 index 91d45b965..000000000 --- a/api/src/main/java/org/bukkit/permissions/Permission.java +++ /dev/null @@ -1,356 +0,0 @@ -package org.bukkit.permissions; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.plugin.PluginManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull String name) { - this(name, null, null, null); - } - - public Permission(@NotNull String name, @Nullable String description) { - this(name, description, null, null); - } - - public Permission(@NotNull String name, @Nullable PermissionDefault defaultValue) { - this(name, null, defaultValue, null); - } - - public Permission(@NotNull String name, @Nullable String description, @Nullable PermissionDefault defaultValue) { - this(name, description, defaultValue, null); - } - - public Permission(@NotNull String name, @Nullable Map children) { - this(name, null, null, children); - } - - public Permission(@NotNull String name, @Nullable String description, @Nullable Map children) { - this(name, description, null, children); - } - - public Permission(@NotNull String name, @Nullable PermissionDefault defaultValue, @Nullable Map children) { - this(name, null, defaultValue, children); - } - - public Permission(@NotNull String name, @Nullable String description, @Nullable PermissionDefault defaultValue, @Nullable 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 - */ - @NotNull - 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 - */ - @NotNull - public Map getChildren() { - return children; - } - - /** - * Gets the default value of this permission. - * - * @return Default value of this permission. - */ - @NotNull - 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(@NotNull PermissionDefault value) { - if (defaultValue == null) { - throw new IllegalArgumentException("Default value cannot be null"); - } - - defaultValue = value; - recalculatePermissibles(); - } - - /** - * Gets a brief description of this permission, may be empty - * - * @return Brief description of this permission - */ - @NotNull - 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(@Nullable 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 - */ - @NotNull - 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 - */ - @NotNull - public Permission addParent(@NotNull String name, boolean value) { - PluginManager pm = Bukkit.getServer().getPluginManager(); - String lname = name.toLowerCase(java.util.Locale.ENGLISH); - - 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(@NotNull 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. May contain "%s" format tag, which will be replaced with the name of invalid permission. - * @param def Default permission value to use if missing - * @return Permission object - */ - @NotNull - public static List loadPermissions(@NotNull Map data, @NotNull String error, @Nullable 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 - */ - @NotNull - public static Permission loadPermission(@NotNull String name, @NotNull 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 - */ - @NotNull - public static Permission loadPermission(@NotNull String name, @NotNull Map data, @Nullable PermissionDefault def, @Nullable 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); - } - - @NotNull - private static Map extractChildren(@NotNull Map input, @NotNull String name, @Nullable PermissionDefault def, @Nullable 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/api/src/main/java/org/bukkit/permissions/PermissionAttachment.java b/api/src/main/java/org/bukkit/permissions/PermissionAttachment.java deleted file mode 100644 index cd8ac371a..000000000 --- a/api/src/main/java/org/bukkit/permissions/PermissionAttachment.java +++ /dev/null @@ -1,145 +0,0 @@ -package org.bukkit.permissions; - -import java.util.LinkedHashMap; -import java.util.Map; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull Plugin plugin, @NotNull 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 - */ - @NotNull - 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(@Nullable 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 - */ - @Nullable - public PermissionRemovedExecutor getRemovalCallback() { - return removed; - } - - /** - * Gets the Permissible that this is attached to - * - * @return Permissible containing this attachment - */ - @NotNull - 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 - */ - @NotNull - 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(@NotNull String name, boolean value) { - permissions.put(name.toLowerCase(java.util.Locale.ENGLISH), 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(@NotNull 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(@NotNull String name) { - permissions.remove(name.toLowerCase(java.util.Locale.ENGLISH)); - 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(@NotNull 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/api/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java b/api/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java deleted file mode 100644 index a7f4cd37c..000000000 --- a/api/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bukkit.permissions; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@NotNull Permissible permissible, @NotNull String permission, @Nullable PermissionAttachment attachment, boolean value) { - if (permissible == null) { - throw new IllegalArgumentException("Permissible may not be null"); - } else if (permission == null) { - throw new IllegalArgumentException("Permission 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 - */ - @NotNull - public Permissible getPermissible() { - return permissible; - } - - /** - * Gets the permission being set - * - * @return Name of the permission - */ - @NotNull - public String getPermission() { - return permission; - } - - /** - * Gets the attachment providing this permission. This may be null for - * default permissions (usually parent permissions). - * - * @return Attachment - */ - @Nullable - public PermissionAttachment getAttachment() { - return attachment; - } - - /** - * Gets the value of this permission - * - * @return Value of the permission - */ - public boolean getValue() { - return value; - } -} diff --git a/api/src/main/java/org/bukkit/permissions/PermissionDefault.java b/api/src/main/java/org/bukkit/permissions/PermissionDefault.java deleted file mode 100644 index 449df7c79..000000000 --- a/api/src/main/java/org/bukkit/permissions/PermissionDefault.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.bukkit.permissions; - -import java.util.HashMap; -import java.util.Map; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 static final Map lookup = new HashMap(); - - private PermissionDefault(/*@NotNull*/ 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 - */ - @Nullable - public static PermissionDefault getByName(@NotNull String name) { - return lookup.get(name.toLowerCase(java.util.Locale.ENGLISH).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/api/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java b/api/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java deleted file mode 100644 index 4cc9e6471..000000000 --- a/api/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.permissions; - -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - public void attachmentRemoved(@NotNull PermissionAttachment attachment); -} diff --git a/api/src/main/java/org/bukkit/permissions/ServerOperator.java b/api/src/main/java/org/bukkit/permissions/ServerOperator.java deleted file mode 100644 index 26ed24307..000000000 --- a/api/src/main/java/org/bukkit/permissions/ServerOperator.java +++ /dev/null @@ -1,24 +0,0 @@ -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 - */ - public boolean isOp(); - - /** - * Sets the operator status of this object - * - * @param value New operator value - */ - public void setOp(boolean value); -} diff --git a/api/src/main/java/org/bukkit/persistence/PersistentDataAdapterContext.java b/api/src/main/java/org/bukkit/persistence/PersistentDataAdapterContext.java deleted file mode 100644 index 8face93f3..000000000 --- a/api/src/main/java/org/bukkit/persistence/PersistentDataAdapterContext.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.persistence; - -import org.jetbrains.annotations.NotNull; - -/** - * This interface represents the context in which the {@link PersistentDataType} can - * serialize and deserialize the passed values. - */ -public interface PersistentDataAdapterContext { - - /** - * Creates a new and empty meta container instance. - * - * @return the fresh container instance - */ - @NotNull - PersistentDataContainer newPersistentDataContainer(); -} diff --git a/api/src/main/java/org/bukkit/persistence/PersistentDataContainer.java b/api/src/main/java/org/bukkit/persistence/PersistentDataContainer.java deleted file mode 100644 index 05a93aa31..000000000 --- a/api/src/main/java/org/bukkit/persistence/PersistentDataContainer.java +++ /dev/null @@ -1,141 +0,0 @@ -package org.bukkit.persistence; - -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * This interface represents a map like object, capable of storing custom tags - * in it. - */ -public interface PersistentDataContainer { - - /** - * Stores a metadata value on the {@link PersistentDataHolder} instance. - *

- * This API cannot be used to manipulate minecraft data, as the values will - * be stored using your namespace. This method will override any existing - * value the {@link PersistentDataHolder} may have stored under the provided - * key. - * - * @param key the key this value will be stored under - * @param type the type this tag uses - * @param value the value stored in the tag - * @param the generic java type of the tag value - * @param the generic type of the object to store - * - * @throws NullPointerException if the key is null - * @throws NullPointerException if the type is null - * @throws NullPointerException if the value is null. Removing a tag should - * be done using {@link #remove(NamespacedKey)} - * @throws IllegalArgumentException if no suitable adapter will be found for - * the {@link PersistentDataType#getPrimitiveType()} - */ - void set(@NotNull NamespacedKey key, @NotNull PersistentDataType type, @NotNull Z value); - - /** - * Returns if the persistent metadata provider has metadata registered - * matching the provided parameters. - *

- * This method will only return if the found value has the same primitive - * data type as the provided key. - *

- * Storing a value using a custom {@link PersistentDataType} implementation - * will not store the complex data type. Therefore storing a UUID (by - * storing a byte[]) will match has("key" , - * {@link PersistentDataType#BYTE_ARRAY}). Likewise a stored byte[] will - * always match your UUID {@link PersistentDataType} even if it is not 16 - * bytes long. - *

- * This method is only usable for custom object keys. Overwriting existing - * tags, like the the display name, will not work as the values are stored - * using your namespace. - * - * @param key the key the value is stored under - * @param type the type which primitive storage type has to match the value - * @param the generic type of the stored primitive - * @param the generic type of the eventually created complex object - * - * @return if a value - * - * @throws NullPointerException if the key to look up is null - * @throws NullPointerException if the type to cast the found object to is - * null - */ - boolean has(@NotNull NamespacedKey key, @NotNull PersistentDataType type); - - /** - * Returns the metadata value that is stored on the - * {@link PersistentDataHolder} instance. - * - * @param key the key to look up in the custom tag map - * @param type the type the value must have and will be casted to - * @param the generic type of the stored primitive - * @param the generic type of the eventually created complex object - * - * @return the value or {@code null} if no value was mapped under the given - * value - * - * @throws NullPointerException if the key to look up is null - * @throws NullPointerException if the type to cast the found object to is - * null - * @throws IllegalArgumentException if the value exists under the given key, - * but cannot be access using the given type - * @throws IllegalArgumentException if no suitable adapter will be found for - * the {@link - * PersistentDataType#getPrimitiveType()} - */ - @Nullable - Z get(@NotNull NamespacedKey key, @NotNull PersistentDataType type); - - /** - * Returns the metadata value that is stored on the - * {@link PersistentDataHolder} instance. If the value does not exist in the - * container, the default value provided is returned. - * - * @param key the key to look up in the custom tag map - * @param type the type the value must have and will be casted to - * @param defaultValue the default value to return if no value was found for - * the provided key - * @param the generic type of the stored primitive - * @param the generic type of the eventually created complex object - * - * @return the value or the default value if no value was mapped under the - * given value - * - * @throws NullPointerException if the key to look up is null - * @throws NullPointerException if the type to cast the found object to is - * null - * @throws IllegalArgumentException if the value exists under the given key, - * but cannot be access using the given type - * @throws IllegalArgumentException if no suitable adapter will be found for - * the {@link PersistentDataType#getPrimitiveType()} - */ - @NotNull - Z getOrDefault(@NotNull NamespacedKey key, @NotNull PersistentDataType type, @NotNull Z defaultValue); - - /** - * Removes a custom key from the {@link PersistentDataHolder} instance. - * - * @param key the key - * - * @throws NullPointerException if the provided key is null - */ - void remove(@NotNull NamespacedKey key); - - /** - * Returns if the container instance is empty, therefore has no entries - * inside it. - * - * @return the boolean - */ - boolean isEmpty(); - - /** - * Returns the adapter context this tag container uses. - * - * @return the tag context - */ - @NotNull - PersistentDataAdapterContext getAdapterContext(); -} diff --git a/api/src/main/java/org/bukkit/persistence/PersistentDataHolder.java b/api/src/main/java/org/bukkit/persistence/PersistentDataHolder.java deleted file mode 100644 index 80b277cc5..000000000 --- a/api/src/main/java/org/bukkit/persistence/PersistentDataHolder.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.persistence; - -import org.jetbrains.annotations.NotNull; - -/** - * The {@link PersistentDataHolder} interface defines an object that can store - * custom persistent meta data on it. - */ -public interface PersistentDataHolder { - - /** - * Returns a custom tag container capable of storing tags on the object. - * - * Note that the tags stored on this container are all stored under their - * own custom namespace therefore modifying default tags using this - * {@link PersistentDataHolder} is impossible. - * - * @return the persistent metadata container - */ - @NotNull - PersistentDataContainer getPersistentDataContainer(); - -} diff --git a/api/src/main/java/org/bukkit/persistence/PersistentDataType.java b/api/src/main/java/org/bukkit/persistence/PersistentDataType.java deleted file mode 100644 index b229b4440..000000000 --- a/api/src/main/java/org/bukkit/persistence/PersistentDataType.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.bukkit.persistence; - -import org.jetbrains.annotations.NotNull; - -/** - * This class represents an enum with a generic content type. It defines the - * types a custom tag can have. - *

- * This interface can be used to create your own custom - * {@link PersistentDataType} with different complex types. This may be useful - * for the likes of a UUIDTagType: - *

- * {@code
- * public class UUIDTagType implements PersistentDataType {
- *
- *         {@literal @Override}
- *         public Class getPrimitiveType() {
- *             return byte[].class;
- *         }
- *
- *         {@literal @Override}
- *         public Class getComplexType() {
- *             return UUID.class;
- *         }
- *
- *         {@literal @Override}
- *         public byte[] toPrimitive(UUID complex, PersistentDataAdapterContext context) {
- *             ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
- *             bb.putLong(complex.getMostSignificantBits());
- *             bb.putLong(complex.getLeastSignificantBits());
- *             return bb.array();
- *         }
- *
- *         {@literal @Override}
- *         public UUID fromPrimitive(byte[] primitive, PersistentDataAdapterContext context) {
- *             ByteBuffer bb = ByteBuffer.wrap(primitive);
- *             long firstLong = bb.getLong();
- *             long secondLong = bb.getLong();
- *             return new UUID(firstLong, secondLong);
- *         }
- *     }}
- * - * @param the primary object type that is stored in the given tag - * @param the retrieved object type when applying this tag type - */ -public interface PersistentDataType { - - /* - The primitive one value types. - */ - PersistentDataType BYTE = new PrimitivePersistentDataType<>(Byte.class); - PersistentDataType SHORT = new PrimitivePersistentDataType<>(Short.class); - PersistentDataType INTEGER = new PrimitivePersistentDataType<>(Integer.class); - PersistentDataType LONG = new PrimitivePersistentDataType<>(Long.class); - PersistentDataType FLOAT = new PrimitivePersistentDataType<>(Float.class); - PersistentDataType DOUBLE = new PrimitivePersistentDataType<>(Double.class); - - /* - String. - */ - PersistentDataType STRING = new PrimitivePersistentDataType<>(String.class); - - /* - Primitive Arrays. - */ - PersistentDataType BYTE_ARRAY = new PrimitivePersistentDataType<>(byte[].class); - PersistentDataType INTEGER_ARRAY = new PrimitivePersistentDataType<>(int[].class); - PersistentDataType LONG_ARRAY = new PrimitivePersistentDataType<>(long[].class); - - /* - Nested PersistentDataContainer. - */ - PersistentDataType TAG_CONTAINER = new PrimitivePersistentDataType<>(PersistentDataContainer.class); - - /** - * Returns the primitive data type of this tag. - * - * @return the class - */ - @NotNull - Class getPrimitiveType(); - - /** - * Returns the complex object type the primitive value resembles. - * - * @return the class type - */ - @NotNull - Class getComplexType(); - - /** - * Returns the primitive data that resembles the complex object passed to - * this method. - * - * @param complex the complex object instance - * @param context the context this operation is running in - * @return the primitive value - */ - @NotNull - T toPrimitive(@NotNull Z complex, @NotNull PersistentDataAdapterContext context); - - /** - * Creates a complex object based of the passed primitive value - * - * @param primitive the primitive value - * @param context the context this operation is running in - * @return the complex object instance - */ - @NotNull - Z fromPrimitive(@NotNull T primitive, @NotNull PersistentDataAdapterContext context); - - /** - * A default implementation that simply exists to pass on the retrieved or - * inserted value to the next layer. - *

- * This implementation does not add any kind of logic, but is used to - * provide default implementations for the primitive types. - * - * @param the generic type of the primitive objects - */ - class PrimitivePersistentDataType implements PersistentDataType { - - private final Class primitiveType; - - PrimitivePersistentDataType(@NotNull Class primitiveType) { - this.primitiveType = primitiveType; - } - - @NotNull - @Override - public Class getPrimitiveType() { - return primitiveType; - } - - @NotNull - @Override - public Class getComplexType() { - return primitiveType; - } - - @NotNull - @Override - public T toPrimitive(@NotNull T complex, @NotNull PersistentDataAdapterContext context) { - return complex; - } - - @NotNull - @Override - public T fromPrimitive(@NotNull T primitive, @NotNull PersistentDataAdapterContext context) { - return primitive; - } - } -} diff --git a/api/src/main/java/org/bukkit/plugin/AuthorNagException.java b/api/src/main/java/org/bukkit/plugin/AuthorNagException.java deleted file mode 100644 index 6565a4414..000000000 --- a/api/src/main/java/org/bukkit/plugin/AuthorNagException.java +++ /dev/null @@ -1,20 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/EventExecutor.java b/api/src/main/java/org/bukkit/plugin/EventExecutor.java deleted file mode 100644 index 9026e108c..000000000 --- a/api/src/main/java/org/bukkit/plugin/EventExecutor.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.bukkit.plugin; - -import org.bukkit.event.Event; -import org.bukkit.event.EventException; -import org.bukkit.event.Listener; -import org.jetbrains.annotations.NotNull; - -// Paper start -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; - -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; -// Paper end - -/** - * Interface which defines the class for event call backs to plugins - */ -public interface EventExecutor { - public void execute(@NotNull Listener listener, @NotNull 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/api/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java b/api/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java deleted file mode 100644 index b25447dcf..000000000 --- a/api/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java +++ /dev/null @@ -1,25 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java b/api/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java deleted file mode 100644 index 0a77c2e21..000000000 --- a/api/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java +++ /dev/null @@ -1,45 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/InvalidPluginException.java b/api/src/main/java/org/bukkit/plugin/InvalidPluginException.java deleted file mode 100644 index 7ddf7b626..000000000 --- a/api/src/main/java/org/bukkit/plugin/InvalidPluginException.java +++ /dev/null @@ -1,49 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/Plugin.java b/api/src/main/java/org/bukkit/plugin/Plugin.java deleted file mode 100644 index 79890c68f..000000000 --- a/api/src/main/java/org/bukkit/plugin/Plugin.java +++ /dev/null @@ -1,186 +0,0 @@ -package org.bukkit.plugin; - -import java.io.File; -import java.io.InputStream; -import java.util.logging.Logger; -import org.bukkit.Server; -import org.bukkit.command.TabExecutor; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.generator.ChunkGenerator; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @NotNull - public File getDataFolder(); - - /** - * Returns the plugin.yaml file containing the details for this plugin - * - * @return Contents of the plugin.yaml file - */ - @NotNull - public 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 - */ - @NotNull - public FileConfiguration getConfig(); - - /** - * Gets an embedded resource in this plugin - * - * @param filename Filename of the resource - * @return File if found, otherwise null - */ - @Nullable - public InputStream getResource(@NotNull String filename); - - /** - * Saves the {@link FileConfiguration} retrievable by {@link #getConfig()}. - */ - public void saveConfig(); - - /** - * Saves the raw contents of the default config.yml file to the location - * retrievable by {@link #getConfig()}. - *

- * This should fail silently if the config.yml already exists. - */ - public 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. - */ - public void saveResource(@NotNull String resourcePath, boolean replace); - - /** - * Discards any data in {@link #getConfig()} and reloads from disk. - */ - public void reloadConfig(); - - /** - * Gets the associated PluginLoader responsible for this plugin - * - * @return PluginLoader that controls this plugin - */ - @NotNull - public PluginLoader getPluginLoader(); - - /** - * Returns the Server instance currently running this plugin - * - * @return Server running this plugin - */ - @NotNull - public Server getServer(); - - /** - * Returns a value indicating whether or not this plugin is currently - * enabled - * - * @return true if this plugin is enabled, otherwise false - */ - public boolean isEnabled(); - - /** - * Called when this plugin is disabled - */ - public void onDisable(); - - /** - * Called after a plugin is loaded but before it has been enabled. - *

- * When multiple plugins are loaded, the onLoad() for all plugins is - * called before any onEnable() is called. - */ - public void onLoad(); - - /** - * Called when this plugin is enabled - */ - public void onEnable(); - - /** - * Simple boolean if we can still nag to the logs about things - * - * @return boolean whether we can nag - */ - public boolean isNaggable(); - - /** - * Set naggable state - * - * @param canNag is this plugin still naggable? - */ - public void setNaggable(boolean canNag); - - /** - * 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 - */ - @Nullable - public ChunkGenerator getDefaultWorldGenerator(@NotNull String worldName, @Nullable 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 - */ - @NotNull - public Logger getLogger(); - - // Paper start - Add SLF4J logger - @NotNull - default org.slf4j.Logger getSLF4JLogger() { - return org.slf4j.LoggerFactory.getLogger(getLogger().getName()); - } - // Paper end - - /** - * 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 - */ - @NotNull - public String getName(); -} diff --git a/api/src/main/java/org/bukkit/plugin/PluginAwareness.java b/api/src/main/java/org/bukkit/plugin/PluginAwareness.java deleted file mode 100644 index 3f535ed5d..000000000 --- a/api/src/main/java/org/bukkit/plugin/PluginAwareness.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.plugin; - -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)}. - */ - public enum Flags implements PluginAwareness { - /** - * This specifies that all (text) resources stored in a plugin's jar - * use UTF-8 encoding. - * - * @deprecated all plugins are now assumed to be UTF-8 aware. - */ - @Deprecated - UTF8, - ; - } -} diff --git a/api/src/main/java/org/bukkit/plugin/PluginBase.java b/api/src/main/java/org/bukkit/plugin/PluginBase.java deleted file mode 100644 index 94f8ceb96..000000000 --- a/api/src/main/java/org/bukkit/plugin/PluginBase.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.plugin; - -import org.jetbrains.annotations.NotNull; - -/** - * 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()); - } - - @Override - @NotNull - public final String getName() { - return getDescription().getName(); - } -} diff --git a/api/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java b/api/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java deleted file mode 100644 index cb31a6d5a..000000000 --- a/api/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java +++ /dev/null @@ -1,1142 +0,0 @@ -package org.bukkit.plugin; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import java.io.InputStream; -import java.io.Reader; -import java.io.Writer; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.command.TabCompleter; -import org.bukkit.permissions.Permissible; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; -import org.bukkit.plugin.java.JavaPlugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -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; - -/** - * 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
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
api-version{@link #getAPIVersion()}The API version which this plugin was programmed against
- *

- * 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
- *depend: [NewFire, FlameWire]
- *api-version: 1.13
- *
- *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 Pattern VALID_NAME = Pattern.compile("^[A-Za-z0-9 _.-]+$"); - private static final ThreadLocal YAML = new ThreadLocal() { - @Override - @NotNull - protected Yaml initialValue() { - return new Yaml(new SafeConstructor() { - { - yamlConstructors.put(null, new AbstractConstruct() { - @NotNull - @Override - public Object construct(@NotNull 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() { - @NotNull - @Override - public PluginAwareness.Flags construct(@NotNull 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 = ImmutableMap.of(); - private String description = null; - private List authors = null; - private String website = null; - private String prefix = null; - private PluginLoadOrder order = PluginLoadOrder.POSTWORLD; - private List permissions = null; - private Map lazyPermissions = null; - private PermissionDefault defaultPerm = PermissionDefault.OP; - private Set awareness = ImmutableSet.of(); - private String apiVersion = null; - - public PluginDescriptionFile(@NotNull 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(@NotNull 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(@NotNull final String pluginName, @NotNull final String pluginVersion, @NotNull final String mainClass) { - name = rawName = pluginName; - - if (!VALID_NAME.matcher(name).matches()) { - throw new IllegalArgumentException("name '" + name + "' contains invalid characters."); - } - name = name.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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @Nullable - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @Nullable - public String getWebsite() { - return website; - } - - /** - * 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @Nullable - 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)} 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - public String getFullName() { - return name + " v" + version; - } - - /** - * Gives the API version which this plugin is designed to support. No - * specific format is guaranteed. - *

    - *
  • Refer to release notes for supported API versions. - *
- *

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

- * Example:

api-version: 1.13
- * - * @return the version of the plugin - */ - @Nullable - public String getAPIVersion() { - return apiVersion; - } - - /** - * @return unused - * @deprecated unused - */ - @Deprecated - @Nullable - public String getClassLoaderOf() { - return classLoaderOf; - } - - /** - * Saves this PluginDescriptionFile to the given writer - * - * @param writer Writer to output this file to - */ - public void save(@NotNull Writer writer) { - YAML.get().dump(saveMap(), writer); - } - - private void loadMap(@NotNull Map map) throws InvalidDescriptionException { - try { - name = rawName = map.get("name").toString(); - - if (!VALID_NAME.matcher(name).matches()) { - 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("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(java.util.Locale.ENGLISH).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); - } - - if (map.get("api-version") != null) { - apiVersion = map.get("api-version").toString(); - } - - 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(); - } - } - - @NotNull - private static List makePluginNameList(@NotNull final Map map, @NotNull 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(); - } - - @NotNull - private Map saveMap() { - Map map = new HashMap(); - - map.put("name", name); - map.put("main", main); - map.put("version", version); - 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 (apiVersion != null) { - map.put("api-version", apiVersion); - } - - if (classLoaderOf != null) { - map.put("class-loader-of", classLoaderOf); - } - - if (prefix != null) { - map.put("prefix", prefix); - } - - return map; - } - - @NotNull - private Map asMap(@NotNull 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 - @NotNull - public String getRawName() { - return rawName; - } -} diff --git a/api/src/main/java/org/bukkit/plugin/PluginLoadOrder.java b/api/src/main/java/org/bukkit/plugin/PluginLoadOrder.java deleted file mode 100644 index b77436fdd..000000000 --- a/api/src/main/java/org/bukkit/plugin/PluginLoadOrder.java +++ /dev/null @@ -1,17 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/PluginLoader.java b/api/src/main/java/org/bukkit/plugin/PluginLoader.java deleted file mode 100644 index 6ab9cd821..000000000 --- a/api/src/main/java/org/bukkit/plugin/PluginLoader.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.bukkit.plugin; - -import java.io.File; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import org.bukkit.event.Event; -import org.bukkit.event.Listener; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public Plugin loadPlugin(@NotNull 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 - */ - @NotNull - public PluginDescriptionFile getPluginDescription(@NotNull File file) throws InvalidDescriptionException; - - /** - * Returns a list of all filename filters expected by this PluginLoader - * - * @return The filters - */ - @NotNull - public 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. - */ - @NotNull - public Map, Set> createRegisteredListeners(@NotNull Listener listener, @NotNull Plugin plugin); - - /** - * Enables the specified plugin - *

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

- * Attempting to disable a plugin that is not enabled will have no effect - * - * @param plugin Plugin to disable - */ - public void disablePlugin(@NotNull Plugin plugin); - // Paper start - close Classloader on disable - /** - * Disables the specified plugin - *

- * Attempting to disable a plugin that is not enabled will have no effect - * - * @param plugin Plugin to disable - * @param closeClassloader if the classloader for the Plugin should be closed - */ - // provide default to allow other PluginLoader implementations to work - default public void disablePlugin(@NotNull Plugin plugin, boolean closeClassloader) { - disablePlugin(plugin); - } - // Paper end - close Classloader on disable -} diff --git a/api/src/main/java/org/bukkit/plugin/PluginLogger.java b/api/src/main/java/org/bukkit/plugin/PluginLogger.java deleted file mode 100644 index 018237001..000000000 --- a/api/src/main/java/org/bukkit/plugin/PluginLogger.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.plugin; - -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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(@NotNull LogRecord logRecord) { - logRecord.setMessage(pluginName + logRecord.getMessage()); - super.log(logRecord); - } - -} diff --git a/api/src/main/java/org/bukkit/plugin/PluginManager.java b/api/src/main/java/org/bukkit/plugin/PluginManager.java deleted file mode 100644 index 86cc5025a..000000000 --- a/api/src/main/java/org/bukkit/plugin/PluginManager.java +++ /dev/null @@ -1,318 +0,0 @@ -package org.bukkit.plugin; - -import java.io.File; -import java.util.Set; -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 org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - public void registerInterface(@NotNull 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 - */ - @Nullable - public Plugin getPlugin(@NotNull String name); - - /** - * Gets a list of all currently loaded plugins - * - * @return Array of Plugins - */ - @NotNull - public 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 - */ - public boolean isPluginEnabled(@NotNull 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 - */ - @Contract("null -> false") - public boolean isPluginEnabled(@Nullable Plugin plugin); - - /** - * 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 - */ - @Nullable - public Plugin loadPlugin(@NotNull 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 - */ - @NotNull - public Plugin[] loadPlugins(@NotNull File directory); - - /** - * Disables all the loaded plugins - */ - public void disablePlugins(); - - /** - * Disables and removes all plugins - */ - public 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. - */ - public void callEvent(@NotNull Event event) throws IllegalStateException; - - /** - * Registers all the events in the given listener class - * - * @param listener Listener to register - * @param plugin Plugin to register - */ - public void registerEvents(@NotNull Listener listener, @NotNull 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 - */ - public void registerEvent(@NotNull Class event, @NotNull Listener listener, @NotNull EventPriority priority, @NotNull EventExecutor executor, @NotNull 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 - */ - public void registerEvent(@NotNull Class event, @NotNull Listener listener, @NotNull EventPriority priority, @NotNull EventExecutor executor, @NotNull 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 - */ - public void enablePlugin(@NotNull Plugin plugin); - - /** - * Disables the specified plugin - *

- * Attempting to disable a plugin that is not enabled will have no effect - * - * @param plugin Plugin to disable - */ - public void disablePlugin(@NotNull Plugin plugin); - - // Paper start - close Classloader on disable - /** - * Disables the specified plugin - *

- * Attempting to disable a plugin that is not enabled will have no effect - * - * @param plugin Plugin to disable - * @param closeClassloader if the classloader for the Plugin should be closed - */ - public void disablePlugin(@NotNull Plugin plugin, boolean closeClassloader); - // Paper end - close Classloader on disable - - /** - * Gets a {@link Permission} from its fully qualified name - * - * @param name Name of the permission - * @return Permission, or null if none - */ - @Nullable - public Permission getPermission(@NotNull 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 - */ - public void addPermission(@NotNull 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 - */ - public void removePermission(@NotNull 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 - */ - public void removePermission(@NotNull String name); - - /** - * Gets the default permissions for the given op status - * - * @param op Which set of default permissions to get - * @return The default permissions - */ - @NotNull - public 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 - */ - public void recalculatePermissionDefaults(@NotNull 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 - */ - public void subscribeToPermission(@NotNull String permission, @NotNull Permissible permissible); - - /** - * Unsubscribes the given Permissible for information about the requested - * Permission, by name. - * - * @param permission Permission to unsubscribe from - * @param permissible Permissible subscribing - */ - public void unsubscribeFromPermission(@NotNull String permission, @NotNull 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 - */ - @NotNull - public Set getPermissionSubscriptions(@NotNull 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 - */ - public void subscribeToDefaultPerms(boolean op, @NotNull Permissible permissible); - - /** - * Unsubscribes from the given Default permissions by operator status - * - * @param op Default list to unsubscribe from - * @param permissible Permissible subscribing - */ - public void unsubscribeFromDefaultPerms(boolean op, @NotNull 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 - */ - @NotNull - public 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 - */ - @NotNull - public Set getPermissions(); - - /** - * Returns whether or not timing code should be used for event calls - * - * @return True if event timings are to be used - */ - public boolean useTimings(); -} diff --git a/api/src/main/java/org/bukkit/plugin/RegisteredListener.java b/api/src/main/java/org/bukkit/plugin/RegisteredListener.java deleted file mode 100644 index 419aec56b..000000000 --- a/api/src/main/java/org/bukkit/plugin/RegisteredListener.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.bukkit.plugin; - -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.EventException; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Listener listener, @NotNull final EventExecutor executor, @NotNull final EventPriority priority, @NotNull 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 - */ - @NotNull - public Listener getListener() { - return listener; - } - - /** - * Gets the plugin for this registration - * - * @return Registered Plugin - */ - @NotNull - public Plugin getPlugin() { - return plugin; - } - - /** - * Gets the priority for this registration - * - * @return Registered Priority - */ - @NotNull - 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(@NotNull 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/api/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java b/api/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java deleted file mode 100644 index f45171937..000000000 --- a/api/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.plugin; - -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Class service, @NotNull T provider, @NotNull ServicePriority priority, @NotNull Plugin plugin) { - this.service = service; - this.plugin = plugin; - this.provider = provider; - this.priority = priority; - } - - @NotNull - public Class getService() { - return service; - } - - @NotNull - public Plugin getPlugin() { - return plugin; - } - - @NotNull - public T getProvider() { - return provider; - } - - @NotNull - public ServicePriority getPriority() { - return priority; - } - - @Override - public int compareTo(@NotNull RegisteredServiceProvider other) { - if (priority.ordinal() == other.getPriority().ordinal()) { - return 0; - } else { - return priority.ordinal() < other.getPriority().ordinal() ? 1 : -1; - } - } -} diff --git a/api/src/main/java/org/bukkit/plugin/ServicePriority.java b/api/src/main/java/org/bukkit/plugin/ServicePriority.java deleted file mode 100644 index 4afe0fb32..000000000 --- a/api/src/main/java/org/bukkit/plugin/ServicePriority.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bukkit.plugin; - -/** - * Represents various priorities of a provider. - */ -public enum ServicePriority { - Lowest, - Low, - Normal, - High, - Highest -} diff --git a/api/src/main/java/org/bukkit/plugin/ServicesManager.java b/api/src/main/java/org/bukkit/plugin/ServicesManager.java deleted file mode 100644 index 9e2f00572..000000000 --- a/api/src/main/java/org/bukkit/plugin/ServicesManager.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.bukkit.plugin; - -import java.util.Collection; -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - public void register(@NotNull Class service, @NotNull T provider, @NotNull Plugin plugin, @NotNull ServicePriority priority); - - /** - * Unregister all the providers registered by a particular plugin. - * - * @param plugin The plugin - */ - public void unregisterAll(@NotNull Plugin plugin); - - /** - * Unregister a particular provider for a particular service. - * - * @param service The service interface - * @param provider The service provider implementation - */ - public void unregister(@NotNull Class service, @NotNull Object provider); - - /** - * Unregister a particular provider. - * - * @param provider The service provider implementation - */ - public void unregister(@NotNull 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 - */ - @Nullable - public T load(@NotNull 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 - */ - @Nullable - public RegisteredServiceProvider getRegistration(@NotNull Class service); - - /** - * Get registrations of providers for a plugin. - * - * @param plugin The plugin - * @return provider registrations - */ - @NotNull - public List> getRegistrations(@NotNull 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 - */ - @NotNull - public Collection> getRegistrations(@NotNull Class service); - - /** - * Get a list of known services. A service is known if it has registered - * providers for it. - * - * @return list of known services - */ - @NotNull - public 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 - */ - public boolean isProvidedFor(@NotNull Class service); - -} diff --git a/api/src/main/java/org/bukkit/plugin/SimplePluginManager.java b/api/src/main/java/org/bukkit/plugin/SimplePluginManager.java deleted file mode 100644 index d0e735bc3..000000000 --- a/api/src/main/java/org/bukkit/plugin/SimplePluginManager.java +++ /dev/null @@ -1,829 +0,0 @@ -package org.bukkit.plugin; - -import com.google.common.collect.ImmutableSet; -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.destroystokyo.paper.event.server.ServerExceptionEvent; -import com.destroystokyo.paper.exception.ServerEventException; -import com.destroystokyo.paper.exception.ServerPluginEnableDisableException; -import org.apache.commons.lang.Validate; -import org.bukkit.Server; -import org.bukkit.World; -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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 File updateDirectory; - 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>(); - private boolean useTimings = false; - - public SimplePluginManager(@NotNull Server instance, @NotNull SimpleCommandMap commandMap) { - server = instance; - this.commandMap = commandMap; - - defaultPerms.put(true, new LinkedHashSet()); - defaultPerms.put(false, new LinkedHashSet()); - } - - /** - * 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 - */ - @Override - public void registerInterface(@NotNull 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 - */ - @Override - @NotNull - public Plugin[] loadPlugins(@NotNull 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 : 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 = null; - 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().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': uses the space-character (0x20) in its name"); - continue; - } - } 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.entrySet().iterator(); - - while (pluginIterator.hasNext()) { - Map.Entry entry = pluginIterator.next(); - String plugin = entry.getKey(); - - 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; - pluginIterator.remove(); - softDependencies.remove(plugin); - dependencies.remove(plugin); - - server.getLogger().log( - Level.SEVERE, - "Could not load '" + entry.getValue().getPath() + "' in folder '" + directory.getPath() + "'", - new UnknownDependencyException(dependency)); - break; - } - } - - if (dependencies.containsKey(plugin) && dependencies.get(plugin).isEmpty()) { - dependencies.remove(plugin); - } - } - if (softDependencies.containsKey(plugin)) { - Iterator softDependencyIterator = softDependencies.get(plugin).iterator(); - - while (softDependencyIterator.hasNext()) { - String softDependency = softDependencyIterator.next(); - - // Soft depend is no longer around - if (!plugins.containsKey(softDependency)) { - softDependencyIterator.remove(); - } - } - - 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 { - result.add(loadPlugin(file)); - loadedPlugins.add(plugin); - continue; - } 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.entrySet().iterator(); - - while (pluginIterator.hasNext()) { - Map.Entry entry = pluginIterator.next(); - String plugin = entry.getKey(); - - if (!dependencies.containsKey(plugin)) { - softDependencies.remove(plugin); - missingDependency = false; - File file = entry.getValue(); - pluginIterator.remove(); - - try { - result.add(loadPlugin(file)); - 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[result.size()]); - } - - /** - * 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 - */ - @Override - @Nullable - public synchronized Plugin loadPlugin(@NotNull 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(java.util.Locale.ENGLISH), result); // Paper - } - - return result; - } - - private void checkUpdate(@NotNull 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 - */ - @Override - @Nullable - public synchronized Plugin getPlugin(@NotNull String name) { - return lookupNames.get(name.replace(' ', '_').toLowerCase(java.util.Locale.ENGLISH)); // Paper - } - - @Override - @NotNull - public synchronized Plugin[] getPlugins() { - return plugins.toArray(new Plugin[plugins.size()]); - } - - /** - * 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 - */ - @Override - public boolean isPluginEnabled(@NotNull 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 - */ - @Override - public synchronized boolean isPluginEnabled(@Nullable Plugin plugin) { // Paper - synchronize - if ((plugin != null) && (plugins.contains(plugin))) { - return plugin.isEnabled(); - } else { - return false; - } - } - - @Override - public synchronized void enablePlugin(@NotNull final Plugin plugin) { // Paper - synchronize - 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) { - handlePluginException("Error occurred (in the plugin loader) while enabling " - + plugin.getDescription().getFullName() + " (Is it up to date?)", ex, plugin); - } - - HandlerList.bakeAll(); - } - } - - @Override - public void disablePlugins() { - disablePlugins(false); - } - - public void disablePlugins(boolean closeClassloaders) { - // Paper end - close Classloader on disable - Plugin[] plugins = getPlugins(); - for (int i = plugins.length - 1; i >= 0; i--) { - disablePlugin(plugins[i], closeClassloaders); // Paper - close Classloader on disable - } - } - - @Override - public void disablePlugin(@NotNull final Plugin plugin) { - disablePlugin(plugin, false); - } - - @Override - public synchronized void disablePlugin(@NotNull final Plugin plugin, boolean closeClassloader) { // Paper - synchronize - // Paper end - close Classloader on disable - if (plugin.isEnabled()) { - try { - plugin.getPluginLoader().disablePlugin(plugin, closeClassloader); // Paper - close Classloader on disable - } catch (Throwable ex) { - handlePluginException("Error occurred (in the plugin loader) while disabling " - + plugin.getDescription().getFullName() + " (Is it up to date?)", ex, plugin); // Paper - } - - try { - server.getScheduler().cancelTasks(plugin); - } catch (Throwable ex) { - handlePluginException("Error occurred (in the plugin loader) while cancelling tasks for " - + plugin.getDescription().getFullName() + " (Is it up to date?)", ex, plugin); // Paper - } - - try { - server.getServicesManager().unregisterAll(plugin); - } catch (Throwable ex) { - handlePluginException("Error occurred (in the plugin loader) while unregistering services for " - + plugin.getDescription().getFullName() + " (Is it up to date?)", ex, plugin); // Paper - } - - try { - HandlerList.unregisterAll(plugin); - } catch (Throwable ex) { - handlePluginException("Error occurred (in the plugin loader) while unregistering events for " - + plugin.getDescription().getFullName() + " (Is it up to date?)", ex, plugin); // Paper - } - - try { - server.getMessenger().unregisterIncomingPluginChannel(plugin); - server.getMessenger().unregisterOutgoingPluginChannel(plugin); - } catch (Throwable ex) { - handlePluginException("Error occurred (in the plugin loader) while unregistering plugin channels for " - + plugin.getDescription().getFullName() + " (Is it up to date?)", ex, plugin); // Paper - } - - try { - for (World world : server.getWorlds()) { - world.removePluginChunkTickets(plugin); - } - } catch (Throwable ex) { - server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while removing chunk tickets for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); - } - } - } - - // Paper start - private void handlePluginException(String msg, Throwable ex, Plugin plugin) { - server.getLogger().log(Level.SEVERE, msg, ex); - callEvent(new ServerExceptionEvent(new ServerPluginEnableDisableException(msg, ex, plugin))); - } - // Paper end - - @Override - public void clearPlugins() { - synchronized (this) { - disablePlugins(true); // Paper - close Classloader on disable - plugins.clear(); - lookupNames.clear(); - HandlerList.unregisterAll(); - fileAssociations.clear(); - permissions.clear(); - defaultPerms.get(true).clear(); - defaultPerms.get(false).clear(); - } - } - private void fireEvent(Event event) { callEvent(event); } // Paper - support old method incase plugin uses reflection - - /** - * Calls an event with the given details. - *

- * This method only synchronizes when the event is not asynchronous. - * - * @param event Event details - */ - @Override - public void callEvent(@NotNull Event event) { - // Paper - replace callEvent by merging to below method - if (event.isAsynchronous() && server.isPrimaryThread()) { - throw new IllegalStateException(event.getEventName() + " may only be triggered asynchronously."); - } else if (!event.isAsynchronous() && !server.isPrimaryThread()) { - throw new IllegalStateException(event.getEventName() + " may only be triggered synchronously."); - } - - 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) { - // Paper start - error reporting - String msg = "Could not pass event " + event.getEventName() + " to " + registration.getPlugin().getDescription().getFullName(); - server.getLogger().log(Level.SEVERE, msg, ex); - if (!(event instanceof ServerExceptionEvent)) { // We don't want to cause an endless event loop - callEvent(new ServerExceptionEvent(new ServerEventException(msg, ex, registration.getPlugin(), registration.getListener(), event))); - } - // Paper end - } - } - } - - @Override - public void registerEvents(@NotNull Listener listener, @NotNull 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()); - } - - } - - @Override - public void registerEvent(@NotNull Class event, @NotNull Listener listener, @NotNull EventPriority priority, @NotNull EventExecutor executor, @NotNull 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 - */ - @Override - public void registerEvent(@NotNull Class event, @NotNull Listener listener, @NotNull EventPriority priority, @NotNull EventExecutor executor, @NotNull 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"); - } - - executor = new co.aikar.timings.TimedEventExecutor(executor, plugin, null, event); // Paper - if (false) { // Spigot - RL handles useTimings check now // Paper - getEventListeners(event).register(new TimedRegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); - } else { - getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); - } - } - - @NotNull - private HandlerList getEventListeners(@NotNull 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()); - } - } - - @NotNull - private Class getRegistrationClass(@NotNull 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!"); - } - } - } - - @Override - @Nullable - public Permission getPermission(@NotNull String name) { - return permissions.get(name.toLowerCase(java.util.Locale.ENGLISH)); - } - - @Override - public void addPermission(@NotNull Permission perm) { - addPermission(perm, true); - } - - @Deprecated - public void addPermission(@NotNull Permission perm, boolean dirty) { - String name = perm.getName().toLowerCase(java.util.Locale.ENGLISH); - - if (permissions.containsKey(name)) { - throw new IllegalArgumentException("The permission " + name + " is already defined!"); - } - - permissions.put(name, perm); - calculatePermissionDefault(perm, dirty); - } - - @Override - @NotNull - public Set getDefaultPermissions(boolean op) { - return ImmutableSet.copyOf(defaultPerms.get(op)); - } - - @Override - public void removePermission(@NotNull Permission perm) { - removePermission(perm.getName()); - } - - @Override - public void removePermission(@NotNull String name) { - permissions.remove(name.toLowerCase(java.util.Locale.ENGLISH)); - } - - @Override - public void recalculatePermissionDefaults(@NotNull Permission perm) { - if (perm != null && permissions.containsKey(perm.getName().toLowerCase(java.util.Locale.ENGLISH))) { - defaultPerms.get(true).remove(perm); - defaultPerms.get(false).remove(perm); - - calculatePermissionDefault(perm, true); - } - } - - private void calculatePermissionDefault(@NotNull Permission perm, boolean dirty) { - if ((perm.getDefault() == PermissionDefault.OP) || (perm.getDefault() == PermissionDefault.TRUE)) { - defaultPerms.get(true).add(perm); - if (dirty) { - dirtyPermissibles(true); - } - } - if ((perm.getDefault() == PermissionDefault.NOT_OP) || (perm.getDefault() == PermissionDefault.TRUE)) { - defaultPerms.get(false).add(perm); - if (dirty) { - dirtyPermissibles(false); - } - } - } - - @Deprecated - public void dirtyPermissibles() { - dirtyPermissibles(true); - dirtyPermissibles(false); - } - - private void dirtyPermissibles(boolean op) { - Set permissibles = getDefaultPermSubscriptions(op); - - for (Permissible p : permissibles) { - p.recalculatePermissions(); - } - } - - @Override - public void subscribeToPermission(@NotNull String permission, @NotNull Permissible permissible) { - String name = permission.toLowerCase(java.util.Locale.ENGLISH); - Map map = permSubs.get(name); - - if (map == null) { - map = new WeakHashMap(); - permSubs.put(name, map); - } - - map.put(permissible, true); - } - - @Override - public void unsubscribeFromPermission(@NotNull String permission, @NotNull Permissible permissible) { - String name = permission.toLowerCase(java.util.Locale.ENGLISH); - Map map = permSubs.get(name); - - if (map != null) { - map.remove(permissible); - - if (map.isEmpty()) { - permSubs.remove(name); - } - } - } - - @Override - @NotNull - public Set getPermissionSubscriptions(@NotNull String permission) { - String name = permission.toLowerCase(java.util.Locale.ENGLISH); - Map map = permSubs.get(name); - - if (map == null) { - return ImmutableSet.of(); - } else { - return ImmutableSet.copyOf(map.keySet()); - } - } - - @Override - public void subscribeToDefaultPerms(boolean op, @NotNull Permissible permissible) { - Map map = defSubs.get(op); - - if (map == null) { - map = new WeakHashMap(); - defSubs.put(op, map); - } - - map.put(permissible, true); - } - - @Override - public void unsubscribeFromDefaultPerms(boolean op, @NotNull Permissible permissible) { - Map map = defSubs.get(op); - - if (map != null) { - map.remove(permissible); - - if (map.isEmpty()) { - defSubs.remove(op); - } - } - } - - @Override - @NotNull - public Set getDefaultPermSubscriptions(boolean op) { - Map map = defSubs.get(op); - - if (map == null) { - return ImmutableSet.of(); - } else { - return ImmutableSet.copyOf(map.keySet()); - } - } - - @Override - @NotNull - public Set getPermissions() { - return new HashSet(permissions.values()); - } - - @Override - public boolean useTimings() { - return co.aikar.timings.Timings.isTimingsEnabled(); // Spigot - } - - /** - * Sets whether or not per event timing code should be used - * - * @param use True if per event timing code should be used - */ - public void useTimings(boolean use) { - co.aikar.timings.Timings.setTimingsEnabled(use); // Paper - } - - // Paper start - public void clearPermissions() { - permissions.clear(); - defaultPerms.get(true).clear(); - defaultPerms.get(false).clear(); - } - // Paper end - -} diff --git a/api/src/main/java/org/bukkit/plugin/SimpleServicesManager.java b/api/src/main/java/org/bukkit/plugin/SimpleServicesManager.java deleted file mode 100644 index f3dd84902..000000000 --- a/api/src/main/java/org/bukkit/plugin/SimpleServicesManager.java +++ /dev/null @@ -1,321 +0,0 @@ -package org.bukkit.plugin; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import org.bukkit.Bukkit; -import org.bukkit.event.server.ServiceRegisterEvent; -import org.bukkit.event.server.ServiceUnregisterEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @Override - public void register(@NotNull Class service, @NotNull T provider, @NotNull Plugin plugin, @NotNull 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 - */ - @Override - public void unregisterAll(@NotNull 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 e) {} - } - 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 - */ - @Override - public void unregister(@NotNull Class service, @NotNull 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 e) {} - } - for (ServiceUnregisterEvent event : unregisteredEvents) { - Bukkit.getServer().getPluginManager().callEvent(event); - } - } - - /** - * Unregister a particular provider. - * - * @param provider The service provider implementation - */ - @Override - public void unregister(@NotNull 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 e) {} - } - 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 - */ - @Override - @Nullable - public T load(@NotNull 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 - */ - @Override - @Nullable - @SuppressWarnings("unchecked") - public RegisteredServiceProvider getRegistration(@NotNull 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 registrations - */ - @Override - @NotNull - public List> getRegistrations(@NotNull 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 - */ - @Override - @NotNull - @SuppressWarnings("unchecked") - public List> getRegistrations(@NotNull 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 - */ - @Override - @NotNull - 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 - */ - @Override - public boolean isProvidedFor(@NotNull Class service) { - synchronized (providers) { - return providers.containsKey(service); - } - } -} diff --git a/api/src/main/java/org/bukkit/plugin/TimedRegisteredListener.java b/api/src/main/java/org/bukkit/plugin/TimedRegisteredListener.java deleted file mode 100644 index 1d76e30b8..000000000 --- a/api/src/main/java/org/bukkit/plugin/TimedRegisteredListener.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.bukkit.plugin; - -import org.bukkit.event.Event; -import org.bukkit.event.EventException; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Extends RegisteredListener to include timing information - */ -public class TimedRegisteredListener extends RegisteredListener { - private int count; - private long totalTime; - private Class eventClass; - private boolean multiple = false; - - public TimedRegisteredListener(@NotNull final Listener pluginListener, @NotNull final EventExecutor eventExecutor, @NotNull final EventPriority eventPriority, @NotNull final Plugin registeredPlugin, final boolean listenCancelled) { - super(pluginListener, eventExecutor, eventPriority, registeredPlugin, listenCancelled); - } - - @Override - public void callEvent(@NotNull Event event) throws EventException { - if (event.isAsynchronous()) { - super.callEvent(event); - return; - } - count++; - Class newEventClass = event.getClass(); - if (this.eventClass == null) { - this.eventClass = newEventClass; - } else if (!this.eventClass.equals(newEventClass)) { - multiple = true; - this.eventClass = getCommonSuperclass(newEventClass, this.eventClass).asSubclass(Event.class); - } - long start = System.nanoTime(); - super.callEvent(event); - totalTime += System.nanoTime() - start; - } - - @NotNull - private static Class getCommonSuperclass(@NotNull Class class1, @NotNull Class class2) { - while (!class1.isAssignableFrom(class2)) { - class1 = class1.getSuperclass(); - } - return class1; - } - - /** - * Resets the call count and total time for this listener - */ - public void reset() { - count = 0; - totalTime = 0; - } - - /** - * Gets the total times this listener has been called - * - * @return Times this listener has been called - */ - public int getCount() { - return count; - } - - /** - * Gets the total time calls to this listener have taken - * - * @return Total time for all calls of this listener - */ - public long getTotalTime() { - return totalTime; - } - - /** - * Gets the class of the events this listener handled. If it handled - * multiple classes of event, the closest shared superclass will be - * returned, such that for any event this listener has handled, - * this.getEventClass().isAssignableFrom(event.getClass()) - * and no class this.getEventClass().isAssignableFrom(clazz) - * {@literal && this.getEventClass() != clazz &&} - * event.getClass().isAssignableFrom(clazz) for all handled events. - * - * @return the event class handled by this RegisteredListener - */ - @Nullable - public Class getEventClass() { - return eventClass; - } - - /** - * Gets whether this listener has handled multiple events, such that for - * some two events, eventA.getClass() != eventB.getClass(). - * - * @return true if this listener has handled multiple events - */ - public boolean hasMultiple() { - return multiple; - } -} diff --git a/api/src/main/java/org/bukkit/plugin/UnknownDependencyException.java b/api/src/main/java/org/bukkit/plugin/UnknownDependencyException.java deleted file mode 100644 index a80251eff..000000000 --- a/api/src/main/java/org/bukkit/plugin/UnknownDependencyException.java +++ /dev/null @@ -1,46 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/java/JavaPlugin.java b/api/src/main/java/org/bukkit/plugin/java/JavaPlugin.java deleted file mode 100644 index 04fa3991f..000000000 --- a/api/src/main/java/org/bukkit/plugin/java/JavaPlugin.java +++ /dev/null @@ -1,429 +0,0 @@ -package org.bukkit.plugin.java; - -import com.google.common.base.Charsets; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.net.URL; -import java.net.URLConnection; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.apache.commons.lang.Validate; -import org.bukkit.Server; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.PluginBase; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginLoader; -import org.bukkit.plugin.PluginLogger; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 FileConfiguration newConfig = null; - private File configFile = null; - Logger logger = null; // Paper - PluginLogger -> Logger, package-private - - public JavaPlugin() { - final ClassLoader classLoader = this.getClass().getClassLoader(); - if (!(classLoader instanceof PluginClassLoader)) { - throw new IllegalStateException("JavaPlugin requires " + PluginClassLoader.class.getName()); - } - ((PluginClassLoader) classLoader).initialize(this); - } - - protected JavaPlugin(@NotNull final JavaPluginLoader loader, @NotNull final PluginDescriptionFile description, @NotNull final File dataFolder, @NotNull 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. - */ - @NotNull - @Override - public final File getDataFolder() { - return dataFolder; - } - - /** - * Gets the associated PluginLoader responsible for this plugin - * - * @return PluginLoader that controls this plugin - */ - @NotNull - @Override - public final PluginLoader getPluginLoader() { - return loader; - } - - /** - * Returns the Server instance currently running this plugin - * - * @return Server running this plugin - */ - @NotNull - @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 - */ - @NotNull - protected File getFile() { - return file; - } - - /** - * Returns the plugin.yaml file containing the details for this plugin - * - * @return Contents of the plugin.yaml file - */ - @NotNull - @Override - public final PluginDescriptionFile getDescription() { - return description; - } - - @NotNull - @Override - public FileConfiguration getConfig() { - if (newConfig == null) { - reloadConfig(); - } - return newConfig; - } - - /** - * Provides a reader for a text file located inside the jar. - *

- * The returned reader will read text with the UTF-8 charset. - * - * @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) - */ - @Nullable - protected final Reader getTextResource(@NotNull String file) { - final InputStream in = getResource(file); - - return in == null ? null : new InputStreamReader(in, Charsets.UTF_8); - } - - @Override - public void reloadConfig() { - newConfig = YamlConfiguration.loadConfiguration(configFile); - - final InputStream defConfigStream = getResource("config.yml"); - if (defConfigStream == null) { - return; - } - - newConfig.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream, Charsets.UTF_8))); - } - - @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(@NotNull 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); - } - } - - @Nullable - @Override - public InputStream getResource(@NotNull 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 - */ - @NotNull - 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(); - } - } - } - - - final void init(@NotNull PluginLoader loader, @NotNull Server server, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file, @NotNull 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"); - // Paper start - if (this.logger == null) { - this.logger = com.destroystokyo.paper.utils.PaperPluginLogger.getLogger(this.description); - } - // Paper end - } - - /** - * {@inheritDoc} - */ - @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - @Nullable - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull 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 - */ - @Nullable - public PluginCommand getCommand(@NotNull String name) { - String alias = name.toLowerCase(java.util.Locale.ENGLISH); - PluginCommand command = getServer().getPluginCommand(alias); - - if (command == null || command.getPlugin() != this) { - command = getServer().getPluginCommand(description.getName().toLowerCase(java.util.Locale.ENGLISH) + ":" + alias); - } - - if (command != null && command.getPlugin() == this) { - return command; - } else { - return null; - } - } - - @Override - public void onLoad() {} - - @Override - public void onDisable() {} - - @Override - public void onEnable() {} - - @Nullable - @Override - public ChunkGenerator getDefaultWorldGenerator(@NotNull String worldName, @Nullable String id) { - return null; - } - - @Override - public final boolean isNaggable() { - return naggable; - } - - @Override - public final void setNaggable(boolean canNag) { - this.naggable = canNag; - } - - @NotNull - @Override - public Logger getLogger() { - return logger; - } - - @NotNull - @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 - */ - @NotNull - public static T getPlugin(@NotNull 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 - */ - @NotNull - public static JavaPlugin getProvidingPlugin(@NotNull 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/api/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java b/api/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java deleted file mode 100644 index 31a70b294..000000000 --- a/api/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java +++ /dev/null @@ -1,400 +0,0 @@ -package org.bukkit.plugin.java; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.logging.Level; -import java.util.regex.Pattern; -import org.apache.commons.lang.Validate; -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.EventException; -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.AuthorNagException; -import org.bukkit.plugin.EventExecutor; -import org.bukkit.plugin.InvalidDescriptionException; -import org.bukkit.plugin.InvalidPluginException; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginLoader; -import org.bukkit.plugin.RegisteredListener; -import org.bukkit.plugin.TimedRegisteredListener; -import org.bukkit.plugin.UnknownDependencyException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.spigotmc.CustomTimingsHandler; // Spigot -import org.yaml.snakeyaml.error.YAMLException; - -/** - * 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 = new Pattern[] { Pattern.compile("\\.jar$"), }; - private final Map> classes = new ConcurrentHashMap>(); - private final List loaders = new CopyOnWriteArrayList(); - - /** - * This class was not meant to be constructed explicitly - * - * @param instance the server instance - */ - @Deprecated - public JavaPluginLoader(@NotNull Server instance) { - Validate.notNull(instance, "Server cannot be null"); - server = instance; - } - - @Override - @NotNull - public Plugin loadPlugin(@NotNull 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()) { - Plugin current = server.getPluginManager().getPlugin(pluginName); - - if (current == null) { - throw new UnknownDependencyException(pluginName); - } - } - - server.getUnsafe().checkSupported(description); - - 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.add(loader); - - return loader.plugin; - } - - @Override - @NotNull - public PluginDescriptionFile getPluginDescription(@NotNull 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 ex) { - throw new InvalidDescriptionException(ex); - } catch (YAMLException ex) { - throw new InvalidDescriptionException(ex); - } finally { - if (jar != null) { - try { - jar.close(); - } catch (IOException e) { - } - } - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - } - } - } - } - - @Override - @NotNull - public Pattern[] getPluginFileFilters() { - return fileFilters.clone(); - } - - @Nullable - Class getClassByName(final String name) { - Class cachedClass = classes.get(name); - - if (cachedClass != null) { - return cachedClass; - } else { - for (PluginClassLoader loader : loaders) { - try { - cachedClass = loader.findClass(name, false); - } catch (ClassNotFoundException cnfe) {} - if (cachedClass != null) { - return cachedClass; - } - } - } - return null; - } - - void setClass(@NotNull final String name, @NotNull 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(@NotNull 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) - } - } - - @Override - @NotNull - public Map, Set> createRegisteredListeners(@NotNull Listener listener, @NotNull final Plugin plugin) { - Validate.notNull(plugin, "Plugin can not be null"); - Validate.notNull(listener, "Listener can not be null"); - - boolean useTimings = server.getPluginManager().useTimings(); - Map, Set> ret = new HashMap, Set>(); - Set methods; - try { - Method[] publicMethods = listener.getClass().getMethods(); - Method[] privateMethods = listener.getClass().getDeclaredMethods(); - methods = new HashSet(publicMethods.length + privateMethods.length, 1.0f); - for (Method method : publicMethods) { - methods.add(method); - } - for (Method method : privateMethods) { - methods.add(method); - } - } 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.get(eventClass); - if (eventSet == null) { - eventSet = new HashSet(); - ret.put(eventClass, eventSet); - } - - 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; - } - } - - EventExecutor executor = new co.aikar.timings.TimedEventExecutor(EventExecutor.create(method, eventClass), plugin, method, eventClass); // Paper // Paper (Yes.) - Use factory method `EventExecutor.create()` - if (false) { // Spigot - RL handles useTimings check now - eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); - } else { - eventSet.add(new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled())); - } - } - return ret; - } - - @Override - public void enablePlugin(@NotNull final Plugin plugin) { - Validate.isTrue(plugin instanceof JavaPlugin, "Plugin is not associated with this PluginLoader"); - - if (!plugin.isEnabled()) { - // Paper start - Add an asterisk to legacy plugins (so admins are aware) - String enableMsg = "Enabling " + plugin.getDescription().getFullName(); - if (org.bukkit.UnsafeValues.isLegacyPlugin(plugin)) { - enableMsg += "*"; - } - - plugin.getLogger().info(enableMsg); - // Paper end - - JavaPlugin jPlugin = (JavaPlugin) plugin; - - PluginClassLoader pluginLoader = (PluginClassLoader) jPlugin.getClassLoader(); - - if (!loaders.contains(pluginLoader)) { - loaders.add(pluginLoader); - server.getLogger().log(Level.WARNING, "Enabled plugin with unregistered PluginClassLoader " + plugin.getDescription().getFullName()); - } - - 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); - // Paper start - Disable plugins that fail to load - server.getPluginManager().disablePlugin(jPlugin, true); // Paper - close Classloader on disable - She's dead jim - return; - // Paper 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)); - } - } - - @Override - public void disablePlugin(@NotNull Plugin plugin) { - // Paper start - close Classloader on disable - disablePlugin(plugin, false); // Retain old behavior unless requested - } - - public void disablePlugin(@NotNull Plugin plugin, boolean closeClassloader) { - // Paper end - close Class Loader on disable - 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); - } - - if (cloader instanceof PluginClassLoader) { - PluginClassLoader loader = (PluginClassLoader) cloader; - loaders.remove(loader); - - Set names = loader.getClasses(); - - for (String name : names) { - removeClass(name); - } - // Paper start - close Class Loader on disable - try { - if (closeClassloader) { - loader.close(); - } - } catch (IOException e) { - server.getLogger().log(Level.WARNING, "Error closing the Plugin Class Loader for " + plugin.getDescription().getFullName()); - e.printStackTrace(); - } - // Paper end - } - } - } -} diff --git a/api/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java b/api/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java deleted file mode 100644 index 6f39f571d..000000000 --- a/api/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java +++ /dev/null @@ -1,180 +0,0 @@ -package org.bukkit.plugin.java; - -import com.google.common.io.ByteStreams; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.security.CodeSigner; -import java.security.CodeSource; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.Manifest; -import org.apache.commons.lang.Validate; -import org.bukkit.plugin.InvalidPluginException; -import org.bukkit.plugin.PluginDescriptionFile; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 ConcurrentHashMap>(); - private final PluginDescriptionFile description; - private final File dataFolder; - private final File file; - private final JarFile jar; - private final Manifest manifest; - private final URL url; - final JavaPlugin plugin; - private JavaPlugin pluginInit; - private IllegalStateException pluginState; - private java.util.logging.Logger logger; // Paper - add field - - static { - ClassLoader.registerAsParallelCapable(); - } - - PluginClassLoader(@NotNull final JavaPluginLoader loader, @Nullable final ClassLoader parent, @NotNull final PluginDescriptionFile description, @NotNull final File dataFolder, @NotNull final File file) throws IOException, 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; - this.jar = new JarFile(file); - this.manifest = jar.getManifest(); - this.url = file.toURI().toURL(); - - this.logger = com.destroystokyo.paper.utils.PaperPluginLogger.getLogger(description); // Paper - Register logger early - - 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(@NotNull 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) { - String path = name.replace('.', '/').concat(".class"); - JarEntry entry = jar.getJarEntry(path); - - if (entry != null) { - byte[] classBytes; - - try (InputStream is = jar.getInputStream(entry)) { - classBytes = ByteStreams.toByteArray(is); - } catch (IOException ex) { - throw new ClassNotFoundException(name, ex); - } - - classBytes = loader.server.getUnsafe().processClass(description, path, classBytes); - - int dot = name.lastIndexOf('.'); - if (dot != -1) { - String pkgName = name.substring(0, dot); - if (getPackage(pkgName) == null) { - try { - if (manifest != null) { - definePackage(pkgName, manifest, url); - } else { - definePackage(pkgName, null, null, null, null, null, null, null); - } - } catch (IllegalArgumentException ex) { - if (getPackage(pkgName) == null) { - throw new IllegalStateException("Cannot find package " + pkgName); - } - } - } - } - - CodeSigner[] signers = entry.getCodeSigners(); - CodeSource source = new CodeSource(url, signers); - - result = defineClass(name, classBytes, 0, classBytes.length, source); - } - - if (result == null) { - result = super.findClass(name); - } - - if (result != null) { - loader.setClass(name, result); - } - } - - classes.put(name, result); - } - - return result; - } - - @Override - public void close() throws IOException { - try { - super.close(); - } finally { - jar.close(); - } - } - - @NotNull - Set getClasses() { - return classes.keySet(); - } - - synchronized void initialize(@NotNull 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.logger = this.logger; // Paper - set logger - javaPlugin.init(loader, loader.server, description, dataFolder, file, this); - } -} diff --git a/api/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java b/api/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java deleted file mode 100644 index 80ef8a2a3..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java +++ /dev/null @@ -1,15 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java b/api/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java deleted file mode 100644 index 2266f1764..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java +++ /dev/null @@ -1,15 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java b/api/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java deleted file mode 100644 index 61af8c4c1..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java +++ /dev/null @@ -1,23 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/messaging/Messenger.java b/api/src/main/java/org/bukkit/plugin/messaging/Messenger.java deleted file mode 100644 index 682c77188..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/Messenger.java +++ /dev/null @@ -1,233 +0,0 @@ -package org.bukkit.plugin.messaging; - -import java.util.Set; -import org.bukkit.NamespacedKey; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * A class responsible for managing the registrations of plugin channels and - * their listeners. - * - * Channel names must contain a colon separator and consist of only [a-z0-9/._-] - * - i.e. they MUST be valid {@link NamespacedKey}. The "BungeeCord" channel is - * an exception and may only take this form. - */ -public interface Messenger { - - /** - * Represents the largest size that an individual Plugin Message may be. - */ - public static final int MAX_MESSAGE_SIZE = 32766; - - /** - * Represents the largest size that a Plugin Channel may be. - */ - public static final int MAX_CHANNEL_SIZE = Integer.getInteger("paper.maxCustomChannelName", 64); // Paper - - /** - * Checks if the specified channel is a reserved name. - *
- * All channels within the "minecraft" namespace except for - * "minecraft:brand" are reserved. - * - * @param channel Channel name to check. - * @return True if the channel is reserved, otherwise false. - * @throws IllegalArgumentException Thrown if channel is null. - */ - public boolean isReservedChannel(@NotNull 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. - */ - public void registerOutgoingPluginChannel(@NotNull Plugin plugin, @NotNull 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. - */ - public void unregisterOutgoingPluginChannel(@NotNull Plugin plugin, @NotNull 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. - */ - public void unregisterOutgoingPluginChannel(@NotNull 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. - */ - @NotNull - public PluginMessageListenerRegistration registerIncomingPluginChannel(@NotNull Plugin plugin, @NotNull String channel, @NotNull 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. - */ - public void unregisterIncomingPluginChannel(@NotNull Plugin plugin, @NotNull String channel, @NotNull 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. - */ - public void unregisterIncomingPluginChannel(@NotNull Plugin plugin, @NotNull 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. - */ - public void unregisterIncomingPluginChannel(@NotNull Plugin plugin); - - /** - * Gets a set containing all the outgoing plugin channels. - * - * @return List of all registered outgoing plugin channels. - */ - @NotNull - public 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. - */ - @NotNull - public Set getOutgoingChannels(@NotNull Plugin plugin); - - /** - * Gets a set containing all the incoming plugin channels. - * - * @return List of all registered incoming plugin channels. - */ - @NotNull - public 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. - */ - @NotNull - public Set getIncomingChannels(@NotNull 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. - */ - @NotNull - public Set getIncomingChannelRegistrations(@NotNull 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. - */ - @NotNull - public Set getIncomingChannelRegistrations(@NotNull 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. - */ - @NotNull - public Set getIncomingChannelRegistrations(@NotNull Plugin plugin, @NotNull 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. - */ - public boolean isRegistrationValid(@NotNull 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. - */ - public boolean isIncomingChannelRegistered(@NotNull Plugin plugin, @NotNull 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. - */ - public boolean isOutgoingChannelRegistered(@NotNull Plugin plugin, @NotNull 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. - */ - public void dispatchIncomingMessage(@NotNull Player source, @NotNull String channel, @NotNull byte[] message); -} diff --git a/api/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java b/api/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java deleted file mode 100644 index 3d7ec2e2e..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java +++ /dev/null @@ -1,17 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java b/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java deleted file mode 100644 index eb962efd5..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.plugin.messaging; - -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, @NotNull byte[] message); -} diff --git a/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java b/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java deleted file mode 100644 index 1d0029672..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bukkit.plugin.messaging; - -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Messenger messenger, @NotNull Plugin plugin, @NotNull String channel, @NotNull 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. - */ - @NotNull - public String getChannel() { - return channel; - } - - /** - * Gets the registered listener described by this registration. - * - * @return Registered listener. - */ - @NotNull - public PluginMessageListener getListener() { - return listener; - } - - /** - * Gets the plugin that this registration is for. - * - * @return Registered plugin. - */ - @NotNull - 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.equals(other.messenger)) { - return false; - } - if (this.plugin != other.plugin && !this.plugin.equals(other.plugin)) { - return false; - } - if (!this.channel.equals(other.channel)) { - return false; - } - if (this.listener != other.listener && !this.listener.equals(other.listener)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 53 * hash + this.messenger.hashCode(); - hash = 53 * hash + this.plugin.hashCode(); - hash = 53 * hash + this.channel.hashCode(); - hash = 53 * hash + this.listener.hashCode(); - return hash; - } -} diff --git a/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java b/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java deleted file mode 100644 index b84b37fe2..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.plugin.messaging; - -import java.util.Set; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - */ - public void sendPluginMessage(@NotNull Plugin source, @NotNull String channel, @NotNull 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. - */ - @NotNull - public Set getListeningPluginChannels(); -} diff --git a/api/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java b/api/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java deleted file mode 100644 index 0221f049a..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java +++ /dev/null @@ -1,16 +0,0 @@ -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/api/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java b/api/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java deleted file mode 100644 index 6fda7f3aa..000000000 --- a/api/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java +++ /dev/null @@ -1,551 +0,0 @@ -package org.bukkit.plugin.messaging; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSet.Builder; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Plugin plugin, @NotNull 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(@NotNull Plugin plugin, @NotNull 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(@NotNull Plugin plugin) { - synchronized (outgoingLock) { - Set channels = outgoingByPlugin.get(plugin); - - if (channels != null) { - String[] toRemove = channels.toArray(new String[channels.size()]); - - outgoingByPlugin.remove(plugin); - - for (String channel : toRemove) { - removeFromOutgoing(plugin, channel); - } - } - } - } - - private void addToIncoming(@NotNull 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(@NotNull 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(@NotNull Plugin plugin, @NotNull String channel) { - synchronized (incomingLock) { - Set registrations = incomingByPlugin.get(plugin); - - if (registrations != null) { - PluginMessageListenerRegistration[] toRemove = registrations.toArray(new PluginMessageListenerRegistration[registrations.size()]); - - for (PluginMessageListenerRegistration registration : toRemove) { - if (registration.getChannel().equals(channel)) { - removeFromIncoming(registration); - } - } - } - } - } - - private void removeFromIncoming(@NotNull Plugin plugin) { - synchronized (incomingLock) { - Set registrations = incomingByPlugin.get(plugin); - - if (registrations != null) { - PluginMessageListenerRegistration[] toRemove = registrations.toArray(new PluginMessageListenerRegistration[registrations.size()]); - - incomingByPlugin.remove(plugin); - - for (PluginMessageListenerRegistration registration : toRemove) { - removeFromIncoming(registration); - } - } - } - } - - @Override - public boolean isReservedChannel(@NotNull String channel) { - channel = validateAndCorrectChannel(channel); - - return channel.equals("minecraft:register") || channel.equals("minecraft:unregister"); // Paper - } - - @Override - public void registerOutgoingPluginChannel(@NotNull Plugin plugin, @NotNull String channel) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - channel = validateAndCorrectChannel(channel); - if (isReservedChannel(channel)) { - throw new ReservedChannelException(channel); - } - - addToOutgoing(plugin, channel); - } - - @Override - public void unregisterOutgoingPluginChannel(@NotNull Plugin plugin, @NotNull String channel) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - channel = validateAndCorrectChannel(channel); - - removeFromOutgoing(plugin, channel); - } - - @Override - public void unregisterOutgoingPluginChannel(@NotNull Plugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - - removeFromOutgoing(plugin); - } - - @Override - @NotNull - public PluginMessageListenerRegistration registerIncomingPluginChannel(@NotNull Plugin plugin, @NotNull String channel, @NotNull PluginMessageListener listener) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - channel = validateAndCorrectChannel(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; - } - - @Override - public void unregisterIncomingPluginChannel(@NotNull Plugin plugin, @NotNull String channel, @NotNull PluginMessageListener listener) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - if (listener == null) { - throw new IllegalArgumentException("Listener cannot be null"); - } - channel = validateAndCorrectChannel(channel); - - removeFromIncoming(new PluginMessageListenerRegistration(this, plugin, channel, listener)); - } - - @Override - public void unregisterIncomingPluginChannel(@NotNull Plugin plugin, @NotNull String channel) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - channel = validateAndCorrectChannel(channel); - - removeFromIncoming(plugin, channel); - } - - @Override - public void unregisterIncomingPluginChannel(@NotNull Plugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - - removeFromIncoming(plugin); - } - - @Override - @NotNull - public Set getOutgoingChannels() { - synchronized (outgoingLock) { - Set keys = outgoingByChannel.keySet(); - return ImmutableSet.copyOf(keys); - } - } - - @Override - @NotNull - public Set getOutgoingChannels(@NotNull 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(); - } - } - } - - @Override - @NotNull - public Set getIncomingChannels() { - synchronized (incomingLock) { - Set keys = incomingByChannel.keySet(); - return ImmutableSet.copyOf(keys); - } - } - - @Override - @NotNull - public Set getIncomingChannels(@NotNull 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(); - } - } - } - - @Override - @NotNull - public Set getIncomingChannelRegistrations(@NotNull 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(); - } - } - } - - @Override - @NotNull - public Set getIncomingChannelRegistrations(@NotNull String channel) { - channel = validateAndCorrectChannel(channel); - - synchronized (incomingLock) { - Set registrations = incomingByChannel.get(channel); - - if (registrations != null) { - return ImmutableSet.copyOf(registrations); - } else { - return ImmutableSet.of(); - } - } - } - - @Override - @NotNull - public Set getIncomingChannelRegistrations(@NotNull Plugin plugin, @NotNull String channel) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - channel = validateAndCorrectChannel(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(); - } - } - } - - @Override - public boolean isRegistrationValid(@NotNull 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; - } - } - - @Override - public boolean isIncomingChannelRegistered(@NotNull Plugin plugin, @NotNull String channel) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - channel = validateAndCorrectChannel(channel); - - synchronized (incomingLock) { - Set registrations = incomingByPlugin.get(plugin); - - if (registrations != null) { - for (PluginMessageListenerRegistration registration : registrations) { - if (registration.getChannel().equals(channel)) { - return true; - } - } - } - - return false; - } - } - - @Override - public boolean isOutgoingChannelRegistered(@NotNull Plugin plugin, @NotNull String channel) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - channel = validateAndCorrectChannel(channel); - - synchronized (outgoingLock) { - Set channels = outgoingByPlugin.get(plugin); - - if (channels != null) { - return channels.contains(channel); - } - - return false; - } - } - - @Override - public void dispatchIncomingMessage(@NotNull Player source, @NotNull String channel, @NotNull byte[] message) { - if (source == null) { - throw new IllegalArgumentException("Player source cannot be null"); - } - if (message == null) { - throw new IllegalArgumentException("Message cannot be null"); - } - channel = validateAndCorrectChannel(channel); - - Set registrations = getIncomingChannelRegistrations(channel); - - for (PluginMessageListenerRegistration registration : registrations) { - try { - registration.getListener().onPluginMessageReceived(channel, source, message); - } catch (Throwable t) { - registration.getPlugin().getLogger().log(Level.WARNING, - String.format("Plugin %s generated an exception whilst handling plugin message", - registration.getPlugin().getDescription().getFullName() - ), t); - } - } - } - - /** - * Validates a Plugin Channel name. - * - * @param channel Channel name to validate. - * @deprecated not an API method - */ - @Deprecated - public static void validateChannel(@NotNull String channel) { - validateAndCorrectChannel(channel); - } - - /** - * Validates and corrects a Plugin Channel name. Method is not reentrant / idempotent. - * - * @param channel Channel name to validate. - * @return corrected channel name - * @deprecated not an API method - */ - @Deprecated - @NotNull - public static String validateAndCorrectChannel(@NotNull String channel) { - if (channel == null) { - throw new IllegalArgumentException("Channel cannot be null"); - } - // This will correct registrations / outgoing messages - // It is not legal to send "BungeeCord" incoming anymore so we are fine there, - // but we must make sure that none of the API methods repeatedly call validate - if (channel.equals("BungeeCord")) { - return "bungeecord:main"; - } - // And this will correct incoming messages. - if (channel.equals("bungeecord:main")) { - return "BungeeCord"; - } - if (channel.length() > Messenger.MAX_CHANNEL_SIZE) { - throw new ChannelNameTooLongException(channel); - } - if (channel.indexOf(':') == -1) { - throw new IllegalArgumentException("Channel must contain : separator (attempted to use " + channel + ")"); - } - if (!channel.toLowerCase(Locale.ROOT).equals(channel)) { - // TODO: use NamespacedKey validation here - throw new IllegalArgumentException("Channel must be entirely lowercase (attempted to use " + channel + ")"); - } - return 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(@NotNull Messenger messenger, @NotNull Plugin source, @NotNull String channel, @NotNull 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/api/src/main/java/org/bukkit/potion/Potion.java b/api/src/main/java/org/bukkit/potion/Potion.java deleted file mode 100644 index 3c400a046..000000000 --- a/api/src/main/java/org/bukkit/potion/Potion.java +++ /dev/null @@ -1,393 +0,0 @@ -package org.bukkit.potion; - -import java.util.Collection; -import org.apache.commons.lang.Validate; -import org.bukkit.Material; -import org.bukkit.entity.LivingEntity; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.PotionMeta; -import org.jetbrains.annotations.NotNull; - -/** - * Potion Adapter for pre-1.9 data values - * see @PotionMeta for 1.9+ - */ -@Deprecated -public class Potion { - private boolean extended = false; - private boolean splash = false; - private int level = 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 - */ - public Potion(@NotNull PotionType type) { - Validate.notNull(type, "Null PotionType"); - this.type = type; - } - - /** - * Create a new potion of the given type and level. - * - * @param type The type of potion. - * @param level The potion's level. - */ - public Potion(@NotNull PotionType type, int level) { - this(type); - Validate.notNull(type, "Type cannot be null"); - 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(@NotNull 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(@NotNull PotionType type, int level, boolean splash, boolean extended) { - this(type, level, splash); - this.extended = extended; - } - - /** - * Chain this to the constructor to make the potion a splash potion. - * - * @return The potion. - */ - @NotNull - public Potion splash() { - setSplash(true); - return this; - } - - /** - * Chain this to the constructor to extend the potion's duration. - * - * @return The potion. - */ - @NotNull - 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(@NotNull ItemStack to) { - Validate.notNull(to, "itemstack cannot be null"); - Validate.isTrue(to.hasItemMeta(), "given itemstack is not a potion"); - Validate.isTrue(to.getItemMeta() instanceof PotionMeta, "given itemstack is not a potion"); - PotionMeta meta = (PotionMeta) to.getItemMeta(); - meta.setBasePotionData(new PotionData(type, extended, level == 2)); - to.setItemMeta(meta); - } - - /** - * 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(@NotNull 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 - */ - @NotNull - public Collection getEffects() { - return getBrewer().getEffects(type, level == 2, extended); - } - - /** - * Returns the level of this potion. - * - * @return The level of this potion - */ - public int getLevel() { - return level; - } - - /** - * Returns the {@link PotionType} of this potion. - * - * @return The type of this potion - */ - @NotNull - 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 PotionType} of this potion. - * - * @param type The new type of this potion - */ - public void setType(@NotNull 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."); - Validate.isTrue(level > 0 && level <= 2, "Level must be between 1 and 2 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 Non-functional - */ - @Deprecated - public short toDamageValue() { - return 0; - } - - /** - * 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 - */ - @NotNull - public ItemStack toItemStack(int amount) { - Material material; - if (isSplash()) { - material = Material.SPLASH_POTION; - } else { - material = Material.POTION; - } - ItemStack itemStack = new ItemStack(material, amount); - PotionMeta meta = (PotionMeta) itemStack.getItemMeta(); - meta.setBasePotionData(new PotionData(type, level == 2, extended)); - itemStack.setItemMeta(meta); - return itemStack; - } - - 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; - - /** - * - * @param damage the damage value - * @return the produced potion - */ - @NotNull - public static Potion fromDamage(int damage) { - PotionType type; - switch (damage & POTION_BIT) { - case 0: - type = PotionType.WATER; - break; - case 1: - type = PotionType.REGEN; - break; - case 2: - type = PotionType.SPEED; - break; - case 3: - type = PotionType.FIRE_RESISTANCE; - break; - case 4: - type = PotionType.POISON; - break; - case 5: - type = PotionType.INSTANT_HEAL; - break; - case 6: - type = PotionType.NIGHT_VISION; - break; - case 8: - type = PotionType.WEAKNESS; - break; - case 9: - type = PotionType.STRENGTH; - break; - case 10: - type = PotionType.SLOWNESS; - break; - case 11: - type = PotionType.JUMP; - break; - case 12: - type = PotionType.INSTANT_DAMAGE; - break; - case 13: - type = PotionType.WATER_BREATHING; - break; - case 14: - type = PotionType.INVISIBILITY; - break; - default: - type = PotionType.WATER; - } - Potion potion; - if (type == null || type == PotionType.WATER) { - potion = new Potion(PotionType.WATER); - } else { - int level = (damage & TIER_BIT) >> TIER_SHIFT; - level++; - potion = new Potion(type, level); - } - if ((damage & SPLASH_BIT) != 0) { - potion = potion.splash(); - } - if ((damage & EXTENDED_BIT) != 0) { - potion = potion.extend(); - } - return potion; - } - - @NotNull - public static Potion fromItemStack(@NotNull 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 - */ - @NotNull - 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(@NotNull PotionBrewer other) { - if (brewer != null) - throw new IllegalArgumentException("brewer can only be set internally"); - brewer = other; - } - - /** - * - * @return the name id - * @deprecated Non-functional - */ - @Deprecated - public int getNameId() { - return 0; - } -} diff --git a/api/src/main/java/org/bukkit/potion/PotionBrewer.java b/api/src/main/java/org/bukkit/potion/PotionBrewer.java deleted file mode 100644 index d21f407cc..000000000 --- a/api/src/main/java/org/bukkit/potion/PotionBrewer.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bukkit.potion; - -import java.util.Collection; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public PotionEffect createEffect(@NotNull 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 Non-Functional - */ - @Deprecated - @NotNull - public Collection getEffectsFromDamage(int damage); - - /** - * Returns a collection of {@link PotionEffect} that would be applied from - * a potion with the given type. - * - * @param type The type of the potion - * @param upgraded Whether the potion is upgraded - * @param extended Whether the potion is extended - * @return The list of effects - */ - @NotNull - public Collection getEffects(@NotNull PotionType type, boolean upgraded, boolean extended); -} diff --git a/api/src/main/java/org/bukkit/potion/PotionData.java b/api/src/main/java/org/bukkit/potion/PotionData.java deleted file mode 100644 index ba0d67116..000000000 --- a/api/src/main/java/org/bukkit/potion/PotionData.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.potion; - -import org.apache.commons.lang.Validate; -import org.jetbrains.annotations.NotNull; - -public final class PotionData { - - private final PotionType type; - private final boolean extended; - private final boolean upgraded; - - /** - * Instantiates a final PotionData object to contain information about a - * Potion - * - * @param type the type of the Potion - * @param extended whether the potion is extended PotionType#isExtendable() - * must be true - * @param upgraded whether the potion is upgraded PotionType#isUpgradable() - * must be true - */ - public PotionData(@NotNull PotionType type, boolean extended, boolean upgraded) { - Validate.notNull(type, "Potion Type must not be null"); - Validate.isTrue(!upgraded || type.isUpgradeable(), "Potion Type is not upgradable"); - Validate.isTrue(!extended || type.isExtendable(), "Potion Type is not extendable"); - Validate.isTrue(!upgraded || !extended, "Potion cannot be both extended and upgraded"); - this.type = type; - this.extended = extended; - this.upgraded = upgraded; - } - - public PotionData(@NotNull PotionType type) { - this(type, false, false); - } - - /** - * Gets the type of the potion, Type matches up with each kind of craftable - * potion - * - * @return the potion type - */ - @NotNull - public PotionType getType() { - return type; - } - - /** - * Checks if the potion is in an upgraded state. This refers to whether or - * not the potion is Tier 2, such as Potion of Fire Resistance II. - * - * @return true if the potion is upgraded; - */ - public boolean isUpgraded() { - return upgraded; - } - - /** - * Checks if the potion is in an extended state. This refers to the extended - * duration potions - * - * @return true if the potion is extended - */ - public boolean isExtended() { - return extended; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 23 * hash + (this.type != null ? this.type.hashCode() : 0); - hash = 23 * hash + (this.extended ? 1 : 0); - hash = 23 * hash + (this.upgraded ? 1 : 0); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - PotionData other = (PotionData) obj; - return (this.upgraded == other.upgraded) && (this.extended == other.extended) && (this.type == other.type); - } -} diff --git a/api/src/main/java/org/bukkit/potion/PotionEffect.java b/api/src/main/java/org/bukkit/potion/PotionEffect.java deleted file mode 100644 index 0193e0754..000000000 --- a/api/src/main/java/org/bukkit/potion/PotionEffect.java +++ /dev/null @@ -1,275 +0,0 @@ -package org.bukkit.potion; - -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import java.util.NoSuchElementException; -import org.apache.commons.lang.Validate; -import org.bukkit.Color; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.SerializableAs; -import org.bukkit.entity.LivingEntity; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 static final String ICON = "has-icon"; - private final int amplifier; - private final int duration; - private final PotionEffectType type; - private final boolean ambient; - private final boolean particles; - private final boolean icon; - - /** - * 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()} - * @param icon the icon status, see {@link PotionEffect#hasIcon()} - */ - public PotionEffect(@NotNull PotionEffectType type, int duration, int amplifier, boolean ambient, boolean particles, boolean icon) { - Validate.notNull(type, "effect type cannot be null"); - this.type = type; - this.duration = duration; - this.amplifier = amplifier; - this.ambient = ambient; - this.particles = particles; - this.icon = icon; - } - - /** - * Creates a potion effect with no defined color. - * - * @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(@NotNull PotionEffectType type, int duration, int amplifier, boolean ambient, boolean particles) { - this(type, duration, amplifier, ambient, 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(@NotNull 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(@NotNull PotionEffectType type, int duration, int amplifier) { - this(type, duration, amplifier, true); - } - - /** - * Constructor for deserialization. - * - * @param map the map to deserialize from - */ - public PotionEffect(@NotNull Map map) { - this(getEffectType(map), getInt(map, DURATION), getInt(map, AMPLIFIER), getBool(map, AMBIENT, false), getBool(map, PARTICLES, true), getBool(map, ICON, getBool(map, PARTICLES, true))); - } - - // Paper start - @NotNull - public PotionEffect withType(@NotNull PotionEffectType type) { - return new PotionEffect(type, duration, amplifier, ambient, particles, icon); - } - @NotNull - public PotionEffect withDuration(int duration) { - return new PotionEffect(this.type, duration, amplifier, ambient, particles, icon); - } - @NotNull - public PotionEffect withAmplifier(int amplifier) { - return new PotionEffect(this.type, duration, amplifier, ambient, particles, icon); - } - @NotNull - public PotionEffect withAmbient(boolean ambient) { - return new PotionEffect(this.type, duration, amplifier, ambient, particles, icon); - } - @NotNull - public PotionEffect withParticles(boolean particles) { - return new PotionEffect(this.type, duration, amplifier, ambient, particles, icon); - } - @NotNull - public PotionEffect withIcon(boolean icon) { - return new PotionEffect(this.type, duration, amplifier, ambient, particles, icon); - } - // Paper end - - @NotNull - private static PotionEffectType getEffectType(@NotNull 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(@NotNull Map map, @NotNull 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(@NotNull Map map, @NotNull Object key, boolean def) { - Object bool = map.get(key); - if (bool instanceof Boolean) { - return (Boolean) bool; - } - return def; - } - - @Override - @NotNull - public Map serialize() { - return ImmutableMap.builder() - .put(TYPE, type.getId()) - .put(DURATION, duration) - .put(AMPLIFIER, amplifier) - .put(AMBIENT, ambient) - .put(PARTICLES, particles) - .put(ICON, icon) - .build(); - } - - /** - * 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(@NotNull 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 && this.icon == that.icon; - } - - /** - * 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 - */ - @NotNull - 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; - } - - /** - * @return color of this potion's particles. May be null if the potion has no particles or defined color. - * @deprecated color is not part of potion effects - */ - @Deprecated - @Nullable - @Contract("-> null") - public Color getColor() { - return null; - } - - /** - * @return whether this effect has an icon or not - */ - public boolean hasIcon() { - return icon; - } - - @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); - hash ^= 0x22222222 >> (icon ? 1 : -1); - return hash; - } - - @Override - public String toString() { - return type.getName() + (ambient ? ":(" : ":") + duration + "t-x" + amplifier + (ambient ? ")" : ""); - } -} diff --git a/api/src/main/java/org/bukkit/potion/PotionEffectType.java b/api/src/main/java/org/bukkit/potion/PotionEffectType.java deleted file mode 100644 index b5790aaac..000000000 --- a/api/src/main/java/org/bukkit/potion/PotionEffectType.java +++ /dev/null @@ -1,333 +0,0 @@ -package org.bukkit.potion; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang.Validate; -import org.bukkit.Color; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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); - - /** - * Outlines the entity so that it can be seen from afar. - */ - public static final PotionEffectType GLOWING = new PotionEffectTypeWrapper(24); - - /** - * Causes the entity to float into the air. - */ - public static final PotionEffectType LEVITATION = new PotionEffectTypeWrapper(25); - - /** - * Loot table luck. - */ - public static final PotionEffectType LUCK = new PotionEffectTypeWrapper(26); - - /** - * Loot table unluck. - */ - public static final PotionEffectType UNLUCK = new PotionEffectTypeWrapper(27); - - /** - * Slows entity fall rate. - */ - public static final PotionEffectType SLOW_FALLING = new PotionEffectTypeWrapper(28); - - /** - * Effects granted by a nearby conduit. Includes enhanced underwater abilities. - */ - public static final PotionEffectType CONDUIT_POWER = new PotionEffectTypeWrapper(29); - - /** - * Squee'ek uh'k kk'kkkk squeek eee'eek. - */ - public static final PotionEffectType DOLPHINS_GRACE = new PotionEffectTypeWrapper(30); - - /** - * oof. - */ - public static final PotionEffectType BAD_OMEN = new PotionEffectTypeWrapper(31); - - /** - * \o/. - */ - public static final PotionEffectType HERO_OF_THE_VILLAGE = new PotionEffectTypeWrapper(32); - - 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 - */ - @NotNull - public PotionEffect createEffect(int duration, int amplifier) { - return new PotionEffect(this, isInstant() ? 1 : (int) (duration * getDurationModifier()), amplifier); - } - - /** - * Returns the duration modifier applied to effects of this type. - * - * @return duration modifier - * @deprecated unused, always 1.0 - */ - @Deprecated - 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 - */ - @NotNull - 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(); - - /** - * Returns the color of this effect type. - * - * @return the color - */ - @NotNull - public abstract Color getColor(); - - @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[33]; - 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 - @Nullable - 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. - */ - @Nullable - public static PotionEffectType getByName(@NotNull String name) { - Validate.notNull(name, "name cannot be null"); - return byName.get(name.toLowerCase(java.util.Locale.ENGLISH)); - } - - /** - * 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(@NotNull PotionEffectType type) { - if (byId[type.id] != null || byName.containsKey(type.getName().toLowerCase(java.util.Locale.ENGLISH))) { - 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(java.util.Locale.ENGLISH), type); - } - - /** - * Stops accepting any effect type registrations. - */ - public static void stopAcceptingRegistrations() { - acceptingNew = false; - } - - /** - * Returns an array of all the registered {@link PotionEffectType}s. - * This array is not necessarily in any particular order. - * - * @return Array of types. - */ - @NotNull - public static PotionEffectType[] values() { - return Arrays.copyOfRange(byId, 1, byId.length); - } -} diff --git a/api/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java b/api/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java deleted file mode 100644 index 47d46edc4..000000000 --- a/api/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.potion; - -import org.bukkit.Color; -import org.jetbrains.annotations.NotNull; - -public class PotionEffectTypeWrapper extends PotionEffectType { - protected PotionEffectTypeWrapper(int id) { - super(id); - } - - @Override - public double getDurationModifier() { - return getType().getDurationModifier(); - } - - @NotNull - @Override - public String getName() { - return getType().getName(); - } - - /** - * Get the potion type bound to this wrapper. - * - * @return The potion effect type - */ - @NotNull - public PotionEffectType getType() { - return PotionEffectType.getById(getId()); - } - - @Override - public boolean isInstant() { - return getType().isInstant(); - } - - @NotNull - @Override - public Color getColor() { - return getType().getColor(); - } -} diff --git a/api/src/main/java/org/bukkit/potion/PotionType.java b/api/src/main/java/org/bukkit/potion/PotionType.java deleted file mode 100644 index af7dea669..000000000 --- a/api/src/main/java/org/bukkit/potion/PotionType.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.bukkit.potion; - -import org.jetbrains.annotations.Nullable; - -/** - * This enum reflects and matches each potion state that can be obtained from - * the Creative mode inventory - */ -public enum PotionType { - UNCRAFTABLE(null, false, false), - WATER(null, false, false), - MUNDANE(null, false, false), - THICK(null, false, false), - AWKWARD(null, false, false), - NIGHT_VISION(PotionEffectType.NIGHT_VISION, false, true), - INVISIBILITY(PotionEffectType.INVISIBILITY, false, true), - JUMP(PotionEffectType.JUMP, true, true), - FIRE_RESISTANCE(PotionEffectType.FIRE_RESISTANCE, false, true), - SPEED(PotionEffectType.SPEED, true, true), - SLOWNESS(PotionEffectType.SLOW, true, true), - WATER_BREATHING(PotionEffectType.WATER_BREATHING, false, true), - INSTANT_HEAL(PotionEffectType.HEAL, true, false), - INSTANT_DAMAGE(PotionEffectType.HARM, true, false), - POISON(PotionEffectType.POISON, true, true), - REGEN(PotionEffectType.REGENERATION, true, true), - STRENGTH(PotionEffectType.INCREASE_DAMAGE, true, true), - WEAKNESS(PotionEffectType.WEAKNESS, false, true), - LUCK(PotionEffectType.LUCK, false, false), - TURTLE_MASTER(PotionEffectType.SLOW, true, true), // TODO: multiple effects - SLOW_FALLING(PotionEffectType.SLOW_FALLING, false, true), - ; - - private final PotionEffectType effect; - private final boolean upgradeable; - private final boolean extendable; - - PotionType(/*@Nullable*/ PotionEffectType effect, boolean upgradeable, boolean extendable) { - this.effect = effect; - this.upgradeable = upgradeable; - this.extendable = extendable; - } - - @Nullable - public PotionEffectType getEffectType() { - return effect; - } - - public boolean isInstant() { - return effect != null && effect.isInstant(); - } - - /** - * Checks if the potion type has an upgraded state. - * This refers to whether or not the potion type can be Tier 2, - * such as Potion of Fire Resistance II. - * - * @return true if the potion type can be upgraded; - */ - public boolean isUpgradeable() { - return upgradeable; - } - - /** - * Checks if the potion type has an extended state. - * This refers to the extended duration potions - * - * @return true if the potion type can be extended - */ - public boolean isExtendable() { - return extendable; - } - - public int getMaxLevel() { - return upgradeable ? 2 : 1; - } - - /** - * @param effectType the effect to get by - * @return the matching potion type - * @deprecated Misleading - */ - @Deprecated - @Nullable - public static PotionType getByEffect(@Nullable PotionEffectType effectType) { - if (effectType == null) - return WATER; - for (PotionType type : PotionType.values()) { - if (effectType.equals(type.effect)) - return type; - } - return null; - } -} diff --git a/api/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java b/api/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java deleted file mode 100644 index 21a3d767b..000000000 --- a/api/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit.projectiles; - -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; - -public interface BlockProjectileSource extends ProjectileSource { - - /** - * Gets the block this projectile source belongs to. - * - * @return Block for the projectile source - */ - @NotNull - public Block getBlock(); -} diff --git a/api/src/main/java/org/bukkit/projectiles/ProjectileSource.java b/api/src/main/java/org/bukkit/projectiles/ProjectileSource.java deleted file mode 100644 index eabd8b926..000000000 --- a/api/src/main/java/org/bukkit/projectiles/ProjectileSource.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.projectiles; - -import org.bukkit.entity.Projectile; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @NotNull - public T launchProjectile(@NotNull 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 - */ - @NotNull - public T launchProjectile(@NotNull Class projectile, @Nullable Vector velocity); -} diff --git a/api/src/main/java/org/bukkit/scheduler/BukkitRunnable.java b/api/src/main/java/org/bukkit/scheduler/BukkitRunnable.java deleted file mode 100644 index 35a1e92fc..000000000 --- a/api/src/main/java/org/bukkit/scheduler/BukkitRunnable.java +++ /dev/null @@ -1,171 +0,0 @@ -package org.bukkit.scheduler; - -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * This class is provided as an easy way to handle scheduling tasks. - */ -public abstract class BukkitRunnable implements Runnable { - private BukkitTask task; - - /** - * Returns true if this task has been cancelled. - * - * @return true if the task has been cancelled - * @throws IllegalStateException if task was not scheduled yet - */ - public synchronized boolean isCancelled() throws IllegalStateException { - checkScheduled(); - return task.isCancelled(); - } - - /** - * 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) - */ - @NotNull - public synchronized BukkitTask runTask(@NotNull Plugin plugin) throws IllegalArgumentException, IllegalStateException { - checkNotYetScheduled(); - return setupTask(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) - */ - @NotNull - public synchronized BukkitTask runTaskAsynchronously(@NotNull Plugin plugin) throws IllegalArgumentException, IllegalStateException { - checkNotYetScheduled(); - return setupTask(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) - */ - @NotNull - public synchronized BukkitTask runTaskLater(@NotNull Plugin plugin, long delay) throws IllegalArgumentException, IllegalStateException { - checkNotYetScheduled(); - return setupTask(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) - */ - @NotNull - public synchronized BukkitTask runTaskLaterAsynchronously(@NotNull Plugin plugin, long delay) throws IllegalArgumentException, IllegalStateException { - checkNotYetScheduled(); - return setupTask(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) - */ - @NotNull - public synchronized BukkitTask runTaskTimer(@NotNull Plugin plugin, long delay, long period) throws IllegalArgumentException, IllegalStateException { - checkNotYetScheduled(); - return setupTask(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) - */ - @NotNull - public synchronized BukkitTask runTaskTimerAsynchronously(@NotNull Plugin plugin, long delay, long period) throws IllegalArgumentException, IllegalStateException { - checkNotYetScheduled(); - return setupTask(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 { - checkScheduled(); - return task.getTaskId(); - } - - private void checkScheduled() { - if (task == null) { - throw new IllegalStateException("Not scheduled yet"); - } - } - - private void checkNotYetScheduled() { - if (task != null) { - throw new IllegalStateException("Already scheduled as " + task.getTaskId()); - } - } - - @NotNull - private BukkitTask setupTask(@NotNull final BukkitTask task) { - this.task = task; - return task; - } -} diff --git a/api/src/main/java/org/bukkit/scheduler/BukkitScheduler.java b/api/src/main/java/org/bukkit/scheduler/BukkitScheduler.java deleted file mode 100644 index ac140fc2c..000000000 --- a/api/src/main/java/org/bukkit/scheduler/BukkitScheduler.java +++ /dev/null @@ -1,461 +0,0 @@ -package org.bukkit.scheduler; - -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; -import java.util.function.Consumer; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -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) - */ - public int scheduleSyncDelayedTask(@NotNull Plugin plugin, @NotNull 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 - public int scheduleSyncDelayedTask(@NotNull Plugin plugin, @NotNull 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) - */ - public int scheduleSyncDelayedTask(@NotNull Plugin plugin, @NotNull 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 - public int scheduleSyncDelayedTask(@NotNull Plugin plugin, @NotNull 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) - */ - public int scheduleSyncRepeatingTask(@NotNull Plugin plugin, @NotNull 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 - public int scheduleSyncRepeatingTask(@NotNull Plugin plugin, @NotNull 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 - public int scheduleAsyncDelayedTask(@NotNull Plugin plugin, @NotNull 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 - public int scheduleAsyncDelayedTask(@NotNull Plugin plugin, @NotNull 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 - public int scheduleAsyncRepeatingTask(@NotNull Plugin plugin, @NotNull 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 - */ - @NotNull - public Future callSyncMethod(@NotNull Plugin plugin, @NotNull Callable task); - - /** - * Removes task from scheduler. - * - * @param taskId Id number of task to be removed - */ - public void cancelTask(int taskId); - - /** - * Removes all tasks associated with a particular plugin from the - * scheduler. - * - * @param plugin Owner of tasks to be removed - */ - public void cancelTasks(@NotNull Plugin plugin); - - /** - * 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. - */ - public 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. - */ - public 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 - */ - @NotNull - public 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 - */ - @NotNull - public 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 - */ - @NotNull - public BukkitTask runTask(@NotNull Plugin plugin, @NotNull Runnable task) throws IllegalArgumentException; - - /** - * 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 - * @throws IllegalArgumentException if plugin is null - * @throws IllegalArgumentException if task is null - */ - public void runTask(@NotNull Plugin plugin, @NotNull Consumer 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 - @NotNull - public BukkitTask runTask(@NotNull Plugin plugin, @NotNull 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 - */ - @NotNull - public BukkitTask runTaskAsynchronously(@NotNull Plugin plugin, @NotNull Runnable 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 - * @throws IllegalArgumentException if plugin is null - * @throws IllegalArgumentException if task is null - */ - public void runTaskAsynchronously(@NotNull Plugin plugin, @NotNull Consumer 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 - @NotNull - public BukkitTask runTaskAsynchronously(@NotNull Plugin plugin, @NotNull 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 - */ - @NotNull - public BukkitTask runTaskLater(@NotNull Plugin plugin, @NotNull Runnable task, long delay) 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 - * @throws IllegalArgumentException if plugin is null - * @throws IllegalArgumentException if task is null - */ - public void runTaskLater(@NotNull Plugin plugin, @NotNull Consumer 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 - @NotNull - public BukkitTask runTaskLater(@NotNull Plugin plugin, @NotNull 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 - */ - @NotNull - public BukkitTask runTaskLaterAsynchronously(@NotNull Plugin plugin, @NotNull Runnable 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 - * @throws IllegalArgumentException if plugin is null - * @throws IllegalArgumentException if task is null - */ - public void runTaskLaterAsynchronously(@NotNull Plugin plugin, @NotNull Consumer 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 - @NotNull - public BukkitTask runTaskLaterAsynchronously(@NotNull Plugin plugin, @NotNull 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 - */ - @NotNull - public BukkitTask runTaskTimer(@NotNull Plugin plugin, @NotNull Runnable task, long delay, long period) 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 - * @throws IllegalArgumentException if plugin is null - * @throws IllegalArgumentException if task is null - */ - public void runTaskTimer(@NotNull Plugin plugin, @NotNull Consumer 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 - @NotNull - public BukkitTask runTaskTimer(@NotNull Plugin plugin, @NotNull 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 - */ - @NotNull - public BukkitTask runTaskTimerAsynchronously(@NotNull Plugin plugin, @NotNull Runnable 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 - * @throws IllegalArgumentException if plugin is null - * @throws IllegalArgumentException if task is null - */ - public void runTaskTimerAsynchronously(@NotNull Plugin plugin, @NotNull Consumer 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 - @NotNull - public BukkitTask runTaskTimerAsynchronously(@NotNull Plugin plugin, @NotNull BukkitRunnable task, long delay, long period) throws IllegalArgumentException; -} diff --git a/api/src/main/java/org/bukkit/scheduler/BukkitTask.java b/api/src/main/java/org/bukkit/scheduler/BukkitTask.java deleted file mode 100644 index 512515849..000000000 --- a/api/src/main/java/org/bukkit/scheduler/BukkitTask.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.scheduler; - -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * Represents a task being executed by the scheduler - */ -public interface BukkitTask { - - /** - * Returns the taskId for the task. - * - * @return Task id number - */ - public int getTaskId(); - - /** - * Returns the Plugin that owns this task. - * - * @return The Plugin that owns the task - */ - @NotNull - public Plugin getOwner(); - - /** - * Returns true if the Task is a sync task. - * - * @return true if the task is run by main thread - */ - public boolean isSync(); - - /** - * Returns true if this task has been cancelled. - * - * @return true if the task has been cancelled - */ - public boolean isCancelled(); - - /** - * Will attempt to cancel this task. - */ - public void cancel(); -} diff --git a/api/src/main/java/org/bukkit/scheduler/BukkitWorker.java b/api/src/main/java/org/bukkit/scheduler/BukkitWorker.java deleted file mode 100644 index 81bdc9cea..000000000 --- a/api/src/main/java/org/bukkit/scheduler/BukkitWorker.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.scheduler; - -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - public int getTaskId(); - - /** - * Returns the Plugin that owns this task. - * - * @return The Plugin that owns the task - */ - @NotNull - public Plugin getOwner(); - - /** - * Returns the thread for the worker. - * - * @return The Thread object for the worker - */ - @NotNull - public Thread getThread(); - -} diff --git a/api/src/main/java/org/bukkit/scoreboard/Criterias.java b/api/src/main/java/org/bukkit/scoreboard/Criterias.java deleted file mode 100644 index 413430928..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/Criterias.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.scoreboard; - -/** - * Criteria names which trigger an objective to be modified by actions in-game - */ -public final class Criterias { - - public static final String HEALTH = "health"; - public static final String PLAYER_KILLS = "playerKillCount"; - public static final String TOTAL_KILLS = "totalKillCount"; - public static final String DEATHS = "deathCount"; - - private Criterias() {} -} diff --git a/api/src/main/java/org/bukkit/scoreboard/DisplaySlot.java b/api/src/main/java/org/bukkit/scoreboard/DisplaySlot.java deleted file mode 100644 index 5d58a18b3..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/DisplaySlot.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.bukkit.scoreboard; - -/** - * Locations for displaying objectives to the player - */ -public enum DisplaySlot { - BELOW_NAME, - PLAYER_LIST, - SIDEBAR; -} diff --git a/api/src/main/java/org/bukkit/scoreboard/NameTagVisibility.java b/api/src/main/java/org/bukkit/scoreboard/NameTagVisibility.java deleted file mode 100644 index d9e9ae1a9..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/NameTagVisibility.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.scoreboard; - -/** - * @deprecated replaced by {@link Team.OptionStatus} - */ -@Deprecated -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/api/src/main/java/org/bukkit/scoreboard/Objective.java b/api/src/main/java/org/bukkit/scoreboard/Objective.java deleted file mode 100644 index f5cbf6df3..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/Objective.java +++ /dev/null @@ -1,137 +0,0 @@ -package org.bukkit.scoreboard; - -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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's name - * @throws IllegalStateException if this objective has been unregistered - */ - @NotNull - 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 - */ - @NotNull - 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 128 - * characters. - */ - void setDisplayName(@NotNull String displayName) throws IllegalStateException, IllegalArgumentException; - - /** - * Gets the criteria this objective tracks. - * - * @return this objective's criteria - * @throws IllegalStateException if this objective has been unregistered - */ - @NotNull - 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} - */ - @Nullable - 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(@Nullable 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 - */ - @Nullable - DisplaySlot getDisplaySlot() throws IllegalStateException; - - /** - * Sets manner in which this objective will be rendered. - * - * @param renderType new render type - * @throws IllegalStateException if this objective has been unregistered - */ - void setRenderType(@NotNull RenderType renderType) throws IllegalStateException; - - /** - * Sets manner in which this objective will be rendered. - * - * @return the render type - * @throws IllegalStateException if this objective has been unregistered - */ - @NotNull - RenderType getRenderType() 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 - @NotNull - Score getScore(@NotNull 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 - * @throws IllegalArgumentException if entry is longer than 40 characters. - */ - @NotNull - Score getScore(@NotNull String entry) throws IllegalArgumentException, IllegalStateException; -} diff --git a/api/src/main/java/org/bukkit/scoreboard/RenderType.java b/api/src/main/java/org/bukkit/scoreboard/RenderType.java deleted file mode 100644 index f169f8726..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/RenderType.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bukkit.scoreboard; - -/** - * Controls the way in which an {@link Objective} is rendered client side. - */ -public enum RenderType { - - /** - * Display integer value. - */ - INTEGER, - /** - * Display number of hearts corresponding to value. - */ - HEARTS; -} diff --git a/api/src/main/java/org/bukkit/scoreboard/Score.java b/api/src/main/java/org/bukkit/scoreboard/Score.java deleted file mode 100644 index f4e626f92..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/Score.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.bukkit.scoreboard; - -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - @NotNull - OfflinePlayer getPlayer(); - - /** - * Gets the entry being tracked by this Score - * - * @return this Score's tracked entry - */ - @NotNull - String getEntry(); - - /** - * Gets the Objective being tracked by this Score - * - * @return this Score's tracked objective - */ - @NotNull - 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; - - /** - * 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; - - /** - * Gets the scoreboard for the associated objective. - * - * @return the owning objective's scoreboard, or null if it has been - * {@link Objective#unregister() unregistered} - */ - @Nullable - Scoreboard getScoreboard(); -} diff --git a/api/src/main/java/org/bukkit/scoreboard/Scoreboard.java b/api/src/main/java/org/bukkit/scoreboard/Scoreboard.java deleted file mode 100644 index aeab2425e..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/Scoreboard.java +++ /dev/null @@ -1,232 +0,0 @@ -package org.bukkit.scoreboard; - -import java.util.Set; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 name is longer than 16 - * characters. - * @throws IllegalArgumentException if criteria is null - * @throws IllegalArgumentException if an objective by that name already - * exists - * @deprecated a displayName should be explicitly specified - */ - @Deprecated - @NotNull - Objective registerNewObjective(@NotNull String name, @NotNull String criteria) throws IllegalArgumentException; - - /** - * Registers an Objective on this Scoreboard - * - * @param name Name of the Objective - * @param criteria Criteria for the Objective - * @param displayName Name displayed to players for the Objective. - * @return The registered Objective - * @throws IllegalArgumentException if name is null - * @throws IllegalArgumentException if name is longer than 16 - * characters. - * @throws IllegalArgumentException if criteria is null - * @throws IllegalArgumentException if displayName is null - * @throws IllegalArgumentException if displayName is longer than 128 - * characters. - * @throws IllegalArgumentException if an objective by that name already - * exists - */ - @NotNull - Objective registerNewObjective(@NotNull String name, @NotNull String criteria, @NotNull String displayName) throws IllegalArgumentException; - - /** - * Registers an Objective on this Scoreboard - * - * @param name Name of the Objective - * @param criteria Criteria for the Objective - * @param displayName Name displayed to players for the Objective. - * @param renderType Manner of rendering the Objective - * @return The registered Objective - * @throws IllegalArgumentException if name is null - * @throws IllegalArgumentException if name is longer than 16 - * characters. - * @throws IllegalArgumentException if criteria is null - * @throws IllegalArgumentException if displayName is null - * @throws IllegalArgumentException if displayName is longer than 128 - * characters. - * @throws IllegalArgumentException if renderType is null - * @throws IllegalArgumentException if an objective by that name already - * exists - */ - @NotNull - Objective registerNewObjective(@NotNull String name, @NotNull String criteria, @NotNull String displayName, @NotNull RenderType renderType) 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 - */ - @Nullable - Objective getObjective(@NotNull 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 - */ - @NotNull - Set getObjectivesByCriteria(@NotNull String criteria) throws IllegalArgumentException; - - /** - * Gets all Objectives on this Scoreboard - * - * @return An immutable set of all Objectives on this Scoreboard - */ - @NotNull - 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 - */ - @Nullable - Objective getObjective(@NotNull 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 - @NotNull - Set getScores(@NotNull 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 - */ - @NotNull - Set getScores(@NotNull 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(@NotNull 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(@NotNull 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 - @Nullable - Team getPlayerTeam(@NotNull 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 - */ - @Nullable - Team getEntryTeam(@NotNull 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 - */ - @Nullable - Team getTeam(@NotNull String teamName) throws IllegalArgumentException; - - /** - * Gets all teams on this Scoreboard - * - * @return an immutable set of Teams - */ - @NotNull - 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 - */ - @NotNull - Team registerNewTeam(@NotNull 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 - @NotNull - Set getPlayers(); - - /** - * Gets all entries tracked by this Scoreboard - * - * @return immutable set of all tracked entries - */ - @NotNull - Set getEntries(); - - /** - * Clears any objective in the specified slot. - * - * @param slot the slot to remove objectives - * @throws IllegalArgumentException if slot is null - */ - void clearSlot(@NotNull DisplaySlot slot) throws IllegalArgumentException; -} diff --git a/api/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java b/api/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java deleted file mode 100644 index 3c0740797..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bukkit.scoreboard; - -import java.lang.ref.WeakReference; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - 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 - */ - @NotNull - Scoreboard getNewScoreboard(); -} diff --git a/api/src/main/java/org/bukkit/scoreboard/Team.java b/api/src/main/java/org/bukkit/scoreboard/Team.java deleted file mode 100644 index dc20daae9..000000000 --- a/api/src/main/java/org/bukkit/scoreboard/Team.java +++ /dev/null @@ -1,339 +0,0 @@ -package org.bukkit.scoreboard; - -import java.util.Set; -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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 - */ - @NotNull - 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 - */ - @NotNull - 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 128 - * characters. - * @throws IllegalStateException if this team has been unregistered - */ - void setDisplayName(@NotNull 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 - */ - @NotNull - 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 64 - * characters - * @throws IllegalStateException if this team has been unregistered - */ - void setPrefix(@NotNull 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 - */ - @NotNull - 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 64 - * characters - * @throws IllegalStateException if this team has been unregistered - */ - void setSuffix(@NotNull String suffix) throws IllegalStateException, IllegalArgumentException; - - /** - * Gets the color of the team. - *
- * This only sets the team outline, other occurrences of colors such as in - * names are handled by prefixes / suffixes. - * - * @return team color, defaults to {@link ChatColor#RESET} - * @throws IllegalStateException if this team has been unregistered - */ - @NotNull - ChatColor getColor() throws IllegalStateException; - - /** - * Sets the color of the team. - *
- * This only sets the team outline, other occurrences of colors such as in - * names are handled by prefixes / suffixes. - * - * @param color new color, must be non-null. Use {@link ChatColor#RESET} for - * no color - */ - void setColor(@NotNull ChatColor color); - - /** - * 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 visibility for the team - * @throws IllegalArgumentException if this team has been unregistered - * @deprecated see {@link #getOption(org.bukkit.scoreboard.Team.Option)} - */ - @Deprecated - @NotNull - NameTagVisibility getNameTagVisibility() throws IllegalArgumentException; - - /** - * Set's the team's ability to see name tags - * - * @param visibility The nameTagVisibility to set - * @throws IllegalArgumentException if this team has been unregistered - * @deprecated see - * {@link #setOption(org.bukkit.scoreboard.Team.Option, org.bukkit.scoreboard.Team.OptionStatus)} - */ - @Deprecated - void setNameTagVisibility(@NotNull 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 - @NotNull - 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\ - */ - @NotNull - 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} - */ - @Nullable - 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull String entry) throws IllegalArgumentException, IllegalStateException; - - /** - * Get an option for this team - * - * @param option the option to get - * @return the option status - * @throws IllegalStateException if this team has been unregistered - */ - @NotNull - OptionStatus getOption(@NotNull Option option) throws IllegalStateException; - - /** - * Set an option for this team - * - * @param option the option to set - * @param status the new option status - * @throws IllegalStateException if this team has been unregistered - */ - void setOption(@NotNull Option option, @NotNull OptionStatus status) throws IllegalStateException; - - /** - * Represents an option which may be applied to this team. - */ - public enum Option { - - /** - * How to display the name tags of players on this team. - */ - NAME_TAG_VISIBILITY, - /** - * How to display the death messages for players on this team. - */ - DEATH_MESSAGE_VISIBILITY, - /** - * How players of this team collide with others. - */ - COLLISION_RULE; - } - - /** - * How an option may be applied to members of this team. - */ - public enum OptionStatus { - - /** - * Apply this option to everyone. - */ - ALWAYS, - /** - * Never apply this option. - */ - NEVER, - /** - * Apply this option only for opposing teams. - */ - FOR_OTHER_TEAMS, - /** - * Apply this option for only team members. - */ - FOR_OWN_TEAM; - } -} diff --git a/api/src/main/java/org/bukkit/util/BlockIterator.java b/api/src/main/java/org/bukkit/util/BlockIterator.java deleted file mode 100644 index 8a377e141..000000000 --- a/api/src/main/java/org/bukkit/util/BlockIterator.java +++ /dev/null @@ -1,371 +0,0 @@ -package org.bukkit.util; - -import static org.bukkit.util.NumberConversions.*; -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.LivingEntity; -import org.jetbrains.annotations.NotNull; - -/** - * 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. - *

- * This considers all blocks as 1x1x1 in size. - * - * @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(@NotNull World world, @NotNull Vector start, @NotNull 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(@NotNull Block a, @NotNull Block b) { - return a.getX() == b.getX() && a.getY() == b.getY() && a.getZ() == b.getZ(); - } - - private BlockFace getXFace(@NotNull Vector direction) { - return ((direction.getX() > 0) ? BlockFace.EAST : BlockFace.WEST); - } - - private BlockFace getYFace(@NotNull Vector direction) { - return ((direction.getY() > 0) ? BlockFace.UP : BlockFace.DOWN); - } - - private BlockFace getZFace(@NotNull Vector direction) { - return ((direction.getZ() > 0) ? BlockFace.SOUTH : BlockFace.NORTH); - } - - private double getXLength(@NotNull Vector direction) { - return Math.abs(direction.getX()); - } - - private double getYLength(@NotNull Vector direction) { - return Math.abs(direction.getY()); - } - - private double getZLength(@NotNull 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(@NotNull Vector direction, @NotNull Vector position, @NotNull Block block) { - return getPosition(direction.getX(), position.getX(), block.getX()); - } - - private double getYPosition(@NotNull Vector direction, @NotNull Vector position, @NotNull Block block) { - return getPosition(direction.getY(), position.getY(), block.getY()); - } - - private double getZPosition(@NotNull Vector direction, @NotNull Vector position, @NotNull Block block) { - return getPosition(direction.getZ(), position.getZ(), block.getZ()); - } - - /** - * Constructs the BlockIterator. - *

- * This considers all blocks as 1x1x1 in size. - * - * @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(@NotNull Location loc, double yOffset, int maxDistance) { - this(loc.getWorld(), loc.toVector(), loc.getDirection(), yOffset, maxDistance); - } - - /** - * Constructs the BlockIterator. - *

- * This considers all blocks as 1x1x1 in size. - * - * @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(@NotNull Location loc, double yOffset) { - this(loc.getWorld(), loc.toVector(), loc.getDirection(), yOffset, 0); - } - - /** - * Constructs the BlockIterator. - *

- * This considers all blocks as 1x1x1 in size. - * - * @param loc The location for the start of the ray trace - */ - - public BlockIterator(@NotNull Location loc) { - this(loc, 0D); - } - - /** - * Constructs the BlockIterator. - *

- * This considers all blocks as 1x1x1 in size. - * - * @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(@NotNull LivingEntity entity, int maxDistance) { - this(entity.getLocation(), entity.getEyeHeight(), maxDistance); - } - - /** - * Constructs the BlockIterator. - *

- * This considers all blocks as 1x1x1 in size. - * - * @param entity Information from the entity is used to set up the trace - */ - - public BlockIterator(@NotNull LivingEntity entity) { - this(entity, 0); - } - - /** - * Returns true if the iteration has more elements - */ - - @Override - public boolean hasNext() { - scan(); - return currentBlock != -1; - } - - /** - * Returns the next Block in the trace - * - * @return the next Block in the trace - */ - @Override - @NotNull - public Block next() throws NoSuchElementException { - scan(); - if (currentBlock <= -1) { - throw new NoSuchElementException(); - } else { - return blockQueue[currentBlock--]; - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("[BlockIterator] doesn't support block removal"); - } - - private void scan() { - if (currentBlock >= 0) { - return; - } - if (maxDistance != 0 && currentDistance > maxDistanceInt) { - end = true; - return; - } - 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/api/src/main/java/org/bukkit/util/BlockVector.java b/api/src/main/java/org/bukkit/util/BlockVector.java deleted file mode 100644 index eddc72489..000000000 --- a/api/src/main/java/org/bukkit/util/BlockVector.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.bukkit.util; - -import java.util.Map; -import org.bukkit.configuration.serialization.SerializableAs; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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(); - } - - @NotNull - public static BlockVector deserialize(@NotNull 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/api/src/main/java/org/bukkit/util/BoundingBox.java b/api/src/main/java/org/bukkit/util/BoundingBox.java deleted file mode 100644 index e5c7826af..000000000 --- a/api/src/main/java/org/bukkit/util/BoundingBox.java +++ /dev/null @@ -1,1064 +0,0 @@ -package org.bukkit.util; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.SerializableAs; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * A mutable axis aligned bounding box (AABB). - *

- * This basically represents a rectangular box (specified by minimum and maximum - * corners) that can for example be used to describe the position and extents of - * an object (such as an entity, block, or rectangular region) in 3D space. Its - * edges and faces are parallel to the axes of the cartesian coordinate system. - *

- * The bounding box may be degenerate (one or more sides having the length 0). - *

- * Because bounding boxes are mutable, storing them long term may be dangerous - * if they get modified later. If you want to keep around a bounding box, it may - * be wise to call {@link #clone()} in order to get a copy. - */ -@SerializableAs("BoundingBox") -public class BoundingBox implements Cloneable, ConfigurationSerializable { - - /** - * Creates a new bounding box using the coordinates of the given vectors as - * corners. - * - * @param corner1 the first corner - * @param corner2 the second corner - * @return the bounding box - */ - @NotNull - public static BoundingBox of(@NotNull Vector corner1, @NotNull Vector corner2) { - Validate.notNull(corner1, "Corner1 is null!"); - Validate.notNull(corner2, "Corner2 is null!"); - return new BoundingBox(corner1.getX(), corner1.getY(), corner1.getZ(), corner2.getX(), corner2.getY(), corner2.getZ()); - } - - /** - * Creates a new bounding box using the coordinates of the given locations - * as corners. - * - * @param corner1 the first corner - * @param corner2 the second corner - * @return the bounding box - */ - @NotNull - public static BoundingBox of(@NotNull Location corner1, @NotNull Location corner2) { - Validate.notNull(corner1, "Corner1 is null!"); - Validate.notNull(corner2, "Corner2 is null!"); - Validate.isTrue(Objects.equals(corner1.getWorld(), corner2.getWorld()), "Locations from different worlds!"); - return new BoundingBox(corner1.getX(), corner1.getY(), corner1.getZ(), corner2.getX(), corner2.getY(), corner2.getZ()); - } - - /** - * Creates a new bounding box using the coordinates of the given blocks as - * corners. - *

- * The bounding box will be sized to fully contain both blocks. - * - * @param corner1 the first corner block - * @param corner2 the second corner block - * @return the bounding box - */ - @NotNull - public static BoundingBox of(@NotNull Block corner1, @NotNull Block corner2) { - Validate.notNull(corner1, "Corner1 is null!"); - Validate.notNull(corner2, "Corner2 is null!"); - Validate.isTrue(Objects.equals(corner1.getWorld(), corner2.getWorld()), "Blocks from different worlds!"); - - int x1 = corner1.getX(); - int y1 = corner1.getY(); - int z1 = corner1.getZ(); - int x2 = corner2.getX(); - int y2 = corner2.getY(); - int z2 = corner2.getZ(); - - int minX = Math.min(x1, x2); - int minY = Math.min(y1, y2); - int minZ = Math.min(z1, z2); - int maxX = Math.max(x1, x2) + 1; - int maxY = Math.max(y1, y2) + 1; - int maxZ = Math.max(z1, z2) + 1; - - return new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ); - } - - /** - * Creates a new 1x1x1 sized bounding box containing the given block. - * - * @param block the block - * @return the bounding box - */ - @NotNull - public static BoundingBox of(@NotNull Block block) { - Validate.notNull(block, "Block is null!"); - return new BoundingBox(block.getX(), block.getY(), block.getZ(), block.getX() + 1, block.getY() + 1, block.getZ() + 1); - } - - /** - * Creates a new bounding box using the given center and extents. - * - * @param center the center - * @param x 1/2 the size of the bounding box along the x axis - * @param y 1/2 the size of the bounding box along the y axis - * @param z 1/2 the size of the bounding box along the z axis - * @return the bounding box - */ - @NotNull - public static BoundingBox of(@NotNull Vector center, double x, double y, double z) { - Validate.notNull(center, "Center is null!"); - return new BoundingBox(center.getX() - x, center.getY() - y, center.getZ() - z, center.getX() + x, center.getY() + y, center.getZ() + z); - } - - /** - * Creates a new bounding box using the given center and extents. - * - * @param center the center - * @param x 1/2 the size of the bounding box along the x axis - * @param y 1/2 the size of the bounding box along the y axis - * @param z 1/2 the size of the bounding box along the z axis - * @return the bounding box - */ - @NotNull - public static BoundingBox of(@NotNull Location center, double x, double y, double z) { - Validate.notNull(center, "Center is null!"); - return new BoundingBox(center.getX() - x, center.getY() - y, center.getZ() - z, center.getX() + x, center.getY() + y, center.getZ() + z); - } - - private double minX; - private double minY; - private double minZ; - private double maxX; - private double maxY; - private double maxZ; - - /** - * Creates a new (degenerate) bounding box with all corner coordinates at - * 0. - */ - public BoundingBox() { - this.resize(0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); - } - - /** - * Creates a new bounding box from the given corner coordinates. - * - * @param x1 the first corner's x value - * @param y1 the first corner's y value - * @param z1 the first corner's z value - * @param x2 the second corner's x value - * @param y2 the second corner's y value - * @param z2 the second corner's z value - */ - public BoundingBox(double x1, double y1, double z1, double x2, double y2, double z2) { - this.resize(x1, y1, z1, x2, y2, z2); - } - - /** - * Resizes this bounding box. - * - * @param x1 the first corner's x value - * @param y1 the first corner's y value - * @param z1 the first corner's z value - * @param x2 the second corner's x value - * @param y2 the second corner's y value - * @param z2 the second corner's z value - * @return this bounding box (resized) - */ - @NotNull - public BoundingBox resize(double x1, double y1, double z1, double x2, double y2, double z2) { - NumberConversions.checkFinite(x1, "x1 not finite"); - NumberConversions.checkFinite(y1, "y1 not finite"); - NumberConversions.checkFinite(z1, "z1 not finite"); - NumberConversions.checkFinite(x2, "x2 not finite"); - NumberConversions.checkFinite(y2, "y2 not finite"); - NumberConversions.checkFinite(z2, "z2 not finite"); - - this.minX = Math.min(x1, x2); - this.minY = Math.min(y1, y2); - this.minZ = Math.min(z1, z2); - this.maxX = Math.max(x1, x2); - this.maxY = Math.max(y1, y2); - this.maxZ = Math.max(z1, z2); - return this; - } - - /** - * Gets the minimum x value. - * - * @return the minimum x value - */ - public double getMinX() { - return minX; - } - - /** - * Gets the minimum y value. - * - * @return the minimum y value - */ - public double getMinY() { - return minY; - } - - /** - * Gets the minimum z value. - * - * @return the minimum z value - */ - public double getMinZ() { - return minZ; - } - - /** - * Gets the minimum corner as vector. - * - * @return the minimum corner as vector - */ - @NotNull - public Vector getMin() { - return new Vector(minX, minY, minZ); - } - - /** - * Gets the maximum x value. - * - * @return the maximum x value - */ - public double getMaxX() { - return maxX; - } - - /** - * Gets the maximum y value. - * - * @return the maximum y value - */ - public double getMaxY() { - return maxY; - } - - /** - * Gets the maximum z value. - * - * @return the maximum z value - */ - public double getMaxZ() { - return maxZ; - } - - /** - * Gets the maximum corner as vector. - * - * @return the maximum corner vector - */ - @NotNull - public Vector getMax() { - return new Vector(maxX, maxY, maxZ); - } - - /** - * Gets the width of the bounding box in the x direction. - * - * @return the width in the x direction - */ - public double getWidthX() { - return (this.maxX - this.minX); - } - - /** - * Gets the width of the bounding box in the z direction. - * - * @return the width in the z direction - */ - public double getWidthZ() { - return (this.maxZ - this.minZ); - } - - /** - * Gets the height of the bounding box. - * - * @return the height - */ - public double getHeight() { - return (this.maxY - this.minY); - } - - /** - * Gets the volume of the bounding box. - * - * @return the volume - */ - public double getVolume() { - return (this.getHeight() * this.getWidthX() * this.getWidthZ()); - } - - /** - * Gets the x coordinate of the center of the bounding box. - * - * @return the center's x coordinate - */ - public double getCenterX() { - return (this.minX + this.getWidthX() * 0.5D); - } - - /** - * Gets the y coordinate of the center of the bounding box. - * - * @return the center's y coordinate - */ - public double getCenterY() { - return (this.minY + this.getHeight() * 0.5D); - } - - /** - * Gets the z coordinate of the center of the bounding box. - * - * @return the center's z coordinate - */ - public double getCenterZ() { - return (this.minZ + this.getWidthZ() * 0.5D); - } - - /** - * Gets the center of the bounding box. - * - * @return the center - */ - @NotNull - public Vector getCenter() { - return new Vector(this.getCenterX(), this.getCenterY(), this.getCenterZ()); - } - - /** - * Copies another bounding box. - * - * @param other the other bounding box - * @return this bounding box - */ - @NotNull - public BoundingBox copy(@NotNull BoundingBox other) { - Validate.notNull(other, "Other bounding box is null!"); - return this.resize(other.getMinX(), other.getMinY(), other.getMinZ(), other.getMaxX(), other.getMaxY(), other.getMaxZ()); - } - - /** - * Expands this bounding box by the given values in the corresponding - * directions. - *

- * Negative values will shrink the bounding box in the corresponding - * direction. Shrinking will be limited to the point where the affected - * opposite faces would meet if the they shrank at uniform speeds. - * - * @param negativeX the amount of expansion in the negative x direction - * @param negativeY the amount of expansion in the negative y direction - * @param negativeZ the amount of expansion in the negative z direction - * @param positiveX the amount of expansion in the positive x direction - * @param positiveY the amount of expansion in the positive y direction - * @param positiveZ the amount of expansion in the positive z direction - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expand(double negativeX, double negativeY, double negativeZ, double positiveX, double positiveY, double positiveZ) { - if (negativeX == 0.0D && negativeY == 0.0D && negativeZ == 0.0D && positiveX == 0.0D && positiveY == 0.0D && positiveZ == 0.0D) { - return this; - } - double newMinX = this.minX - negativeX; - double newMinY = this.minY - negativeY; - double newMinZ = this.minZ - negativeZ; - double newMaxX = this.maxX + positiveX; - double newMaxY = this.maxY + positiveY; - double newMaxZ = this.maxZ + positiveZ; - - // limit shrinking: - if (newMinX > newMaxX) { - double centerX = this.getCenterX(); - if (newMaxX >= centerX) { - newMinX = newMaxX; - } else if (newMinX <= centerX) { - newMaxX = newMinX; - } else { - newMinX = centerX; - newMaxX = centerX; - } - } - if (newMinY > newMaxY) { - double centerY = this.getCenterY(); - if (newMaxY >= centerY) { - newMinY = newMaxY; - } else if (newMinY <= centerY) { - newMaxY = newMinY; - } else { - newMinY = centerY; - newMaxY = centerY; - } - } - if (newMinZ > newMaxZ) { - double centerZ = this.getCenterZ(); - if (newMaxZ >= centerZ) { - newMinZ = newMaxZ; - } else if (newMinZ <= centerZ) { - newMaxZ = newMinZ; - } else { - newMinZ = centerZ; - newMaxZ = centerZ; - } - } - return this.resize(newMinX, newMinY, newMinZ, newMaxX, newMaxY, newMaxZ); - } - - /** - * Expands this bounding box uniformly by the given values in both positive - * and negative directions. - *

- * Negative values will shrink the bounding box. Shrinking will be limited - * to the bounding box's current size. - * - * @param x the amount of expansion in both positive and negative x - * direction - * @param y the amount of expansion in both positive and negative y - * direction - * @param z the amount of expansion in both positive and negative z - * direction - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expand(double x, double y, double z) { - return this.expand(x, y, z, x, y, z); - } - - /** - * Expands this bounding box uniformly by the given values in both positive - * and negative directions. - *

- * Negative values will shrink the bounding box. Shrinking will be limited - * to the bounding box's current size. - * - * @param expansion the expansion values - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expand(@NotNull Vector expansion) { - Validate.notNull(expansion, "Expansion is null!"); - double x = expansion.getX(); - double y = expansion.getY(); - double z = expansion.getZ(); - return this.expand(x, y, z, x, y, z); - } - - /** - * Expands this bounding box uniformly by the given value in all directions. - *

- * A negative value will shrink the bounding box. Shrinking will be limited - * to the bounding box's current size. - * - * @param expansion the amount of expansion - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expand(double expansion) { - return this.expand(expansion, expansion, expansion, expansion, expansion, expansion); - } - - /** - * Expands this bounding box in the specified direction. - *

- * The magnitude of the direction will scale the expansion. A negative - * expansion value will shrink the bounding box in this direction. Shrinking - * will be limited to the bounding box's current size. - * - * @param dirX the x direction component - * @param dirY the y direction component - * @param dirZ the z direction component - * @param expansion the amount of expansion - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expand(double dirX, double dirY, double dirZ, double expansion) { - if (expansion == 0.0D) return this; - if (dirX == 0.0D && dirY == 0.0D && dirZ == 0.0D) return this; - - double negativeX = (dirX < 0.0D ? (-dirX * expansion) : 0.0D); - double negativeY = (dirY < 0.0D ? (-dirY * expansion) : 0.0D); - double negativeZ = (dirZ < 0.0D ? (-dirZ * expansion) : 0.0D); - double positiveX = (dirX > 0.0D ? (dirX * expansion) : 0.0D); - double positiveY = (dirY > 0.0D ? (dirY * expansion) : 0.0D); - double positiveZ = (dirZ > 0.0D ? (dirZ * expansion) : 0.0D); - return this.expand(negativeX, negativeY, negativeZ, positiveX, positiveY, positiveZ); - } - - /** - * Expands this bounding box in the specified direction. - *

- * The magnitude of the direction will scale the expansion. A negative - * expansion value will shrink the bounding box in this direction. Shrinking - * will be limited to the bounding box's current size. - * - * @param direction the direction - * @param expansion the amount of expansion - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expand(@NotNull Vector direction, double expansion) { - Validate.notNull(direction, "Direction is null!"); - return this.expand(direction.getX(), direction.getY(), direction.getZ(), expansion); - } - - /** - * Expands this bounding box in the direction specified by the given block - * face. - *

- * A negative expansion value will shrink the bounding box in this - * direction. Shrinking will be limited to the bounding box's current size. - * - * @param blockFace the block face - * @param expansion the amount of expansion - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expand(@NotNull BlockFace blockFace, double expansion) { - Validate.notNull(blockFace, "Block face is null!"); - if (blockFace == BlockFace.SELF) return this; - - return this.expand(blockFace.getDirection(), expansion); - } - - /** - * Expands this bounding box in the specified direction. - *

- * Negative values will expand the bounding box in the negative direction, - * positive values will expand it in the positive direction. The magnitudes - * of the direction components determine the corresponding amounts of - * expansion. - * - * @param dirX the x direction component - * @param dirY the y direction component - * @param dirZ the z direction component - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expandDirectional(double dirX, double dirY, double dirZ) { - return this.expand(dirX, dirY, dirZ, 1.0D); - } - - /** - * Expands this bounding box in the specified direction. - *

- * Negative values will expand the bounding box in the negative direction, - * positive values will expand it in the positive direction. The magnitude - * of the direction vector determines the amount of expansion. - * - * @param direction the direction and magnitude of the expansion - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox expandDirectional(@NotNull Vector direction) { - Validate.notNull(direction, "Expansion is null!"); - return this.expand(direction.getX(), direction.getY(), direction.getZ(), 1.0D); - } - - /** - * Expands this bounding box to contain (or border) the specified position. - * - * @param posX the x position value - * @param posY the y position value - * @param posZ the z position value - * @return this bounding box (now expanded) - * @see #contains(double, double, double) - */ - @NotNull - public BoundingBox union(double posX, double posY, double posZ) { - double newMinX = Math.min(this.minX, posX); - double newMinY = Math.min(this.minY, posY); - double newMinZ = Math.min(this.minZ, posZ); - double newMaxX = Math.max(this.maxX, posX); - double newMaxY = Math.max(this.maxY, posY); - double newMaxZ = Math.max(this.maxZ, posZ); - if (newMinX == this.minX && newMinY == this.minY && newMinZ == this.minZ && newMaxX == this.maxX && newMaxY == this.maxY && newMaxZ == this.maxZ) { - return this; - } - return this.resize(newMinX, newMinY, newMinZ, newMaxX, newMaxY, newMaxZ); - } - - /** - * Expands this bounding box to contain (or border) the specified position. - * - * @param position the position - * @return this bounding box (now expanded) - * @see #contains(double, double, double) - */ - @NotNull - public BoundingBox union(@NotNull Vector position) { - Validate.notNull(position, "Position is null!"); - return this.union(position.getX(), position.getY(), position.getZ()); - } - - /** - * Expands this bounding box to contain (or border) the specified position. - * - * @param position the position - * @return this bounding box (now expanded) - * @see #contains(double, double, double) - */ - @NotNull - public BoundingBox union(@NotNull Location position) { - Validate.notNull(position, "Position is null!"); - return this.union(position.getX(), position.getY(), position.getZ()); - } - - /** - * Expands this bounding box to contain both this and the given bounding - * box. - * - * @param other the other bounding box - * @return this bounding box (now expanded) - */ - @NotNull - public BoundingBox union(@NotNull BoundingBox other) { - Validate.notNull(other, "Other bounding box is null!"); - if (this.contains(other)) return this; - double newMinX = Math.min(this.minX, other.minX); - double newMinY = Math.min(this.minY, other.minY); - double newMinZ = Math.min(this.minZ, other.minZ); - double newMaxX = Math.max(this.maxX, other.maxX); - double newMaxY = Math.max(this.maxY, other.maxY); - double newMaxZ = Math.max(this.maxZ, other.maxZ); - return this.resize(newMinX, newMinY, newMinZ, newMaxX, newMaxY, newMaxZ); - } - - /** - * Resizes this bounding box to represent the intersection of this and the - * given bounding box. - * - * @param other the other bounding box - * @return this bounding box (now representing the intersection) - * @throws IllegalArgumentException if the bounding boxes don't overlap - */ - @NotNull - public BoundingBox intersection(@NotNull BoundingBox other) { - Validate.notNull(other, "Other bounding box is null!"); - Validate.isTrue(this.overlaps(other), "The bounding boxes do not overlap!"); - double newMinX = Math.max(this.minX, other.minX); - double newMinY = Math.max(this.minY, other.minY); - double newMinZ = Math.max(this.minZ, other.minZ); - double newMaxX = Math.min(this.maxX, other.maxX); - double newMaxY = Math.min(this.maxY, other.maxY); - double newMaxZ = Math.min(this.maxZ, other.maxZ); - return this.resize(newMinX, newMinY, newMinZ, newMaxX, newMaxY, newMaxZ); - } - - /** - * Shifts this bounding box by the given amounts. - * - * @param shiftX the shift in x direction - * @param shiftY the shift in y direction - * @param shiftZ the shift in z direction - * @return this bounding box (now shifted) - */ - @NotNull - public BoundingBox shift(double shiftX, double shiftY, double shiftZ) { - if (shiftX == 0.0D && shiftY == 0.0D && shiftZ == 0.0D) return this; - return this.resize(this.minX + shiftX, this.minY + shiftY, this.minZ + shiftZ, - this.maxX + shiftX, this.maxY + shiftY, this.maxZ + shiftZ); - } - - /** - * Shifts this bounding box by the given amounts. - * - * @param shift the shift - * @return this bounding box (now shifted) - */ - @NotNull - public BoundingBox shift(@NotNull Vector shift) { - Validate.notNull(shift, "Shift is null!"); - return this.shift(shift.getX(), shift.getY(), shift.getZ()); - } - - /** - * Shifts this bounding box by the given amounts. - * - * @param shift the shift - * @return this bounding box (now shifted) - */ - @NotNull - public BoundingBox shift(@NotNull Location shift) { - Validate.notNull(shift, "Shift is null!"); - return this.shift(shift.getX(), shift.getY(), shift.getZ()); - } - - private boolean overlaps(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { - return this.minX < maxX && this.maxX > minX - && this.minY < maxY && this.maxY > minY - && this.minZ < maxZ && this.maxZ > minZ; - } - - /** - * Checks if this bounding box overlaps with the given bounding box. - *

- * Bounding boxes that are only intersecting at the borders are not - * considered overlapping. - * - * @param other the other bounding box - * @return true if overlapping - */ - public boolean overlaps(@NotNull BoundingBox other) { - Validate.notNull(other, "Other bounding box is null!"); - return this.overlaps(other.minX, other.minY, other.minZ, other.maxX, other.maxY, other.maxZ); - } - - /** - * Checks if this bounding box overlaps with the bounding box that is - * defined by the given corners. - *

- * Bounding boxes that are only intersecting at the borders are not - * considered overlapping. - * - * @param min the first corner - * @param max the second corner - * @return true if overlapping - */ - public boolean overlaps(@NotNull Vector min, @NotNull Vector max) { - Validate.notNull(min, "Min is null!"); - Validate.notNull(max, "Max is null!"); - double x1 = min.getX(); - double y1 = min.getY(); - double z1 = min.getZ(); - double x2 = max.getX(); - double y2 = max.getY(); - double z2 = max.getZ(); - return this.overlaps(Math.min(x1, x2), Math.min(y1, y2), Math.min(z1, z2), - Math.max(x1, x2), Math.max(y1, y2), Math.max(z1, z2)); - } - - /** - * Checks if this bounding box contains the specified position. - *

- * Positions exactly on the minimum borders of the bounding box are - * considered to be inside the bounding box, while positions exactly on the - * maximum borders are considered to be outside. This allows bounding boxes - * to reside directly next to each other with positions always only residing - * in exactly one of them. - * - * @param x the position's x coordinates - * @param y the position's y coordinates - * @param z the position's z coordinates - * @return true if the bounding box contains the position - */ - public boolean contains(double x, double y, double z) { - return x >= this.minX && x < this.maxX - && y >= this.minY && y < this.maxY - && z >= this.minZ && z < this.maxZ; - } - - /** - * Checks if this bounding box contains the specified position. - *

- * Positions exactly on the minimum borders of the bounding box are - * considered to be inside the bounding box, while positions exactly on the - * maximum borders are considered to be outside. This allows bounding boxes - * to reside directly next to each other with positions always only residing - * in exactly one of them. - * - * @param position the position - * @return true if the bounding box contains the position - */ - public boolean contains(@NotNull Vector position) { - Validate.notNull(position, "Position is null!"); - return this.contains(position.getX(), position.getY(), position.getZ()); - } - - private boolean contains(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { - return this.minX <= minX && this.maxX >= maxX - && this.minY <= minY && this.maxY >= maxY - && this.minZ <= minZ && this.maxZ >= maxZ; - } - - /** - * Checks if this bounding box fully contains the given bounding box. - * - * @param other the other bounding box - * @return true if the bounding box contains the given bounding - * box - */ - public boolean contains(@NotNull BoundingBox other) { - Validate.notNull(other, "Other bounding box is null!"); - return this.contains(other.minX, other.minY, other.minZ, other.maxX, other.maxY, other.maxZ); - } - - /** - * Checks if this bounding box fully contains the bounding box that is - * defined by the given corners. - * - * @param min the first corner - * @param max the second corner - * @return true if the bounding box contains the specified - * bounding box - */ - public boolean contains(@NotNull Vector min, @NotNull Vector max) { - Validate.notNull(min, "Min is null!"); - Validate.notNull(max, "Max is null!"); - double x1 = min.getX(); - double y1 = min.getY(); - double z1 = min.getZ(); - double x2 = max.getX(); - double y2 = max.getY(); - double z2 = max.getZ(); - return this.contains(Math.min(x1, x2), Math.min(y1, y2), Math.min(z1, z2), - Math.max(x1, x2), Math.max(y1, y2), Math.max(z1, z2)); - } - - /** - * Calculates the intersection of this bounding box with the specified line - * segment. - *

- * Intersections at edges and corners yield one of the affected block faces - * as hit result, but it is not defined which of them. - * - * @param start the start position - * @param direction the ray direction - * @param maxDistance the maximum distance - * @return the ray trace hit result, or null if there is no hit - */ - @Nullable - public RayTraceResult rayTrace(@NotNull Vector start, @NotNull Vector direction, double maxDistance) { - Validate.notNull(start, "Start is null!"); - start.checkFinite(); - Validate.notNull(direction, "Direction is null!"); - direction.checkFinite(); - Validate.isTrue(direction.lengthSquared() > 0, "Direction's magnitude is 0!"); - if (maxDistance < 0.0D) return null; - - // ray start: - double startX = start.getX(); - double startY = start.getY(); - double startZ = start.getZ(); - - // ray direction: - Vector dir = direction.clone().normalize(); - double dirX = dir.getX(); - double dirY = dir.getY(); - double dirZ = dir.getZ(); - - // saving a few divisions below: - double divX = 1.0D / dirX; - double divY = 1.0D / dirY; - double divZ = 1.0D / dirZ; - - double tMin; - double tMax; - BlockFace hitBlockFaceMin; - BlockFace hitBlockFaceMax; - - // intersections with x planes: - if (dirX >= 0.0D) { - tMin = (this.minX - startX) * divX; - tMax = (this.maxX - startX) * divX; - hitBlockFaceMin = BlockFace.WEST; - hitBlockFaceMax = BlockFace.EAST; - } else { - tMin = (this.maxX - startX) * divX; - tMax = (this.minX - startX) * divX; - hitBlockFaceMin = BlockFace.EAST; - hitBlockFaceMax = BlockFace.WEST; - } - - // intersections with y planes: - double tyMin; - double tyMax; - BlockFace hitBlockFaceYMin; - BlockFace hitBlockFaceYMax; - if (dirY >= 0.0D) { - tyMin = (this.minY - startY) * divY; - tyMax = (this.maxY - startY) * divY; - hitBlockFaceYMin = BlockFace.DOWN; - hitBlockFaceYMax = BlockFace.UP; - } else { - tyMin = (this.maxY - startY) * divY; - tyMax = (this.minY - startY) * divY; - hitBlockFaceYMin = BlockFace.UP; - hitBlockFaceYMax = BlockFace.DOWN; - } - if ((tMin > tyMax) || (tMax < tyMin)) { - return null; - } - if (tyMin > tMin) { - tMin = tyMin; - hitBlockFaceMin = hitBlockFaceYMin; - } - if (tyMax < tMax) { - tMax = tyMax; - hitBlockFaceMax = hitBlockFaceYMax; - } - - // intersections with z planes: - double tzMin; - double tzMax; - BlockFace hitBlockFaceZMin; - BlockFace hitBlockFaceZMax; - if (dirZ >= 0.0D) { - tzMin = (this.minZ - startZ) * divZ; - tzMax = (this.maxZ - startZ) * divZ; - hitBlockFaceZMin = BlockFace.NORTH; - hitBlockFaceZMax = BlockFace.SOUTH; - } else { - tzMin = (this.maxZ - startZ) * divZ; - tzMax = (this.minZ - startZ) * divZ; - hitBlockFaceZMin = BlockFace.SOUTH; - hitBlockFaceZMax = BlockFace.NORTH; - } - if ((tMin > tzMax) || (tMax < tzMin)) { - return null; - } - if (tzMin > tMin) { - tMin = tzMin; - hitBlockFaceMin = hitBlockFaceZMin; - } - if (tzMax < tMax) { - tMax = tzMax; - hitBlockFaceMax = hitBlockFaceZMax; - } - - // intersections are behind the start: - if (tMax < 0.0D) return null; - // intersections are to far away: - if (tMin > maxDistance) { - return null; - } - - // find the closest intersection: - double t; - BlockFace hitBlockFace; - if (tMin < 0.0D) { - t = tMax; - hitBlockFace = hitBlockFaceMax; - } else { - t = tMin; - hitBlockFace = hitBlockFaceMin; - } - // reusing the newly created direction vector for the hit position: - Vector hitPosition = dir.multiply(t).add(start); - return new RayTraceResult(hitPosition, hitBlockFace); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - long temp; - temp = Double.doubleToLongBits(maxX); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(maxY); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(maxZ); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(minX); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(minY); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(minZ); - result = prime * result + (int) (temp ^ (temp >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (!(obj instanceof BoundingBox)) return false; - BoundingBox other = (BoundingBox) obj; - if (Double.doubleToLongBits(maxX) != Double.doubleToLongBits(other.maxX)) return false; - if (Double.doubleToLongBits(maxY) != Double.doubleToLongBits(other.maxY)) return false; - if (Double.doubleToLongBits(maxZ) != Double.doubleToLongBits(other.maxZ)) return false; - if (Double.doubleToLongBits(minX) != Double.doubleToLongBits(other.minX)) return false; - if (Double.doubleToLongBits(minY) != Double.doubleToLongBits(other.minY)) return false; - if (Double.doubleToLongBits(minZ) != Double.doubleToLongBits(other.minZ)) return false; - return true; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("BoundingBox [minX="); - builder.append(minX); - builder.append(", minY="); - builder.append(minY); - builder.append(", minZ="); - builder.append(minZ); - builder.append(", maxX="); - builder.append(maxX); - builder.append(", maxY="); - builder.append(maxY); - builder.append(", maxZ="); - builder.append(maxZ); - builder.append("]"); - return builder.toString(); - } - - /** - * Creates a copy of this bounding box. - * - * @return the cloned bounding box - */ - @NotNull - @Override - public BoundingBox clone() { - try { - return (BoundingBox) super.clone(); - } catch (CloneNotSupportedException e) { - throw new Error(e); - } - } - - @NotNull - @Override - public Map serialize() { - Map result = new LinkedHashMap(); - result.put("minX", minX); - result.put("minY", minY); - result.put("minZ", minZ); - result.put("maxX", maxX); - result.put("maxY", maxY); - result.put("maxZ", maxZ); - return result; - } - - @NotNull - public static BoundingBox deserialize(@NotNull Map args) { - double minX = 0.0D; - double minY = 0.0D; - double minZ = 0.0D; - double maxX = 0.0D; - double maxY = 0.0D; - double maxZ = 0.0D; - - if (args.containsKey("minX")) { - minX = ((Number) args.get("minX")).doubleValue(); - } - if (args.containsKey("minY")) { - minY = ((Number) args.get("minY")).doubleValue(); - } - if (args.containsKey("minZ")) { - minZ = ((Number) args.get("minZ")).doubleValue(); - } - if (args.containsKey("maxX")) { - maxX = ((Number) args.get("maxX")).doubleValue(); - } - if (args.containsKey("maxY")) { - maxY = ((Number) args.get("maxY")).doubleValue(); - } - if (args.containsKey("maxZ")) { - maxZ = ((Number) args.get("maxZ")).doubleValue(); - } - - return new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ); - } -} diff --git a/api/src/main/java/org/bukkit/util/CachedServerIcon.java b/api/src/main/java/org/bukkit/util/CachedServerIcon.java deleted file mode 100644 index bb4f7702c..000000000 --- a/api/src/main/java/org/bukkit/util/CachedServerIcon.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit.util; - -import org.bukkit.Server; -import org.bukkit.event.server.ServerListPingEvent; -import org.jetbrains.annotations.Nullable; - -/** - * 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 { - - @Nullable - public String getData(); // Paper - - // Paper start - default boolean isEmpty() { - return getData() == null; - } - // Paper end -} diff --git a/api/src/main/java/org/bukkit/util/ChatPaginator.java b/api/src/main/java/org/bukkit/util/ChatPaginator.java deleted file mode 100644 index 1f5102118..000000000 --- a/api/src/main/java/org/bukkit/util/ChatPaginator.java +++ /dev/null @@ -1,177 +0,0 @@ -package org.bukkit.util; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import org.bukkit.ChatColor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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. - */ - @NotNull - public static ChatPage paginate(@Nullable 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. - */ - @NotNull - public static ChatPage paginate(@Nullable 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 = 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. - */ - @NotNull - public static String[] wordWrap(@Nullable 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() + 1 + word.length() - lineColorChars == lineLength) { // Line exactly the correct length...newline - if (line.length() > 0) { - line.append(' '); - } - 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(@NotNull 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; - } - - @NotNull - public String[] getLines() { - return lines; - } - } -} diff --git a/api/src/main/java/org/bukkit/util/Consumer.java b/api/src/main/java/org/bukkit/util/Consumer.java deleted file mode 100644 index fb9e6b90f..000000000 --- a/api/src/main/java/org/bukkit/util/Consumer.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.util; - -/** - * Represents an operation that accepts a single input argument and returns no - * result. - * - * @param the type of the input to the operation - */ -public interface Consumer { - - /** - * Performs this operation on the given argument. - * - * @param t the input argument - */ - void accept(T t); -} diff --git a/api/src/main/java/org/bukkit/util/EulerAngle.java b/api/src/main/java/org/bukkit/util/EulerAngle.java deleted file mode 100644 index 201cb4a8c..000000000 --- a/api/src/main/java/org/bukkit/util/EulerAngle.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.bukkit.util; - -import org.jetbrains.annotations.NotNull; - -/** - * 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 y axis in radians - * @param z the angle for the z 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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/api/src/main/java/org/bukkit/util/FileUtil.java b/api/src/main/java/org/bukkit/util/FileUtil.java deleted file mode 100644 index 6e2352a30..000000000 --- a/api/src/main/java/org/bukkit/util/FileUtil.java +++ /dev/null @@ -1,58 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull File inFile, @NotNull 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/api/src/main/java/org/bukkit/util/NumberConversions.java b/api/src/main/java/org/bukkit/util/NumberConversions.java deleted file mode 100644 index e10b9a4e5..000000000 --- a/api/src/main/java/org/bukkit/util/NumberConversions.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.bukkit.util; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * 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(@Nullable Object object) { - if (object instanceof Number) { - return ((Number) object).intValue(); - } - - try { - return Integer.parseInt(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static float toFloat(@Nullable Object object) { - if (object instanceof Number) { - return ((Number) object).floatValue(); - } - - try { - return Float.parseFloat(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static double toDouble(@Nullable Object object) { - if (object instanceof Number) { - return ((Number) object).doubleValue(); - } - - try { - return Double.parseDouble(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static long toLong(@Nullable Object object) { - if (object instanceof Number) { - return ((Number) object).longValue(); - } - - try { - return Long.parseLong(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static short toShort(@Nullable Object object) { - if (object instanceof Number) { - return ((Number) object).shortValue(); - } - - try { - return Short.parseShort(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - return 0; - } - - public static byte toByte(@Nullable Object object) { - if (object instanceof Number) { - return ((Number) object).byteValue(); - } - - try { - return Byte.parseByte(object.toString()); - } catch (NumberFormatException e) { - } catch (NullPointerException e) { - } - 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, @NotNull String message) { - if (!isFinite(d)) { - throw new IllegalArgumentException(message); - } - } - - public static void checkFinite(float d, @NotNull String message) { - if (!isFinite(d)) { - throw new IllegalArgumentException(message); - } - } -} diff --git a/api/src/main/java/org/bukkit/util/RayTraceResult.java b/api/src/main/java/org/bukkit/util/RayTraceResult.java deleted file mode 100644 index 19c52a2a6..000000000 --- a/api/src/main/java/org/bukkit/util/RayTraceResult.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.bukkit.util; - -import java.util.Objects; -import org.apache.commons.lang.Validate; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Entity; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * The hit result of a ray trace. - *

- * Only the hit position is guaranteed to always be available. The availability - * of the other attributes depends on what got hit and on the context in which - * the ray trace was performed. - */ -public class RayTraceResult { - - private final Vector hitPosition; - - private final Block hitBlock; - private final BlockFace hitBlockFace; - private final Entity hitEntity; - - private RayTraceResult(@NotNull Vector hitPosition, @Nullable Block hitBlock, @Nullable BlockFace hitBlockFace, @Nullable Entity hitEntity) { - Validate.notNull(hitPosition, "Hit position is null!"); - this.hitPosition = hitPosition.clone(); - this.hitBlock = hitBlock; - this.hitBlockFace = hitBlockFace; - this.hitEntity = hitEntity; - } - - /** - * Creates a RayTraceResult. - * - * @param hitPosition the hit position - */ - public RayTraceResult(@NotNull Vector hitPosition) { - this(hitPosition, null, null, null); - } - - /** - * Creates a RayTraceResult. - * - * @param hitPosition the hit position - * @param hitBlockFace the hit block face - */ - public RayTraceResult(@NotNull Vector hitPosition, @Nullable BlockFace hitBlockFace) { - this(hitPosition, null, hitBlockFace, null); - } - - /** - * Creates a RayTraceResult. - * - * @param hitPosition the hit position - * @param hitBlock the hit block - * @param hitBlockFace the hit block face - */ - public RayTraceResult(@NotNull Vector hitPosition, @Nullable Block hitBlock, @Nullable BlockFace hitBlockFace) { - this(hitPosition, hitBlock, hitBlockFace, null); - } - - /** - * Creates a RayTraceResult. - * - * @param hitPosition the hit position - * @param hitEntity the hit entity - */ - public RayTraceResult(@NotNull Vector hitPosition, @Nullable Entity hitEntity) { - this(hitPosition, null, null, hitEntity); - } - - /** - * Creates a RayTraceResult. - * - * @param hitPosition the hit position - * @param hitEntity the hit entity - * @param hitBlockFace the hit block face - */ - public RayTraceResult(@NotNull Vector hitPosition, @Nullable Entity hitEntity, @Nullable BlockFace hitBlockFace) { - this(hitPosition, null, hitBlockFace, hitEntity); - } - - /** - * Gets the exact position of the hit. - * - * @return a copy of the exact hit position - */ - @NotNull - public Vector getHitPosition() { - return hitPosition.clone(); - } - - /** - * Gets the hit block. - * - * @return the hit block, or null if not available - */ - @Nullable - public Block getHitBlock() { - return hitBlock; - } - - /** - * Gets the hit block face. - * - * @return the hit block face, or null if not available - */ - @Nullable - public BlockFace getHitBlockFace() { - return hitBlockFace; - } - - /** - * Gets the hit entity. - * - * @return the hit entity, or null if not available - */ - @Nullable - public Entity getHitEntity() { - return hitEntity; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + hitPosition.hashCode(); - result = prime * result + ((hitBlock == null) ? 0 : hitBlock.hashCode()); - result = prime * result + ((hitBlockFace == null) ? 0 : hitBlockFace.hashCode()); - result = prime * result + ((hitEntity == null) ? 0 : hitEntity.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (!(obj instanceof RayTraceResult)) return false; - RayTraceResult other = (RayTraceResult) obj; - if (!hitPosition.equals(other.hitPosition)) return false; - if (!Objects.equals(hitBlock, other.hitBlock)) return false; - if (!Objects.equals(hitBlockFace, other.hitBlockFace)) return false; - if (!Objects.equals(hitEntity, other.hitEntity)) return false; - return true; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("RayTraceResult [hitPosition="); - builder.append(hitPosition); - builder.append(", hitBlock="); - builder.append(hitBlock); - builder.append(", hitBlockFace="); - builder.append(hitBlockFace); - builder.append(", hitEntity="); - builder.append(hitEntity); - builder.append("]"); - return builder.toString(); - } -} diff --git a/api/src/main/java/org/bukkit/util/StringUtil.java b/api/src/main/java/org/bukkit/util/StringUtil.java deleted file mode 100644 index 458d5ebdf..000000000 --- a/api/src/main/java/org/bukkit/util/StringUtil.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bukkit.util; - -import java.util.Collection; -import org.apache.commons.lang.Validate; -import org.jetbrains.annotations.NotNull; - -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 - */ - @NotNull - public static > T copyPartialMatches(@NotNull final String token, @NotNull final Iterable originals, @NotNull 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(@NotNull final String string, @NotNull 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/api/src/main/java/org/bukkit/util/Vector.java b/api/src/main/java/org/bukkit/util/Vector.java deleted file mode 100644 index 143579bb3..000000000 --- a/api/src/main/java/org/bukkit/util/Vector.java +++ /dev/null @@ -1,880 +0,0 @@ -package org.bukkit.util; - -import com.google.common.base.Preconditions; -import com.google.common.primitives.Doubles; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Random; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.SerializableAs; -import org.jetbrains.annotations.NotNull; - -/** - * 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 - */ - @NotNull - public Vector add(@NotNull 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 - */ - @NotNull - public Vector subtract(@NotNull 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 - */ - @NotNull - public Vector multiply(@NotNull 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 - */ - @NotNull - public Vector divide(@NotNull 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 - */ - @NotNull - public Vector copy(@NotNull 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(@NotNull 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(@NotNull 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(@NotNull Vector other) { - double dot = Doubles.constrainToRange(dot(other) / (length() * other.length()), -1.0, 1.0); - - 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) - */ - @NotNull - public Vector midpoint(@NotNull 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 - */ - @NotNull - public Vector getMidpoint(@NotNull 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 - */ - @NotNull - 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 - */ - @NotNull - 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 - */ - @NotNull - 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(@NotNull 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 - */ - @NotNull - public Vector crossProduct(@NotNull 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; - } - - /** - * Calculates the cross product of this vector with another without mutating - * the original. 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 a new vector - */ - @NotNull - public Vector getCrossProduct(@NotNull Vector o) { - double x = this.y * o.z - o.y * this.z; - double y = this.z * o.x - o.z * this.x; - double z = this.x * o.y - o.x * this.y; - return new Vector(x, y, z); - } - - /** - * Converts this vector to a unit vector (a vector with length of 1). - * - * @return the same vector - */ - @NotNull - public Vector normalize() { - double length = length(); - - x /= length; - y /= length; - z /= length; - - return this; - } - - /** - * Zero this vector's components. - * - * @return the same vector - */ - @NotNull - 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(@NotNull Vector min, @NotNull 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(@NotNull Vector origin, double radius) { - return (NumberConversions.square(origin.x - x) + NumberConversions.square(origin.y - y) + NumberConversions.square(origin.z - z)) <= NumberConversions.square(radius); - } - - /** - * Returns if a vector is normalized - * - * @return whether the vector is normalised - */ - public boolean isNormalized() { - return Math.abs(this.lengthSquared() - 1) < getEpsilon(); - } - - /** - * Rotates the vector around the x axis. - *

- * This piece of math is based on the standard rotation matrix for vectors - * in three dimensional space. This matrix can be found here: - * Rotation - * Matrix. - * - * @param angle the angle to rotate the vector about. This angle is passed - * in radians - * @return the same vector - */ - @NotNull - public Vector rotateAroundX(double angle) { - double angleCos = Math.cos(angle); - double angleSin = Math.sin(angle); - - double y = angleCos * getY() - angleSin * getZ(); - double z = angleSin * getY() + angleCos * getZ(); - return setY(y).setZ(z); - } - - /** - * Rotates the vector around the y axis. - *

- * This piece of math is based on the standard rotation matrix for vectors - * in three dimensional space. This matrix can be found here: - * Rotation - * Matrix. - * - * @param angle the angle to rotate the vector about. This angle is passed - * in radians - * @return the same vector - */ - @NotNull - public Vector rotateAroundY(double angle) { - double angleCos = Math.cos(angle); - double angleSin = Math.sin(angle); - - double x = angleCos * getX() + angleSin * getZ(); - double z = -angleSin * getX() + angleCos * getZ(); - return setX(x).setZ(z); - } - - /** - * Rotates the vector around the z axis - *

- * This piece of math is based on the standard rotation matrix for vectors - * in three dimensional space. This matrix can be found here: - * Rotation - * Matrix. - * - * @param angle the angle to rotate the vector about. This angle is passed - * in radians - * @return the same vector - */ - @NotNull - public Vector rotateAroundZ(double angle) { - double angleCos = Math.cos(angle); - double angleSin = Math.sin(angle); - - double x = angleCos * getX() - angleSin * getY(); - double y = angleSin * getX() + angleCos * getY(); - return setX(x).setY(y); - } - - /** - * Rotates the vector around a given arbitrary axis in 3 dimensional space. - * - *

- * Rotation will follow the general Right-Hand-Rule, which means rotation - * will be counterclockwise when the axis is pointing towards the observer. - *

- * This method will always make sure the provided axis is a unit vector, to - * not modify the length of the vector when rotating. If you are experienced - * with the scaling of a non-unit axis vector, you can use - * {@link Vector#rotateAroundNonUnitAxis(Vector, double)}. - * - * @param axis the axis to rotate the vector around. If the passed vector is - * not of length 1, it gets copied and normalized before using it for the - * rotation. Please use {@link Vector#normalize()} on the instance before - * passing it to this method - * @param angle the angle to rotate the vector around the axis - * @return the same vector - * @throws IllegalArgumentException if the provided axis vector instance is - * null - */ - @NotNull - public Vector rotateAroundAxis(@NotNull Vector axis, double angle) throws IllegalArgumentException { - Preconditions.checkArgument(axis != null, "The provided axis vector was null"); - - return rotateAroundNonUnitAxis(axis.isNormalized() ? axis : axis.clone().normalize(), angle); - } - - /** - * Rotates the vector around a given arbitrary axis in 3 dimensional space. - * - *

- * Rotation will follow the general Right-Hand-Rule, which means rotation - * will be counterclockwise when the axis is pointing towards the observer. - *

- * Note that the vector length will change accordingly to the axis vector - * length. If the provided axis is not a unit vector, the rotated vector - * will not have its previous length. The scaled length of the resulting - * vector will be related to the axis vector. If you are not perfectly sure - * about the scaling of the vector, use - * {@link Vector#rotateAroundAxis(Vector, double)} - * - * @param axis the axis to rotate the vector around. - * @param angle the angle to rotate the vector around the axis - * @return the same vector - * @throws IllegalArgumentException if the provided axis vector instance is - * null - */ - @NotNull - public Vector rotateAroundNonUnitAxis(@NotNull Vector axis, double angle) throws IllegalArgumentException { - Preconditions.checkArgument(axis != null, "The provided axis vector was null"); - - double x = getX(), y = getY(), z = getZ(); - double x2 = axis.getX(), y2 = axis.getY(), z2 = axis.getZ(); - - double cosTheta = Math.cos(angle); - double sinTheta = Math.sin(angle); - double dotProduct = this.dot(axis); - - double xPrime = x2 * dotProduct * (1d - cosTheta) - + x * cosTheta - + (-z2 * y + y2 * z) * sinTheta; - double yPrime = y2 * dotProduct * (1d - cosTheta) - + y * cosTheta - + (z2 * x - x2 * z) * sinTheta; - double zPrime = z2 * dotProduct * (1d - cosTheta) - + z * cosTheta - + (-y2 * x + x2 * y) * sinTheta; - - return setX(xPrime).setY(yPrime).setZ(zPrime); - } - - /** - * 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. - */ - @NotNull - public Vector setX(int x) { - this.x = x; - return this; - } - - /** - * Set the X component. - * - * @param x The new X component. - * @return This vector. - */ - @NotNull - public Vector setX(double x) { - this.x = x; - return this; - } - - /** - * Set the X component. - * - * @param x The new X component. - * @return This vector. - */ - @NotNull - public Vector setX(float x) { - this.x = x; - return this; - } - - /** - * Set the Y component. - * - * @param y The new Y component. - * @return This vector. - */ - @NotNull - public Vector setY(int y) { - this.y = y; - return this; - } - - /** - * Set the Y component. - * - * @param y The new Y component. - * @return This vector. - */ - @NotNull - public Vector setY(double y) { - this.y = y; - return this; - } - - /** - * Set the Y component. - * - * @param y The new Y component. - * @return This vector. - */ - @NotNull - public Vector setY(float y) { - this.y = y; - return this; - } - - /** - * Set the Z component. - * - * @param z The new Z component. - * @return This vector. - */ - @NotNull - public Vector setZ(int z) { - this.z = z; - return this; - } - - /** - * Set the Z component. - * - * @param z The new Z component. - * @return This vector. - */ - @NotNull - public Vector setZ(double z) { - this.z = z; - return this; - } - - /** - * Set the Z component. - * - * @param z The new Z component. - * @return This vector. - */ - @NotNull - 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 - */ - @NotNull - @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 - */ - @NotNull - public Location toLocation(@NotNull 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 - */ - @NotNull - public Location toLocation(@NotNull 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. - */ - @NotNull - public BlockVector toBlockVector() { - return new BlockVector(x, y, z); - } - - /** - * Check if each component of this Vector is finite. - * - * @throws IllegalArgumentException if any component is not finite - */ - public void checkFinite() throws IllegalArgumentException { - NumberConversions.checkFinite(x, "x not finite"); - NumberConversions.checkFinite(y, "y not finite"); - NumberConversions.checkFinite(z, "z not finite"); - } - - /** - * 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 - */ - @NotNull - public static Vector getMinimum(@NotNull Vector v1, @NotNull 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 - */ - @NotNull - public static Vector getMaximum(@NotNull Vector v1, @NotNull 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. - */ - @NotNull - public static Vector getRandom() { - return new Vector(random.nextDouble(), random.nextDouble(), random.nextDouble()); - } - - @Override - @NotNull - public Map serialize() { - Map result = new LinkedHashMap(); - - result.put("x", getX()); - result.put("y", getY()); - result.put("z", getZ()); - - return result; - } - - @NotNull - public static Vector deserialize(@NotNull 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/api/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java b/api/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java deleted file mode 100644 index d05aaaa46..000000000 --- a/api/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.util.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.ConfigurationSerialization; - -/** - * 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/api/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java b/api/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java deleted file mode 100644 index 0b073f26d..000000000 --- a/api/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.util.io; - -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; -import org.bukkit.configuration.serialization.ConfigurationSerializable; - -/** - * 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/api/src/main/java/org/bukkit/util/io/Wrapper.java b/api/src/main/java/org/bukkit/util/io/Wrapper.java deleted file mode 100644 index c3496dc8b..000000000 --- a/api/src/main/java/org/bukkit/util/io/Wrapper.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.util.io; - -import com.google.common.collect.ImmutableMap; -import java.io.Serializable; -import java.util.Map; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.ConfigurationSerialization; -import org.jetbrains.annotations.NotNull; - -final class Wrapper & Serializable> implements Serializable { - private static final long serialVersionUID = -986209235411767547L; - - final T map; - - static Wrapper> newWrapper(@NotNull ConfigurationSerializable obj) { - return new Wrapper>(ImmutableMap.builder().put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(obj.getClass())).putAll(obj.serialize()).build()); - } - - private Wrapper(@NotNull T map) { - this.map = map; - } -} diff --git a/api/src/main/java/org/bukkit/util/noise/NoiseGenerator.java b/api/src/main/java/org/bukkit/util/noise/NoiseGenerator.java deleted file mode 100644 index aa2d70414..000000000 --- a/api/src/main/java/org/bukkit/util/noise/NoiseGenerator.java +++ /dev/null @@ -1,176 +0,0 @@ -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/api/src/main/java/org/bukkit/util/noise/OctaveGenerator.java b/api/src/main/java/org/bukkit/util/noise/OctaveGenerator.java deleted file mode 100644 index 618ed706e..000000000 --- a/api/src/main/java/org/bukkit/util/noise/OctaveGenerator.java +++ /dev/null @@ -1,203 +0,0 @@ -package org.bukkit.util.noise; - -import org.jetbrains.annotations.NotNull; - -/** - * Creates noise using unbiased octaves - */ -public abstract class OctaveGenerator { - @NotNull - protected final NoiseGenerator[] octaves; - protected double xScale = 1; - protected double yScale = 1; - protected double zScale = 1; - - protected OctaveGenerator(@NotNull 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 - */ - @NotNull - 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/api/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java b/api/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java deleted file mode 100644 index 520b65f9e..000000000 --- a/api/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java +++ /dev/null @@ -1,219 +0,0 @@ -package org.bukkit.util.noise; - -import java.util.Random; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; - -/** - * Generates noise using the "classic" perlin generator - * - * @see SimplexNoiseGenerator "Improved" and faster version with slightly - * 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(@NotNull 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(@NotNull 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 - */ - @NotNull - 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/api/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java b/api/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java deleted file mode 100644 index af7e01188..000000000 --- a/api/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.util.noise; - -import java.util.Random; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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(@NotNull Random rand, int octaves) { - super(createOctaves(rand, octaves)); - } - - @NotNull - private static NoiseGenerator[] createOctaves(@NotNull 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/api/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java b/api/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java deleted file mode 100644 index afe8fa954..000000000 --- a/api/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java +++ /dev/null @@ -1,522 +0,0 @@ -package org.bukkit.util.noise; - -import java.util.Random; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; - -/** - * 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 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(@NotNull 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(@NotNull Random rand) { - super(rand); - offsetW = rand.nextDouble() * 256; - } - - protected static double dot(@NotNull int[] g, double x, double y) { - return g[0] * x + g[1] * y; - } - - protected static double dot(@NotNull int[] g, double x, double y, double z) { - return g[0] * x + g[1] * y + g[2] * z; - } - - protected static double dot(@NotNull 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 - */ - @NotNull - public static SimplexNoiseGenerator getInstance() { - return instance; - } -} diff --git a/api/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java b/api/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java deleted file mode 100644 index 6cc15431e..000000000 --- a/api/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.bukkit.util.noise; - -import java.util.Random; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull 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(@NotNull 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; - } - - @NotNull - private static NoiseGenerator[] createOctaves(@NotNull 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/api/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java b/api/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java deleted file mode 100644 index 54bc41370..000000000 --- a/api/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.util.permissions; - -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; -import org.jetbrains.annotations.NotNull; - -public final class BroadcastPermissions { - private static final String ROOT = "bukkit.broadcast"; - private static final String PREFIX = ROOT + "."; - - private BroadcastPermissions() {} - - @NotNull - public static Permission registerPermissions(@NotNull 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/api/src/main/java/org/bukkit/util/permissions/CommandPermissions.java b/api/src/main/java/org/bukkit/util/permissions/CommandPermissions.java deleted file mode 100644 index 7763d6101..000000000 --- a/api/src/main/java/org/bukkit/util/permissions/CommandPermissions.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.util.permissions; - -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; -import org.jetbrains.annotations.NotNull; - -public final class CommandPermissions { - private static final String ROOT = "bukkit.command"; - private static final String PREFIX = ROOT + "."; - - private CommandPermissions() {} - - @NotNull - public static Permission registerPermissions(@NotNull 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/api/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java b/api/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java deleted file mode 100644 index e1a4ddf2c..000000000 --- a/api/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.bukkit.util.permissions; - -import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public final class DefaultPermissions { - private static final String ROOT = "craftbukkit"; - private static final String LEGACY_PREFIX = "craft"; - - private DefaultPermissions() {} - - @NotNull - public static Permission registerPermission(@NotNull Permission perm) { - return registerPermission(perm, true); - } - - @NotNull - public static Permission registerPermission(@NotNull Permission perm, boolean withLegacy) { - Permission result = perm; - - try { - Bukkit.getPluginManager().addPermission(perm); - } catch (IllegalArgumentException ex) { - result = Bukkit.getPluginManager().getPermission(perm.getName()); - assert result != null; - } - - 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; - } - - @NotNull - public static Permission registerPermission(@NotNull Permission perm, @NotNull Permission parent) { - parent.getChildren().put(perm.getName(), true); - return registerPermission(perm); - } - - @NotNull - public static Permission registerPermission(@NotNull String name, @Nullable String desc) { - Permission perm = registerPermission(new Permission(name, desc)); - return perm; - } - - @NotNull - public static Permission registerPermission(@NotNull String name, @Nullable String desc, @NotNull Permission parent) { - Permission perm = registerPermission(name, desc); - parent.getChildren().put(perm.getName(), true); - return perm; - } - - @NotNull - public static Permission registerPermission(@NotNull String name, @Nullable String desc, @Nullable PermissionDefault def) { - Permission perm = registerPermission(new Permission(name, desc, def)); - return perm; - } - - @NotNull - public static Permission registerPermission(@NotNull String name, @Nullable String desc, @Nullable PermissionDefault def, @NotNull Permission parent) { - Permission perm = registerPermission(name, desc, def); - parent.getChildren().put(perm.getName(), true); - return perm; - } - - @NotNull - public static Permission registerPermission(@NotNull String name, @Nullable String desc, @Nullable PermissionDefault def, @Nullable Map children) { - Permission perm = registerPermission(new Permission(name, desc, def, children)); - return perm; - } - - @NotNull - public static Permission registerPermission(@NotNull String name, @Nullable String desc, @Nullable PermissionDefault def, @Nullable Map children, @NotNull 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/api/src/main/java/org/spigotmc/CustomTimingsHandler.java b/api/src/main/java/org/spigotmc/CustomTimingsHandler.java deleted file mode 100644 index 3cbe5c2bb..000000000 --- a/api/src/main/java/org/spigotmc/CustomTimingsHandler.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * This file is licensed under the MIT License (MIT). - * - * Copyright (c) 2014 Daniel Ennis - * - * 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.spigotmc; - -import java.io.PrintStream; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.bukkit.plugin.AuthorNagException; -import org.bukkit.plugin.Plugin; -import co.aikar.timings.Timing; -import co.aikar.timings.Timings; -import co.aikar.timings.TimingsManager; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.logging.Level; - -/** - * 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 - * @see co.aikar.timings.Timings#of - */ -@Deprecated -public final class CustomTimingsHandler { - private final Timing handler; - private static Boolean sunReflectAvailable; - private static Method getCallerClass; - - public CustomTimingsHandler(@NotNull String name) { - if (sunReflectAvailable == null) { - String javaVer = System.getProperty("java.version"); - String[] elements = javaVer.split("\\."); - - int major = Integer.parseInt(elements.length >= 2 ? elements[1] : javaVer); - if (major <= 8) { - sunReflectAvailable = true; - - try { - Class reflection = Class.forName("sun.reflect.Reflection"); - getCallerClass = reflection.getMethod("getCallerClass", int.class); - } catch (ClassNotFoundException | NoSuchMethodException ignored) { - } - } else { - sunReflectAvailable = false; - } - } - - Class calling = null; - if (sunReflectAvailable) { - try { - calling = (Class) getCallerClass.invoke(null, 2); - } catch (IllegalAccessException | InvocationTargetException ignored) { - } - } - - Timing timing; - - Plugin plugin = null; - try { - plugin = TimingsManager.getPluginByClassloader(calling); - } catch (Exception ignored) {} - - new AuthorNagException("Deprecated use of CustomTimingsHandler. Please Switch to Timings.of ASAP").printStackTrace(); - if (plugin != null) { - timing = Timings.of(plugin, "(Deprecated API) " + name); - } else { - try { - final Method ofSafe = TimingsManager.class.getDeclaredMethod("getHandler", String.class, String.class, Timing.class); - ofSafe.setAccessible(true); - timing = (Timing) ofSafe.invoke(null,"Minecraft", "(Deprecated API) " + name, null); - } catch (Exception e) { - e.printStackTrace(); - Bukkit.getLogger().log(Level.SEVERE, "This handler could not be registered"); - timing = Timings.NULL_HANDLER; - } - } - handler = timing; - } - - public void startTiming() { handler.startTiming(); } - public void stopTiming() { handler.stopTiming(); } - -} diff --git a/api/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java b/api/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java deleted file mode 100644 index a5b4aed52..000000000 --- a/api/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java +++ /dev/null @@ -1,74 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * Called when an entity stops riding another entity. - * - */ -public class EntityDismountEvent extends EntityEvent implements Cancellable -{ - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - private final Entity dismounted; - private final boolean isCancellable; // Paper - - public EntityDismountEvent(@NotNull Entity what, @NotNull Entity dismounted) - { - // Paper start - this(what, dismounted, true); - } - - public EntityDismountEvent(@NotNull Entity what, @NotNull Entity dismounted, boolean isCancellable) - { - // Paper end - super( what ); - this.dismounted = dismounted; - this.isCancellable = isCancellable; // Paper - } - - @NotNull - public Entity getDismounted() - { - return dismounted; - } - - @Override - public boolean isCancelled() - { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) - { - // Paper start - if (cancel && !isCancellable) { - return; - } - this.cancelled = cancel; - } - - public boolean isCancellable() { - return isCancellable; - // Paper end - } - - @NotNull - @Override - public HandlerList getHandlers() - { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() - { - return handlers; - } -} diff --git a/api/src/main/java/org/spigotmc/event/entity/EntityMountEvent.java b/api/src/main/java/org/spigotmc/event/entity/EntityMountEvent.java deleted file mode 100644 index c608e65bd..000000000 --- a/api/src/main/java/org/spigotmc/event/entity/EntityMountEvent.java +++ /dev/null @@ -1,56 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull Entity what, @NotNull Entity mount) - { - super( what ); - this.mount = mount; - } - - @NotNull - public Entity getMount() - { - return mount; - } - - @Override - public boolean isCancelled() - { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) - { - this.cancelled = cancel; - } - - @NotNull - @Override - public HandlerList getHandlers() - { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() - { - return handlers; - } -} diff --git a/api/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java b/api/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java deleted file mode 100644 index 2515887c2..000000000 --- a/api/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -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; -import org.jetbrains.annotations.NotNull; - -/** - * 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(@NotNull final Player who, @NotNull 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 - */ - @NotNull - public Location getSpawnLocation() { - return spawnLocation; - } - - /** - * Sets player's spawn location. - * - * @param location the spawn location - */ - public void setSpawnLocation(@NotNull Location location) { - this.spawnLocation = location; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/main/javadoc/org/bukkit/block/package-info.java b/api/src/main/javadoc/org/bukkit/block/package-info.java deleted file mode 100644 index dc0f36a80..000000000 --- a/api/src/main/javadoc/org/bukkit/block/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Classes used to manipulate the voxels in a {@link org.bukkit.World world}, - * including special states. - */ -package org.bukkit.block; - diff --git a/api/src/main/javadoc/org/bukkit/command/defaults/package-info.java b/api/src/main/javadoc/org/bukkit/command/defaults/package-info.java deleted file mode 100644 index b67dfba0f..000000000 --- a/api/src/main/javadoc/org/bukkit/command/defaults/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Commands for emulating the Minecraft commands and other necessary ones for - * use by a Bukkit implementation. - */ -package org.bukkit.command.defaults; - diff --git a/api/src/main/javadoc/org/bukkit/command/package-info.java b/api/src/main/javadoc/org/bukkit/command/package-info.java deleted file mode 100644 index 6428f474a..000000000 --- a/api/src/main/javadoc/org/bukkit/command/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes relating to handling specialized non-chat player input. - */ -package org.bukkit.command; - diff --git a/api/src/main/javadoc/org/bukkit/configuration/file/package-info.java b/api/src/main/javadoc/org/bukkit/configuration/file/package-info.java deleted file mode 100644 index 4973ffc18..000000000 --- a/api/src/main/javadoc/org/bukkit/configuration/file/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Classes dedicated facilitating {@link - * org.bukkit.configuration.Configuration configurations} to be read and - * stored on the filesystem. - */ -package org.bukkit.configuration.file; - diff --git a/api/src/main/javadoc/org/bukkit/configuration/package-info.java b/api/src/main/javadoc/org/bukkit/configuration/package-info.java deleted file mode 100644 index 63a39650b..000000000 --- a/api/src/main/javadoc/org/bukkit/configuration/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes dedicated to handling a plugin's runtime configuration. - */ -package org.bukkit.configuration; - diff --git a/api/src/main/javadoc/org/bukkit/configuration/serialization/package-info.java b/api/src/main/javadoc/org/bukkit/configuration/serialization/package-info.java deleted file mode 100644 index 529de2e8c..000000000 --- a/api/src/main/javadoc/org/bukkit/configuration/serialization/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Classes dedicated to being able to perform serialization specialized for - * the Bukkit {@link org.bukkit.configuration.Configuration configuration} - * implementation. - */ -package org.bukkit.configuration.serialization; - diff --git a/api/src/main/javadoc/org/bukkit/conversations/package-info.java b/api/src/main/javadoc/org/bukkit/conversations/package-info.java deleted file mode 100644 index d49dafaf0..000000000 --- a/api/src/main/javadoc/org/bukkit/conversations/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes dedicated to facilitate direct player-to-plugin communication. - */ -package org.bukkit.conversations; - diff --git a/api/src/main/javadoc/org/bukkit/enchantments/package-info.java b/api/src/main/javadoc/org/bukkit/enchantments/package-info.java deleted file mode 100644 index fb67cc7e6..000000000 --- a/api/src/main/javadoc/org/bukkit/enchantments/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Classes relating to the specialized enhancements to {@link - * org.bukkit.inventory.ItemStack item stacks}, as part of the {@link - * org.bukkit.inventory.meta.ItemMeta meta data}. - */ -package org.bukkit.enchantments; - diff --git a/api/src/main/javadoc/org/bukkit/entity/minecart/package-info.java b/api/src/main/javadoc/org/bukkit/entity/minecart/package-info.java deleted file mode 100644 index 342f10bac..000000000 --- a/api/src/main/javadoc/org/bukkit/entity/minecart/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Interfaces for various {@link org.bukkit.entity.Minecart} types. - */ -package org.bukkit.entity.minecart; - diff --git a/api/src/main/javadoc/org/bukkit/entity/package-info.java b/api/src/main/javadoc/org/bukkit/entity/package-info.java deleted file mode 100644 index 167a830d3..000000000 --- a/api/src/main/javadoc/org/bukkit/entity/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Interfaces for non-voxel objects that can exist in a {@link - * org.bukkit.World world}, including all players, monsters, projectiles, etc. - */ -package org.bukkit.entity; - diff --git a/api/src/main/javadoc/org/bukkit/event/block/package-info.java b/api/src/main/javadoc/org/bukkit/event/block/package-info.java deleted file mode 100644 index 30aec2185..000000000 --- a/api/src/main/javadoc/org/bukkit/event/block/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} relating to when a {@link - * org.bukkit.block.Block block} is changed or interacts with the {@link - * org.bukkit.World world}. - */ -package org.bukkit.event.block; - diff --git a/api/src/main/javadoc/org/bukkit/event/enchantment/package-info.java b/api/src/main/javadoc/org/bukkit/event/enchantment/package-info.java deleted file mode 100644 index e609c6348..000000000 --- a/api/src/main/javadoc/org/bukkit/event/enchantment/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} triggered from an {@link - * org.bukkit.inventory.EnchantingInventory enchantment table}. - */ -package org.bukkit.event.enchantment; - diff --git a/api/src/main/javadoc/org/bukkit/event/entity/package-info.java b/api/src/main/javadoc/org/bukkit/event/entity/package-info.java deleted file mode 100644 index cddcd4e46..000000000 --- a/api/src/main/javadoc/org/bukkit/event/entity/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} relating to {@link - * org.bukkit.entity.Entity entities}, excluding some directly referencing - * some more specific entity types. - */ -package org.bukkit.event.entity; - diff --git a/api/src/main/javadoc/org/bukkit/event/hanging/package-info.java b/api/src/main/javadoc/org/bukkit/event/hanging/package-info.java deleted file mode 100644 index bf16382bc..000000000 --- a/api/src/main/javadoc/org/bukkit/event/hanging/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} relating to {@link - * org.bukkit.entity.Hanging entities that hang}. - */ -package org.bukkit.event.hanging; - diff --git a/api/src/main/javadoc/org/bukkit/event/inventory/package-info.java b/api/src/main/javadoc/org/bukkit/event/inventory/package-info.java deleted file mode 100644 index 7dd5b699e..000000000 --- a/api/src/main/javadoc/org/bukkit/event/inventory/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} relating to {@link - * org.bukkit.inventory.Inventory inventory} manipulation. - */ -package org.bukkit.event.inventory; - diff --git a/api/src/main/javadoc/org/bukkit/event/package-info.java b/api/src/main/javadoc/org/bukkit/event/package-info.java deleted file mode 100644 index dd8baa1dc..000000000 --- a/api/src/main/javadoc/org/bukkit/event/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes dedicated to handling triggered code executions. - */ -package org.bukkit.event; - diff --git a/api/src/main/javadoc/org/bukkit/event/player/package-info.java b/api/src/main/javadoc/org/bukkit/event/player/package-info.java deleted file mode 100644 index fb645f32a..000000000 --- a/api/src/main/javadoc/org/bukkit/event/player/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} relating to {@link - * org.bukkit.entity.Player players}. - */ -package org.bukkit.event.player; - diff --git a/api/src/main/javadoc/org/bukkit/event/server/package-info.java b/api/src/main/javadoc/org/bukkit/event/server/package-info.java deleted file mode 100644 index b548270ca..000000000 --- a/api/src/main/javadoc/org/bukkit/event/server/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} relating to programmatic state - * changes on the server. - */ -package org.bukkit.event.server; - diff --git a/api/src/main/javadoc/org/bukkit/event/vehicle/package-info.java b/api/src/main/javadoc/org/bukkit/event/vehicle/package-info.java deleted file mode 100644 index b88cbcd6b..000000000 --- a/api/src/main/javadoc/org/bukkit/event/vehicle/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} relating to {@link - * org.bukkit.entity.Vehicle vehicular entities}. - */ -package org.bukkit.event.vehicle; - diff --git a/api/src/main/javadoc/org/bukkit/event/weather/package-info.java b/api/src/main/javadoc/org/bukkit/event/weather/package-info.java deleted file mode 100644 index edaaf9f19..000000000 --- a/api/src/main/javadoc/org/bukkit/event/weather/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} relating to weather. - */ -package org.bukkit.event.weather; - diff --git a/api/src/main/javadoc/org/bukkit/event/world/package-info.java b/api/src/main/javadoc/org/bukkit/event/world/package-info.java deleted file mode 100644 index 4cbb818a3..000000000 --- a/api/src/main/javadoc/org/bukkit/event/world/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * {@link org.bukkit.event.Event Events} triggered by various {@link - * org.bukkit.World world} states or changes. - */ -package org.bukkit.event.world; - diff --git a/api/src/main/javadoc/org/bukkit/generator/package-info.java b/api/src/main/javadoc/org/bukkit/generator/package-info.java deleted file mode 100644 index 2532addf5..000000000 --- a/api/src/main/javadoc/org/bukkit/generator/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Classes to facilitate {@link org.bukkit.World world} generation - * implementation. - */ -package org.bukkit.generator; - diff --git a/api/src/main/javadoc/org/bukkit/help/package-info.java b/api/src/main/javadoc/org/bukkit/help/package-info.java deleted file mode 100644 index 66a4aacbe..000000000 --- a/api/src/main/javadoc/org/bukkit/help/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes used to manipulate the default command and topic assistance system. - */ -package org.bukkit.help; - diff --git a/api/src/main/javadoc/org/bukkit/inventory/meta/package-info.java b/api/src/main/javadoc/org/bukkit/inventory/meta/package-info.java deleted file mode 100644 index b80eb88b6..000000000 --- a/api/src/main/javadoc/org/bukkit/inventory/meta/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * The interfaces used when manipulating extra data can can be stored inside - * {@link org.bukkit.inventory.ItemStack item stacks}. - */ -package org.bukkit.inventory.meta; - diff --git a/api/src/main/javadoc/org/bukkit/inventory/package-info.java b/api/src/main/javadoc/org/bukkit/inventory/package-info.java deleted file mode 100644 index 8881abcc0..000000000 --- a/api/src/main/javadoc/org/bukkit/inventory/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes involved in manipulating player inventories and item interactions. - */ -package org.bukkit.inventory; - diff --git a/api/src/main/javadoc/org/bukkit/map/package-info.java b/api/src/main/javadoc/org/bukkit/map/package-info.java deleted file mode 100644 index 30de8b24c..000000000 --- a/api/src/main/javadoc/org/bukkit/map/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Classes to facilitate plugin handling of {@link org.bukkit.Material#MAP - * map} displays. - */ -package org.bukkit.map; - diff --git a/api/src/main/javadoc/org/bukkit/material/package-info.java b/api/src/main/javadoc/org/bukkit/material/package-info.java deleted file mode 100644 index f3be435e5..000000000 --- a/api/src/main/javadoc/org/bukkit/material/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes that represents various voxel types and states. - */ -package org.bukkit.material; - diff --git a/api/src/main/javadoc/org/bukkit/metadata/package-info.java b/api/src/main/javadoc/org/bukkit/metadata/package-info.java deleted file mode 100644 index f8e00397a..000000000 --- a/api/src/main/javadoc/org/bukkit/metadata/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Classes dedicated to providing a layer of plugin specified data on various - * Minecraft concepts. - */ -package org.bukkit.metadata; - diff --git a/api/src/main/javadoc/org/bukkit/package-info.java b/api/src/main/javadoc/org/bukkit/package-info.java deleted file mode 100644 index da7d9f12c..000000000 --- a/api/src/main/javadoc/org/bukkit/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * More generalized classes in the API. - */ -package org.bukkit; - diff --git a/api/src/main/javadoc/org/bukkit/permissions/package-info.java b/api/src/main/javadoc/org/bukkit/permissions/package-info.java deleted file mode 100644 index 860abc3f3..000000000 --- a/api/src/main/javadoc/org/bukkit/permissions/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes dedicated to providing binary state properties to players. - */ -package org.bukkit.permissions; - diff --git a/api/src/main/javadoc/org/bukkit/plugin/doc-files/permissions-example_plugin.yml b/api/src/main/javadoc/org/bukkit/plugin/doc-files/permissions-example_plugin.yml deleted file mode 100644 index 34d0381a6..000000000 --- a/api/src/main/javadoc/org/bukkit/plugin/doc-files/permissions-example_plugin.yml +++ /dev/null @@ -1,64 +0,0 @@ -name: ScrapBukkit -main: com.dinnerbone.bukkit.scrap.ScrapBukkit -version: 1.0.0 -website: http://www.bukkit.org -author: The Bukkit Team -description: > - Miscellaneous administrative commands for Bukkit. - This plugin is one of the default plugins shipped with Bukkit. -# commands: snipped - -permissions: - scrapbukkit.*: - description: Gives all permissions for Scrapbukkit - default: op - children: - scrapbukkit.remove: - description: Allows the player to remove items from anyones inventory - children: - scrapbukkit.remove.self: - description: Allows the player to remove items from their own inventory - scrapbukkit.remove.other: - description: Allows the player to remove items from other peoples inventory - - scrapbukkit.time: - description: Allows the player to view and change the time - children: - scrapbukkit.time.view: - description: Allows the player to view the time - default: true - scrapbukkit.time.change: - description: Allows the player to change the time - - scrapbukkit.tp: - description: Allows the player to teleport anyone to anyone else - children: - scrapbukkit.tp.here: - description: Allows the player to teleport other players to themselves - scrapbukkit.tp.self: - description: Allows the player to teleport themselves to another player - scrapbukkit.tp.other: - description: Allows the player to teleport anyone to another player - - scrapbukkit.give: - description: Allows the player to give items - children: - scrapbukkit.give.self: - description: Allows the player to give themselves items - scrapbukkit.give.other: - description: Allows the player to give other players items - - scrapbukkit.clear: - description: Allows the player to clear inventories - children: - scrapbukkit.clear.self: - description: Allows the player to clear their own inventory - scrapbukkit.clear.other: - description: Allows the player to clear other players inventory - - scrapbukkit.some.standard.perm: {} - scrapbukkit.some.other.perm: true - scrapbukkit.some.bad.perm: false - # This is defined here individually, as simply giving it an association will not cause it to exist at runtime - scrapbukkit.some.bad.perm: {} - scrapbukkit.some.other.perm: {} diff --git a/api/src/main/javadoc/org/bukkit/plugin/java/package-info.java b/api/src/main/javadoc/org/bukkit/plugin/java/package-info.java deleted file mode 100644 index c74e70935..000000000 --- a/api/src/main/javadoc/org/bukkit/plugin/java/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Classes for handling {@link org.bukkit.plugin.Plugin plugins} written in - * java. - */ -package org.bukkit.plugin.java; - diff --git a/api/src/main/javadoc/org/bukkit/plugin/messaging/package-info.java b/api/src/main/javadoc/org/bukkit/plugin/messaging/package-info.java deleted file mode 100644 index 04cb2b93c..000000000 --- a/api/src/main/javadoc/org/bukkit/plugin/messaging/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes dedicated to specialized plugin to client protocols. - */ -package org.bukkit.plugin.messaging; - diff --git a/api/src/main/javadoc/org/bukkit/plugin/package-info.java b/api/src/main/javadoc/org/bukkit/plugin/package-info.java deleted file mode 100644 index 76fbe6ba1..000000000 --- a/api/src/main/javadoc/org/bukkit/plugin/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes specifically relating to loading software modules at runtime. - */ -package org.bukkit.plugin; - diff --git a/api/src/main/javadoc/org/bukkit/potion/package-info.java b/api/src/main/javadoc/org/bukkit/potion/package-info.java deleted file mode 100644 index 6dd345449..000000000 --- a/api/src/main/javadoc/org/bukkit/potion/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Classes to represent various {@link org.bukkit.Material#POTION potion} - * properties and manipulation. - */ -package org.bukkit.potion; - diff --git a/api/src/main/javadoc/org/bukkit/projectiles/package-info.java b/api/src/main/javadoc/org/bukkit/projectiles/package-info.java deleted file mode 100644 index 5efe7364a..000000000 --- a/api/src/main/javadoc/org/bukkit/projectiles/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes to represent the source of a projectile - */ -package org.bukkit.projectiles; - diff --git a/api/src/main/javadoc/org/bukkit/scheduler/package-info.java b/api/src/main/javadoc/org/bukkit/scheduler/package-info.java deleted file mode 100644 index c441df679..000000000 --- a/api/src/main/javadoc/org/bukkit/scheduler/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Classes dedicated to letting {@link org.bukkit.plugin.Plugin plugins} run - * code at specific time intervals, including thread safety. - */ -package org.bukkit.scheduler; - diff --git a/api/src/main/javadoc/org/bukkit/scoreboard/package-info.java b/api/src/main/javadoc/org/bukkit/scoreboard/package-info.java deleted file mode 100644 index 4d0b7e206..000000000 --- a/api/src/main/javadoc/org/bukkit/scoreboard/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Interfaces used to manage the client side score display system. - */ -package org.bukkit.scoreboard; - diff --git a/api/src/main/javadoc/org/bukkit/util/io/package-info.java b/api/src/main/javadoc/org/bukkit/util/io/package-info.java deleted file mode 100644 index c4efffbd0..000000000 --- a/api/src/main/javadoc/org/bukkit/util/io/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes used to facilitate stream processing for specific Bukkit concepts. - */ -package org.bukkit.util.io; - diff --git a/api/src/main/javadoc/org/bukkit/util/noise/package-info.java b/api/src/main/javadoc/org/bukkit/util/noise/package-info.java deleted file mode 100644 index 8dd1501c5..000000000 --- a/api/src/main/javadoc/org/bukkit/util/noise/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Classes dedicated to facilitating deterministic noise. - */ -package org.bukkit.util.noise; - diff --git a/api/src/main/javadoc/org/bukkit/util/package-info.java b/api/src/main/javadoc/org/bukkit/util/package-info.java deleted file mode 100644 index 58176d08b..000000000 --- a/api/src/main/javadoc/org/bukkit/util/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Multi and single purpose classes to facilitate various programmatic - * concepts. - */ -package org.bukkit.util; - diff --git a/api/src/main/javadoc/org/bukkit/util/permissions/package-info.java b/api/src/main/javadoc/org/bukkit/util/permissions/package-info.java deleted file mode 100644 index 07498118d..000000000 --- a/api/src/main/javadoc/org/bukkit/util/permissions/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Static methods for miscellaneous {@link org.bukkit.permissions.Permission - * permission} functionality. - */ -package org.bukkit.util.permissions; - diff --git a/api/src/main/javadoc/overview.html b/api/src/main/javadoc/overview.html deleted file mode 100644 index e96bf35eb..000000000 --- a/api/src/main/javadoc/overview.html +++ /dev/null @@ -1,17 +0,0 @@ - -

Bukkit, the plugin development framework.

- -

- The documentation is for developing plugins and is split into the - respective packages for each subject matter. This documentation does not - cover running a server, contributing code back to the project, or setting - up a workspace. Working knowledge of the Java language is a prerequisite - for developing plugins. -

- For basic plugin development, see the {@link org.bukkit.plugin plugin - package}. It covers the basic requirements of a plugin jar. -

- For handling events and triggered code, see the {@link org.bukkit.event - event package}. -

- diff --git a/api/src/test/java/com/destroystokyo/paper/MaterialTagsTest.java b/api/src/test/java/com/destroystokyo/paper/MaterialTagsTest.java deleted file mode 100644 index 328c51471..000000000 --- a/api/src/test/java/com/destroystokyo/paper/MaterialTagsTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2018 Daniel Ennis (Aikar) MIT License - */ - -package com.destroystokyo.paper; - -import org.bukkit.Bukkit; -import org.bukkit.TestServer; -import org.junit.Test; - -import java.util.logging.Level; - -public class MaterialTagsTest { - @Test - public void testInitialize() { - try { - TestServer.getInstance(); - MaterialTags.SHULKER_BOXES.getValues(); - assert true; - } catch (Throwable e) { - Bukkit.getLogger().log(Level.SEVERE, e.getMessage(), e); - assert false; - } - } -} diff --git a/api/src/test/java/org/bukkit/AnnotationTest.java b/api/src/test/java/org/bukkit/AnnotationTest.java deleted file mode 100644 index cdc0afc0c..000000000 --- a/api/src/test/java/org/bukkit/AnnotationTest.java +++ /dev/null @@ -1,257 +0,0 @@ -package org.bukkit; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.junit.Assert; -import org.junit.Test; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; -import org.objectweb.asm.tree.ParameterNode; - -public class AnnotationTest { - - private static final String[] ACCEPTED_ANNOTATIONS = { - "Lorg/jetbrains/annotations/Nullable;", - "Lorg/jetbrains/annotations/NotNull;", - "Lorg/jetbrains/annotations/Contract;", - "Lorg/bukkit/UndefinedNullability;" - }; - - private static final String[] EXCLUDED_CLASSES = { - // Internal technical classes - "org/bukkit/plugin/java/JavaPluginLoader", - "org/bukkit/util/io/BukkitObjectInputStream", - "org/bukkit/util/io/BukkitObjectOutputStream", - "org/bukkit/util/io/Wrapper", - "org/bukkit/plugin/java/PluginClassLoader", - // Generic functional interface - "org/bukkit/util/Consumer", - // Paper start - // Timings history is broken in terms of nullability due to guavas Function defining that the param is NonNull - "co/aikar/timings/TimingHistory$2", - "co/aikar/timings/TimingHistory$2$1", - "co/aikar/timings/TimingHistory$2$1$1", - "co/aikar/timings/TimingHistory$2$1$2", - "co/aikar/timings/TimingHistory$3", - "co/aikar/timings/TimingHistory$4", - "co/aikar/timings/TimingHistoryEntry$1" - // Paper end - }; - - @Test - public void testAll() throws IOException, URISyntaxException { - URL loc = Bukkit.class.getProtectionDomain().getCodeSource().getLocation(); - File file = new File(loc.toURI()); - - // Running from jar is not supported yet - Assert.assertTrue("code must be in a directory", file.isDirectory()); - - final HashMap foundClasses = new HashMap<>(); - collectClasses(file, foundClasses); - - final ArrayList errors = new ArrayList<>(); - - for (ClassNode clazz : foundClasses.values()) { - if (!isClassIncluded(clazz, foundClasses)) { - continue; - } - - for (MethodNode method : clazz.methods) { - if (!isMethodIncluded(clazz, method, foundClasses)) { - continue; - } - - if (mustBeAnnotated(Type.getReturnType(method.desc)) && !isWellAnnotated(method.invisibleAnnotations)) { - warn(errors, clazz, method, "return value"); - } - - Type[] paramTypes = Type.getArgumentTypes(method.desc); - List parameters = method.parameters; - - for (int i = 0; i < paramTypes.length; i++) { - if (mustBeAnnotated(paramTypes[i]) && !isWellAnnotated(method.invisibleParameterAnnotations == null ? null : method.invisibleParameterAnnotations[i])) { - ParameterNode paramNode = parameters == null ? null : parameters.get(i); - String paramName = paramNode == null ? null : paramNode.name; - - warn(errors, clazz, method, "parameter " + i + (paramName == null ? "" : ": " + paramName)); - } - } - } - } - - if (errors.isEmpty()) { - // Success - return; - } - - Collections.sort(errors); - - System.out.println(errors.size() + " missing annotation(s):"); - for (String message : errors) { - System.out.print("\t"); - System.out.println(message); - } - - Assert.fail("There " + errors.size() + " are missing annotation(s)"); - } - - private static void collectClasses(@NotNull File from, @NotNull Map to) throws IOException { - if (from.isDirectory()) { - final File[] files = from.listFiles(); - assert files != null; - - for (File file : files) { - collectClasses(file, to); - } - return; - } - - if (!from.getName().endsWith(".class")) { - return; - } - - try (FileInputStream in = new FileInputStream(from)) { - final ClassReader cr = new ClassReader(in); - - final ClassNode node = new ClassNode(); - cr.accept(node, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); - - to.put(node.name, node); - } - } - - private static boolean isClassIncluded(@NotNull ClassNode clazz, @NotNull Map allClasses) { - // Exclude private, synthetic or deprecated classes and annotations, since their members can't be null - if ((clazz.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_DEPRECATED | Opcodes.ACC_ANNOTATION)) != 0) { - return false; - } - - if (isSubclassOf(clazz, "org/bukkit/material/MaterialData", allClasses)) { - // MaterialData is deprecated and all of its subclasses are excluded - return false; - } - - if (isSubclassOf(clazz, "java/lang/Exception", allClasses) - || isSubclassOf(clazz, "java/lang/RuntimeException", allClasses)) { - // Exceptions are excluded - return false; - } - - for (String excludedClass : EXCLUDED_CLASSES) { - if (excludedClass.equals(clazz.name)) { - return false; - } - } - - return true; - } - - private static boolean isMethodIncluded(@NotNull ClassNode clazz, @NotNull MethodNode method, @NotNull Map allClasses) { - // Exclude private, synthetic and deprecated methods - if ((method.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_DEPRECATED)) != 0 || (method.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED | Opcodes.ACC_PUBLIC)) == 0) { // Paper - ignore package-private - return false; - } - - // Exclude Java methods - if (is(method, "toString", 0) || is(method, "clone", 0) || is(method, "equals", 1)) { - return false; - } - - // Exclude generated Enum methods - if (isSubclassOf(clazz, "java/lang/Enum", allClasses) && (is(method, "values", 0) || is(method, "valueOf", 1))) { - return false; - } - - // Anonymous classes have generated constructors, which can't be annotated nor invoked - if ("".equals(method.name) && isAnonymous(clazz)) { - return false; - } - - return true; - } - - private static boolean isWellAnnotated(@Nullable List annotations) { - if (annotations == null) { - return false; - } - - for (AnnotationNode node : annotations) { - for (String acceptedAnnotation : ACCEPTED_ANNOTATIONS) { - if (acceptedAnnotation.equals(node.desc)) { - return true; - } - } - } - - return false; - } - - private static boolean mustBeAnnotated(@NotNull Type type) { - return type.getSort() == Type.ARRAY || type.getSort() == Type.OBJECT; - } - - private static boolean is(@NotNull MethodNode method, @NotNull String name, int parameters) { - final List params = method.parameters; - return method.name.equals(name) && (params == null || params.size() == parameters); - } - - /** - * @return true if given class is anonymous - */ - private static boolean isAnonymous(@NotNull ClassNode clazz) { - final String name = clazz.name; - if (name == null) { - return false; - } - final int nestedSeparator = name.lastIndexOf('$'); - if (nestedSeparator == -1 || nestedSeparator + 1 == name.length()) { - return false; - } - - // Nested classes have purely numeric names. Java classes can't begin with a number, - // so if first character is a number, the class must be anonymous - final char c = name.charAt(nestedSeparator + 1); - return c >= '0' && c <= '9'; - } - - private static boolean isSubclassOf(@NotNull ClassNode what, @NotNull String ofWhat, @NotNull Map allClasses) { - if (ofWhat.equals(what.name) - // Not only optimization: Super class may not be present in allClasses, so it is checked here - || ofWhat.equals(what.superName)) { - return true; - } - - final ClassNode parent = allClasses.get(what.superName); - if (parent != null && isSubclassOf(parent, ofWhat, allClasses)) { - return true; - } - - for (String superInterface : what.interfaces) { - final ClassNode interfaceParent = allClasses.get(superInterface); - if (interfaceParent != null && isSubclassOf(interfaceParent, ofWhat, allClasses)) { - return true; - } - } - - return false; - } - - private static void warn(@NotNull Collection out, @NotNull ClassNode clazz, @NotNull MethodNode method, @NotNull String description) { - out.add(clazz.name + " \t" + method.name + " \t" + description); - } -} diff --git a/api/src/test/java/org/bukkit/ArtTest.java b/api/src/test/java/org/bukkit/ArtTest.java deleted file mode 100644 index 29fe34ad4..000000000 --- a/api/src/test/java/org/bukkit/ArtTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class ArtTest { - - @Test(expected = IllegalArgumentException.class) - public void getByNullName() { - Art.getByName(null); - } - - @Test - public void getById() { - for (Art art : Art.values()) { - assertThat(Art.getById(art.getId()), is(art)); - } - } - - @Test - public void getByName() { - for (Art art : Art.values()) { - assertThat(Art.getByName(art.toString()), is(art)); - } - } - - @Test - public void dimensionSanityCheck() { - for (Art art : Art.values()) { - assertThat(art.getBlockHeight(), is(greaterThan(0))); - assertThat(art.getBlockWidth(), is(greaterThan(0))); - } - } - - @Test - public void getByNameWithMixedCase() { - Art subject = Art.values()[0]; - String name = subject.toString().replace('E', 'e'); - - assertThat(Art.getByName(name), is(subject)); - } -} diff --git a/api/src/test/java/org/bukkit/BukkitMirrorTest.java b/api/src/test/java/org/bukkit/BukkitMirrorTest.java deleted file mode 100644 index 9d7b9eb65..000000000 --- a/api/src/test/java/org/bukkit/BukkitMirrorTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Function; -import com.google.common.collect.Lists; - -@RunWith(Parameterized.class) -public class BukkitMirrorTest { - - @Parameters(name="{index}: {1}") - public static List data() { - return Lists.transform(Arrays.asList(Server.class.getDeclaredMethods()), new Function() { - @Override - public Object[] apply(Method input) { - return new Object[] { - input, - input.toGenericString().substring("public abstract ".length()).replace("(", "{").replace(")", "}") - }; - } - }); - } - - @Parameter(0) - public Method server; - - @Parameter(1) - public String name; - - private Method bukkit; - - @Before - public void makeBukkit() throws Throwable { - bukkit = Bukkit.class.getDeclaredMethod(server.getName(), server.getParameterTypes()); - } - - @Test - public void isStatic() throws Throwable { - assertThat(Modifier.isStatic(bukkit.getModifiers()), is(true)); - } - - @Test - public void isDeprecated() throws Throwable { - assertThat(bukkit.isAnnotationPresent(Deprecated.class), is(server.isAnnotationPresent(Deprecated.class))); - } - - @Test - public void returnType() throws Throwable { - assertThat(bukkit.getReturnType(), is((Object) server.getReturnType())); - // assertThat(bukkit.getGenericReturnType(), is(server.getGenericReturnType())); // too strict on type generics - } - - @Test - public void parameterTypes() throws Throwable { - // assertThat(bukkit.getGenericParameterTypes(), is(server.getGenericParameterTypes())); // too strict on type generics - } - - @Test - public void declaredException() throws Throwable { - assertThat(bukkit.getGenericExceptionTypes(), is(server.getGenericExceptionTypes())); - } -} diff --git a/api/src/test/java/org/bukkit/ChatColorTest.java b/api/src/test/java/org/bukkit/ChatColorTest.java deleted file mode 100644 index 80108a5d3..000000000 --- a/api/src/test/java/org/bukkit/ChatColorTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class ChatColorTest { - - @Test - public void getByChar() { - for (ChatColor color : ChatColor.values()) { - assertThat(ChatColor.getByChar(color.getChar()), is(color)); - } - } - - @Test(expected = IllegalArgumentException.class) - public void getByStringWithNull() { - ChatColor.getByChar((String) null); - } - - @Test(expected = IllegalArgumentException.class) - public void getByStringWithEmpty() { - ChatColor.getByChar(""); - } - - @Test - public void getByNull() { - assertThat(ChatColor.stripColor(null), is(nullValue())); - } - - @Test - public void getByString() { - for (ChatColor color : ChatColor.values()) { - assertThat(ChatColor.getByChar(String.valueOf(color.getChar())), is(color)); - } - } - - @Test - public void stripColorOnNullString() { - assertThat(ChatColor.stripColor(null), is(nullValue())); - } - - @Test - public void stripColor() { - StringBuilder subject = new StringBuilder(); - StringBuilder expected = new StringBuilder(); - - final String filler = "test"; - for (ChatColor color : ChatColor.values()) { - subject.append(color).append(filler); - expected.append(filler); - } - - assertThat(ChatColor.stripColor(subject.toString()), is(expected.toString())); - } - - @Test - public void toStringWorks() { - for (ChatColor color : ChatColor.values()) { - assertThat(String.format("%c%c", ChatColor.COLOR_CHAR, color.getChar()), is(color.toString())); - } - } - - @Test - public void translateAlternateColorCodes() { - String s = "&0&1&2&3&4&5&6&7&8&9&A&a&B&b&C&c&D&d&E&e&F&f&K&k & more"; - String t = ChatColor.translateAlternateColorCodes('&', s); - String u = ChatColor.BLACK.toString() + ChatColor.DARK_BLUE + ChatColor.DARK_GREEN + ChatColor.DARK_AQUA + ChatColor.DARK_RED + ChatColor.DARK_PURPLE + ChatColor.GOLD + ChatColor.GRAY + ChatColor.DARK_GRAY + ChatColor.BLUE + ChatColor.GREEN + ChatColor.GREEN + ChatColor.AQUA + ChatColor.AQUA + ChatColor.RED + ChatColor.RED + ChatColor.LIGHT_PURPLE + ChatColor.LIGHT_PURPLE + ChatColor.YELLOW + ChatColor.YELLOW + ChatColor.WHITE + ChatColor.WHITE + ChatColor.MAGIC + ChatColor.MAGIC + " & more"; - assertThat(t, is(u)); - } - - @Test - public void getChatColors() { - String s = String.format("%c%ctest%c%ctest%c", ChatColor.COLOR_CHAR, ChatColor.RED.getChar(), ChatColor.COLOR_CHAR, ChatColor.ITALIC.getChar(), ChatColor.COLOR_CHAR); - String expected = ChatColor.RED.toString() + ChatColor.ITALIC; - assertThat(ChatColor.getLastColors(s), is(expected)); - - s = String.format("%c%ctest%c%ctest", ChatColor.COLOR_CHAR, ChatColor.RED.getChar(), ChatColor.COLOR_CHAR, ChatColor.BLUE.getChar()); - assertThat(ChatColor.getLastColors(s), is(ChatColor.BLUE.toString())); - } -} diff --git a/api/src/test/java/org/bukkit/ChatPaginatorTest.java b/api/src/test/java/org/bukkit/ChatPaginatorTest.java deleted file mode 100644 index a644b150a..000000000 --- a/api/src/test/java/org/bukkit/ChatPaginatorTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.bukkit; - -import org.bukkit.util.ChatPaginator; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; - -public class ChatPaginatorTest { - @Test - public void testWordWrap1() { - String rawString = ChatColor.RED + "123456789 123456789 123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 19); - - assertThat(lines.length, is(2)); - assertThat(lines[0], is(ChatColor.RED + "123456789 123456789")); - assertThat(lines[1], is(ChatColor.RED.toString() + "123456789")); - } - - @Test - public void testWordWrap2() { - String rawString = "123456789 123456789 123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 22); - - assertThat(lines.length, is(2)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456789 123456789")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789")); - } - - @Test - public void testWordWrap3() { - String rawString = ChatColor.RED + "123456789 " + ChatColor.RED + ChatColor.RED + "123456789 " + ChatColor.RED + "123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 16); - - assertThat(lines.length, is(3)); - assertThat(lines[0], is(ChatColor.RED + "123456789")); - assertThat(lines[1], is(ChatColor.RED.toString() + ChatColor.RED + "123456789")); - assertThat(lines[2], is(ChatColor.RED + "123456789")); - } - - @Test - public void testWordWrap4() { - String rawString = "123456789 123456789 123456789 12345"; - String[] lines = ChatPaginator.wordWrap(rawString, 19); - - assertThat(lines.length, is(2)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456789 123456789")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789 12345")); - } - - @Test - public void testWordWrap5() { - String rawString = "123456789\n123456789 123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 19); - - assertThat(lines.length, is(2)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456789")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789 123456789")); - } - - @Test - public void testWordWrap6() { - String rawString = "12345678 23456789 123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 19); - - assertThat(lines.length, is(2)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "12345678 23456789")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789")); - } - - @Test - public void testWordWrap7() { - String rawString = "12345678 23456789 123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 19); - - assertThat(lines.length, is(2)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "12345678 23456789")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789")); - } - - @Test - public void testWordWrap8() { - String rawString = "123456789 123456789 123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 6); - - assertThat(lines.length, is(6)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "789")); - assertThat(lines[2], is(ChatColor.WHITE.toString() + "123456")); - assertThat(lines[3], is(ChatColor.WHITE.toString() + "789")); - assertThat(lines[4], is(ChatColor.WHITE.toString() + "123456")); - assertThat(lines[5], is(ChatColor.WHITE.toString() + "789")); - } - - @Test - public void testWordWrap9() { - String rawString = "1234 123456789 123456789 123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 6); - - assertThat(lines.length, is(7)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "1234")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456")); - assertThat(lines[2], is(ChatColor.WHITE.toString() + "789")); - assertThat(lines[3], is(ChatColor.WHITE.toString() + "123456")); - assertThat(lines[4], is(ChatColor.WHITE.toString() + "789")); - assertThat(lines[5], is(ChatColor.WHITE.toString() + "123456")); - assertThat(lines[6], is(ChatColor.WHITE.toString() + "789")); - } - - @Test - public void testWordWrap10() { - String rawString = "123456789\n123456789"; - String[] lines = ChatPaginator.wordWrap(rawString, 19); - - assertThat(lines.length, is(2)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "123456789")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "123456789")); - } - - @Test - public void testWordWrap11() { - String rawString = ChatColor.RED + "a a a " + ChatColor.BLUE + "a a"; - String[] lines = ChatPaginator.wordWrap(rawString, 9); - - assertThat(lines.length, is(1)); - assertThat(lines[0], is(ChatColor.RED + "a a a " + ChatColor.BLUE + "a a")); - } - - @Test - public void testWordWrap12() { - String rawString = "123 1 123"; - String[] lines = ChatPaginator.wordWrap(rawString, 5); - - assertThat(lines.length, is(2)); - assertThat(lines[0], is(ChatColor.WHITE.toString() + "123 1")); - assertThat(lines[1], is(ChatColor.WHITE.toString() + "123")); - } - - @Test - public void testPaginate1() { - String rawString = "1234 123456789 123456789 123456789"; - ChatPaginator.ChatPage page = ChatPaginator.paginate(rawString, 1, 6, 2); - - assertThat(page.getPageNumber(), is(1)); - assertThat(page.getTotalPages(), is(4)); - assertThat(page.getLines().length, is(2)); - assertThat(page.getLines()[0], is(ChatColor.WHITE.toString() + "1234")); - assertThat(page.getLines()[1], is(ChatColor.WHITE.toString() + "123456")); - } - - @Test - public void testPaginate2() { - String rawString = "1234 123456789 123456789 123456789"; - ChatPaginator.ChatPage page = ChatPaginator.paginate(rawString, 2, 6, 2); - - assertThat(page.getPageNumber(), is(2)); - assertThat(page.getTotalPages(), is(4)); - assertThat(page.getLines().length, is(2)); - assertThat(page.getLines()[0], is(ChatColor.WHITE.toString() + "789")); - assertThat(page.getLines()[1], is(ChatColor.WHITE.toString() + "123456")); - } - - @Test - public void testPaginate3() { - String rawString = "1234 123456789 123456789 123456789"; - ChatPaginator.ChatPage page = ChatPaginator.paginate(rawString, 4, 6, 2); - - assertThat(page.getPageNumber(), is(4)); - assertThat(page.getTotalPages(), is(4)); - assertThat(page.getLines().length, is(1)); - assertThat(page.getLines()[0], is(ChatColor.WHITE.toString() + "789")); - } -} diff --git a/api/src/test/java/org/bukkit/CoalTypeTest.java b/api/src/test/java/org/bukkit/CoalTypeTest.java deleted file mode 100644 index 7eb11ceaf..000000000 --- a/api/src/test/java/org/bukkit/CoalTypeTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class CoalTypeTest { - @Test - public void getByData() { - for (CoalType coalType : CoalType.values()) { - assertThat(CoalType.getByData(coalType.getData()), is(coalType)); - } - } -} diff --git a/api/src/test/java/org/bukkit/ColorTest.java b/api/src/test/java/org/bukkit/ColorTest.java deleted file mode 100644 index 8d9557af1..000000000 --- a/api/src/test/java/org/bukkit/ColorTest.java +++ /dev/null @@ -1,365 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.Test; - -@SuppressWarnings("javadoc") -public class ColorTest { - static class TestColor { - static int id = 0; - final String name; - final int rgb; - final int bgr; - final int r; - final int g; - final int b; - - TestColor(int rgb, int bgr, int r, int g, int b) { - this.rgb = rgb; - this.bgr = bgr; - this.r = r; - this.g = g; - this.b = b; - this.name = id + ":" + Integer.toHexString(rgb).toUpperCase() + "_" + Integer.toHexString(bgr).toUpperCase() + "-r" + Integer.toHexString(r).toUpperCase() + "-g" + Integer.toHexString(g).toUpperCase() + "-b" + Integer.toHexString(b).toUpperCase(); - } - } - - static TestColor[] examples = new TestColor[] { - /* 0xRRGGBB, 0xBBGGRR, 0xRR, 0xGG, 0xBB */ - new TestColor(0xFFFFFF, 0xFFFFFF, 0xFF, 0xFF, 0xFF), - new TestColor(0xFFFFAA, 0xAAFFFF, 0xFF, 0xFF, 0xAA), - new TestColor(0xFF00FF, 0xFF00FF, 0xFF, 0x00, 0xFF), - new TestColor(0x67FF22, 0x22FF67, 0x67, 0xFF, 0x22), - new TestColor(0x000000, 0x000000, 0x00, 0x00, 0x00) - }; - - @Test - public void testSerialization() throws Throwable { - for (TestColor testColor : examples) { - Color base = Color.fromRGB(testColor.rgb); - - YamlConfiguration toSerialize = new YamlConfiguration(); - toSerialize.set("color", base); - String serialized = toSerialize.saveToString(); - - YamlConfiguration deserialized = new YamlConfiguration(); - deserialized.loadFromString(serialized); - - assertThat(testColor.name + " on " + serialized, base, is(deserialized.getColor("color"))); - } - } - - // Equality tests - @Test - public void testEqualities() { - for (TestColor testColor : examples) { - Color fromRGB = Color.fromRGB(testColor.rgb); - Color fromBGR = Color.fromBGR(testColor.bgr); - Color fromRGBs = Color.fromRGB(testColor.r, testColor.g, testColor.b); - Color fromBGRs = Color.fromBGR(testColor.b, testColor.g, testColor.r); - - assertThat(testColor.name, fromRGB, is(fromRGBs)); - assertThat(testColor.name, fromRGB, is(fromBGR)); - assertThat(testColor.name, fromRGB, is(fromBGRs)); - assertThat(testColor.name, fromRGBs, is(fromBGR)); - assertThat(testColor.name, fromRGBs, is(fromBGRs)); - assertThat(testColor.name, fromBGR, is(fromBGRs)); - } - } - - @Test - public void testInequalities() { - for (int i = 1; i < examples.length; i++) { - TestColor testFrom = examples[i]; - Color from = Color.fromRGB(testFrom.rgb); - for (int j = i - 1; j >= 0; j--) { - TestColor testTo = examples[j]; - Color to = Color.fromRGB(testTo.rgb); - String name = testFrom.name + " to " + testTo.name; - assertThat(name, from, is(not(to))); - - Color transform = from.setRed(testTo.r).setBlue(testTo.b).setGreen(testTo.g); - assertThat(name, transform, is(not(sameInstance(from)))); - assertThat(name, transform, is(to)); - } - } - } - - // RGB tests - @Test - public void testRGB() { - for (TestColor testColor : examples) { - assertThat(testColor.name, Color.fromRGB(testColor.rgb).asRGB(), is(testColor.rgb)); - assertThat(testColor.name, Color.fromBGR(testColor.bgr).asRGB(), is(testColor.rgb)); - assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).asRGB(), is(testColor.rgb)); - assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).asRGB(), is(testColor.rgb)); - } - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidRGB1() { - Color.fromRGB(0x01000000); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidRGB2() { - Color.fromRGB(Integer.MIN_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidRGB3() { - Color.fromRGB(Integer.MAX_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidRGB4() { - Color.fromRGB(-1); - } - - // BGR tests - @Test - public void testBGR() { - for (TestColor testColor : examples) { - assertThat(testColor.name, Color.fromRGB(testColor.rgb).asBGR(), is(testColor.bgr)); - assertThat(testColor.name, Color.fromBGR(testColor.bgr).asBGR(), is(testColor.bgr)); - assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).asBGR(), is(testColor.bgr)); - assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).asBGR(), is(testColor.bgr)); - } - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidBGR1() { - Color.fromBGR(0x01000000); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidBGR2() { - Color.fromBGR(Integer.MIN_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidBGR3() { - Color.fromBGR(Integer.MAX_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidBGR4() { - Color.fromBGR(-1); - } - - // Red tests - @Test - public void testRed() { - for (TestColor testColor : examples) { - assertThat(testColor.name, Color.fromRGB(testColor.rgb).getRed(), is(testColor.r)); - assertThat(testColor.name, Color.fromBGR(testColor.bgr).getRed(), is(testColor.r)); - assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).getRed(), is(testColor.r)); - assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).getRed(), is(testColor.r)); - } - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR01() { - Color.fromRGB(-1, 0x00, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR02() { - Color.fromRGB(Integer.MAX_VALUE, 0x00, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR03() { - Color.fromRGB(Integer.MIN_VALUE, 0x00, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR04() { - Color.fromRGB(0x100, 0x00, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR05() { - Color.fromBGR(0x00, 0x00, -1); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR06() { - Color.fromBGR(0x00, 0x00, Integer.MAX_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR07() { - Color.fromBGR(0x00, 0x00, Integer.MIN_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR08() { - Color.fromBGR(0x00, 0x00, 0x100); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR09() { - Color.WHITE.setRed(-1); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR10() { - Color.WHITE.setRed(Integer.MAX_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR11() { - Color.WHITE.setRed(Integer.MIN_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidR12() { - Color.WHITE.setRed(0x100); - } - - // Blue tests - @Test - public void testBlue() { - for (TestColor testColor : examples) { - assertThat(testColor.name, Color.fromRGB(testColor.rgb).getBlue(), is(testColor.b)); - assertThat(testColor.name, Color.fromBGR(testColor.bgr).getBlue(), is(testColor.b)); - assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).getBlue(), is(testColor.b)); - assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).getBlue(), is(testColor.b)); - } - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB01() { - Color.fromRGB(0x00, 0x00, -1); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB02() { - Color.fromRGB(0x00, 0x00, Integer.MAX_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB03() { - Color.fromRGB(0x00, 0x00, Integer.MIN_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB04() { - Color.fromRGB(0x00, 0x00, 0x100); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB05() { - Color.fromBGR(-1, 0x00, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB06() { - Color.fromBGR(Integer.MAX_VALUE, 0x00, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB07() { - Color.fromBGR(Integer.MIN_VALUE, 0x00, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB08() { - Color.fromBGR(0x100, 0x00, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB09() { - Color.WHITE.setBlue(-1); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB10() { - Color.WHITE.setBlue(Integer.MAX_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB11() { - Color.WHITE.setBlue(Integer.MIN_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidB12() { - Color.WHITE.setBlue(0x100); - } - - // Green tests - @Test - public void testGreen() { - for (TestColor testColor : examples) { - assertThat(testColor.name, Color.fromRGB(testColor.rgb).getGreen(), is(testColor.g)); - assertThat(testColor.name, Color.fromBGR(testColor.bgr).getGreen(), is(testColor.g)); - assertThat(testColor.name, Color.fromRGB(testColor.r, testColor.g, testColor.b).getGreen(), is(testColor.g)); - assertThat(testColor.name, Color.fromBGR(testColor.b, testColor.g, testColor.r).getGreen(), is(testColor.g)); - } - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG01() { - Color.fromRGB(0x00, -1, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG02() { - Color.fromRGB(0x00, Integer.MAX_VALUE, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG03() { - Color.fromRGB(0x00, Integer.MIN_VALUE, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG04() { - Color.fromRGB(0x00, 0x100, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG05() { - Color.fromBGR(0x00, -1, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG06() { - Color.fromBGR(0x00, Integer.MAX_VALUE, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG07() { - Color.fromBGR(0x00, Integer.MIN_VALUE, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG08() { - Color.fromBGR(0x00, 0x100, 0x00); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG09() { - Color.WHITE.setGreen(-1); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG10() { - Color.WHITE.setGreen(Integer.MAX_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG11() { - Color.WHITE.setGreen(Integer.MIN_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testInvalidG12() { - Color.WHITE.setGreen(0x100); - } -} diff --git a/api/src/test/java/org/bukkit/CropStateTest.java b/api/src/test/java/org/bukkit/CropStateTest.java deleted file mode 100644 index f792a1c4d..000000000 --- a/api/src/test/java/org/bukkit/CropStateTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class CropStateTest { - @Test - public void getByData() { - for (CropState cropState : CropState.values()) { - assertThat(CropState.getByData(cropState.getData()), is(cropState)); - } - } -} diff --git a/api/src/test/java/org/bukkit/DifficultyTest.java b/api/src/test/java/org/bukkit/DifficultyTest.java deleted file mode 100644 index 293e283a2..000000000 --- a/api/src/test/java/org/bukkit/DifficultyTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class DifficultyTest { - @Test - public void getByValue() { - for (Difficulty difficulty : Difficulty.values()) { - assertThat(Difficulty.getByValue(difficulty.getValue()), is(difficulty)); - } - } -} diff --git a/api/src/test/java/org/bukkit/DyeColorTest.java b/api/src/test/java/org/bukkit/DyeColorTest.java deleted file mode 100644 index c5aaecf57..000000000 --- a/api/src/test/java/org/bukkit/DyeColorTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.bukkit; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.material.Colorable; -import org.bukkit.material.Dye; -import org.bukkit.material.Wool; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class DyeColorTest { - - @Parameters(name= "{index}: {0}") - public static List data() { - List list = new ArrayList(); - for (DyeColor dye : DyeColor.values()) { - list.add(new Object[] {dye}); - } - return list; - } - - @Parameter public DyeColor dye; - - @Test - @SuppressWarnings("deprecation") - public void getByData() { - byte data = dye.getWoolData(); - - DyeColor byData = DyeColor.getByWoolData(data); - assertThat(byData, is(dye)); - } - - @Test - public void getByWoolData() { - byte data = dye.getWoolData(); - - DyeColor byData = DyeColor.getByWoolData(data); - assertThat(byData, is(dye)); - } - - @Test - public void getByDyeData() { - byte data = dye.getDyeData(); - - DyeColor byData = DyeColor.getByDyeData(data); - assertThat(byData, is(dye)); - } - - @Test - public void getDyeDyeColor() { - testColorable(new Dye(Material.LEGACY_INK_SACK, dye.getDyeData())); - testColorable(new Dye(dye)); - } - - @Test - public void getWoolDyeColor() { - testColorable(new Wool(Material.LEGACY_WOOL, dye.getWoolData())); - } - - private void testColorable(final Colorable colorable) { - assertThat(colorable.getColor(), is(this.dye)); - } -} diff --git a/api/src/test/java/org/bukkit/EffectTest.java b/api/src/test/java/org/bukkit/EffectTest.java deleted file mode 100644 index 08aa71d3a..000000000 --- a/api/src/test/java/org/bukkit/EffectTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class EffectTest { - @Test - public void getById() { - for (Effect effect : Effect.values()) { - assertThat(Effect.getById(effect.getId()), is(effect)); - } - } -} diff --git a/api/src/test/java/org/bukkit/EntityEffectTest.java b/api/src/test/java/org/bukkit/EntityEffectTest.java deleted file mode 100644 index 0c92d5cdd..000000000 --- a/api/src/test/java/org/bukkit/EntityEffectTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class EntityEffectTest { - @Test - public void getByData() { - for (EntityEffect entityEffect : EntityEffect.values()) { - assertThat(EntityEffect.getByData(entityEffect.getData()), is(entityEffect)); - } - } -} diff --git a/api/src/test/java/org/bukkit/GameModeTest.java b/api/src/test/java/org/bukkit/GameModeTest.java deleted file mode 100644 index f671faefe..000000000 --- a/api/src/test/java/org/bukkit/GameModeTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class GameModeTest { - @Test - public void getByValue() { - for (GameMode gameMode : GameMode.values()) { - assertThat(GameMode.getByValue(gameMode.getValue()), is(gameMode)); - } - } -} diff --git a/api/src/test/java/org/bukkit/GrassSpeciesTest.java b/api/src/test/java/org/bukkit/GrassSpeciesTest.java deleted file mode 100644 index 9e332c71d..000000000 --- a/api/src/test/java/org/bukkit/GrassSpeciesTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class GrassSpeciesTest { - @Test - public void getByData() { - for (GrassSpecies grassSpecies : GrassSpecies.values()) { - assertThat(GrassSpecies.getByData(grassSpecies.getData()), is(grassSpecies)); - } - } -} diff --git a/api/src/test/java/org/bukkit/InstrumentTest.java b/api/src/test/java/org/bukkit/InstrumentTest.java deleted file mode 100644 index f1a05705f..000000000 --- a/api/src/test/java/org/bukkit/InstrumentTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class InstrumentTest { - @Test - public void getByType() { - for (Instrument instrument : Instrument.values()) { - assertThat(Instrument.getByType(instrument.getType()), is(instrument)); - } - } -} diff --git a/api/src/test/java/org/bukkit/LocationTest.java b/api/src/test/java/org/bukkit/LocationTest.java deleted file mode 100644 index 48d20761b..000000000 --- a/api/src/test/java/org/bukkit/LocationTest.java +++ /dev/null @@ -1,196 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.util.List; -import java.util.Random; - -import org.bukkit.util.Vector; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.collect.ImmutableList; - -@RunWith(Parameterized.class) -public class LocationTest { - private static final double delta = 1.0 / 1000000; - /** - *
-     * a² + b² = c², a = b
-     * => 2∙(a²) = 2∙(b²) = c², c = 1
-     * => 2∙(a²) = 1
-     * => a² = 1/2
-     * => a = √(1/2) ∎
-     * 
- */ - private static final double HALF_UNIT = Math.sqrt(1 / 2f); - /** - *
-     * a² + b² = c², c = √(1/2)
-     * => a² + b² = √(1/2)², a = b
-     * => 2∙(a²) = 2∙(b²) = 1/2
-     * => a² = 1/4
-     * => a = √(1/4) ∎
-     * 
- */ - private static final double HALF_HALF_UNIT = Math.sqrt(1 / 4f); - - @Parameters(name= "{index}: {0}") - public static List data() { - Random RANDOM = new Random(1l); // Test is deterministic - int r = 0; - return ImmutableList.of( - new Object[] { "X", - 1, 0, 0, - 270, 0 - }, - new Object[] { "-X", - -1, 0, 0, - 90, 0 - }, - new Object[] { "Z", - 0, 0, 1, - 0, 0 - }, - new Object[] { "-Z", - 0, 0, -1, - 180, 0 - }, - new Object[] { "Y", - 0, 1, 0, - 0, -90 // Zero is here as a "default" value - }, - new Object[] { "-Y", - 0, -1, 0, - 0, 90 // Zero is here as a "default" value - }, - new Object[] { "X Z", - HALF_UNIT, 0, HALF_UNIT, - (270 + 360) / 2, 0 - }, - new Object[] { "X -Z", - HALF_UNIT, 0, -HALF_UNIT, - (270 + 180) / 2, 0 - }, - new Object[] { "-X -Z", - -HALF_UNIT, 0, -HALF_UNIT, - (90 + 180) / 2, 0 - }, - new Object[] { "-X Z", - -HALF_UNIT, 0, HALF_UNIT, - (90 + 0) / 2, 0 - }, - new Object[] { "X Y Z", - HALF_HALF_UNIT, HALF_UNIT, HALF_HALF_UNIT, - (270 + 360) / 2, -45 - }, - new Object[] { "-X -Y -Z", - -HALF_HALF_UNIT, -HALF_UNIT, -HALF_HALF_UNIT, - (90 + 180) / 2, 45 - }, - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++), - getRandom(RANDOM, r++) - ); - } - - private static Object[] getRandom(Random random, int index) { - final double YAW_FACTOR = 360; - final double YAW_OFFSET = 0; - final double PITCH_FACTOR = 180; - final double PITCH_OFFSET = -90; - final double CARTESIAN_FACTOR = 256; - final double CARTESIAN_OFFSET = -128; - - Vector vector; - Location location; - if (random.nextBoolean()) { - float pitch = (float) (random.nextDouble() * PITCH_FACTOR + PITCH_OFFSET); - float yaw = (float) (random.nextDouble() * YAW_FACTOR + YAW_OFFSET); - - location = getEmptyLocation(); - location.setPitch(pitch); - location.setYaw(yaw); - - vector = location.getDirection(); - } else { - double x = random.nextDouble() * CARTESIAN_FACTOR + CARTESIAN_OFFSET; - double y = random.nextDouble() * CARTESIAN_FACTOR + CARTESIAN_OFFSET; - double z = random.nextDouble() * CARTESIAN_FACTOR + CARTESIAN_OFFSET; - - location = getEmptyLocation(); - vector = new Vector(x, y, z).normalize(); - - location.setDirection(vector); - } - - return new Object[] { "R" + index, - vector.getX(), vector.getY(), vector.getZ(), - location.getYaw(), location.getPitch() - }; - } - - @Parameter(0) - public String nane; - @Parameter(1) - public double x; - @Parameter(2) - public double y; - @Parameter(3) - public double z; - @Parameter(4) - public float yaw; - @Parameter(5) - public float pitch; - - @Test - public void testExpectedPitchYaw() { - Location location = getEmptyLocation().setDirection(getVector()); - - assertThat((double) location.getYaw(), is(closeTo(yaw, delta))); - assertThat((double) location.getPitch(), is(closeTo(pitch, delta))); - } - - @Test - public void testExpectedXYZ() { - Vector vector = getLocation().getDirection(); - - assertThat(vector.getX(), is(closeTo(x, delta))); - assertThat(vector.getY(), is(closeTo(y, delta))); - assertThat(vector.getZ(), is(closeTo(z, delta))); - } - - private Vector getVector() { - return new Vector(x, y, z); - } - - private static Location getEmptyLocation() { - return new Location(null, 0, 0, 0); - } - - private Location getLocation() { - Location location = getEmptyLocation(); - location.setYaw(yaw); - location.setPitch(pitch); - return location; - } -} diff --git a/api/src/test/java/org/bukkit/MaterialTest.java b/api/src/test/java/org/bukkit/MaterialTest.java deleted file mode 100644 index 66f4603a2..000000000 --- a/api/src/test/java/org/bukkit/MaterialTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import org.bukkit.material.MaterialData; -import org.junit.Test; - -public class MaterialTest { - @Test - public void getByName() { - for (Material material : Material.values()) { - assertThat(Material.getMaterial(material.toString()), is(material)); - } - } - - @Test - public void getByNameNull() { - assertThat(Material.getMaterial(null), is(nullValue())); - } - - @Test - public void getData() { - for (Material material : Material.values()) { - if (!material.isLegacy()) { - continue; - } - Class clazz = material.getData(); - - assertThat(material.getNewData((byte) 0), is(instanceOf(clazz))); - } - } - - @Test(expected = IllegalArgumentException.class) - public void matchMaterialByNull() { - Material.matchMaterial(null); - } - - @Test - public void matchMaterialByName() { - for (Material material : Material.values()) { - assertThat(Material.matchMaterial(material.toString()), is(material)); - } - } - - @Test - public void matchMaterialByKey() { - for (Material material : Material.values()) { - if (material.isLegacy()) { - continue; - } - assertThat(Material.matchMaterial(material.getKey().toString()), is(material)); - } - } - - @Test - public void matchMaterialByWrongNamespace() { - for (Material material : Material.values()) { - if (material.isLegacy()) { - continue; - } - assertNull(Material.matchMaterial("bogus:" + material.getKey().getKey())); - } - } - - @Test - public void matchMaterialByLowerCaseAndSpaces() { - for (Material material : Material.values()) { - String name = material.toString().replaceAll("_", " ").toLowerCase(java.util.Locale.ENGLISH); - assertThat(Material.matchMaterial(name), is(material)); - } - } -} diff --git a/api/src/test/java/org/bukkit/NamespacedKeyTest.java b/api/src/test/java/org/bukkit/NamespacedKeyTest.java deleted file mode 100644 index 8c5e5ca78..000000000 --- a/api/src/test/java/org/bukkit/NamespacedKeyTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.bukkit; - -import org.junit.Assert; -import org.junit.Test; - -public class NamespacedKeyTest { - - @Test - public void testValid() { - Assert.assertEquals("minecraft:foo", new NamespacedKey("minecraft", "foo").toString()); - Assert.assertEquals("minecraft:foo/bar", new NamespacedKey("minecraft", "foo/bar").toString()); - Assert.assertEquals("minecraft:foo/bar_baz", new NamespacedKey("minecraft", "foo/bar_baz").toString()); - Assert.assertEquals("minecraft:foo/bar_baz-qux", new NamespacedKey("minecraft", "foo/bar_baz-qux").toString()); - Assert.assertEquals("minecraft:foo/bar_baz-qux.quux", new NamespacedKey("minecraft", "foo/bar_baz-qux.quux").toString()); - } - - @Test(expected = IllegalArgumentException.class) - public void testEmptyNamespace() { - new NamespacedKey("", "foo").toString(); - } - - @Test(expected = IllegalArgumentException.class) - public void testEmptyKey() { - new NamespacedKey("minecraft", "").toString(); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidNamespace() { - new NamespacedKey("minecraft/test", "foo").toString(); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidNamespaceCasing() { - new NamespacedKey("Minecraft", "foo").toString(); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidKeyCasing() { - new NamespacedKey("minecraft", "Foo").toString(); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidKey() { - new NamespacedKey("minecraft", "foo!").toString(); - } - - @Test - public void testBelowLength() { - new NamespacedKey("loremipsumdolorsitametconsecteturadipiscingelitduisvolutpatvelitsitametmaximusscelerisquemorbiullamcorperexacconsequategestas", - "loremipsumdolorsitametconsecteturadipiscingelitduisvolutpatvelitsitametmaximusscelerisquemorbiullamcorperexacconsequategestas").toString(); - } - - @Test(expected = IllegalArgumentException.class) - public void testAboveLength() { - new NamespacedKey("loremipsumdolorsitametconsecteturadipiscingelitduisvolutpatvelitsitametmaximusscelerisquemorbiullamcorperexacconsequategestas", - "loremipsumdolorsitametconsecteturadipiscingelitduisvolutpatvelitsitametmaximusscelerisquemorbiullamcorperexacconsequategestas/" - + "loremipsumdolorsitametconsecteturadipiscingelitduisvolutpatvelitsitametmaximusscelerisquemorbiullamcorperexacconsequategestas").toString(); - } -} diff --git a/api/src/test/java/org/bukkit/NoteTest.java b/api/src/test/java/org/bukkit/NoteTest.java deleted file mode 100644 index 4759041a7..000000000 --- a/api/src/test/java/org/bukkit/NoteTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Collection; - -import org.junit.Test; - -import com.google.common.collect.Lists; - -public class NoteTest { - @Test - public void getToneByData() { - for (Note.Tone tone : Note.Tone.values()) { - assertThat(Note.Tone.getById(tone.getId()), is(tone)); - } - } - - @Test - public void verifySharpedData() { - for (Note.Tone tone : Note.Tone.values()) { - if (!tone.isSharpable()) return; - - assertFalse(tone.isSharped(tone.getId(false))); - assertTrue(tone.isSharped(tone.getId(true))); - } - } - - @Test - public void verifyUnknownToneData() { - Collection tones = Lists.newArrayList(); - for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) { - tones.add((byte) i); - } - - for (Note.Tone tone : Note.Tone.values()) { - if (tone.isSharpable()) tones.remove(tone.getId(true)); - tones.remove(tone.getId()); - } - - for (Byte data : tones) { - assertThat(Note.Tone.getById(data), is(nullValue())); - - for (Note.Tone tone : Note.Tone.values()) { - try { - tone.isSharped(data); - - fail(data + " should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - assertNotNull(e); - } - } - } - } - - @Test(expected = IllegalArgumentException.class) - public void createNoteBelowMin() { - new Note((byte) -1); - } - - @Test(expected = IllegalArgumentException.class) - public void createNoteAboveMax() { - new Note((byte) 25); - } - - @Test(expected = IllegalArgumentException.class) - public void createNoteOctaveBelowMax() { - new Note((byte) -1, Note.Tone.A, true); - } - - @Test(expected = IllegalArgumentException.class) - public void createNoteOctaveAboveMax() { - new Note((byte) 3, Note.Tone.A, true); - } - - @Test - public void createNoteOctaveNonSharpable() { - Note note = new Note((byte) 0, Note.Tone.B, true); - assertFalse(note.isSharped()); - assertThat(note.getTone(), is(Note.Tone.C)); - } - - @Test - public void createNoteFlat() { - Note note = Note.flat(0, Note.Tone.D); - assertTrue(note.isSharped()); - assertThat(note.getTone(), is(Note.Tone.C)); - } - - @Test - public void createNoteFlatNonFlattenable() { - Note note = Note.flat(0, Note.Tone.C); - assertFalse(note.isSharped()); - assertThat(note.getTone(), is(Note.Tone.B)); - } - - @Test - public void testFlatWrapping() { - Note note = Note.flat(1, Note.Tone.G); - assertTrue(note.isSharped()); - assertThat(note.getTone(), is(Note.Tone.F)); - } - - @Test - public void testFlatWrapping2() { - Note note = new Note(1, Note.Tone.G, false).flattened(); - assertTrue(note.isSharped()); - assertThat(note.getTone(), is(Note.Tone.F)); - } - - @Test - public void testSharpWrapping() { - Note note = new Note(1, Note.Tone.F, false).sharped(); - assertTrue(note.isSharped()); - assertThat(note.getTone(), is(Note.Tone.F)); - assertEquals(note.getOctave(), 2); - } - - @Test(expected=IllegalArgumentException.class) - public void testSharpWrapping2() { - new Note(2, Note.Tone.F, true).sharped(); - } - - @Test - public void testHighest() { - Note note = new Note(2, Note.Tone.F, true); - assertEquals(note.getId(), (byte)24); - } - - @Test - public void testLowest() { - Note note = new Note(0, Note.Tone.F, true); - assertEquals(note.getId(), (byte)0); - } - - @Test - public void doo() { - for (int i = 1; i <= 24; i++) { - Note note = new Note((byte) i); - int octave = note.getOctave(); - Note.Tone tone = note.getTone(); - boolean sharped = note.isSharped(); - - Note newNote = new Note(octave, tone, sharped); - assertThat(newNote, is(note)); - assertThat(newNote.getId(), is(note.getId())); - } - } -} diff --git a/api/src/test/java/org/bukkit/TestServer.java b/api/src/test/java/org/bukkit/TestServer.java deleted file mode 100644 index 613675c3b..000000000 --- a/api/src/test/java/org/bukkit/TestServer.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.bukkit; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Map; -import java.util.logging.Logger; - -import org.bukkit.command.SimpleCommandMap; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.SimplePluginManager; - -import com.google.common.collect.ImmutableMap; - -public class TestServer implements InvocationHandler { - private static interface MethodHandler { - Object handle(TestServer server, Object[] args); - } - - private static final Map methods; - - static { - try { - ImmutableMap.Builder methodMap = ImmutableMap.builder(); - methodMap.put( - Server.class.getMethod("isPrimaryThread"), - new MethodHandler() { - public Object handle(TestServer server, Object[] args) { - return Thread.currentThread().equals(server.creatingThread); - } - } - ); - // Paper start - methodMap.put( - Server.class.getMethod("getTag", String.class, NamespacedKey.class, Class.class), - new MethodHandler() { - public Object handle(TestServer server, Object[] args) { - return new com.destroystokyo.paper.MaterialSetTag(); - } - } - ); - // Paper end - methodMap.put( - Server.class.getMethod("getPluginManager"), - new MethodHandler() { - public Object handle(TestServer server, Object[] args) { - return server.pluginManager; - } - } - ); - methodMap.put( - Server.class.getMethod("getLogger"), - new MethodHandler() { - final Logger logger = Logger.getLogger(TestServer.class.getCanonicalName()); - public Object handle(TestServer server, Object[] args) { - return logger; - } - } - ); - methodMap.put( - Server.class.getMethod("getName"), - new MethodHandler() { - public Object handle(TestServer server, Object[] args) { - return TestServer.class.getSimpleName(); - } - } - ); - methodMap.put( - Server.class.getMethod("getVersion"), - new MethodHandler() { - public Object handle(TestServer server, Object[] args) { - return "Version_" + TestServer.class.getPackage().getImplementationVersion(); - } - } - ); - methodMap.put( - Server.class.getMethod("getBukkitVersion"), - new MethodHandler() { - public Object handle(TestServer server, Object[] args) { - return "BukkitVersion_" + TestServer.class.getPackage().getImplementationVersion(); - } - } - ); - methods = methodMap.build(); - - TestServer server = new TestServer(); - Server instance = Proxy.getProxyClass(Server.class.getClassLoader(), Server.class).asSubclass(Server.class).getConstructor(InvocationHandler.class).newInstance(server); - Bukkit.setServer(instance); - server.pluginManager = new SimplePluginManager(instance, new SimpleCommandMap(instance)); - } catch (Throwable t) { - throw new Error(t); - } - } - - private Thread creatingThread = Thread.currentThread(); - private PluginManager pluginManager; - private TestServer() {}; - - public static Server getInstance() { - return Bukkit.getServer(); - } - - public Object invoke(Object proxy, Method method, Object[] args) { - MethodHandler handler = methods.get(method); - if (handler != null) { - return handler.handle(this, args); - } - throw new UnsupportedOperationException(String.valueOf(method)); - } -} diff --git a/api/src/test/java/org/bukkit/TreeSpeciesTest.java b/api/src/test/java/org/bukkit/TreeSpeciesTest.java deleted file mode 100644 index 4a997306f..000000000 --- a/api/src/test/java/org/bukkit/TreeSpeciesTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class TreeSpeciesTest { - @Test - public void getByData() { - for (TreeSpecies treeSpecies : TreeSpecies.values()) { - assertThat(TreeSpecies.getByData(treeSpecies.getData()), is(treeSpecies)); - } - } -} diff --git a/api/src/test/java/org/bukkit/WorldTypeTest.java b/api/src/test/java/org/bukkit/WorldTypeTest.java deleted file mode 100644 index d31c20522..000000000 --- a/api/src/test/java/org/bukkit/WorldTypeTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class WorldTypeTest { - @Test - public void getByName() { - for (WorldType worldType : WorldType.values()) { - assertThat(WorldType.getByName(worldType.getName()), is(worldType)); - } - } -} diff --git a/api/src/test/java/org/bukkit/configuration/ConfigurationSectionTest.java b/api/src/test/java/org/bukkit/configuration/ConfigurationSectionTest.java deleted file mode 100644 index 4e91b1a27..000000000 --- a/api/src/test/java/org/bukkit/configuration/ConfigurationSectionTest.java +++ /dev/null @@ -1,600 +0,0 @@ -package org.bukkit.configuration; - -import org.bukkit.Material; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; -import org.junit.Test; -import static org.junit.Assert.*; - -public abstract class ConfigurationSectionTest { - public abstract ConfigurationSection getConfigurationSection(); - - @Test - public void testGetKeys() { - ConfigurationSection section = getConfigurationSection(); - - section.set("key", true); - section.set("subsection.subkey", true); - section.set("subsection.subkey2", true); - section.set("subsection.subsubsection.key", true); - section.set("key2", true); - section.set("42", true); - - assertArrayEquals(new String[] { "key", "subsection", "key2", "42" }, section.getKeys(false).toArray()); - assertArrayEquals(new String[] { "key", "subsection", "subsection.subkey", "subsection.subkey2", "subsection.subsubsection", "subsection.subsubsection.key", "key2", "42" }, section.getKeys(true).toArray()); - assertArrayEquals(new String[] { "subkey", "subkey2", "subsubsection", "subsubsection.key" }, section.getConfigurationSection("subsection").getKeys(true).toArray()); - } - - @Test - public void testGetKeysWithDefaults() { - ConfigurationSection section = getConfigurationSection(); - section.getRoot().options().copyDefaults(true); - - section.set("key", true); - section.addDefault("subsection.subkey", true); - section.addDefault("subsection.subkey2", true); - section.addDefault("subsection.subsubsection.key", true); - section.addDefault("key2", true); - - assertArrayEquals(new String[] { "subsection", "key2", "key" }, section.getKeys(false).toArray()); - assertArrayEquals(new String[] { "subsection", "subsection.subkey", "subsection.subkey2", "subsection.subsubsection", "subsection.subsubsection.key", "key2", "key" }, section.getKeys(true).toArray()); - assertArrayEquals(new String[] { "subkey", "subkey2", "subsubsection", "subsubsection.key" }, section.getConfigurationSection("subsection").getKeys(true).toArray()); - } - - @Test - public void testGetValues() { - ConfigurationSection section = getConfigurationSection(); - - section.set("bool", true); - section.set("subsection.string", "test"); - section.set("subsection.long", Long.MAX_VALUE); - section.set("int", 42); - - Map shallowValues = section.getValues(false); - assertArrayEquals(new String[] { "bool", "subsection", "int" }, shallowValues.keySet().toArray()); - assertArrayEquals(new Object[] { true, section.getConfigurationSection("subsection"), 42 }, shallowValues.values().toArray()); - - Map deepValues = section.getValues(true); - assertArrayEquals(new String[] { "bool", "subsection", "subsection.string", "subsection.long", "int" }, deepValues.keySet().toArray()); - assertArrayEquals(new Object[] { true, section.getConfigurationSection("subsection"), "test", Long.MAX_VALUE, 42 }, deepValues.values().toArray()); - } - - @Test - public void testGetValuesWithDefaults() { - ConfigurationSection section = getConfigurationSection(); - section.getRoot().options().copyDefaults(true); - - // Fix for SPIGOT-4558 means that defaults will always be first - // This is a little bit unintuitive for section defaults when deep iterating keys / values as shown below - // But the API doesn't guarantee order & when serialized (using shallow getters) all is well - section.set("bool", true); - section.set("subsection.string", "test"); - section.addDefault("subsection.long", Long.MAX_VALUE); - section.addDefault("int", 42); - - Map shallowValues = section.getValues(false); - assertArrayEquals(new String[] { "int", "bool", "subsection" }, shallowValues.keySet().toArray()); - assertArrayEquals(new Object[] { 42, true, section.getConfigurationSection("subsection") }, shallowValues.values().toArray()); - - Map deepValues = section.getValues(true); - assertArrayEquals(new String[] { "subsection.long", "int", "bool", "subsection", "subsection.string" }, deepValues.keySet().toArray()); - assertArrayEquals(new Object[] { Long.MAX_VALUE, 42, true, section.getConfigurationSection("subsection"), "test" }, deepValues.values().toArray()); - } - - @Test - public void testContains() { - ConfigurationSection section = getConfigurationSection(); - - section.set("exists", true); - - assertTrue(section.contains("exists")); - assertFalse(section.contains("doesnt-exist")); - - assertTrue(section.contains("exists", true)); - assertTrue(section.contains("exists", false)); - - assertFalse(section.contains("doesnt-exist", true)); - assertFalse(section.contains("doesnt-exist", false)); - - section.addDefault("doenst-exist-two", true); - section.set("doenst-exist-two", null); - - assertFalse(section.contains("doenst-exist-two", true)); - assertTrue(section.contains("doenst-exist-two", false)); - } - - @Test - public void testIsSet() { - ConfigurationSection section = getConfigurationSection(); - - section.set("notDefault", true); - section.getRoot().addDefault("default", true); - section.getRoot().addDefault("defaultAndSet", true); - section.set("defaultAndSet", true); - - assertTrue(section.isSet("notDefault")); - assertFalse(section.isSet("default")); - assertTrue(section.isSet("defaultAndSet")); - } - - @Test - public void testGetCurrentPath() { - ConfigurationSection section = getConfigurationSection(); - - assertEquals(section.getName(), section.getCurrentPath()); - } - - @Test - public void testGetName() { - ConfigurationSection section = getConfigurationSection().createSection("subsection"); - - assertEquals("subsection", section.getName()); - assertEquals("", section.getRoot().getName()); - } - - @Test - public void testGetRoot() { - ConfigurationSection section = getConfigurationSection(); - - assertNotNull(section.getRoot()); - assertTrue(section.getRoot().contains(section.getCurrentPath())); - } - - @Test - public void testGetParent() { - ConfigurationSection section = getConfigurationSection(); - ConfigurationSection subsection = section.createSection("subsection"); - - assertEquals(section.getRoot(), section.getParent()); - assertEquals(section, subsection.getParent()); - } - - @Test - public void testGet_String() { - ConfigurationSection section = getConfigurationSection(); - - section.set("exists", "hello world"); - - assertEquals("hello world", section.getString("exists")); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGet_String_Object() { - ConfigurationSection section = getConfigurationSection(); - - section.set("exists", "Set Value"); - - assertEquals("Set Value", section.get("exists", "Default Value")); - assertEquals("Default Value", section.get("doesntExist", "Default Value")); - } - - @Test - public void testSet() { - ConfigurationSection section = getConfigurationSection(); - - section.set("exists", "hello world"); - - assertTrue(section.contains("exists")); - assertTrue(section.isSet("exists")); - assertEquals("hello world", section.get("exists")); - - section.set("exists", null); - - assertFalse(section.contains("exists")); - assertFalse(section.isSet("exists")); - } - - @Test - public void testCreateSection() { - ConfigurationSection section = getConfigurationSection(); - ConfigurationSection subsection = section.createSection("subsection"); - - assertEquals("subsection", subsection.getName()); - } - - @Test - public void testSectionMap() { - ConfigurationSection config = getConfigurationSection(); - Map testMap = new LinkedHashMap(); - - testMap.put("string", "Hello World"); - testMap.put("integer", 15); - - config.createSection("test.path", testMap); - - assertEquals(testMap, config.getConfigurationSection("test.path").getValues(false)); - } - - @Test - public void testGetString_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - String value = "Hello World"; - - section.set(key, value); - - assertEquals(value, section.getString(key)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetString_String_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - String value = "Hello World"; - String def = "Default Value"; - - section.set(key, value); - - assertEquals(value, section.getString(key, def)); - assertEquals(def, section.getString("doesntExist", def)); - } - - @Test - public void testIsString() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - String value = "Hello World"; - - section.set(key, value); - - assertTrue(section.isString(key)); - assertFalse(section.isString("doesntExist")); - } - - @Test - public void testGetInt_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - int value = Integer.MAX_VALUE; - - section.set(key, value); - - assertEquals(value, section.getInt(key)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetInt_String_Int() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - int value = Integer.MAX_VALUE; - int def = Integer.MIN_VALUE; - - section.set(key, value); - - assertEquals(value, section.getInt(key, def)); - assertEquals(def, section.getInt("doesntExist", def)); - } - - @Test - public void testIsInt() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - int value = Integer.MAX_VALUE; - - section.set(key, value); - - assertTrue(section.isInt(key)); - assertFalse(section.isInt("doesntExist")); - } - - @Test - public void testGetBoolean_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - boolean value = true; - - section.set(key, value); - - assertEquals(value, section.getBoolean(key)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetBoolean_String_Boolean() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - boolean value = true; - boolean def = false; - - section.set(key, value); - - assertEquals(value, section.getBoolean(key, def)); - assertEquals(def, section.getBoolean("doesntExist", def)); - } - - @Test - public void testIsBoolean() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - boolean value = true; - - section.set(key, value); - - assertTrue(section.isBoolean(key)); - assertFalse(section.isBoolean("doesntExist")); - } - - @Test - public void testGetDouble_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - double value = Double.MAX_VALUE; - - section.set(key, value); - - assertEquals(value, section.getDouble(key), 1); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetDoubleFromInt() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - double value = 123; - - section.set(key, (int) value); - - assertEquals(value, section.getDouble(key), 1); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetDouble_String_Double() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - double value = Double.MAX_VALUE; - double def = Double.MIN_VALUE; - - section.set(key, value); - - assertEquals(value, section.getDouble(key, def), 1); - assertEquals(def, section.getDouble("doesntExist", def), 1); - } - - @Test - public void testIsDouble() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - double value = Double.MAX_VALUE; - - section.set(key, value); - - assertTrue(section.isDouble(key)); - assertFalse(section.isDouble("doesntExist")); - } - - @Test - public void testGetLong_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - long value = Long.MAX_VALUE; - - section.set(key, value); - - assertEquals(value, section.getLong(key)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetLong_String_Long() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - long value = Long.MAX_VALUE; - long def = Long.MIN_VALUE; - - section.set(key, value); - - assertEquals(value, section.getLong(key, def)); - assertEquals(def, section.getLong("doesntExist", def)); - } - - @Test - public void testIsLong() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - long value = Long.MAX_VALUE; - - section.set(key, value); - - assertTrue(section.isLong(key)); - assertFalse(section.isLong("doesntExist")); - } - - @Test - public void testGetList_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - Map map = new HashMap(); - - map.put("one", 1); - map.put("two", "two"); - map.put("three", 3.14); - - List value = Arrays.asList("One", "Two", "Three", 4, "5", 6.0, true, "false", map); - - section.set(key, value); - - assertEquals(value, section.getList(key)); - assertEquals(Arrays.asList((Object) "One", "Two", "Three", "4", "5", "6.0", "true", "false"), section.getStringList(key)); - assertEquals(Arrays.asList((Object) 4, 5, 6), section.getIntegerList(key)); - assertEquals(Arrays.asList((Object) true, false), section.getBooleanList(key)); - assertEquals(Arrays.asList((Object) 4.0, 5.0, 6.0), section.getDoubleList(key)); - assertEquals(Arrays.asList((Object) 4.0f, 5.0f, 6.0f), section.getFloatList(key)); - assertEquals(Arrays.asList((Object) 4l, 5l, 6l), section.getLongList(key)); - assertEquals(Arrays.asList((Object) (byte) 4, (byte) 5, (byte) 6), section.getByteList(key)); - assertEquals(Arrays.asList((Object) (short) 4, (short) 5, (short) 6), section.getShortList(key)); - assertEquals(map, section.getMapList(key).get(0)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetList_String_List() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - List value = Arrays.asList("One", "Two", "Three"); - List def = Arrays.asList("A", "B", "C"); - - section.set(key, value); - - assertEquals(value, section.getList(key, def)); - assertEquals(def, section.getList("doesntExist", def)); - } - - @Test - public void testIsList() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - List value = Arrays.asList("One", "Two", "Three"); - - section.set(key, value); - - assertTrue(section.isList(key)); - assertFalse(section.isList("doesntExist")); - } - - @Test - public void testGetObject_String_Class() { - ConfigurationSection section = getConfigurationSection(); - - section.set("set", Integer.valueOf(1)); - section.addDefault("default", Integer.valueOf(2)); - section.addDefault("defaultAndSet", Boolean.TRUE); - section.set("defaultAndSet", Integer.valueOf(3)); - - assertEquals(Integer.valueOf(1), section.getObject("set", Integer.class)); - assertNull(section.getObject("set", Boolean.class)); - assertEquals(Integer.valueOf(2), section.getObject("default", Number.class)); - assertNull(section.getObject("default", Boolean.class)); - assertEquals(Integer.valueOf(3), section.getObject("defaultAndSet", Integer.class)); - assertEquals(Boolean.TRUE, section.getObject("defaultAndSet", Boolean.class)); - assertEquals(Integer.valueOf(3), section.getObject("defaultAndSet", Object.class)); - assertNull(section.getObject("defaultAndSet", String.class)); - assertNull(section.getObject("doesntExist", Boolean.class)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetObject_String_Class_T() { - ConfigurationSection section = getConfigurationSection(); - - section.set("set", Integer.valueOf(1)); - section.addDefault("default", Integer.valueOf(2)); - - assertEquals(Integer.valueOf(1), section.getObject("set", Integer.class, null)); - assertEquals(Integer.valueOf(1), section.getObject("set", Integer.class, Integer.valueOf(4))); - assertNull(section.getObject("set", Boolean.class, null)); - assertNull(section.getObject("default", Integer.class, null)); - assertNull(section.getObject("doesntExist", Boolean.class, null)); - assertEquals(Boolean.TRUE, section.getObject("doesntExist", Boolean.class, Boolean.TRUE)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetVector_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - Vector value = new Vector(Double.MIN_VALUE, Double.MAX_VALUE, 5); - - section.set(key, value); - - assertEquals(value, section.getVector(key)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetVector_String_Vector() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - Vector value = new Vector(Double.MIN_VALUE, Double.MAX_VALUE, 5); - Vector def = new Vector(100, Double.MIN_VALUE, Double.MAX_VALUE); - - section.set(key, value); - - assertEquals(value, section.getVector(key, def)); - assertEquals(def, section.getVector("doesntExist", def)); - } - - @Test - public void testIsVector() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - Vector value = new Vector(Double.MIN_VALUE, Double.MAX_VALUE, 5); - - section.set(key, value); - - assertTrue(section.isVector(key)); - assertFalse(section.isVector("doesntExist")); - } - - @Test - public void testGetItemStack_String() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - ItemStack value = new ItemStack(Material.ACACIA_WOOD, 50); - - section.set(key, value); - - assertEquals(value, section.getItemStack(key)); - assertNull(section.getString("doesntExist")); - } - - @Test - public void testGetItemStack_String_ItemStack() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - ItemStack value = new ItemStack(Material.ACACIA_WOOD, 50); - ItemStack def = new ItemStack(Material.STONE, 1); - - section.set(key, value); - - assertEquals(value, section.getItemStack(key, def)); - assertEquals(def, section.getItemStack("doesntExist", def)); - } - - @Test - public void testIsItemStack() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - ItemStack value = new ItemStack(Material.ACACIA_WOOD, 50); - - section.set(key, value); - - assertTrue(section.isItemStack(key)); - assertFalse(section.isItemStack("doesntExist")); - } - - @Test - public void testGetConfigurationSection() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - - ConfigurationSection subsection = section.createSection(key); - - assertEquals(subsection, section.getConfigurationSection(key)); - } - - @Test - public void testIsConfigurationSection() { - ConfigurationSection section = getConfigurationSection(); - String key = "exists"; - - section.createSection(key); - - assertTrue(section.isConfigurationSection(key)); - assertFalse(section.isConfigurationSection("doesntExist")); - } - - public enum TestEnum { - HELLO, - WORLD, - BANANAS - } -} \ No newline at end of file diff --git a/api/src/test/java/org/bukkit/configuration/ConfigurationTest.java b/api/src/test/java/org/bukkit/configuration/ConfigurationTest.java deleted file mode 100644 index e187d1500..000000000 --- a/api/src/test/java/org/bukkit/configuration/ConfigurationTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.bukkit.configuration; - -import java.util.LinkedHashMap; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import org.bukkit.util.Vector; -import org.junit.Test; -import static org.junit.Assert.*; - -public abstract class ConfigurationTest { - public abstract Configuration getConfig(); - - public Map getTestValues() { - HashMap result = new LinkedHashMap(); - - result.put("integer", Integer.MIN_VALUE); - result.put("string", "String Value"); - result.put("long", Long.MAX_VALUE); - result.put("true-boolean", true); - result.put("false-boolean", false); - result.put("vector", new Vector(12345.67, 64, -12345.6789)); - result.put("list", Arrays.asList(1, 2, 3, 4, 5)); - result.put("42", "The Answer"); - - return result; - } - - /** - * Test of addDefault method, of class Configuration. - */ - @Test - public void testAddDefault() { - Configuration config = getConfig(); - Map values = getTestValues(); - - for (Map.Entry entry : values.entrySet()) { - String path = entry.getKey(); - Object object = entry.getValue(); - - config.addDefault(path, object); - - assertEquals(object, config.get(path)); - assertTrue(config.contains(path)); - assertFalse(config.isSet(path)); - assertTrue(config.getDefaults().isSet(path)); - } - } - - /** - * Test of addDefaults method, of class Configuration. - */ - @Test - public void testAddDefaults_Map() { - Configuration config = getConfig(); - Map values = getTestValues(); - - config.addDefaults(values); - - for (Map.Entry entry : values.entrySet()) { - String path = entry.getKey(); - Object object = entry.getValue(); - - assertEquals(object, config.get(path)); - assertTrue(config.contains(path)); - assertFalse(config.isSet(path)); - assertTrue(config.getDefaults().isSet(path)); - } - } - - /** - * Test of addDefaults method, of class Configuration. - */ - @Test - public void testAddDefaults_Configuration() { - Configuration config = getConfig(); - Map values = getTestValues(); - Configuration defaults = getConfig(); - - for (Map.Entry entry : values.entrySet()) { - defaults.set(entry.getKey(), entry.getValue()); - } - - config.addDefaults(defaults); - - for (Map.Entry entry : values.entrySet()) { - String path = entry.getKey(); - Object object = entry.getValue(); - - assertEquals(object, config.get(path)); - assertTrue(config.contains(path)); - assertFalse(config.isSet(path)); - assertTrue(config.getDefaults().isSet(path)); - } - } - - /** - * Test of setDefaults method, of class Configuration. - */ - @Test - public void testSetDefaults() { - Configuration config = getConfig(); - Map values = getTestValues(); - Configuration defaults = getConfig(); - - for (Map.Entry entry : values.entrySet()) { - defaults.set(entry.getKey(), entry.getValue()); - } - - config.setDefaults(defaults); - - for (Map.Entry entry : values.entrySet()) { - String path = entry.getKey(); - Object object = entry.getValue(); - - assertEquals(object, config.get(path)); - assertTrue(config.contains(path)); - assertFalse(config.isSet(path)); - assertTrue(config.getDefaults().isSet(path)); - } - } - - /** - * Test creation of ConfigurationSection - */ - @Test - public void testCreateSection() { - Configuration config = getConfig(); - - Set set = new HashSet(); - set.add("this"); - set.add("this.test.sub"); - set.add("this.test"); - set.add("this.test.other"); - - config.createSection("this.test.sub"); - config.createSection("this.test.other"); - - assertEquals(set, config.getKeys(true)); - } - - /** - * Test of getDefaults method, of class Configuration. - */ - @Test - public void testGetDefaults() { - Configuration config = getConfig(); - Configuration defaults = getConfig(); - - config.setDefaults(defaults); - - assertEquals(defaults, config.getDefaults()); - } -} \ No newline at end of file diff --git a/api/src/test/java/org/bukkit/configuration/MemoryConfigurationTest.java b/api/src/test/java/org/bukkit/configuration/MemoryConfigurationTest.java deleted file mode 100644 index 3de0ce926..000000000 --- a/api/src/test/java/org/bukkit/configuration/MemoryConfigurationTest.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.configuration; - -public class MemoryConfigurationTest extends ConfigurationTest { - @Override - public Configuration getConfig() { - return new MemoryConfiguration(); - } -} diff --git a/api/src/test/java/org/bukkit/configuration/MemorySectionTest.java b/api/src/test/java/org/bukkit/configuration/MemorySectionTest.java deleted file mode 100644 index be7768abe..000000000 --- a/api/src/test/java/org/bukkit/configuration/MemorySectionTest.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.bukkit.configuration; - -public class MemorySectionTest extends ConfigurationSectionTest { - @Override - public ConfigurationSection getConfigurationSection() { - return new MemoryConfiguration().createSection("section"); - } -} diff --git a/api/src/test/java/org/bukkit/configuration/file/FileConfigurationTest.java b/api/src/test/java/org/bukkit/configuration/file/FileConfigurationTest.java deleted file mode 100644 index ce0c2e5a4..000000000 --- a/api/src/test/java/org/bukkit/configuration/file/FileConfigurationTest.java +++ /dev/null @@ -1,209 +0,0 @@ -package org.bukkit.configuration.file; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.Map; -import org.bukkit.configuration.MemoryConfigurationTest; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import static org.junit.Assert.*; - -public abstract class FileConfigurationTest extends MemoryConfigurationTest { - @Rule - public TemporaryFolder testFolder = new TemporaryFolder(); - - @Override - public abstract FileConfiguration getConfig(); - - public abstract String getTestValuesString(); - - public abstract String getTestHeaderInput(); - - public abstract String getTestHeaderResult(); - - @Test - public void testSave_File() throws Exception { - FileConfiguration config = getConfig(); - File file = testFolder.newFile("test.config"); - - for (Map.Entry entry : getTestValues().entrySet()) { - config.set(entry.getKey(), entry.getValue()); - } - - config.save(file); - - assertTrue(file.isFile()); - } - - @Test - public void testSave_String() throws Exception { - FileConfiguration config = getConfig(); - File file = testFolder.newFile("test.config"); - - for (Map.Entry entry : getTestValues().entrySet()) { - config.set(entry.getKey(), entry.getValue()); - } - - config.save(file.getAbsolutePath()); - - assertTrue(file.isFile()); - } - - @Test - public void testSaveToString() { - FileConfiguration config = getConfig(); - - for (Map.Entry entry : getTestValues().entrySet()) { - config.set(entry.getKey(), entry.getValue()); - } - - String result = config.saveToString(); - String expected = getTestValuesString(); - - assertEquals(expected, result); - } - - @Test - public void testLoad_File() throws Exception { - FileConfiguration config = getConfig(); - File file = testFolder.newFile("test.config"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - String saved = getTestValuesString(); - Map values = getTestValues(); - - try { - writer.write(saved); - } finally { - writer.close(); - } - - config.load(file); - - for (Map.Entry entry : values.entrySet()) { - assertEquals(entry.getValue(), config.get(entry.getKey())); - } - - assertEquals(values.keySet(), config.getKeys(true)); - } - - @Test - public void testLoad_String() throws Exception { - FileConfiguration config = getConfig(); - File file = testFolder.newFile("test.config"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - String saved = getTestValuesString(); - Map values = getTestValues(); - - try { - writer.write(saved); - } finally { - writer.close(); - } - - config.load(file.getAbsolutePath()); - - for (Map.Entry entry : values.entrySet()) { - assertEquals(entry.getValue(), config.get(entry.getKey())); - } - - assertEquals(values.keySet(), config.getKeys(true)); - } - - @Test - public void testLoadFromString() throws Exception { - FileConfiguration config = getConfig(); - Map values = getTestValues(); - String saved = getTestValuesString(); - - config.loadFromString(saved); - - for (Map.Entry entry : values.entrySet()) { - assertEquals(entry.getValue(), config.get(entry.getKey())); - } - - assertEquals(values.keySet(), config.getKeys(true)); - assertEquals(saved, config.saveToString()); - } - - @Test - public void testSaveToStringWithHeader() { - FileConfiguration config = getConfig(); - config.options().header(getTestHeaderInput()); - - for (Map.Entry entry : getTestValues().entrySet()) { - config.set(entry.getKey(), entry.getValue()); - } - - String result = config.saveToString(); - String expected = getTestHeaderResult() + "\n" + getTestValuesString(); - - assertEquals(expected, result); - } - - @Test - public void testParseHeader() throws Exception { - FileConfiguration config = getConfig(); - Map values = getTestValues(); - String saved = getTestValuesString(); - String header = getTestHeaderResult(); - String expected = getTestHeaderInput(); - - config.loadFromString(header + "\n" + saved); - - assertEquals(expected, config.options().header()); - - for (Map.Entry entry : values.entrySet()) { - assertEquals(entry.getValue(), config.get(entry.getKey())); - } - - assertEquals(values.keySet(), config.getKeys(true)); - assertEquals(header + "\n" + saved, config.saveToString()); - } - - @Test - public void testCopyHeader() throws Exception { - FileConfiguration config = getConfig(); - FileConfiguration defaults = getConfig(); - Map values = getTestValues(); - String saved = getTestValuesString(); - String header = getTestHeaderResult(); - String expected = getTestHeaderInput(); - - defaults.loadFromString(header); - config.loadFromString(saved); - config.setDefaults(defaults); - - assertNull(config.options().header()); - assertEquals(expected, defaults.options().header()); - - for (Map.Entry entry : values.entrySet()) { - assertEquals(entry.getValue(), config.get(entry.getKey())); - } - - assertEquals(values.keySet(), config.getKeys(true)); - assertEquals(header + "\n" + saved, config.saveToString()); - - config = getConfig(); - config.loadFromString(getTestHeaderResult() + saved); - assertEquals(getTestHeaderResult() + saved, config.saveToString()); - } - - @Test - public void testReloadEmptyConfig() throws Exception { - FileConfiguration config = getConfig(); - - assertEquals("", config.saveToString()); - - config = getConfig(); - config.loadFromString(""); - - assertEquals("", config.saveToString()); - - config = getConfig(); - config.loadFromString("\n\n"); // Should trim the first newlines of a header - - assertEquals("", config.saveToString()); - } -} diff --git a/api/src/test/java/org/bukkit/configuration/file/YamlConfigurationTest.java b/api/src/test/java/org/bukkit/configuration/file/YamlConfigurationTest.java deleted file mode 100644 index aa83af320..000000000 --- a/api/src/test/java/org/bukkit/configuration/file/YamlConfigurationTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.configuration.file; - -import org.junit.Test; -import static org.junit.Assert.*; - -public class YamlConfigurationTest extends FileConfigurationTest { - - @Override - public YamlConfiguration getConfig() { - return new YamlConfiguration(); - } - - @Override - public String getTestHeaderInput() { - return "This is a sample\nheader.\n\nNewline above should be commented.\n\n"; - } - - @Override - public String getTestHeaderResult() { - return "# This is a sample\n# header.\n# \n# Newline above should be commented.\n\n"; - } - - @Override - public String getTestValuesString() { - return "integer: -2147483648\n" + - "string: String Value\n" + - "long: 9223372036854775807\n" + - "true-boolean: true\n" + - "false-boolean: false\n" + - "vector:\n" + - " ==: Vector\n" + - " x: 12345.67\n" + - " y: 64.0\n" + - " z: -12345.6789\n" + - "list:\n" + - "- 1\n" + - "- 2\n" + - "- 3\n" + - "- 4\n" + - "- 5\n" + - "'42': The Answer\n"; - } - - @Test - public void testSaveToStringWithIndent() { - YamlConfiguration config = getConfig(); - config.options().indent(9); - - config.set("section.key", 1); - - String result = config.saveToString(); - String expected = "section:\n key: 1\n"; - - assertEquals(expected, result); - } -} diff --git a/api/src/test/java/org/bukkit/conversations/ConversationContextTest.java b/api/src/test/java/org/bukkit/conversations/ConversationContextTest.java deleted file mode 100644 index dfc462b51..000000000 --- a/api/src/test/java/org/bukkit/conversations/ConversationContextTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.conversations; - -import org.junit.Test; -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; - -/** - */ -public class ConversationContextTest { - @Test - public void TestFromWhom() { - Conversable conversable = new FakeConversable(); - ConversationContext context = new ConversationContext(null, conversable, new HashMap()); - assertEquals(conversable, context.getForWhom()); - } - - @Test - public void TestPlugin() { - Conversable conversable = new FakeConversable(); - ConversationContext context = new ConversationContext(null, conversable, new HashMap()); - assertEquals(null, context.getPlugin()); - } - - @Test - public void TestSessionData() { - Conversable conversable = new FakeConversable(); - Map session = new HashMap(); - session.put("key", "value"); - ConversationContext context = new ConversationContext(null, conversable, session); - assertEquals("value", context.getSessionData("key")); - } -} diff --git a/api/src/test/java/org/bukkit/conversations/ConversationTest.java b/api/src/test/java/org/bukkit/conversations/ConversationTest.java deleted file mode 100644 index 544f1f3c2..000000000 --- a/api/src/test/java/org/bukkit/conversations/ConversationTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.bukkit.conversations; - -import org.bukkit.plugin.TestPlugin; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - */ -public class ConversationTest { - - @Test - public void testBaseConversationFlow() { - FakeConversable forWhom = new FakeConversable(); - Conversation conversation = new Conversation(null, forWhom, new FirstPrompt()); - - // Conversation not yet begun - assertNull(forWhom.lastSentMessage); - assertEquals(conversation.getForWhom(), forWhom); - assertTrue(conversation.isModal()); - - // Begin the conversation - conversation.begin(); - assertEquals("FirstPrompt", forWhom.lastSentMessage); - assertEquals(conversation, forWhom.begunConversation); - - // Send the first input - conversation.acceptInput("FirstInput"); - assertEquals("SecondPrompt", forWhom.lastSentMessage); - assertEquals(conversation, forWhom.abandonedConverstion); - } - - @Test - public void testConversationFactory() { - FakeConversable forWhom = new FakeConversable(); - NullConversationPrefix prefix = new NullConversationPrefix(); - ConversationFactory factory = new ConversationFactory(new TestPlugin("Test")) - .withFirstPrompt(new FirstPrompt()) - .withModality(false) - .withPrefix(prefix); - Conversation conversation = factory.buildConversation(forWhom); - - // Conversation not yet begun - assertNull(forWhom.lastSentMessage); - assertEquals(conversation.getForWhom(), forWhom); - assertFalse(conversation.isModal()); - assertEquals(conversation.getPrefix(), prefix); - - // Begin the conversation - conversation.begin(); - assertEquals("FirstPrompt", forWhom.lastSentMessage); - assertEquals(conversation, forWhom.begunConversation); - - // Send the first input - conversation.acceptInput("FirstInput"); - assertEquals("SecondPrompt", forWhom.lastSentMessage); - assertEquals(conversation, forWhom.abandonedConverstion); - } - - @Test - public void testEscapeSequence() { - FakeConversable forWhom = new FakeConversable(); - Conversation conversation = new Conversation(null, forWhom, new FirstPrompt()); - conversation.addConversationCanceller(new ExactMatchConversationCanceller("bananas")); - - // Begin the conversation - conversation.begin(); - assertEquals("FirstPrompt", forWhom.lastSentMessage); - assertEquals(conversation, forWhom.begunConversation); - - // Send the first input - conversation.acceptInput("bananas"); - assertEquals("bananas", forWhom.lastSentMessage); - assertEquals(conversation, forWhom.abandonedConverstion); - } - - @Test - public void testNotPlayer() { - FakeConversable forWhom = new FakeConversable(); - ConversationFactory factory = new ConversationFactory(new TestPlugin("Test")) - .thatExcludesNonPlayersWithMessage("bye"); - Conversation conversation = factory.buildConversation(forWhom); - - // Begin the conversation - conversation.begin(); - assertEquals("bye", forWhom.lastSentMessage); - assertEquals(conversation, forWhom.begunConversation); - assertEquals(conversation, forWhom.abandonedConverstion); - } - - private class FirstPrompt extends StringPrompt { - - public String getPromptText(ConversationContext context) { - return "FirstPrompt"; - } - - public Prompt acceptInput(ConversationContext context, String input) { - assertEquals("FirstInput", input); - context.setSessionData("data", 10); - return new SecondPrompt(); - } - } - - private class SecondPrompt extends MessagePrompt { - - @Override - protected Prompt getNextPrompt(ConversationContext context) { - return Prompt.END_OF_CONVERSATION; - } - - public String getPromptText(ConversationContext context) { - // Assert that session data passes from one prompt to the next - assertEquals(context.getSessionData("data"), 10); - return "SecondPrompt"; - } - } -} diff --git a/api/src/test/java/org/bukkit/conversations/FakeConversable.java b/api/src/test/java/org/bukkit/conversations/FakeConversable.java deleted file mode 100644 index 87fb31139..000000000 --- a/api/src/test/java/org/bukkit/conversations/FakeConversable.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.bukkit.conversations; - -import org.bukkit.Server; -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 FakeConversable implements Conversable { - public String lastSentMessage; - public Conversation begunConversation; - public Conversation abandonedConverstion; - public ConversationAbandonedEvent abandonedConversationEvent; - - public boolean isConversing() { - return false; - } - - public void acceptConversationInput(String input) { - - } - - public boolean beginConversation(Conversation conversation) { - begunConversation = conversation; - conversation.outputNextPrompt(); - return true; - } - - public void abandonConversation(Conversation conversation) { - abandonedConverstion = conversation; - } - - public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { - abandonedConverstion = conversation; - abandonedConversationEvent = details; - } - - public void sendRawMessage(String message) { - lastSentMessage = message; - } - - public Server getServer() { - return null; - } - - public String getName() { - return null; - } - - public boolean isPermissionSet(String name) { - return false; - } - - public boolean isPermissionSet(Permission perm) { - return false; - } - - public boolean hasPermission(String name) { - return false; - } - - public boolean hasPermission(Permission perm) { - return false; - } - - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return null; - } - - public PermissionAttachment addAttachment(Plugin plugin) { - return null; - } - - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { - return null; - } - - public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return null; - } - - public void removeAttachment(PermissionAttachment attachment) { - - } - - public void recalculatePermissions() { - - } - - public Set getEffectivePermissions() { - return null; - } - - public boolean isOp() { - return false; - } - - public void setOp(boolean value) { - - } -} diff --git a/api/src/test/java/org/bukkit/conversations/ValidatingPromptTest.java b/api/src/test/java/org/bukkit/conversations/ValidatingPromptTest.java deleted file mode 100644 index d1c0f42c0..000000000 --- a/api/src/test/java/org/bukkit/conversations/ValidatingPromptTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.bukkit.conversations; - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - */ -public class ValidatingPromptTest { - - @Test - public void TestBooleanPrompt() { - TestBooleanPrompt prompt = new TestBooleanPrompt(); - assertTrue(prompt.isInputValid(null, "true")); - assertFalse(prompt.isInputValid(null, "bananas")); - prompt.acceptInput(null, "true"); - assertTrue(prompt.result); - prompt.acceptInput(null, "no"); - assertFalse(prompt.result); - } - - @Test - public void TestFixedSetPrompt() { - TestFixedSetPrompt prompt = new TestFixedSetPrompt("foo", "bar"); - assertTrue(prompt.isInputValid(null, "foo")); - assertFalse(prompt.isInputValid(null, "cheese")); - prompt.acceptInput(null, "foo"); - assertEquals("foo", prompt.result); - } - - @Test - public void TestNumericPrompt() { - TestNumericPrompt prompt = new TestNumericPrompt(); - assertTrue(prompt.isInputValid(null, "1010220")); - assertFalse(prompt.isInputValid(null, "tomato")); - prompt.acceptInput(null, "1010220"); - assertEquals(1010220, prompt.result); - } - - @Test - public void TestRegexPrompt() { - TestRegexPrompt prompt = new TestRegexPrompt("a.c"); - assertTrue(prompt.isInputValid(null, "abc")); - assertTrue(prompt.isInputValid(null, "axc")); - assertFalse(prompt.isInputValid(null, "xyz")); - prompt.acceptInput(null, "abc"); - assertEquals("abc", prompt.result); - } - - //TODO: TestPlayerNamePrompt() - - private class TestBooleanPrompt extends BooleanPrompt { - public boolean result; - - @Override - protected Prompt acceptValidatedInput(ConversationContext context, boolean input) { - result = input; - return null; - } - - public String getPromptText(ConversationContext context) { - return null; - } - } - - private class TestFixedSetPrompt extends FixedSetPrompt { - public String result; - - public TestFixedSetPrompt(String... fixedSet) { - super(fixedSet); - } - - @Override - protected Prompt acceptValidatedInput(ConversationContext context, String input) { - result = input; - return null; - } - - public String getPromptText(ConversationContext context) { - return null; - } - } - - private class TestNumericPrompt extends NumericPrompt { - public Number result; - - @Override - protected Prompt acceptValidatedInput(ConversationContext context, Number input) { - result = input; - return null; - } - - public String getPromptText(ConversationContext context) { - return null; - } - } - - private class TestRegexPrompt extends RegexPrompt { - public String result; - - public TestRegexPrompt(String pattern) { - super(pattern); - } - - @Override - protected Prompt acceptValidatedInput(ConversationContext context, String input) { - result = input; - return null; - } - - public String getPromptText(ConversationContext context) { - return null; - } - } -} diff --git a/api/src/test/java/org/bukkit/event/PlayerChatTabCompleteEventTest.java b/api/src/test/java/org/bukkit/event/PlayerChatTabCompleteEventTest.java deleted file mode 100644 index 619bf30b0..000000000 --- a/api/src/test/java/org/bukkit/event/PlayerChatTabCompleteEventTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.event; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import org.bukkit.event.player.PlayerChatTabCompleteEvent; -import org.bukkit.plugin.messaging.TestPlayer; -import org.junit.Test; - -import com.google.common.collect.ImmutableList; - -public class PlayerChatTabCompleteEventTest { - - @Test - public void testGetLastToken() { - assertThat(getToken("Hello everyone!"), is("everyone!")); - assertThat(getToken(" welcome to the show..."), is("show...")); - assertThat(getToken("The whitespace is here "), is("")); - assertThat(getToken("Too much whitespace is here "), is("")); - assertThat(getToken("The_whitespace_is_missing"), is("The_whitespace_is_missing")); - assertThat(getToken(""), is("")); - assertThat(getToken(" "), is("")); - } - - private String getToken(String message) { - return new PlayerChatTabCompleteEvent(TestPlayer.getInstance(), message, ImmutableList.of()).getLastToken(); - } -} diff --git a/api/src/test/java/org/bukkit/event/SyntheticEventTest.java b/api/src/test/java/org/bukkit/event/SyntheticEventTest.java deleted file mode 100644 index 04b1b9840..000000000 --- a/api/src/test/java/org/bukkit/event/SyntheticEventTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bukkit.event; - -import org.bukkit.TestServer; -import org.bukkit.plugin.PluginLoader; -import org.bukkit.plugin.SimplePluginManager; -import org.bukkit.plugin.TestPlugin; -import org.bukkit.plugin.java.JavaPluginLoader; -import org.junit.Assert; -import org.junit.Test; - -public class SyntheticEventTest { - @SuppressWarnings("deprecation") - @Test - public void test() { - final JavaPluginLoader loader = new JavaPluginLoader(TestServer.getInstance()); - TestPlugin plugin = new TestPlugin(getClass().getName()) { - @Override - public PluginLoader getPluginLoader() { - return loader; - } - }; - SimplePluginManager pluginManager = new SimplePluginManager(TestServer.getInstance(), null); - - TestEvent event = new TestEvent(false); - Impl impl = new Impl(); - - pluginManager.registerEvents(impl, plugin); - pluginManager.callEvent(event); - - Assert.assertEquals(1, impl.callCount); - } - - public static abstract class Base implements Listener { - int callCount = 0; - - public void accept(E evt) { - callCount++; - } - } - - public static class Impl extends Base { - @Override - @EventHandler - public void accept(TestEvent evt) { - super.accept(evt); - } - } -} diff --git a/api/src/test/java/org/bukkit/event/TestEvent.java b/api/src/test/java/org/bukkit/event/TestEvent.java deleted file mode 100644 index 25904f5f8..000000000 --- a/api/src/test/java/org/bukkit/event/TestEvent.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.event; - - -public class TestEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - - public TestEvent(boolean async) { - super(async); - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/api/src/test/java/org/bukkit/materials/MaterialDataTest.java b/api/src/test/java/org/bukkit/materials/MaterialDataTest.java deleted file mode 100644 index eb55c02e8..000000000 --- a/api/src/test/java/org/bukkit/materials/MaterialDataTest.java +++ /dev/null @@ -1,433 +0,0 @@ -package org.bukkit.materials; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import org.bukkit.CropState; -import org.bukkit.Material; -import org.bukkit.NetherWartsState; -import org.bukkit.TreeSpecies; -import org.bukkit.block.BlockFace; -import org.bukkit.material.Crops; -import org.bukkit.material.Comparator; -import org.bukkit.material.Diode; -import org.bukkit.material.Door; -import org.bukkit.material.Hopper; -import org.bukkit.material.Leaves; -import org.bukkit.material.Mushroom; -import org.bukkit.material.NetherWarts; -import org.bukkit.material.Sapling; -import org.bukkit.material.Tree; -import org.bukkit.material.Wood; -import org.bukkit.material.WoodenStep; -import org.bukkit.material.types.MushroomBlockTexture; -import org.junit.Test; - -public class MaterialDataTest { - - @Test - public void testDoor() - { - @SuppressWarnings("deprecation") - Door door = new Door(); - assertThat("Constructed with default door type",door.getItemType(),equalTo(Material.LEGACY_WOODEN_DOOR)); - assertThat("Constructed with default top or bottom",door.isTopHalf(),equalTo(false)); - assertThat("Constructed with default direction",door.getFacing(),equalTo(BlockFace.WEST)); - assertThat("Constructed with default open state",door.isOpen(),equalTo(false)); - - Material[] types = new Material[] { Material.LEGACY_WOODEN_DOOR, - Material.LEGACY_IRON_DOOR_BLOCK, Material.LEGACY_SPRUCE_DOOR, - Material.LEGACY_BIRCH_DOOR, Material.LEGACY_JUNGLE_DOOR, - Material.LEGACY_ACACIA_DOOR, Material.LEGACY_DARK_OAK_DOOR }; - BlockFace[] directions = new BlockFace[] { BlockFace.WEST, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH }; - boolean[] openStates = new boolean[] {false, true}; - boolean[] hingeStates = new boolean[] {false, true}; - for(Material type : types) - { - // Test bottom half - for(BlockFace facing : directions) - { - door = new Door(type,facing); - assertThat("Constructed with correct door type",door.getItemType(),equalTo(type)); - assertThat("Constructed with default top or bottom",door.isTopHalf(),equalTo(false)); - assertThat("Constructed with correct direction",door.getFacing(),equalTo(facing)); - assertThat("Constructed with default open state",door.isOpen(),equalTo(false)); - - for(boolean openState : openStates) - { - door = new Door(type,facing,openState); - assertThat("Constructed with correct door type",door.getItemType(),equalTo(type)); - assertThat("Constructed with default top or bottom",door.isTopHalf(),equalTo(false)); - assertThat("Constructed with correct direction",door.getFacing(),equalTo(facing)); - assertThat("Constructed with correct open state",door.isOpen(),equalTo(openState)); - } - } - - // Test top half - for(boolean hingeState : hingeStates) - { - door = new Door(type,hingeState); - assertThat("Constructed with correct door type",door.getItemType(),equalTo(type)); - assertThat("Constructed with default top or bottom",door.isTopHalf(),equalTo(true)); - assertThat("Constructed with correct direction",door.getHinge(),equalTo(hingeState)); - } - } - } - - @Test - public void testWood() { - Wood wood = new Wood(); - assertThat("Constructed with default wood type", wood.getItemType(), equalTo(Material.LEGACY_WOOD)); - assertThat("Constructed with default tree species", wood.getSpecies(), equalTo(TreeSpecies.GENERIC)); - - TreeSpecies[] allSpecies = TreeSpecies.values(); - for (TreeSpecies species : allSpecies) { - wood = new Wood(species); - assertThat("Constructed with default wood type", wood.getItemType(), equalTo(Material.LEGACY_WOOD)); - assertThat("Constructed with correct tree species", wood.getSpecies(), equalTo(species)); - } - - Material[] types = new Material[]{Material.LEGACY_WOOD, Material.LEGACY_WOOD_DOUBLE_STEP}; - for (Material type : types) { - wood = new Wood(type); - assertThat("Constructed with correct wood type", wood.getItemType(), equalTo(type)); - assertThat("Constructed with default tree species", wood.getSpecies(), equalTo(TreeSpecies.GENERIC)); - - for (TreeSpecies species : allSpecies) { - wood = new Wood(type, species); - assertThat("Constructed with correct wood type", wood.getItemType(), equalTo(type)); - assertThat("Constructed with correct tree species", wood.getSpecies(), equalTo(species)); - } - } - } - - @Test - public void testTree() { - Tree tree = new Tree(); - assertThat("Constructed with default tree type", tree.getItemType(), equalTo(Material.LEGACY_LOG)); - assertThat("Constructed with default tree species", tree.getSpecies(), equalTo(TreeSpecies.GENERIC)); - assertThat("Constructed with default direction", tree.getDirection(), equalTo(BlockFace.UP)); - - tree = new Tree(Material.LEGACY_LOG); - assertThat("Constructed with correct tree type", tree.getItemType(), equalTo(Material.LEGACY_LOG)); - assertThat("Constructed with default tree species", tree.getSpecies(), equalTo(TreeSpecies.GENERIC)); - assertThat("Constructed with default direction", tree.getDirection(), equalTo(BlockFace.UP)); - - Material[] types = new Material[]{Material.LEGACY_LOG, Material.LEGACY_LOG_2}; - TreeSpecies[][] allSpecies = new TreeSpecies[][]{ - {TreeSpecies.GENERIC, TreeSpecies.REDWOOD, TreeSpecies.BIRCH, TreeSpecies.JUNGLE}, - {TreeSpecies.ACACIA, TreeSpecies.DARK_OAK} - }; - BlockFace[] allDirections = new BlockFace[]{BlockFace.UP, BlockFace.WEST, BlockFace.NORTH, BlockFace.SELF}; - for (int t = 0; t < types.length; t++) { - for (TreeSpecies species : allSpecies[t]) { - tree = new Tree(types[t], species); - assertThat("Constructed with correct tree type", tree.getItemType(), equalTo(types[t])); - assertThat("Constructed with correct tree species", tree.getSpecies(), equalTo(species)); - assertThat("Constructed with default direction", tree.getDirection(), equalTo(BlockFace.UP)); - - // check item type is fixed automatically for invalid type-species combo - tree = new Tree(types[types.length - 1 - t], species); - assertThat("Constructed with fixed tree type", tree.getItemType(), equalTo(types[t])); - assertThat("Constructed with correct tree species", tree.getSpecies(), equalTo(species)); - assertThat("Constructed with default direction", tree.getDirection(), equalTo(BlockFace.UP)); - for (BlockFace dir : allDirections) { - tree = new Tree(types[t], species, dir); - assertThat("Constructed with correct tree type", tree.getItemType(), equalTo(types[t])); - assertThat("Constructed with correct tree species", tree.getSpecies(), equalTo(species)); - assertThat("Constructed with correct direction", tree.getDirection(), equalTo(dir)); - } - } - } - } - - @Test - public void testLeaves() { - Leaves leaves = new Leaves(); - assertThat("Constructed with default leaf type", leaves.getItemType(), equalTo(Material.LEGACY_LEAVES)); - assertThat("Constructed with default tree species", leaves.getSpecies(), equalTo(TreeSpecies.GENERIC)); - assertThat("Constructed with default decayable", leaves.isDecayable(), equalTo(true)); - assertThat("Constructed with default decaying", leaves.isDecaying(), equalTo(false)); - - leaves = new Leaves(Material.LEGACY_LEAVES); - assertThat("Constructed with correct leaf type", leaves.getItemType(), equalTo(Material.LEGACY_LEAVES)); - assertThat("Constructed with default tree species", leaves.getSpecies(), equalTo(TreeSpecies.GENERIC)); - assertThat("Constructed with default decayable", leaves.isDecayable(), equalTo(true)); - assertThat("Constructed with default decaying", leaves.isDecaying(), equalTo(false)); - - Material[] types = new Material[]{Material.LEGACY_LEAVES, Material.LEGACY_LEAVES_2}; - TreeSpecies[][] allSpecies = new TreeSpecies[][]{ - {TreeSpecies.GENERIC, TreeSpecies.REDWOOD, TreeSpecies.BIRCH, TreeSpecies.JUNGLE}, - {TreeSpecies.ACACIA, TreeSpecies.DARK_OAK} - }; - boolean[] decayable = new boolean[]{true, false}; - boolean[] decaying = new boolean[]{true, false}; - for (int t = 0; t < types.length; t++) { - for (TreeSpecies species : allSpecies[t]) { - leaves = new Leaves(types[t], species); - assertThat("Constructed with correct leaf type", leaves.getItemType(), equalTo(types[t])); - assertThat("Constructed with correct tree species", leaves.getSpecies(), equalTo(species)); - assertThat("Constructed with default decayable", leaves.isDecayable(), equalTo(true)); - assertThat("Constructed with default decaying", leaves.isDecaying(), equalTo(false)); - - // check item type is fixed automatically for invalid type-species combo - leaves = new Leaves(types[types.length - 1 - t], species); - assertThat("Constructed with fixed leaf type", leaves.getItemType(), equalTo(types[t])); - assertThat("Constructed with correct tree species", leaves.getSpecies(), equalTo(species)); - assertThat("Constructed with default decayable", leaves.isDecayable(), equalTo(true)); - assertThat("Constructed with default decaying", leaves.isDecaying(), equalTo(false)); - for (boolean isDecayable : decayable) { - leaves = new Leaves(types[t], species, isDecayable); - assertThat("Constructed with correct wood type", leaves.getItemType(), equalTo(types[t])); - assertThat("Constructed with correct tree species", leaves.getSpecies(), equalTo(species)); - assertThat("Constructed with correct decayable", leaves.isDecayable(), equalTo(isDecayable)); - assertThat("Constructed with default decaying", leaves.isDecaying(), equalTo(false)); - for (boolean isDecaying : decaying) { - leaves = new Leaves(types[t], species, isDecayable); - leaves.setDecaying(isDecaying); - assertThat("Constructed with correct wood type", leaves.getItemType(), equalTo(types[t])); - assertThat("Constructed with correct tree species", leaves.getSpecies(), equalTo(species)); - assertThat("Constructed with correct decayable", leaves.isDecayable(), equalTo(isDecaying || isDecayable)); - assertThat("Constructed with correct decaying", leaves.isDecaying(), equalTo(isDecaying)); - } - } - } - } - } - - @Test - public void testWoodenStep() { - WoodenStep woodenStep = new WoodenStep(); - assertThat("Constructed with default step type", woodenStep.getItemType(), equalTo(Material.LEGACY_WOOD_STEP)); - assertThat("Constructed with default tree species", woodenStep.getSpecies(), equalTo(TreeSpecies.GENERIC)); - assertThat("Constructed with default inversion", woodenStep.isInverted(), equalTo(false)); - - TreeSpecies[] allSpecies = TreeSpecies.values(); - boolean[] inversion = new boolean[]{true, false}; - for (TreeSpecies species : allSpecies) { - woodenStep = new WoodenStep(species); - assertThat("Constructed with default step type", woodenStep.getItemType(), equalTo(Material.LEGACY_WOOD_STEP)); - assertThat("Constructed with correct tree species", woodenStep.getSpecies(), equalTo(species)); - assertThat("Constructed with default inversion", woodenStep.isInverted(), equalTo(false)); - for (boolean isInverted : inversion) { - woodenStep = new WoodenStep(species, isInverted); - assertThat("Constructed with default step type", woodenStep.getItemType(), equalTo(Material.LEGACY_WOOD_STEP)); - assertThat("Constructed with correct tree species", woodenStep.getSpecies(), equalTo(species)); - assertThat("Constructed with correct inversion", woodenStep.isInverted(), equalTo(isInverted)); - } - } - } - - @Test - public void testSapling() { - Sapling sapling = new Sapling(); - assertThat("Constructed with default sapling type", sapling.getItemType(), equalTo(Material.LEGACY_SAPLING)); - assertThat("Constructed with default tree species", sapling.getSpecies(), equalTo(TreeSpecies.GENERIC)); - assertThat("Constructed with default growable", sapling.isInstantGrowable(), equalTo(false)); - - TreeSpecies[] allSpecies = TreeSpecies.values(); - boolean[] growable = new boolean[]{true, false}; - for (TreeSpecies species : allSpecies) { - sapling = new Sapling(species); - assertThat("Constructed with default sapling type", sapling.getItemType(), equalTo(Material.LEGACY_SAPLING)); - assertThat("Constructed with correct tree species", sapling.getSpecies(), equalTo(species)); - assertThat("Constructed with default growable", sapling.isInstantGrowable(), equalTo(false)); - for (boolean isInstantGrowable : growable) { - sapling = new Sapling(species, isInstantGrowable); - assertThat("Constructed with default sapling type", sapling.getItemType(), equalTo(Material.LEGACY_SAPLING)); - assertThat("Constructed with correct tree species", sapling.getSpecies(), equalTo(species)); - assertThat("Constructed with correct growable", sapling.isInstantGrowable(), equalTo(isInstantGrowable)); - } - } - } - - @Test - public void testMushroom() { - Material[] mushroomTypes = new Material[] { Material.LEGACY_HUGE_MUSHROOM_1, Material.LEGACY_HUGE_MUSHROOM_2 }; - BlockFace[] setFaces = new BlockFace[] { BlockFace.SELF, BlockFace.UP, BlockFace.NORTH, - BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH_EAST, BlockFace.NORTH_WEST, - BlockFace.SOUTH_EAST, BlockFace.SOUTH_WEST }; - MushroomBlockTexture[] textures = MushroomBlockTexture.values(); - for (Material type : mushroomTypes) { - Mushroom mushroom = new Mushroom(type); - assertThat("Constructed with correct mushroom type", mushroom.getItemType(), equalTo(type)); - assertThat("Constructed with default pores face", mushroom.getBlockTexture(), equalTo(MushroomBlockTexture.ALL_PORES)); - - for (int f = 0; f < setFaces.length; f++) { - mushroom = new Mushroom(type, setFaces[f]); - assertThat("Constructed with correct mushroom type", mushroom.getItemType(), equalTo(type)); - assertThat("Constructed with correct texture", mushroom.getBlockTexture(), equalTo(MushroomBlockTexture.getCapByFace(setFaces[f]))); - } - - for (MushroomBlockTexture texture : textures) { - mushroom = new Mushroom(type, texture); - assertThat("Constructed with correct mushroom type", mushroom.getItemType(), equalTo(type)); - assertThat("Constructed with correct texture", mushroom.getBlockTexture(), equalTo(texture)); - } - } - } - - @Test - public void testCrops() { - Crops crops = new Crops(); - assertThat("Constructed with default crops type", crops.getItemType(), equalTo(Material.LEGACY_CROPS)); - assertThat("Constructed with default crop state", crops.getState(), equalTo(CropState.SEEDED)); - - CropState[] allStates = CropState.values(); - for (CropState state : allStates) { - crops = new Crops(state); - assertThat("Constructed with default crops type", crops.getItemType(), equalTo(Material.LEGACY_CROPS)); - assertThat("Constructed with correct crop state", crops.getState(), equalTo(state)); - } - - // The crops which fully implement all crop states - Material[] allCrops = new Material[] {Material.LEGACY_CROPS, Material.LEGACY_CARROT, Material.LEGACY_POTATO}; - for (Material crop : allCrops) { - crops = new Crops(crop); - assertThat("Constructed with correct crops type", crops.getItemType(), equalTo(crop)); - assertThat("Constructed with default crop state", crops.getState(), equalTo(CropState.SEEDED)); - - for (CropState state : allStates) { - crops = new Crops(crop, state); - assertThat("Constructed with correct crops type", crops.getItemType(), equalTo(crop)); - assertThat("Constructed with correct crop state", crops.getState(), equalTo(state)); - } - } - - // Beetroot are crops too, but they only have four states - // Setting different crop states for beetroot will return the following when retrieved back - CropState[] beetrootStates = new CropState[] {CropState.SEEDED, CropState.SEEDED, CropState.SMALL, CropState.SMALL, CropState.TALL, CropState.TALL, CropState.RIPE, CropState.RIPE}; - assertThat("Beetroot state translations match size", beetrootStates.length, equalTo(allStates.length)); - crops = new Crops(Material.LEGACY_BEETROOT_BLOCK); - assertThat("Constructed with correct crops type", crops.getItemType(), equalTo(Material.LEGACY_BEETROOT_BLOCK)); - assertThat("Constructed with default crop state", crops.getState(), equalTo(CropState.SEEDED)); - for (int s = 0; s < beetrootStates.length; s++) { - crops = new Crops(Material.LEGACY_BEETROOT_BLOCK, allStates[s]); - assertThat("Constructed with correct crops type", crops.getItemType(), equalTo(Material.LEGACY_BEETROOT_BLOCK)); - assertThat("Constructed with correct crop state", crops.getState(), equalTo(beetrootStates[s])); - } - - // In case you want to treat NetherWarts as Crops, although they really aren't - crops = new Crops(Material.LEGACY_NETHER_WARTS); - NetherWarts warts = new NetherWarts(); - assertThat("Constructed with correct crops type", crops.getItemType(), equalTo(warts.getItemType())); - assertThat("Constructed with default crop state", crops.getState(), equalTo(CropState.SEEDED)); - assertThat("Constructed with default wart state", warts.getState(), equalTo(NetherWartsState.SEEDED)); - allStates = new CropState[] {CropState.SEEDED, CropState.SMALL, CropState.TALL, CropState.RIPE}; - NetherWartsState[] allWartStates = NetherWartsState.values(); - assertThat("Nether Warts state translations match size", allWartStates.length, equalTo(allStates.length)); - for (int s = 0; s < allStates.length; s++) { - crops = new Crops(Material.LEGACY_NETHER_WARTS, allStates[s]); - warts = new NetherWarts(allWartStates[s]); - assertThat("Constructed with correct crops type", crops.getItemType(), equalTo(warts.getItemType())); - assertThat("Constructed with correct crop state", crops.getState(), equalTo(allStates[s])); - assertThat("Constructed with correct wart state", warts.getState(), equalTo(allWartStates[s])); - } - } - - @Test - public void testDiode() { - Diode diode = new Diode(); - assertThat("Constructed with backward compatible diode state", diode.getItemType(), equalTo(Material.LEGACY_DIODE_BLOCK_ON)); - assertThat("Constructed with backward compatible powered", diode.isPowered(), equalTo(true)); - assertThat("Constructed with default delay", diode.getDelay(), equalTo(1)); - assertThat("Constructed with default direction", diode.getFacing(), equalTo(BlockFace.NORTH)); - - BlockFace[] directions = new BlockFace[] {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; - int[] delays = new int[] {1, 2, 3, 4}; - boolean[] states = new boolean[] {false, true}; - for (BlockFace direction : directions) { - diode = new Diode(direction); - assertThat("Constructed with default diode state", diode.getItemType(), equalTo(Material.LEGACY_DIODE_BLOCK_OFF)); - assertThat("Constructed with default powered", diode.isPowered(), equalTo(false)); - assertThat("Constructed with default delay", diode.getDelay(), equalTo(1)); - assertThat("Constructed with correct direction", diode.getFacing(), equalTo(direction)); - for (int delay : delays) { - diode = new Diode(direction, delay); - assertThat("Constructed with default diode state", diode.getItemType(), equalTo(Material.LEGACY_DIODE_BLOCK_OFF)); - assertThat("Constructed with default powered", diode.isPowered(), equalTo(false)); - assertThat("Constructed with correct delay", diode.getDelay(), equalTo(delay)); - assertThat("Constructed with correct direction", diode.getFacing(), equalTo(direction)); - for (boolean state : states) { - diode = new Diode(direction, delay, state); - assertThat("Constructed with correct diode state", diode.getItemType(), equalTo(state ? Material.LEGACY_DIODE_BLOCK_ON : Material.LEGACY_DIODE_BLOCK_OFF)); - assertThat("Constructed with default powered", diode.isPowered(), equalTo(state)); - assertThat("Constructed with correct delay", diode.getDelay(), equalTo(delay)); - assertThat("Constructed with correct direction", diode.getFacing(), equalTo(direction)); - } - } - } - } - - @Test - public void testComparator() { - Comparator comparator = new Comparator(); - assertThat("Constructed with default comparator state", comparator.getItemType(), equalTo(Material.LEGACY_REDSTONE_COMPARATOR_OFF)); - assertThat("Constructed with default powered", comparator.isPowered(), equalTo(false)); - assertThat("Constructed with default being powered", comparator.isBeingPowered(), equalTo(false)); - assertThat("Constructed with default mode", comparator.isSubtractionMode(), equalTo(false)); - assertThat("Constructed with default direction", comparator.getFacing(), equalTo(BlockFace.NORTH)); - - BlockFace[] directions = new BlockFace[] {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; - boolean[] modes = new boolean[] {false, true}; - boolean[] states = new boolean[] {false, true}; - for (BlockFace direction : directions) { - comparator = new Comparator(direction); - assertThat("Constructed with default comparator state", comparator.getItemType(), equalTo(Material.LEGACY_REDSTONE_COMPARATOR_OFF)); - assertThat("Constructed with default powered", comparator.isPowered(), equalTo(false)); - assertThat("Constructed with default being powered", comparator.isBeingPowered(), equalTo(false)); - assertThat("Constructed with default mode", comparator.isSubtractionMode(), equalTo(false)); - assertThat("Constructed with correct direction", comparator.getFacing(), equalTo(direction)); - for (boolean mode : modes) { - comparator = new Comparator(direction, mode); - assertThat("Constructed with default comparator state", comparator.getItemType(), equalTo(Material.LEGACY_REDSTONE_COMPARATOR_OFF)); - assertThat("Constructed with default powered", comparator.isPowered(), equalTo(false)); - assertThat("Constructed with default being powered", comparator.isBeingPowered(), equalTo(false)); - assertThat("Constructed with correct mode", comparator.isSubtractionMode(), equalTo(mode)); - assertThat("Constructed with correct direction", comparator.getFacing(), equalTo(direction)); - for (boolean state : states) { - comparator = new Comparator(direction, mode, state); - assertThat("Constructed with correct comparator state", comparator.getItemType(), equalTo(state ? Material.LEGACY_REDSTONE_COMPARATOR_ON : Material.LEGACY_REDSTONE_COMPARATOR_OFF)); - assertThat("Constructed with correct powered", comparator.isPowered(), equalTo(state)); - assertThat("Constructed with default being powered", comparator.isBeingPowered(), equalTo(false)); - assertThat("Constructed with correct mode", comparator.isSubtractionMode(), equalTo(mode)); - assertThat("Constructed with correct direction", comparator.getFacing(), equalTo(direction)); - - // Check if the game sets the fourth bit, that block data is still interpreted correctly - comparator.setData((byte)((comparator.getData() & 0x7) | 0x8)); - assertThat("Constructed with correct comparator state", comparator.getItemType(), equalTo(state ? Material.LEGACY_REDSTONE_COMPARATOR_ON : Material.LEGACY_REDSTONE_COMPARATOR_OFF)); - assertThat("Constructed with correct powered", comparator.isPowered(), equalTo(state)); - assertThat("Constructed with correct being powered", comparator.isBeingPowered(), equalTo(true)); - assertThat("Constructed with correct mode", comparator.isSubtractionMode(), equalTo(mode)); - assertThat("Constructed with correct direction", comparator.getFacing(), equalTo(direction)); - } - } - } - } - - @Test - public void testHopper() { - Hopper hopper = new Hopper(); - assertThat("Constructed with default hopper type", hopper.getItemType(), equalTo(Material.LEGACY_HOPPER)); - assertThat("Constructed with default active state", hopper.isActive(), equalTo(true)); - assertThat("Constructed with default powered state", hopper.isPowered(), equalTo(false)); - assertThat("Constructed with default direction", hopper.getFacing(), equalTo(BlockFace.DOWN)); - - BlockFace[] directions = new BlockFace[] {BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.WEST, BlockFace.EAST}; - boolean[] activeStates = new boolean[] {true, false}; - for (BlockFace direction : directions) { - hopper = new Hopper(direction); - assertThat("Constructed with default hopper type", hopper.getItemType(), equalTo(Material.LEGACY_HOPPER)); - assertThat("Constructed with default active state", hopper.isActive(), equalTo(true)); - assertThat("Constructed with correct powered state", hopper.isPowered(), equalTo(false)); - assertThat("Constructed with correct direction", hopper.getFacing(), equalTo(direction)); - for(boolean isActive : activeStates) { - hopper = new Hopper(direction, isActive); - assertThat("Constructed with default hopper type", hopper.getItemType(), equalTo(Material.LEGACY_HOPPER)); - assertThat("Constructed with correct active state", hopper.isActive(), equalTo(isActive)); - assertThat("Constructed with correct powered state", hopper.isPowered(), equalTo(!isActive)); - assertThat("Constructed with correct direction", hopper.getFacing(), equalTo(direction)); - } - } - } -} diff --git a/api/src/test/java/org/bukkit/metadata/FixedMetadataValueTest.java b/api/src/test/java/org/bukkit/metadata/FixedMetadataValueTest.java deleted file mode 100644 index 5583b274b..000000000 --- a/api/src/test/java/org/bukkit/metadata/FixedMetadataValueTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.metadata; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.TestPlugin; -import org.junit.Test; - -public class FixedMetadataValueTest { - private Plugin plugin = new TestPlugin("X"); - private FixedMetadataValue subject; - - @Test - public void testBasic() { - subject = new FixedMetadataValue(plugin, new Integer(50)); - assertSame(plugin, subject.getOwningPlugin()); - assertEquals(new Integer(50), subject.value()); - } - - @Test - public void testNumberTypes() { - subject = new FixedMetadataValue(plugin, new Integer(5)); - assertEquals(new Integer(5), subject.value()); - assertEquals(5, subject.asInt()); - assertEquals(true, subject.asBoolean()); - assertEquals(5, subject.asByte()); - assertEquals(5.0, subject.asFloat(), 0.1e-8); - assertEquals(5.0D, subject.asDouble(), 0.1e-8D); - assertEquals(5L, subject.asLong()); - assertEquals(5, subject.asShort()); - assertEquals("5", subject.asString()); - } - - @Test - public void testInvalidateDoesNothing() { - Object o = new Object(); - subject = new FixedMetadataValue(plugin, o); - subject.invalidate(); - assertSame(o, subject.value()); - } -} diff --git a/api/src/test/java/org/bukkit/metadata/LazyMetadataValueTest.java b/api/src/test/java/org/bukkit/metadata/LazyMetadataValueTest.java deleted file mode 100644 index a3172db70..000000000 --- a/api/src/test/java/org/bukkit/metadata/LazyMetadataValueTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.bukkit.metadata; - -import org.bukkit.plugin.TestPlugin; -import org.junit.Test; - -import java.util.concurrent.Callable; - -import static org.junit.Assert.*; - -public class LazyMetadataValueTest { - private LazyMetadataValue subject; - private TestPlugin plugin = new TestPlugin("x"); - - @Test - public void testLazyInt() { - int value = 10; - subject = makeSimpleCallable(value); - - assertEquals(value, subject.value()); - } - - @Test - public void testLazyDouble() { - double value = 10.5; - subject = makeSimpleCallable(value); - - assertEquals(value, (Double)subject.value(), 0.01); - } - - @Test - public void testLazyString() { - String value = "TEN"; - subject = makeSimpleCallable(value); - - assertEquals(value, subject.value()); - } - - @Test - public void testLazyBoolean() { - boolean value = false; - subject = makeSimpleCallable(value); - - assertEquals(value, subject.value()); - } - - @Test(expected=MetadataEvaluationException.class) - public void testEvalException() { - subject = new LazyMetadataValue(plugin, LazyMetadataValue.CacheStrategy.CACHE_AFTER_FIRST_EVAL, new Callable() { - public Object call() throws Exception { - throw new RuntimeException("Gotcha!"); - } - }); - subject.value(); - } - - @Test - public void testCacheStrategyCacheAfterFirstEval() { - final Counter counter = new Counter(); - final int value = 10; - subject = new LazyMetadataValue(plugin, LazyMetadataValue.CacheStrategy.CACHE_AFTER_FIRST_EVAL, new Callable() { - public Object call() throws Exception { - counter.increment(); - return value; - } - }); - - subject.value(); - subject.value(); - assertEquals(value, subject.value()); - assertEquals(1, counter.value()); - - subject.invalidate(); - subject.value(); - assertEquals(2, counter.value()); - } - - @Test - public void testCacheStrategyNeverCache() { - final Counter counter = new Counter(); - final int value = 10; - subject = new LazyMetadataValue(plugin, LazyMetadataValue.CacheStrategy.NEVER_CACHE, new Callable() { - public Object call() throws Exception { - counter.increment(); - return value; - } - }); - - subject.value(); - subject.value(); - assertEquals(value, subject.value()); - assertEquals(3, counter.value()); - } - - @Test - public void testCacheStrategyEternally() { - final Counter counter = new Counter(); - final int value = 10; - subject = new LazyMetadataValue(plugin, LazyMetadataValue.CacheStrategy.CACHE_ETERNALLY, new Callable() { - public Object call() throws Exception { - counter.increment(); - return value; - } - }); - - subject.value(); - subject.value(); - assertEquals(value, subject.value()); - assertEquals(1, counter.value()); - - subject.invalidate(); - subject.value(); - assertEquals(value, subject.value()); - assertEquals(1, counter.value()); - } - - private LazyMetadataValue makeSimpleCallable(final Object value) { - return new LazyMetadataValue(plugin, new Callable() { - public Object call() throws Exception { - return value; - } - }); - } - - private class Counter { - private int c = 0; - - public void increment() { - c++; - } - - public int value() { - return c; - } - } -} diff --git a/api/src/test/java/org/bukkit/metadata/MetadataConversionTest.java b/api/src/test/java/org/bukkit/metadata/MetadataConversionTest.java deleted file mode 100644 index a595cc8d6..000000000 --- a/api/src/test/java/org/bukkit/metadata/MetadataConversionTest.java +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (C) 2011 Ryan Michela -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -package org.bukkit.metadata; - -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.TestPlugin; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - */ -public class MetadataConversionTest { - private Plugin plugin = new TestPlugin("x"); - private FixedMetadataValue subject; - - private void setSubject(Object value) { - subject = new FixedMetadataValue(plugin, value); - } - - @Test - public void testFromInt() { - setSubject(10); - - assertEquals(10, subject.asInt()); - assertEquals(10, subject.asFloat(), 0.000001); - assertEquals(10, subject.asDouble(), 0.000001); - assertEquals(10, subject.asLong()); - assertEquals(10, subject.asShort()); - assertEquals(10, subject.asByte()); - assertEquals(true, subject.asBoolean()); - assertEquals("10", subject.asString()); - } - - @Test - public void testFromFloat() { - setSubject(10.5); - - assertEquals(10, subject.asInt()); - assertEquals(10.5, subject.asFloat(), 0.000001); - assertEquals(10.5, subject.asDouble(), 0.000001); - assertEquals(10, subject.asLong()); - assertEquals(10, subject.asShort()); - assertEquals(10, subject.asByte()); - assertEquals(true, subject.asBoolean()); - assertEquals("10.5", subject.asString()); - } - - @Test - public void testFromNumericString() { - setSubject("10"); - - assertEquals(10, subject.asInt()); - assertEquals(10, subject.asFloat(), 0.000001); - assertEquals(10, subject.asDouble(), 0.000001); - assertEquals(10, subject.asLong()); - assertEquals(10, subject.asShort()); - assertEquals(10, subject.asByte()); - assertEquals(false, subject.asBoolean()); - assertEquals("10", subject.asString()); - } - - @Test - public void testFromNonNumericString() { - setSubject("true"); - - assertEquals(0, subject.asInt()); - assertEquals(0, subject.asFloat(), 0.000001); - assertEquals(0, subject.asDouble(), 0.000001); - assertEquals(0, subject.asLong()); - assertEquals(0, subject.asShort()); - assertEquals(0, subject.asByte()); - assertEquals(true, subject.asBoolean()); - assertEquals("true", subject.asString()); - } - - @Test - public void testFromNull() { - setSubject(null); - - assertEquals(0, subject.asInt()); - assertEquals(0, subject.asFloat(), 0.000001); - assertEquals(0, subject.asDouble(), 0.000001); - assertEquals(0, subject.asLong()); - assertEquals(0, subject.asShort()); - assertEquals(0, subject.asByte()); - assertEquals(false, subject.asBoolean()); - assertEquals("", subject.asString()); - } -} diff --git a/api/src/test/java/org/bukkit/metadata/MetadataStoreTest.java b/api/src/test/java/org/bukkit/metadata/MetadataStoreTest.java deleted file mode 100644 index 30f036864..000000000 --- a/api/src/test/java/org/bukkit/metadata/MetadataStoreTest.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.bukkit.metadata; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.List; -import java.util.concurrent.Callable; - -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.TestPlugin; -import org.junit.Test; - -public class MetadataStoreTest { - private Plugin pluginX = new TestPlugin("x"); - private Plugin pluginY = new TestPlugin("y"); - - StringMetadataStore subject = new StringMetadataStore(); - - @Test - public void testMetadataStore() { - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); - - assertTrue(subject.hasMetadata("subject", "key")); - List values = subject.getMetadata("subject", "key"); - assertEquals(10, values.get(0).value()); - } - - @Test - public void testMetadataNotPresent() { - assertFalse(subject.hasMetadata("subject", "key")); - List values = subject.getMetadata("subject", "key"); - assertTrue(values.isEmpty()); - } - - @Test - public void testInvalidateAll() { - final Counter counter = new Counter(); - - subject.setMetadata("subject", "key", new LazyMetadataValue(pluginX, new Callable() { - public Object call() throws Exception { - counter.increment(); - return 10; - } - })); - - assertTrue(subject.hasMetadata("subject", "key")); - subject.getMetadata("subject", "key").get(0).value(); - subject.invalidateAll(pluginX); - subject.getMetadata("subject", "key").get(0).value(); - assertEquals(2, counter.value()); - } - - @Test - public void testInvalidateAllButActuallyNothing() { - final Counter counter = new Counter(); - - subject.setMetadata("subject", "key", new LazyMetadataValue(pluginX, new Callable() { - public Object call() throws Exception { - counter.increment(); - return 10; - } - })); - - assertTrue(subject.hasMetadata("subject", "key")); - subject.getMetadata("subject", "key").get(0).value(); - subject.invalidateAll(pluginY); - subject.getMetadata("subject", "key").get(0).value(); - assertEquals(1, counter.value()); - } - - @Test - public void testMetadataReplace() { - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginY, 10)); - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 20)); - - for (MetadataValue mv : subject.getMetadata("subject", "key")) { - if (mv.getOwningPlugin().equals(pluginX)) { - assertEquals(20, mv.value()); - } - if (mv.getOwningPlugin().equals(pluginY)) { - assertEquals(10, mv.value()); - } - } - } - - @Test - public void testMetadataRemove() { - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginY, 20)); - subject.removeMetadata("subject", "key", pluginX); - - assertTrue(subject.hasMetadata("subject", "key")); - assertEquals(1, subject.getMetadata("subject", "key").size()); - assertEquals(20, subject.getMetadata("subject", "key").get(0).value()); - } - - @Test - public void testMetadataRemoveLast() { - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); - subject.removeMetadata("subject", "key", pluginX); - - assertFalse(subject.hasMetadata("subject", "key")); - assertEquals(0, subject.getMetadata("subject", "key").size()); - } - - @Test - public void testMetadataRemoveForNonExistingPlugin() { - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); - subject.removeMetadata("subject", "key", pluginY); - - assertTrue(subject.hasMetadata("subject", "key")); - assertEquals(1, subject.getMetadata("subject", "key").size()); - assertEquals(10, subject.getMetadata("subject", "key").get(0).value()); - } - - @Test - public void testHasMetadata() { - subject.setMetadata("subject", "key", new FixedMetadataValue(pluginX, 10)); - assertTrue(subject.hasMetadata("subject", "key")); - assertFalse(subject.hasMetadata("subject", "otherKey")); - } - - private class StringMetadataStore extends MetadataStoreBase implements MetadataStore { - @Override - protected String disambiguate(String subject, String metadataKey) { - return subject + ":" + metadataKey; - } - } - - private class Counter { - int c = 0; - - public void increment() { - c++; - } - - public int value() { - return c; - } - } -} diff --git a/api/src/test/java/org/bukkit/metadata/MetadataValueAdapterTest.java b/api/src/test/java/org/bukkit/metadata/MetadataValueAdapterTest.java deleted file mode 100644 index 7d8a17fee..000000000 --- a/api/src/test/java/org/bukkit/metadata/MetadataValueAdapterTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.bukkit.metadata; - -import static org.junit.Assert.assertEquals; - -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.TestPlugin; -import org.junit.Test; - -public class MetadataValueAdapterTest { - private TestPlugin plugin = new TestPlugin("x"); - - @Test - public void testAdapterBasics() { - IncrementingMetaValue mv = new IncrementingMetaValue(plugin); - // check getOwningPlugin - assertEquals(mv.getOwningPlugin(), this.plugin); - - // Check value-getting and invalidation. - assertEquals(new Integer(1), mv.value()); - assertEquals(new Integer(2), mv.value()); - mv.invalidate(); - assertEquals(new Integer(1), mv.value()); - } - - @Test - public void testAdapterConversions() { - IncrementingMetaValue mv = new IncrementingMetaValue(plugin); - - assertEquals(1, mv.asInt()); - assertEquals(2L, mv.asLong()); - assertEquals(3.0, mv.asFloat(), 0.001); - assertEquals(4, mv.asByte()); - assertEquals(5.0, mv.asDouble(), 0.001); - assertEquals(6, mv.asShort()); - assertEquals("7", mv.asString()); - } - - /** Boolean conversion is non-trivial, we want to test it thoroughly. */ - @Test - public void testBooleanConversion() { - // null is False. - assertEquals(false, simpleValue(null).asBoolean()); - - // String to boolean. - assertEquals(true, simpleValue("True").asBoolean()); - assertEquals(true, simpleValue("TRUE").asBoolean()); - assertEquals(false, simpleValue("false").asBoolean()); - - // Number to boolean. - assertEquals(true, simpleValue(1).asBoolean()); - assertEquals(true, simpleValue(5.0).asBoolean()); - assertEquals(false, simpleValue(0).asBoolean()); - assertEquals(false, simpleValue(0.1).asBoolean()); - - // Boolean as boolean, of course. - assertEquals(true, simpleValue(Boolean.TRUE).asBoolean()); - assertEquals(false, simpleValue(Boolean.FALSE).asBoolean()); - - // any object that is not null and not a Boolean, String, or Number is true. - assertEquals(true, simpleValue(new Object()).asBoolean()); - } - - /** Test String conversions return an empty string when given null. */ - @Test - public void testStringConversionNull() { - assertEquals("", simpleValue(null).asString()); - } - - /** Get a fixed value MetadataValue. */ - private MetadataValue simpleValue(Object value) { - return new FixedMetadataValue(plugin, value); - } - - /** - * A sample non-trivial MetadataValueAdapter implementation. - * - * The rationale for implementing an incrementing value is to have a value - * which changes with every call to value(). This is important for testing - * because we want to make sure all the tested conversions are calling the - * value() method exactly once and no caching is going on. - */ - class IncrementingMetaValue extends MetadataValueAdapter { - private int internalValue = 0; - - protected IncrementingMetaValue(Plugin owningPlugin) { - super(owningPlugin); - } - - public Object value() { - return ++internalValue; - } - - public void invalidate() { - internalValue = 0; - } - } -} diff --git a/api/src/test/java/org/bukkit/plugin/PluginManagerTest.java b/api/src/test/java/org/bukkit/plugin/PluginManagerTest.java deleted file mode 100644 index 56308c0c6..000000000 --- a/api/src/test/java/org/bukkit/plugin/PluginManagerTest.java +++ /dev/null @@ -1,176 +0,0 @@ -package org.bukkit.plugin; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import org.bukkit.TestServer; -import org.bukkit.event.Event; -import org.bukkit.event.TestEvent; -import org.bukkit.permissions.Permission; - -import org.junit.After; -import org.junit.Test; - -public class PluginManagerTest { - private class MutableObject { - volatile Object value = null; - } - - private static final PluginManager pm = TestServer.getInstance().getPluginManager(); - - private final MutableObject store = new MutableObject(); -/* // Paper start - remove unneeded test - @Test - public void testAsyncSameThread() { - final Event event = new TestEvent(true); - try { - pm.callEvent(event); - } catch (IllegalStateException ex) { - assertThat(event.getEventName() + " cannot be triggered asynchronously from primary server thread.", is(ex.getMessage())); - return; - } - throw new IllegalStateException("No exception thrown"); - }*/ // Paper end - - @Test - public void testSyncSameThread() { - final Event event = new TestEvent(false); - pm.callEvent(event); - } -/* // Paper start - remove unneeded test - @Test - public void testAsyncLocked() throws InterruptedException { - final Event event = new TestEvent(true); - Thread secondThread = new Thread( - new Runnable() { - public void run() { - try { - synchronized (pm) { - pm.callEvent(event); - } - } catch (Throwable ex) { - store.value = ex; - } - } - } - ); - secondThread.start(); - secondThread.join(); - assertThat(store.value, is(instanceOf(IllegalStateException.class))); - assertThat(event.getEventName() + " cannot be triggered asynchronously from inside synchronized code.", is(((Throwable) store.value).getMessage())); - }*/ // Paper end - - @Test - public void testAsyncUnlocked() throws InterruptedException { - final Event event = new TestEvent(true); - Thread secondThread = new Thread( - new Runnable() { - public void run() { - try { - pm.callEvent(event); - } catch (Throwable ex) { - store.value = ex; - } - }}); - secondThread.start(); - secondThread.join(); - if (store.value != null) { - throw new RuntimeException((Throwable) store.value); - } - } - - @Test - public void testSyncUnlocked() throws InterruptedException { - final Event event = new TestEvent(false); - Thread secondThread = new Thread( - new Runnable() { - public void run() { - try { - pm.callEvent(event); - } catch (Throwable ex) { - store.value = ex; - } - } - } - ); - secondThread.start(); - secondThread.join(); - if (store.value != null) { - throw new RuntimeException((Throwable) store.value); - } - } - - @Test - public void testSyncLocked() throws InterruptedException { - final Event event = new TestEvent(false); - Thread secondThread = new Thread( - new Runnable() { - public void run() { - try { - synchronized (pm) { - pm.callEvent(event); - } - } catch (Throwable ex) { - store.value = ex; - } - } - } - ); - secondThread.start(); - secondThread.join(); - if (store.value != null) { - throw new RuntimeException((Throwable) store.value); - } - } - - @Test - public void testRemovePermissionByNameLower() { - this.testRemovePermissionByName("lower"); - } - - @Test - public void testRemovePermissionByNameUpper() { - this.testRemovePermissionByName("UPPER"); - } - - @Test - public void testRemovePermissionByNameCamel() { - this.testRemovePermissionByName("CaMeL"); - } - - public void testRemovePermissionByPermissionLower() { - this.testRemovePermissionByPermission("lower"); - } - - @Test - public void testRemovePermissionByPermissionUpper() { - this.testRemovePermissionByPermission("UPPER"); - } - - @Test - public void testRemovePermissionByPermissionCamel() { - this.testRemovePermissionByPermission("CaMeL"); - } - - private void testRemovePermissionByName(final String name) { - final Permission perm = new Permission(name); - pm.addPermission(perm); - assertThat("Permission \"" + name + "\" was not added", pm.getPermission(name), is(perm)); - pm.removePermission(name); - assertThat("Permission \"" + name + "\" was not removed", pm.getPermission(name), is(nullValue())); - } - - private void testRemovePermissionByPermission(final String name) { - final Permission perm = new Permission(name); - pm.addPermission(perm); - assertThat("Permission \"" + name + "\" was not added", pm.getPermission(name), is(perm)); - pm.removePermission(perm); - assertThat("Permission \"" + name + "\" was not removed", pm.getPermission(name), is(nullValue())); - } - - @After - public void tearDown() { - pm.clearPlugins(); - assertThat(pm.getPermissions(), is(empty())); - } -} diff --git a/api/src/test/java/org/bukkit/plugin/TestPlugin.java b/api/src/test/java/org/bukkit/plugin/TestPlugin.java deleted file mode 100644 index f85e5f175..000000000 --- a/api/src/test/java/org/bukkit/plugin/TestPlugin.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.bukkit.plugin; - -import java.io.File; -import java.io.InputStream; -import java.util.List; - -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; - -public class TestPlugin extends PluginBase { - private boolean enabled = true; - - final private String pluginName; - - public TestPlugin(String pluginName) { - this.pluginName = pluginName; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public File getDataFolder() { - throw new UnsupportedOperationException("Not supported."); - } - - public PluginDescriptionFile getDescription() { - return new PluginDescriptionFile(pluginName, "1.0", "test.test"); - } - - public FileConfiguration getConfig() { - throw new UnsupportedOperationException("Not supported."); - } - - public InputStream getResource(String filename) { - throw new UnsupportedOperationException("Not supported."); - } - - public void saveConfig() { - throw new UnsupportedOperationException("Not supported."); - } - - public void saveDefaultConfig() { - throw new UnsupportedOperationException("Not supported."); - } - - public void saveResource(String resourcePath, boolean replace) { - throw new UnsupportedOperationException("Not supported."); - } - - public void reloadConfig() { - throw new UnsupportedOperationException("Not supported."); - } - - public PluginLogger getLogger() { - throw new UnsupportedOperationException("Not supported."); - } - - public PluginLoader getPluginLoader() { - throw new UnsupportedOperationException("Not supported."); - } - - public Server getServer() { - throw new UnsupportedOperationException("Not supported."); - } - - public boolean isEnabled() { - return enabled; - } - - public void onDisable() { - throw new UnsupportedOperationException("Not supported."); - } - - public void onLoad() { - throw new UnsupportedOperationException("Not supported."); - } - - public void onEnable() { - throw new UnsupportedOperationException("Not supported."); - } - - public boolean isNaggable() { - throw new UnsupportedOperationException("Not supported."); - } - - public void setNaggable(boolean canNag) { - throw new UnsupportedOperationException("Not supported."); - } - - public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { - throw new UnsupportedOperationException("Not supported."); - } - - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - throw new UnsupportedOperationException("Not supported."); - } - - public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { - throw new UnsupportedOperationException("Not supported."); - } -} diff --git a/api/src/test/java/org/bukkit/plugin/TimedRegisteredListenerTest.java b/api/src/test/java/org/bukkit/plugin/TimedRegisteredListenerTest.java deleted file mode 100644 index b206b1f38..000000000 --- a/api/src/test/java/org/bukkit/plugin/TimedRegisteredListenerTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.plugin; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import org.bukkit.event.Event; -import org.bukkit.event.EventException; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.junit.Test; - -public class TimedRegisteredListenerTest { - - @Test - public void testEventClass() throws EventException { - Listener listener = new Listener() {}; - EventExecutor executor = new EventExecutor() { - public void execute(Listener listener, Event event) {} - }; - TestPlugin plugin = new TestPlugin("Test"); - - PlayerInteractEvent interactEvent = new PlayerInteractEvent(null, null, null, null, null); - PlayerMoveEvent moveEvent = new PlayerMoveEvent(null, null, null); - BlockBreakEvent breakEvent = new BlockBreakEvent(null, null); - - TimedRegisteredListener trl = new TimedRegisteredListener(listener, executor, EventPriority.NORMAL, plugin, false); - - // Ensure that the correct event type is reported for a single event - trl.callEvent(interactEvent); - assertThat(trl.getEventClass(), is((Object) PlayerInteractEvent.class)); - // Ensure that no superclass is used in lieu of the actual event, after two identical event types - trl.callEvent(interactEvent); - assertThat(trl.getEventClass(), is((Object) PlayerInteractEvent.class)); - // Ensure that the closest superclass of the two events is chosen - trl.callEvent(moveEvent); - assertThat(trl.getEventClass(), is((Object) PlayerEvent.class)); - // As above, so below - trl.callEvent(breakEvent); - assertThat(trl.getEventClass(), is((Object) Event.class)); - // In the name of being thorough, check that it never travels down the hierarchy again. - trl.callEvent(breakEvent); - assertThat(trl.getEventClass(), is((Object) Event.class)); - - trl = new TimedRegisteredListener(listener, executor, EventPriority.NORMAL, plugin, false); - - trl.callEvent(breakEvent); - assertThat(trl.getEventClass(), is((Object) BlockBreakEvent.class)); - // Test moving up the class hierarchy by more than one class at a time - trl.callEvent(moveEvent); - assertThat(trl.getEventClass(), is((Object) Event.class)); - } -} diff --git a/api/src/test/java/org/bukkit/plugin/messaging/StandardMessengerTest.java b/api/src/test/java/org/bukkit/plugin/messaging/StandardMessengerTest.java deleted file mode 100644 index 31ff2f61d..000000000 --- a/api/src/test/java/org/bukkit/plugin/messaging/StandardMessengerTest.java +++ /dev/null @@ -1,305 +0,0 @@ -package org.bukkit.plugin.messaging; - -import org.bukkit.entity.Player; -import org.bukkit.plugin.TestPlugin; -import java.util.Collection; -import org.junit.Test; -import org.junit.Assert; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; - -public class StandardMessengerTest { - public StandardMessenger getMessenger() { - return new StandardMessenger(); - } - - private int count = 0; - public TestPlugin getPlugin() { - return new TestPlugin("" + count++); - } - - @Test - public void testIsReservedChannel() { - Messenger messenger = getMessenger(); - - assertTrue(messenger.isReservedChannel("minecraft:register")); - assertFalse(messenger.isReservedChannel("test:register")); - assertTrue(messenger.isReservedChannel("minecraft:unregister")); - assertFalse(messenger.isReservedChannel("test:unregister")); // Paper - fix typo - assertFalse(messenger.isReservedChannel("minecraft:something")); // Paper - now less strict - assertFalse(messenger.isReservedChannel("minecraft:brand")); - } - - @Test - public void testRegisterAndUnregisterOutgoingPluginChannel() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - - assertFalse(messenger.isOutgoingChannelRegistered(plugin, "test:foo")); - messenger.registerOutgoingPluginChannel(plugin, "test:foo"); - assertTrue(messenger.isOutgoingChannelRegistered(plugin, "test:foo")); - assertFalse(messenger.isOutgoingChannelRegistered(plugin, "test:bar")); - - messenger.unregisterOutgoingPluginChannel(plugin, "test:foo"); - assertFalse(messenger.isOutgoingChannelRegistered(plugin, "test:foo")); - } - - @Test(expected = ReservedChannelException.class) - public void testReservedOutgoingRegistration() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - - messenger.registerOutgoingPluginChannel(plugin, "minecraft:register"); - } - - @Test - public void testUnregisterOutgoingPluginChannel_Plugin() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - - assertFalse(messenger.isOutgoingChannelRegistered(plugin, "test:foo")); - messenger.registerOutgoingPluginChannel(plugin, "test:foo"); - messenger.registerOutgoingPluginChannel(plugin, "test:bar"); - assertTrue(messenger.isOutgoingChannelRegistered(plugin, "test:foo")); - assertTrue(messenger.isOutgoingChannelRegistered(plugin, "test:bar")); - - messenger.unregisterOutgoingPluginChannel(plugin); - assertFalse(messenger.isOutgoingChannelRegistered(plugin, "test:foo")); - assertFalse(messenger.isOutgoingChannelRegistered(plugin, "test:bar")); - } - - @Test - public void testRegisterIncomingPluginChannel() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - TestMessageListener listener = new TestMessageListener("test:foo", "test:bar".getBytes()); - Player player = TestPlayer.getInstance(); - PluginMessageListenerRegistration registration = messenger.registerIncomingPluginChannel(plugin, "test:foo", listener); - - assertTrue(registration.isValid()); - assertTrue(messenger.isIncomingChannelRegistered(plugin, "test:foo")); - messenger.dispatchIncomingMessage(player, "test:foo", "test:bar".getBytes()); - assertTrue(listener.hasReceived()); - - messenger.unregisterIncomingPluginChannel(plugin, "test:foo", listener); - listener.reset(); - - assertFalse(registration.isValid()); - assertFalse(messenger.isIncomingChannelRegistered(plugin, "test:foo")); - messenger.dispatchIncomingMessage(player, "test:foo", "test:bar".getBytes()); - assertFalse(listener.hasReceived()); - } - - @Test(expected = ReservedChannelException.class) - public void testReservedIncomingRegistration() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - - messenger.registerIncomingPluginChannel(plugin, "minecraft:register", new TestMessageListener("test:foo", "test:bar".getBytes())); - } - - @Test(expected = IllegalArgumentException.class) - public void testDuplicateIncomingRegistration() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - TestMessageListener listener = new TestMessageListener("test:foo", "test:bar".getBytes()); - - messenger.registerIncomingPluginChannel(plugin, "test:baz", listener); - messenger.registerIncomingPluginChannel(plugin, "test:baz", listener); - } - - @Test - public void testUnregisterIncomingPluginChannel_Plugin_String() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - TestMessageListener listener1 = new TestMessageListener("test:foo", "test:bar".getBytes()); - TestMessageListener listener2 = new TestMessageListener("test:baz", "test:qux".getBytes()); - Player player = TestPlayer.getInstance(); - PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin, "test:foo", listener1); - PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin, "test:baz", listener2); - - assertTrue(registration1.isValid()); - assertTrue(registration2.isValid()); - messenger.dispatchIncomingMessage(player, "test:foo", "test:bar".getBytes()); - messenger.dispatchIncomingMessage(player, "test:baz", "test:qux".getBytes()); - assertTrue(listener1.hasReceived()); - assertTrue(listener2.hasReceived()); - - messenger.unregisterIncomingPluginChannel(plugin, "test:foo"); - listener1.reset(); - listener2.reset(); - - assertFalse(registration1.isValid()); - assertTrue(registration2.isValid()); - messenger.dispatchIncomingMessage(player, "test:foo", "test:bar".getBytes()); - messenger.dispatchIncomingMessage(player, "test:baz", "test:qux".getBytes()); - assertFalse(listener1.hasReceived()); - assertTrue(listener2.hasReceived()); - } - - @Test - public void testUnregisterIncomingPluginChannel_Plugin() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - TestMessageListener listener1 = new TestMessageListener("test:foo", "test:bar".getBytes()); - TestMessageListener listener2 = new TestMessageListener("test:baz", "test:qux".getBytes()); - Player player = TestPlayer.getInstance(); - PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin, "test:foo", listener1); - PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin, "test:baz", listener2); - - assertTrue(registration1.isValid()); - assertTrue(registration2.isValid()); - messenger.dispatchIncomingMessage(player, "test:foo", "test:bar".getBytes()); - messenger.dispatchIncomingMessage(player, "test:baz", "test:qux".getBytes()); - assertTrue(listener1.hasReceived()); - assertTrue(listener2.hasReceived()); - - messenger.unregisterIncomingPluginChannel(plugin); - listener1.reset(); - listener2.reset(); - - assertFalse(registration1.isValid()); - assertFalse(registration2.isValid()); - messenger.dispatchIncomingMessage(player, "test:foo", "test:bar".getBytes()); - messenger.dispatchIncomingMessage(player, "test:baz", "test:qux".getBytes()); - assertFalse(listener1.hasReceived()); - assertFalse(listener2.hasReceived()); - } - - @Test - public void testGetOutgoingChannels() { - Messenger messenger = getMessenger(); - TestPlugin plugin1 = getPlugin(); - TestPlugin plugin2 = getPlugin(); - - assertEquals(messenger.getOutgoingChannels()); - - messenger.registerOutgoingPluginChannel(plugin1, "test:foo"); - messenger.registerOutgoingPluginChannel(plugin1, "test:bar"); - messenger.registerOutgoingPluginChannel(plugin2, "test:baz"); - messenger.registerOutgoingPluginChannel(plugin2, "test:baz"); - - assertEquals(messenger.getOutgoingChannels(), "test:foo", "test:bar", "test:baz"); - } - - @Test - public void testGetOutgoingChannels_Plugin() { - Messenger messenger = getMessenger(); - TestPlugin plugin1 = getPlugin(); - TestPlugin plugin2 = getPlugin(); - TestPlugin plugin3 = getPlugin(); - - messenger.registerOutgoingPluginChannel(plugin1, "test:foo"); - messenger.registerOutgoingPluginChannel(plugin1, "test:bar"); - messenger.registerOutgoingPluginChannel(plugin2, "test:baz"); - messenger.registerOutgoingPluginChannel(plugin2, "test:qux"); - - assertEquals(messenger.getOutgoingChannels(plugin1), "test:foo", "test:bar"); - assertEquals(messenger.getOutgoingChannels(plugin2), "test:baz", "test:qux"); - assertEquals(messenger.getOutgoingChannels(plugin3)); - } - - @Test - public void testGetIncomingChannels() { - Messenger messenger = getMessenger(); - TestPlugin plugin1 = getPlugin(); - TestPlugin plugin2 = getPlugin(); - - assertEquals(messenger.getIncomingChannels()); - - messenger.registerIncomingPluginChannel(plugin1, "test:foo", new TestMessageListener("test:foo", "test:bar".getBytes())); - messenger.registerIncomingPluginChannel(plugin1, "test:bar", new TestMessageListener("test:foo", "test:bar".getBytes())); - messenger.registerIncomingPluginChannel(plugin2, "test:baz", new TestMessageListener("test:foo", "test:bar".getBytes())); - messenger.registerIncomingPluginChannel(plugin2, "test:baz", new TestMessageListener("test:foo", "test:bar".getBytes())); - - assertEquals(messenger.getIncomingChannels(), "test:foo", "test:bar", "test:baz"); - } - - @Test - public void testGetIncomingChannels_Plugin() { - Messenger messenger = getMessenger(); - TestPlugin plugin1 = getPlugin(); - TestPlugin plugin2 = getPlugin(); - TestPlugin plugin3 = getPlugin(); - - messenger.registerIncomingPluginChannel(plugin1, "test:foo", new TestMessageListener("test:foo", "test:bar".getBytes())); - messenger.registerIncomingPluginChannel(plugin1, "test:bar", new TestMessageListener("test:foo", "test:bar".getBytes())); - messenger.registerIncomingPluginChannel(plugin2, "test:baz", new TestMessageListener("test:foo", "test:bar".getBytes())); - messenger.registerIncomingPluginChannel(plugin2, "test:qux", new TestMessageListener("test:foo", "test:bar".getBytes())); - - assertEquals(messenger.getIncomingChannels(plugin1), "test:foo", "test:bar"); - assertEquals(messenger.getIncomingChannels(plugin2), "test:baz", "test:qux"); - assertEquals(messenger.getIncomingChannels(plugin3)); - } - - @Test - public void testGetIncomingChannelRegistrations_Plugin() { - Messenger messenger = getMessenger(); - TestPlugin plugin1 = getPlugin(); - TestPlugin plugin2 = getPlugin(); - TestPlugin plugin3 = getPlugin(); - PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin1, "test:foo", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin1, "test:bar", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration3 = messenger.registerIncomingPluginChannel(plugin2, "test:baz", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration4 = messenger.registerIncomingPluginChannel(plugin2, "test:qux", new TestMessageListener("test:foo", "test:bar".getBytes())); - - assertEquals(messenger.getIncomingChannelRegistrations(plugin1), registration1, registration2); - assertEquals(messenger.getIncomingChannelRegistrations(plugin2), registration3, registration4); - assertEquals(messenger.getIncomingChannels(plugin3)); - } - - @Test - public void testGetIncomingChannelRegistrations_String() { - Messenger messenger = getMessenger(); - TestPlugin plugin1 = getPlugin(); - TestPlugin plugin2 = getPlugin(); - PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin1, "test:foo", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin1, "test:bar", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration3 = messenger.registerIncomingPluginChannel(plugin2, "test:foo", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration4 = messenger.registerIncomingPluginChannel(plugin2, "test:bar", new TestMessageListener("test:foo", "test:bar".getBytes())); - - assertEquals(messenger.getIncomingChannelRegistrations("test:foo"), registration1, registration3); - assertEquals(messenger.getIncomingChannelRegistrations("test:bar"), registration2, registration4); - assertEquals(messenger.getIncomingChannelRegistrations("test:baz")); - } - - @Test - public void testGetIncomingChannelRegistrations_Plugin_String() { - Messenger messenger = getMessenger(); - TestPlugin plugin1 = getPlugin(); - TestPlugin plugin2 = getPlugin(); - TestPlugin plugin3 = getPlugin(); - PluginMessageListenerRegistration registration1 = messenger.registerIncomingPluginChannel(plugin1, "test:foo", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration2 = messenger.registerIncomingPluginChannel(plugin1, "test:foo", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration3 = messenger.registerIncomingPluginChannel(plugin1, "test:bar", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration4 = messenger.registerIncomingPluginChannel(plugin2, "test:bar", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration5 = messenger.registerIncomingPluginChannel(plugin2, "test:baz", new TestMessageListener("test:foo", "test:bar".getBytes())); - PluginMessageListenerRegistration registration6 = messenger.registerIncomingPluginChannel(plugin2, "test:baz", new TestMessageListener("test:foo", "test:bar".getBytes())); - - assertEquals(messenger.getIncomingChannelRegistrations(plugin1, "test:foo"), registration1, registration2); - assertEquals(messenger.getIncomingChannelRegistrations(plugin1, "test:bar"), registration3); - assertEquals(messenger.getIncomingChannelRegistrations(plugin2, "test:bar"), registration4); - assertEquals(messenger.getIncomingChannelRegistrations(plugin2, "test:baz"), registration5, registration6); - assertEquals(messenger.getIncomingChannelRegistrations(plugin1, "test:baz")); - assertEquals(messenger.getIncomingChannelRegistrations(plugin3, "test:qux")); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidChannel() { - Messenger messenger = getMessenger(); - TestPlugin plugin = getPlugin(); - - messenger.registerOutgoingPluginChannel(plugin, "foo"); - } - - @Test - public void testValidateAndCorrectChannel() { - Assert.assertEquals("bungeecord:main", StandardMessenger.validateAndCorrectChannel("BungeeCord")); - Assert.assertEquals("BungeeCord", StandardMessenger.validateAndCorrectChannel("bungeecord:main")); - } - - private static void assertEquals(Collection actual, T... expected) { - assertThat("Size of the array", actual.size(), is(expected.length)); - assertThat(actual, hasItems(expected)); - } -} diff --git a/api/src/test/java/org/bukkit/plugin/messaging/TestMessageListener.java b/api/src/test/java/org/bukkit/plugin/messaging/TestMessageListener.java deleted file mode 100644 index 98860ec19..000000000 --- a/api/src/test/java/org/bukkit/plugin/messaging/TestMessageListener.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.plugin.messaging; - -import org.bukkit.entity.Player; -import static org.junit.Assert.*; - -public class TestMessageListener implements PluginMessageListener { - private final String channel; - private final byte[] message; - private boolean received = false; - - public TestMessageListener(String channel, byte[] message) { - this.channel = channel; - this.message = message; - } - - public void onPluginMessageReceived(String channel, Player player, byte[] message) { - assertEquals(this.channel, channel); - assertArrayEquals(this.message, message); - this.received = true; - } - - public boolean hasReceived() { - return received; - } - - public void reset() { - received = false; - } -} diff --git a/api/src/test/java/org/bukkit/plugin/messaging/TestPlayer.java b/api/src/test/java/org/bukkit/plugin/messaging/TestPlayer.java deleted file mode 100644 index 71f59c5d3..000000000 --- a/api/src/test/java/org/bukkit/plugin/messaging/TestPlayer.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.plugin.messaging; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.HashMap; - -import org.bukkit.entity.Player; - - -public class TestPlayer implements InvocationHandler { - private static interface MethodHandler { - Object handle(TestPlayer server, Object[] args); - } - private static final Constructor constructor; - private static final HashMap methods = new HashMap(); - static { - try { - /* - methods.put(Player.class.getMethod("methodName"), - new MethodHandler() { - public Object handle(TestPlayer server, Object[] args) { - } - }); - */ - constructor = Proxy.getProxyClass(Player.class.getClassLoader(), Player.class).asSubclass(Player.class).getConstructor(InvocationHandler.class); - } catch (Throwable t) { - throw new Error(t); - } - } - - private TestPlayer() {}; - - public static Player getInstance() { - try { - return constructor.newInstance(new TestPlayer()); - } catch (Throwable t) { - throw new RuntimeException(t); - } - } - - public Object invoke(Object proxy, Method method, Object[] args) { - MethodHandler handler = methods.get(method); - if (handler != null) { - return handler.handle(this, args); - } - throw new UnsupportedOperationException(String.valueOf(method)); - } -} diff --git a/api/src/test/java/org/bukkit/util/BoundingBoxTest.java b/api/src/test/java/org/bukkit/util/BoundingBoxTest.java deleted file mode 100644 index 1332aa265..000000000 --- a/api/src/test/java/org/bukkit/util/BoundingBoxTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.bukkit.util; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.util.Map; - -import org.bukkit.Location; -import org.bukkit.block.BlockFace; -import org.junit.Test; - -public class BoundingBoxTest { - - private static final double delta = 1.0 / 1000000; - - @Test - public void testConstruction() { - BoundingBox expected = new BoundingBox(-1, -1, -1, 1, 2, 3); - assertThat(expected.getMin(), is(new Vector(-1, -1, -1))); - assertThat(expected.getMax(), is(new Vector(1, 2, 3))); - assertThat(expected.getCenter(), is(new Vector(0.0D, 0.5D, 1.0D))); - assertThat(expected.getWidthX(), is(2.0D)); - assertThat(expected.getHeight(), is(3.0D)); - assertThat(expected.getWidthZ(), is(4.0D)); - assertThat(expected.getVolume(), is(24.0D)); - - assertThat(BoundingBox.of(new Vector(-1, -1, -1), new Vector(1, 2, 3)), is(expected)); - assertThat(BoundingBox.of(new Vector(1, 2, 3), new Vector(-1, -1, -1)), is(expected)); - assertThat(BoundingBox.of(new Location(null, -1, -1, -1), new Location(null, 1, 2, 3)), is(expected)); - assertThat(BoundingBox.of(new Vector(0.0D, 0.5D, 1.0D), 1.0D, 1.5D, 2.0D), is(expected)); - assertThat(BoundingBox.of(new Location(null, 0.0D, 0.5D, 1.0D), 1.0D, 1.5D, 2.0D), is(expected)); - } - - @Test - public void testContains() { - BoundingBox aabb = new BoundingBox(-1, -1, -1, 1, 2, 3); - assertThat(aabb.contains(-0.5D, 0.0D, 0.5D), is(true)); - assertThat(aabb.contains(-1.0D, -1.0D, -1.0D), is(true)); - assertThat(aabb.contains(1.0D, 2.0D, 3.0D), is(false)); - assertThat(aabb.contains(-1.0D, 1.0D, 4.0D), is(false)); - assertThat(aabb.contains(new Vector(-0.5D, 0.0D, 0.5D)), is(true)); - - assertThat(aabb.contains(new BoundingBox(-0.5D, -0.5D, -0.5D, 0.5D, 1.0D, 2.0D)), is(true)); - assertThat(aabb.contains(aabb), is(true)); - assertThat(aabb.contains(new BoundingBox(-1, -1, -1, 1, 1, 3)), is(true)); - assertThat(aabb.contains(new BoundingBox(-2, -1, -1, 1, 2, 3)), is(false)); - assertThat(aabb.contains(new Vector(-0.5D, -0.5D, -0.5D), new Vector(0.5D, 1.0D, 2.0D)), is(true)); - } - - @Test - public void testOverlaps() { - BoundingBox aabb = new BoundingBox(-1, -1, -1, 1, 2, 3); - assertThat(aabb.contains(aabb), is(true)); - assertThat(aabb.overlaps(new BoundingBox(-2, -2, -2, 0, 0, 0)), is(true)); - assertThat(aabb.overlaps(new BoundingBox(0.5D, 1.5D, 2.5D, 1, 2, 3)), is(true)); - assertThat(aabb.overlaps(new BoundingBox(0.5D, 1.5D, 2.5D, 2, 3, 4)), is(true)); - assertThat(aabb.overlaps(new BoundingBox(-2, -2, -2, -1, -1, -1)), is(false)); - assertThat(aabb.overlaps(new BoundingBox(1, 2, 3, 2, 3, 4)), is(false)); - assertThat(aabb.overlaps(new Vector(0.5D, 1.5D, 2.5D), new Vector(1, 2, 3)), is(true)); - } - - @Test - public void testDegenerate() { - BoundingBox aabb = new BoundingBox(0, 0, 0, 0, 0, 0); - assertThat(aabb.getWidthX(), is(0.0D)); - assertThat(aabb.getHeight(), is(0.0D)); - assertThat(aabb.getWidthZ(), is(0.0D)); - assertThat(aabb.getVolume(), is(0.0D)); - } - - @Test - public void testShift() { - BoundingBox aabb = new BoundingBox(0, 0, 0, 1, 1, 1); - assertThat(aabb.clone().shift(1, 2, 3), is(new BoundingBox(1, 2, 3, 2, 3, 4))); - assertThat(aabb.clone().shift(-1, -2, -3), is(new BoundingBox(-1, -2, -3, 0, -1, -2))); - assertThat(aabb.clone().shift(new Vector(1, 2, 3)), is(new BoundingBox(1, 2, 3, 2, 3, 4))); - assertThat(aabb.clone().shift(new Location(null, 1, 2, 3)), is(new BoundingBox(1, 2, 3, 2, 3, 4))); - } - - @Test - public void testUnion() { - BoundingBox aabb1 = new BoundingBox(0, 0, 0, 1, 1, 1); - assertThat(aabb1.clone().union(new BoundingBox(-2, -2, -2, -1, -1, -1)), is(new BoundingBox(-2, -2, -2, 1, 1, 1))); - assertThat(aabb1.clone().union(1, 2, 3), is(new BoundingBox(0, 0, 0, 1, 2, 3))); - assertThat(aabb1.clone().union(new Vector(1, 2, 3)), is(new BoundingBox(0, 0, 0, 1, 2, 3))); - assertThat(aabb1.clone().union(new Location(null, 1, 2, 3)), is(new BoundingBox(0, 0, 0, 1, 2, 3))); - } - - @Test - public void testIntersection() { - BoundingBox aabb = new BoundingBox(-1, -1, -1, 1, 2, 3); - assertThat(aabb.clone().intersection(new BoundingBox(-2, -2, -2, 4, 4, 4)), is(aabb)); - assertThat(aabb.clone().intersection(new BoundingBox(-2, -2, -2, 1, 1, 1)), is(new BoundingBox(-1, -1, -1, 1, 1, 1))); - } - - @Test - public void testExpansion() { - BoundingBox aabb = new BoundingBox(0, 0, 0, 2, 2, 2); - assertThat(aabb.clone().expand(1, 2, 3, 1, 2, 3), is(new BoundingBox(-1, -2, -3, 3, 4, 5))); - assertThat(aabb.clone().expand(-1, -2, -3, 1, 2, 3), is(new BoundingBox(1, 2, 3, 3, 4, 5))); - assertThat(aabb.clone().expand(1, 2, 3, -1, -2, -3), is(new BoundingBox(-1, -2, -3, 1, 0, -1))); - assertThat(aabb.clone().expand(-1, -2, -3, -0.5D, -0.5, -3), is(new BoundingBox(1, 1.5D, 1, 1.5D, 1.5D, 1))); - - assertThat(aabb.clone().expand(1, 2, 3), is(new BoundingBox(-1, -2, -3, 3, 4, 5))); - assertThat(aabb.clone().expand(-0.1, -0.5, -2), is(new BoundingBox(0.1D, 0.5D, 1, 1.9D, 1.5D, 1))); - assertThat(aabb.clone().expand(new Vector(1, 2, 3)), is(new BoundingBox(-1, -2, -3, 3, 4, 5))); - - assertThat(aabb.clone().expand(1), is(new BoundingBox(-1, -1, -1, 3, 3, 3))); - assertThat(aabb.clone().expand(-0.5D), is(new BoundingBox(0.5D, 0.5D, 0.5D, 1.5D, 1.5D, 1.5D))); - - assertThat(aabb.clone().expand(1, 0, 0, 0.5D), is(new BoundingBox(0, 0, 0, 2.5D, 2, 2))); - assertThat(aabb.clone().expand(1, 0, 0, -0.5D), is(new BoundingBox(0, 0, 0, 1.5D, 2, 2))); - assertThat(aabb.clone().expand(-1, 0, 0, 0.5D), is(new BoundingBox(-0.5D, 0, 0, 2, 2, 2))); - assertThat(aabb.clone().expand(-1, 0, 0, -0.5D), is(new BoundingBox(0.5D, 0, 0, 2, 2, 2))); - - assertThat(aabb.clone().expand(0, 1, 0, 0.5D), is(new BoundingBox(0, 0, 0, 2, 2.5D, 2))); - assertThat(aabb.clone().expand(0, 1, 0, -0.5D), is(new BoundingBox(0, 0, 0, 2, 1.5D, 2))); - assertThat(aabb.clone().expand(0, -1, 0, 0.5D), is(new BoundingBox(0, -0.5D, 0, 2, 2, 2))); - assertThat(aabb.clone().expand(0, -1, 0, -0.5D), is(new BoundingBox(0, 0.5D, 0, 2, 2, 2))); - - assertThat(aabb.clone().expand(0, 0, 1, 0.5D), is(new BoundingBox(0, 0, 0, 2, 2, 2.5D))); - assertThat(aabb.clone().expand(0, 0, 1, -0.5D), is(new BoundingBox(0, 0, 0, 2, 2, 1.5D))); - assertThat(aabb.clone().expand(0, 0, -1, 0.5D), is(new BoundingBox(0, 0, -0.5D, 2, 2, 2))); - assertThat(aabb.clone().expand(0, 0, -1, -0.5D), is(new BoundingBox(0, 0, 0.5D, 2, 2, 2))); - - assertThat(aabb.clone().expand(new Vector(1, 0, 0), 0.5D), is(new BoundingBox(0, 0, 0, 2.5D, 2, 2))); - assertThat(aabb.clone().expand(BlockFace.EAST, 0.5D), is(new BoundingBox(0, 0, 0, 2.5D, 2, 2))); - assertThat(aabb.clone().expand(BlockFace.NORTH_NORTH_WEST, 1.0D), is(aabb.clone().expand(BlockFace.NORTH_NORTH_WEST.getDirection(), 1.0D))); - assertThat(aabb.clone().expand(BlockFace.SELF, 1.0D), is(aabb)); - - BoundingBox expanded = aabb.clone().expand(BlockFace.NORTH_WEST, 1.0D); - assertThat(expanded.getWidthX(), is(closeTo(aabb.getWidthX() + Math.sqrt(0.5D), delta))); - assertThat(expanded.getWidthZ(), is(closeTo(aabb.getWidthZ() + Math.sqrt(0.5D), delta))); - assertThat(expanded.getHeight(), is(aabb.getHeight())); - - assertThat(aabb.clone().expandDirectional(1, 2, 3), is(new BoundingBox(0, 0, 0, 3, 4, 5))); - assertThat(aabb.clone().expandDirectional(-1, -2, -3), is(new BoundingBox(-1, -2, -3, 2, 2, 2))); - assertThat(aabb.clone().expandDirectional(new Vector(1, 2, 3)), is(new BoundingBox(0, 0, 0, 3, 4, 5))); - } - - @Test - public void testRayTrace() { - BoundingBox aabb = new BoundingBox(-1, -1, -1, 1, 1, 1); - - assertThat(aabb.rayTrace(new Vector(-2, 0, 0), new Vector(1, 0, 0), 10), - is(new RayTraceResult(new Vector(-1, 0, 0), BlockFace.WEST))); - assertThat(aabb.rayTrace(new Vector(2, 0, 0), new Vector(-1, 0, 0), 10), - is(new RayTraceResult(new Vector(1, 0, 0), BlockFace.EAST))); - - assertThat(aabb.rayTrace(new Vector(0, -2, 0), new Vector(0, 1, 0), 10), - is(new RayTraceResult(new Vector(0, -1, 0), BlockFace.DOWN))); - assertThat(aabb.rayTrace(new Vector(0, 2, 0), new Vector(0, -1, 0), 10), - is(new RayTraceResult(new Vector(0, 1, 0), BlockFace.UP))); - - assertThat(aabb.rayTrace(new Vector(0, 0, -2), new Vector(0, 0, 1), 10), - is(new RayTraceResult(new Vector(0, 0, -1), BlockFace.NORTH))); - assertThat(aabb.rayTrace(new Vector(0, 0, 2), new Vector(0, 0, -1), 10), - is(new RayTraceResult(new Vector(0, 0, 1), BlockFace.SOUTH))); - - assertThat(aabb.rayTrace(new Vector(0, 0, 0), new Vector(1, 0, 0), 10), - is(new RayTraceResult(new Vector(1, 0, 0), BlockFace.EAST))); - assertThat(aabb.rayTrace(new Vector(0, 0, 0), new Vector(-1, 0, 0), 10), - is(new RayTraceResult(new Vector(-1, 0, 0), BlockFace.WEST))); - - assertThat(aabb.rayTrace(new Vector(0, 0, 0), new Vector(0, 1, 0), 10), - is(new RayTraceResult(new Vector(0, 1, 0), BlockFace.UP))); - assertThat(aabb.rayTrace(new Vector(0, 0, 0), new Vector(0, -1, 0), 10), - is(new RayTraceResult(new Vector(0, -1, 0), BlockFace.DOWN))); - - assertThat(aabb.rayTrace(new Vector(0, 0, 0), new Vector(0, 0, 1), 10), - is(new RayTraceResult(new Vector(0, 0, 1), BlockFace.SOUTH))); - assertThat(aabb.rayTrace(new Vector(0, 0, 0), new Vector(0, 0, -1), 10), - is(new RayTraceResult(new Vector(0, 0, -1), BlockFace.NORTH))); - - assertThat(aabb.rayTrace(new Vector(-2, -2, -2), new Vector(1, 0, 0), 10), is(nullValue())); - assertThat(aabb.rayTrace(new Vector(-2, -2, -2), new Vector(0, 1, 0), 10), is(nullValue())); - assertThat(aabb.rayTrace(new Vector(-2, -2, -2), new Vector(0, 0, 1), 10), is(nullValue())); - - assertThat(aabb.rayTrace(new Vector(0, 0, -3), new Vector(1, 0, 1), 10), is(nullValue())); - assertThat(aabb.rayTrace(new Vector(0, 0, -2), new Vector(1, 0, 2), 10), - is(new RayTraceResult(new Vector(0.5D, 0, -1), BlockFace.NORTH))); - - // corner/edge hits yield unspecified block face: - assertThat(aabb.rayTrace(new Vector(2, 2, 2), new Vector(-1, -1, -1), 10), - anyOf(is(new RayTraceResult(new Vector(1, 1, 1), BlockFace.EAST)), - is(new RayTraceResult(new Vector(1, 1, 1), BlockFace.UP)), - is(new RayTraceResult(new Vector(1, 1, 1), BlockFace.SOUTH)))); - - assertThat(aabb.rayTrace(new Vector(-2, -2, -2), new Vector(1, 1, 1), 10), - anyOf(is(new RayTraceResult(new Vector(-1, -1, -1), BlockFace.WEST)), - is(new RayTraceResult(new Vector(-1, -1, -1), BlockFace.DOWN)), - is(new RayTraceResult(new Vector(-1, -1, -1), BlockFace.NORTH)))); - - assertThat(aabb.rayTrace(new Vector(0, 0, -2), new Vector(1, 0, 1), 10), - anyOf(is(new RayTraceResult(new Vector(1, 0, -1), BlockFace.NORTH)), - is(new RayTraceResult(new Vector(1, 0, -1), BlockFace.EAST)))); - } - - @Test - public void testSerialization() { - BoundingBox aabb = new BoundingBox(-1, -1, -1, 1, 1, 1); - Map serialized = aabb.serialize(); - BoundingBox deserialized = BoundingBox.deserialize(serialized); - assertThat(deserialized, is(aabb)); - } -} diff --git a/api/src/test/java/org/bukkit/util/StringUtilStartsWithTest.java b/api/src/test/java/org/bukkit/util/StringUtilStartsWithTest.java deleted file mode 100644 index b85a2b21e..000000000 --- a/api/src/test/java/org/bukkit/util/StringUtilStartsWithTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.bukkit.util; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.collect.ImmutableList; - -@RunWith(Parameterized.class) -public class StringUtilStartsWithTest { - - @Parameters(name= "{index}: {0} startsWith {1} == {2}") - public static List data() { - return ImmutableList.of( - new Object[] { - "Apple", - "Apples", - false - }, - new Object[] { - "Apples", - "Apple", - true - }, - new Object[] { - "Apple", - "Apple", - true - }, - new Object[] { - "Apple", - "apples", - false - }, - new Object[] { - "apple", - "Apples", - false - }, - new Object[] { - "apple", - "apples", - false - }, - new Object[] { - "Apples", - "apPL", - true - }, - new Object[] { - "123456789", - "1234567", - true - }, - new Object[] { - "", - "", - true - }, - new Object[] { - "string", - "", - true - } - ); - } - - @Parameter(0) - public String base; - @Parameter(1) - public String prefix; - @Parameter(2) - public boolean result; - - @Test - public void testFor() { - assertThat(base + " starts with " + prefix + ": " + result, StringUtil.startsWithIgnoreCase(base, prefix), is(result)); - } -} diff --git a/api/src/test/java/org/bukkit/util/StringUtilTest.java b/api/src/test/java/org/bukkit/util/StringUtilTest.java deleted file mode 100644 index 9c8444c1c..000000000 --- a/api/src/test/java/org/bukkit/util/StringUtilTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.util; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; - -import com.google.common.collect.ImmutableList; - -public class StringUtilTest { - - @Test(expected=NullPointerException.class) - public void nullPrefixTest() { - StringUtil.startsWithIgnoreCase("String", null); - } - - @Test(expected=IllegalArgumentException.class) - public void nullStringTest() { - StringUtil.startsWithIgnoreCase(null, "String"); - } - - @Test(expected=IllegalArgumentException.class) - public void nullCollectionTest() { - StringUtil.copyPartialMatches("Token", ImmutableList.of(), null); - } - - @Test(expected=IllegalArgumentException.class) - public void nullIterableTest() { - StringUtil.copyPartialMatches("Token", null, new ArrayList()); - } - - @Test(expected=IllegalArgumentException.class) - public void nullTokenTest() { - StringUtil.copyPartialMatches(null, ImmutableList.of(), new ArrayList()); - } - - @Test - public void copyTokenTest() { - String token = "ab"; - Iterable original = ImmutableList.of("ab12", "aC561", "AB5195", "Ab76", "", "a"); - List expected = ImmutableList.of("ab12", "AB5195", "Ab76" ); - List list = new ArrayList(); - assertThat(StringUtil.copyPartialMatches(token, original, list), is(expected)); - assertThat(StringUtil.copyPartialMatches(token, original, list), is(sameInstance(list))); - assertThat(list.size(), is(expected.size() * 2)); - } - - @Test(expected=UnsupportedOperationException.class) - public void copyUnsupportedTest() { - StringUtil.copyPartialMatches("token", ImmutableList.of("token1", "token2"), ImmutableList.of()); - } - - @Test(expected=IllegalArgumentException.class) - public void copyNullTest() { - StringUtil.copyPartialMatches("token", Arrays.asList("token1", "token2", null), new ArrayList()); - } -} diff --git a/api/src/test/java/org/bukkit/util/VectorTest.java b/api/src/test/java/org/bukkit/util/VectorTest.java deleted file mode 100644 index 6170f28c6..000000000 --- a/api/src/test/java/org/bukkit/util/VectorTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.bukkit.util; - -import org.bukkit.block.BlockFace; -import org.junit.Test; -import static org.junit.Assert.*; - -public class VectorTest { - - @Test - public void testNormalisedVectors() { - assertFalse(new Vector(1, 0, 0).multiply(1.1).isNormalized()); - - assertTrue(new Vector(1, 1, 1).normalize().isNormalized()); - assertTrue(new Vector(1, 0, 0).isNormalized()); - } - - @Test(expected = IllegalArgumentException.class) - public void testNullVectorAxis() { - new Vector(0, 1, 0).rotateAroundAxis(null, Math.PI); - } - - @Test - public void testBypassingAxisVector() { - new Vector(0, 1, 0).rotateAroundNonUnitAxis(new Vector(1, 1, 1), Math.PI); // This will result some weird result, but there may be some use for it for some people - } - - @Test - public void testResizeAxis() { - Vector axis = new Vector(0, 10, 0); - assertEquals(BlockFace.EAST.getDirection().rotateAroundAxis(axis, Math.PI * 0.5), BlockFace.NORTH.getDirection()); - } - - /** - * As west to east are the x axis in Minecraft, rotating around it from up - * should lead to up -> south -> down -> north. - */ - @Test - public void testRotationAroundX() { - Vector vector = BlockFace.UP.getDirection(); - assertEquals(BlockFace.SOUTH.getDirection(), vector.clone().rotateAroundX(Math.PI * 0.5)); // Should rotate around x axis for 1/4 of a circle. - assertEquals(BlockFace.DOWN.getDirection(), vector.clone().rotateAroundX(Math.PI * 1.0)); // Should rotate around x axis for 2/4 of a circle. - assertEquals(BlockFace.NORTH.getDirection(), vector.clone().rotateAroundX(Math.PI * 1.5)); // Should rotate around x axis for 3/4 of a circle. - assertEquals(BlockFace.UP.getDirection(), vector.clone().rotateAroundX(Math.PI * 2.0)); // Should rotate around x axis for 4/4 of a circle. - } - - /** - * As up to down are the y axis in Minecraft, rotating around it from up - * should lead to east (positive x) -> south -> west -> north. - */ - @Test - public void testRotationAroundY() { - Vector vector = BlockFace.EAST.getDirection(); - assertEquals(BlockFace.NORTH.getDirection(), vector.clone().rotateAroundY(Math.PI * 0.5)); // Should rotate around x axis for 1/4 of a circle. - assertEquals(BlockFace.WEST.getDirection(), vector.clone().rotateAroundY(Math.PI * 1.0)); // Should rotate around x axis for 2/4 of a circle. - assertEquals(BlockFace.SOUTH.getDirection(), vector.clone().rotateAroundY(Math.PI * 1.5)); // Should rotate around x axis for 3/4 of a circle. - assertEquals(BlockFace.EAST.getDirection(), vector.clone().rotateAroundY(Math.PI * 2.0)); // Should rotate around x axis for 4/4 of a circle. - } - - /** - * As up to down are the y axis in Minecraft, rotating around it from up - * should lead to east (positive x) -> south -> west -> north. - */ - @Test - public void testRotationAroundYUsingCustomAxis() { - Vector vector = BlockFace.EAST.getDirection(); - Vector axis = BlockFace.UP.getDirection(); - assertEquals(BlockFace.NORTH.getDirection(), vector.clone().rotateAroundAxis(axis, Math.PI * 0.5)); // Should rotate around x axis for 1/4 of a circle. - assertEquals(BlockFace.WEST.getDirection(), vector.clone().rotateAroundAxis(axis, Math.PI * 1.0)); // Should rotate around x axis for 2/4 of a circle. - assertEquals(BlockFace.SOUTH.getDirection(), vector.clone().rotateAroundAxis(axis, Math.PI * 1.5)); // Should rotate around x axis for 3/4 of a circle. - assertEquals(BlockFace.EAST.getDirection(), vector.clone().rotateAroundAxis(axis, Math.PI * 2.0)); // Should rotate around x axis for 4/4 of a circle. - } - - /** - * As south to north are the z axis in Minecraft, rotating around it from up - * should lead to up (positive y) -> west -> down -> east. - */ - @Test - public void testRotationAroundZ() { - Vector vector = BlockFace.UP.getDirection(); - assertEquals(BlockFace.WEST.getDirection(), vector.clone().rotateAroundZ(Math.PI * 0.5)); // Should rotate around x axis for 1/4 of a circle. - assertEquals(BlockFace.DOWN.getDirection(), vector.clone().rotateAroundZ(Math.PI * 1.0)); // Should rotate around x axis for 2/4 of a circle. - assertEquals(BlockFace.EAST.getDirection(), vector.clone().rotateAroundZ(Math.PI * 1.5)); // Should rotate around x axis for 3/4 of a circle. - assertEquals(BlockFace.UP.getDirection(), vector.clone().rotateAroundZ(Math.PI * 2.0)); // Should rotate around x axis for 4/4 of a circle. - } - - @Test - public void testRotationAroundAxis() { - Vector axis = new Vector(1, 0, 1); - assertEquals(new Vector(0, 1, 0).rotateAroundNonUnitAxis(axis, Math.PI * 0.5), new Vector(-1, 0, 1)); - } - - @Test - public void testRotationAroundAxisNonUnit() { - Vector axis = new Vector(0, 2, 0); - Vector v = BlockFace.EAST.getDirection(); - - assertEquals(v.rotateAroundNonUnitAxis(axis, Math.PI * 0.5), BlockFace.NORTH.getDirection().multiply(2)); - } - - /** - * This will be a bit tricky to prove so we will try to simply see if the - * vectors have correct angle to each other This will work with any two - * vectors, as the rotation will keep the angle the same. - */ - @Test - public void testRotationAroundCustomAngle() { - Vector axis = new Vector(-30, 1, 2000).normalize(); - Vector v = new Vector(53, 12, 98); - - float a = v.angle(axis); - double stepSize = Math.PI / 21; - for (int i = 0; i < 42; i++) { - v.rotateAroundAxis(axis, stepSize); - assertEquals(a, v.angle(axis), Vector.getEpsilon()); - } - } -} diff --git a/api/src/test/java/org/bukkit/util/io/BukkitObjectStreamTest.java b/api/src/test/java/org/bukkit/util/io/BukkitObjectStreamTest.java deleted file mode 100644 index d0af4a015..000000000 --- a/api/src/test/java/org/bukkit/util/io/BukkitObjectStreamTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package org.bukkit.util.io; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.List; - -import org.bukkit.Color; -import org.bukkit.FireworkEffect; -import org.bukkit.FireworkEffect.Type; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.util.Vector; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; - -import com.google.common.collect.ImmutableList; - -@RunWith(Parameterized.class) -public class BukkitObjectStreamTest { - - @Parameters(name= "{index}: {0}") - public static List data() { - return ImmutableList.of( - new Object[] { - Color.class.getName(), - "rO0ABXNyADZjb20uZ29vZ2xlLmNvbW1vbi5jb2xsZWN0LkltbXV0YWJsZUxpc3QkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAVsACGVsZW1lbnRzdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwdXIAE1tMamF2YS5sYW5nLk9iamVjdDuQzlifEHMpbAIAAHhwAAAABXNyABpvcmcuYnVra2l0LnV0aWwuaW8uV3JhcHBlcvJQR+zxEm8FAgABTAADbWFwdAAPTGphdmEvdXRpbC9NYXA7eHBzcgA1Y29tLmdvb2dsZS5jb21tb24uY29sbGVjdC5JbW11dGFibGVNYXAkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAlsABGtleXNxAH4AAVsABnZhbHVlc3EAfgABeHB1cQB+AAMAAAAEdAACPT10AANSRUR0AARCTFVFdAAFR1JFRU51cQB+AAMAAAAEdAAFQ29sb3JzcgARamF2YS5sYW5nLkludGVnZXIS4qCk94GHOAIAAUkABXZhbHVleHIAEGphdmEubGFuZy5OdW1iZXKGrJUdC5TgiwIAAHhwAAAA/3NxAH4AEQAAAP9zcQB+ABEAAAD/c3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARAAAAAHNxAH4AEQAAAIBzcQB+ABEAAACAc3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARAAAAgHNxAH4AEQAAAIBxAH4AGnNxAH4ABXNxAH4ACHVxAH4AAwAAAARxAH4AC3EAfgAMcQB+AA1xAH4ADnVxAH4AAwAAAARxAH4AEHNxAH4AEQAAAP9xAH4AGnEAfgAac3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARAAAA/3EAfgAac3EAfgARAAAApQ==", - ImmutableList.of( - Color.WHITE, - Color.TEAL, - Color.PURPLE, - Color.RED, - Color.ORANGE - ) - }, - new Object[] { - FireworkEffect.class.getName(), - "rO0ABXNyADZjb20uZ29vZ2xlLmNvbW1vbi5jb2xsZWN0LkltbXV0YWJsZUxpc3QkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAVsACGVsZW1lbnRzdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwdXIAE1tMamF2YS5sYW5nLk9iamVjdDuQzlifEHMpbAIAAHhwAAAAA3NyABpvcmcuYnVra2l0LnV0aWwuaW8uV3JhcHBlcvJQR+zxEm8FAgABTAADbWFwdAAPTGphdmEvdXRpbC9NYXA7eHBzcgA1Y29tLmdvb2dsZS5jb21tb24uY29sbGVjdC5JbW11dGFibGVNYXAkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAlsABGtleXNxAH4AAVsABnZhbHVlc3EAfgABeHB1cQB+AAMAAAAGdAACPT10AAdmbGlja2VydAAFdHJhaWx0AAZjb2xvcnN0AAtmYWRlLWNvbG9yc3QABHR5cGV1cQB+AAMAAAAGdAAIRmlyZXdvcmtzcgARamF2YS5sYW5nLkJvb2xlYW7NIHKA1Zz67gIAAVoABXZhbHVleHABc3EAfgATAHNxAH4AAHVxAH4AAwAAAAJzcQB+AAVzcQB+AAh1cQB+AAMAAAAEcQB+AAt0AANSRUR0AARCTFVFdAAFR1JFRU51cQB+AAMAAAAEdAAFQ29sb3JzcgARamF2YS5sYW5nLkludGVnZXIS4qCk94GHOAIAAUkABXZhbHVleHIAEGphdmEubGFuZy5OdW1iZXKGrJUdC5TgiwIAAHhwAAAAAHEAfgAicQB+ACJzcQB+AAVzcQB+AAh1cQB+AAMAAAAEcQB+AAtxAH4AG3EAfgAccQB+AB11cQB+AAMAAAAEcQB+AB9zcQB+ACAAAADAc3EAfgAgAAAAwHNxAH4AIAAAAMBzcQB+AAB1cQB+AAMAAAABc3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+ABtxAH4AHHEAfgAddXEAfgADAAAABHEAfgAfc3EAfgAgAAAA/3NxAH4AIAAAAP9zcQB+ACAAAAD/dAAKQkFMTF9MQVJHRXNxAH4ABXNxAH4ACHVxAH4AAwAAAAZxAH4AC3EAfgAMcQB+AA1xAH4ADnEAfgAPcQB+ABB1cQB+AAMAAAAGcQB+ABJxAH4AFXEAfgAVc3EAfgAAdXEAfgADAAAAAXNxAH4ABXNxAH4ACHVxAH4AAwAAAARxAH4AC3EAfgAbcQB+ABxxAH4AHXVxAH4AAwAAAARxAH4AH3EAfgAic3EAfgAgAAAAgHEAfgAic3EAfgAAdXEAfgADAAAAAHQABEJBTExzcQB+AAVzcQB+AAh1cQB+AAMAAAAGcQB+AAtxAH4ADHEAfgANcQB+AA5xAH4AD3EAfgAQdXEAfgADAAAABnEAfgAScQB+ABRxAH4AFHNxAH4AAHVxAH4AAwAAAAFzcQB+AAVzcQB+AAh1cQB+AAMAAAAEcQB+AAtxAH4AG3EAfgAccQB+AB11cQB+AAMAAAAEcQB+AB9zcQB+ACAAAACAcQB+ACJxAH4AInEAfgA/dAAHQ1JFRVBFUg==", - ImmutableList.of( - FireworkEffect.builder() - .withColor(Color.BLACK, Color.SILVER) - .with(Type.BALL_LARGE) - .withFade(Color.WHITE) - .withFlicker() - .build(), - FireworkEffect.builder() - .withColor(Color.NAVY) - .build(), - FireworkEffect.builder() - .withColor(Color.MAROON) - .withTrail() - .withFlicker() - .with(Type.CREEPER) - .build() - ), - }, - new Object[] { - Vector.class.getName(), - "rO0ABXNyADZjb20uZ29vZ2xlLmNvbW1vbi5jb2xsZWN0LkltbXV0YWJsZUxpc3QkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAVsACGVsZW1lbnRzdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwdXIAE1tMamF2YS5sYW5nLk9iamVjdDuQzlifEHMpbAIAAHhwAAAABHNyABpvcmcuYnVra2l0LnV0aWwuaW8uV3JhcHBlcvJQR+zxEm8FAgABTAADbWFwdAAPTGphdmEvdXRpbC9NYXA7eHBzcgA1Y29tLmdvb2dsZS5jb21tb24uY29sbGVjdC5JbW11dGFibGVNYXAkU2VyaWFsaXplZEZvcm0AAAAAAAAAAAIAAlsABGtleXNxAH4AAVsABnZhbHVlc3EAfgABeHB1cQB+AAMAAAAEdAACPT10AAF4dAABeXQAAXp1cQB+AAMAAAAEdAAGVmVjdG9yc3IAEGphdmEubGFuZy5Eb3VibGWAs8JKKWv7BAIAAUQABXZhbHVleHIAEGphdmEubGFuZy5OdW1iZXKGrJUdC5TgiwIAAHhwAAAAAAAAAABzcQB+ABEAAAAAAAAAAHNxAH4AEQAAAAAAAAAAc3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARQIOFwo9cKPZzcQB+ABFAtCKcKPXCj3NxAH4AEUBzrpeNT987c3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARwEQTMzMzMzNzcQB+ABFASYAAAAAAAHNxAH4AEcCjqG3UQTVUc3EAfgAFc3EAfgAIdXEAfgADAAAABHEAfgALcQB+AAxxAH4ADXEAfgAOdXEAfgADAAAABHEAfgAQc3EAfgARQd/////AAABzcQB+ABHB4AAAAAAAAHNxAH4AEQAAAAAAAAAA", - ImmutableList.of( - new Vector(0, 0, 0), - new Vector(624.72, 5154.61, 314.912), - new Vector(-40.15, 51, -2516.21451), - new Vector(Integer.MAX_VALUE, Integer.MIN_VALUE, 0) - ) - }); - } - - @Parameter(0) - public String className; - - @Parameter(1) - public String preEncoded; - - @Parameter(2) - public List object; - - @Test - public void checkSerlialization() throws Throwable { - // If this test fails, you may start your trek to debug by commenting the '@Ignore' on the next method - // (and of course, you would read those comments too) - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream oos = null; - try { - oos = new BukkitObjectOutputStream(out); - oos.writeObject(object); - } finally { - if (oos != null) { - try { - oos.close(); - } catch (IOException e) { - } - } - } - - final byte[] preEncodedArray = Base64Coder.decode(preEncoded); - - final Object readBack; - final Object preEncoded; - - ObjectInputStream ois = null; - ObjectInputStream preois = null; - try { - ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); - ByteArrayInputStream preIn = new ByteArrayInputStream(preEncodedArray); - ois = new BukkitObjectInputStream(in); - preois = new BukkitObjectInputStream(preIn); - - readBack = ois.readObject(); - preEncoded = preois.readObject(); - } finally { - if (ois != null) { - try { - ois.close(); - } catch (IOException ex) { - } - } - if (preois != null) { - try { - preois.close(); - } catch (IOException ex) { - } - } - } - - assertThat(object, is(readBack)); - assertThat(object, is(preEncoded)); - } - - @Ignore - @Test - public void preEncoded() throws Throwable { - // This test is placed in the case that a necessary change is made to change the encoding format - // Just remove the ignore (or run manually) and it'll give you the new pre-encoded values - - // It really does not matter if the encoded array is different per system (hence why this test is set to not run), - // as long as all systems can deserialize it. - - // The entire reason the pre-encoded string was added is to make a build (test) fail if someone accidentally makes it not backward-compatible - - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream oos = null; - try { - oos = new BukkitObjectOutputStream(out); - oos.writeObject(object); - oos.flush(); - } finally { - if (oos != null) { - try { - oos.close(); - } catch (IOException e) { - } - } - } - - final String string = new String(Base64Coder.encode(out.toByteArray())); - try { - assertThat(preEncoded, is(string)); - } catch (Throwable t) { - System.out.println(className + ": \"" + string + "\""); - throw t; - } - } -} diff --git a/build.gradle b/build.gradle deleted file mode 100644 index b82d4a8e2..000000000 --- a/build.gradle +++ /dev/null @@ -1,57 +0,0 @@ -apply plugin: 'java' -apply plugin: 'maven' - -group = 'com.destroystokyo.paper' -version = '1.15.2-R0.1-SNAPSHOT' - -description = """Akarin""" - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -tasks.withType(JavaCompile) { - options.encoding = 'UTF-8' -} - -repositories { - - maven { url "https://hub.spigotmc.org/nexus/content/groups/public/" } - maven { url "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" } - maven { url "https://papermc.io/repo/repository/maven-public/" } - maven { url "https://nexus.piratescode.co.uk/" } - maven { url "https://repo.spongepowered.org/maven/" } - maven { url "https://oss.sonatype.org/content/repositories" } - maven { url "https://zoidberg.ukp.informatik.tu-darmstadt.de/artifactory/public-releases/" } - maven { url "https://repo.md-5.net/content/repositories/releases/" } - maven { url "https://repo.aikar.co/content/groups/aikar/" } - maven { url "https://repo.maven.apache.org/maven2" } -} -dependencies { - compile group: 'com.destroystokyo.paper', name: 'paper-api', version:'1.14.4-R0.1-SNAPSHOT' - compile group: 'org.spigotmc', name: 'minecraft-server', version:'1.14.4-SNAPSHOT' - compile group: 'net.minecrell', name: 'terminalconsoleappender', version:'1.1.1' - compile group: 'org.apache.logging.log4j', name: 'log4j-core', version:'2.8.1' - compile group: 'org.apache.logging.log4j', name: 'log4j-iostreams', version:'2.8.1' - compile group: 'org.ow2.asm', name: 'asm', version:'7.1' - compile group: 'com.github.ben-manes.caffeine', name: 'caffeine', version:'2.7.0' - compile group: 'com.koloboke', name: 'koloboke-api-jdk8', version:'1.0.0' - compile group: 'gnu.trove', name: 'trove', version:'3.0.3' - compile group: 'org.jetbrains', name: 'annotations', version:'16.0.1' - compile group: 'io.netty', name: 'netty-all', version:'4.1.42.Final' - runtime group: 'net.java.dev.jna', name: 'jna', version:'4.5.2' - runtime group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version:'2.8.1' - runtime group: 'com.lmax', name: 'disruptor', version:'3.4.2' - runtime group: 'org.xerial', name: 'sqlite-jdbc', version:'3.28.0' - runtime group: 'mysql', name: 'mysql-connector-java', version:'5.1.47' - runtime group: 'com.koloboke', name: 'koloboke-impl-jdk8', version:'1.0.0' - runtime group: 'it.unimi.dsi', name: 'fastutil', version:'8.2.2' - runtime group: 'com.google.code.findbugs', name: 'jsr305', version:'1.3.9' - runtime group: 'com.google.guava', name: 'guava', version:'21.0' - runtime group: 'com.google.code.gson', name: 'gson', version:'2.8.0' - runtime group: 'org.jetbrains', name: 'annotations-java5', version:'17.0.0' - runtime group: 'org.slf4j', name: 'slf4j-api', version:'1.7.25' - runtime group: 'org.ow2.asm', name: 'asm-commons', version:'7.1' - testCompile group: 'junit', name: 'junit', version:'4.12' - testCompile group: 'org.hamcrest', name: 'hamcrest-library', version:'1.3' - compileOnly group: 'org.projectlombok', name: 'lombok', version:'1.16.20' -} diff --git a/current-paper b/current-paper new file mode 100644 index 000000000..a7b0be95c --- /dev/null +++ b/current-paper @@ -0,0 +1 @@ +1.15.2--cc4590cd4fd38d2230ceea00a69d281ac531d457 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 5c2d1cf01..000000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index a2bf1313b..000000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.2-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew deleted file mode 100755 index 83f2acfdc..000000000 --- a/gradlew +++ /dev/null @@ -1,188 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or authors. -# -# 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 -# -# 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. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 24467a141..000000000 --- a/gradlew.bat +++ /dev/null @@ -1,100 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/patches/api/0001-POM-Changes.patch b/patches/api/0001-POM-Changes.patch new file mode 100644 index 000000000..a8441d252 --- /dev/null +++ b/patches/api/0001-POM-Changes.patch @@ -0,0 +1,36 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?=E3=84=97=E3=84=A0=CB=8B=20=E3=84=91=E3=84=A7=CB=8A?= + +Date: Fri, 14 Dec 2018 21:52:29 -0800 +Subject: [PATCH] POM Changes + + +diff --git a/pom.xml b/pom.xml +index 2cb9714084c8a7aa1b20d445edd5be4cc206672f..d167304be5ca4d067886a9740230b25b9fa21b56 100644 +--- a/pom.xml ++++ b/pom.xml +@@ -3,18 +3,18 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + +- com.destroystokyo.paper +- paper-parent ++ io.akarin.server ++ akarin-parent + dev-SNAPSHOT ++ ../pom.xml + + +- com.destroystokyo.paper +- paper-api ++ akarin-api + 1.15.2-R0.1-SNAPSHOT + jar + +- Paper-API +- https://github.com/PaperMC/Paper ++ Akarin-API ++ https://github.com/Akarin-project/Akarin + An enhanced plugin API for Minecraft servers. + + diff --git a/patches/server/0001-POM-Changes.patch b/patches/server/0001-POM-Changes.patch new file mode 100644 index 000000000..bf69c049f --- /dev/null +++ b/patches/server/0001-POM-Changes.patch @@ -0,0 +1,81 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?=E3=84=97=E3=84=A0=CB=8B=20=E3=84=91=E3=84=A7=CB=8A?= + +Date: Fri, 14 Dec 2018 21:53:58 -0800 +Subject: [PATCH] POM Changes + + +diff --git a/pom.xml b/pom.xml +index 55679af926485eca6bb0b9ed368a4c91c8a7e37e..19f87edb55a48b151f81f899cedbc573aec66405 100644 +--- a/pom.xml ++++ b/pom.xml +@@ -1,12 +1,11 @@ +- + 4.0.0 +- paper ++ akarin + jar + 1.15.2-R0.1-SNAPSHOT +- Paper +- https://papermc.io +- ++ Akarin-Server ++ https://github.com/Akarin-project/Akarin + + + UTF-8 +@@ -21,16 +20,16 @@ + + + +- com.destroystokyo.paper +- paper-parent ++ io.akarin.server ++ akarin-parent + dev-SNAPSHOT + ../pom.xml + + + + +- com.destroystokyo.paper +- paper-api ++ io.akarin.server ++ akarin-api + ${project.version} + compile + +@@ -143,15 +142,15 @@ + + + +- paper-${minecraft.version} +- clean install ++ akarin-${minecraft.version} ++ install + + + com.lukegb.mojo + gitdescribe-maven-plugin + 1.3 + +- git-Paper- ++ git-Akarin- + .. + + +diff --git a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java +index 674096cab190d62622f9947853b056f57d43a2a5..9a7235b8e525fbc52ff7ce53156816f9bbdb5d6f 100644 +--- a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java ++++ b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java +@@ -11,7 +11,7 @@ public final class Versioning { + public static String getBukkitVersion() { + String result = "Unknown-Version"; + +- InputStream stream = Bukkit.class.getClassLoader().getResourceAsStream("META-INF/maven/com.destroystokyo.paper/paper-api/pom.properties"); ++ InputStream stream = Bukkit.class.getClassLoader().getResourceAsStream("META-INF/maven/io.akarin.server/akarin-api/pom.properties"); // Akarin + Properties properties = new Properties(); + + if (stream != null) { diff --git a/patches/server/0002-Brand-changes.patch b/patches/server/0002-Brand-changes.patch new file mode 100644 index 000000000..abf6dcd62 --- /dev/null +++ b/patches/server/0002-Brand-changes.patch @@ -0,0 +1,46 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: =?UTF-8?q?=E3=84=97=E3=84=A0=CB=8B=20=E3=84=91=E3=84=A7=CB=8A?= + +Date: Tue, 18 Dec 2018 06:27:02 -0800 +Subject: [PATCH] Brand changes + + +diff --git a/src/main/java/net/minecraft/server/EULA.java b/src/main/java/net/minecraft/server/EULA.java +index cf00f35a5b7c2d2f6b6989e0855de8b882dcef50..a45e63a02759305e119a41eac55a7f40488dd12c 100644 +--- a/src/main/java/net/minecraft/server/EULA.java ++++ b/src/main/java/net/minecraft/server/EULA.java +@@ -70,7 +70,7 @@ public class EULA { + Properties properties = new Properties(); + + properties.setProperty("eula", "false"); +- properties.store(outputstream, "By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).\nYou also agree that tacos are tasty, and the best food in the world."); // Paper - fix lag; ++ properties.store(outputstream, "By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula)."); // Paper - fix lag; // Akarin - Tacos are disgusting + } catch (Throwable throwable1) { + throwable = throwable1; + throw throwable1; +diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java +index c9deaffc4a317c8ec75d9e6ef5889ab909e2fbe8..4dd21b5e15ab2bd5b09ab1bb6e60cc3ae1bfd00e 100644 +--- a/src/main/java/net/minecraft/server/MinecraftServer.java ++++ b/src/main/java/net/minecraft/server/MinecraftServer.java +@@ -1484,7 +1484,7 @@ public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant // Spigot - Spigot > // CraftBukkit - cb > vanilla! ++ return "Akarin"; // Akarin //Paper - Paper > // Spigot - Spigot > // CraftBukkit - cb > vanilla! + } + + public CrashReport b(CrashReport crashreport) { +diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java +index b9a398bc577b16317057d70bb43a261b078d67a9..b03443f9a72a3c455f49746fea2f555c2f53e504 100644 +--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java ++++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java +@@ -203,7 +203,7 @@ import javax.annotation.Nullable; // Paper + import javax.annotation.Nonnull; // Paper + + public final class CraftServer implements Server { +- private final String serverName = "Paper"; // Paper ++ private final String serverName = "Akarin"; // Paper // Akarin + private final String serverVersion; + private final String bukkitVersion = Versioning.getBukkitVersion(); + private final Logger logger = Logger.getLogger("Minecraft"); diff --git a/pom.xml b/pom.xml index 88a2c2351..b6e26aae1 100644 --- a/pom.xml +++ b/pom.xml @@ -1,432 +1,18 @@ - + 4.0.0 - akarin - jar - 1.15.2-R0.1-SNAPSHOT - Akarin - https://github.com/Akarin-project/Akarin - - - UTF-8 - 1.15.2-R0.1-SNAPSHOT - 1.15.2 - 1_15_R1 - git-Bukkit- - - yyyyMMdd-HHmm - 1.8 - 1.8 - + io.akarin.server + akarin-parent + dev-SNAPSHOT + pom + Akarin (Parent) - - - com.destroystokyo.paper - paper-parent - dev-SNAPSHOT - ../pom.xml - - - - - com.destroystokyo.paper - paper-api - ${api.version} - compile - - - org.spigotmc - minecraft-server - ${minecraft.version}-SNAPSHOT - compile - - - net.minecrell - terminalconsoleappender - 1.1.1 - - - net.java.dev.jna - jna - 4.5.2 - runtime - - - - org.apache.logging.log4j - log4j-core - 2.8.1 - compile - - - org.apache.logging.log4j - log4j-slf4j-impl - 2.8.1 - runtime - - - org.apache.logging.log4j - log4j-iostreams - 2.8.1 - - - - com.lmax - disruptor - 3.4.2 - runtime - - - org.ow2.asm - asm - 7.1 - compile - - - org.xerial - sqlite-jdbc - 3.28.0 - runtime - - - mysql - mysql-connector-java - 5.1.47 - runtime - - - - junit - junit - 4.12 - test - - - org.hamcrest - hamcrest-library - 1.3 - test - - - - com.github.ben-manes.caffeine - caffeine - 2.7.0 - - - com.koloboke - koloboke-api-jdk8 - 1.0.0 - - - com.koloboke - koloboke-impl-jdk8 - 1.0.0 - runtime - - - - gnu.trove - trove - 3.0.3 - - - org.jetbrains - annotations - 16.0.1 - - - org.projectlombok - lombok - 1.16.20 - provided - - - io.netty - netty-all - 4.1.42.Final - - - - it.unimi.dsi - fastutil - 8.2.2 - runtime - - - com.google.code.findbugs - jsr305 - 1.3.9 - runtime - - - com.google.guava - guava - 21.0 - runtime - - - com.google.code.gson - gson - 2.8.0 - runtime - - - org.jetbrains - annotations-java5 - 17.0.0 - runtime - - - org.slf4j - slf4j-api - 1.7.25 - runtime - - - org.ow2.asm - asm-commons - 7.1 - runtime - - - - - - - spigotmc-public - https://hub.spigotmc.org/nexus/content/groups/public/ - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - - papermc - https://papermc.io/repo/repository/maven-public/ - - - piratescode - https://nexus.piratescode.co.uk/ - - - spongepowered-repo - https://repo.spongepowered.org/maven/ - - - sonatype-nexusg - https://oss.sonatype.org/content/repositories - - - tu-darmstadt - https://zoidberg.ukp.informatik.tu-darmstadt.de/artifactory/public-releases/ - - - - - - spigotmc-public - https://hub.spigotmc.org/nexus/content/groups/public/ - - - - - akarin-${minecraft.version} - clean install - - - com.lukegb.mojo - gitdescribe-maven-plugin - 1.3 - - git-Akarin- - ../.. - - - - compile - - gitdescribe - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - true - - - org.bukkit.craftbukkit.Main - CraftBukkit - - ${describe} - ${maven.build.timestamp} - Bukkit - ${api.version} - Bukkit Team - - - - net/bukkit/ - - true - - - - com/bukkit/ - - true - - - - org/bukkit/ - - true - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.1.1 - - - package - - shade - - - ${project.build.directory}/dependency-reduced-pom.xml - ${shadeSourcesJar} - - - - - jline - org.bukkit.craftbukkit.libs.jline - - - - - - - - org.bukkit.craftbukkit - org.bukkit.craftbukkit.v${minecraft_version} - - org.bukkit.craftbukkit.Main* - - - - net.minecraft.server - net.minecraft.server.v${minecraft_version} - - - - - META-INF/services/java.sql.Driver - - - - - - - - - com.github.edwgiz - maven-shade-plugin.log4j2-cachefile-transformer - 2.8.1 - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - - - org.codehaus.plexus - plexus-compiler-eclipse - 2.8.5-spigotmc - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12.4 - - ${basedir}/target/test-server - - org/bukkit/craftbukkit/inventory/ItemStack*Test.java - - - - + install + ${project.artifactId} - - - - shadeSourcesJar - - true - true - - - - development - - false - - - - - org.codehaus.mojo - animal-sniffer-maven-plugin - 1.17 - - - process-classes - - check - - - - - - org.codehaus.mojo.signature - java18 - 1.0 - - - - - - - + + Akarin-API + Akarin-Server + diff --git a/scripts/apply.sh b/scripts/apply.sh new file mode 100755 index 000000000..b48a3b057 --- /dev/null +++ b/scripts/apply.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# get base dir regardless of execution location +# resolve shell-specifics +case "$(echo "$SHELL" | sed -E 's|/usr(/local)?||g')" in + "/bin/zsh") + RCPATH="$HOME/.zshrc" + SOURCE="${BASH_SOURCE[0]:-${(%):-%N}}" + ;; + *) + RCPATH="$HOME/.bashrc" + if [[ -f "$HOME/.bash_aliases" ]]; then + RCPATH="$HOME/.bash_aliases" + fi + SOURCE="${BASH_SOURCE[0]}" + ;; +esac + +# get base dir regardless of execution location + +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +. $(dirname $SOURCE)/init.sh +PS1="$" + +paperVer=$(cat current-paper) +gpgsign="$(git config commit.gpgsign || echo "false")" +echo "Rebuilding Forked projects.... " +function applyPatch { + what=$1 + what_name=$(basename $what) + target=$2 + branch=$3 + patch_folder=$4 + + cd "$basedir/$what" + git fetch --all + git branch -f upstream "$branch" >/dev/null + + cd "$basedir" + if [ ! -d "$basedir/$target" ]; then + mkdir "$basedir/$target" + cd "$basedir/$target" + git init + git remote add origin "$5" + cd "$basedir" + fi + cd "$basedir/$target" + + # Disable GPG signing before AM, slows things down and doesn't play nicely. + # There is also zero rational or logical reason to do so for these sub-repo AMs. + # Calm down kids, it's re-enabled (if needed) immediately after, pass or fail. + git config commit.gpgsign false + + echo "Resetting $target to $what_name..." + git remote rm upstream > /dev/null 2>&1 + git remote add upstream "$basedir/$what" >/dev/null 2>&1 + git checkout master 2>/dev/null || git checkout -b master + git fetch upstream >/dev/null 2>&1 + git reset --hard upstream/upstream + echo " Applying patches to $target..." + git am --abort >/dev/null 2>&1 + git am --3way --ignore-whitespace "$basedir/patches/$patch_folder/"*.patch + if [ "$?" != "0" ]; then + echo " Something did not apply cleanly to $target." + echo " Please review above details and finish the apply then" + echo " save the changes with rebuildPatches.sh" + exit 1 + else + echo " Patches applied cleanly to $target" + fi +} + +function enableCommitSigningIfNeeded { + if [[ "$gpgsign" == "true" ]]; then + git config commit.gpgsign true + fi +} + + echo "Importing MC-DEV" + ./scripts/importmcdev.sh "$basedir" || exit 1 +( + (applyPatch Paper/Paper-API ${FORK_NAME}-API HEAD api $API_REPO && + applyPatch Paper/Paper-Server ${FORK_NAME}-Server HEAD server $SERVER_REPO) || exit 1 + enableCommitSigningIfNeeded +) || ( + echo "Failed to apply patches" + enableCommitSigningIfNeeded + exit 1 +) || exit 1 diff --git a/scripts/build.sh b/scripts/build.sh deleted file mode 100755 index 9915c2d52..000000000 --- a/scripts/build.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bash - -( -set -e -basedir="$(cd "$1" && pwd -P)" -workdir="$basedir/work" -paperbasedir="$basedir/work/Paper" -paperworkdir="$basedir/work/Paper/work" - -if [[ "$2" == "--setup" ]] || [[ "$3" == "--setup" ]] || [[ "$4" == "--setup" ]]; then - echo "[Akarin] Setup Paper.." - ( - if [[ "$2" == "--remote" ]] || [[ "$3" == "--remote" ]] || [[ "$4" == "--remote" ]]; then - cd "$paperworkdir" - if [[ -d "Minecraft" ]]; then - rm Minecraft/ -r - fi - git clone https://github.com/Akarin-project/Minecraft.git - fi - - #cd "$paperbasedir" - #./paper patch - ) -fi - -echo "[Akarin] Ready to build" -( - cd "$paperbasedir" - echo "[Akarin] Touch sources.." - - cd "$paperbasedir" - if [[ "$2" == "--fast" ]] || [[ "$3" == "--fast" ]] || [[ "$4" == "--fast" ]]; then - echo "[Akarin] Test and repatch has been skipped" - echo "$paperbasedir/if" - \cp -rf "$basedir/api/src/main" "$paperbasedir/Paper-API/src/" - \cp -rf "$basedir/api/pom.xml" "$paperbasedir/Paper-API/" - \cp -rf "$basedir/src" "$paperbasedir/Paper-Server/" - \cp -rf "$basedir/pom.xml" "$paperbasedir/Paper-Server/" - mvn clean install -Dmaven.test.skip=true - else - echo "$paperbasedir/else" - rm -rf Paper-API/src - rm -rf Paper-Server/src - ./paper patch - \cp -rf "$basedir/api/src/main" "$paperbasedir/Paper-API/src/" - \cp -rf "$basedir/api/pom.xml" "$paperbasedir/Paper-API/" - \cp -rf "$basedir/src" "$paperbasedir/Paper-Server/" - \cp -rf "$basedir/pom.xml" "$paperbasedir/Paper-Server/" - mvn clean install -Dmaven.test.skip=true - fi - - minecraftversion=$(cat "$paperworkdir/BuildData/info.json" | grep minecraftVersion | cut -d '"' -f 4) - rawjar="$paperbasedir/Paper-Server/target/akarin-$minecraftversion.jar" - \cp -rf "$rawjar" "$basedir/akarin-$minecraftversion.jar" - rawapi="$paperbasedir/Paper-API/target/akarin-api-1.15.2-R0.1-SNAPSHOT.jar" - \cp -rf "$rawapi" "$basedir/akarin-api-1.15.2-R0.1-SNAPSHOT.jar" - - echo "" - echo "[Akarin] Build successful" - echo "[Akarin] Migrated the final jar to $basedir/" -) - -) diff --git a/scripts/generatesources.sh b/scripts/generatesources.sh new file mode 100755 index 000000000..e5d7c7790 --- /dev/null +++ b/scripts/generatesources.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +. $(dirname $SOURCE)/init.sh + + +cd $basedir +paperVer=$(cat current-paper) + +minecraftversion=$(cat $basedir/Paper/work/BuildData/info.json | grep minecraftVersion | cut -d '"' -f 4) +decompile="Paper/work/Minecraft/$minecraftversion/spigot" + +mkdir -p mc-dev/src/net/minecraft/server + +cd mc-dev +if [ ! -d ".git" ]; then + git init +fi + +rm src/net/minecraft/server/*.java +cp $basedir/$decompile/net/minecraft/server/*.java src/net/minecraft/server + +base="$basedir/Paper/Paper-Server/src/main/java/net/minecraft/server" +cd $basedir/mc-dev/src/net/minecraft/server/ +for file in $(/bin/ls $base) +do + if [ -f "$file" ]; then + rm -f "$file" + fi +done +cd $basedir/mc-dev +git add . -A +git commit . -m "mc-dev" +git tag -a "$paperVer" -m "$paperVer" 2>/dev/null +pushRepo . $MCDEV_REPO $paperVer diff --git a/scripts/gradlebuild.sh b/scripts/gradlebuild.sh deleted file mode 100644 index 799fa4ad0..000000000 --- a/scripts/gradlebuild.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash - -( -set -e -version="master" -basedir="$(cd "$1" && pwd -P)" -workdir="$basedir/work" -paperbasedir="$basedir/work/Paper" -paperworkdir="$basedir/work/Paper/work" - -# init -git submodule update --init --remote -cd "$basedir" - -echo "[Akarin] Setup Paper.." -cd "$paperworkdir" -if [[ -d "Minecraft" ]]; then - rm Minecraft/ -r -fi -git clone https://github.com/Akarin-project/Minecraft.git - -echo "[Akarin] Ready to build" - -cd "$paperbasedir" -echo "[Akarin] Touch sources.." - -rm -rf Paper-API/src -rm -rf Paper-Server/src -./paper patch -\cp -rf "$basedir/api/src/main" "$paperbasedir/Paper-API/src/" -\cp -rf "$basedir/api/pom.xml" "$paperbasedir/Paper-API/" -\cp -rf "$basedir/src" "$paperbasedir/Paper-Server/" -\cp -rf "$basedir/pom.xml" "$paperbasedir/Paper-Server/" - -cd "$basedir" -bash ./gradlew install - -minecraftversion=$(cat "$paperworkdir/BuildData/info.json" | grep minecraftVersion | cut -d '"' -f 4) -rawjar="$paperbasedir/Paper-Server/target/akarin-$minecraftversion.jar" -\cp -rf "$rawjar" "$basedir/akarin-$minecraftversion.jar" -rawapi="$paperbasedir/Paper-API/target/akarin-api-1.14.4-R0.1-SNAPSHOT.jar" -\cp -rf "$rawapi" "$basedir/akarin-api-1.14.4-R0.1-SNAPSHOT.jar" - -echo "" -echo "[Akarin] Build successful" -echo "[Akarin] Migrated the final jar to $basedir/" - -) diff --git a/scripts/importmcdev.sh b/scripts/importmcdev.sh new file mode 100755 index 000000000..585447d6c --- /dev/null +++ b/scripts/importmcdev.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env bash + +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +. $(dirname $SOURCE)/init.sh + +workdir="$basedir"/Paper/work +minecraftversion=$(cat "$basedir"/Paper/work/BuildData/info.json | grep minecraftVersion | cut -d '"' -f 4) +decompiledir=$workdir/Minecraft/$minecraftversion/spigot + +nms="net/minecraft/server" +export MODLOG="" +cd "$basedir" + +function containsElement { + local e + for e in "${@:2}"; do + [[ "$e" == "$1" ]] && return 0; + done + return 1 +} + +export importedmcdev="" +function import { + if [ -f "$basedir/Paper/Paper-Server/src/main/java/net/minecraft/server/$1.java" ]; then + echo "ALREADY IMPORTED $1" + return 0 + fi + export importedmcdev="$importedmcdev $1" + file="${1}.java" + target="$basedir/Paper/Paper-Server/src/main/java/$nms/$file" + base="$decompiledir/$nms/$file" + + if [[ ! -f "$target" ]]; then + export MODLOG="$MODLOG Imported $file from mc-dev\n"; + echo "$(bashColor 1 32) Copying $(bashColor 1 34)$base $(bashColor 1 32)to$(bashColor 1 34) $target $(bashColorReset)" + cp "$base" "$target" + else + echo "$(bashColor 1 33) UN-NEEDED IMPORT STATEMENT:$(bashColor 1 34) $file $(bashColorReset)" + fi +} + +function importLibrary { + group=$1 + lib=$2 + prefix=$3 + shift 3 + for file in "$@"; do + file="$prefix/$file" + target="$basedir/Paper/Paper-Server/src/main/java/$file" + targetdir=$(dirname "$target") + mkdir -p "${targetdir}" + base="$workdir/Minecraft/$minecraftversion/libraries/${group}/${lib}/$file" + if [ ! -f "$base" ]; then + echo "Missing $base" + exit 1 + fi + export MODLOG="$MODLOG Imported $file from $lib\n"; + sed 's/\r$//' "$base" > "$target" || exit 1 + done +} + +( + cd Paper/Paper-Server/ + lastlog=$(git log -1 --oneline) + if [[ "$lastlog" = *"Tuinity-Extra mc-dev Imports"* ]]; then + git reset --hard HEAD^ + fi +) + + +files=$(cat patches/server/* | grep "+++ b/src/main/java/net/minecraft/server/" | sort | uniq | sed 's/\+\+\+ b\/src\/main\/java\/net\/minecraft\/server\///g' | sed 's/.java//g') + +nonnms=$(cat patches/server/* | grep "create mode " | grep -Po "src/main/java/net/minecraft/server/(.*?).java" | sort | uniq | sed 's/src\/main\/java\/net\/minecraft\/server\///g' | sed 's/.java//g') + +for f in $files; do + containsElement "$f" ${nonnms[@]} + if [ "$?" == "1" ]; then + if [ ! -f "$basedir/Paper/Paper-Server/src/main/java/net/minecraft/server/$f.java" ]; then + if [ ! -f "$decompiledir/$nms/$f.java" ]; then + echo "$(bashColor 1 31) ERROR!!! Missing NMS$(bashColor 1 34) $f $(bashColorReset)"; + else + import $f + fi + fi + fi +done + +############################################################################################### +############################################################################################### +#################### ADD TEMPORARY ADDITIONS HERE ############################################# +############################################################################################### +############################################################################################### + +# import Foo + +######################################################## +######################################################## +######################################################## +# LIBRARY IMPORTS +# These must always be mapped manually, no automatic stuff +# +# # group # lib # prefix # many files + +importLibrary com.mojang datafixerupper com/mojang/datafixers/util Either.java + +################ +( + cd Paper/Paper-Server/ + rm -rf nms-patches + git add src -A + echo -e "Tuinity-Extra mc-dev Imports\n\n$MODLOG" | git commit src -F - + exit 0 +) diff --git a/scripts/init.sh b/scripts/init.sh new file mode 100755 index 000000000..9d6780a08 --- /dev/null +++ b/scripts/init.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# BEGIN config +FORK_NAME="Akarin" +API_REPO="" +SERVER_REPO="" +PAPER_API_REPO="" +PAPER_SERVER_REPO="" +MCDEV_REPO="" +# END config + +sourceBase=$(dirname $SOURCE)/../ +cd "${basedir:-$sourceBase}" + +basedir=$(pwd -P) +cd - + + +function bashColor { +if [ $2 ]; then + echo -e "\e[$1;$2m" +else + echo -e "\e[$1m" +fi +} +function bashColorReset { + echo -e "\e[m" +} + +function cleanupPatches { + cd "$1" + for patch in *.patch; do + gitver=$(tail -n 2 $patch | grep -ve "^$" | tail -n 1) + diffs=$(git diff --staged $patch | grep -E "^(\+|\-)" | grep -Ev "(From [a-z0-9]{32,}|\-\-\- a|\+\+\+ b|.index|Date\: )") + + testver=$(echo "$diffs" | tail -n 2 | grep -ve "^$" | tail -n 1 | grep "$gitver") + if [ "x$testver" != "x" ]; then + diffs=$(echo "$diffs" | tail -n +3) + fi + + if [ "x$diffs" == "x" ] ; then + git reset HEAD $patch >/dev/null + git checkout -- $patch >/dev/null + fi + done +} +function pushRepo { + if [ "$(git config minecraft.push-${FORK_NAME})" == "1" ]; then + echo "Pushing - $1 ($3) to $2" + ( + cd "$1" + git remote rm emc-push > /dev/null 2>&1 + git remote add emc-push $2 >/dev/null 2>&1 + git push emc-push $3 -f + ) + fi +} +function basedir { + cd "$basedir" +} +function gethead { + ( + cd "$1" + git log -1 --oneline + ) +} diff --git a/scripts/inst.sh b/scripts/inst.sh deleted file mode 100755 index 6bbc40d14..000000000 --- a/scripts/inst.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash - -( -set -e -basedir="$(pwd -P)" -version="master" - -(git submodule update --init --remote && cd "$basedir" && chmod +x scripts/build.sh && ./scripts/build.sh "$basedir" "$1" "$2" "$3") || ( - echo "Failed to build Akarin" - exit 1 -) || exit 1 - -) \ No newline at end of file diff --git a/scripts/paperclip.sh b/scripts/paperclip.sh new file mode 100755 index 000000000..f2af9ab9a --- /dev/null +++ b/scripts/paperclip.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +# Copied from https://github.com/PaperMC/Paper/blob/d54ce6c17fb7a35238d6b9f734d30a4289886773/scripts/paperclip.sh +# License from Paper applies to this file + +( +set -e +basedir="$(cd "$1" && pwd -P)" +workdir="$basedir/Paper/work" +mcver=$(cat "$workdir/BuildData/info.json" | grep minecraftVersion | cut -d '"' -f 4) +paperjar="$basedir/Akarin-Server/target/akarin-$mcver.jar" +vanillajar="$workdir/Minecraft/$mcver/$mcver.jar" + +( + cd "$workdir/Paperclip" + mvn clean package "-Dmcver=$mcver" "-Dpaperjar=$paperjar" "-Dvanillajar=$vanillajar" +) +cp "$workdir/Paperclip/assembly/target/paperclip-${mcver}.jar" "$basedir/akarin-paperclip.jar" + +echo "" +echo "" +echo "" +echo "Build success!" +echo "Copied final jar to $(cd "$basedir" && pwd -P)/akarin-paperclip.jar" +) || exit 1 diff --git a/scripts/push.sh b/scripts/push.sh new file mode 100755 index 000000000..ed4bf9f00 --- /dev/null +++ b/scripts/push.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# get base dir regardless of execution location +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +. $(dirname $SOURCE)/init.sh + +minecraftversion=$(cat $basedir/Paper/work/BuildData/info.json | grep minecraftVersion | cut -d '"' -f 4) + +basedir +pushRepo ${FORK_NAME}-API $API_REPO master:$minecraftversion +pushRepo ${FORK_NAME}-Server $SERVER_REPO master:$minecraftversion diff --git a/scripts/rebuildpatches.sh b/scripts/rebuildpatches.sh new file mode 100755 index 000000000..e09a74d14 --- /dev/null +++ b/scripts/rebuildpatches.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# get base dir regardless of execution location +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +. $(dirname $SOURCE)/init.sh + +PS1="$" +echo "Rebuilding patch files from current fork state..." +function savePatches { + what=$1 + cd $basedir/$what/ + + mkdir -p $basedir/patches/$2 + if [ -d ".git/rebase-apply" ]; then + # in middle of a rebase, be smarter + echo "REBASE DETECTED - PARTIAL SAVE" + last=$(cat ".git/rebase-apply/last") + next=$(cat ".git/rebase-apply/next") + declare -a files=("$basedir/patches/$2/"*.patch) + for i in $(seq -f "%04g" 1 1 $last) + do + if [ $i -lt $next ]; then + rm "${files[`expr $i - 1`]}" + fi + done + else + rm $basedir/patches/$2/*.patch + fi + + git format-patch --no-signature --zero-commit --full-index --no-stat -N -o $basedir/patches/$2 upstream/upstream + cd $basedir + git add -A $basedir/patches/$2 + echo " Patches saved for $what to patches/$2" +} + +savePatches ${FORK_NAME}-API api +savePatches ${FORK_NAME}-Server server + +$basedir/scripts/push.sh diff --git a/scripts/upstream.sh b/scripts/upstream.sh new file mode 100755 index 000000000..2f434d383 --- /dev/null +++ b/scripts/upstream.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# get base dir regardless of execution location +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +. $(dirname $SOURCE)/init.sh + +git submodule update --init --recursive + +if [[ "$1" == up* ]]; then + ( + cd "$basedir/Paper/" + git fetch && git reset --hard origin/master + cd ../ + git add Paper + ) +fi + +paperVer=$(gethead Paper) +cd "$basedir/Paper/" + +./paper patch + +cd "Paper-Server" +mcVer=$(mvn -o org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=minecraft_version | sed -n -e '/^\[.*\]/ !{ /^[0-9]/ { p; q } }') + +basedir +. "$basedir"/scripts/importmcdev.sh + +minecraftversion=$(cat "$basedir"/Paper/work/BuildData/info.json | grep minecraftVersion | cut -d '"' -f 4) +version=$(echo -e "Paper: $paperVer\nmc-dev:$importedmcdev") +tag="${minecraftversion}-${mcVer}-$(echo -e $version | shasum | awk '{print $1}')" +echo "$tag" > "$basedir"/current-paper + +"$basedir"/scripts/generatesources.sh + +cd Paper/ + +function tag { +( + cd $1 + if [ "$2" == "1" ]; then + git tag -d "$tag" 2>/dev/null + fi + echo -e "$(date)\n\n$version" | git tag -a "$tag" -F - 2>/dev/null +) +} +echo "Tagging as $tag" +echo -e "$version" + +forcetag=0 +if [ "$(cat "$basedir"/current-paper)" != "$tag" ]; then + forcetag=1 +fi + +tag Paper-API $forcetag +tag Paper-Server $forcetag + +pushRepo Paper-API $PAPER_API_REPO $tag +pushRepo Paper-Server $PAPER_SERVER_REPO $tag + diff --git a/scripts/upstreamCommit.sh b/scripts/upstreamCommit.sh new file mode 100755 index 000000000..c68788ffa --- /dev/null +++ b/scripts/upstreamCommit.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +( +set -e +PS1="$" + +function changelog() { + base=$(git ls-tree HEAD $1 | cut -d' ' -f3 | cut -f1) + cd $1 && git log --oneline ${base}...HEAD +} +paper=$(changelog Paper) + +updated="" +logsuffix="" +if [ ! -z "$paper" ]; then + logsuffix="$logsuffix\n\nPaper Changes:\n$paper" + if [ -z "$updated" ]; then updated="Paper"; else updated="$updated/Paper"; fi +fi +disclaimer="Upstream has released updates that appears to apply and compile correctly" + +if [ ! -z "$1" ]; then + disclaimer="$@" +fi + +log="${UP_LOG_PREFIX}Updated Upstream ($updated)\n\n${disclaimer}${logsuffix}" + +echo -e "$log" | git commit -F - + +) || exit 1 \ No newline at end of file diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index fa7fac7da..000000000 --- a/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'akarin' diff --git a/src/main/java/co/aikar/timings/MinecraftTimings.java b/src/main/java/co/aikar/timings/MinecraftTimings.java deleted file mode 100644 index c6818bc86..000000000 --- a/src/main/java/co/aikar/timings/MinecraftTimings.java +++ /dev/null @@ -1,135 +0,0 @@ -package co.aikar.timings; - -import com.google.common.collect.MapMaker; -import net.minecraft.server.*; -import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitTask; - -import org.bukkit.craftbukkit.scheduler.CraftTask; - -import java.util.Map; - -// TODO: Re-implement missing timers -public final class MinecraftTimings { - - public static final Timing serverOversleep = Timings.ofSafe("Server Oversleep"); - public static final Timing playerListTimer = Timings.ofSafe("Player List"); - public static final Timing commandFunctionsTimer = Timings.ofSafe("Command Functions"); - public static final Timing connectionTimer = Timings.ofSafe("Connection Handler"); - public static final Timing tickablesTimer = Timings.ofSafe("Tickables"); - public static final Timing minecraftSchedulerTimer = Timings.ofSafe("Minecraft Scheduler"); - public static final Timing bukkitSchedulerTimer = Timings.ofSafe("Bukkit Scheduler"); - public static final Timing bukkitSchedulerPendingTimer = Timings.ofSafe("Bukkit Scheduler - Pending"); - public static final Timing bukkitSchedulerFinishTimer = Timings.ofSafe("Bukkit Scheduler - Finishing"); - public static final Timing chunkIOTickTimer = Timings.ofSafe("ChunkIOTick"); - public static final Timing timeUpdateTimer = Timings.ofSafe("Time Update"); - public static final Timing serverCommandTimer = Timings.ofSafe("Server Command"); - public static final Timing savePlayers = Timings.ofSafe("Save Players"); - - public static final Timing tickEntityTimer = Timings.ofSafe("## tickEntity"); - public static final Timing tickTileEntityTimer = Timings.ofSafe("## tickTileEntity"); - public static final Timing packetProcessTimer = Timings.ofSafe("## Packet Processing"); - public static final Timing scheduledBlocksTimer = Timings.ofSafe("## Scheduled Blocks"); - public static final Timing structureGenerationTimer = Timings.ofSafe("Structure Generation"); - - public static final Timing processQueueTimer = Timings.ofSafe("processQueue"); - public static final Timing processTasksTimer = Timings.ofSafe("processTasks"); - - public static final Timing playerCommandTimer = Timings.ofSafe("playerCommand"); - - public static final Timing entityActivationCheckTimer = Timings.ofSafe("entityActivationCheck"); - - public static final Timing antiXrayUpdateTimer = Timings.ofSafe("anti-xray - update"); - public static final Timing antiXrayObfuscateTimer = Timings.ofSafe("anti-xray - obfuscate"); - - private static final Map, String> taskNameCache = new MapMaker().weakKeys().makeMap(); - - private MinecraftTimings() {} - - /** - * Gets a timer associated with a plugins tasks. - * @param bukkitTask - * @param period - * @return - */ - public static Timing getPluginTaskTimings(BukkitTask bukkitTask, long period) { - if (!bukkitTask.isSync()) { - return NullTimingHandler.NULL; - } - Plugin plugin; - - CraftTask craftTask = (CraftTask) bukkitTask; - - final Class taskClass = craftTask.getTaskClass(); - if (bukkitTask.getOwner() != null) { - plugin = bukkitTask.getOwner(); - } else { - plugin = TimingsManager.getPluginByClassloader(taskClass); - } - - final String taskname = taskNameCache.computeIfAbsent(taskClass, clazz -> - clazz.isAnonymousClass() || clazz.isLocalClass() - ? clazz.getName() - : clazz.getCanonicalName()); - - StringBuilder name = new StringBuilder(64); - name.append("Task: ").append(taskname); - if (period > 0) { - name.append(" (interval:").append(period).append(")"); - } else { - name.append(" (Single)"); - } - - if (plugin == null) { - return Timings.ofSafe(null, name.toString()); - } - - return Timings.ofSafe(plugin, name.toString()); - } - - /** - * Get a named timer for the specified entity type to track type specific timings. - * @param entity - * @return - */ - public static Timing getEntityTimings(Entity entity) { - String entityType = entity.getClass().getName(); - return Timings.ofSafe("Minecraft", "## tickEntity - " + entityType, tickEntityTimer); - } - - /** - * Get a named timer for the specified tile entity type to track type specific timings. - * @param entity - * @return - */ - public static Timing getTileEntityTimings(TileEntity entity) { - String entityType = entity.getClass().getName(); - return Timings.ofSafe("Minecraft", "## tickTileEntity - " + entityType, tickTileEntityTimer); - } - public static Timing getCancelTasksTimer() { - return Timings.ofSafe("Cancel Tasks"); - } - public static Timing getCancelTasksTimer(Plugin plugin) { - return Timings.ofSafe(plugin, "Cancel Tasks"); - } - - public static void stopServer() { - TimingsManager.stopServer(); - } - - public static Timing getBlockTiming(Block block) { - return Timings.ofSafe("## Scheduled Block: " + block.toString(), scheduledBlocksTimer); - } -/* - public static Timing getStructureTiming(StructureGenerator structureGenerator) { - return Timings.ofSafe("Structure Generator - " + structureGenerator.getName(), structureGenerationTimer); - }*/ - - public static Timing getPacketTiming(Packet packet) { - return Timings.ofSafe("## Packet - " + packet.getClass().getSimpleName(), packetProcessTimer); - } - - public static Timing getCommandFunctionTiming(CustomFunction function) { - return Timings.ofSafe("Command Function - " + function.getMinecraftKey().toString()); - } -} diff --git a/src/main/java/co/aikar/timings/WorldTimingsHandler.java b/src/main/java/co/aikar/timings/WorldTimingsHandler.java deleted file mode 100644 index ddec62fbf..000000000 --- a/src/main/java/co/aikar/timings/WorldTimingsHandler.java +++ /dev/null @@ -1,156 +0,0 @@ -package co.aikar.timings; - -import net.minecraft.server.World; -import net.minecraft.server.WorldServer; - -/** - * Set of timers per world, to track world specific timings. - */ -// TODO: Re-implement missing timers -public class WorldTimingsHandler { - public final Timing mobSpawn; - public final Timing doChunkUnload; - public final Timing doPortalForcer; - public final Timing scheduledBlocks; - public final Timing scheduledBlocksCleanup; - public final Timing scheduledBlocksTicking; - public final Timing chunkTicks; - public final Timing lightChunk; - public final Timing chunkTicksBlocks; - public final Timing doVillages; - public final Timing doChunkMap; - public final Timing doChunkMapUpdate; - public final Timing doChunkMapToUpdate; - public final Timing doChunkMapSortMissing; - public final Timing doChunkMapSortSendToPlayers; - public final Timing doChunkMapPlayersNeedingChunks; - public final Timing doChunkMapPendingSendToPlayers; - public final Timing doChunkMapUnloadChunks; - public final Timing doChunkGC; - public final Timing doSounds; - public final Timing entityRemoval; - public final Timing entityTick; - public final Timing tileEntityTick; - public final Timing tileEntityPending; - public final Timing tracker1; - public final Timing tracker2; - public final Timing doTick; - public final Timing tickEntities; - public final Timing chunks; - public final Timing newEntities; - public final Timing raids; - public final Timing chunkProviderTick; - public final Timing broadcastChunkUpdates; - public final Timing countNaturalMobs; - - public final Timing syncChunkLoadTimer; - public final Timing syncChunkLoadDataTimer; - public final Timing syncChunkLoadStructuresTimer; - public final Timing syncChunkLoadPostTimer; - public final Timing syncChunkLoadPopulateTimer; - public final Timing chunkAwait; - public final Timing chunkLoadLevelTimer; - public final Timing chunkGeneration; - public final Timing chunkIOStage1; - public final Timing chunkIOStage2; - public final Timing worldSave; - public final Timing worldSaveChunks; - public final Timing worldSaveLevel; - public final Timing chunkSaveData; - - - public final Timing miscMobSpawning; - public final Timing chunkRangeCheckBig; - public final Timing chunkRangeCheckSmall; - - public final Timing poiUnload; - public final Timing chunkUnload; - public final Timing poiSaveDataSerialization; - public final Timing chunkSave; - public final Timing chunkSaveOverwriteCheck; - public final Timing chunkSaveDataSerialization; - public final Timing chunkSaveIOWait; - public final Timing chunkUnloadPrepareSave; - public final Timing chunkUnloadPOISerialization; - public final Timing chunkUnloadDataSave; - - public final Timing playerMobDistanceMapUpdate; - - public WorldTimingsHandler(World server) { - String name = server.worldData.getName() +" - "; - - mobSpawn = Timings.ofSafe(name + "mobSpawn"); - doChunkUnload = Timings.ofSafe(name + "doChunkUnload"); - scheduledBlocks = Timings.ofSafe(name + "Scheduled Blocks"); - scheduledBlocksCleanup = Timings.ofSafe(name + "Scheduled Blocks - Cleanup"); - scheduledBlocksTicking = Timings.ofSafe(name + "Scheduled Blocks - Ticking"); - chunkTicks = Timings.ofSafe(name + "Chunk Ticks"); - lightChunk = Timings.ofSafe(name + "Light Chunk"); - chunkTicksBlocks = Timings.ofSafe(name + "Chunk Ticks - Blocks"); - doVillages = Timings.ofSafe(name + "doVillages"); - doChunkMap = Timings.ofSafe(name + "doChunkMap"); - doChunkMapUpdate = Timings.ofSafe(name + "doChunkMap - Update"); - doChunkMapToUpdate = Timings.ofSafe(name + "doChunkMap - To Update"); - doChunkMapSortMissing = Timings.ofSafe(name + "doChunkMap - Sort Missing"); - doChunkMapSortSendToPlayers = Timings.ofSafe(name + "doChunkMap - Sort Send To Players"); - doChunkMapPlayersNeedingChunks = Timings.ofSafe(name + "doChunkMap - Players Needing Chunks"); - doChunkMapPendingSendToPlayers = Timings.ofSafe(name + "doChunkMap - Pending Send To Players"); - doChunkMapUnloadChunks = Timings.ofSafe(name + "doChunkMap - Unload Chunks"); - doSounds = Timings.ofSafe(name + "doSounds"); - doChunkGC = Timings.ofSafe(name + "doChunkGC"); - doPortalForcer = Timings.ofSafe(name + "doPortalForcer"); - entityTick = Timings.ofSafe(name + "entityTick"); - entityRemoval = Timings.ofSafe(name + "entityRemoval"); - tileEntityTick = Timings.ofSafe(name + "tileEntityTick"); - tileEntityPending = Timings.ofSafe(name + "tileEntityPending"); - - syncChunkLoadTimer = Timings.ofSafe(name + "syncChunkLoad"); - syncChunkLoadDataTimer = Timings.ofSafe(name + "syncChunkLoad - Data"); - syncChunkLoadStructuresTimer = Timings.ofSafe(name + "chunkLoad - recreateStructures"); - syncChunkLoadPostTimer = Timings.ofSafe(name + "chunkLoad - Post"); - syncChunkLoadPopulateTimer = Timings.ofSafe(name + "chunkLoad - Populate"); - chunkAwait = Timings.ofSafe(name + "chunkAwait"); - chunkLoadLevelTimer = Timings.ofSafe(name + "chunkLoad - Load Level"); - chunkGeneration = Timings.ofSafe(name + "chunkGeneration"); - chunkIOStage1 = Timings.ofSafe(name + "ChunkIO Stage 1 - DiskIO"); - chunkIOStage2 = Timings.ofSafe(name + "ChunkIO Stage 2 - Post Load"); - worldSave = Timings.ofSafe(name + "World Save"); - worldSaveLevel = Timings.ofSafe(name + "World Save - Level"); - worldSaveChunks = Timings.ofSafe(name + "World Save - Chunks"); - chunkSaveData = Timings.ofSafe(name + "Chunk Save - Data"); - - tracker1 = Timings.ofSafe(name + "tracker stage 1"); - tracker2 = Timings.ofSafe(name + "tracker stage 2"); - doTick = Timings.ofSafe(name + "doTick"); - tickEntities = Timings.ofSafe(name + "tickEntities"); - - chunks = Timings.ofSafe(name + "Chunks"); - newEntities = Timings.ofSafe(name + "New entity registration"); - raids = Timings.ofSafe(name + "Raids"); - chunkProviderTick = Timings.ofSafe(name + "Chunk provider tick"); - broadcastChunkUpdates = Timings.ofSafe(name + "Broadcast chunk updates"); - countNaturalMobs = Timings.ofSafe(name + "Count natural mobs"); - - - miscMobSpawning = Timings.ofSafe(name + "Mob spawning - Misc"); - chunkRangeCheckBig = Timings.ofSafe(name + "Chunk Tick Range - Big"); - chunkRangeCheckSmall = Timings.ofSafe(name + "Chunk Tick Range - Small"); - - poiUnload = Timings.ofSafe(name + "Chunk unload - POI"); - chunkUnload = Timings.ofSafe(name + "Chunk unload - Chunk"); - poiSaveDataSerialization = Timings.ofSafe(name + "Chunk save - POI Data serialization"); - chunkSave = Timings.ofSafe(name + "Chunk save - Chunk"); - chunkSaveOverwriteCheck = Timings.ofSafe(name + "Chunk save - Chunk Overwrite Check"); - chunkSaveDataSerialization = Timings.ofSafe(name + "Chunk save - Chunk Data serialization"); - chunkSaveIOWait = Timings.ofSafe(name + "Chunk save - Chunk IO Wait"); - chunkUnloadPrepareSave = Timings.ofSafe(name + "Chunk unload - Async Save Prepare"); - chunkUnloadPOISerialization = Timings.ofSafe(name + "Chunk unload - POI Data Serialization"); - chunkUnloadDataSave = Timings.ofSafe(name + "Chunk unload - Data Serialization"); - - playerMobDistanceMapUpdate = Timings.ofSafe(name + "Per Player Mob Spawning - Distance Map Update"); - } - - public static Timing getTickList(WorldServer worldserver, String timingsType) { - return Timings.ofSafe(worldserver.getWorldData().getName() + " - Scheduled " + timingsType); - } -} diff --git a/src/main/java/com/destroystokyo/paper/Metrics.java b/src/main/java/com/destroystokyo/paper/Metrics.java deleted file mode 100644 index e257d6b36..000000000 --- a/src/main/java/com/destroystokyo/paper/Metrics.java +++ /dev/null @@ -1,627 +0,0 @@ -package com.destroystokyo.paper; - -import net.minecraft.server.MinecraftServer; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -import javax.net.ssl.HttpsURLConnection; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.zip.GZIPOutputStream; - -/** - * bStats collects some data for plugin authors. - * - * Check out https://bStats.org/ to learn more about bStats! - */ -public class Metrics { - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/server-implementation"; - - // Should failed requests be logged? - private static boolean logFailedRequests = false; - - // The logger for the failed requests - private static Logger logger = Logger.getLogger("bStats"); - - // The name of the server software - private final String name; - - // The uuid of the server - private final String serverUUID; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param name The name of the server software. - * @param serverUUID The uuid of the server. - * @param logFailedRequests Whether failed requests should be logged or not. - * @param logger The logger for the failed requests. - */ - public Metrics(String name, String serverUUID, boolean logFailedRequests, Logger logger) { - this.name = name; - this.serverUUID = serverUUID; - Metrics.logFailedRequests = logFailedRequests; - Metrics.logger = logger; - - // Start submitting the data - startSubmitting(); - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - submitData(); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * - * @return The plugin specific data. - */ - private JSONObject getPluginData() { - JSONObject data = new JSONObject(); - - data.put("pluginName", name); // Append the name of the server software - JSONArray customCharts = new JSONArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JSONObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.put("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JSONObject getServerData() { - // OS specific data - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JSONObject data = new JSONObject(); - - data.put("serverUUID", serverUUID); - - data.put("osName", osName); - data.put("osArch", osArch); - data.put("osVersion", osVersion); - data.put("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JSONObject data = getServerData(); - - JSONArray pluginData = new JSONArray(); - pluginData.add(getPluginData()); - data.put("plugins", pluginData); - - try { - // We are still in the Thread of the timer, so nothing get blocked :) - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - logger.log(Level.WARNING, "Could not submit stats of " + name, e); - } - } - } - - /** - * Sends the data to the bStats server. - * - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(JSONObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - connection.getInputStream().close(); // We don't care about the response - Just send our data :) - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(outputStream); - gzip.write(str.getBytes("UTF-8")); - gzip.close(); - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - private JSONObject getRequestJsonObject() { - JSONObject chart = new JSONObject(); - chart.put("chartId", chartId); - try { - JSONObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.put("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - logger.log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JSONObject getChartData() throws Exception; - - } - - /** - * Represents a custom simple pie. - */ - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - - /** - * Represents a custom drilldown pie. - */ - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JSONObject value = new JSONObject(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - value.put(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - values.put(entryValues.getKey(), value); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JSONArray categoryValues = new JSONArray(); - categoryValues.add(entry.getValue()); - values.put(entry.getKey(), categoryValues); - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JSONObject getChartData() throws Exception { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JSONArray categoryValues = new JSONArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(categoryValue); - } - values.put(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - static class PaperMetrics { - static void startMetrics() { - // Get the config file - File configFile = new File(new File((File) MinecraftServer.getServer().options.valueOf("plugins"), "bStats"), "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { - } - } - // Load the data - String serverUUID = config.getString("serverUuid"); - boolean logFailedRequests = config.getBoolean("logFailedRequests", false); - // Only start Metrics, if it's enabled in the config - if (config.getBoolean("enabled", true)) { - Metrics metrics = new Metrics("Paper", serverUUID, logFailedRequests, Bukkit.getLogger()); - - metrics.addCustomChart(new Metrics.SimplePie("minecraft_version", () -> { - String minecraftVersion = Bukkit.getVersion(); - minecraftVersion = minecraftVersion.substring(minecraftVersion.indexOf("MC: ") + 4, minecraftVersion.length() - 1); - return minecraftVersion; - })); - - metrics.addCustomChart(new Metrics.SingleLineChart("players", () -> Bukkit.getOnlinePlayers().size())); - metrics.addCustomChart(new Metrics.SimplePie("online_mode", () -> Bukkit.getOnlineMode() ? "online" : "offline")); - metrics.addCustomChart(new Metrics.SimplePie("paper_version", () -> (Metrics.class.getPackage().getImplementationVersion() != null) ? Metrics.class.getPackage().getImplementationVersion() : "unknown")); - - metrics.addCustomChart(new Metrics.DrilldownPie("java_version", () -> { - Map> map = new HashMap<>(); - String javaVersion = System.getProperty("java.version"); - Map entry = new HashMap<>(); - entry.put(javaVersion, 1); - - // http://openjdk.java.net/jeps/223 - // Java decided to change their versioning scheme and in doing so modified the java.version system - // property to return $major[.$minor][.$secuity][-ea], as opposed to 1.$major.0_$identifier - // we can handle pre-9 by checking if the "major" is equal to "1", otherwise, 9+ - String majorVersion = javaVersion.split("\\.")[0]; - String release; - - int indexOf = javaVersion.lastIndexOf('.'); - - if (majorVersion.equals("1")) { - release = "Java " + javaVersion.substring(0, indexOf); - } else { - // of course, it really wouldn't be all that simple if they didn't add a quirk, now would it - // valid strings for the major may potentially include values such as -ea to deannotate a pre release - Matcher versionMatcher = Pattern.compile("\\d+").matcher(majorVersion); - if (versionMatcher.find()) { - majorVersion = versionMatcher.group(0); - } - release = "Java " + majorVersion; - } - map.put(release, entry); - - return map; - })); - } - - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/PaperCommand.java b/src/main/java/com/destroystokyo/paper/PaperCommand.java deleted file mode 100644 index 132397b3f..000000000 --- a/src/main/java/com/destroystokyo/paper/PaperCommand.java +++ /dev/null @@ -1,403 +0,0 @@ -package com.destroystokyo.paper; - -import com.destroystokyo.paper.io.SyncLoadFinder; -import com.google.common.base.Functions; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.gson.JsonObject; -import com.google.gson.internal.Streams; -import com.google.gson.stream.JsonWriter; -import net.minecraft.server.*; -import org.apache.commons.lang3.tuple.MutablePair; -import org.apache.commons.lang3.tuple.Pair; -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.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.entity.Player; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.PrintStream; -import java.io.StringWriter; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.stream.Collectors; - -public class PaperCommand extends Command { - - public PaperCommand(String name) { - super(name); - this.description = "Paper related commands"; - this.usageMessage = "/paper [heap | entity | reload | version | debug | chunkinfo]"; - this.setPermission("bukkit.command.paper"); - } - - @Override - public List tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException { - if (args.length <= 1) - return getListMatchingLast(args, "heap", "entity", "reload", "version", "debug", "chunkinfo"); - - switch (args[0].toLowerCase(Locale.ENGLISH)) - { - case "entity": - if (args.length == 2) - return getListMatchingLast(args, "help", "list"); - if (args.length == 3) - return getListMatchingLast(args, EntityTypes.getEntityNameList().stream().map(MinecraftKey::toString).sorted().toArray(String[]::new)); - break; - case "debug": - if (args.length == 2) { - return getListMatchingLast(args, "help", "chunks"); - } - break; - case "chunkinfo": - List worldNames = new ArrayList<>(); - worldNames.add("*"); - for (org.bukkit.World world : Bukkit.getWorlds()) { - worldNames.add(world.getName()); - } - if (args.length == 2) { - return getListMatchingLast(args, worldNames); - } - break; - } - return Collections.emptyList(); - } - - // Code from Mojang - copyright them - public static List getListMatchingLast(String[] args, String... matches) { - return getListMatchingLast(args, (Collection) Arrays.asList(matches)); - } - - public static boolean matches(String s, String s1) { - return s1.regionMatches(true, 0, s, 0, s.length()); - } - - public static List getListMatchingLast(String[] strings, Collection collection) { - String last = strings[strings.length - 1]; - ArrayList results = Lists.newArrayList(); - - if (!collection.isEmpty()) { - Iterator iterator = Iterables.transform(collection, Functions.toStringFunction()).iterator(); - - while (iterator.hasNext()) { - String s1 = (String) iterator.next(); - - if (matches(last, s1)) { - results.add(s1); - } - } - - if (results.isEmpty()) { - iterator = collection.iterator(); - - while (iterator.hasNext()) { - Object object = iterator.next(); - - if (object instanceof MinecraftKey && matches(last, ((MinecraftKey) object).getKey())) { - results.add(String.valueOf(object)); - } - } - } - } - - return results; - } - // end copy stuff - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!testPermission(sender)) return true; - - if (args.length == 0) { - sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); - return false; - } - - switch (args[0].toLowerCase(Locale.ENGLISH)) { - case "heap": - dumpHeap(sender); - break; - case "entity": - listEntities(sender, args); - break; - case "reload": - doReload(sender); - break; - case "debug": - doDebug(sender, args); - break; - case "chunkinfo": - doChunkInfo(sender, args); - break; - case "syncloadinfo": - this.doSyncLoadInfo(sender, args); - break; - case "ver": - case "version": - Command ver = org.bukkit.Bukkit.getServer().getCommandMap().getCommand("version"); - if (ver != null) { - ver.execute(sender, commandLabel, new String[0]); - break; - } - // else - fall through to default - default: - sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); - return false; - } - - return true; - } - - private void doSyncLoadInfo(CommandSender sender, String[] args) { - if (!SyncLoadFinder.ENABLED) { - sender.sendMessage(ChatColor.RED + "This command requires the server startup flag '-Dpaper.debug-sync-loads=true' to be set."); - return; - } - File file = new File(new File(new File("."), "debug"), - "sync-load-info" + DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss").format(LocalDateTime.now()) + ".txt"); - file.getParentFile().mkdirs(); - sender.sendMessage(ChatColor.GREEN + "Writing sync load info to " + file.toString()); - - - try { - final JsonObject data = SyncLoadFinder.serialize(); - - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); - jsonWriter.setIndent(" "); - jsonWriter.setLenient(false); - Streams.write(data, jsonWriter); - - String fileData = stringWriter.toString(); - - try ( - PrintStream out = new PrintStream(new FileOutputStream(file), false, "UTF-8") - ) { - out.print(fileData); - } - sender.sendMessage(ChatColor.GREEN + "Successfully written sync load information!"); - } catch (Throwable thr) { - sender.sendMessage(ChatColor.RED + "Failed to write sync load information"); - thr.printStackTrace(); - } - } - - private void doChunkInfo(CommandSender sender, String[] args) { - List worlds; - if (args.length < 2 || args[1].equals("*")) { - worlds = Bukkit.getWorlds(); - } else { - worlds = new ArrayList<>(args.length - 1); - for (int i = 1; i < args.length; ++i) { - org.bukkit.World world = Bukkit.getWorld(args[i]); - if (world == null) { - sender.sendMessage(ChatColor.RED + "World '" + args[i] + "' is invalid"); - return; - } - worlds.add(world); - } - } - - for (org.bukkit.World bukkitWorld : worlds) { - WorldServer world = ((CraftWorld)bukkitWorld).getHandle(); - - int total = 0; - int inactive = 0; - int border = 0; - int ticking = 0; - int entityTicking = 0; - - for (PlayerChunk chunk : world.getChunkProvider().playerChunkMap.updatingChunks.values()) { - if (chunk.getFullChunkIfCached() == null) { - continue; - } - - ++total; - - PlayerChunk.State state = PlayerChunk.getChunkState(chunk.getTicketLevel()); - - switch (state) { - case INACCESSIBLE: - ++inactive; - continue; - case BORDER: - ++border; - continue; - case TICKING: - ++ticking; - continue; - case ENTITY_TICKING: - ++entityTicking; - continue; - } - } - - sender.sendMessage(ChatColor.BLUE + "Chunks in " + ChatColor.GREEN + bukkitWorld.getName() + ChatColor.DARK_AQUA + ":"); - sender.sendMessage(ChatColor.BLUE + "Total: " + ChatColor.DARK_AQUA + total + ChatColor.BLUE + " Inactive: " + ChatColor.DARK_AQUA - + inactive + ChatColor.BLUE + " Border: " + ChatColor.DARK_AQUA + border + ChatColor.BLUE + " Ticking: " - + ChatColor.DARK_AQUA + ticking + ChatColor.BLUE + " Entity: " + ChatColor.DARK_AQUA + entityTicking); - } - } - - private void doDebug(CommandSender sender, String[] args) { - if (args.length < 2) { - sender.sendMessage(ChatColor.RED + "Use /paper debug [chunks] help for more information on a specific command"); - return; - } - - String debugType = args[1].toLowerCase(Locale.ENGLISH); - switch (debugType) { - case "chunks": - if (args.length >= 3 && args[2].toLowerCase(Locale.ENGLISH).equals("help")) { - sender.sendMessage(ChatColor.RED + "Use /paper debug chunks to dump loaded chunk information to a file"); - break; - } - File file = new File(new File(new File("."), "debug"), - "chunks-" + DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss").format(LocalDateTime.now()) + ".txt"); - sender.sendMessage(ChatColor.GREEN + "Writing chunk information dump to " + file.toString()); - try { - MCUtil.dumpChunks(file); - sender.sendMessage(ChatColor.GREEN + "Successfully written chunk information!"); - } catch (Throwable thr) { - MinecraftServer.LOGGER.warn("Failed to dump chunk information to file " + file.toString(), thr); - sender.sendMessage(ChatColor.RED + "Failed to dump chunk information, see console"); - } - - break; - case "help": - // fall through to default - default: - sender.sendMessage(ChatColor.RED + "Use /paper debug [chunks] help for more information on a specific command"); - return; - } - } - - /* - * Ported from MinecraftForge - author: LexManos - License: LGPLv2.1 - */ - private void listEntities(CommandSender sender, String[] args) { - if (args.length < 2 || args[1].toLowerCase(Locale.ENGLISH).equals("help")) { - sender.sendMessage(ChatColor.RED + "Use /paper entity [list] help for more information on a specific command."); - return; - } - - switch (args[1].toLowerCase(Locale.ENGLISH)) { - case "list": - String filter = "*"; - if (args.length > 2) { - if (args[2].toLowerCase(Locale.ENGLISH).equals("help")) { - sender.sendMessage(ChatColor.RED + "Use /paper entity list [filter] [worldName] to get entity info that matches the optional filter."); - return; - } - filter = args[2]; - } - final String cleanfilter = filter.replace("?", ".?").replace("*", ".*?"); - Set names = EntityTypes.getEntityNameList().stream() - .filter(n -> n.toString().matches(cleanfilter)) - .collect(Collectors.toSet()); - - if (names.isEmpty()) { - sender.sendMessage(ChatColor.RED + "Invalid filter, does not match any entities. Use /paper entity list for a proper list"); - return; - } - - String worldName; - if (args.length > 3) { - worldName = args[3]; - } else if (sender instanceof Player) { - worldName = ((Player) sender).getWorld().getName(); - } else { - sender.sendMessage(ChatColor.RED + "Please specify the name of a world"); - sender.sendMessage(ChatColor.RED + "To do so without a filter, specify '*' as the filter"); - return; - } - - Map>> list = Maps.newHashMap(); - World bukkitWorld = Bukkit.getWorld(worldName); - if (bukkitWorld == null) { - sender.sendMessage(ChatColor.RED + "Could not load world for " + worldName + ". Please select a valid world."); - return; - } - WorldServer world = ((CraftWorld) Bukkit.getWorld(worldName)).getHandle(); - - Collection entities = world.entitiesById.values(); - entities.forEach(e -> { - if (!e.isChunkLoaded()) { - return; - } - MinecraftKey key = e.getMinecraftKey(); - if (e.shouldBeRemoved) return; // Paper - - MutablePair> info = list.computeIfAbsent(key, k -> MutablePair.of(0, Maps.newHashMap())); - ChunkCoordIntPair chunk = new ChunkCoordIntPair(e.getChunkX(), e.getChunkZ()); - info.left++; - info.right.put(chunk, info.right.getOrDefault(chunk, 0) + 1); - }); - - if (names.size() == 1) { - MinecraftKey name = names.iterator().next(); - Pair> info = list.get(name); - if (info == null) { - sender.sendMessage(ChatColor.RED + "No entities found."); - return; - } - sender.sendMessage("Entity: " + name + " Total: " + info.getLeft()); - info.getRight().entrySet().stream() - .sorted((a, b) -> !a.getValue().equals(b.getValue()) ? b.getValue() - a.getValue() : a.getKey().toString().compareTo(b.getKey().toString())) - .limit(10).forEach(e -> sender.sendMessage(" " + e.getValue() + ": " + e.getKey().x + ", " + e.getKey().z)); - } else { - List> info = list.entrySet().stream() - .filter(e -> names.contains(e.getKey())) - .map(e -> Pair.of(e.getKey(), e.getValue().left)) - .sorted((a, b) -> !a.getRight().equals(b.getRight()) ? b.getRight() - a.getRight() : a.getKey().toString().compareTo(b.getKey().toString())) - .collect(Collectors.toList()); - - if (info == null || info.size() == 0) { - sender.sendMessage(ChatColor.RED + "No entities found."); - return; - } - - int count = info.stream().mapToInt(Pair::getRight).sum(); - sender.sendMessage("Total: " + count); - info.forEach(e -> sender.sendMessage(" " + e.getValue() + ": " + e.getKey())); - } - break; - } - } - - private void dumpHeap(CommandSender sender) { - java.nio.file.Path dir = java.nio.file.Paths.get("./dumps"); - String name = "heap-dump-" + DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss").format(LocalDateTime.now()); - - Command.broadcastCommandMessage(sender, ChatColor.YELLOW + "Writing JVM heap data..."); - - java.nio.file.Path file = CraftServer.dumpHeap(dir, name); - if (file != null) { - Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Heap dump saved to " + file); - } else { - Command.broadcastCommandMessage(sender, ChatColor.RED + "Failed to write heap dump, see sever log for details"); - } - } - - private void doReload(CommandSender sender) { - Command.broadcastCommandMessage(sender, ChatColor.RED + "Please note that this command is not supported and may cause issues."); - Command.broadcastCommandMessage(sender, ChatColor.RED + "If you encounter any issues please use the /stop command to restart your server."); - - MinecraftServer console = MinecraftServer.getServer(); - com.destroystokyo.paper.PaperConfig.init((File) console.options.valueOf("paper-settings")); - for (WorldServer world : console.getWorlds()) { - world.paperConfig.init(); - } - console.server.reloadCount++; - - Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Paper config reload complete."); - } -} diff --git a/src/main/java/com/destroystokyo/paper/PaperConfig.java b/src/main/java/com/destroystokyo/paper/PaperConfig.java deleted file mode 100644 index 93c0c422d..000000000 --- a/src/main/java/com/destroystokyo/paper/PaperConfig.java +++ /dev/null @@ -1,452 +0,0 @@ -package com.destroystokyo.paper; - -import com.destroystokyo.paper.io.chunk.ChunkTaskManager; -import com.google.common.base.Strings; -import com.google.common.base.Throwables; - -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.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -import com.google.common.collect.Lists; -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 co.aikar.timings.Timings; -import co.aikar.timings.TimingsManager; -import org.spigotmc.SpigotConfig; -import org.spigotmc.WatchdogThread; - -public class PaperConfig { - - private static File CONFIG_FILE; - private static final String HEADER = "This is the main configuration file for Paper.\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 Paper,\n" - + "join us in our Discord or IRC channel.\n" - + "\n" - + "Discord: https://paperdiscord.emc.gs\n" - + "IRC: #paper @ irc.spi.gt ( http://irc.spi.gt/iris/?channels=paper )\n" - + "Website: https://papermc.io/ \n" - + "Docs: https://paper.readthedocs.org/ \n"; - /*========================================================================*/ - public static YamlConfiguration config; - static int version; - static Map commands; - private static boolean verbose; - private static boolean fatalError; - /*========================================================================*/ - private static boolean metricsStarted; - - public static void init(File configFile) { - CONFIG_FILE = configFile; - config = new YamlConfiguration(); - try { - config.load(CONFIG_FILE); - } catch (IOException ex) { - } catch (InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Could not load paper.yml, please correct your syntax errors", ex); - throw Throwables.propagate(ex); - } - config.options().header(HEADER); - config.options().copyDefaults(true); - verbose = getBoolean("verbose", false); - - commands = new HashMap(); - commands.put("paper", new PaperCommand("paper")); - - version = getInt("config-version", 20); - set("config-version", 20); - readConfig(PaperConfig.class, null); - } - - protected static void logError(String s) { - Bukkit.getLogger().severe(s); - } - - protected static void fatal(String s) { - fatalError = true; - throw new RuntimeException("Fatal paper.yml config error: " + s); - } - - protected static void log(String s) { - if (verbose) { - Bukkit.getLogger().info(s); - } - } - - public static void registerCommands() { - for (Map.Entry entry : commands.entrySet()) { - MinecraftServer.getServer().server.getCommandMap().register(entry.getKey(), "Paper", entry.getValue()); - } - - if (!metricsStarted) { - Metrics.PaperMetrics.startMetrics(); - metricsStarted = true; - } - } - - 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 final Pattern SPACE = Pattern.compile(" "); - private static final Pattern NOT_NUMERIC = Pattern.compile("[^-\\d.]"); - public static int getSeconds(String str) { - str = SPACE.matcher(str).replaceAll(""); - final char unit = str.charAt(str.length() - 1); - str = NOT_NUMERIC.matcher(str).replaceAll(""); - double num; - try { - num = Double.parseDouble(str); - } catch (Exception e) { - num = 0D; - } - switch (unit) { - case 'd': num *= (double) 60*60*24; break; - case 'h': num *= (double) 60*60; break; - case 'm': num *= (double) 60; break; - default: case 's': break; - } - return (int) num; - } - - protected static String timeSummary(int seconds) { - String time = ""; - - if (seconds > 60 * 60 * 24) { - time += TimeUnit.SECONDS.toDays(seconds) + "d"; - seconds %= 60 * 60 * 24; - } - - if (seconds > 60 * 60) { - time += TimeUnit.SECONDS.toHours(seconds) + "h"; - seconds %= 60 * 60; - } - - if (seconds > 0) { - time += TimeUnit.SECONDS.toMinutes(seconds) + "m"; - } - return time; - } - - 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 (List) 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 String timingsServerName; - private static void timings() { - boolean timings = getBoolean("timings.enabled", true); - boolean verboseTimings = getBoolean("timings.verbose", true); - TimingsManager.privacy = getBoolean("timings.server-name-privacy", false); - TimingsManager.hiddenConfigs = getList("timings.hidden-config-entries", Lists.newArrayList("database", "settings.bungeecord-addresses")); - int timingHistoryInterval = getInt("timings.history-interval", 300); - int timingHistoryLength = getInt("timings.history-length", 3600); - timingsServerName = getString("timings.server-name", "Unknown Server"); - - - Timings.setVerboseTimingsEnabled(verboseTimings); - Timings.setTimingsEnabled(timings); - Timings.setHistoryInterval(timingHistoryInterval * 20); - Timings.setHistoryLength(timingHistoryLength * 20); - - log("Timings: " + timings + - " - Verbose: " + verboseTimings + - " - Interval: " + timeSummary(Timings.getHistoryInterval() / 20) + - " - Length: " + timeSummary(Timings.getHistoryLength() / 20) + - " - Server Name: " + timingsServerName); - } - - public static boolean loadPermsBeforePlugins = true; - private static void loadPermsBeforePlugins() { - loadPermsBeforePlugins = getBoolean("settings.load-permissions-yml-before-plugins", true); - } - - public static int regionFileCacheSize = 256; - private static void regionFileCacheSize() { - regionFileCacheSize = Math.max(getInt("settings.region-file-cache-size", 256), 4); - } - - public static boolean enablePlayerCollisions = true; - private static void enablePlayerCollisions() { - enablePlayerCollisions = getBoolean("settings.enable-player-collisions", true); - } - - public static boolean saveEmptyScoreboardTeams = false; - private static void saveEmptyScoreboardTeams() { - saveEmptyScoreboardTeams = getBoolean("settings.save-empty-scoreboard-teams", false); - } - - public static boolean bungeeOnlineMode = true; - private static void bungeeOnlineMode() { - bungeeOnlineMode = getBoolean("settings.bungee-online-mode", true); - } - - public static boolean isProxyOnlineMode() { - return Bukkit.getOnlineMode() || (SpigotConfig.bungee && bungeeOnlineMode) || (velocitySupport && velocityOnlineMode); - } - - public static int packetInSpamThreshold = 300; - private static void packetInSpamThreshold() { - if (version < 11) { - int oldValue = getInt("settings.play-in-use-item-spam-threshold", 300); - set("settings.incoming-packet-spam-threshold", oldValue); - } - packetInSpamThreshold = getInt("settings.incoming-packet-spam-threshold", 300); - } - - public static String flyingKickPlayerMessage = "Flying is not enabled on this server"; - public static String flyingKickVehicleMessage = "Flying is not enabled on this server"; - private static void flyingKickMessages() { - flyingKickPlayerMessage = getString("messages.kick.flying-player", flyingKickPlayerMessage); - flyingKickVehicleMessage = getString("messages.kick.flying-vehicle", flyingKickVehicleMessage); - } - - public static boolean suggestPlayersWhenNullTabCompletions = true; - private static void suggestPlayersWhenNull() { - suggestPlayersWhenNullTabCompletions = getBoolean("settings.suggest-player-names-when-null-tab-completions", suggestPlayersWhenNullTabCompletions); - } - - public static String authenticationServersDownKickMessage = ""; // empty = use translatable message - private static void authenticationServersDownKickMessage() { - authenticationServersDownKickMessage = Strings.emptyToNull(getString("messages.kick.authentication-servers-down", authenticationServersDownKickMessage)); - } - - public static String connectionThrottleKickMessage = "Connection throttled! Please wait before reconnecting."; - private static void connectionThrottleKickMessage() { - connectionThrottleKickMessage = getString("messages.kick.connection-throttle", connectionThrottleKickMessage); - } - - public static String noPermissionMessage = "&cI'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."; - private static void noPermissionMessage() { - noPermissionMessage = ChatColor.translateAlternateColorCodes('&', getString("messages.no-permission", noPermissionMessage)); - } - - public static boolean savePlayerData = true; - private static void savePlayerData() { - savePlayerData = getBoolean("settings.save-player-data", savePlayerData); - if(!savePlayerData) { - Bukkit.getLogger().log(Level.WARNING, "Player Data Saving is currently disabled. Any changes to your players data, " + - "such as inventories, experience points, advancements and the like will not be saved when they log out."); - } - } - - public static boolean useAlternativeLuckFormula = false; - private static void useAlternativeLuckFormula() { - useAlternativeLuckFormula = getBoolean("settings.use-alternative-luck-formula", false); - if (useAlternativeLuckFormula) { - Bukkit.getLogger().log(Level.INFO, "Using Aikar's Alternative Luck Formula to apply Luck attribute to all loot pool calculations. See https://luckformula.emc.gs"); - } - } - - public static boolean useVersionedWorld = false; - private static void useVersionedWorld() { - useVersionedWorld = getBoolean("settings.use-versioned-world", false); - if (useVersionedWorld) { - Logger logger = Bukkit.getLogger(); - String ver = MinecraftServer.getServer().getVersion(); - logger.log(Level.INFO, "******************************************************"); - logger.log(Level.INFO, "*** Using a versioned world folder. Your world will be saved"); - logger.log(Level.INFO, "*** to into the " + ver + " folder, but copied from your current world."); - logger.log(Level.INFO, "*** "); - logger.log(Level.INFO, "*** This setting should not be used in your real world!!!"); - logger.log(Level.INFO, "*** If you want to retain the new world, you need to move "); - logger.log(Level.INFO, "*** the folders out of the " + ver + " folder and overwrite existing"); - logger.log(Level.INFO, "*** "); - logger.log(Level.INFO, "*** Deleting the " + ver + " folder will cause it to recreate again"); - logger.log(Level.INFO, "*** from your unversioned world files."); - logger.log(Level.INFO, "*** "); - logger.log(Level.INFO, "*** You should backup your original world files incase something goes"); - logger.log(Level.INFO, "*** wrong with this system! This is not a backup system."); - logger.log(Level.INFO, "******************************************************"); - } - } - - public static int watchdogPrintEarlyWarningEvery = 5000; - public static int watchdogPrintEarlyWarningDelay = 10000; - private static void watchdogEarlyWarning() { - watchdogPrintEarlyWarningEvery = getInt("settings.watchdog.early-warning-every", 5000); - watchdogPrintEarlyWarningDelay = getInt("settings.watchdog.early-warning-delay", 10000); - WatchdogThread.doStart(SpigotConfig.timeoutTime, SpigotConfig.restartOnCrash ); - } - - public static int tabSpamIncrement = 1; - public static int tabSpamLimit = 500; - private static void tabSpamLimiters() { - tabSpamIncrement = getInt("settings.spam-limiter.tab-spam-increment", tabSpamIncrement); - // Older versions used a smaller limit, which is too low for 1.13, we'll bump this up if default - if (version < 14) { - if (tabSpamIncrement == 10) { - set("settings.spam-limiter.tab-spam-increment", 2); - tabSpamIncrement = 2; - } - } - tabSpamLimit = getInt("settings.spam-limiter.tab-spam-limit", tabSpamLimit); - } - - public static Map seedOverride = new java.util.HashMap<>(); - private static void worldSeedOverrides() { - ConfigurationSection seeds = config.getConfigurationSection("seed-overrides"); - if (seeds != null) { - TimingsManager.hiddenConfigs.add("seed-overrides"); - for (String key : seeds.getKeys(false)) { - String seedString = seeds.getString(key); - long seed; - try { - seed = Long.parseLong(seedString); - } catch (Exception e) { - seed = (long) seedString.hashCode(); - } - log("Seed Override: " + key + " => " + seed); - seedOverride.put(key, seed); - } - } - } - - public static boolean velocitySupport; - public static boolean velocityOnlineMode; - public static byte[] velocitySecretKey; - private static void velocitySupport() { - velocitySupport = getBoolean("settings.velocity-support.enabled", false); - velocityOnlineMode = getBoolean("settings.velocity-support.online-mode", false); - String secret = getString("settings.velocity-support.secret", ""); - if (velocitySupport && secret.isEmpty()) { - fatal("Velocity support is enabled, but no secret key was specified. A secret key is required!"); - } else { - velocitySecretKey = secret.getBytes(StandardCharsets.UTF_8); - } - } - - public static int maxBookPageSize = 2560; - public static double maxBookTotalSizeMultiplier = 0.98D; - private static void maxBookSize() { - maxBookPageSize = getInt("settings.book-size.page-max", maxBookPageSize); - maxBookTotalSizeMultiplier = getDouble("settings.book-size.total-multiplier", maxBookTotalSizeMultiplier); - } - - public static boolean asyncChunks = false; - //public static boolean asyncChunkGeneration = true; // Leave out for now until we can control this - //public static boolean asyncChunkGenThreadPerWorld = true; // Leave out for now until we can control this - public static int asyncChunkLoadThreads = -1; - private static void asyncChunks() { - if (version < 15) { - boolean enabled = config.getBoolean("settings.async-chunks", true); - ConfigurationSection section = config.createSection("settings.async-chunks"); - section.set("enable", enabled); - section.set("load-threads", -1); - section.set("generation", true); - section.set("thread-per-world-generation", true); - } - - // TODO load threads now control async chunk save for unloading chunks, look into renaming this? - - asyncChunks = getBoolean("settings.async-chunks.enable", true); - //asyncChunkGeneration = getBoolean("settings.async-chunks.generation", true); // Leave out for now until we can control this - //asyncChunkGenThreadPerWorld = getBoolean("settings.async-chunks.thread-per-world-generation", true); // Leave out for now until we can control this - asyncChunkLoadThreads = getInt("settings.async-chunks.load-threads", -1); - if (asyncChunkLoadThreads <= 0) { - asyncChunkLoadThreads = (int) Math.min(Integer.getInteger("paper.maxChunkThreads", 8), Math.max(1, Runtime.getRuntime().availableProcessors() - 1)); - } - - // Let Shared Host set some limits - String sharedHostEnvGen = System.getenv("PAPER_ASYNC_CHUNKS_SHARED_HOST_GEN"); - String sharedHostEnvLoad = System.getenv("PAPER_ASYNC_CHUNKS_SHARED_HOST_LOAD"); - /* Ignore temporarily - we cannot control the gen threads (for now) - if ("1".equals(sharedHostEnvGen)) { - log("Async Chunks - Generation: Your host has requested to use a single thread world generation"); - asyncChunkGenThreadPerWorld = false; - } else if ("2".equals(sharedHostEnvGen)) { - log("Async Chunks - Generation: Your host has disabled async world generation - You will experience lag from world generation"); - asyncChunkGeneration = false; - } - */ - - if (sharedHostEnvLoad != null) { - try { - asyncChunkLoadThreads = Math.max(1, Math.min(asyncChunkLoadThreads, Integer.parseInt(sharedHostEnvLoad))); - } catch (NumberFormatException ignored) {} - } - - if (!asyncChunks) { - log("Async Chunks: Disabled - Chunks will be managed synchronosuly, and will cause tremendous lag."); - } else { - ChunkTaskManager.initGlobalLoadThreads(asyncChunkLoadThreads); - log("Async Chunks: Enabled - Chunks will be loaded much faster, without lag."); - /* Ignore temporarily - we cannot control the gen threads (for now) - if (!asyncChunkGeneration) { - log("Async Chunks - Generation: Disabled - Chunks will be generated synchronosuly, and will cause tremendous lag."); - } else if (asyncChunkGenThreadPerWorld) { - log("Async Chunks - Generation: Enabled - Chunks will be generated much faster, without lag."); - } else { - log("Async Chunks - Generation: Enabled (Single Thread) - Chunks will be generated much faster, without lag."); - } - */ - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/PaperVersionFetcher.java b/src/main/java/com/destroystokyo/paper/PaperVersionFetcher.java deleted file mode 100644 index 513cddb9b..000000000 --- a/src/main/java/com/destroystokyo/paper/PaperVersionFetcher.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.destroystokyo.paper; - -import com.destroystokyo.paper.util.VersionFetcher; -import com.google.common.base.Charsets; -import com.google.common.io.Resources; -import com.google.gson.*; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; - -public class PaperVersionFetcher implements VersionFetcher { - private static final java.util.regex.Pattern VER_PATTERN = java.util.regex.Pattern.compile("^([0-9\\.]*)\\-.*R"); // R is an anchor, will always give '-R' at end - private static final String GITHUB_BRANCH_NAME = "ver/1.14"; - private static @Nullable String mcVer; - - @Override - public long getCacheTime() { - return 720000; - } - - @Nonnull - @Override - public String getVersionMessage(@Nonnull String serverVersion) { - String[] parts = serverVersion.substring("git-Paper-".length()).split("[-\\s]"); - String updateMessage = getUpdateStatusMessage("PaperMC/Paper", GITHUB_BRANCH_NAME, parts[0]); - String history = getHistory(); - - return history != null ? history + "\n" + updateMessage : updateMessage; - } - - private static @Nullable String getMinecraftVersion() { - if (mcVer == null) { - java.util.regex.Matcher matcher = VER_PATTERN.matcher(org.bukkit.Bukkit.getBukkitVersion()); - if (matcher.find()) { - String result = matcher.group(); - mcVer = result.substring(0, result.length() - 2); // strip 'R' anchor and trailing '-' - } else { - org.bukkit.Bukkit.getLogger().warning("Unable to match version to pattern! Report to PaperMC!"); - org.bukkit.Bukkit.getLogger().warning("Pattern: " + VER_PATTERN.toString()); - org.bukkit.Bukkit.getLogger().warning("Version: " + org.bukkit.Bukkit.getBukkitVersion()); - } - } - - return mcVer; - } - - private static String getUpdateStatusMessage(@Nonnull String repo, @Nonnull String branch, @Nonnull String versionInfo) { - int distance; - try { - int jenkinsBuild = Integer.parseInt(versionInfo); - distance = fetchDistanceFromSiteApi(jenkinsBuild, getMinecraftVersion()); - } catch (NumberFormatException ignored) { - versionInfo = versionInfo.replace("\"", ""); - distance = fetchDistanceFromGitHub(repo, branch, versionInfo); - } - - switch (distance) { - case -1: - return "Error obtaining version information"; - case 0: - return "You are running the latest version"; - case -2: - return "Unknown version"; - default: - return "You are " + distance + " version(s) behind"; - } - } - - private static int fetchDistanceFromSiteApi(int jenkinsBuild, @Nullable String siteApiVersion) { - if (siteApiVersion == null) { return -1; } - try { - try (BufferedReader reader = Resources.asCharSource( - new URL("https://papermc.io/api/v1/paper/" + siteApiVersion + "/latest"), - Charsets.UTF_8 - ).openBufferedStream()) { - JsonObject json = new Gson().fromJson(reader, JsonObject.class); - int latest = json.get("build").getAsInt(); - return latest - jenkinsBuild; - } catch (JsonSyntaxException ex) { - ex.printStackTrace(); - return -1; - } - } catch (IOException e) { - e.printStackTrace(); - return -1; - } - } - - // Contributed by Techcable in GH-65 - private static int fetchDistanceFromGitHub(@Nonnull String repo, @Nonnull String branch, @Nonnull String hash) { - try { - HttpURLConnection connection = (HttpURLConnection) new URL("https://api.github.com/repos/" + repo + "/compare/" + branch + "..." + hash).openConnection(); - connection.connect(); - if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return -2; // Unknown commit - try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8))) { - JsonObject obj = new Gson().fromJson(reader, JsonObject.class); - String status = obj.get("status").getAsString(); - switch (status) { - case "identical": - return 0; - case "behind": - return obj.get("behind_by").getAsInt(); - default: - return -1; - } - } catch (JsonSyntaxException | NumberFormatException e) { - e.printStackTrace(); - return -1; - } - } catch (IOException e) { - e.printStackTrace(); - return -1; - } - } - - @Nullable - private String getHistory() { - final VersionHistoryManager.VersionData data = VersionHistoryManager.INSTANCE.getVersionData(); - if (data == null) { - return null; - } - - final String oldVersion = data.getOldVersion(); - if (oldVersion == null) { - return null; - } - - return "Previous version: " + oldVersion; - } -} diff --git a/src/main/java/com/destroystokyo/paper/PaperWorldConfig.java b/src/main/java/com/destroystokyo/paper/PaperWorldConfig.java deleted file mode 100644 index 3e5571f7d..000000000 --- a/src/main/java/com/destroystokyo/paper/PaperWorldConfig.java +++ /dev/null @@ -1,638 +0,0 @@ -package com.destroystokyo.paper; - -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.destroystokyo.paper.antixray.ChunkPacketBlockControllerAntiXray.ChunkEdgeMode; -import com.destroystokyo.paper.antixray.ChunkPacketBlockControllerAntiXray.EngineMode; -import net.minecraft.server.MinecraftServer; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; -import org.spigotmc.SpigotWorldConfig; - -import static com.destroystokyo.paper.PaperConfig.log; -import static com.destroystokyo.paper.PaperConfig.logError; - -public class PaperWorldConfig { - - private final String worldName; - private final SpigotWorldConfig spigotConfig; - private final YamlConfiguration config; - private boolean verbose; - - public PaperWorldConfig(String worldName, SpigotWorldConfig spigotConfig) { - this.worldName = worldName; - this.spigotConfig = spigotConfig; - this.config = PaperConfig.config; - init(); - } - - public void init() { - log("-------- World Settings For [" + worldName + "] --------"); - PaperConfig.readConfig(PaperWorldConfig.class, this); - } - - private void set(String path, Object val) { - config.set("world-settings.default." + path, val); - if (config.get("world-settings." + worldName + "." + path) != null) { - config.set("world-settings." + worldName + "." + 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, List 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 cactusMaxHeight; - public int reedMaxHeight; - private void blockGrowthHeight() { - cactusMaxHeight = getInt("max-growth-height.cactus", 3); - reedMaxHeight = getInt("max-growth-height.reeds", 3); - log("Max height for cactus growth " + cactusMaxHeight + ". Max height for reed growth " + reedMaxHeight); - - } - - public double babyZombieMovementModifier; - private void babyZombieMovementModifier() { - babyZombieMovementModifier = getDouble("baby-zombie-movement-modifier", 0.5D); - if (PaperConfig.version < 20) { - babyZombieMovementModifier = getDouble("baby-zombie-movement-speed", 0.5D); - set("baby-zombie-movement-modifier", babyZombieMovementModifier); - } - - log("Baby zombies will move at the speed of " + babyZombieMovementModifier); - } - - public int fishingMinTicks; - public int fishingMaxTicks; - private void fishingTickRange() { - fishingMinTicks = getInt("fishing-time-range.MinimumTicks", 100); - fishingMaxTicks = getInt("fishing-time-range.MaximumTicks", 600); - log("Fishing time ranges are between " + fishingMinTicks +" and " + fishingMaxTicks + " ticks"); - } - - public boolean nerfedMobsShouldJump; - private void nerfedMobsShouldJump() { - nerfedMobsShouldJump = getBoolean("spawner-nerfed-mobs-should-jump", false); - } - - 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; - } - - log("Living Entity Despawn Ranges: Soft: " + softDespawnDistance + " Hard: " + hardDespawnDistance); - - softDespawnDistance = softDespawnDistance*softDespawnDistance; - hardDespawnDistance = hardDespawnDistance*hardDespawnDistance; - } - - public boolean keepSpawnInMemory; - private void keepSpawnInMemory() { - keepSpawnInMemory = getBoolean("keep-spawn-loaded", true); - log("Keep spawn chunk loaded: " + keepSpawnInMemory); - } - - public int fallingBlockHeightNerf; - public int entityTNTHeightNerf; - private void heightNerfs() { - fallingBlockHeightNerf = getInt("falling-block-height-nerf", 0); - entityTNTHeightNerf = getInt("tnt-entity-height-nerf", 0); - - if (fallingBlockHeightNerf != 0) log("Falling Block Height Limit set to Y: " + fallingBlockHeightNerf); - if (entityTNTHeightNerf != 0) log("TNT Entity Height Limit set to Y: " + entityTNTHeightNerf); - } - - public int netherVoidTopDamageHeight; - public boolean doNetherTopVoidDamage() { return netherVoidTopDamageHeight > 0; } - private void netherVoidTopDamageHeight() { - netherVoidTopDamageHeight = getInt("nether-ceiling-void-damage-height", 0); - log("Top of the nether void damage height: " + netherVoidTopDamageHeight); - - if (PaperConfig.version < 18) { - boolean legacy = getBoolean("nether-ceiling-void-damage", false); - if (legacy) { - netherVoidTopDamageHeight = 128; - set("nether-ceiling-void-damage-height", netherVoidTopDamageHeight); - } - } - } - - public boolean disableEndCredits; - private void disableEndCredits() { - disableEndCredits = getBoolean("game-mechanics.disable-end-credits", false); - log("End credits disabled: " + disableEndCredits); - } - - public boolean optimizeExplosions; - private void optimizeExplosions() { - optimizeExplosions = getBoolean("optimize-explosions", false); - log("Optimize explosions: " + optimizeExplosions); - } - - 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 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 boolean disableChestCatDetection; - private void disableChestCatDetection() { - disableChestCatDetection = getBoolean("game-mechanics.disable-chest-cat-detection", false); - } - - public boolean disablePlayerCrits; - private void disablePlayerCrits() { - disablePlayerCrits = getBoolean("game-mechanics.disable-player-crits", false); - } - - public boolean allChunksAreSlimeChunks; - private void allChunksAreSlimeChunks() { - allChunksAreSlimeChunks = getBoolean("all-chunks-are-slime-chunks", false); - } - - 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 nonPlayerEntitiesOnScoreboards = false; - private void nonPlayerEntitiesOnScoreboards() { - nonPlayerEntitiesOnScoreboards = getBoolean("allow-non-player-entities-on-scoreboards", false); - } - - public boolean allowLeashingUndeadHorse = false; - private void allowLeashingUndeadHorse() { - allowLeashingUndeadHorse = getBoolean("allow-leashing-undead-horse", false); - } - - public int nonPlayerArrowDespawnRate = -1; - public int creativeArrowDespawnRate = -1; - private void nonPlayerArrowDespawnRate() { - nonPlayerArrowDespawnRate = getInt("non-player-arrow-despawn-rate", -1); - if (nonPlayerArrowDespawnRate == -1) { - nonPlayerArrowDespawnRate = spigotConfig.arrowDespawnRate; - } - creativeArrowDespawnRate = getInt("creative-arrow-despawn-rate", -1); - if (creativeArrowDespawnRate == -1) { - creativeArrowDespawnRate = spigotConfig.arrowDespawnRate; - } - log("Non Player Arrow Despawn Rate: " + nonPlayerArrowDespawnRate); - log("Creative Arrow Despawn Rate: " + creativeArrowDespawnRate); - } - - public double skeleHorseSpawnChance; - private void skeleHorseSpawnChance() { - skeleHorseSpawnChance = getDouble("skeleton-horse-thunder-spawn-chance", 0.01D); - if (skeleHorseSpawnChance < 0) { - skeleHorseSpawnChance = 0.01D; // Vanilla value - } - } - - public double sqrMaxThunderDistance; - public double sqrMaxLightningImpactSoundDistance; - public double maxLightningFlashDistance; - private void lightningStrikeDistanceLimit() { - sqrMaxThunderDistance = getInt("lightning-strike-distance-limit.sound", -1); - if (sqrMaxThunderDistance > 0) { - sqrMaxThunderDistance *= sqrMaxThunderDistance; - } - - sqrMaxLightningImpactSoundDistance = getInt("lightning-strike-distance-limit.impact-sound", -1); - if (sqrMaxLightningImpactSoundDistance < 0) { - sqrMaxLightningImpactSoundDistance = 32 * 32; //Vanilla value - } else { - sqrMaxLightningImpactSoundDistance *= sqrMaxLightningImpactSoundDistance; - } - - maxLightningFlashDistance = getInt("lightning-strike-distance-limit.flash", -1); - if (maxLightningFlashDistance < 0) { - maxLightningFlashDistance = 512; // Vanilla value - } - } - - public int fixedInhabitedTime; - private void fixedInhabitedTime() { - if (PaperConfig.version < 16) { - if (!config.getBoolean("world-settings.default.use-chunk-inhabited-timer", true)) config.set("world-settings.default.fixed-chunk-inhabited-time", 0); - if (!config.getBoolean("world-settings." + worldName + ".use-chunk-inhabited-timer", true)) config.set("world-settings." + worldName + ".fixed-chunk-inhabited-time", 0); - set("use-chunk-inhabited-timer", null); - } - fixedInhabitedTime = getInt("fixed-chunk-inhabited-time", -1); - } - - public int grassUpdateRate = 1; - private void grassUpdateRate() { - grassUpdateRate = Math.max(0, getInt("grass-spread-tick-rate", grassUpdateRate)); - log("Grass Spread Tick Rate: " + grassUpdateRate); - } - - public boolean useVanillaScoreboardColoring; - private void useVanillaScoreboardColoring() { - useVanillaScoreboardColoring = getBoolean("use-vanilla-world-scoreboard-name-coloring", false); - } - - public boolean frostedIceEnabled = true; - public int frostedIceDelayMin = 20; - public int frostedIceDelayMax = 40; - private void frostedIce() { - this.frostedIceEnabled = this.getBoolean("frosted-ice.enabled", this.frostedIceEnabled); - this.frostedIceDelayMin = this.getInt("frosted-ice.delay.min", this.frostedIceDelayMin); - this.frostedIceDelayMax = this.getInt("frosted-ice.delay.max", this.frostedIceDelayMax); - log("Frosted Ice: " + (this.frostedIceEnabled ? "enabled" : "disabled") + " / delay: min=" + this.frostedIceDelayMin + ", max=" + this.frostedIceDelayMax); - } - - public boolean autoReplenishLootables; - public boolean restrictPlayerReloot; - public boolean changeLootTableSeedOnFill; - public int maxLootableRefills; - public int lootableRegenMin; - public int lootableRegenMax; - private void enhancedLootables() { - autoReplenishLootables = getBoolean("lootables.auto-replenish", false); - restrictPlayerReloot = getBoolean("lootables.restrict-player-reloot", true); - changeLootTableSeedOnFill = getBoolean("lootables.reset-seed-on-fill", true); - maxLootableRefills = getInt("lootables.max-refills", -1); - lootableRegenMin = PaperConfig.getSeconds(getString("lootables.refresh-min", "12h")); - lootableRegenMax = PaperConfig.getSeconds(getString("lootables.refresh-max", "2d")); - if (autoReplenishLootables) { - log("Lootables: Replenishing every " + - PaperConfig.timeSummary(lootableRegenMin) + " to " + - PaperConfig.timeSummary(lootableRegenMax) + - (restrictPlayerReloot ? " (restricting reloot)" : "") - ); - } - } - - public boolean preventTntFromMovingInWater; - private void preventTntFromMovingInWater() { - if (PaperConfig.version < 13) { - boolean oldVal = getBoolean("enable-old-tnt-cannon-behaviors", false); - set("prevent-tnt-from-moving-in-water", oldVal); - } - preventTntFromMovingInWater = getBoolean("prevent-tnt-from-moving-in-water", false); - log("Prevent TNT from moving in water: " + preventTntFromMovingInWater); - } - - public boolean removeCorruptTEs = false; - private void removeCorruptTEs() { - removeCorruptTEs = getBoolean("remove-corrupt-tile-entities", false); - } - - public boolean filterNBTFromSpawnEgg = true; - private void fitlerNBTFromSpawnEgg() { - filterNBTFromSpawnEgg = getBoolean("filter-nbt-data-from-spawn-eggs-and-related", true); - if (!filterNBTFromSpawnEgg) { - Bukkit.getLogger().warning("Spawn Egg and Armor Stand NBT filtering disabled, this is a potential security risk"); - } - } - - public boolean enableTreasureMaps = true; - public boolean treasureMapsAlreadyDiscovered = false; - private void treasureMapsAlreadyDiscovered() { - enableTreasureMaps = getBoolean("enable-treasure-maps", true); - treasureMapsAlreadyDiscovered = getBoolean("treasure-maps-return-already-discovered", false); - if (treasureMapsAlreadyDiscovered) { - log("Treasure Maps will return already discovered locations"); - } - } - - public boolean armorStandEntityLookups = true; - private void armorStandEntityLookups() { - armorStandEntityLookups = getBoolean("armor-stands-do-collision-entity-lookups", true); - } - - public int maxCollisionsPerEntity; - private void maxEntityCollision() { - maxCollisionsPerEntity = getInt( "max-entity-collisions", this.spigotConfig.getInt("max-entity-collisions", 8) ); - log( "Max Entity Collisions: " + maxCollisionsPerEntity ); - } - - public boolean parrotsHangOnBetter; - private void parrotsHangOnBetter() { - parrotsHangOnBetter = getBoolean("parrots-are-unaffected-by-player-movement", false); - log("Parrots are unaffected by player movement: " + parrotsHangOnBetter); - } - - public boolean disableCreeperLingeringEffect; - private void setDisableCreeperLingeringEffect() { - disableCreeperLingeringEffect = getBoolean("disable-creeper-lingering-effect", false); - log("Creeper lingering effect: " + disableCreeperLingeringEffect); - } - - public int expMergeMaxValue; - private void expMergeMaxValue() { - expMergeMaxValue = getInt("experience-merge-max-value", -1); - log("Experience Merge Max Value: " + expMergeMaxValue); - } - - public double squidMaxSpawnHeight; - private void squidMaxSpawnHeight() { - squidMaxSpawnHeight = getDouble("squid-spawn-height.maximum", 0.0D); - } - - public boolean cooldownHopperWhenFull = true; - public boolean disableHopperMoveEvents = false; - private void hopperOptimizations() { - cooldownHopperWhenFull = getBoolean("hopper.cooldown-when-full", cooldownHopperWhenFull); - log("Cooldown Hoppers when Full: " + (cooldownHopperWhenFull ? "enabled" : "disabled")); - disableHopperMoveEvents = getBoolean("hopper.disable-move-event", disableHopperMoveEvents); - log("Hopper Move Item Events: " + (disableHopperMoveEvents ? "disabled" : "enabled")); - } - - public boolean disableSprintInterruptionOnAttack; - private void disableSprintInterruptionOnAttack() { - disableSprintInterruptionOnAttack = getBoolean("game-mechanics.disable-sprint-interruption-on-attack", false); - } - - public boolean disableEnderpearlExploit = true; - private void disableEnderpearlExploit() { - disableEnderpearlExploit = getBoolean("game-mechanics.disable-unloaded-chunk-enderpearl-exploit", disableEnderpearlExploit); - log("Disable Unloaded Chunk Enderpearl Exploit: " + (disableEnderpearlExploit ? "enabled" : "disabled")); - } - - public int shieldBlockingDelay = 5; - private void shieldBlockingDelay() { - shieldBlockingDelay = getInt("game-mechanics.shield-blocking-delay", 5); - } - - public boolean scanForLegacyEnderDragon = true; - private void scanForLegacyEnderDragon() { - scanForLegacyEnderDragon = getBoolean("game-mechanics.scan-for-legacy-ender-dragon", true); - } - - public int bedSearchRadius = 1; - private void bedSearchRadius() { - bedSearchRadius = getInt("bed-search-radius", 1); - if (bedSearchRadius < 1) { - bedSearchRadius = 1; - } - if (bedSearchRadius > 1) { - log("Bed Search Radius: " + bedSearchRadius); - } - } - - public int waterOverLavaFlowSpeed; - private void waterOverLavaFlowSpeed() { - waterOverLavaFlowSpeed = getInt("water-over-lava-flow-speed", 5); - log("Water over lava flow speed: " + waterOverLavaFlowSpeed); - } - - public boolean armorStandTick = true; - private void armorStandTick() { - this.armorStandTick = this.getBoolean("armor-stands-tick", this.armorStandTick); - log("ArmorStand ticking is " + (this.armorStandTick ? "enabled" : "disabled") + " by default"); - } - - public boolean preventMovingIntoUnloadedChunks = false; - private void preventMovingIntoUnloadedChunks() { - preventMovingIntoUnloadedChunks = getBoolean("prevent-moving-into-unloaded-chunks", false); - } - - public boolean useEigencraftRedstone = false; - private void useEigencraftRedstone() { - useEigencraftRedstone = this.getBoolean("use-faster-eigencraft-redstone", false); - if (useEigencraftRedstone) { - log("Using Eigencraft redstone algorithm by theosib."); - } else { - log("Using vanilla redstone algorithm."); - } - } - - public enum DuplicateUUIDMode { - SAFE_REGEN, DELETE, NOTHING, WARN - } - public DuplicateUUIDMode duplicateUUIDMode = DuplicateUUIDMode.SAFE_REGEN; - public int duplicateUUIDDeleteRange = 32; - private void repairDuplicateUUID() { - String desiredMode = getString("duplicate-uuid-resolver", "saferegen").toLowerCase().trim(); - duplicateUUIDDeleteRange = getInt("duplicate-uuid-saferegen-delete-range", duplicateUUIDDeleteRange); - switch (desiredMode.toLowerCase()) { - case "regen": - case "regenerate": - case "saferegen": - case "saferegenerate": - duplicateUUIDMode = DuplicateUUIDMode.SAFE_REGEN; - log("Duplicate UUID Resolve: Regenerate New UUID if distant (Delete likely duplicates within " + duplicateUUIDDeleteRange + " blocks)"); - break; - case "remove": - case "delete": - duplicateUUIDMode = DuplicateUUIDMode.DELETE; - log("Duplicate UUID Resolve: Delete Entity"); - break; - case "silent": - case "nothing": - duplicateUUIDMode = DuplicateUUIDMode.NOTHING; - logError("Duplicate UUID Resolve: Do Nothing (no logs) - Warning, may lose indication of bad things happening"); - break; - case "log": - case "warn": - duplicateUUIDMode = DuplicateUUIDMode.WARN; - log("Duplicate UUID Resolve: Warn (do nothing but log it happened, may be spammy)"); - break; - default: - duplicateUUIDMode = DuplicateUUIDMode.WARN; - logError("Warning: Invalid duplicate-uuid-resolver config " + desiredMode + " - must be one of: regen, delete, nothing, warn"); - log("Duplicate UUID Resolve: Warn (do nothing but log it happened, may be spammy)"); - break; - } - } - - public short keepLoadedRange; - private void keepLoadedRange() { - keepLoadedRange = (short) (getInt("keep-spawn-loaded-range", Math.min(spigotConfig.viewDistance, 10)) * 16); - log( "Keep Spawn Loaded Range: " + (keepLoadedRange/16)); - } - - public int autoSavePeriod = -1; - private void autoSavePeriod() { - autoSavePeriod = getInt("auto-save-interval", -1); - if (autoSavePeriod > 0) { - log("Auto Save Interval: " +autoSavePeriod + " (" + (autoSavePeriod / 20) + "s)"); - } else if (autoSavePeriod < 0) { - autoSavePeriod = net.minecraft.server.MinecraftServer.getServer().autosavePeriod; - } - } - - public int maxAutoSaveChunksPerTick = 24; - private void maxAutoSaveChunksPerTick() { - maxAutoSaveChunksPerTick = getInt("max-auto-save-chunks-per-tick", 24); - } - - public boolean countAllMobsForSpawning = false; - private void countAllMobsForSpawning() { - countAllMobsForSpawning = getBoolean("count-all-mobs-for-spawning", false); - if (countAllMobsForSpawning) { - log("Counting all mobs for spawning. Mob farms may reduce natural spawns elsewhere in world."); - } else { - log("Using improved mob spawn limits (Only Natural Spawns impact spawn limits for more natural spawns)"); - } - } - - public boolean antiXray; - public boolean asynchronous; - public EngineMode engineMode; - public ChunkEdgeMode chunkEdgeMode; - public int maxChunkSectionIndex; - public int updateRadius; - public List hiddenBlocks; - public List replacementBlocks; - private void antiXray() { - antiXray = getBoolean("anti-xray.enabled", false); - asynchronous = true; - engineMode = EngineMode.getById(getInt("anti-xray.engine-mode", EngineMode.HIDE.getId())); - engineMode = engineMode == null ? EngineMode.HIDE : engineMode; - chunkEdgeMode = ChunkEdgeMode.getById(getInt("anti-xray.chunk-edge-mode", ChunkEdgeMode.WAIT.getId())); - chunkEdgeMode = chunkEdgeMode == null ? ChunkEdgeMode.DEFAULT : chunkEdgeMode; - - if (chunkEdgeMode != ChunkEdgeMode.WAIT) { - log("Migrating anti-xray chunk edge mode to " + ChunkEdgeMode.WAIT + " (" + ChunkEdgeMode.WAIT.getId() + ")"); - chunkEdgeMode = ChunkEdgeMode.WAIT; - set("anti-xray.chunk-edge-mode", ChunkEdgeMode.WAIT.getId()); - } - - maxChunkSectionIndex = getInt("anti-xray.max-chunk-section-index", 3); - maxChunkSectionIndex = maxChunkSectionIndex > 15 ? 15 : maxChunkSectionIndex; - updateRadius = getInt("anti-xray.update-radius", 2); - hiddenBlocks = getList("anti-xray.hidden-blocks", Arrays.asList("gold_ore", "iron_ore", "coal_ore", "lapis_ore", "mossy_cobblestone", "obsidian", "chest", "diamond_ore", "redstone_ore", "clay", "emerald_ore", "ender_chest")); - replacementBlocks = getList("anti-xray.replacement-blocks", Arrays.asList("stone", "oak_planks")); - if (PaperConfig.version < 19) { - hiddenBlocks.remove("lit_redstone_ore"); - int index = replacementBlocks.indexOf("planks"); - if (index != -1) { - replacementBlocks.set(index, "oak_planks"); - } - set("anti-xray.hidden-blocks", hiddenBlocks); - set("anti-xray.replacement-blocks", replacementBlocks); - } - log("Anti-Xray: " + (antiXray ? "enabled" : "disabled") + " / Engine Mode: " + engineMode.getDescription() + " / Chunk Edge Mode: " + chunkEdgeMode.getDescription() + " / Up to " + ((maxChunkSectionIndex + 1) * 16) + " blocks / Update Radius: " + updateRadius); - } - - public boolean disableRelativeProjectileVelocity; - private void disableRelativeProjectileVelocity() { - disableRelativeProjectileVelocity = getBoolean("game-mechanics.disable-relative-projectile-velocity", false); - } - - public boolean fixZeroTickInstantGrowFarms = true; - private void fixZeroTickInstantGrowFarms() { - fixZeroTickInstantGrowFarms = getBoolean("fix-zero-tick-instant-grow-farms", fixZeroTickInstantGrowFarms); - } - - public boolean altItemDespawnRateEnabled; - public Map altItemDespawnRateMap; - private void altItemDespawnRate() { - String path = "alt-item-despawn-rate"; - - altItemDespawnRateEnabled = getBoolean(path + ".enabled", false); - - Map altItemDespawnRateMapDefault = new EnumMap<>(Material.class); - altItemDespawnRateMapDefault.put(Material.COBBLESTONE, 300); - for (Material key : altItemDespawnRateMapDefault.keySet()) { - config.addDefault("world-settings.default." + path + ".items." + key, altItemDespawnRateMapDefault.get(key)); - } - - Map rawMap = new HashMap<>(); - try { - ConfigurationSection mapSection = config.getConfigurationSection("world-settings." + worldName + "." + path + ".items"); - if (mapSection == null) { - mapSection = config.getConfigurationSection("world-settings.default." + path + ".items"); - } - for (String key : mapSection.getKeys(false)) { - int val = mapSection.getInt(key); - rawMap.put(key, val); - } - } - catch (Exception e) { - logError("alt-item-despawn-rate was malformatted"); - altItemDespawnRateEnabled = false; - } - - altItemDespawnRateMap = new EnumMap<>(Material.class); - if (!altItemDespawnRateEnabled) { - return; - } - - for(String key : rawMap.keySet()) { - try { - altItemDespawnRateMap.put(Material.valueOf(key), rawMap.get(key)); - } catch (Exception e) { - logError("Could not add item " + key + " to altItemDespawnRateMap: " + e.getMessage()); - } - } - if(altItemDespawnRateEnabled) { - for(Material key : altItemDespawnRateMap.keySet()) { - log("Alternative item despawn rate of " + key + ": " + altItemDespawnRateMap.get(key)); - } - } - } - - public boolean perPlayerMobSpawns = false; - private void perPlayerMobSpawns() { - perPlayerMobSpawns = getBoolean("per-player-mob-spawns", false); - } - - public boolean generateFlatBedrock; - private void generatorSettings() { - generateFlatBedrock = getBoolean("generator-settings.flat-bedrock", false); - } -} diff --git a/src/main/java/com/destroystokyo/paper/PaperWorldMap.java b/src/main/java/com/destroystokyo/paper/PaperWorldMap.java deleted file mode 100644 index 6bb2f98b4..000000000 --- a/src/main/java/com/destroystokyo/paper/PaperWorldMap.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.destroystokyo.paper; - -import net.minecraft.server.DimensionManager; -import net.minecraft.server.WorldServer; - -import javax.annotation.Nonnull; -import java.util.AbstractSet; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class PaperWorldMap extends HashMap { - private final List worlds = new ArrayList<>(); - private final List worldsIterable = new ArrayList() { - @Override - public Iterator iterator() { - Iterator iterator = super.iterator(); - return new Iterator() { - private WorldServer last; - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public WorldServer next() { - this.last = iterator.next(); - return last; - } - - @Override - public void remove() { - worlds.set(last.worldProvider.getDimensionManager().getDimensionID() + 1, null); - } - }; - } - }; - @Override - public int size() { - return worldsIterable.size(); - } - - @Override - public boolean isEmpty() { - return worldsIterable.isEmpty(); - } - - @Override - public WorldServer get(Object key) { - // Will hit the below method - return key instanceof DimensionManager ? get((DimensionManager) key) : null; - } - - public WorldServer get(DimensionManager key) { - int id = key.getDimensionID()+1; - return worlds.size() > id ? worlds.get(id) : null; - } - - @Override - public boolean containsKey(Object key) { - // will hit below method - return key instanceof DimensionManager && containsKey((DimensionManager) key); - } - public boolean containsKey(DimensionManager key) { - return get(key) != null; - } - - @Override - public WorldServer put(DimensionManager key, WorldServer value) { - while (worlds.size() <= key.getDimensionID()+1) { - worlds.add(null); - } - WorldServer old = worlds.set(key.getDimensionID()+1, value); - if (old != null) { - worldsIterable.remove(old); - } - worldsIterable.add(value); - return old; - } - - @Override - public void putAll(Map m) { - for (Entry e : m.entrySet()) { - put(e.getKey(), e.getValue()); - } - } - - @Override - public WorldServer remove(Object key) { - return key instanceof DimensionManager ? remove((DimensionManager) key) : null; - } - - public WorldServer remove(DimensionManager key) { - WorldServer old; - if (key.getDimensionID()+1 == worlds.size() - 1) { - old = worlds.remove(key.getDimensionID()+1); - } else { - old = worlds.set(key.getDimensionID() + 1, null); - } - if (old != null) { - worldsIterable.remove(old); - } - return old; - } - - @Override - public void clear() { - throw new RuntimeException("What the hell are you doing?"); - } - - @Override - public boolean containsValue(Object value) { - return value instanceof WorldServer && get(((WorldServer) value).worldProvider.getDimensionManager()) != null; - } - - @Nonnull - @Override - public Set keySet() { - return new AbstractSet() { - @Override - public Iterator iterator() { - Iterator iterator = worldsIterable.iterator(); - return new Iterator() { - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public DimensionManager next() { - return iterator.next().worldProvider.getDimensionManager(); - } - - @Override - public void remove() { - iterator.remove(); - } - }; - } - - @Override - public int size() { - return worlds.size(); - } - }; - } - - @Override - public Collection values() { - return worldsIterable; - } - - @Override - public Set> entrySet() { - return new AbstractSet>() { - @Override - public Iterator> iterator() { - Iterator iterator = worldsIterable.iterator(); - return new Iterator>() { - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Entry next() { - WorldServer entry = iterator.next(); - return new SimpleEntry<>(entry.worldProvider.getDimensionManager(), entry); - } - - @Override - public void remove() { - iterator.remove(); - } - }; - } - - @Override - public int size() { - return worldsIterable.size(); - } - }; - } -} diff --git a/src/main/java/com/destroystokyo/paper/ServerSchedulerReportingWrapper.java b/src/main/java/com/destroystokyo/paper/ServerSchedulerReportingWrapper.java deleted file mode 100644 index f699ce18c..000000000 --- a/src/main/java/com/destroystokyo/paper/ServerSchedulerReportingWrapper.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.destroystokyo.paper; - -import com.google.common.base.Preconditions; -import org.bukkit.craftbukkit.scheduler.CraftTask; -import com.destroystokyo.paper.event.server.ServerExceptionEvent; -import com.destroystokyo.paper.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; - } -} diff --git a/src/main/java/com/destroystokyo/paper/VersionHistoryManager.java b/src/main/java/com/destroystokyo/paper/VersionHistoryManager.java deleted file mode 100644 index aac3f66cb..000000000 --- a/src/main/java/com/destroystokyo/paper/VersionHistoryManager.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.destroystokyo.paper; - -import com.google.common.base.MoreObjects; -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Bukkit; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -public enum VersionHistoryManager { - INSTANCE; - - private final Gson gson = new Gson(); - - private final Logger logger = Bukkit.getLogger(); - - private VersionData currentData = null; - - VersionHistoryManager() { - final Path path = Paths.get("version_history.json"); - - if (Files.exists(path)) { - // Basic file santiy checks - if (!Files.isRegularFile(path)) { - if (Files.isDirectory(path)) { - logger.severe(path + " is a directory, cannot be used for version history"); - } else { - logger.severe(path + " is not a regular file, cannot be used for version history"); - } - // We can't continue - return; - } - - try (final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { - currentData = gson.fromJson(reader, VersionData.class); - } catch (final IOException e) { - logger.log(Level.SEVERE, "Failed to read version history file '" + path + "'", e); - return; - } catch (final JsonSyntaxException e) { - logger.log(Level.SEVERE, "Invalid json syntax for file '" + path + "'", e); - return; - } - - final String version = Bukkit.getVersion(); - if (version == null) { - logger.severe("Failed to retrieve current version"); - return; - } - - if (!version.equals(currentData.getCurrentVersion())) { - // The version appears to have changed - currentData.setOldVersion(currentData.getCurrentVersion()); - currentData.setCurrentVersion(version); - writeFile(path); - } - } else { - // File doesn't exist, start fresh - currentData = new VersionData(); - // oldVersion is null - currentData.setCurrentVersion(Bukkit.getVersion()); - writeFile(path); - } - } - - private void writeFile(@Nonnull final Path path) { - try (final BufferedWriter writer = Files.newBufferedWriter( - path, - StandardCharsets.UTF_8, - StandardOpenOption.WRITE, - StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING - )) { - gson.toJson(currentData, writer); - } catch (final IOException e) { - logger.log(Level.SEVERE, "Failed to write to version history file", e); - } - } - - @Nullable - public VersionData getVersionData() { - return currentData; - } - - public static class VersionData { - private String oldVersion; - - private String currentVersion; - - @Nullable - public String getOldVersion() { - return oldVersion; - } - - public void setOldVersion(@Nullable String oldVersion) { - this.oldVersion = oldVersion; - } - - @Nullable - public String getCurrentVersion() { - return currentVersion; - } - - public void setCurrentVersion(@Nullable String currentVersion) { - this.currentVersion = currentVersion; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("oldVersion", oldVersion) - .add("currentVersion", currentVersion) - .toString(); - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final VersionData versionData = (VersionData) o; - return Objects.equals(oldVersion, versionData.oldVersion) && - Objects.equals(currentVersion, versionData.currentVersion); - } - - @Override - public int hashCode() { - return Objects.hash(oldVersion, currentVersion); - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketBlockController.java b/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketBlockController.java deleted file mode 100644 index f7e376ce6..000000000 --- a/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketBlockController.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.destroystokyo.paper.antixray; - -import net.minecraft.server.BlockPosition; -import net.minecraft.server.Chunk; -import net.minecraft.server.ChunkSection; -import net.minecraft.server.EnumDirection; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IChunkAccess; -import net.minecraft.server.IWorldReader; -import net.minecraft.server.PacketPlayOutMapChunk; -import net.minecraft.server.PlayerInteractManager; -import net.minecraft.server.World; - -public class ChunkPacketBlockController { - - public static final ChunkPacketBlockController NO_OPERATION_INSTANCE = new ChunkPacketBlockController(); - - protected ChunkPacketBlockController() { - - } - - public IBlockData[] getPredefinedBlockData(IWorldReader world, IChunkAccess chunk, ChunkSection chunkSection, boolean initializeBlocks) { - return null; - } - - public boolean onChunkPacketCreate(Chunk chunk, int chunkSectionSelector, boolean force) { - return true; - } - - public ChunkPacketInfo getChunkPacketInfo(PacketPlayOutMapChunk packetPlayOutMapChunk, Chunk chunk, - int chunkSectionSelector, boolean forceLoad) { - return null; - } - - public void modifyBlocks(PacketPlayOutMapChunk packetPlayOutMapChunk, ChunkPacketInfo chunkPacketInfo, boolean loadChunks, Integer ticketHold) { - packetPlayOutMapChunk.setReady(true); - } - - public void onBlockChange(World world, BlockPosition blockPosition, IBlockData newBlockData, IBlockData oldBlockData, int flag) { - - } - - public void onPlayerLeftClickBlock(PlayerInteractManager playerInteractManager, BlockPosition blockPosition, EnumDirection enumDirection) { - - } -} diff --git a/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketBlockControllerAntiXray.java b/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketBlockControllerAntiXray.java deleted file mode 100644 index 1edcecd2e..000000000 --- a/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketBlockControllerAntiXray.java +++ /dev/null @@ -1,822 +0,0 @@ -package com.destroystokyo.paper.antixray; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; - -import com.destroystokyo.paper.io.PrioritizedTaskQueue; -import net.minecraft.server.*; -import org.bukkit.Bukkit; -import org.bukkit.World.Environment; - -import com.destroystokyo.paper.PaperWorldConfig; - -public class ChunkPacketBlockControllerAntiXray extends ChunkPacketBlockController { - - private static ExecutorService executorServiceInstance = null; - private final ExecutorService executorService; - private final boolean asynchronous; - private final EngineMode engineMode; - private final ChunkEdgeMode chunkEdgeMode; - private final int maxChunkSectionIndex; - private final int updateRadius; - private final IBlockData[] predefinedBlockData; - private final IBlockData[] predefinedBlockDataStone; - private final IBlockData[] predefinedBlockDataNetherrack; - private final IBlockData[] predefinedBlockDataEndStone; - private final int[] predefinedBlockDataBitsGlobal; - private final int[] predefinedBlockDataBitsStoneGlobal; - private final int[] predefinedBlockDataBitsNetherrackGlobal; - private final int[] predefinedBlockDataBitsEndStoneGlobal; - private final boolean[] solidGlobal = new boolean[Block.REGISTRY_ID.size()]; - private final boolean[] obfuscateGlobal = new boolean[Block.REGISTRY_ID.size()]; - private final ChunkSection[] emptyNearbyChunkSections = {Chunk.EMPTY_CHUNK_SECTION, Chunk.EMPTY_CHUNK_SECTION, Chunk.EMPTY_CHUNK_SECTION, Chunk.EMPTY_CHUNK_SECTION}; - private final int maxBlockYUpdatePosition; - - public ChunkPacketBlockControllerAntiXray(PaperWorldConfig paperWorldConfig) { - asynchronous = paperWorldConfig.asynchronous; - engineMode = paperWorldConfig.engineMode; - chunkEdgeMode = paperWorldConfig.chunkEdgeMode; - maxChunkSectionIndex = paperWorldConfig.maxChunkSectionIndex; - updateRadius = paperWorldConfig.updateRadius; - - if (asynchronous) { - executorService = getExecutorServiceInstance(); - } else { - executorService = null; - } - - List toObfuscate; - - if (engineMode == EngineMode.HIDE) { - toObfuscate = paperWorldConfig.hiddenBlocks; - predefinedBlockData = null; - predefinedBlockDataStone = new IBlockData[] {Blocks.STONE.getBlockData()}; - predefinedBlockDataNetherrack = new IBlockData[] {Blocks.NETHERRACK.getBlockData()}; - predefinedBlockDataEndStone = new IBlockData[] {Blocks.END_STONE.getBlockData()}; - predefinedBlockDataBitsGlobal = null; - predefinedBlockDataBitsStoneGlobal = new int[] {ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(Blocks.STONE.getBlockData())}; - predefinedBlockDataBitsNetherrackGlobal = new int[] {ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(Blocks.NETHERRACK.getBlockData())}; - predefinedBlockDataBitsEndStoneGlobal = new int[] {ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(Blocks.END_STONE.getBlockData())}; - } else { - toObfuscate = new ArrayList<>(paperWorldConfig.replacementBlocks); - Set predefinedBlockDataSet = new HashSet(); - - for (String id : paperWorldConfig.hiddenBlocks) { - Block block = IRegistry.BLOCK.getOptional(new MinecraftKey(id)).orElse(null); - - if (block != null && !block.isTileEntity()) { - toObfuscate.add(id); - predefinedBlockDataSet.add(block.getBlockData()); - } - } - - predefinedBlockData = predefinedBlockDataSet.size() == 0 ? new IBlockData[] {Blocks.DIAMOND_ORE.getBlockData()} : predefinedBlockDataSet.toArray(new IBlockData[0]); - predefinedBlockDataStone = null; - predefinedBlockDataNetherrack = null; - predefinedBlockDataEndStone = null; - predefinedBlockDataBitsGlobal = new int[predefinedBlockData.length]; - - for (int i = 0; i < predefinedBlockData.length; i++) { - predefinedBlockDataBitsGlobal[i] = ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(predefinedBlockData[i]); - } - - predefinedBlockDataBitsStoneGlobal = null; - predefinedBlockDataBitsNetherrackGlobal = null; - predefinedBlockDataBitsEndStoneGlobal = null; - } - - for (String id : toObfuscate) { - Block block = IRegistry.BLOCK.getOptional(new MinecraftKey(id)).orElse(null); - - if (block != null) { - obfuscateGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(block.getBlockData())] = true; - } - } - - ChunkEmpty emptyChunk = new ChunkEmpty(null, new ChunkCoordIntPair(0, 0)); - BlockPosition zeroPos = new BlockPosition(0, 0, 0); - - for (int i = 0; i < solidGlobal.length; i++) { - IBlockData blockData = ChunkSection.GLOBAL_PALETTE.getObject(i); - - if (blockData != null) { - solidGlobal[i] = blockData.getBlock().isOccluding(blockData, emptyChunk, zeroPos) - && blockData.getBlock() != Blocks.SPAWNER && blockData.getBlock() != Blocks.BARRIER && blockData.getBlock() != Blocks.SHULKER_BOX; - // shulker box checks TE. - } - } - - this.maxBlockYUpdatePosition = (maxChunkSectionIndex + 1) * 16 + updateRadius - 1; - } - - private static ExecutorService getExecutorServiceInstance() { - if (executorServiceInstance == null) { - executorServiceInstance = Executors.newSingleThreadExecutor(); - } - - return executorServiceInstance; - } - - @Override - public IBlockData[] getPredefinedBlockData(IWorldReader world, IChunkAccess chunk, ChunkSection chunkSection, boolean initializeBlocks) { - //Return the block data which should be added to the data palettes so that they can be used for the obfuscation - if (chunkSection.getYPosition() >> 4 <= maxChunkSectionIndex) { - switch (engineMode) { - case HIDE: - if (world instanceof GeneratorAccess) { - switch (((GeneratorAccess) world).getMinecraftWorld().getWorld().getEnvironment()) { - case NETHER: - return predefinedBlockDataNetherrack; - case THE_END: - return predefinedBlockDataEndStone; - default: - return predefinedBlockDataStone; - } - } - - return null; - default: - return predefinedBlockData; - } - } - - return null; - } - - private final AtomicInteger xrayRequests = new AtomicInteger(); - - // Paper start - async chunk api - private Integer nextTicketHold() { - return Integer.valueOf(this.xrayRequests.getAndIncrement()); - } - // Paper end - - private Integer addXrayTickets(final int x, final int z, final ChunkProviderServer chunkProvider) { - final Integer hold = Integer.valueOf(this.xrayRequests.getAndIncrement()); - - // Add at ticket level 33, which is just enough to keep chunks loaded - chunkProvider.addTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x, z), 0, hold); - chunkProvider.addTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x - 1, z), 0, hold); - chunkProvider.addTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x + 1, z), 0, hold); - chunkProvider.addTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x, z - 1), 0, hold); - chunkProvider.addTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x, z + 1), 0, hold); - - return hold; - } - - private void removeXrayTickets(final int x, final int z, final ChunkProviderServer chunkProvider, final Integer hold) { - // Remove at ticket level 33 (same one we added as), which is just enough to keep chunks loaded - chunkProvider.removeTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x, z), 0, hold); - chunkProvider.removeTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x - 1, z), 0, hold); - chunkProvider.removeTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x + 1, z), 0, hold); - chunkProvider.removeTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x, z - 1), 0, hold); - chunkProvider.removeTicket(TicketType.ANTIXRAY, new ChunkCoordIntPair(x, z + 1), 0, hold); - } - - private void loadNeighbours(Chunk chunk) { - int locX = chunk.getPos().x; - int locZ = chunk.getPos().z; - chunk.world.getChunkAt(locX - 1, locZ); - chunk.world.getChunkAt(locX + 1, locZ); - chunk.world.getChunkAt(locX, locZ - 1); - chunk.world.getChunkAt(locX, locZ + 1); - } - - // Paper start - async chunk api - private void loadNeighbourAsync(ChunkProviderServer chunkProvider, WorldServer world, int chunkX, int chunkZ, int[] counter, java.util.function.Consumer onNeighourLoad, Runnable onAllNeighboursLoad) { - chunkProvider.getChunkAtAsynchronously(chunkX, chunkZ, true, (Chunk neighbour) -> { - onNeighourLoad.accept(neighbour); - if (++counter[0] == 4) { - onAllNeighboursLoad.run(); - } - }); - world.asyncChunkTaskManager.raisePriority(chunkX, chunkZ, PrioritizedTaskQueue.HIGHER_PRIORITY); - } - - private void loadNeighboursAsync(Chunk chunk, java.util.function.Consumer onNeighourLoad, Runnable onAllNeighboursLoad) { - int[] loaded = new int[1]; - - int locX = chunk.getPos().x; - int locZ = chunk.getPos().z; - WorldServer world = ((WorldServer)chunk.world); - - onNeighourLoad.accept(chunk); - - ChunkProviderServer chunkProvider = world.getChunkProvider(); - - this.loadNeighbourAsync(chunkProvider, world, locX - 1, locZ, loaded, onNeighourLoad, onAllNeighboursLoad); - this.loadNeighbourAsync(chunkProvider, world, locX + 1, locZ, loaded, onNeighourLoad, onAllNeighboursLoad); - this.loadNeighbourAsync(chunkProvider, world, locX, locZ - 1, loaded, onNeighourLoad, onAllNeighboursLoad); - this.loadNeighbourAsync(chunkProvider, world, locX, locZ + 1, loaded, onNeighourLoad, onAllNeighboursLoad); - } - // Paper end - - @Override - public boolean onChunkPacketCreate(Chunk chunk, int chunkSectionSelector, boolean force) { - int locX = chunk.getPos().x; - int locZ = chunk.getPos().z; - WorldServer world = (WorldServer)chunk.world; - ChunkProviderServer chunkProvider = world.getChunkProvider(); - - //Load nearby chunks if necessary - if (force || chunkEdgeMode == ChunkEdgeMode.LOAD) { // TODO temporary - // if forced, load NOW; - this.loadNeighbours(chunk); - } else if (chunkEdgeMode == ChunkEdgeMode.WAIT) { - if (chunkProvider.getChunkAtIfCachedImmediately(locX - 1, locZ) == null || - chunkProvider.getChunkAtIfCachedImmediately(locX + 1, locZ) == null || - chunkProvider.getChunkAtIfCachedImmediately(locX, locZ - 1) == null || - chunkProvider.getChunkAtIfCachedImmediately(locX, locZ + 1) == null) { - //Don't create the chunk packet now, wait until nearby chunks are loaded and create it later - return false; - } - } else if (false && chunkEdgeMode == ChunkEdgeMode.LOAD) { - // TODO Note: These should be asynchronous loads; however we have no such thing in 1.14. - boolean missingChunk = false; - //noinspection ConstantConditions - /* - missingChunk |= ((WorldServer)chunk.world).getChunkProvider().getChunkAt(chunk.locX - 1, chunk.locZ, true, true, c -> {}) == null; - missingChunk |= ((WorldServer)chunk.world).getChunkProvider().getChunkAt(chunk.locX + 1, chunk.locZ, true, true, c -> {}) == null; - missingChunk |= ((WorldServer)chunk.world).getChunkProvider().getChunkAt(chunk.locX, chunk.locZ - 1, true, true, c -> {}) == null; - missingChunk |= ((WorldServer)chunk.world).getChunkProvider().getChunkAt(chunk.locX, chunk.locZ + 1, true, true, c -> {}) == null; - */ - if (missingChunk) { - return false; - } - } - - //Create the chunk packet now - return true; - } - - @Override - public ChunkPacketInfoAntiXray getChunkPacketInfo(PacketPlayOutMapChunk packetPlayOutMapChunk, Chunk chunk, - int chunkSectionSelector, boolean forceLoad) { - // Return a new instance to collect data and objects in the right state while creating the chunk packet for thread safe access later - // Note: As of 1.14 this has to be moved later due to the chunk system. - - ChunkPacketInfoAntiXray chunkPacketInfoAntiXray = new ChunkPacketInfoAntiXray(packetPlayOutMapChunk, chunk, chunkSectionSelector, this); - return chunkPacketInfoAntiXray; - } - - @Override - public void modifyBlocks(PacketPlayOutMapChunk packetPlayOutMapChunk, ChunkPacketInfo chunkPacketInfo, boolean loadChunks, Integer hold) { - if (!Bukkit.isPrimaryThread()) { - // plugins? - final Integer finalHold = hold; - MinecraftServer.getServer().scheduleOnMain(() -> { - this.modifyBlocks(packetPlayOutMapChunk, chunkPacketInfo, loadChunks, finalHold); - }); - return; - } - Chunk chunk = chunkPacketInfo.getChunk(); - int locX = chunk.getPos().x; - int locZ = chunk.getPos().z; - WorldServer world = (WorldServer)chunk.world; - - Chunk[] chunks = new Chunk[] { - (Chunk)world.getChunkIfLoadedImmediately(locX - 1, locZ), - (Chunk)world.getChunkIfLoadedImmediately(locX + 1, locZ), - (Chunk)world.getChunkIfLoadedImmediately(locX, locZ - 1), - (Chunk)world.getChunkIfLoadedImmediately(locX, locZ + 1) - }; - - if (loadChunks) { - // Note: This ugly hack is to get us out of the general chunk load/unload queue to prevent deadlock - - if (chunks[0] == null || chunks[1] == null || chunks[2] == null || chunks[3] == null) { - // we need to load - // Paper start - async chunk api - Integer ticketHold = this.nextTicketHold(); - this.loadNeighboursAsync(chunk, (Chunk neighbour) -> { // when a neighbour is loaded - ((WorldServer)neighbour.world).getChunkProvider().addTicket(TicketType.ANTIXRAY, neighbour.getPos(), 0, ticketHold); - }, - () -> { // once neighbours get loaded - this.modifyBlocks(packetPlayOutMapChunk, chunkPacketInfo, false, ticketHold); - }); - // Paper end - return; - } - - hold = this.addXrayTickets(locX, locZ, world.getChunkProvider()); - // fall through to normal behavior, our chunks are now loaded & have a ticket - } - - ((ChunkPacketInfoAntiXray)chunkPacketInfo).setNearbyChunks(chunks); - ((ChunkPacketInfoAntiXray)chunkPacketInfo).ticketHold = hold; - - if (asynchronous) { - executorService.submit((ChunkPacketInfoAntiXray) chunkPacketInfo); - } else { - obfuscate((ChunkPacketInfoAntiXray) chunkPacketInfo); - } - } - - //Actually these fields should be variables inside the obfuscate method but in sync mode or with SingleThreadExecutor in async mode it's okay - private int[] predefinedBlockDataBits; - private final boolean[] solid = new boolean[Block.REGISTRY_ID.size()]; - private final boolean[] obfuscate = new boolean[Block.REGISTRY_ID.size()]; - //These boolean arrays represent chunk layers, true means don't obfuscate, false means obfuscate - private boolean[][] current = new boolean[16][16]; - private boolean[][] next = new boolean[16][16]; - private boolean[][] nextNext = new boolean[16][16]; - private final DataBitsReader dataBitsReader = new DataBitsReader(); - private final DataBitsWriter dataBitsWriter = new DataBitsWriter(); - private final ChunkSection[] nearbyChunkSections = new ChunkSection[4]; - - public void obfuscate(ChunkPacketInfoAntiXray chunkPacketInfoAntiXray) { - try { - boolean[] solidTemp = null; - boolean[] obfuscateTemp = null; - dataBitsReader.setDataBits(chunkPacketInfoAntiXray.getData()); - dataBitsWriter.setDataBits(chunkPacketInfoAntiXray.getData()); - int counter = 0; - - for (int chunkSectionIndex = 0; chunkSectionIndex <= maxChunkSectionIndex; chunkSectionIndex++) { - if (chunkPacketInfoAntiXray.isWritten(chunkSectionIndex) && chunkPacketInfoAntiXray.getPredefinedObjects(chunkSectionIndex) != null) { - int[] predefinedBlockDataBitsTemp; - - if (chunkPacketInfoAntiXray.getDataPalette(chunkSectionIndex) == ChunkSection.GLOBAL_PALETTE) { - predefinedBlockDataBitsTemp = engineMode == EngineMode.HIDE ? chunkPacketInfoAntiXray.getChunk().world.getWorld().getEnvironment() == Environment.NETHER ? predefinedBlockDataBitsNetherrackGlobal : chunkPacketInfoAntiXray.getChunk().world.getWorld().getEnvironment() == Environment.THE_END ? predefinedBlockDataBitsEndStoneGlobal : predefinedBlockDataBitsStoneGlobal : predefinedBlockDataBitsGlobal; - } else { - predefinedBlockDataBitsTemp = predefinedBlockDataBits == null ? predefinedBlockDataBits = engineMode == EngineMode.HIDE ? new int[1] : new int[predefinedBlockData.length] : predefinedBlockDataBits; - - for (int i = 0; i < predefinedBlockDataBitsTemp.length; i++) { - predefinedBlockDataBitsTemp[i] = chunkPacketInfoAntiXray.getDataPalette(chunkSectionIndex).getOrCreateIdFor(chunkPacketInfoAntiXray.getPredefinedObjects(chunkSectionIndex)[i]); - } - } - - dataBitsWriter.setIndex(chunkPacketInfoAntiXray.getOrCreateIdForIndex(chunkSectionIndex)); - - //Check if the chunk section below was not obfuscated - if (chunkSectionIndex == 0 || !chunkPacketInfoAntiXray.isWritten(chunkSectionIndex - 1) || chunkPacketInfoAntiXray.getPredefinedObjects(chunkSectionIndex - 1) == null) { - //If so, initialize some stuff - dataBitsReader.setBitsPerObject(chunkPacketInfoAntiXray.getBitsPerObject(chunkSectionIndex)); - dataBitsReader.setIndex(chunkPacketInfoAntiXray.getOrCreateIdForIndex(chunkSectionIndex)); - solidTemp = readDataPalette(chunkPacketInfoAntiXray.getDataPalette(chunkSectionIndex), solid, solidGlobal); - obfuscateTemp = readDataPalette(chunkPacketInfoAntiXray.getDataPalette(chunkSectionIndex), obfuscate, obfuscateGlobal); - //Read the blocks of the upper layer of the chunk section below if it exists - ChunkSection belowChunkSection = null; - boolean skipFirstLayer = chunkSectionIndex == 0 || (belowChunkSection = chunkPacketInfoAntiXray.getChunk().getSections()[chunkSectionIndex - 1]) == Chunk.EMPTY_CHUNK_SECTION; - - for (int z = 0; z < 16; z++) { - for (int x = 0; x < 16; x++) { - current[z][x] = true; - next[z][x] = skipFirstLayer || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(belowChunkSection.getType(x, 15, z))]; - } - } - - //Abuse the obfuscateLayer method to read the blocks of the first layer of the current chunk section - dataBitsWriter.setBitsPerObject(0); - obfuscateLayer(-1, dataBitsReader, dataBitsWriter, solidTemp, obfuscateTemp, predefinedBlockDataBitsTemp, current, next, nextNext, emptyNearbyChunkSections, counter); - } - - dataBitsWriter.setBitsPerObject(chunkPacketInfoAntiXray.getBitsPerObject(chunkSectionIndex)); - nearbyChunkSections[0] = chunkPacketInfoAntiXray.getNearbyChunks()[0] == null ? Chunk.EMPTY_CHUNK_SECTION : chunkPacketInfoAntiXray.getNearbyChunks()[0].getSections()[chunkSectionIndex]; - nearbyChunkSections[1] = chunkPacketInfoAntiXray.getNearbyChunks()[1] == null ? Chunk.EMPTY_CHUNK_SECTION : chunkPacketInfoAntiXray.getNearbyChunks()[1].getSections()[chunkSectionIndex]; - nearbyChunkSections[2] = chunkPacketInfoAntiXray.getNearbyChunks()[2] == null ? Chunk.EMPTY_CHUNK_SECTION : chunkPacketInfoAntiXray.getNearbyChunks()[2].getSections()[chunkSectionIndex]; - nearbyChunkSections[3] = chunkPacketInfoAntiXray.getNearbyChunks()[3] == null ? Chunk.EMPTY_CHUNK_SECTION : chunkPacketInfoAntiXray.getNearbyChunks()[3].getSections()[chunkSectionIndex]; - - //Obfuscate all layers of the current chunk section except the upper one - for (int y = 0; y < 15; y++) { - boolean[][] temp = current; - current = next; - next = nextNext; - nextNext = temp; - counter = obfuscateLayer(y, dataBitsReader, dataBitsWriter, solidTemp, obfuscateTemp, predefinedBlockDataBitsTemp, current, next, nextNext, nearbyChunkSections, counter); - } - - //Check if the chunk section above doesn't need obfuscation - if (chunkSectionIndex == maxChunkSectionIndex || !chunkPacketInfoAntiXray.isWritten(chunkSectionIndex + 1) || chunkPacketInfoAntiXray.getPredefinedObjects(chunkSectionIndex + 1) == null) { - //If so, obfuscate the upper layer of the current chunk section by reading blocks of the first layer from the chunk section above if it exists - ChunkSection aboveChunkSection; - - if (chunkSectionIndex != 15 && (aboveChunkSection = chunkPacketInfoAntiXray.getChunk().getSections()[chunkSectionIndex + 1]) != Chunk.EMPTY_CHUNK_SECTION) { - boolean[][] temp = current; - current = next; - next = nextNext; - nextNext = temp; - - for (int z = 0; z < 16; z++) { - for (int x = 0; x < 16; x++) { - if (!solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(aboveChunkSection.getType(x, 0, z))]) { - current[z][x] = true; - } - } - } - - //There is nothing to read anymore - dataBitsReader.setBitsPerObject(0); - solid[0] = true; - counter = obfuscateLayer(15, dataBitsReader, dataBitsWriter, solid, obfuscateTemp, predefinedBlockDataBitsTemp, current, next, nextNext, nearbyChunkSections, counter); - } - } else { - //If not, initialize the reader and other stuff for the chunk section above to obfuscate the upper layer of the current chunk section - dataBitsReader.setBitsPerObject(chunkPacketInfoAntiXray.getBitsPerObject(chunkSectionIndex + 1)); - dataBitsReader.setIndex(chunkPacketInfoAntiXray.getOrCreateIdForIndex(chunkSectionIndex + 1)); - solidTemp = readDataPalette(chunkPacketInfoAntiXray.getDataPalette(chunkSectionIndex + 1), solid, solidGlobal); - obfuscateTemp = readDataPalette(chunkPacketInfoAntiXray.getDataPalette(chunkSectionIndex + 1), obfuscate, obfuscateGlobal); - boolean[][] temp = current; - current = next; - next = nextNext; - nextNext = temp; - counter = obfuscateLayer(15, dataBitsReader, dataBitsWriter, solidTemp, obfuscateTemp, predefinedBlockDataBitsTemp, current, next, nextNext, nearbyChunkSections, counter); - } - - dataBitsWriter.finish(); - } - } - - chunkPacketInfoAntiXray.getPacketPlayOutMapChunk().setReady(true); - - } finally { - if (chunkPacketInfoAntiXray.ticketHold != null) { - Runnable runnable = () -> { - Chunk chunk = chunkPacketInfoAntiXray.getChunk(); - ChunkCoordIntPair chunkPos = chunk.getPos(); - - ChunkPacketBlockControllerAntiXray.this.removeXrayTickets(chunkPos.x, chunkPos.z, (ChunkProviderServer) chunk.world.getChunkProvider(), - chunkPacketInfoAntiXray.ticketHold); - }; - if (MinecraftServer.getServer().isMainThread()) { - runnable.run(); - } else { - MinecraftServer.getServer().scheduleOnMain(runnable); - } - } - } - } - - private int obfuscateLayer(int y, DataBitsReader dataBitsReader, DataBitsWriter dataBitsWriter, boolean[] solid, boolean[] obfuscate, int[] predefinedBlockDataBits, boolean[][] current, boolean[][] next, boolean[][] nextNext, ChunkSection[] nearbyChunkSections, int counter) { - //First block of first line - int dataBits = dataBitsReader.read(); - - if (nextNext[0][0] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[0][1] = true; - next[1][0] = true; - } else { - if (nearbyChunkSections[2] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[2].getType(0, y, 15))] || nearbyChunkSections[0] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[0].getType(15, y, 0))] || current[0][0]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[0][0] = true; - } - - //First line - for (int x = 1; x < 15; x++) { - dataBits = dataBitsReader.read(); - - if (nextNext[0][x] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[0][x - 1] = true; - next[0][x + 1] = true; - next[1][x] = true; - } else { - if (nearbyChunkSections[2] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[2].getType(x, y, 15))] || current[0][x]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[0][x] = true; - } - } - - //Last block of first line - dataBits = dataBitsReader.read(); - - if (nextNext[0][15] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[0][14] = true; - next[1][15] = true; - } else { - if (nearbyChunkSections[2] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[2].getType(15, y, 15))] || nearbyChunkSections[1] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[1].getType(0, y, 0))] || current[0][15]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[0][15] = true; - } - - //All inner lines - for (int z = 1; z < 15; z++) { - //First block - dataBits = dataBitsReader.read(); - - if (nextNext[z][0] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[z][1] = true; - next[z - 1][0] = true; - next[z + 1][0] = true; - } else { - if (nearbyChunkSections[0] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[0].getType(15, y, z))] || current[z][0]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[z][0] = true; - } - - //All inner blocks - for (int x = 1; x < 15; x++) { - dataBits = dataBitsReader.read(); - - if (nextNext[z][x] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[z][x - 1] = true; - next[z][x + 1] = true; - next[z - 1][x] = true; - next[z + 1][x] = true; - } else { - if (current[z][x]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[z][x] = true; - } - } - - //Last block - dataBits = dataBitsReader.read(); - - if (nextNext[z][15] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[z][14] = true; - next[z - 1][15] = true; - next[z + 1][15] = true; - } else { - if (nearbyChunkSections[1] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[1].getType(0, y, z))] || current[z][15]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[z][15] = true; - } - } - - //First block of last line - dataBits = dataBitsReader.read(); - - if (nextNext[15][0] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[15][1] = true; - next[14][0] = true; - } else { - if (nearbyChunkSections[3] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[3].getType(0, y, 0))] || nearbyChunkSections[0] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[0].getType(15, y, 15))] || current[15][0]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[15][0] = true; - } - - //Last line - for (int x = 1; x < 15; x++) { - dataBits = dataBitsReader.read(); - - if (nextNext[15][x] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[15][x - 1] = true; - next[15][x + 1] = true; - next[14][x] = true; - } else { - if (nearbyChunkSections[3] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[3].getType(x, y, 0))] || current[15][x]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[15][x] = true; - } - } - - //Last block of last line - dataBits = dataBitsReader.read(); - - if (nextNext[15][15] = !solid[dataBits]) { - dataBitsWriter.skip(); - next[15][14] = true; - next[14][15] = true; - } else { - if (nearbyChunkSections[3] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[3].getType(15, y, 0))] || nearbyChunkSections[1] == Chunk.EMPTY_CHUNK_SECTION || !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(nearbyChunkSections[1].getType(0, y, 15))] || current[15][15]) { - dataBitsWriter.skip(); - } else { - if (counter >= predefinedBlockDataBits.length) { - counter = 0; - } - - dataBitsWriter.write(predefinedBlockDataBits[counter++]); - } - } - - if (!obfuscate[dataBits]) { - next[15][15] = true; - } - - return counter; - } - - private boolean[] readDataPalette(DataPalette dataPalette, boolean[] temp, boolean[] global) { - if (dataPalette == ChunkSection.GLOBAL_PALETTE) { - return global; - } - - IBlockData blockData; - - for (int i = 0; (blockData = dataPalette.getObject(i)) != null; i++) { - temp[i] = global[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(blockData)]; - } - - return temp; - } - - @Override - public void onBlockChange(World world, BlockPosition blockPosition, IBlockData newBlockData, IBlockData oldBlockData, int flag) { - if (oldBlockData != null && solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(oldBlockData)] && !solidGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(newBlockData)] && blockPosition.getY() <= maxBlockYUpdatePosition) { - updateNearbyBlocks(world, blockPosition); - } - } - - @Override - public void onPlayerLeftClickBlock(PlayerInteractManager playerInteractManager, BlockPosition blockPosition, EnumDirection enumDirection) { - if (blockPosition.getY() <= maxBlockYUpdatePosition) { - updateNearbyBlocks(playerInteractManager.world, blockPosition); - } - } - - private void updateNearbyBlocks(World world, BlockPosition blockPosition) { - if (updateRadius >= 2) { - BlockPosition temp = blockPosition.west(); - updateBlock(world, temp); - updateBlock(world, temp.west()); - updateBlock(world, temp.down()); - updateBlock(world, temp.up()); - updateBlock(world, temp.north()); - updateBlock(world, temp.south()); - updateBlock(world, temp = blockPosition.east()); - updateBlock(world, temp.east()); - updateBlock(world, temp.down()); - updateBlock(world, temp.up()); - updateBlock(world, temp.north()); - updateBlock(world, temp.south()); - updateBlock(world, temp = blockPosition.down()); - updateBlock(world, temp.down()); - updateBlock(world, temp.north()); - updateBlock(world, temp.south()); - updateBlock(world, temp = blockPosition.up()); - updateBlock(world, temp.up()); - updateBlock(world, temp.north()); - updateBlock(world, temp.south()); - updateBlock(world, temp = blockPosition.north()); - updateBlock(world, temp.north()); - updateBlock(world, temp = blockPosition.south()); - updateBlock(world, temp.south()); - } else if (updateRadius == 1) { - updateBlock(world, blockPosition.west()); - updateBlock(world, blockPosition.east()); - updateBlock(world, blockPosition.down()); - updateBlock(world, blockPosition.up()); - updateBlock(world, blockPosition.north()); - updateBlock(world, blockPosition.south()); - } else { - //Do nothing if updateRadius <= 0 (test mode) - } - } - - private void updateBlock(World world, BlockPosition blockPosition) { - IBlockData blockData = world.getTypeIfLoaded(blockPosition); - - if (blockData != null && obfuscateGlobal[ChunkSection.GLOBAL_PALETTE.getOrCreateIdFor(blockData)]) { - //world.notify(blockPosition, blockData, blockData, 3); - ((WorldServer)world).getChunkProvider().flagDirty(blockPosition); // We only need to re-send to client - } - } - - public enum EngineMode { - - HIDE(1, "hide ores"), - OBFUSCATE(2, "obfuscate"); - - private final int id; - private final String description; - - EngineMode(int id, String description) { - this.id = id; - this.description = description; - } - - public static EngineMode getById(int id) { - for (EngineMode engineMode : values()) { - if (engineMode.id == id) { - return engineMode; - } - } - - return null; - } - - public int getId() { - return id; - } - - public String getDescription() { - return description; - } - } - - public enum ChunkEdgeMode { - - DEFAULT(1, "default"), - WAIT(2, "wait until nearby chunks are loaded"), - LOAD(3, "load nearby chunks"); - - private final int id; - private final String description; - - ChunkEdgeMode(int id, String description) { - this.id = id; - this.description = description; - } - - public static ChunkEdgeMode getById(int id) { - for (ChunkEdgeMode chunkEdgeMode : values()) { - if (chunkEdgeMode.id == id) { - return chunkEdgeMode; - } - } - - return null; - } - - public int getId() { - return id; - } - - public String getDescription() { - return description; - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketInfo.java b/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketInfo.java deleted file mode 100644 index a68bace35..000000000 --- a/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketInfo.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.destroystokyo.paper.antixray; - -import net.minecraft.server.Chunk; -import net.minecraft.server.DataPalette; -import net.minecraft.server.PacketPlayOutMapChunk; - -public class ChunkPacketInfo { - - private final PacketPlayOutMapChunk packetPlayOutMapChunk; - private final Chunk chunk; - private final int chunkSectionSelector; - private byte[] data; - private final int[] bitsPerObject = new int[16]; - private final Object[] dataPalettes = new Object[16]; - private final int[] dataBitsIndexes = new int[16]; - private final Object[][] predefinedObjects = new Object[16][]; - - public ChunkPacketInfo(PacketPlayOutMapChunk packetPlayOutMapChunk, Chunk chunk, int chunkSectionSelector) { - this.packetPlayOutMapChunk = packetPlayOutMapChunk; - this.chunk = chunk; - this.chunkSectionSelector = chunkSectionSelector; - } - - public PacketPlayOutMapChunk getPacketPlayOutMapChunk() { - return packetPlayOutMapChunk; - } - - public Chunk getChunk() { - return chunk; - } - - public int getChunkSectionSelector() { - return chunkSectionSelector; - } - - public byte[] getData() { - return data; - } - - public void setData(byte[] data) { - this.data = data; - } - - public int getBitsPerObject(int chunkSectionIndex) { - return bitsPerObject[chunkSectionIndex]; - } - - public void setBitsPerObject(int chunkSectionIndex, int bitsPerObject) { - this.bitsPerObject[chunkSectionIndex] = bitsPerObject; - } - - @SuppressWarnings("unchecked") - public DataPalette getDataPalette(int chunkSectionIndex) { - return (DataPalette) dataPalettes[chunkSectionIndex]; - } - - public void setDataPalette(int chunkSectionIndex, DataPalette dataPalette) { - dataPalettes[chunkSectionIndex] = dataPalette; - } - - public int getOrCreateIdForIndex(int chunkSectionIndex) { - return dataBitsIndexes[chunkSectionIndex]; - } - - public void setDataBitsIndex(int chunkSectionIndex, int dataBitsIndex) { - dataBitsIndexes[chunkSectionIndex] = dataBitsIndex; - } - - @SuppressWarnings("unchecked") - public T[] getPredefinedObjects(int chunkSectionIndex) { - return (T[]) predefinedObjects[chunkSectionIndex]; - } - - public void setPredefinedObjects(int chunkSectionIndex, T[] predefinedObjects) { - this.predefinedObjects[chunkSectionIndex] = predefinedObjects; - } - - public boolean isWritten(int chunkSectionIndex) { - return bitsPerObject[chunkSectionIndex] != 0; - } -} diff --git a/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketInfoAntiXray.java b/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketInfoAntiXray.java deleted file mode 100644 index 067dfb2f1..000000000 --- a/src/main/java/com/destroystokyo/paper/antixray/ChunkPacketInfoAntiXray.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.destroystokyo.paper.antixray; - -import net.minecraft.server.Chunk; -import net.minecraft.server.IBlockData; -import net.minecraft.server.PacketPlayOutMapChunk; - -public class ChunkPacketInfoAntiXray extends ChunkPacketInfo implements Runnable { - - private Chunk[] nearbyChunks; - private final ChunkPacketBlockControllerAntiXray chunkPacketBlockControllerAntiXray; - public Integer ticketHold; - - public ChunkPacketInfoAntiXray(PacketPlayOutMapChunk packetPlayOutMapChunk, Chunk chunk, int chunkSectionSelector, - ChunkPacketBlockControllerAntiXray chunkPacketBlockControllerAntiXray) { - super(packetPlayOutMapChunk, chunk, chunkSectionSelector); - this.chunkPacketBlockControllerAntiXray = chunkPacketBlockControllerAntiXray; - } - - public Chunk[] getNearbyChunks() { - return nearbyChunks; - } - - public void setNearbyChunks(Chunk... nearbyChunks) { - this.nearbyChunks = nearbyChunks; - } - - @Override - public void run() { - chunkPacketBlockControllerAntiXray.obfuscate(this); - } -} diff --git a/src/main/java/com/destroystokyo/paper/antixray/DataBitsReader.java b/src/main/java/com/destroystokyo/paper/antixray/DataBitsReader.java deleted file mode 100644 index cc586827a..000000000 --- a/src/main/java/com/destroystokyo/paper/antixray/DataBitsReader.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.destroystokyo.paper.antixray; - -public class DataBitsReader { - - private byte[] dataBits; - private int bitsPerObject; - private int mask; - private int longInDataBitsIndex; - private int bitInLongIndex; - private long current; - - public void setDataBits(byte[] dataBits) { - this.dataBits = dataBits; - } - - public void setBitsPerObject(int bitsPerObject) { - this.bitsPerObject = bitsPerObject; - mask = (1 << bitsPerObject) - 1; - } - - public void setIndex(int index) { - this.longInDataBitsIndex = index; - bitInLongIndex = 0; - init(); - } - - private void init() { - if (dataBits.length > longInDataBitsIndex + 7) { - current = ((((long) dataBits[longInDataBitsIndex]) << 56) - | (((long) dataBits[longInDataBitsIndex + 1] & 0xff) << 48) - | (((long) dataBits[longInDataBitsIndex + 2] & 0xff) << 40) - | (((long) dataBits[longInDataBitsIndex + 3] & 0xff) << 32) - | (((long) dataBits[longInDataBitsIndex + 4] & 0xff) << 24) - | (((long) dataBits[longInDataBitsIndex + 5] & 0xff) << 16) - | (((long) dataBits[longInDataBitsIndex + 6] & 0xff) << 8) - | (((long) dataBits[longInDataBitsIndex + 7] & 0xff))); - } - } - - public int read() { - int value = (int) (current >>> bitInLongIndex) & mask; - bitInLongIndex += bitsPerObject; - - if (bitInLongIndex > 63) { - bitInLongIndex -= 64; - longInDataBitsIndex += 8; - init(); - - if (bitInLongIndex > 0) { - value |= current << bitsPerObject - bitInLongIndex & mask; - } - } - - return value; - } -} diff --git a/src/main/java/com/destroystokyo/paper/antixray/DataBitsWriter.java b/src/main/java/com/destroystokyo/paper/antixray/DataBitsWriter.java deleted file mode 100644 index 37093419c..000000000 --- a/src/main/java/com/destroystokyo/paper/antixray/DataBitsWriter.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.destroystokyo.paper.antixray; - -public class DataBitsWriter { - - private byte[] dataBits; - private int bitsPerObject; - private long mask; - private int longInDataBitsIndex; - private int bitInLongIndex; - private long current; - private boolean dirty; - - public void setDataBits(byte[] dataBits) { - this.dataBits = dataBits; - } - - public void setBitsPerObject(int bitsPerObject) { - this.bitsPerObject = bitsPerObject; - mask = (1 << bitsPerObject) - 1; - } - - public void setIndex(int index) { - this.longInDataBitsIndex = index; - bitInLongIndex = 0; - init(); - } - - private void init() { - if (dataBits.length > longInDataBitsIndex + 7) { - current = ((((long) dataBits[longInDataBitsIndex]) << 56) - | (((long) dataBits[longInDataBitsIndex + 1] & 0xff) << 48) - | (((long) dataBits[longInDataBitsIndex + 2] & 0xff) << 40) - | (((long) dataBits[longInDataBitsIndex + 3] & 0xff) << 32) - | (((long) dataBits[longInDataBitsIndex + 4] & 0xff) << 24) - | (((long) dataBits[longInDataBitsIndex + 5] & 0xff) << 16) - | (((long) dataBits[longInDataBitsIndex + 6] & 0xff) << 8) - | (((long) dataBits[longInDataBitsIndex + 7] & 0xff))); - } - - dirty = false; - } - - public void finish() { - if (dirty && dataBits.length > longInDataBitsIndex + 7) { - dataBits[longInDataBitsIndex] = (byte) (current >> 56 & 0xff); - dataBits[longInDataBitsIndex + 1] = (byte) (current >> 48 & 0xff); - dataBits[longInDataBitsIndex + 2] = (byte) (current >> 40 & 0xff); - dataBits[longInDataBitsIndex + 3] = (byte) (current >> 32 & 0xff); - dataBits[longInDataBitsIndex + 4] = (byte) (current >> 24 & 0xff); - dataBits[longInDataBitsIndex + 5] = (byte) (current >> 16 & 0xff); - dataBits[longInDataBitsIndex + 6] = (byte) (current >> 8 & 0xff); - dataBits[longInDataBitsIndex + 7] = (byte) (current & 0xff); - } - } - - public void write(int value) { - current = current & ~(mask << bitInLongIndex) | (value & mask) << bitInLongIndex; - dirty = true; - bitInLongIndex += bitsPerObject; - - if (bitInLongIndex > 63) { - finish(); - bitInLongIndex -= 64; - longInDataBitsIndex += 8; - init(); - - if (bitInLongIndex > 0) { - current = current & ~(mask >>> bitsPerObject - bitInLongIndex) | (value & mask) >>> bitsPerObject - bitInLongIndex; - dirty = true; - } - } - } - - public void skip() { - bitInLongIndex += bitsPerObject; - - if (bitInLongIndex > 63) { - finish(); - bitInLongIndex -= 64; - longInDataBitsIndex += 8; - init(); - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/block/CraftBlockSoundGroup.java b/src/main/java/com/destroystokyo/paper/block/CraftBlockSoundGroup.java deleted file mode 100644 index 99f99330d..000000000 --- a/src/main/java/com/destroystokyo/paper/block/CraftBlockSoundGroup.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.destroystokyo.paper.block; - -import net.minecraft.server.SoundEffectType; -import org.bukkit.Sound; -import org.bukkit.craftbukkit.CraftSound; - -public class CraftBlockSoundGroup implements BlockSoundGroup { - private final SoundEffectType soundEffectType; - - public CraftBlockSoundGroup(SoundEffectType soundEffectType) { - this.soundEffectType = soundEffectType; - } - - @Override - public Sound getBreakSound() { - return CraftSound.getSoundByEffect(soundEffectType.getBreakSound()); - } - - @Override - public Sound getStepSound() { - return CraftSound.getSoundByEffect(soundEffectType.getStepSound()); - } - - @Override - public Sound getPlaceSound() { - return CraftSound.getSoundByEffect(soundEffectType.getPlaceSound()); - } - - @Override - public Sound getHitSound() { - return CraftSound.getSoundByEffect(soundEffectType.getHitSound()); - } - - @Override - public Sound getFallSound() { - return CraftSound.getSoundByEffect(soundEffectType.getFallSound()); - } -} diff --git a/src/main/java/com/destroystokyo/paper/console/PaperConsole.java b/src/main/java/com/destroystokyo/paper/console/PaperConsole.java deleted file mode 100644 index cd6e25923..000000000 --- a/src/main/java/com/destroystokyo/paper/console/PaperConsole.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.destroystokyo.paper.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 PaperConsole extends SimpleTerminalConsole { - - private final DedicatedServer server; - - public PaperConsole(DedicatedServer server) { - this.server = server; - } - - @Override - protected LineReader buildReader(LineReaderBuilder builder) { - return super.buildReader(builder - .appName("Paper") - .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.getServerCommandListener()); - } - - @Override - protected void shutdown() { - this.server.safeShutdown(false); - } - -} diff --git a/src/main/java/com/destroystokyo/paper/console/TerminalConsoleCommandSender.java b/src/main/java/com/destroystokyo/paper/console/TerminalConsoleCommandSender.java deleted file mode 100644 index 685deaa0e..000000000 --- a/src/main/java/com/destroystokyo/paper/console/TerminalConsoleCommandSender.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.destroystokyo.paper.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); - } - -} diff --git a/src/main/java/com/destroystokyo/paper/entity/CraftRangedEntity.java b/src/main/java/com/destroystokyo/paper/entity/CraftRangedEntity.java deleted file mode 100644 index 696660b08..000000000 --- a/src/main/java/com/destroystokyo/paper/entity/CraftRangedEntity.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.destroystokyo.paper.entity; - -import net.minecraft.server.IRangedEntity; -import org.bukkit.craftbukkit.entity.CraftLivingEntity; -import org.bukkit.entity.LivingEntity; - -public interface CraftRangedEntity extends RangedEntity { - T getHandle(); - - @Override - default void rangedAttack(LivingEntity target, float charge) { - getHandle().rangedAttack(((CraftLivingEntity) target).getHandle(), charge); - } - - @Override - default void setChargingAttack(boolean raiseHands) { - getHandle().setChargingAttack(raiseHands); - } -} diff --git a/src/main/java/com/destroystokyo/paper/entity/PaperPathfinder.java b/src/main/java/com/destroystokyo/paper/entity/PaperPathfinder.java deleted file mode 100644 index f68a07cb9..000000000 --- a/src/main/java/com/destroystokyo/paper/entity/PaperPathfinder.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.destroystokyo.paper.entity; - -import net.minecraft.server.EntityInsentient; -import net.minecraft.server.PathEntity; -import net.minecraft.server.PathPoint; -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftLivingEntity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Mob; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.List; - -public class PaperPathfinder implements com.destroystokyo.paper.entity.Pathfinder { - - private final EntityInsentient entity; - - public PaperPathfinder(EntityInsentient entity) { - this.entity = entity; - } - - @Override - public Mob getEntity() { - return entity.getBukkitMob(); - } - - @Override - public void stopPathfinding() { - entity.getNavigation().stopPathfinding(); - } - - @Override - public boolean hasPath() { - return entity.getNavigation().getPathEntity() != null; - } - - @Nullable - @Override - public PathResult getCurrentPath() { - PathEntity path = entity.getNavigation().getPathEntity(); - return path != null ? new PaperPathResult(path) : null; - } - - @Nullable - @Override - public PathResult findPath(Location loc) { - Validate.notNull(loc, "Location can not be null"); - PathEntity path = entity.getNavigation().calculateDestination(loc.getX(), loc.getY(), loc.getZ()); - return path != null ? new PaperPathResult(path) : null; - } - - @Nullable - @Override - public PathResult findPath(LivingEntity target) { - Validate.notNull(target, "Target can not be null"); - PathEntity path = entity.getNavigation().calculateDestination(((CraftLivingEntity) target).getHandle()); - return path != null ? new PaperPathResult(path) : null; - } - - @Override - public boolean moveTo(@Nonnull PathResult path, double speed) { - Validate.notNull(path, "PathResult can not be null"); - PathEntity pathEntity = ((PaperPathResult) path).path; - return entity.getNavigation().setDestination(pathEntity, speed); - } - - public class PaperPathResult implements com.destroystokyo.paper.entity.PaperPathfinder.PathResult { - - private final PathEntity path; - PaperPathResult(PathEntity path) { - this.path = path; - } - - @Nullable - @Override - public Location getFinalPoint() { - PathPoint point = path.getFinalPoint(); - return point != null ? toLoc(point) : null; - } - - @Override - public List getPoints() { - List points = new ArrayList<>(); - for (PathPoint point : path.getPoints()) { - points.add(toLoc(point)); - } - return points; - } - - @Override - public int getNextPointIndex() { - return path.getNextIndex(); - } - - @Nullable - @Override - public Location getNextPoint() { - if (!path.hasNext()) { - return null; - } - return toLoc(path.getPoints().get(path.getNextIndex())); - } - } - - private Location toLoc(PathPoint point) { - return new Location(entity.world.getWorld(), point.getX(), point.getY(), point.getZ()); - } -} diff --git a/src/main/java/com/destroystokyo/paper/io/IOUtil.java b/src/main/java/com/destroystokyo/paper/io/IOUtil.java deleted file mode 100644 index 5af0ac3d9..000000000 --- a/src/main/java/com/destroystokyo/paper/io/IOUtil.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.destroystokyo.paper.io; - -import org.bukkit.Bukkit; - -public final class IOUtil { - - /* Copied from concrete or concurrentutil */ - - public static long getCoordinateKey(final int x, final int z) { - return ((long)z << 32) | (x & 0xFFFFFFFFL); - } - - public static int getCoordinateX(final long key) { - return (int)key; - } - - public static int getCoordinateZ(final long key) { - return (int)(key >>> 32); - } - - public static int getRegionCoordinate(final int chunkCoordinate) { - return chunkCoordinate >> 5; - } - - public static int getChunkInRegion(final int chunkCoordinate) { - return chunkCoordinate & 31; - } - - public static String genericToString(final Object object) { - return object == null ? "null" : object.getClass().getName() + ":" + object.toString(); - } - - public static T notNull(final T obj) { - if (obj == null) { - throw new NullPointerException(); - } - return obj; - } - - public static T notNull(final T obj, final String msgIfNull) { - if (obj == null) { - throw new NullPointerException(msgIfNull); - } - return obj; - } - - public static void arrayBounds(final int off, final int len, final int arrayLength, final String msgPrefix) { - if (off < 0 || len < 0 || (arrayLength - off) < len) { - throw new ArrayIndexOutOfBoundsException(msgPrefix + ": off: " + off + ", len: " + len + ", array length: " + arrayLength); - } - } - - public static int getPriorityForCurrentThread() { - return Bukkit.isPrimaryThread() ? PrioritizedTaskQueue.HIGHEST_PRIORITY : PrioritizedTaskQueue.NORMAL_PRIORITY; - } - - @SuppressWarnings("unchecked") - public static void rethrow(final Throwable throwable) throws T { - throw (T)throwable; - } - -} diff --git a/src/main/java/com/destroystokyo/paper/io/PaperFileIOThread.java b/src/main/java/com/destroystokyo/paper/io/PaperFileIOThread.java deleted file mode 100644 index 4f10a8311..000000000 --- a/src/main/java/com/destroystokyo/paper/io/PaperFileIOThread.java +++ /dev/null @@ -1,661 +0,0 @@ -package com.destroystokyo.paper.io; - -import net.minecraft.server.ChunkCoordIntPair; -import net.minecraft.server.ExceptionWorldConflict; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.RegionFile; -import net.minecraft.server.WorldServer; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Consumer; -import java.util.function.Function; - -/** - * Prioritized singleton thread responsible for all chunk IO that occurs in a minecraft server. - * - *

- * Singleton access: {@link Holder#INSTANCE} - *

- * - *

- * All functions provided are MT-Safe, however certain ordering constraints are (but not enforced): - *

  • - * Chunk saves may not occur for unloaded chunks. - *
  • - *
  • - * Tasks must be scheduled on the main thread. - *
  • - *

    - * - * @see Holder#INSTANCE - * @see #scheduleSave(WorldServer, int, int, NBTTagCompound, NBTTagCompound, int) - * @see #loadChunkDataAsync(WorldServer, int, int, int, Consumer, boolean, boolean, boolean) - */ -public final class PaperFileIOThread extends QueueExecutorThread { - - public static final Logger LOGGER = MinecraftServer.LOGGER; - public static final NBTTagCompound FAILURE_VALUE = new NBTTagCompound(); - - public static final class Holder { - - public static final PaperFileIOThread INSTANCE = new PaperFileIOThread(); - - static { - INSTANCE.start(); - } - } - - private final AtomicLong writeCounter = new AtomicLong(); - - private PaperFileIOThread() { - super(new PrioritizedTaskQueue<>(), (int)(1.0e6)); // 1.0ms spinwait time - this.setName("Paper RegionFile IO Thread"); - this.setPriority(Thread.NORM_PRIORITY - 1); // we keep priority close to normal because threads can wait on us - this.setUncaughtExceptionHandler((final Thread unused, final Throwable thr) -> { - LOGGER.fatal("Uncaught exception thrown from IO thread, report this!", thr); - }); - } - - /* run() is implemented by superclass */ - - /* - * - * IO thread will perform reads before writes - * - * How reads/writes are scheduled: - * - * If read in progress while scheduling write, ignore read and schedule write - * If read in progress while scheduling read (no write in progress), chain the read task - * - * - * If write in progress while scheduling read, use the pending write data and ret immediately - * If write in progress while scheduling write (ignore read in progress), overwrite the write in progress data - * - * This allows the reads and writes to act as if they occur synchronously to the thread scheduling them, however - * it fails to properly propagate write failures. When writes fail the data is kept so future reads will actually - * read the failed write data. This should hopefully act as a way to prevent data loss for spurious fails for writing data. - * - */ - - /** - * Attempts to bump the priority of all IO tasks for the given chunk coordinates. This has no effect if no tasks are queued. - * @param world Chunk's world - * @param chunkX Chunk's x coordinate - * @param chunkZ Chunk's z coordinate - * @param priority Priority level to try to bump to - */ - public void bumpPriority(final WorldServer world, final int chunkX, final int chunkZ, final int priority) { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalArgumentException("Invalid priority: " + priority); - } - - final Long key = Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ)); - - final ChunkDataTask poiTask = world.poiDataController.tasks.get(key); - final ChunkDataTask chunkTask = world.chunkDataController.tasks.get(key); - - if (poiTask != null) { - poiTask.raisePriority(priority); - } - if (chunkTask != null) { - chunkTask.raisePriority(priority); - } - } - - // Hack start - /** - * if {@code waitForRead} is true, then this task will wait on an available read task, else it will wait on an available - * write task - * if {@code poiTask} is true, then this task will wait on a poi task, else it will wait on chunk data task - * @deprecated API is garbage and will only work for main thread queueing of tasks (which is vanilla), plugins messing - * around asynchronously will give unexpected results - * @return whether the task succeeded, or {@code null} if there is no task - */ - @Deprecated - public Boolean waitForIOToComplete(final WorldServer world, final int chunkX, final int chunkZ, final boolean waitForRead, - final boolean poiTask) { - final ChunkDataTask task; - - final Long key = IOUtil.getCoordinateKey(chunkX, chunkZ); - if (poiTask) { - task = world.poiDataController.tasks.get(key); - } else { - task = world.chunkDataController.tasks.get(key); - } - - if (task == null) { - return null; - } - - if (waitForRead) { - ChunkDataController.InProgressRead read = task.inProgressRead; - if (read == null) { - return null; - } - return Boolean.valueOf(read.readFuture.join() != PaperFileIOThread.FAILURE_VALUE); - } - - // wait for write - ChunkDataController.InProgressWrite write = task.inProgressWrite; - if (write == null) { - return null; - } - return Boolean.valueOf(write.wrote.join() != PaperFileIOThread.FAILURE_VALUE); - } - // Hack end - - public NBTTagCompound getPendingWrite(final WorldServer world, final int chunkX, final int chunkZ, final boolean poiData) { - final ChunkDataController taskController = poiData ? world.poiDataController : world.chunkDataController; - - final ChunkDataTask dataTask = taskController.tasks.get(Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ))); - - if (dataTask == null) { - return null; - } - - final ChunkDataController.InProgressWrite write = dataTask.inProgressWrite; - - if (write == null) { - return null; - } - - return write.data; - } - - /** - * Sets the priority of all IO tasks for the given chunk coordinates. This has no effect if no tasks are queued. - * @param world Chunk's world - * @param chunkX Chunk's x coordinate - * @param chunkZ Chunk's z coordinate - * @param priority Priority level to set to - */ - public void setPriority(final WorldServer world, final int chunkX, final int chunkZ, final int priority) { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalArgumentException("Invalid priority: " + priority); - } - - final Long key = Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ)); - - final ChunkDataTask poiTask = world.poiDataController.tasks.get(key); - final ChunkDataTask chunkTask = world.chunkDataController.tasks.get(key); - - if (poiTask != null) { - poiTask.updatePriority(priority); - } - if (chunkTask != null) { - chunkTask.updatePriority(priority); - } - } - - /** - * Schedules the chunk data to be written asynchronously. - *

    - * Impl notes: - *

    - *
  • - * This function presumes a chunk load for the coordinates is not called during this function (anytime after is OK). This means - * saves must be scheduled before a chunk is unloaded. - *
  • - *
  • - * Writes may be called concurrently, although only the "later" write will go through. - *
  • - * @param world Chunk's world - * @param chunkX Chunk's x coordinate - * @param chunkZ Chunk's z coordinate - * @param poiData Chunk point of interest data. If {@code null}, then no poi data is saved. - * @param chunkData Chunk data. If {@code null}, then no chunk data is saved. - * @param priority Priority level for this task. See {@link PrioritizedTaskQueue} - * @throws IllegalArgumentException If both {@code poiData} and {@code chunkData} are {@code null}. - * @throws IllegalStateException If the file io thread has shutdown. - */ - public void scheduleSave(final WorldServer world, final int chunkX, final int chunkZ, - final NBTTagCompound poiData, final NBTTagCompound chunkData, - final int priority) throws IllegalArgumentException { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalArgumentException("Invalid priority: " + priority); - } - - final long writeCounter = this.writeCounter.getAndIncrement(); - - if (poiData != null) { - this.scheduleWrite(world.poiDataController, world, chunkX, chunkZ, poiData, priority, writeCounter); - } - if (chunkData != null) { - this.scheduleWrite(world.chunkDataController, world, chunkX, chunkZ, chunkData, priority, writeCounter); - } - } - - private void scheduleWrite(final ChunkDataController dataController, final WorldServer world, - final int chunkX, final int chunkZ, final NBTTagCompound data, final int priority, final long writeCounter) { - dataController.tasks.compute(Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ)), (final Long keyInMap, final ChunkDataTask taskRunning) -> { - if (taskRunning == null) { - // no task is scheduled - - // create task - final ChunkDataTask newTask = new ChunkDataTask(priority, world, chunkX, chunkZ, dataController); - newTask.inProgressWrite = new ChunkDataController.InProgressWrite(); - newTask.inProgressWrite.writeCounter = writeCounter; - newTask.inProgressWrite.data = data; - - PaperFileIOThread.this.queueTask(newTask); // schedule - return newTask; - } - - taskRunning.raisePriority(priority); - - if (taskRunning.inProgressWrite == null) { - taskRunning.inProgressWrite = new ChunkDataController.InProgressWrite(); - } - - boolean reschedule = taskRunning.inProgressWrite.writeCounter == -1L; - - // synchronize for readers - //noinspection SynchronizationOnLocalVariableOrMethodParameter - synchronized (taskRunning) { - taskRunning.inProgressWrite.data = data; - taskRunning.inProgressWrite.writeCounter = writeCounter; - } - - if (reschedule) { - // We need to reschedule this task since the previous one is not currently scheduled since it failed - taskRunning.reschedule(priority); - } - - return taskRunning; - }); - } - - /** - * Same as {@link #loadChunkDataAsync(WorldServer, int, int, int, Consumer, boolean, boolean, boolean)}, except this function returns - * a {@link CompletableFuture} which is potentially completed ASYNCHRONOUSLY ON THE FILE IO THREAD when the load task - * has completed. - *

    - * Note that if the chunk fails to load the returned future is completed with {@code null}. - *

    - */ - public CompletableFuture loadChunkDataAsyncFuture(final WorldServer world, final int chunkX, final int chunkZ, - final int priority, final boolean readPoiData, final boolean readChunkData, - final boolean intendingToBlock) { - final CompletableFuture future = new CompletableFuture<>(); - this.loadChunkDataAsync(world, chunkX, chunkZ, priority, future::complete, readPoiData, readChunkData, intendingToBlock); - return future; - } - - /** - * Schedules a load to be executed asynchronously. - *

    - * Impl notes: - *

    - *
  • - * If a chunk fails to load, the {@code onComplete} parameter is completed with {@code null}. - *
  • - *
  • - * It is possible for the {@code onComplete} parameter to be given {@link ChunkData} containing data - * this call did not request. - *
  • - *
  • - * The {@code onComplete} parameter may be completed during the execution of this function synchronously or it may - * be completed asynchronously on this file io thread. Interacting with the file IO thread in the completion of - * data is undefined behaviour, and can cause deadlock. - *
  • - * @param world Chunk's world - * @param chunkX Chunk's x coordinate - * @param chunkZ Chunk's z coordinate - * @param priority Priority level for this task. See {@link PrioritizedTaskQueue} - * @param onComplete Consumer to execute once this task has completed - * @param readPoiData Whether to read point of interest data. If {@code false}, the {@code NBTTagCompound} will be {@code null}. - * @param readChunkData Whether to read chunk data. If {@code false}, the {@code NBTTagCompound} will be {@code null}. - * @return The {@link PrioritizedTaskQueue.PrioritizedTask} associated with this task. Note that this task does not support - * cancellation. - */ - public void loadChunkDataAsync(final WorldServer world, final int chunkX, final int chunkZ, - final int priority, final Consumer onComplete, - final boolean readPoiData, final boolean readChunkData, - final boolean intendingToBlock) { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalArgumentException("Invalid priority: " + priority); - } - - if (!(readPoiData | readChunkData)) { - throw new IllegalArgumentException("Must read chunk data or poi data"); - } - - final ChunkData complete = new ChunkData(); - final boolean[] requireCompletion = new boolean[] { readPoiData, readChunkData }; - - if (readPoiData) { - this.scheduleRead(world.poiDataController, world, chunkX, chunkZ, (final NBTTagCompound poiData) -> { - complete.poiData = poiData; - - final boolean finished; - - // avoid a race condition where the file io thread completes and we complete synchronously - // Note: Synchronization can be elided if both of the accesses are volatile - synchronized (requireCompletion) { - requireCompletion[0] = false; // 0 -> poi data - finished = !requireCompletion[1]; // 1 -> chunk data - } - - if (finished) { - onComplete.accept(complete); - } - }, priority, intendingToBlock); - } - - if (readChunkData) { - this.scheduleRead(world.chunkDataController, world, chunkX, chunkZ, (final NBTTagCompound chunkData) -> { - complete.chunkData = chunkData; - - final boolean finished; - - // avoid a race condition where the file io thread completes and we complete synchronously - // Note: Synchronization can be elided if both of the accesses are volatile - synchronized (requireCompletion) { - requireCompletion[1] = false; // 1 -> chunk data - finished = !requireCompletion[0]; // 0 -> poi data - } - - if (finished) { - onComplete.accept(complete); - } - }, priority, intendingToBlock); - } - - } - - // Note: the onComplete may be called asynchronously or synchronously here. - private void scheduleRead(final ChunkDataController dataController, final WorldServer world, - final int chunkX, final int chunkZ, final Consumer onComplete, final int priority, - final boolean intendingToBlock) { - - Function tryLoadFunction = (final RegionFile file) -> { - if (file == null) { - return Boolean.TRUE; - } - return Boolean.valueOf(file.chunkExists(new ChunkCoordIntPair(chunkX, chunkZ))); - }; - - dataController.tasks.compute(Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ)), (final Long keyInMap, final ChunkDataTask running) -> { - if (running == null) { - // not scheduled - - final Boolean shouldSchedule = intendingToBlock ? dataController.computeForRegionFile(chunkX, chunkZ, tryLoadFunction) : - dataController.computeForRegionFileIfLoaded(chunkX, chunkZ, tryLoadFunction); - - if (shouldSchedule == Boolean.FALSE) { - // not on disk - onComplete.accept(null); - return null; - } - - // set up task - final ChunkDataTask newTask = new ChunkDataTask(priority, world, chunkX, chunkZ, dataController); - newTask.inProgressRead = new ChunkDataController.InProgressRead(); - newTask.inProgressRead.readFuture.thenAccept(onComplete); - - PaperFileIOThread.this.queueTask(newTask); // schedule task - return newTask; - } - - running.raisePriority(priority); - - if (running.inProgressWrite == null) { - // chain to the read future - running.inProgressRead.readFuture.thenAccept(onComplete); - return running; - } - - // at this stage we have to use the in progress write's data to avoid an order issue - // we don't synchronize since all writes to data occur in the compute() call - onComplete.accept(running.inProgressWrite.data); - return running; - }); - } - - /** - * Same as {@link #loadChunkDataAsync(WorldServer, int, int, int, Consumer, boolean, boolean, boolean)}, except this function returns - * the {@link ChunkData} associated with the specified chunk when the task is complete. - * @return The chunk data, or {@code null} if the chunk failed to load. - */ - public ChunkData loadChunkData(final WorldServer world, final int chunkX, final int chunkZ, final int priority, - final boolean readPoiData, final boolean readChunkData) { - return this.loadChunkDataAsyncFuture(world, chunkX, chunkZ, priority, readPoiData, readChunkData, true).join(); - } - - /** - * Schedules the given task at the specified priority to be executed on the IO thread. - *

    - * Internal api. Do not use. - *

    - */ - public void runTask(final int priority, final Runnable runnable) { - this.queueTask(new GeneralTask(priority, runnable)); - } - - static final class GeneralTask extends PrioritizedTaskQueue.PrioritizedTask implements Runnable { - - private final Runnable run; - - public GeneralTask(final int priority, final Runnable run) { - super(priority); - this.run = IOUtil.notNull(run, "Task may not be null"); - } - - @Override - public void run() { - try { - this.run.run(); - } catch (final Throwable throwable) { - if (throwable instanceof ThreadDeath) { - throw (ThreadDeath)throwable; - } - LOGGER.fatal("Failed to execute general task on IO thread " + IOUtil.genericToString(this.run), throwable); - } - } - } - - public static final class ChunkData { - - public NBTTagCompound poiData; - public NBTTagCompound chunkData; - - public ChunkData() {} - - public ChunkData(final NBTTagCompound poiData, final NBTTagCompound chunkData) { - this.poiData = poiData; - this.chunkData = chunkData; - } - } - - public static abstract class ChunkDataController { - - // ConcurrentHashMap synchronizes per chain, so reduce the chance of task's hashes colliding. - public final ConcurrentHashMap tasks = new ConcurrentHashMap<>(64, 0.5f); - - public abstract void writeData(final int x, final int z, final NBTTagCompound compound) throws IOException; - public abstract NBTTagCompound readData(final int x, final int z) throws IOException; - - public abstract T computeForRegionFile(final int chunkX, final int chunkZ, final Function function); - public abstract T computeForRegionFileIfLoaded(final int chunkX, final int chunkZ, final Function function); - - public static final class InProgressWrite { - public long writeCounter; - public NBTTagCompound data; - - // Hack start - @Deprecated - public CompletableFuture wrote = new CompletableFuture<>(); - // Hack end - } - - public static final class InProgressRead { - public final CompletableFuture readFuture = new CompletableFuture<>(); - } - } - - public static final class ChunkDataTask extends PrioritizedTaskQueue.PrioritizedTask implements Runnable { - - public ChunkDataController.InProgressWrite inProgressWrite; - public ChunkDataController.InProgressRead inProgressRead; - - private final WorldServer world; - private final int x; - private final int z; - private final ChunkDataController taskController; - - public ChunkDataTask(final int priority, final WorldServer world, final int x, final int z, final ChunkDataController taskController) { - super(priority); - this.world = world; - this.x = x; - this.z = z; - this.taskController = taskController; - } - - @Override - public String toString() { - return "Task for world: '" + this.world.getWorld().getName() + "' at " + this.x + "," + this.z + - " poi: " + (this.taskController == this.world.poiDataController) + ", hash: " + this.hashCode(); - } - - /* - * - * IO thread will perform reads before writes - * - * How reads/writes are scheduled: - * - * If read in progress while scheduling write, ignore read and schedule write - * If read in progress while scheduling read (no write in progress), chain the read task - * - * - * If write in progress while scheduling read, use the pending write data and ret immediately - * If write in progress while scheduling write (ignore read in progress), overwrite the write in progress data - * - * This allows the reads and writes to act as if they occur synchronously to the thread scheduling them, however - * it fails to properly propagate write failures - * - */ - - void reschedule(final int priority) { - // priority is checked before this stage // TODO what - this.queue.lazySet(null); - this.inProgressWrite.wrote = new CompletableFuture<>(); // Hack - this.priority.lazySet(priority); - PaperFileIOThread.Holder.INSTANCE.queueTask(this); - } - - @Override - public void run() { - ChunkDataController.InProgressRead read = this.inProgressRead; - if (read != null) { - NBTTagCompound compound = PaperFileIOThread.FAILURE_VALUE; - try { - compound = this.taskController.readData(this.x, this.z); - } catch (final Throwable thr) { - if (thr instanceof ThreadDeath) { - throw (ThreadDeath)thr; - } - LOGGER.fatal("Failed to read chunk data for task: " + this.toString(), thr); - // fall through to complete with null data - } - read.readFuture.complete(compound); - } - - final Long chunkKey = Long.valueOf(IOUtil.getCoordinateKey(this.x, this.z)); - - ChunkDataController.InProgressWrite write = this.inProgressWrite; - - if (write == null) { - // IntelliJ warns this is invalid, however it does not consider that writes to the task map & the inProgress field can occur concurrently. - ChunkDataTask inMap = this.taskController.tasks.compute(chunkKey, (final Long keyInMap, final ChunkDataTask valueInMap) -> { - if (valueInMap == null) { - throw new IllegalStateException("Write completed concurrently, expected this task: " + ChunkDataTask.this.toString() + ", report this!"); - } - if (valueInMap != ChunkDataTask.this) { - throw new IllegalStateException("Chunk task mismatch, expected this task: " + ChunkDataTask.this.toString() + ", got: " + valueInMap.toString() + ", report this!"); - } - return valueInMap.inProgressWrite == null ? null : valueInMap; - }); - - if (inMap == null) { - return; // set the task value to null, indicating we're done - } - - // not null, which means there was a concurrent write - write = this.inProgressWrite; - } - - // check if another process is writing - try { - this.world.checkSession(); - } catch (final ExceptionWorldConflict ex) { - LOGGER.fatal("Couldn't save chunk; already in use by another instance of Minecraft?", ex); - // we don't need to set the write counter to -1 as we know at this stage there's no point in re-scheduling - // writes since they'll fail anyways. - write.wrote.complete(PaperFileIOThread.FAILURE_VALUE); // Hack - However we need to fail the write - return; - } - - for (;;) { - final long writeCounter; - final NBTTagCompound data; - - //noinspection SynchronizationOnLocalVariableOrMethodParameter - synchronized (write) { - writeCounter = write.writeCounter; - data = write.data; - } - - boolean failedWrite = false; - - try { - this.taskController.writeData(this.x, this.z, data); - } catch (final Throwable thr) { - if (thr instanceof ThreadDeath) { - throw (ThreadDeath)thr; - } - LOGGER.fatal("Failed to write chunk data for task: " + this.toString(), thr); - failedWrite = true; - } - - boolean finalFailWrite = failedWrite; - - ChunkDataTask inMap = this.taskController.tasks.compute(chunkKey, (final Long keyInMap, final ChunkDataTask valueInMap) -> { - if (valueInMap == null) { - ChunkDataTask.this.inProgressWrite.wrote.complete(PaperFileIOThread.FAILURE_VALUE); // Hack - throw new IllegalStateException("Write completed concurrently, expected this task: " + ChunkDataTask.this.toString() + ", report this!"); - } - if (valueInMap != ChunkDataTask.this) { - ChunkDataTask.this.inProgressWrite.wrote.complete(PaperFileIOThread.FAILURE_VALUE); // Hack - throw new IllegalStateException("Chunk task mismatch, expected this task: " + ChunkDataTask.this.toString() + ", got: " + valueInMap.toString() + ", report this!"); - } - if (valueInMap.inProgressWrite.writeCounter == writeCounter) { - if (finalFailWrite) { - valueInMap.inProgressWrite.writeCounter = -1L; - valueInMap.inProgressWrite.wrote.complete(PaperFileIOThread.FAILURE_VALUE); - } else { - valueInMap.inProgressWrite.wrote.complete(data); - } - - return null; - } - return valueInMap; - // Hack end - }); - - if (inMap == null) { - // write counter matched, so we wrote the most up-to-date pending data, we're done here - // or we failed to write and successfully set the write counter to -1 - return; // we're done here - } - - // fetch & write new data - continue; - } - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/io/PrioritizedTaskQueue.java b/src/main/java/com/destroystokyo/paper/io/PrioritizedTaskQueue.java deleted file mode 100644 index 78bd238f4..000000000 --- a/src/main/java/com/destroystokyo/paper/io/PrioritizedTaskQueue.java +++ /dev/null @@ -1,276 +0,0 @@ -package com.destroystokyo.paper.io; - -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -public class PrioritizedTaskQueue { - - // lower numbers are a higher priority (except < 0) - // higher priorities are always executed before lower priorities - - /** - * Priority value indicating the task has completed or is being completed. - */ - public static final int COMPLETING_PRIORITY = -1; - - /** - * Highest priority, should only be used for main thread tasks or tasks that are blocking the main thread. - */ - public static final int HIGHEST_PRIORITY = 0; - - /** - * Should be only used in an IO task so that chunk loads do not wait on other IO tasks. - * This only exists because IO tasks are scheduled before chunk load tasks to decrease IO waiting times. - */ - public static final int HIGHER_PRIORITY = 1; - - /** - * Should be used for scheduling chunk loads/generation that would increase response times to users. - */ - public static final int HIGH_PRIORITY = 2; - - /** - * Default priority. - */ - public static final int NORMAL_PRIORITY = 3; - - /** - * Use for tasks not at all critical and can potentially be delayed. - */ - public static final int LOW_PRIORITY = 4; - - /** - * Use for tasks that should "eventually" execute. - */ - public static final int LOWEST_PRIORITY = 5; - - private static final int TOTAL_PRIORITIES = 6; - - final ConcurrentLinkedQueue[] queues = (ConcurrentLinkedQueue[])new ConcurrentLinkedQueue[TOTAL_PRIORITIES]; - - private final AtomicBoolean shutdown = new AtomicBoolean(); - - { - for (int i = 0; i < TOTAL_PRIORITIES; ++i) { - this.queues[i] = new ConcurrentLinkedQueue<>(); - } - } - - /** - * Returns whether the specified priority is valid - */ - public static boolean validPriority(final int priority) { - return priority >= 0 && priority < TOTAL_PRIORITIES; - } - - /** - * Queues a task. - * @throws IllegalStateException If the task has already been queued. Use {@link PrioritizedTask#raisePriority(int)} to - * raise a task's priority. - * This can also be thrown if the queue has shutdown. - */ - public void add(final T task) throws IllegalStateException { - task.onQueue(this); - this.queues[task.getPriority()].add(task); - if (this.shutdown.get()) { - // note: we're not actually sure at this point if our task will go through - throw new IllegalStateException("Queue has shutdown, refusing to execute task " + IOUtil.genericToString(task)); - } - } - - /** - * Polls the highest priority task currently available. {@code null} if none. - */ - public T poll() { - T task; - for (int i = 0; i < TOTAL_PRIORITIES; ++i) { - final ConcurrentLinkedQueue queue = this.queues[i]; - - while ((task = queue.poll()) != null) { - final int prevPriority = task.tryComplete(i); - if (prevPriority != COMPLETING_PRIORITY && prevPriority <= i) { - // if the prev priority was greater-than or equal to our current priority - return task; - } - } - } - - return null; - } - - /** - * Returns whether this queue may have tasks queued. - *

    - * This operation is not atomic, but is MT-Safe. - *

    - * @return {@code true} if tasks may be queued, {@code false} otherwise - */ - public boolean hasTasks() { - for (int i = 0; i < TOTAL_PRIORITIES; ++i) { - final ConcurrentLinkedQueue queue = this.queues[i]; - - if (queue.peek() != null) { - return true; - } - } - return false; - } - - /** - * Prevent further additions to this queue. Attempts to add after this call has completed (potentially during) will - * result in {@link IllegalStateException} being thrown. - *

    - * This operation is atomic with respect to other shutdown calls - *

    - *

    - * After this call has completed, regardless of return value, this queue will be shutdown. - *

    - * @return {@code true} if the queue was shutdown, {@code false} if it has shut down already - */ - public boolean shutdown() { - return this.shutdown.getAndSet(false); - } - - public abstract static class PrioritizedTask { - - protected final AtomicReference queue = new AtomicReference<>(); - - protected final AtomicInteger priority; - - protected PrioritizedTask() { - this(PrioritizedTaskQueue.NORMAL_PRIORITY); - } - - protected PrioritizedTask(final int priority) { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalArgumentException("Invalid priority " + priority); - } - this.priority = new AtomicInteger(priority); - } - - /** - * Returns the current priority. Note that {@link PrioritizedTaskQueue#COMPLETING_PRIORITY} will be returned - * if this task is completing or has completed. - */ - public final int getPriority() { - return this.priority.get(); - } - - /** - * Returns whether this task is scheduled to execute, or has been already executed. - */ - public boolean isScheduled() { - return this.queue.get() != null; - } - - final int tryComplete(final int minPriority) { - for (int curr = this.getPriorityVolatile();;) { - if (curr == COMPLETING_PRIORITY) { - return COMPLETING_PRIORITY; - } - if (curr > minPriority) { - // curr is lower priority - return curr; - } - - if (curr == (curr = this.compareAndExchangePriorityVolatile(curr, COMPLETING_PRIORITY))) { - return curr; - } - continue; - } - } - - /** - * Forces this task to be completed. - * @return {@code true} if the task was cancelled, {@code false} if the task has already completed or is being completed. - */ - public boolean cancel() { - return this.exchangePriorityVolatile(PrioritizedTaskQueue.COMPLETING_PRIORITY) != PrioritizedTaskQueue.COMPLETING_PRIORITY; - } - - /** - * Attempts to raise the priority to the priority level specified. - * @param priority Priority specified - * @return {@code true} if successful, {@code false} otherwise. - */ - public boolean raisePriority(final int priority) { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalArgumentException("Invalid priority"); - } - - for (int curr = this.getPriorityVolatile();;) { - if (curr == COMPLETING_PRIORITY) { - return false; - } - if (priority >= curr) { - return true; - } - - if (curr == (curr = this.compareAndExchangePriorityVolatile(curr, priority))) { - PrioritizedTaskQueue queue = this.queue.get(); - if (queue != null) { - //noinspection unchecked - queue.queues[priority].add(this); // silently fail on shutdown - } - return true; - } - continue; - } - } - - /** - * Attempts to set this task's priority level to the level specified. - * @param priority Specified priority level. - * @return {@code true} if successful, {@code false} if this task is completing or has completed. - */ - public boolean updatePriority(final int priority) { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalArgumentException("Invalid priority"); - } - - for (int curr = this.getPriorityVolatile();;) { - if (curr == COMPLETING_PRIORITY) { - return false; - } - if (curr == priority) { - return true; - } - - if (curr == (curr = this.compareAndExchangePriorityVolatile(curr, priority))) { - PrioritizedTaskQueue queue = this.queue.get(); - if (queue != null) { - //noinspection unchecked - queue.queues[priority].add(this); // silently fail on shutdown - } - return true; - } - continue; - } - } - - void onQueue(final PrioritizedTaskQueue queue) { - if (this.queue.getAndSet(queue) != null) { - throw new IllegalStateException("Already queued!"); - } - } - - /* priority */ - - protected final int getPriorityVolatile() { - return this.priority.get(); - } - - protected final int compareAndExchangePriorityVolatile(final int expect, final int update) { - if (this.priority.compareAndSet(expect, update)) { - return expect; - } - return this.priority.get(); - } - - protected final int exchangePriorityVolatile(final int value) { - return this.priority.getAndSet(value); - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/io/QueueExecutorThread.java b/src/main/java/com/destroystokyo/paper/io/QueueExecutorThread.java deleted file mode 100644 index ee906b594..000000000 --- a/src/main/java/com/destroystokyo/paper/io/QueueExecutorThread.java +++ /dev/null @@ -1,241 +0,0 @@ -package com.destroystokyo.paper.io; - -import net.minecraft.server.MinecraftServer; -import org.apache.logging.log4j.Logger; - -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.locks.LockSupport; - -public class QueueExecutorThread extends Thread { - - private static final Logger LOGGER = MinecraftServer.LOGGER; - - protected final PrioritizedTaskQueue queue; - protected final long spinWaitTime; - - protected volatile boolean closed; - - protected final AtomicBoolean parked = new AtomicBoolean(); - - protected volatile ConcurrentLinkedQueue flushQueue = new ConcurrentLinkedQueue<>(); - protected volatile long flushCycles; - - public QueueExecutorThread(final PrioritizedTaskQueue queue) { - this(queue, (int)(1.e6)); // 1.0ms - } - - public QueueExecutorThread(final PrioritizedTaskQueue queue, final long spinWaitTime) { // in ms - this.queue = queue; - this.spinWaitTime = spinWaitTime; - } - - @Override - public void run() { - final long spinWaitTime = this.spinWaitTime; - main_loop: - for (;;) { - this.pollTasks(true); - - // spinwait - - final long start = System.nanoTime(); - - for (;;) { - // If we are interrpted for any reason, park() will always return immediately. Clear so that we don't needlessly use cpu in such an event. - Thread.interrupted(); - LockSupport.parkNanos("Spinwaiting on tasks", 1000L); // 1us - - if (this.pollTasks(true)) { - // restart loop, found tasks - continue main_loop; - } - - if (this.handleClose()) { - return; // we're done - } - - if ((System.nanoTime() - start) >= spinWaitTime) { - break; - } - } - - if (this.handleClose()) { - return; - } - - this.parked.set(true); - - // We need to parse here to avoid a race condition where a thread queues a task before we set parked to true - // (i.e it will not notify us) - if (this.pollTasks(true)) { - this.parked.set(false); - continue; - } - - if (this.handleClose()) { - return; - } - - // we don't need to check parked before sleeping, but we do need to check parked in a do-while loop - // LockSupport.park() can fail for any reason - do { - Thread.interrupted(); - LockSupport.park("Waiting on tasks"); - } while (this.parked.get()); - } - } - - protected boolean handleClose() { - if (this.closed) { - this.pollTasks(true); // this ensures we've emptied the queue - this.handleFlushThreads(true); - return true; - } - return false; - } - - protected boolean pollTasks(boolean flushTasks) { - Runnable task; - boolean ret = false; - - while ((task = this.queue.poll()) != null) { - ret = true; - try { - task.run(); - } catch (final Throwable throwable) { - if (throwable instanceof ThreadDeath) { - throw (ThreadDeath)throwable; - } - LOGGER.fatal("Exception thrown from prioritized runnable task in thread '" + this.getName() + "': " + IOUtil.genericToString(task), throwable); - } - } - - if (flushTasks) { - this.handleFlushThreads(false); - } - - return ret; - } - - protected void handleFlushThreads(final boolean shutdown) { - Thread parking; - ConcurrentLinkedQueue flushQueue = this.flushQueue; - do { - ++flushCycles; // may be plain read opaque write - while ((parking = flushQueue.poll()) != null) { - LockSupport.unpark(parking); - } - } while (this.pollTasks(false)); - - if (shutdown) { - this.flushQueue = null; - - // defend against a race condition where a flush thread double-checks right before we set to null - while ((parking = flushQueue.poll()) != null) { - LockSupport.unpark(parking); - } - } - } - - /** - * Notify's this thread that a task has been added to its queue - * @return {@code true} if this thread was waiting for tasks, {@code false} if it is executing tasks - */ - public boolean notifyTasks() { - if (this.parked.get() && this.parked.getAndSet(false)) { - LockSupport.unpark(this); - return true; - } - return false; - } - - protected void queueTask(final T task) { - this.queue.add(task); - this.notifyTasks(); - } - - /** - * Waits until this thread's queue is empty. - * - * @throws IllegalStateException If the current thread is {@code this} thread. - */ - public void flush() { - final Thread currentThread = Thread.currentThread(); - - if (currentThread == this) { - // avoid deadlock - throw new IllegalStateException("Cannot flush the queue executor thread while on the queue executor thread"); - } - - // order is important - - int successes = 0; - long lastCycle = -1L; - - do { - final ConcurrentLinkedQueue flushQueue = this.flushQueue; - if (flushQueue == null) { - return; - } - - flushQueue.add(currentThread); - - // double check flush queue - if (this.flushQueue == null) { - return; - } - - final long currentCycle = this.flushCycles; // may be opaque read - - if (currentCycle == lastCycle) { - Thread.yield(); - continue; - } - - // force response - this.parked.set(false); - LockSupport.unpark(this); - - LockSupport.park("flushing queue executor thread"); - - // returns whether there are tasks queued, does not return whether there are tasks executing - // this is why we cycle twice twice through flush (we know a pollTask call is made after a flush cycle) - // we really only need to guarantee that the tasks this thread has queued has gone through, and can leave - // tasks queued concurrently that are unsychronized with this thread as undefined behavior - if (this.queue.hasTasks()) { - successes = 0; - } else { - ++successes; - } - - } while (successes != 2); - - } - - /** - * Closes this queue executor's queue and optionally waits for it to empty. - *

    - * If wait is {@code true}, then the queue will be empty by the time this call completes. - *

    - *

    - * This function is MT-Safe. - *

    - * @param wait If this call is to wait until the queue is empty - * @param killQueue Whether to shutdown this thread's queue - * @return whether this thread shut down the queue - */ - public boolean close(final boolean wait, final boolean killQueue) { - boolean ret = !killQueue ? false : this.queue.shutdown(); - this.closed = true; - - // force thread to respond to the shutdown - this.parked.set(false); - LockSupport.unpark(this); - - if (wait) { - this.flush(); - } - return ret; - } -} diff --git a/src/main/java/com/destroystokyo/paper/io/SyncLoadFinder.java b/src/main/java/com/destroystokyo/paper/io/SyncLoadFinder.java deleted file mode 100644 index 59aec1032..000000000 --- a/src/main/java/com/destroystokyo/paper/io/SyncLoadFinder.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.destroystokyo.paper.io; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.mojang.datafixers.util.Pair; -import it.unimi.dsi.fastutil.longs.Long2IntMap; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import net.minecraft.server.World; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; - -public class SyncLoadFinder { - - public static final boolean ENABLED = Boolean.getBoolean("paper.debug-sync-loads"); - - private static final WeakHashMap> SYNC_LOADS = new WeakHashMap<>(); - - private static final class SyncLoadInformation { - - public int times; - - public final Long2IntOpenHashMap coordinateTimes = new Long2IntOpenHashMap(); - } - - public static void logSyncLoad(final World world, final int chunkX, final int chunkZ) { - if (!ENABLED) { - return; - } - - final ThrowableWithEquals stacktrace = new ThrowableWithEquals(Thread.currentThread().getStackTrace()); - - SYNC_LOADS.compute(world, (final World keyInMap, Object2ObjectOpenHashMap map) -> { - if (map == null) { - map = new Object2ObjectOpenHashMap<>(); - } - - map.compute(stacktrace, (ThrowableWithEquals keyInMap0, SyncLoadInformation valueInMap) -> { - if (valueInMap == null) { - valueInMap = new SyncLoadInformation(); - } - - ++valueInMap.times; - - valueInMap.coordinateTimes.compute(IOUtil.getCoordinateKey(chunkX, chunkZ), (Long keyInMap1, Integer valueInMap1) -> { - return valueInMap1 == null ? Integer.valueOf(1) : Integer.valueOf(valueInMap1.intValue() + 1); - }); - - return valueInMap; - }); - - return map; - }); - } - - public static JsonObject serialize() { - final JsonObject ret = new JsonObject(); - - final JsonArray worldsData = new JsonArray(); - - for (final Map.Entry> entry : SYNC_LOADS.entrySet()) { - final World world = entry.getKey(); - - final JsonObject worldData = new JsonObject(); - - worldData.addProperty("name", world.getWorld().getName()); - - final List> data = new ArrayList<>(); - - entry.getValue().forEach((ThrowableWithEquals stacktrace, SyncLoadInformation times) -> { - data.add(new Pair<>(stacktrace, times)); - }); - - data.sort((Pair pair1, Pair pair2) -> { - return Integer.compare(pair2.getSecond().times, pair1.getSecond().times); // reverse order - }); - - final JsonArray stacktraces = new JsonArray(); - - for (Pair pair : data) { - final JsonObject stacktrace = new JsonObject(); - - stacktrace.addProperty("times", pair.getSecond().times); - - final JsonArray traces = new JsonArray(); - - for (StackTraceElement element : pair.getFirst().stacktrace) { - traces.add(String.valueOf(element)); - } - - stacktrace.add("stacktrace", traces); - - final JsonArray coordinates = new JsonArray(); - - for (Long2IntMap.Entry coordinate : pair.getSecond().coordinateTimes.long2IntEntrySet()) { - final long key = coordinate.getLongKey(); - final int times = coordinate.getIntValue(); - coordinates.add("(" + IOUtil.getCoordinateX(key) + "," + IOUtil.getCoordinateZ(key) + "): " + times); - } - - stacktrace.add("coordinates", coordinates); - - stacktraces.add(stacktrace); - } - - - worldData.add("stacktraces", stacktraces); - worldsData.add(worldData); - } - - ret.add("worlds", worldsData); - - return ret; - } - - static final class ThrowableWithEquals { - - private final StackTraceElement[] stacktrace; - private final int hash; - - public ThrowableWithEquals(final StackTraceElement[] stacktrace) { - this.stacktrace = stacktrace; - this.hash = ThrowableWithEquals.hash(stacktrace); - } - - public static int hash(final StackTraceElement[] stacktrace) { - int hash = 0; - - for (int i = 0; i < stacktrace.length; ++i) { - hash *= 31; - hash += stacktrace[i].hashCode(); - } - - return hash; - } - - @Override - public int hashCode() { - return this.hash; - } - - @Override - public boolean equals(final Object obj) { - if (obj == null || obj.getClass() != this.getClass()) { - return false; - } - - final ThrowableWithEquals other = (ThrowableWithEquals)obj; - final StackTraceElement[] otherStackTrace = other.stacktrace; - - if (this.stacktrace.length != otherStackTrace.length) { - return false; - } - - if (this == obj) { - return true; - } - - for (int i = 0; i < this.stacktrace.length; ++i) { - if (!this.stacktrace[i].equals(otherStackTrace[i])) { - return false; - } - } - - return true; - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/io/chunk/ChunkLoadTask.java b/src/main/java/com/destroystokyo/paper/io/chunk/ChunkLoadTask.java deleted file mode 100644 index 305da4786..000000000 --- a/src/main/java/com/destroystokyo/paper/io/chunk/ChunkLoadTask.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.destroystokyo.paper.io.chunk; - -import co.aikar.timings.Timing; -import com.destroystokyo.paper.io.PaperFileIOThread; -import com.destroystokyo.paper.io.IOUtil; -import net.minecraft.server.ChunkCoordIntPair; -import net.minecraft.server.ChunkRegionLoader; -import net.minecraft.server.PlayerChunkMap; -import net.minecraft.server.WorldServer; - -import java.util.ArrayDeque; -import java.util.function.Consumer; - -public final class ChunkLoadTask extends ChunkTask { - - public boolean cancelled; - - Consumer onComplete; - public PaperFileIOThread.ChunkData chunkData; - - private boolean hasCompleted; - - public ChunkLoadTask(final WorldServer world, final int chunkX, final int chunkZ, final int priority, - final ChunkTaskManager taskManager, - final Consumer onComplete) { - super(world, chunkX, chunkZ, priority, taskManager); - this.onComplete = onComplete; - } - - private static final ArrayDeque EMPTY_QUEUE = new ArrayDeque<>(); - - private static ChunkRegionLoader.InProgressChunkHolder createEmptyHolder() { - return new ChunkRegionLoader.InProgressChunkHolder(null, EMPTY_QUEUE); - } - - @Override - public void run() { - try { - this.executeTask(); - } catch (final Throwable ex) { - PaperFileIOThread.LOGGER.error("Failed to execute chunk load task: " + this.toString(), ex); - if (!this.hasCompleted) { - this.complete(ChunkLoadTask.createEmptyHolder()); - } - } - } - - private boolean checkCancelled() { - if (this.cancelled) { - // IntelliJ does not understand writes may occur to cancelled concurrently. - return this.taskManager.chunkLoadTasks.compute(Long.valueOf(IOUtil.getCoordinateKey(this.chunkX, this.chunkZ)), (final Long keyInMap, final ChunkLoadTask valueInMap) -> { - if (valueInMap != ChunkLoadTask.this) { - throw new IllegalStateException("Expected this task to be scheduled, but another was! Other: " + valueInMap + ", current: " + ChunkLoadTask.this); - } - - if (valueInMap.cancelled) { - return null; - } - return valueInMap; - }) == null; - } - return false; - } - - public void executeTask() { - if (this.checkCancelled()) { - return; - } - - // either executed synchronously or asynchronously - final PaperFileIOThread.ChunkData chunkData = this.chunkData; - - if (chunkData.poiData == PaperFileIOThread.FAILURE_VALUE || chunkData.chunkData == PaperFileIOThread.FAILURE_VALUE) { - PaperFileIOThread.LOGGER.error("Could not load chunk for task: " + this.toString() + ", file IO thread has dumped the relevant exception above"); - this.complete(ChunkLoadTask.createEmptyHolder()); - return; - } - - if (chunkData.chunkData == null) { - // not on disk - this.complete(ChunkLoadTask.createEmptyHolder()); - return; - } - - final ChunkCoordIntPair chunkPos = new ChunkCoordIntPair(this.chunkX, this.chunkZ); - - final PlayerChunkMap chunkManager = this.world.getChunkProvider().playerChunkMap; - - try (Timing ignored = this.world.timings.chunkIOStage1.startTimingIfSync()) { - final ChunkRegionLoader.InProgressChunkHolder chunkHolder; - - // apply fixes - - try { - if (chunkData.poiData != null) { - chunkData.poiData = chunkData.poiData.clone(); // clone data for safety, file IO thread does not clone - } - chunkData.chunkData = chunkManager.getChunkData(this.world.getWorldProvider().getDimensionManager(), - chunkManager.getWorldPersistentDataSupplier(), chunkData.chunkData.clone(), chunkPos, this.world); // clone data for safety, file IO thread does not clone - } catch (final Throwable ex) { - PaperFileIOThread.LOGGER.error("Could not apply datafixers for chunk task: " + this.toString(), ex); - this.complete(ChunkLoadTask.createEmptyHolder()); - } - - if (this.checkCancelled()) { - return; - } - - try { - this.world.getChunkProvider().playerChunkMap.updateChunkStatusOnDisk(chunkPos, chunkData.chunkData); - } catch (final Throwable ex) { - PaperFileIOThread.LOGGER.warn("Failed to update chunk status cache for task: " + this.toString(), ex); - // non-fatal, continue - } - - try { - chunkHolder = ChunkRegionLoader.loadChunk(this.world, - chunkManager.definedStructureManager, chunkManager.getVillagePlace(), chunkPos, - chunkData.chunkData, true); - } catch (final Throwable ex) { - PaperFileIOThread.LOGGER.error("Could not de-serialize chunk data for task: " + this.toString(), ex); - this.complete(ChunkLoadTask.createEmptyHolder()); - return; - } - - this.complete(chunkHolder); - } - } - - private void complete(final ChunkRegionLoader.InProgressChunkHolder holder) { - this.hasCompleted = true; - holder.poiData = this.chunkData == null ? null : this.chunkData.poiData; - - this.taskManager.chunkLoadTasks.compute(Long.valueOf(IOUtil.getCoordinateKey(this.chunkX, this.chunkZ)), (final Long keyInMap, final ChunkLoadTask valueInMap) -> { - if (valueInMap != ChunkLoadTask.this) { - throw new IllegalStateException("Expected this task to be scheduled, but another was! Other: " + valueInMap + ", current: " + ChunkLoadTask.this); - } - if (valueInMap.cancelled) { - return null; - } - try { - ChunkLoadTask.this.onComplete.accept(holder); - } catch (final Throwable thr) { - PaperFileIOThread.LOGGER.error("Failed to complete chunk data for task: " + this.toString(), thr); - } - return null; - }); - } -} diff --git a/src/main/java/com/destroystokyo/paper/io/chunk/ChunkSaveTask.java b/src/main/java/com/destroystokyo/paper/io/chunk/ChunkSaveTask.java deleted file mode 100644 index 60312b85f..000000000 --- a/src/main/java/com/destroystokyo/paper/io/chunk/ChunkSaveTask.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.destroystokyo.paper.io.chunk; - -import co.aikar.timings.Timing; -import com.destroystokyo.paper.io.PaperFileIOThread; -import com.destroystokyo.paper.io.IOUtil; -import com.destroystokyo.paper.io.PrioritizedTaskQueue; -import net.minecraft.server.ChunkRegionLoader; -import net.minecraft.server.IAsyncTaskHandler; -import net.minecraft.server.IChunkAccess; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.WorldServer; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicInteger; - -public final class ChunkSaveTask extends ChunkTask { - - public final ChunkRegionLoader.AsyncSaveData asyncSaveData; - public final IChunkAccess chunk; - public final CompletableFuture onComplete = new CompletableFuture<>(); - - private final AtomicInteger attemptedPriority; - - public ChunkSaveTask(final WorldServer world, final int chunkX, final int chunkZ, final int priority, - final ChunkTaskManager taskManager, final ChunkRegionLoader.AsyncSaveData asyncSaveData, - final IChunkAccess chunk) { - super(world, chunkX, chunkZ, priority, taskManager); - this.chunk = chunk; - this.asyncSaveData = asyncSaveData; - this.attemptedPriority = new AtomicInteger(priority); - } - - @Override - public void run() { - // can be executed asynchronously or synchronously - final NBTTagCompound compound; - - try (Timing ignored = this.world.timings.chunkUnloadDataSave.startTimingIfSync()) { - compound = ChunkRegionLoader.saveChunk(this.world, this.chunk, this.asyncSaveData); - } catch (final Throwable ex) { - // has a plugin modified something it should not have and made us CME? - PaperFileIOThread.LOGGER.error("Failed to serialize unloading chunk data for task: " + this.toString() + ", falling back to a synchronous execution", ex); - - // Note: We add to the server thread queue here since this is what the server will drain tasks from - // when waiting for chunks - ChunkTaskManager.queueChunkWaitTask(() -> { - try (Timing ignored = this.world.timings.chunkUnloadDataSave.startTiming()) { - NBTTagCompound data = PaperFileIOThread.FAILURE_VALUE; - - try { - data = ChunkRegionLoader.saveChunk(this.world, this.chunk, this.asyncSaveData); - PaperFileIOThread.LOGGER.info("Successfully serialized chunk data for task: " + this.toString() + " synchronously"); - } catch (final Throwable ex1) { - PaperFileIOThread.LOGGER.fatal("Failed to synchronously serialize unloading chunk data for task: " + this.toString() + "! Chunk data will be lost", ex1); - } - - ChunkSaveTask.this.complete(data); - } - }); - - return; // the main thread will now complete the data - } - - this.complete(compound); - } - - @Override - public boolean raisePriority(final int priority) { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalStateException("Invalid priority: " + priority); - } - - // we know priority is valid here - for (int curr = this.attemptedPriority.get();;) { - if (curr <= priority) { - break; // curr is higher/same priority - } - if (this.attemptedPriority.compareAndSet(curr, priority)) { - break; - } - curr = this.attemptedPriority.get(); - } - - return super.raisePriority(priority); - } - - @Override - public boolean updatePriority(final int priority) { - if (!PrioritizedTaskQueue.validPriority(priority)) { - throw new IllegalStateException("Invalid priority: " + priority); - } - this.attemptedPriority.set(priority); - return super.updatePriority(priority); - } - - private void complete(final NBTTagCompound compound) { - try { - this.onComplete.complete(compound); - } catch (final Throwable thr) { - PaperFileIOThread.LOGGER.error("Failed to complete chunk data for task: " + this.toString(), thr); - } - if (compound != PaperFileIOThread.FAILURE_VALUE) { - PaperFileIOThread.Holder.INSTANCE.scheduleSave(this.world, this.chunkX, this.chunkZ, null, compound, this.attemptedPriority.get()); - } - this.taskManager.chunkSaveTasks.compute(Long.valueOf(IOUtil.getCoordinateKey(this.chunkX, this.chunkZ)), (final Long keyInMap, final ChunkSaveTask valueInMap) -> { - if (valueInMap != ChunkSaveTask.this) { - throw new IllegalStateException("Expected this task to be scheduled, but another was! Other: " + valueInMap + ", this: " + ChunkSaveTask.this); - } - return null; - }); - } -} diff --git a/src/main/java/com/destroystokyo/paper/io/chunk/ChunkTask.java b/src/main/java/com/destroystokyo/paper/io/chunk/ChunkTask.java deleted file mode 100644 index 1dfa8abfd..000000000 --- a/src/main/java/com/destroystokyo/paper/io/chunk/ChunkTask.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.destroystokyo.paper.io.chunk; - -import com.destroystokyo.paper.io.PaperFileIOThread; -import com.destroystokyo.paper.io.PrioritizedTaskQueue; -import net.minecraft.server.WorldServer; - -abstract class ChunkTask extends PrioritizedTaskQueue.PrioritizedTask implements Runnable { - - public final WorldServer world; - public final int chunkX; - public final int chunkZ; - public final ChunkTaskManager taskManager; - - public ChunkTask(final WorldServer world, final int chunkX, final int chunkZ, final int priority, - final ChunkTaskManager taskManager) { - super(priority); - this.world = world; - this.chunkX = chunkX; - this.chunkZ = chunkZ; - this.taskManager = taskManager; - } - - @Override - public String toString() { - return "Chunk task: class:" + this.getClass().getName() + ", for world '" + this.world.getWorld().getName() + - "', (" + this.chunkX + "," + this.chunkZ + "), hashcode:" + this.hashCode() + ", priority: " + this.getPriority(); - } - - @Override - public boolean raisePriority(final int priority) { - PaperFileIOThread.Holder.INSTANCE.bumpPriority(this.world, this.chunkX, this.chunkZ, priority); - return super.raisePriority(priority); - } - - @Override - public boolean updatePriority(final int priority) { - PaperFileIOThread.Holder.INSTANCE.setPriority(this.world, this.chunkX, this.chunkZ, priority); - return super.updatePriority(priority); - } -} diff --git a/src/main/java/com/destroystokyo/paper/io/chunk/ChunkTaskManager.java b/src/main/java/com/destroystokyo/paper/io/chunk/ChunkTaskManager.java deleted file mode 100644 index 59d73bfad..000000000 --- a/src/main/java/com/destroystokyo/paper/io/chunk/ChunkTaskManager.java +++ /dev/null @@ -1,453 +0,0 @@ -package com.destroystokyo.paper.io.chunk; - -import com.destroystokyo.paper.io.PaperFileIOThread; -import com.destroystokyo.paper.io.IOUtil; -import com.destroystokyo.paper.io.PrioritizedTaskQueue; -import com.destroystokyo.paper.io.QueueExecutorThread; -import net.minecraft.server.ChunkRegionLoader; -import net.minecraft.server.IAsyncTaskHandler; -import net.minecraft.server.IChunkAccess; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.WorldServer; -import org.apache.logging.log4j.Level; -import org.bukkit.Bukkit; -import org.spigotmc.AsyncCatcher; - -import java.util.ArrayDeque; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.function.Consumer; - -public final class ChunkTaskManager { - - private final QueueExecutorThread[] workers; - private final WorldServer world; - - private final PrioritizedTaskQueue queue; - private final boolean perWorldQueue; - - final ConcurrentHashMap chunkLoadTasks = new ConcurrentHashMap<>(64, 0.5f); - final ConcurrentHashMap chunkSaveTasks = new ConcurrentHashMap<>(64, 0.5f); - - private final PrioritizedTaskQueue chunkTasks = new PrioritizedTaskQueue<>(); // used if async chunks are disabled in config - - protected static QueueExecutorThread[] globalWorkers; - protected static PrioritizedTaskQueue globalQueue; - - protected static final ConcurrentLinkedQueue CHUNK_WAIT_QUEUE = new ConcurrentLinkedQueue<>(); - - public static final ArrayDeque WAITING_CHUNKS = new ArrayDeque<>(); // stack - - private static final class ChunkInfo { - - public final int chunkX; - public final int chunkZ; - public final WorldServer world; - - public ChunkInfo(final int chunkX, final int chunkZ, final WorldServer world) { - this.chunkX = chunkX; - this.chunkZ = chunkZ; - this.world = world; - } - - @Override - public String toString() { - return "[( " + this.chunkX + "," + this.chunkZ + ") in '" + this.world.getWorld().getName() + "']"; - } - } - - public static void pushChunkWait(final WorldServer world, final int chunkX, final int chunkZ) { - synchronized (WAITING_CHUNKS) { - WAITING_CHUNKS.push(new ChunkInfo(chunkX, chunkZ, world)); - } - } - - public static void popChunkWait() { - synchronized (WAITING_CHUNKS) { - WAITING_CHUNKS.pop(); - } - } - - public static String getChunkWaitInfo() { - synchronized (WAITING_CHUNKS) { - return WAITING_CHUNKS.toString(); - } - } - - public static void dumpAllChunkLoadInfo() { - synchronized (WAITING_CHUNKS) { - if (WAITING_CHUNKS.isEmpty()) { - return; - } - - PaperFileIOThread.LOGGER.log(Level.ERROR, "Chunk wait task info below: "); - - for (final ChunkInfo chunkInfo : WAITING_CHUNKS) { - final long key = IOUtil.getCoordinateKey(chunkInfo.chunkX, chunkInfo.chunkZ); - final ChunkLoadTask loadTask = chunkInfo.world.asyncChunkTaskManager.chunkLoadTasks.get(key); - final ChunkSaveTask saveTask = chunkInfo.world.asyncChunkTaskManager.chunkSaveTasks.get(key); - - PaperFileIOThread.LOGGER.log(Level.ERROR, chunkInfo.chunkX + "," + chunkInfo.chunkZ + " in '" + chunkInfo.world.getWorld().getName() + ":"); - PaperFileIOThread.LOGGER.log(Level.ERROR, "Load Task - " + (loadTask == null ? "none" : loadTask.toString())); - PaperFileIOThread.LOGGER.log(Level.ERROR, "Save Task - " + (saveTask == null ? "none" : saveTask.toString())); - // log current status of chunk to indicate whether we're waiting on generation or loading - net.minecraft.server.PlayerChunk chunkHolder = chunkInfo.world.getChunkProvider().playerChunkMap.getVisibleChunk(key); - - if (chunkHolder == null) { - PaperFileIOThread.LOGGER.log(Level.ERROR, "Chunk Holder - null"); - } else { - IChunkAccess chunk = chunkHolder.getAvailableChunkNow(); - PaperFileIOThread.LOGGER.log(Level.ERROR, "Chunk Holder - non-null"); - PaperFileIOThread.LOGGER.log(Level.ERROR, "Chunk Status - " + ((chunk == null) ? "null chunk" : chunk.getChunkStatus().toString())); - } - - } - } - } - - public static void initGlobalLoadThreads(int threads) { - if (threads <= 0 || globalWorkers != null) { - return; - } - - globalWorkers = new QueueExecutorThread[threads]; - globalQueue = new PrioritizedTaskQueue<>(); - - for (int i = 0; i < threads; ++i) { - globalWorkers[i] = new QueueExecutorThread<>(globalQueue, (long)0.10e6); //0.1ms - globalWorkers[i].setName("Paper Async Chunk Task Thread #" + i); - globalWorkers[i].setPriority(Thread.NORM_PRIORITY - 1); - globalWorkers[i].setUncaughtExceptionHandler((final Thread thread, final Throwable throwable) -> { - PaperFileIOThread.LOGGER.fatal("Thread '" + thread.getName() + "' threw an uncaught exception!", throwable); - }); - - globalWorkers[i].start(); - } - } - - /** - * Creates this chunk task manager to operate off the specified number of threads. If the specified number of threads is - * less-than or equal to 0, then this chunk task manager will operate off of the world's chunk task queue. - * @param world Specified world. - * @param threads Specified number of threads. - * @see net.minecraft.server.ChunkProviderServer#serverThreadQueue - */ - public ChunkTaskManager(final WorldServer world, final int threads) { - this.world = world; - this.workers = threads <= 0 ? null : new QueueExecutorThread[threads]; - this.queue = new PrioritizedTaskQueue<>(); - this.perWorldQueue = true; - - for (int i = 0; i < threads; ++i) { - this.workers[i] = new QueueExecutorThread<>(this.queue, (long)0.10e6); //0.1ms - this.workers[i].setName("Async chunk loader thread #" + i + " for world: " + world.getWorldData().getName()); - this.workers[i].setPriority(Thread.NORM_PRIORITY - 1); - this.workers[i].setUncaughtExceptionHandler((final Thread thread, final Throwable throwable) -> { - PaperFileIOThread.LOGGER.fatal("Thread '" + thread.getName() + "' threw an uncaught exception!", throwable); - }); - - this.workers[i].start(); - } - } - - /** - * Creates the chunk task manager to work from the global workers. When {@link #close(boolean)} is invoked, - * the global queue is not shutdown. If the global workers is configured to be disabled or use 0 threads, then - * this chunk task manager will operate off of the world's chunk task queue. - * @param world The world that this task manager is responsible for - * @see net.minecraft.server.ChunkProviderServer#serverThreadQueue - */ - public ChunkTaskManager(final WorldServer world) { - this.world = world; - this.workers = globalWorkers; - this.queue = globalQueue; - this.perWorldQueue = false; - } - - public boolean pollNextChunkTask() { - final ChunkTask task = this.chunkTasks.poll(); - - if (task != null) { - task.run(); - return true; - } - return false; - } - - /** - * Polls and runs the next available chunk wait queue task. This is to be used when the server is waiting on a chunk queue. - * (per-world can cause issues if all the worker threads are blocked waiting for a response from the main thread) - */ - public static boolean pollChunkWaitQueue() { - final Runnable run = CHUNK_WAIT_QUEUE.poll(); - if (run != null) { - run.run(); - return true; - } - return false; - } - - /** - * Queues a chunk wait task. Note that this will execute out of order with respect to tasks scheduled on a world's - * chunk task queue, since this is the global chunk wait queue. - */ - public static void queueChunkWaitTask(final Runnable runnable) { - CHUNK_WAIT_QUEUE.add(runnable); - } - - private static void drainChunkWaitQueue() { - Runnable run; - while ((run = CHUNK_WAIT_QUEUE.poll()) != null) { - run.run(); - } - } - - /** - * The exact same as {@link #scheduleChunkLoad(int, int, int, Consumer, boolean)}, except that the chunk data is provided as - * the {@code data} parameter. - */ - public ChunkLoadTask scheduleChunkLoad(final int chunkX, final int chunkZ, final int priority, - final Consumer onComplete, - final boolean intendingToBlock, final CompletableFuture dataFuture) { - final WorldServer world = this.world; - - return this.chunkLoadTasks.compute(Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ)), (final Long keyInMap, final ChunkLoadTask valueInMap) -> { - if (valueInMap != null) { - if (!valueInMap.cancelled) { - throw new IllegalStateException("Double scheduling chunk load for task: " + valueInMap.toString()); - } - valueInMap.cancelled = false; - valueInMap.onComplete = onComplete; - return valueInMap; - } - - final ChunkLoadTask ret = new ChunkLoadTask(world, chunkX, chunkZ, priority, ChunkTaskManager.this, onComplete); - - dataFuture.thenAccept((final NBTTagCompound data) -> { - final boolean failed = data == PaperFileIOThread.FAILURE_VALUE; - PaperFileIOThread.Holder.INSTANCE.loadChunkDataAsync(world, chunkX, chunkZ, priority, (final PaperFileIOThread.ChunkData chunkData) -> { - ret.chunkData = chunkData; - if (!failed) { - chunkData.chunkData = data; - } - ChunkTaskManager.this.internalSchedule(ret); // only schedule to the worker threads here - }, true, failed, intendingToBlock); // read data off disk if the future fails - }); - - return ret; - }); - } - - public void cancelChunkLoad(final int chunkX, final int chunkZ) { - this.chunkLoadTasks.compute(IOUtil.getCoordinateKey(chunkX, chunkZ), (final Long keyInMap, final ChunkLoadTask valueInMap) -> { - if (valueInMap == null) { - return null; - } - - if (valueInMap.cancelled) { - PaperFileIOThread.LOGGER.warn("Task " + valueInMap.toString() + " is already cancelled!"); - } - valueInMap.cancelled = true; - if (valueInMap.cancel()) { - return null; - } - - return valueInMap; - }); - } - - /** - * Schedules an asynchronous chunk load for the specified coordinates. The onComplete parameter may be invoked asynchronously - * on a worker thread or on the world's chunk executor queue. As such the code that is executed for the parameter should be - * carefully chosen. - * @param chunkX Chunk's x coordinate - * @param chunkZ Chunk's z coordinate - * @param priority Priority for this task - * @param onComplete The consumer to invoke with the {@link net.minecraft.server.ChunkRegionLoader.InProgressChunkHolder} object once this task is complete - * @param intendingToBlock Whether the caller is intending to block on this task completing (this is a performance tune, and has no adverse side-effects) - * @return The {@link ChunkLoadTask} associated with - */ - public ChunkLoadTask scheduleChunkLoad(final int chunkX, final int chunkZ, final int priority, - final Consumer onComplete, - final boolean intendingToBlock) { - final WorldServer world = this.world; - - return this.chunkLoadTasks.compute(Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ)), (final Long keyInMap, final ChunkLoadTask valueInMap) -> { - if (valueInMap != null) { - if (!valueInMap.cancelled) { - throw new IllegalStateException("Double scheduling chunk load for task: " + valueInMap.toString()); - } - valueInMap.cancelled = false; - valueInMap.onComplete = onComplete; - return valueInMap; - } - - final ChunkLoadTask ret = new ChunkLoadTask(world, chunkX, chunkZ, priority, ChunkTaskManager.this, onComplete); - - PaperFileIOThread.Holder.INSTANCE.loadChunkDataAsync(world, chunkX, chunkZ, priority, (final PaperFileIOThread.ChunkData chunkData) -> { - ret.chunkData = chunkData; - ChunkTaskManager.this.internalSchedule(ret); // only schedule to the worker threads here - }, true, true, intendingToBlock); - - return ret; - }); - } - - /** - * Schedules an async save for the specified chunk. The chunk, at the beginning of this call, must be completely unloaded - * from the world. - * @param chunkX Chunk's x coordinate - * @param chunkZ Chunk's z coordinate - * @param priority Priority for this task - * @param asyncSaveData Async save data. See {@link ChunkRegionLoader#getAsyncSaveData(WorldServer, IChunkAccess)} - * @param chunk Chunk to save - * @return The {@link ChunkSaveTask} associated with the save task. - */ - public ChunkSaveTask scheduleChunkSave(final int chunkX, final int chunkZ, final int priority, - final ChunkRegionLoader.AsyncSaveData asyncSaveData, - final IChunkAccess chunk) { - AsyncCatcher.catchOp("chunk save schedule"); - - final WorldServer world = this.world; - - return this.chunkSaveTasks.compute(Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ)), (final Long keyInMap, final ChunkSaveTask valueInMap) -> { - if (valueInMap != null) { - throw new IllegalStateException("Double scheduling chunk save for task: " + valueInMap.toString()); - } - - final ChunkSaveTask ret = new ChunkSaveTask(world, chunkX, chunkZ, priority, ChunkTaskManager.this, asyncSaveData, chunk); - - ChunkTaskManager.this.internalSchedule(ret); - - return ret; - }); - } - - /** - * Returns a completable future which will be completed with the un-copied chunk data for an in progress async save. - * Returns {@code null} if no save is in progress. - * @param chunkX Chunk's x coordinate - * @param chunkZ Chunk's z coordinate - */ - public CompletableFuture getChunkSaveFuture(final int chunkX, final int chunkZ) { - final ChunkSaveTask chunkSaveTask = this.chunkSaveTasks.get(Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ))); - if (chunkSaveTask == null) { - return null; - } - return chunkSaveTask.onComplete; - } - - /** - * Returns the chunk object being used to serialize data async for an unloaded chunk. Note that modifying this chunk - * is not safe to do as another thread is handling its save. The chunk is also not loaded into the world. - * @param chunkX Chunk's x coordinate - * @param chunkZ Chunk's z coordinate - * @return Chunk object for an in-progress async save, or {@code null} if no save is in progress - */ - public IChunkAccess getChunkInSaveProgress(final int chunkX, final int chunkZ) { - final ChunkSaveTask chunkSaveTask = this.chunkSaveTasks.get(Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ))); - if (chunkSaveTask == null) { - return null; - } - return chunkSaveTask.chunk; - } - - public void flush() { - // flush here since we schedule tasks on the IO thread that can schedule tasks here - drainChunkWaitQueue(); - PaperFileIOThread.Holder.INSTANCE.flush(); - drainChunkWaitQueue(); - - if (this.workers == null) { - if (Bukkit.isPrimaryThread()) { - ((IAsyncTaskHandler)this.world.getChunkProvider().serverThreadQueue).executeAll(); - } else { - CompletableFuture wait = new CompletableFuture<>(); - MinecraftServer.getServer().scheduleOnMain(() -> { - ((IAsyncTaskHandler)this.world.getChunkProvider().serverThreadQueue).executeAll(); - }); - wait.join(); - } - } else { - for (final QueueExecutorThread worker : this.workers) { - worker.flush(); - } - } - - // flush again since tasks we execute async saves - drainChunkWaitQueue(); - PaperFileIOThread.Holder.INSTANCE.flush(); - } - - public void close(final boolean wait) { - // flush here since we schedule tasks on the IO thread that can schedule tasks to this task manager - // we do this regardless of the wait param since after we invoke close no tasks can be queued - PaperFileIOThread.Holder.INSTANCE.flush(); - - if (this.workers == null) { - if (wait) { - this.flush(); - } - return; - } - - if (this.workers != globalWorkers) { - for (final QueueExecutorThread worker : this.workers) { - worker.close(false, this.perWorldQueue); - } - } - - if (wait) { - this.flush(); - } - } - - public void raisePriority(final int chunkX, final int chunkZ, final int priority) { - final Long chunkKey = Long.valueOf(IOUtil.getCoordinateKey(chunkX, chunkZ)); - - ChunkSaveTask chunkSaveTask = this.chunkSaveTasks.get(chunkKey); - if (chunkSaveTask != null) { - final boolean raised = chunkSaveTask.raisePriority(priority); - if (chunkSaveTask.isScheduled() && raised) { - // only notify if we're in queue to be executed - this.internalScheduleNotify(); - } - } - - ChunkLoadTask chunkLoadTask = this.chunkLoadTasks.get(chunkKey); - if (chunkLoadTask != null) { - final boolean raised = chunkLoadTask.raisePriority(priority); - if (chunkLoadTask.isScheduled() && raised) { - // only notify if we're in queue to be executed - this.internalScheduleNotify(); - } - } - } - - protected void internalSchedule(final ChunkTask task) { - if (this.workers == null) { - this.chunkTasks.add(task); - return; - } - - // It's important we order the task to be executed before notifying. Avoid a race condition where the worker thread - // wakes up and goes to sleep before we actually schedule (or it's just about to sleep) - this.queue.add(task); - this.internalScheduleNotify(); - } - - protected void internalScheduleNotify() { - if (this.workers == null) { - return; - } - for (final QueueExecutorThread worker : this.workers) { - if (worker.notifyTasks()) { - // break here since we only want to wake up one worker for scheduling one task - break; - } - } - } - -} diff --git a/src/main/java/com/destroystokyo/paper/log/LogFullPolicy.java b/src/main/java/com/destroystokyo/paper/log/LogFullPolicy.java deleted file mode 100644 index db652a1f7..000000000 --- a/src/main/java/com/destroystokyo/paper/log/LogFullPolicy.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.destroystokyo.paper.log; - -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 { - - /* - * Prevents log calls being logged out of order when the log queue is full. - */ - - @Override - public EventRoute getRoute(final long backgroundThreadId, final Level level) { - return EventRoute.ENQUEUE; - } -} diff --git a/src/main/java/com/destroystokyo/paper/loottable/PaperLootableBlockInventory.java b/src/main/java/com/destroystokyo/paper/loottable/PaperLootableBlockInventory.java deleted file mode 100644 index d6fce3112..000000000 --- a/src/main/java/com/destroystokyo/paper/loottable/PaperLootableBlockInventory.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import net.minecraft.server.BlockPosition; -import net.minecraft.server.TileEntityLootable; -import net.minecraft.server.World; -import org.bukkit.Chunk; -import org.bukkit.block.Block; - -public interface PaperLootableBlockInventory extends LootableBlockInventory, PaperLootableInventory { - - TileEntityLootable getTileEntity(); - - @Override - default LootableInventory getAPILootableInventory() { - return this; - } - - @Override - default World getNMSWorld() { - return getTileEntity().getWorld(); - } - - default Block getBlock() { - final BlockPosition position = getTileEntity().getPosition(); - final Chunk bukkitChunk = getTileEntity().getWorld().getChunkAtWorldCoords(position).bukkitChunk; - return bukkitChunk.getBlock(position.getX(), position.getY(), position.getZ()); - } - - @Override - default PaperLootableInventoryData getLootableData() { - return getTileEntity().lootableData; - } -} diff --git a/src/main/java/com/destroystokyo/paper/loottable/PaperLootableEntityInventory.java b/src/main/java/com/destroystokyo/paper/loottable/PaperLootableEntityInventory.java deleted file mode 100644 index 5e637782d..000000000 --- a/src/main/java/com/destroystokyo/paper/loottable/PaperLootableEntityInventory.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import net.minecraft.server.World; -import org.bukkit.entity.Entity; - -public interface PaperLootableEntityInventory extends LootableEntityInventory, PaperLootableInventory { - - net.minecraft.server.Entity getHandle(); - - @Override - default LootableInventory getAPILootableInventory() { - return this; - } - - default Entity getEntity() { - return getHandle().getBukkitEntity(); - } - - @Override - default World getNMSWorld() { - return getHandle().getWorld(); - } - - @Override - default PaperLootableInventoryData getLootableData() { - return getHandle().lootableData; - } -} diff --git a/src/main/java/com/destroystokyo/paper/loottable/PaperLootableInventory.java b/src/main/java/com/destroystokyo/paper/loottable/PaperLootableInventory.java deleted file mode 100644 index 856843fc9..000000000 --- a/src/main/java/com/destroystokyo/paper/loottable/PaperLootableInventory.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import net.minecraft.server.World; -import org.bukkit.loot.Lootable; - -import java.util.UUID; - -public interface PaperLootableInventory extends LootableInventory, Lootable { - - PaperLootableInventoryData getLootableData(); - LootableInventory getAPILootableInventory(); - - World getNMSWorld(); - - default org.bukkit.World getBukkitWorld() { - return getNMSWorld().getWorld(); - } - - @Override - default boolean isRefillEnabled() { - return getNMSWorld().paperConfig.autoReplenishLootables; - } - - @Override - default boolean hasBeenFilled() { - return getLastFilled() != -1; - } - - @Override - default boolean hasPlayerLooted(UUID player) { - return getLootableData().hasPlayerLooted(player); - } - - @Override - default Long getLastLooted(UUID player) { - return getLootableData().getLastLooted(player); - } - - @Override - default boolean setHasPlayerLooted(UUID player, boolean looted) { - final boolean hasLooted = hasPlayerLooted(player); - if (hasLooted != looted) { - getLootableData().setPlayerLootedState(player, looted); - } - return hasLooted; - } - - @Override - default boolean hasPendingRefill() { - long nextRefill = getLootableData().getNextRefill(); - return nextRefill != -1 && nextRefill > getLootableData().getLastFill(); - } - - @Override - default long getLastFilled() { - return getLootableData().getLastFill(); - } - - @Override - default long getNextRefill() { - return getLootableData().getNextRefill(); - } - - @Override - default long setNextRefill(long refillAt) { - if (refillAt < -1) { - refillAt = -1; - } - return getLootableData().setNextRefill(refillAt); - } -} diff --git a/src/main/java/com/destroystokyo/paper/loottable/PaperLootableInventoryData.java b/src/main/java/com/destroystokyo/paper/loottable/PaperLootableInventoryData.java deleted file mode 100644 index b5401eaf9..000000000 --- a/src/main/java/com/destroystokyo/paper/loottable/PaperLootableInventoryData.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import com.destroystokyo.paper.PaperWorldConfig; -import net.minecraft.server.*; -import org.bukkit.entity.Player; -import org.bukkit.loot.LootTable; - -import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.UUID; - -public class PaperLootableInventoryData { - - private static final Random RANDOM = new Random(); - - private long lastFill = -1; - private long nextRefill = -1; - private int numRefills = 0; - private Map lootedPlayers; - private final PaperLootableInventory lootable; - - public PaperLootableInventoryData(PaperLootableInventory lootable) { - this.lootable = lootable; - } - - long getLastFill() { - return this.lastFill; - } - - long getNextRefill() { - return this.nextRefill; - } - - long setNextRefill(long nextRefill) { - long prev = this.nextRefill; - this.nextRefill = nextRefill; - return prev; - } - - public boolean shouldReplenish(@Nullable EntityHuman player) { - LootTable table = this.lootable.getLootTable(); - - // No Loot Table associated - if (table == null) { - return false; - } - - // ALWAYS process the first fill or if the feature is disabled - if (this.lastFill == -1 || !this.lootable.getNMSWorld().paperConfig.autoReplenishLootables) { - return true; - } - - // Only process refills when a player is set - if (player == null) { - return false; - } - - // Chest is not scheduled for refill - if (this.nextRefill == -1) { - return false; - } - - final PaperWorldConfig paperConfig = this.lootable.getNMSWorld().paperConfig; - - // Check if max refills has been hit - if (paperConfig.maxLootableRefills != -1 && this.numRefills >= paperConfig.maxLootableRefills) { - return false; - } - - // Refill has not been reached - if (this.nextRefill > System.currentTimeMillis()) { - return false; - } - - - final Player bukkitPlayer = (Player) player.getBukkitEntity(); - LootableInventoryReplenishEvent event = new LootableInventoryReplenishEvent(bukkitPlayer, lootable.getAPILootableInventory()); - if (paperConfig.restrictPlayerReloot && hasPlayerLooted(player.getUniqueID())) { - event.setCancelled(true); - } - return event.callEvent(); - } - public void processRefill(@Nullable EntityHuman player) { - this.lastFill = System.currentTimeMillis(); - final PaperWorldConfig paperConfig = this.lootable.getNMSWorld().paperConfig; - if (paperConfig.autoReplenishLootables) { - int min = paperConfig.lootableRegenMin; - int max = paperConfig.lootableRegenMax; - this.nextRefill = this.lastFill + (min + RANDOM.nextInt(max - min + 1)) * 1000L; - this.numRefills++; - if (paperConfig.changeLootTableSeedOnFill) { - this.lootable.setSeed(0); - } - if (player != null) { // This means that numRefills can be incremented without a player being in the lootedPlayers list - Seems to be EntityMinecartChest specific - this.setPlayerLootedState(player.getUniqueID(), true); - } - } else { - this.lootable.clearLootTable(); - } - } - - - public void loadNbt(NBTTagCompound base) { - if (!base.hasKeyOfType("Paper.LootableData", 10)) { // 10 = compound - return; - } - NBTTagCompound comp = base.getCompound("Paper.LootableData"); - if (comp.hasKey("lastFill")) { - this.lastFill = comp.getLong("lastFill"); - } - if (comp.hasKey("nextRefill")) { - this.nextRefill = comp.getLong("nextRefill"); - } - - if (comp.hasKey("numRefills")) { - this.numRefills = comp.getInt("numRefills"); - } - if (comp.hasKeyOfType("lootedPlayers", 9)) { // 9 = list - NBTTagList list = comp.getList("lootedPlayers", 10); // 10 = compound - final int size = list.size(); - if (size > 0) { - this.lootedPlayers = new HashMap<>(list.size()); - } - for (int i = 0; i < size; i++) { - final NBTTagCompound cmp = list.getCompound(i); - lootedPlayers.put(cmp.getUUID("UUID"), cmp.getLong("Time")); - } - } - } - public void saveNbt(NBTTagCompound base) { - NBTTagCompound comp = new NBTTagCompound(); - if (this.nextRefill != -1) { - comp.setLong("nextRefill", this.nextRefill); - } - if (this.lastFill != -1) { - comp.setLong("lastFill", this.lastFill); - } - if (this.numRefills != 0) { - comp.setInt("numRefills", this.numRefills); - } - if (this.lootedPlayers != null && !this.lootedPlayers.isEmpty()) { - NBTTagList list = new NBTTagList(); - for (Map.Entry entry : this.lootedPlayers.entrySet()) { - NBTTagCompound cmp = new NBTTagCompound(); - cmp.setUUID("UUID", entry.getKey()); - cmp.setLong("Time", entry.getValue()); - list.add(cmp); - } - comp.set("lootedPlayers", list); - } - - if (!comp.isEmpty()) { - base.set("Paper.LootableData", comp); - } - } - - void setPlayerLootedState(UUID player, boolean looted) { - if (looted && this.lootedPlayers == null) { - this.lootedPlayers = new HashMap<>(); - } - if (looted) { - if (!this.lootedPlayers.containsKey(player)) { - this.lootedPlayers.put(player, System.currentTimeMillis()); - } - } else if (this.lootedPlayers != null) { - this.lootedPlayers.remove(player); - } - } - - boolean hasPlayerLooted(UUID player) { - return this.lootedPlayers != null && this.lootedPlayers.containsKey(player); - } - - Long getLastLooted(UUID player) { - return lootedPlayers != null ? lootedPlayers.get(player) : null; - } -} diff --git a/src/main/java/com/destroystokyo/paper/loottable/PaperMinecartLootableInventory.java b/src/main/java/com/destroystokyo/paper/loottable/PaperMinecartLootableInventory.java deleted file mode 100644 index f9fbc221b..000000000 --- a/src/main/java/com/destroystokyo/paper/loottable/PaperMinecartLootableInventory.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import net.minecraft.server.Entity; -import net.minecraft.server.EntityMinecartContainer; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.World; -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; - -public class PaperMinecartLootableInventory implements PaperLootableEntityInventory { - - private EntityMinecartContainer entity; - - public PaperMinecartLootableInventory(EntityMinecartContainer entity) { - this.entity = entity; - } - - @Override - public org.bukkit.loot.LootTable getLootTable() { - return entity.getLootTableKey() != null ? Bukkit.getLootTable(CraftNamespacedKey.fromMinecraft(entity.getLootTableKey())) : null; - } - - @Override - public void setLootTable(org.bukkit.loot.LootTable table, long seed) { - setLootTable(table); - setSeed(seed); - } - - @Override - public void setSeed(long seed) { - entity.lootTableSeed = seed; - } - - @Override - public long getSeed() { - return entity.lootTableSeed; - } - - @Override - public void setLootTable(org.bukkit.loot.LootTable table) { - MinecraftKey newKey = (table == null) ? null : CraftNamespacedKey.toMinecraft(table.getKey()); - entity.setLootTable(newKey); - } - - @Override - public PaperLootableInventoryData getLootableData() { - return entity.lootableData; - } - - @Override - public Entity getHandle() { - return entity; - } - - @Override - public LootableInventory getAPILootableInventory() { - return (LootableInventory) entity.getBukkitEntity(); - } - - @Override - public World getNMSWorld() { - return entity.world; - } -} diff --git a/src/main/java/com/destroystokyo/paper/loottable/PaperTileEntityLootableInventory.java b/src/main/java/com/destroystokyo/paper/loottable/PaperTileEntityLootableInventory.java deleted file mode 100644 index d50410532..000000000 --- a/src/main/java/com/destroystokyo/paper/loottable/PaperTileEntityLootableInventory.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.destroystokyo.paper.loottable; - -import net.minecraft.server.MCUtil; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.TileEntityLootable; -import net.minecraft.server.World; -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; - -public class PaperTileEntityLootableInventory implements PaperLootableBlockInventory { - private TileEntityLootable tileEntityLootable; - - public PaperTileEntityLootableInventory(TileEntityLootable tileEntityLootable) { - this.tileEntityLootable = tileEntityLootable; - } - - @Override - public org.bukkit.loot.LootTable getLootTable() { - return tileEntityLootable.getLootTableKey() != null ? Bukkit.getLootTable(CraftNamespacedKey.fromMinecraft(tileEntityLootable.getLootTableKey())) : null; - } - - @Override - public void setLootTable(org.bukkit.loot.LootTable table, long seed) { - setLootTable(table); - setSeed(seed); - } - - @Override - public void setLootTable(org.bukkit.loot.LootTable table) { - MinecraftKey newKey = (table == null) ? null : CraftNamespacedKey.toMinecraft(table.getKey()); - tileEntityLootable.setLootTable(newKey); - } - - @Override - public void setSeed(long seed) { - tileEntityLootable.setSeed(seed); - } - - @Override - public long getSeed() { - return tileEntityLootable.getSeed(); - } - - @Override - public PaperLootableInventoryData getLootableData() { - return tileEntityLootable.lootableData; - } - - @Override - public TileEntityLootable getTileEntity() { - return tileEntityLootable; - } - - @Override - public LootableInventory getAPILootableInventory() { - World world = tileEntityLootable.getWorld(); - if (world == null) { - return null; - } - return (LootableInventory) getBukkitWorld().getBlockAt(MCUtil.toLocation(world, tileEntityLootable.getPosition())).getState(); - } - - @Override - public World getNMSWorld() { - return tileEntityLootable.getWorld(); - } -} diff --git a/src/main/java/com/destroystokyo/paper/network/PaperLegacyStatusClient.java b/src/main/java/com/destroystokyo/paper/network/PaperLegacyStatusClient.java deleted file mode 100644 index 74c012fd4..000000000 --- a/src/main/java/com/destroystokyo/paper/network/PaperLegacyStatusClient.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.destroystokyo.paper.network; - -import com.destroystokyo.paper.event.server.PaperServerListPingEvent; -import net.minecraft.server.MinecraftServer; -import org.apache.commons.lang3.StringUtils; -import org.bukkit.ChatColor; - -import java.net.InetSocketAddress; - -import javax.annotation.Nullable; - -public final class PaperLegacyStatusClient implements StatusClient { - - private final InetSocketAddress address; - private final int protocolVersion; - @Nullable private final InetSocketAddress virtualHost; - - private PaperLegacyStatusClient(InetSocketAddress address, int protocolVersion, @Nullable InetSocketAddress virtualHost) { - this.address = address; - this.protocolVersion = protocolVersion; - this.virtualHost = virtualHost; - } - - @Override - public InetSocketAddress getAddress() { - return this.address; - } - - @Override - public int getProtocolVersion() { - return this.protocolVersion; - } - - @Nullable - @Override - public InetSocketAddress getVirtualHost() { - return this.virtualHost; - } - - @Override - public boolean isLegacy() { - return true; - } - - public static PaperServerListPingEvent processRequest(MinecraftServer server, - InetSocketAddress address, int protocolVersion, @Nullable InetSocketAddress virtualHost) { - - PaperServerListPingEvent event = new PaperServerListPingEventImpl(server, - new PaperLegacyStatusClient(address, protocolVersion, virtualHost), Byte.MAX_VALUE, null); - server.server.getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return null; - } - - return event; - } - - public static String getMotd(PaperServerListPingEvent event) { - return getFirstLine(event.getMotd()); - } - - public static String getUnformattedMotd(PaperServerListPingEvent event) { - // Strip color codes and all other occurrences of the color char (because it's used as delimiter) - return getFirstLine(StringUtils.remove(ChatColor.stripColor(event.getMotd()), ChatColor.COLOR_CHAR)); - } - - private static String getFirstLine(String s) { - int pos = s.indexOf('\n'); - return pos >= 0 ? s.substring(0, pos) : s; - } - -} diff --git a/src/main/java/com/destroystokyo/paper/network/PaperNetworkClient.java b/src/main/java/com/destroystokyo/paper/network/PaperNetworkClient.java deleted file mode 100644 index 5caca6439..000000000 --- a/src/main/java/com/destroystokyo/paper/network/PaperNetworkClient.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.destroystokyo.paper.network; - -import net.minecraft.server.NetworkManager; - -import java.net.InetSocketAddress; - -import javax.annotation.Nullable; - -public class PaperNetworkClient implements NetworkClient { - - private final NetworkManager networkManager; - - PaperNetworkClient(NetworkManager networkManager) { - this.networkManager = networkManager; - } - - @Override - public InetSocketAddress getAddress() { - return (InetSocketAddress) this.networkManager.getSocketAddress(); - } - - @Override - public int getProtocolVersion() { - return this.networkManager.protocolVersion; - } - - @Nullable - @Override - public InetSocketAddress getVirtualHost() { - return this.networkManager.virtualHost; - } - - public static InetSocketAddress prepareVirtualHost(String host, int port) { - int len = host.length(); - - // FML appends a marker to the host to recognize FML clients (\0FML\0) - int pos = host.indexOf('\0'); - if (pos >= 0) { - len = pos; - } - - // When clients connect with a SRV record, their host contains a trailing '.' - if (len > 0 && host.charAt(len - 1) == '.') { - len--; - } - - return InetSocketAddress.createUnresolved(host.substring(0, len), port); - } - -} diff --git a/src/main/java/com/destroystokyo/paper/network/PaperServerListPingEventImpl.java b/src/main/java/com/destroystokyo/paper/network/PaperServerListPingEventImpl.java deleted file mode 100644 index c1a8e295b..000000000 --- a/src/main/java/com/destroystokyo/paper/network/PaperServerListPingEventImpl.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.destroystokyo.paper.network; - -import com.destroystokyo.paper.event.server.PaperServerListPingEvent; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.MinecraftServer; -import org.bukkit.entity.Player; -import org.bukkit.util.CachedServerIcon; - -import javax.annotation.Nullable; - -class PaperServerListPingEventImpl extends PaperServerListPingEvent { - - private final MinecraftServer server; - - PaperServerListPingEventImpl(MinecraftServer server, StatusClient client, int protocolVersion, @Nullable CachedServerIcon icon) { - super(client, server.getMotd(), server.getPlayerCount(), server.getMaxPlayers(), - server.getServerModName() + ' ' + server.getVersion(), protocolVersion, icon); - this.server = server; - } - - @Override - protected final Object[] getOnlinePlayers() { - return this.server.getPlayerList().players.toArray(); - } - - @Override - protected final Player getBukkitPlayer(Object player) { - return ((EntityPlayer) player).getBukkitEntity(); - } - -} diff --git a/src/main/java/com/destroystokyo/paper/network/PaperStatusClient.java b/src/main/java/com/destroystokyo/paper/network/PaperStatusClient.java deleted file mode 100644 index a2a409e63..000000000 --- a/src/main/java/com/destroystokyo/paper/network/PaperStatusClient.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.destroystokyo.paper.network; - -import net.minecraft.server.NetworkManager; - -class PaperStatusClient extends PaperNetworkClient implements StatusClient { - - PaperStatusClient(NetworkManager networkManager) { - super(networkManager); - } - -} diff --git a/src/main/java/com/destroystokyo/paper/network/StandardPaperServerListPingEventImpl.java b/src/main/java/com/destroystokyo/paper/network/StandardPaperServerListPingEventImpl.java deleted file mode 100644 index a85466bc7..000000000 --- a/src/main/java/com/destroystokyo/paper/network/StandardPaperServerListPingEventImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.destroystokyo.paper.network; - -import com.destroystokyo.paper.profile.CraftPlayerProfile; -import com.destroystokyo.paper.profile.PlayerProfile; -import com.google.common.base.MoreObjects; -import com.google.common.base.Strings; -import com.mojang.authlib.GameProfile; -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.NetworkManager; -import net.minecraft.server.PacketStatusOutServerInfo; -import net.minecraft.server.ServerPing; - -import java.util.List; -import java.util.UUID; - -import javax.annotation.Nonnull; - -public final class StandardPaperServerListPingEventImpl extends PaperServerListPingEventImpl { - - private static final GameProfile[] EMPTY_PROFILES = new GameProfile[0]; - private static final UUID FAKE_UUID = new UUID(0, 0); - - private GameProfile[] originalSample; - - private StandardPaperServerListPingEventImpl(MinecraftServer server, NetworkManager networkManager, ServerPing ping) { - super(server, new PaperStatusClient(networkManager), ping.getServerData() != null ? ping.getServerData().getProtocolVersion() : -1, server.server.getServerIcon()); - this.originalSample = ping.getPlayers() == null ? null : ping.getPlayers().getSample(); // GH-1473 - pre-tick race condition NPE - } - - @Nonnull - @Override - public List getPlayerSample() { - List sample = super.getPlayerSample(); - - if (this.originalSample != null) { - for (GameProfile profile : this.originalSample) { - sample.add(CraftPlayerProfile.asBukkitCopy(profile)); - } - this.originalSample = null; - } - - return sample; - } - - private GameProfile[] getPlayerSampleHandle() { - if (this.originalSample != null) { - return this.originalSample; - } - - List entries = super.getPlayerSample(); - if (entries.isEmpty()) { - return EMPTY_PROFILES; - } - - GameProfile[] profiles = new GameProfile[entries.size()]; - for (int i = 0; i < profiles.length; i++) { - /* - * Avoid null UUIDs/names since that will make the response invalid - * on the client. - * Instead, fall back to a fake/empty UUID and an empty string as name. - * This can be used to create custom lines in the player list that do not - * refer to a specific player. - */ - - PlayerProfile profile = entries.get(i); - if (profile.getId() != null && profile.getName() != null) { - profiles[i] = CraftPlayerProfile.asAuthlib(profile); - } else { - profiles[i] = new GameProfile(MoreObjects.firstNonNull(profile.getId(), FAKE_UUID), Strings.nullToEmpty(profile.getName())); - } - } - - return profiles; - } - - @SuppressWarnings("deprecation") - public static void processRequest(MinecraftServer server, NetworkManager networkManager) { - StandardPaperServerListPingEventImpl event = new StandardPaperServerListPingEventImpl(server, networkManager, server.getServerPing()); - server.server.getPluginManager().callEvent(event); - - // Close connection immediately if event is cancelled - if (event.isCancelled()) { - networkManager.close(null); - return; - } - - // Setup response - ServerPing ping = new ServerPing(); - - // Description - ping.setMOTD(new ChatComponentText(event.getMotd())); - - // Players - if (!event.shouldHidePlayers()) { - ping.setPlayerSample(new ServerPing.ServerPingPlayerSample(event.getMaxPlayers(), event.getNumPlayers())); - ping.getPlayers().setSample(event.getPlayerSampleHandle()); - } - - // Version - ping.setServerInfo(new ServerPing.ServerData(event.getVersion(), event.getProtocolVersion())); - - // Favicon - if (event.getServerIcon() != null) { - ping.setFavicon(event.getServerIcon().getData()); - } - - // Send response - networkManager.sendPacket(new PacketStatusOutServerInfo(ping)); - } - -} diff --git a/src/main/java/com/destroystokyo/paper/profile/CraftPlayerProfile.java b/src/main/java/com/destroystokyo/paper/profile/CraftPlayerProfile.java deleted file mode 100644 index b151a13c1..000000000 --- a/src/main/java/com/destroystokyo/paper/profile/CraftPlayerProfile.java +++ /dev/null @@ -1,280 +0,0 @@ -package com.destroystokyo.paper.profile; - -import com.destroystokyo.paper.PaperConfig; -import com.google.common.base.Charsets; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.properties.Property; -import com.mojang.authlib.properties.PropertyMap; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.UserCache; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.spigotmc.SpigotConfig; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.AbstractSet; -import java.util.Collection; -import java.util.Iterator; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; - -public class CraftPlayerProfile implements PlayerProfile { - - private GameProfile profile; - private final PropertySet properties = new PropertySet(); - - public CraftPlayerProfile(CraftPlayer player) { - this.profile = player.getHandle().getProfile(); - } - - public CraftPlayerProfile(UUID id, String name) { - this.profile = new GameProfile(id, name); - } - - public CraftPlayerProfile(GameProfile profile) { - this.profile = profile; - } - - @Override - public boolean hasProperty(String property) { - return profile.getProperties().containsKey(property); - } - - @Override - public void setProperty(ProfileProperty property) { - String name = property.getName(); - PropertyMap properties = profile.getProperties(); - properties.removeAll(name); - properties.put(name, new Property(name, property.getValue(), property.getSignature())); - } - - public GameProfile getGameProfile() { - return profile; - } - - @Nullable - @Override - public UUID getId() { - return profile.getId(); - } - - @Override - public UUID setId(@Nullable UUID uuid) { - GameProfile prev = this.profile; - this.profile = new GameProfile(uuid, prev.getName()); - copyProfileProperties(prev, this.profile); - return prev.getId(); - } - - @Nullable - @Override - public String getName() { - return profile.getName(); - } - - @Override - public String setName(@Nullable String name) { - GameProfile prev = this.profile; - this.profile = new GameProfile(prev.getId(), name); - copyProfileProperties(prev, this.profile); - return prev.getName(); - } - - @Nonnull - @Override - public Set getProperties() { - return properties; - } - - @Override - public void setProperties(Collection properties) { - properties.forEach(this::setProperty); - } - - @Override - public void clearProperties() { - profile.getProperties().clear(); - } - - @Override - public boolean removeProperty(String property) { - return !profile.getProperties().removeAll(property).isEmpty(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CraftPlayerProfile that = (CraftPlayerProfile) o; - return Objects.equals(profile, that.profile); - } - - @Override - public int hashCode() { - return profile.hashCode(); - } - - @Override - public String toString() { - return profile.toString(); - } - - @Override - public CraftPlayerProfile clone() { - CraftPlayerProfile clone = new CraftPlayerProfile(this.getId(), this.getName()); - clone.setProperties(getProperties()); - return clone; - } - - @Override - public boolean isComplete() { - return profile.isComplete(); - } - - @Override - public boolean completeFromCache() { - return completeFromCache(false); - } - - public boolean completeFromCache(boolean lookupName) { - if (profile.isComplete()) { - return true; - } - MinecraftServer server = MinecraftServer.getServer(); - String name = profile.getName(); - UserCache userCache = server.getUserCache(); - if (profile.getId() == null) { - final GameProfile profile; - boolean isOnlineMode = server.getOnlineMode() || (SpigotConfig.bungee && PaperConfig.bungeeOnlineMode); - if (isOnlineMode) { - profile = lookupName ? userCache.getProfile(name) : userCache.getProfileIfCached(name); - } else { - // Make an OfflinePlayer using an offline mode UUID since the name has no profile - profile = new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)), name); - } - if (profile != null) { - this.profile = profile; - } - } - - if (profile.getName() == null) { - // If we need textures, skip this check, as we will get it below anyways. - GameProfile profile = userCache.getProfile(this.profile.getId()); - if (profile != null) { - this.profile = profile; - } - } - return this.profile.isComplete(); - } - - public boolean complete(boolean textures) { - MinecraftServer server = MinecraftServer.getServer(); - - boolean isOnlineMode = server.getOnlineMode() || (SpigotConfig.bungee && PaperConfig.bungeeOnlineMode); - boolean isCompleteFromCache = this.completeFromCache(true); - if (isOnlineMode && (!isCompleteFromCache || textures && !hasTextures())) { - GameProfile result = server.getSessionService().fillProfileProperties(profile, true); - if (result != null) { - this.profile = result; - } - } - return profile.isComplete() && (!isOnlineMode || !textures || hasTextures()); - } - - private static void copyProfileProperties(GameProfile source, GameProfile target) { - PropertyMap sourceProperties = source.getProperties(); - if (sourceProperties.isEmpty()) { - return; - } - PropertyMap properties = target.getProperties(); - properties.clear(); - - for (Property property : sourceProperties.values()) { - properties.put(property.getName(), property); - } - } - - private static ProfileProperty toBukkit(Property property) { - return new ProfileProperty(property.getName(), property.getValue(), property.getSignature()); - } - - public static PlayerProfile asBukkitCopy(GameProfile gameProfile) { - CraftPlayerProfile profile = new CraftPlayerProfile(gameProfile.getId(), gameProfile.getName()); - copyProfileProperties(gameProfile, profile.profile); - return profile; - } - - public static PlayerProfile asBukkitMirror(GameProfile profile) { - return new CraftPlayerProfile(profile); - } - - public static Property asAuthlib(ProfileProperty property) { - return new Property(property.getName(), property.getValue(), property.getSignature()); - } - - public static GameProfile asAuthlibCopy(PlayerProfile profile) { - CraftPlayerProfile craft = ((CraftPlayerProfile) profile); - return asAuthlib(craft.clone()); - } - - public static GameProfile asAuthlib(PlayerProfile profile) { - CraftPlayerProfile craft = ((CraftPlayerProfile) profile); - return craft.getGameProfile(); - } - - private class PropertySet extends AbstractSet { - - @Override - @Nonnull - public Iterator iterator() { - return new ProfilePropertyIterator(profile.getProperties().values().iterator()); - } - - @Override - public int size() { - return profile.getProperties().size(); - } - - @Override - public boolean add(ProfileProperty property) { - setProperty(property); - return true; - } - - @Override - public boolean addAll(Collection c) { - //noinspection unchecked - setProperties((Collection) c); - return true; - } - - @Override - public boolean contains(Object o) { - return o instanceof ProfileProperty && profile.getProperties().containsKey(((ProfileProperty) o).getName()); - } - - private class ProfilePropertyIterator implements Iterator { - private final Iterator iterator; - - ProfilePropertyIterator(Iterator iterator) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public ProfileProperty next() { - return toBukkit(iterator.next()); - } - - @Override - public void remove() { - iterator.remove(); - } - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/profile/PaperAuthenticationService.java b/src/main/java/com/destroystokyo/paper/profile/PaperAuthenticationService.java deleted file mode 100644 index 25836b975..000000000 --- a/src/main/java/com/destroystokyo/paper/profile/PaperAuthenticationService.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.destroystokyo.paper.profile; - -import com.mojang.authlib.Agent; -import com.mojang.authlib.GameProfileRepository; -import com.mojang.authlib.UserAuthentication; -import com.mojang.authlib.minecraft.MinecraftSessionService; -import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; - -import java.net.Proxy; - -public class PaperAuthenticationService extends YggdrasilAuthenticationService { - public PaperAuthenticationService(Proxy proxy, String clientToken) { - super(proxy, clientToken); - } - - @Override - public UserAuthentication createUserAuthentication(Agent agent) { - return new PaperUserAuthentication(this, agent); - } - - @Override - public MinecraftSessionService createMinecraftSessionService() { - return new PaperMinecraftSessionService(this); - } - - @Override - public GameProfileRepository createProfileRepository() { - return new PaperGameProfileRepository(this); - } -} diff --git a/src/main/java/com/destroystokyo/paper/profile/PaperGameProfileRepository.java b/src/main/java/com/destroystokyo/paper/profile/PaperGameProfileRepository.java deleted file mode 100644 index bb9894318..000000000 --- a/src/main/java/com/destroystokyo/paper/profile/PaperGameProfileRepository.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.destroystokyo.paper.profile; - -import com.destroystokyo.paper.event.profile.LookupProfileEvent; -import com.destroystokyo.paper.event.profile.PreLookupProfileEvent; -import com.google.common.collect.Sets; -import com.mojang.authlib.Agent; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.ProfileLookupCallback; -import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; -import com.mojang.authlib.yggdrasil.YggdrasilGameProfileRepository; - -import java.util.Set; - -public class PaperGameProfileRepository extends YggdrasilGameProfileRepository { - - public PaperGameProfileRepository(YggdrasilAuthenticationService authenticationService) { - super(authenticationService); - } - - @Override - public void findProfilesByNames(String[] names, Agent agent, ProfileLookupCallback callback) { - Set unfoundNames = Sets.newHashSet(); - for (String name : names) { - PreLookupProfileEvent event = new PreLookupProfileEvent(name); - event.callEvent(); - if (event.getUUID() != null) { - // Plugin provided UUI, we can skip network call. - GameProfile gameprofile = new GameProfile(event.getUUID(), name); - // We might even have properties! - Set profileProperties = event.getProfileProperties(); - if (!profileProperties.isEmpty()) { - for (ProfileProperty property : profileProperties) { - gameprofile.getProperties().put(property.getName(), CraftPlayerProfile.asAuthlib(property)); - } - } - callback.onProfileLookupSucceeded(gameprofile); - } else { - unfoundNames.add(name); - } - } - - // Some things were not found.... Proceed to look up. - if (!unfoundNames.isEmpty()) { - String[] namesArr = unfoundNames.toArray(new String[unfoundNames.size()]); - super.findProfilesByNames(namesArr, agent, new PreProfileLookupCallback(callback)); - } - } - - private static class PreProfileLookupCallback implements ProfileLookupCallback { - private final ProfileLookupCallback callback; - - PreProfileLookupCallback(ProfileLookupCallback callback) { - this.callback = callback; - } - - @Override - public void onProfileLookupSucceeded(GameProfile gameProfile) { - PlayerProfile from = CraftPlayerProfile.asBukkitMirror(gameProfile); - new LookupProfileEvent(from).callEvent(); - callback.onProfileLookupSucceeded(gameProfile); - } - - @Override - public void onProfileLookupFailed(GameProfile gameProfile, Exception e) { - callback.onProfileLookupFailed(gameProfile, e); - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/profile/PaperMinecraftSessionService.java b/src/main/java/com/destroystokyo/paper/profile/PaperMinecraftSessionService.java deleted file mode 100644 index 61cfdf73c..000000000 --- a/src/main/java/com/destroystokyo/paper/profile/PaperMinecraftSessionService.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.destroystokyo.paper.profile; - -import com.destroystokyo.paper.event.profile.FillProfileEvent; -import com.destroystokyo.paper.event.profile.PreFillProfileEvent; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.minecraft.MinecraftProfileTexture; -import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; -import com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService; - -import java.util.Map; - -public class PaperMinecraftSessionService extends YggdrasilMinecraftSessionService { - protected PaperMinecraftSessionService(YggdrasilAuthenticationService authenticationService) { - super(authenticationService); - } - - @Override - public Map getTextures(GameProfile profile, boolean requireSecure) { - return super.getTextures(profile, requireSecure); - } - - @Override - public GameProfile fillProfileProperties(GameProfile profile, boolean requireSecure) { - CraftPlayerProfile playerProfile = (CraftPlayerProfile) CraftPlayerProfile.asBukkitMirror(profile); - new PreFillProfileEvent(playerProfile).callEvent(); - profile = playerProfile.getGameProfile(); - if (profile.isComplete() && profile.getProperties().containsKey("textures")) { - return profile; - } - GameProfile gameProfile = super.fillProfileProperties(profile, requireSecure); - new FillProfileEvent(CraftPlayerProfile.asBukkitMirror(gameProfile)).callEvent(); - return gameProfile; - } - - @Override - protected GameProfile fillGameProfile(GameProfile profile, boolean requireSecure) { - return super.fillGameProfile(profile, requireSecure); - } -} diff --git a/src/main/java/com/destroystokyo/paper/profile/PaperUserAuthentication.java b/src/main/java/com/destroystokyo/paper/profile/PaperUserAuthentication.java deleted file mode 100644 index 3aceb0ea8..000000000 --- a/src/main/java/com/destroystokyo/paper/profile/PaperUserAuthentication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.destroystokyo.paper.profile; - -import com.mojang.authlib.Agent; -import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; -import com.mojang.authlib.yggdrasil.YggdrasilUserAuthentication; - -public class PaperUserAuthentication extends YggdrasilUserAuthentication { - public PaperUserAuthentication(YggdrasilAuthenticationService authenticationService, Agent agent) { - super(authenticationService, agent); - } -} diff --git a/src/main/java/com/destroystokyo/paper/proxy/VelocityProxy.java b/src/main/java/com/destroystokyo/paper/proxy/VelocityProxy.java deleted file mode 100644 index fdd8708f9..000000000 --- a/src/main/java/com/destroystokyo/paper/proxy/VelocityProxy.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.destroystokyo.paper.proxy; - -import com.destroystokyo.paper.PaperConfig; -import com.google.common.net.InetAddresses; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.properties.Property; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.PacketDataSerializer; - -import java.net.InetAddress; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -public class VelocityProxy { - private static final int SUPPORTED_FORWARDING_VERSION = 1; - public static final MinecraftKey PLAYER_INFO_CHANNEL = new MinecraftKey("velocity", "player_info"); - - public static boolean checkIntegrity(final PacketDataSerializer buf) { - final byte[] signature = new byte[32]; - buf.readBytes(signature); - - final byte[] data = new byte[buf.readableBytes()]; - buf.getBytes(buf.readerIndex(), data); - - try { - final Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(PaperConfig.velocitySecretKey, "HmacSHA256")); - final byte[] mySignature = mac.doFinal(data); - if (!MessageDigest.isEqual(signature, mySignature)) { - return false; - } - } catch (final InvalidKeyException | NoSuchAlgorithmException e) { - throw new AssertionError(e); - } - - int version = buf.readVarInt(); - if (version != SUPPORTED_FORWARDING_VERSION) { - throw new IllegalStateException("Unsupported forwarding version " + version + ", wanted " + SUPPORTED_FORWARDING_VERSION); - } - - return true; - } - - public static InetAddress readAddress(final PacketDataSerializer buf) { - return InetAddresses.forString(buf.readUTF(Short.MAX_VALUE)); - } - - public static GameProfile createProfile(final PacketDataSerializer buf) { - final GameProfile profile = new GameProfile(buf.readUUID(), buf.readUTF(16)); - readProperties(buf, profile); - return profile; - } - - private static void readProperties(final PacketDataSerializer buf, final GameProfile profile) { - final int properties = buf.readVarInt(); - for (int i1 = 0; i1 < properties; i1++) { - final String name = buf.readUTF(Short.MAX_VALUE); - final String value = buf.readUTF(Short.MAX_VALUE); - final String signature = buf.readBoolean() ? buf.readUTF(Short.MAX_VALUE) : null; - profile.getProperties().put(name, new Property(name, value, signature)); - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/util/PlayerMobDistanceMap.java b/src/main/java/com/destroystokyo/paper/util/PlayerMobDistanceMap.java deleted file mode 100644 index 9ebd7ecb7..000000000 --- a/src/main/java/com/destroystokyo/paper/util/PlayerMobDistanceMap.java +++ /dev/null @@ -1,253 +0,0 @@ -package com.destroystokyo.paper.util; - -import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; -import net.minecraft.server.ChunkCoordIntPair; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.SectionPosition; -import org.spigotmc.AsyncCatcher; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** @author Spottedleaf */ -public final class PlayerMobDistanceMap { - - private static final PooledHashSets.PooledObjectLinkedOpenHashSet EMPTY_SET = new PooledHashSets.PooledObjectLinkedOpenHashSet<>(); - - private final Map players = new HashMap<>(); - // we use linked for better iteration. - private final Long2ObjectOpenHashMap> playerMap = new Long2ObjectOpenHashMap<>(32, 0.5f); - private int viewDistance; - - private final PooledHashSets pooledHashSets = new PooledHashSets<>(); - - public PooledHashSets.PooledObjectLinkedOpenHashSet getPlayersInRange(final ChunkCoordIntPair chunkPos) { - return this.getPlayersInRange(chunkPos.x, chunkPos.z); - } - - public PooledHashSets.PooledObjectLinkedOpenHashSet getPlayersInRange(final int chunkX, final int chunkZ) { - return this.playerMap.getOrDefault(ChunkCoordIntPair.pair(chunkX, chunkZ), EMPTY_SET); - } - - public void update(final List currentPlayers, final int newViewDistance) { - AsyncCatcher.catchOp("Distance map update"); - final ObjectLinkedOpenHashSet gone = new ObjectLinkedOpenHashSet<>(this.players.keySet()); - - final int oldViewDistance = this.viewDistance; - this.viewDistance = newViewDistance; - - for (final EntityPlayer player : currentPlayers) { - if (player.isSpectator() || !player.affectsSpawning) { - continue; // will be left in 'gone' (or not added at all) - } - - gone.remove(player); - - final SectionPosition newPosition = player.getPlayerMapSection(); - final SectionPosition oldPosition = this.players.put(player, newPosition); - - if (oldPosition == null) { - this.addNewPlayer(player, newPosition, newViewDistance); - } else { - this.updatePlayer(player, oldPosition, newPosition, oldViewDistance, newViewDistance); - } - //this.validatePlayer(player, newViewDistance); // debug only - } - - for (final EntityPlayer player : gone) { - final SectionPosition oldPosition = this.players.remove(player); - if (oldPosition != null) { - this.removePlayer(player, oldPosition, oldViewDistance); - } - } - } - - // expensive op, only for debug - private void validatePlayer(final EntityPlayer player, final int viewDistance) { - int entiesGot = 0; - int expectedEntries = (2 * viewDistance + 1); - expectedEntries *= expectedEntries; - - final SectionPosition currPosition = player.getPlayerMapSection(); - - final int centerX = currPosition.getX(); - final int centerZ = currPosition.getZ(); - - for (final Long2ObjectLinkedOpenHashMap.Entry> entry : this.playerMap.long2ObjectEntrySet()) { - final long key = entry.getLongKey(); - final PooledHashSets.PooledObjectLinkedOpenHashSet map = entry.getValue(); - - if (map.referenceCount == 0) { - throw new IllegalStateException("Invalid map"); - } - - if (map.set.contains(player)) { - ++entiesGot; - - final int chunkX = ChunkCoordIntPair.getX(key); - final int chunkZ = ChunkCoordIntPair.getZ(key); - - final int dist = Math.max(Math.abs(chunkX - centerX), Math.abs(chunkZ - centerZ)); - - if (dist > viewDistance) { - throw new IllegalStateException("Expected view distance " + viewDistance + ", got " + dist); - } - } - } - - if (entiesGot != expectedEntries) { - throw new IllegalStateException("Expected " + expectedEntries + ", got " + entiesGot); - } - } - - private void addPlayerTo(final EntityPlayer player, final int chunkX, final int chunkZ) { - this.playerMap.compute(ChunkCoordIntPair.pair(chunkX, chunkZ), (final Long key, final PooledHashSets.PooledObjectLinkedOpenHashSet players) -> { - if (players == null) { - return player.cachedSingleMobDistanceMap; - } else { - return PlayerMobDistanceMap.this.pooledHashSets.findMapWith(players, player); - } - }); - } - - private void removePlayerFrom(final EntityPlayer player, final int chunkX, final int chunkZ) { - this.playerMap.compute(ChunkCoordIntPair.pair(chunkX, chunkZ), (final Long keyInMap, final PooledHashSets.PooledObjectLinkedOpenHashSet players) -> { - return PlayerMobDistanceMap.this.pooledHashSets.findMapWithout(players, player); // rets null instead of an empty map - }); - } - - private void updatePlayer(final EntityPlayer player, final SectionPosition oldPosition, final SectionPosition newPosition, final int oldViewDistance, final int newViewDistance) { - final int toX = newPosition.getX(); - final int toZ = newPosition.getZ(); - final int fromX = oldPosition.getX(); - final int fromZ = oldPosition.getZ(); - - final int dx = toX - fromX; - final int dz = toZ - fromZ; - - final int totalX = Math.abs(fromX - toX); - final int totalZ = Math.abs(fromZ - toZ); - - if (Math.max(totalX, totalZ) > (2 * oldViewDistance)) { - // teleported? - this.removePlayer(player, oldPosition, oldViewDistance); - this.addNewPlayer(player, newPosition, newViewDistance); - return; - } - - // x axis is width - // z axis is height - // right refers to the x axis of where we moved - // top refers to the z axis of where we moved - - if (oldViewDistance == newViewDistance) { - // same view distance - - // used for relative positioning - final int up = 1 | (dz >> (Integer.SIZE - 1)); // 1 if dz >= 0, -1 otherwise - final int right = 1 | (dx >> (Integer.SIZE - 1)); // 1 if dx >= 0, -1 otherwise - - // The area excluded by overlapping the two view distance squares creates four rectangles: - // Two on the left, and two on the right. The ones on the left we consider the "removed" section - // and on the right the "added" section. - // https://i.imgur.com/MrnOBgI.png is a reference image. Note that the outside border is not actually - // exclusive to the regions they surround. - - // 4 points of the rectangle - int maxX; // exclusive - int minX; // inclusive - int maxZ; // exclusive - int minZ; // inclusive - - if (dx != 0) { - // handle right addition - - maxX = toX + (oldViewDistance * right) + right; // exclusive - minX = fromX + (oldViewDistance * right) + right; // inclusive - maxZ = fromZ + (oldViewDistance * up) + up; // exclusive - minZ = toZ - (oldViewDistance * up); // inclusive - - for (int currX = minX; currX != maxX; currX += right) { - for (int currZ = minZ; currZ != maxZ; currZ += up) { - this.addPlayerTo(player, currX, currZ); - } - } - } - - if (dz != 0) { - // handle up addition - - maxX = toX + (oldViewDistance * right) + right; // exclusive - minX = toX - (oldViewDistance * right); // inclusive - maxZ = toZ + (oldViewDistance * up) + up; // exclusive - minZ = fromZ + (oldViewDistance * up) + up; // inclusive - - for (int currX = minX; currX != maxX; currX += right) { - for (int currZ = minZ; currZ != maxZ; currZ += up) { - this.addPlayerTo(player, currX, currZ); - } - } - } - - if (dx != 0) { - // handle left removal - - maxX = toX - (oldViewDistance * right); // exclusive - minX = fromX - (oldViewDistance * right); // inclusive - maxZ = fromZ + (oldViewDistance * up) + up; // exclusive - minZ = toZ - (oldViewDistance * up); // inclusive - - for (int currX = minX; currX != maxX; currX += right) { - for (int currZ = minZ; currZ != maxZ; currZ += up) { - this.removePlayerFrom(player, currX, currZ); - } - } - } - - if (dz != 0) { - // handle down removal - - maxX = fromX + (oldViewDistance * right) + right; // exclusive - minX = fromX - (oldViewDistance * right); // inclusive - maxZ = toZ - (oldViewDistance * up); // exclusive - minZ = fromZ - (oldViewDistance * up); // inclusive - - for (int currX = minX; currX != maxX; currX += right) { - for (int currZ = minZ; currZ != maxZ; currZ += up) { - this.removePlayerFrom(player, currX, currZ); - } - } - } - } else { - // different view distance - // for now :) - this.removePlayer(player, oldPosition, oldViewDistance); - this.addNewPlayer(player, newPosition, newViewDistance); - } - } - - private void removePlayer(final EntityPlayer player, final SectionPosition position, final int viewDistance) { - final int x = position.getX(); - final int z = position.getZ(); - - for (int xoff = -viewDistance; xoff <= viewDistance; ++xoff) { - for (int zoff = -viewDistance; zoff <= viewDistance; ++zoff) { - this.removePlayerFrom(player, x + xoff, z + zoff); - } - } - } - - private void addNewPlayer(final EntityPlayer player, final SectionPosition position, final int viewDistance) { - final int x = position.getX(); - final int z = position.getZ(); - - for (int xoff = -viewDistance; xoff <= viewDistance; ++xoff) { - for (int zoff = -viewDistance; zoff <= viewDistance; ++zoff) { - this.addPlayerTo(player, x + xoff, z + zoff); - } - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/util/PooledHashSets.java b/src/main/java/com/destroystokyo/paper/util/PooledHashSets.java deleted file mode 100644 index 4f13d3ff8..000000000 --- a/src/main/java/com/destroystokyo/paper/util/PooledHashSets.java +++ /dev/null @@ -1,241 +0,0 @@ -package com.destroystokyo.paper.util; - -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; -import java.lang.ref.WeakReference; -import java.util.Iterator; - -/** @author Spottedleaf */ -public class PooledHashSets { - - // we really want to avoid that equals() check as much as possible... - protected final Object2ObjectOpenHashMap, PooledObjectLinkedOpenHashSet> mapPool = new Object2ObjectOpenHashMap<>(64, 0.25f); - - protected void decrementReferenceCount(final PooledObjectLinkedOpenHashSet current) { - if (current.referenceCount == 0) { - throw new IllegalStateException("Cannot decrement reference count for " + current); - } - if (current.referenceCount == -1 || --current.referenceCount > 0) { - return; - } - - this.mapPool.remove(current); - return; - } - - public PooledObjectLinkedOpenHashSet findMapWith(final PooledObjectLinkedOpenHashSet current, final E object) { - final PooledObjectLinkedOpenHashSet cached = current.getAddCache(object); - - if (cached != null) { - if (cached.referenceCount != -1) { - ++cached.referenceCount; - } - - decrementReferenceCount(current); - - return cached; - } - - if (!current.add(object)) { - return current; - } - - // we use get/put since we use a different key on put - PooledObjectLinkedOpenHashSet ret = this.mapPool.get(current); - - if (ret == null) { - ret = new PooledObjectLinkedOpenHashSet<>(current); - current.remove(object); - this.mapPool.put(ret, ret); - ret.referenceCount = 1; - } else { - if (ret.referenceCount != -1) { - ++ret.referenceCount; - } - current.remove(object); - } - - current.updateAddCache(object, ret); - - decrementReferenceCount(current); - return ret; - } - - // rets null if current.size() == 1 - public PooledObjectLinkedOpenHashSet findMapWithout(final PooledObjectLinkedOpenHashSet current, final E object) { - if (current.set.size() == 1) { - decrementReferenceCount(current); - return null; - } - - final PooledObjectLinkedOpenHashSet cached = current.getRemoveCache(object); - - if (cached != null) { - if (cached.referenceCount != -1) { - ++cached.referenceCount; - } - - decrementReferenceCount(current); - - return cached; - } - - if (!current.remove(object)) { - return current; - } - - // we use get/put since we use a different key on put - PooledObjectLinkedOpenHashSet ret = this.mapPool.get(current); - - if (ret == null) { - ret = new PooledObjectLinkedOpenHashSet<>(current); - current.add(object); - this.mapPool.put(ret, ret); - ret.referenceCount = 1; - } else { - if (ret.referenceCount != -1) { - ++ret.referenceCount; - } - current.add(object); - } - - current.updateRemoveCache(object, ret); - - decrementReferenceCount(current); - return ret; - } - - public static final class PooledObjectLinkedOpenHashSet implements Iterable { - - private static final WeakReference NULL_REFERENCE = new WeakReference(null); - - final ObjectLinkedOpenHashSet set; - int referenceCount; // -1 if special - int hash; // optimize hashcode - - // add cache - WeakReference lastAddObject = NULL_REFERENCE; - WeakReference> lastAddMap = NULL_REFERENCE; - - // remove cache - WeakReference lastRemoveObject = NULL_REFERENCE; - WeakReference> lastRemoveMap = NULL_REFERENCE; - - public PooledObjectLinkedOpenHashSet() { - this.set = new ObjectLinkedOpenHashSet<>(2, 0.6f); - } - - public PooledObjectLinkedOpenHashSet(final E single) { - this(); - this.referenceCount = -1; - this.add(single); - } - - public PooledObjectLinkedOpenHashSet(final PooledObjectLinkedOpenHashSet other) { - this.set = other.set.clone(); - this.hash = other.hash; - } - - // from https://github.com/Spottedleaf/ConcurrentUtil/blob/master/src/main/java/ca/spottedleaf/concurrentutil/util/IntegerUtil.java - // generated by https://github.com/skeeto/hash-prospector - static int hash0(int x) { - x *= 0x36935555; - x ^= x >>> 16; - return x; - } - - public PooledObjectLinkedOpenHashSet getAddCache(final E element) { - final E currentAdd = this.lastAddObject.get(); - - if (currentAdd == null || !(currentAdd == element || currentAdd.equals(element))) { - return null; - } - - final PooledObjectLinkedOpenHashSet map = this.lastAddMap.get(); - if (map == null || map.referenceCount == 0) { - // we need to ret null if ref count is zero as calling code will assume the map is in use - return null; - } - - return map; - } - - public PooledObjectLinkedOpenHashSet getRemoveCache(final E element) { - final E currentRemove = this.lastRemoveObject.get(); - - if (currentRemove == null || !(currentRemove == element || currentRemove.equals(element))) { - return null; - } - - final PooledObjectLinkedOpenHashSet map = this.lastRemoveMap.get(); - if (map == null || map.referenceCount == 0) { - // we need to ret null if ref count is zero as calling code will assume the map is in use - return null; - } - - return map; - } - - public void updateAddCache(final E element, final PooledObjectLinkedOpenHashSet map) { - this.lastAddObject = new WeakReference<>(element); - this.lastAddMap = new WeakReference<>(map); - } - - public void updateRemoveCache(final E element, final PooledObjectLinkedOpenHashSet map) { - this.lastRemoveObject = new WeakReference<>(element); - this.lastRemoveMap = new WeakReference<>(map); - } - - boolean add(final E element) { - boolean added = this.set.add(element); - - if (added) { - this.hash += hash0(element.hashCode()); - } - - return added; - } - - boolean remove(Object element) { - boolean removed = this.set.remove(element); - - if (removed) { - this.hash -= hash0(element.hashCode()); - } - - return removed; - } - - @Override - public Iterator iterator() { - return this.set.iterator(); - } - - @Override - public int hashCode() { - return this.hash; - } - - @Override - public boolean equals(final Object other) { - if (!(other instanceof PooledObjectLinkedOpenHashSet)) { - return false; - } - if (this.referenceCount == 0) { - return other == this; - } else { - if (other == this) { - // Unfortunately we are never equal to our own instance while in use! - return false; - } - return this.hash == ((PooledObjectLinkedOpenHashSet)other).hash && this.set.equals(((PooledObjectLinkedOpenHashSet)other).set); - } - } - - @Override - public String toString() { - return "PooledHashSet: size: " + this.set.size() + ", reference count: " + this.referenceCount + ", hash: " + - this.hashCode() + ", identity: " + System.identityHashCode(this) + " map: " + this.set.toString(); - } - } -} diff --git a/src/main/java/com/destroystokyo/paper/util/RedstoneWireTurbo.java b/src/main/java/com/destroystokyo/paper/util/RedstoneWireTurbo.java deleted file mode 100644 index cf5661f1c..000000000 --- a/src/main/java/com/destroystokyo/paper/util/RedstoneWireTurbo.java +++ /dev/null @@ -1,912 +0,0 @@ -package com.destroystokyo.paper.util; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; - -import org.bukkit.event.block.BlockRedstoneEvent; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import net.minecraft.server.Block; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.BlockRedstoneWire; -import net.minecraft.server.IBlockData; -import net.minecraft.server.Items; -import net.minecraft.server.ItemStack; -import net.minecraft.server.World; - -/** - * Used for the faster redstone algorithm. - * Original author: theosib - * Original license: MIT - * - * Ported to Paper and updated to 1.13 by egg82 - */ -public class RedstoneWireTurbo { - /* - * 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. - */ - - /* Reference to BlockRedstoneWire object, which uses this accelerator */ - private final BlockRedstoneWire wire; - - /* - * 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 RedstoneWireTurbo(BlockRedstoneWire wire) { - this.wire = wire; - } - - /* - * 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 static 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 != wire) { - // 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 (!wire.canPlace(null, worldIn, pos)) { - // Pop off the redstone dust - Block.a(worldIn, pos, new ItemStack(Items.REDSTONE)); // TODO - 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 = wire.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.size()>0 || updateQueue1.size()>0) { - // 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). - worldIn.neighborChanged(upd.self, wire, 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 IBlockData 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. - return newState; - } - - /* - * 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 IBlockData 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 = wire.calculateCurrentChanges(worldIn, pos, pos, state); - - // If no change, exit - if (newState == state) { - return state; - } - - // Check to see if this update was received during an on-going breadth first search - if (currentWalkLayer > 0 || nodeCache.size() > 0) { - // 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. - return scheduleReentrantNeighborChanged(worldIn, pos, newState, source); - } - // 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(); - - return newState; - } - - // 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).intValue(); - int j = 0; - j = getMaxCurrentStrength(upd, j); - int l = 0; - - wire.setCanProvidePower(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.isBlockIndirectlyGettingPowered(upd.self); - wire.setCanProvidePower(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.isOccluding(worldIn, center_up.self); // TODO - - 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.isOccluding(worldIn, neighbor.self); // TODO - 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. - state = state.set(BlockRedstoneWire.POWER, Integer.valueOf(j)); - worldIn.setTypeAndData(upd.self, state, 2); - } - - return state; - } - - /* - * 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).intValue(); - return i > strength ? i : strength; - } -} diff --git a/src/main/java/com/destroystokyo/paper/util/ReentrantLockWithGetOwner.java b/src/main/java/com/destroystokyo/paper/util/ReentrantLockWithGetOwner.java deleted file mode 100644 index a3b174618..000000000 --- a/src/main/java/com/destroystokyo/paper/util/ReentrantLockWithGetOwner.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.destroystokyo.paper.util; - -import java.util.concurrent.locks.ReentrantLock; - -public class ReentrantLockWithGetOwner extends ReentrantLock { - - @Override - public Thread getOwner() { - return super.getOwner(); - } -} diff --git a/src/main/java/com/mojang/authlib/yggdrasil/YggdrasilGameProfileRepository.java b/src/main/java/com/mojang/authlib/yggdrasil/YggdrasilGameProfileRepository.java deleted file mode 100644 index 23f1447cf..000000000 --- a/src/main/java/com/mojang/authlib/yggdrasil/YggdrasilGameProfileRepository.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.mojang.authlib.yggdrasil; - -import com.google.common.base.Strings; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; -import com.mojang.authlib.Agent; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.GameProfileRepository; -import com.mojang.authlib.HttpAuthenticationService; -import com.mojang.authlib.ProfileLookupCallback; -import com.mojang.authlib.exceptions.AuthenticationException; -import com.mojang.authlib.yggdrasil.response.ProfileSearchResultsResponse; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.List; -import java.util.Set; - -public class YggdrasilGameProfileRepository implements GameProfileRepository { - private static final Logger LOGGER = LogManager.getLogger(); - private static final String BASE_URL = "https://api.mojang.com/"; - private static final String SEARCH_PAGE_URL = BASE_URL + "profiles/"; - private static final int ENTRIES_PER_PAGE = 2; - private static final int MAX_FAIL_COUNT = 3; - private static final int DELAY_BETWEEN_PAGES = 100; - private static final int DELAY_BETWEEN_FAILURES = 750; - - private final YggdrasilAuthenticationService authenticationService; - - public YggdrasilGameProfileRepository(final YggdrasilAuthenticationService authenticationService) { - this.authenticationService = authenticationService; - } - - @Override - public void findProfilesByNames(final String[] names, final Agent agent, final ProfileLookupCallback callback) { - final Set criteria = Sets.newHashSet(); - - for (final String name : names) { - if (!Strings.isNullOrEmpty(name)) { - criteria.add(name.toLowerCase()); - } - } - - final int page = 0; - boolean hasRequested = false; // Paper - - for (final List request : Iterables.partition(criteria, ENTRIES_PER_PAGE)) { - int failCount = 0; - boolean failed; - - do { - failed = false; - - try { - final ProfileSearchResultsResponse response = authenticationService.makeRequest(HttpAuthenticationService.constantURL(SEARCH_PAGE_URL + agent.getName().toLowerCase()), request, ProfileSearchResultsResponse.class); - failCount = 0; - - LOGGER.debug("Page {} returned {} results, parsing", page, response.getProfiles().length); - - final Set missing = Sets.newHashSet(request); - for (final GameProfile profile : response.getProfiles()) { - LOGGER.debug("Successfully looked up profile {}", profile); - missing.remove(profile.getName().toLowerCase()); - callback.onProfileLookupSucceeded(profile); - } - - for (final String name : missing) { - LOGGER.debug("Couldn't find profile {}", name); - callback.onProfileLookupFailed(new GameProfile(null, name), new ProfileNotFoundException("Server did not find the requested profile")); - } - // Paper start - if (!hasRequested) { - hasRequested = true; - continue; - } - // Paper end - - try { - Thread.sleep(DELAY_BETWEEN_PAGES); - } catch (final InterruptedException ignored) { - } - } catch (final AuthenticationException e) { - failCount++; - - if (failCount == MAX_FAIL_COUNT) { - for (final String name : request) { - LOGGER.debug("Couldn't find profile {} because of a server error", name); - callback.onProfileLookupFailed(new GameProfile(null, name), e); - } - } else { - try { - Thread.sleep(DELAY_BETWEEN_FAILURES); - } catch (final InterruptedException ignored) { - } - failed = true; - } - } - } while (failed); - } - } -} diff --git a/src/main/java/com/mojang/brigadier/tree/CommandNode.java b/src/main/java/com/mojang/brigadier/tree/CommandNode.java deleted file mode 100644 index 98592a3e6..000000000 --- a/src/main/java/com/mojang/brigadier/tree/CommandNode.java +++ /dev/null @@ -1,207 +0,0 @@ -package com.mojang.brigadier.tree; - -import com.google.common.collect.ComparisonChain; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.mojang.brigadier.AmbiguityConsumer; -import com.mojang.brigadier.Command; -import com.mojang.brigadier.RedirectModifier; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.builder.ArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.context.CommandContextBuilder; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.suggestion.Suggestions; -import com.mojang.brigadier.suggestion.SuggestionsBuilder; - -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import net.minecraft.server.CommandListenerWrapper; // CraftBukkit - -public abstract class CommandNode implements Comparable> { - private Map> children = Maps.newLinkedHashMap(); - private Map> literals = Maps.newLinkedHashMap(); - private Map> arguments = Maps.newLinkedHashMap(); - private final Predicate requirement; - private final CommandNode redirect; - private final RedirectModifier modifier; - private final boolean forks; - private Command command; - // CraftBukkit start - public void removeCommand(String name) { - children.remove(name); - literals.remove(name); - arguments.remove(name); - } - // CraftBukkit end - - protected CommandNode(final Command command, final Predicate requirement, final CommandNode redirect, final RedirectModifier modifier, final boolean forks) { - this.command = command; - this.requirement = requirement; - this.redirect = redirect; - this.modifier = modifier; - this.forks = forks; - } - - public Command getCommand() { - return command; - } - - public Collection> getChildren() { - return children.values(); - } - - public CommandNode getChild(final String name) { - return children.get(name); - } - - public CommandNode getRedirect() { - return redirect; - } - - public RedirectModifier getRedirectModifier() { - return modifier; - } - - public boolean canUse(final S source) { - // CraftBukkit start - if (source instanceof CommandListenerWrapper) { - try { - ((CommandListenerWrapper) source).currentCommand = this; - return requirement.test(source); - } finally { - ((CommandListenerWrapper) source).currentCommand = null; - } - } - // CraftBukkit end - return requirement.test(source); - } - - public void addChild(final CommandNode node) { - if (node instanceof RootCommandNode) { - throw new UnsupportedOperationException("Cannot add a RootCommandNode as a child to any other CommandNode"); - } - - final CommandNode child = children.get(node.getName()); - if (child != null) { - // We've found something to merge onto - if (node.getCommand() != null) { - child.command = node.getCommand(); - } - for (final CommandNode grandchild : node.getChildren()) { - child.addChild(grandchild); - } - } else { - children.put(node.getName(), node); - if (node instanceof LiteralCommandNode) { - literals.put(node.getName(), (LiteralCommandNode) node); - } else if (node instanceof ArgumentCommandNode) { - arguments.put(node.getName(), (ArgumentCommandNode) node); - } - } - - children = children.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); - } - - public void findAmbiguities(final AmbiguityConsumer consumer) { - Set matches = Sets.newHashSet(); - - for (final CommandNode child : children.values()) { - for (final CommandNode sibling : children.values()) { - if (child == sibling) { - continue; - } - - for (final String input : child.getExamples()) { - if (sibling.isValidInput(input)) { - matches.add(input); - } - } - - if (matches.size() > 0) { - consumer.ambiguous(this, child, sibling, matches); - matches = Sets.newHashSet(); - } - } - - child.findAmbiguities(consumer); - } - } - - protected abstract boolean isValidInput(final String input); - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (!(o instanceof CommandNode)) return false; - - final CommandNode that = (CommandNode) o; - - if (!children.equals(that.children)) return false; - if (command != null ? !command.equals(that.command) : that.command != null) return false; - - return true; - } - - @Override - public int hashCode() { - return 31 * children.hashCode() + (command != null ? command.hashCode() : 0); - } - - public Predicate getRequirement() { - return requirement; - } - - public abstract String getName(); - - public abstract String getUsageText(); - - public abstract void parse(StringReader reader, CommandContextBuilder contextBuilder) throws CommandSyntaxException; - - public abstract CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) throws CommandSyntaxException; - - public abstract ArgumentBuilder createBuilder(); - - protected abstract String getSortedKey(); - - public Collection> getRelevantNodes(final StringReader input) { - if (literals.size() > 0) { - final int cursor = input.getCursor(); - while (input.canRead() && input.peek() != ' ') { - input.skip(); - } - final String text = input.getString().substring(cursor, input.getCursor()); - input.setCursor(cursor); - final LiteralCommandNode literal = literals.get(text); - if (literal != null) { - return Collections.singleton(literal); - } else { - return arguments.values(); - } - } else { - return arguments.values(); - } - } - - @Override - public int compareTo(final CommandNode o) { - return ComparisonChain - .start() - .compareTrueFirst(this instanceof LiteralCommandNode, o instanceof LiteralCommandNode) - .compare(getSortedKey(), o.getSortedKey()) - .result(); - } - - public boolean isFork() { - return forks; - } - - public abstract Collection getExamples(); -} diff --git a/src/main/java/net/minecraft/server/Advancement.java b/src/main/java/net/minecraft/server/Advancement.java deleted file mode 100644 index 3ef2f4d2a..000000000 --- a/src/main/java/net/minecraft/server/Advancement.java +++ /dev/null @@ -1,440 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; -import java.util.Arrays; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; -import java.util.function.Consumer; -import java.util.function.Function; -import javax.annotation.Nullable; -import org.apache.commons.lang3.ArrayUtils; - -public class Advancement { - - private final Advancement a; - private final AdvancementDisplay b; - private final AdvancementRewards c; - private final MinecraftKey d; - private final Map e; - private final String[][] f; - private final Set g = Sets.newLinkedHashSet(); - private final IChatBaseComponent h; - public final org.bukkit.advancement.Advancement bukkit = new org.bukkit.craftbukkit.advancement.CraftAdvancement(this); // CraftBukkit - - public Advancement(MinecraftKey minecraftkey, @Nullable Advancement advancement, @Nullable AdvancementDisplay advancementdisplay, AdvancementRewards advancementrewards, Map map, String[][] astring) { - this.d = minecraftkey; - this.b = advancementdisplay; - this.e = ImmutableMap.copyOf(map); - this.a = advancement; - this.c = advancementrewards; - this.f = astring; - if (advancement != null) { - advancement.a(this); - } - - if (advancementdisplay == null) { - this.h = new ChatComponentText(minecraftkey.toString()); - } else { - IChatBaseComponent ichatbasecomponent = advancementdisplay.a(); - EnumChatFormat enumchatformat = advancementdisplay.e().c(); - IChatBaseComponent ichatbasecomponent1 = ichatbasecomponent.h().a(enumchatformat).a("\n").addSibling(advancementdisplay.b()); - IChatBaseComponent ichatbasecomponent2 = ichatbasecomponent.h().a((chatmodifier) -> { - chatmodifier.setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_TEXT, ichatbasecomponent1)); - }); - - this.h = (new ChatComponentText("[")).addSibling(ichatbasecomponent2).a("]").a(enumchatformat); - } - - } - - public Advancement.SerializedAdvancement a() { - return new Advancement.SerializedAdvancement(this.a == null ? null : this.a.getName(), this.b, this.c, this.e, this.f); - } - - @Nullable - public Advancement b() { - return this.a; - } - - @Nullable - public AdvancementDisplay c() { - return this.b; - } - - public AdvancementRewards d() { - return this.c; - } - - public String toString() { - return "SimpleAdvancement{id=" + this.getName() + ", parent=" + (this.a == null ? "null" : this.a.getName()) + ", display=" + this.b + ", rewards=" + this.c + ", criteria=" + this.e + ", requirements=" + Arrays.deepToString(this.f) + '}'; - } - - public Iterable e() { - return this.g; - } - - public Map getCriteria() { - return this.e; - } - - public void a(Advancement advancement) { - this.g.add(advancement); - } - - public MinecraftKey getName() { - return this.d; - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (!(object instanceof Advancement)) { - return false; - } else { - Advancement advancement = (Advancement) object; - - return this.d.equals(advancement.d); - } - } - - public int hashCode() { - return this.d.hashCode(); - } - - public String[][] i() { - return this.f; - } - - public IChatBaseComponent j() { - return this.h; - } - - public static class SerializedAdvancement { - - private MinecraftKey a; - private Advancement b; - private AdvancementDisplay c; - private AdvancementRewards d; - private Map e; - private String[][] f; - private AdvancementRequirements g; - - private SerializedAdvancement(@Nullable MinecraftKey minecraftkey, @Nullable AdvancementDisplay advancementdisplay, AdvancementRewards advancementrewards, Map map, String[][] astring) { - this.d = AdvancementRewards.a; - this.e = Maps.newLinkedHashMap(); - this.g = AdvancementRequirements.AND; - this.a = minecraftkey; - this.c = advancementdisplay; - this.d = advancementrewards; - this.e = map; - this.f = astring; - } - - private SerializedAdvancement() { - this.d = AdvancementRewards.a; - this.e = Maps.newLinkedHashMap(); - this.g = AdvancementRequirements.AND; - } - - public static Advancement.SerializedAdvancement a() { - return new Advancement.SerializedAdvancement(); - } - - public Advancement.SerializedAdvancement a(Advancement advancement) { - this.b = advancement; - return this; - } - - public Advancement.SerializedAdvancement a(MinecraftKey minecraftkey) { - this.a = minecraftkey; - return this; - } - - public Advancement.SerializedAdvancement a(ItemStack itemstack, IChatBaseComponent ichatbasecomponent, IChatBaseComponent ichatbasecomponent1, @Nullable MinecraftKey minecraftkey, AdvancementFrameType advancementframetype, boolean flag, boolean flag1, boolean flag2) { - return this.a(new AdvancementDisplay(itemstack, ichatbasecomponent, ichatbasecomponent1, minecraftkey, advancementframetype, flag, flag1, flag2)); - } - - public Advancement.SerializedAdvancement a(IMaterial imaterial, IChatBaseComponent ichatbasecomponent, IChatBaseComponent ichatbasecomponent1, @Nullable MinecraftKey minecraftkey, AdvancementFrameType advancementframetype, boolean flag, boolean flag1, boolean flag2) { - return this.a(new AdvancementDisplay(new ItemStack(imaterial.getItem()), ichatbasecomponent, ichatbasecomponent1, minecraftkey, advancementframetype, flag, flag1, flag2)); - } - - public Advancement.SerializedAdvancement a(AdvancementDisplay advancementdisplay) { - this.c = advancementdisplay; - return this; - } - - public Advancement.SerializedAdvancement a(AdvancementRewards.a advancementrewards_a) { - return this.a(advancementrewards_a.a()); - } - - public Advancement.SerializedAdvancement a(AdvancementRewards advancementrewards) { - this.d = advancementrewards; - return this; - } - - public Advancement.SerializedAdvancement a(String s, CriterionInstance criterioninstance) { - return this.a(s, new Criterion(criterioninstance)); - } - - public Advancement.SerializedAdvancement a(String s, Criterion criterion) { - if (this.e.containsKey(s)) { - throw new IllegalArgumentException("Duplicate criterion " + s); - } else { - this.e.put(s, criterion); - return this; - } - } - - public Advancement.SerializedAdvancement a(AdvancementRequirements advancementrequirements) { - this.g = advancementrequirements; - return this; - } - - public boolean a(Function function) { - if (this.a == null) { - return true; - } else { - if (this.b == null) { - this.b = (Advancement) function.apply(this.a); - } - - return this.b != null; - } - } - - public Advancement b(MinecraftKey minecraftkey) { - if (!this.a((Function) (minecraftkey1) -> { // CraftBukkit - decompile error - return null; - })) { - throw new IllegalStateException("Tried to build incomplete advancement!"); - } else { - if (this.f == null) { - this.f = this.g.createRequirements(this.e.keySet()); - } - - return new Advancement(minecraftkey, this.b, this.c, this.d, this.e, this.f); - } - } - - public Advancement a(Consumer consumer, String s) { - Advancement advancement = this.b(new MinecraftKey(s)); - - consumer.accept(advancement); - return advancement; - } - - public JsonObject b() { - if (this.f == null) { - this.f = this.g.createRequirements(this.e.keySet()); - } - - JsonObject jsonobject = new JsonObject(); - - if (this.b != null) { - jsonobject.addProperty("parent", this.b.getName().toString()); - } else if (this.a != null) { - jsonobject.addProperty("parent", this.a.toString()); - } - - if (this.c != null) { - jsonobject.add("display", this.c.k()); - } - - jsonobject.add("rewards", this.d.b()); - JsonObject jsonobject1 = new JsonObject(); - Iterator iterator = this.e.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - jsonobject1.add((String) entry.getKey(), ((Criterion) entry.getValue()).b()); - } - - jsonobject.add("criteria", jsonobject1); - JsonArray jsonarray = new JsonArray(); - String[][] astring = this.f; - int i = astring.length; - - for (int j = 0; j < i; ++j) { - String[] astring1 = astring[j]; - JsonArray jsonarray1 = new JsonArray(); - String[] astring2 = astring1; - int k = astring1.length; - - for (int l = 0; l < k; ++l) { - String s = astring2[l]; - - jsonarray1.add(s); - } - - jsonarray.add(jsonarray1); - } - - jsonobject.add("requirements", jsonarray); - return jsonobject; - } - - public void a(PacketDataSerializer packetdataserializer) { - if (this.a == null) { - packetdataserializer.writeBoolean(false); - } else { - packetdataserializer.writeBoolean(true); - packetdataserializer.a(this.a); - } - - if (this.c == null) { - packetdataserializer.writeBoolean(false); - } else { - packetdataserializer.writeBoolean(true); - this.c.a(packetdataserializer); - } - - Criterion.a(this.e, packetdataserializer); - packetdataserializer.d(this.f.length); - String[][] astring = this.f; - int i = astring.length; - - for (int j = 0; j < i; ++j) { - String[] astring1 = astring[j]; - - packetdataserializer.d(astring1.length); - String[] astring2 = astring1; - int k = astring1.length; - - for (int l = 0; l < k; ++l) { - String s = astring2[l]; - - packetdataserializer.a(s); - } - } - - } - - public String toString() { - return "Task Advancement{parentId=" + this.a + ", display=" + this.c + ", rewards=" + this.d + ", criteria=" + this.e + ", requirements=" + Arrays.deepToString(this.f) + '}'; - } - - public static Advancement.SerializedAdvancement a(JsonObject jsonobject, JsonDeserializationContext jsondeserializationcontext) { - MinecraftKey minecraftkey = jsonobject.has("parent") ? new MinecraftKey(ChatDeserializer.h(jsonobject, "parent")) : null; - AdvancementDisplay advancementdisplay = jsonobject.has("display") ? AdvancementDisplay.a(ChatDeserializer.t(jsonobject, "display"), jsondeserializationcontext) : null; - AdvancementRewards advancementrewards = (AdvancementRewards) ChatDeserializer.a(jsonobject, "rewards", AdvancementRewards.a, jsondeserializationcontext, AdvancementRewards.class); - Map map = Criterion.b(ChatDeserializer.t(jsonobject, "criteria"), jsondeserializationcontext); - - if (map.isEmpty()) { - throw new JsonSyntaxException("Advancement criteria cannot be empty"); - } else { - JsonArray jsonarray = ChatDeserializer.a(jsonobject, "requirements", new JsonArray()); - String[][] astring = new String[jsonarray.size()][]; - - int i; - int j; - - for (i = 0; i < jsonarray.size(); ++i) { - JsonArray jsonarray1 = ChatDeserializer.n(jsonarray.get(i), "requirements[" + i + "]"); - - astring[i] = new String[jsonarray1.size()]; - - for (j = 0; j < jsonarray1.size(); ++j) { - astring[i][j] = ChatDeserializer.a(jsonarray1.get(j), "requirements[" + i + "][" + j + "]"); - } - } - - if (astring.length == 0) { - astring = new String[map.size()][]; - i = 0; - - String s; - - for (Iterator iterator = map.keySet().iterator(); iterator.hasNext(); astring[i++] = new String[]{s}) { - s = (String) iterator.next(); - } - } - - String[][] astring1 = astring; - int k = astring.length; - - int l; - - for (j = 0; j < k; ++j) { - String[] astring2 = astring1[j]; - - if (astring2.length == 0 && map.isEmpty()) { - throw new JsonSyntaxException("Requirement entry cannot be empty"); - } - - String[] astring3 = astring2; - - l = astring2.length; - - for (int i1 = 0; i1 < l; ++i1) { - String s1 = astring3[i1]; - - if (!map.containsKey(s1)) { - throw new JsonSyntaxException("Unknown required criterion '" + s1 + "'"); - } - } - } - - Iterator iterator1 = map.keySet().iterator(); - - while (iterator1.hasNext()) { - String s2 = (String) iterator1.next(); - boolean flag = false; - String[][] astring4 = astring; - int j1 = astring.length; - - l = 0; - - while (true) { - if (l < j1) { - String[] astring5 = astring4[l]; - - if (!ArrayUtils.contains(astring5, s2)) { - ++l; - continue; - } - - flag = true; - } - - if (!flag) { - throw new JsonSyntaxException("Criterion '" + s2 + "' isn't a requirement for completion. This isn't supported behaviour, all criteria must be required."); - } - break; - } - } - - return new Advancement.SerializedAdvancement(minecraftkey, advancementdisplay, advancementrewards, map, astring); - } - } - - public static Advancement.SerializedAdvancement b(PacketDataSerializer packetdataserializer) { - MinecraftKey minecraftkey = packetdataserializer.readBoolean() ? packetdataserializer.o() : null; - AdvancementDisplay advancementdisplay = packetdataserializer.readBoolean() ? AdvancementDisplay.b(packetdataserializer) : null; - Map map = Criterion.c(packetdataserializer); - String[][] astring = new String[packetdataserializer.i()][]; - - for (int i = 0; i < astring.length; ++i) { - astring[i] = new String[packetdataserializer.i()]; - - for (int j = 0; j < astring[i].length; ++j) { - astring[i][j] = packetdataserializer.e(32767); - } - } - - return new Advancement.SerializedAdvancement(minecraftkey, advancementdisplay, AdvancementRewards.a, map, astring); - } - - public Map c() { - return this.e; - } - } -} diff --git a/src/main/java/net/minecraft/server/AdvancementDataPlayer.java b/src/main/java/net/minecraft/server/AdvancementDataPlayer.java deleted file mode 100644 index b7f1f39a1..000000000 --- a/src/main/java/net/minecraft/server/AdvancementDataPlayer.java +++ /dev/null @@ -1,514 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Charsets; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.common.io.Files; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; -import com.google.gson.internal.Streams; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.types.JsonOps; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.StringReader; -import java.nio.charset.StandardCharsets; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class AdvancementDataPlayer { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final Gson b = (new GsonBuilder()).registerTypeAdapter(AdvancementProgress.class, new AdvancementProgress.a()).registerTypeAdapter(MinecraftKey.class, new MinecraftKey.a()).setPrettyPrinting().create(); - private static final TypeToken> c = new TypeToken>() { - }; - private final MinecraftServer d; - private final File e; - public final Map data = Maps.newLinkedHashMap(); - private final Set g = Sets.newLinkedHashSet(); - private final Set h = Sets.newLinkedHashSet(); - private final Set i = Sets.newLinkedHashSet(); - private EntityPlayer player; - @Nullable - private Advancement k; - private boolean l = true; - - public AdvancementDataPlayer(MinecraftServer minecraftserver, File file, EntityPlayer entityplayer) { - this.d = minecraftserver; - this.e = file; - this.player = entityplayer; - this.g(); - } - - public void a(EntityPlayer entityplayer) { - this.player = entityplayer; - } - - public void a() { - Iterator iterator = CriterionTriggers.a().iterator(); - - while (iterator.hasNext()) { - CriterionTrigger criteriontrigger = (CriterionTrigger) iterator.next(); - - criteriontrigger.a(this); - } - - } - - public void b() { - this.a(); - this.data.clear(); - this.g.clear(); - this.h.clear(); - this.i.clear(); - this.l = true; - this.k = null; - this.g(); - } - - private void d() { - Iterator iterator = this.d.getAdvancementData().a().iterator(); - - while (iterator.hasNext()) { - Advancement advancement = (Advancement) iterator.next(); - - this.c(advancement); - } - - } - - private void e() { - List list = Lists.newArrayList(); - Iterator iterator = this.data.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - if (((AdvancementProgress) entry.getValue()).isDone()) { - list.add(entry.getKey()); - this.i.add(entry.getKey()); - } - } - - iterator = list.iterator(); - - while (iterator.hasNext()) { - Advancement advancement = (Advancement) iterator.next(); - - this.e(advancement); - } - - } - - private void f() { - Iterator iterator = this.d.getAdvancementData().a().iterator(); - - while (iterator.hasNext()) { - Advancement advancement = (Advancement) iterator.next(); - - if (advancement.getCriteria().isEmpty()) { - this.grantCriteria(advancement, ""); - advancement.d().a(this.player); - } - } - - } - - private void g() { - if (this.e.isFile()) { - try { - JsonReader jsonreader = new JsonReader(new StringReader(Files.toString(this.e, StandardCharsets.UTF_8))); - Throwable throwable = null; - - try { - jsonreader.setLenient(false); - Dynamic dynamic = new Dynamic(JsonOps.INSTANCE, Streams.parse(jsonreader)); - - if (!dynamic.get("DataVersion").asNumber().isPresent()) { - dynamic = dynamic.set("DataVersion", dynamic.createInt(1343)); - } - - dynamic = this.d.aB().update(DataFixTypes.ADVANCEMENTS.a(), dynamic, dynamic.get("DataVersion").asInt(0), SharedConstants.a().getWorldVersion()); - dynamic = dynamic.remove("DataVersion"); - Map map = (Map) AdvancementDataPlayer.b.getAdapter(AdvancementDataPlayer.c).fromJsonTree((JsonElement) dynamic.getValue()); - - if (map == null) { - throw new JsonParseException("Found null for advancements"); - } - - Stream> stream = map.entrySet().stream().sorted(Comparator.comparing(Entry::getValue)); - Iterator iterator = ((List) stream.collect(Collectors.toList())).iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - Advancement advancement = this.d.getAdvancementData().a((MinecraftKey) entry.getKey()); - - if (advancement == null) { - // CraftBukkit start - if (entry.getKey().getNamespace().equals("minecraft")) { - AdvancementDataPlayer.LOGGER.warn("Ignored advancement '{}' in progress file {} - it doesn't exist anymore?", entry.getKey(), this.e); - } - // CraftBukkit end - } else { - this.a(advancement, (AdvancementProgress) entry.getValue()); - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (jsonreader != null) { - if (throwable != null) { - try { - jsonreader.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - jsonreader.close(); - } - } - - } - } catch (JsonParseException jsonparseexception) { - AdvancementDataPlayer.LOGGER.error("Couldn't parse player advancements in {}", this.e, jsonparseexception); - } catch (IOException ioexception) { - AdvancementDataPlayer.LOGGER.error("Couldn't access player advancements in {}", this.e, ioexception); - } - } - - this.f(); - this.e(); - this.d(); - } - - public void c() { - if (org.spigotmc.SpigotConfig.disableAdvancementSaving) return; - Map map = Maps.newHashMap(); - Iterator iterator = this.data.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - AdvancementProgress advancementprogress = (AdvancementProgress) entry.getValue(); - - if (advancementprogress.b()) { - map.put(((Advancement) entry.getKey()).getName(), advancementprogress); - } - } - - if (this.e.getParentFile() != null) { - this.e.getParentFile().mkdirs(); - } - - JsonElement jsonelement = AdvancementDataPlayer.b.toJsonTree(map); - - jsonelement.getAsJsonObject().addProperty("DataVersion", SharedConstants.a().getWorldVersion()); - - try { - FileOutputStream fileoutputstream = new FileOutputStream(this.e); - Throwable throwable = null; - - try { - OutputStreamWriter outputstreamwriter = new OutputStreamWriter(fileoutputstream, Charsets.UTF_8.newEncoder()); - Throwable throwable1 = null; - - try { - AdvancementDataPlayer.b.toJson(jsonelement, outputstreamwriter); - } catch (Throwable throwable2) { - throwable1 = throwable2; - throw throwable2; - } finally { - if (outputstreamwriter != null) { - if (throwable1 != null) { - try { - outputstreamwriter.close(); - } catch (Throwable throwable3) { - throwable1.addSuppressed(throwable3); - } - } else { - outputstreamwriter.close(); - } - } - - } - } catch (Throwable throwable4) { - throwable = throwable4; - throw throwable4; - } finally { - if (fileoutputstream != null) { - if (throwable != null) { - try { - fileoutputstream.close(); - } catch (Throwable throwable5) { - throwable.addSuppressed(throwable5); - } - } else { - fileoutputstream.close(); - } - } - - } - } catch (IOException ioexception) { - AdvancementDataPlayer.LOGGER.error("Couldn't save player advancements to {}", this.e, ioexception); - } - - } - - public boolean grantCriteria(Advancement advancement, String s) { - boolean flag = false; - AdvancementProgress advancementprogress = this.getProgress(advancement); - boolean flag1 = advancementprogress.isDone(); - - if (advancementprogress.a(s)) { - // Paper start - if (!new com.destroystokyo.paper.event.player.PlayerAdvancementCriterionGrantEvent(this.player.getBukkitEntity(), advancement.bukkit, s).callEvent()) { - advancementprogress.b(s); - return false; - } - // Paper end - this.d(advancement); - this.i.add(advancement); - flag = true; - if (!flag1 && advancementprogress.isDone()) { - this.player.world.getServer().getPluginManager().callEvent(new org.bukkit.event.player.PlayerAdvancementDoneEvent(this.player.getBukkitEntity(), advancement.bukkit)); // CraftBukkit - advancement.d().a(this.player); - if (advancement.c() != null && advancement.c().i() && this.player.world.getGameRules().getBoolean(GameRules.ANNOUNCE_ADVANCEMENTS)) { - this.d.getPlayerList().sendMessage(new ChatMessage("chat.type.advancement." + advancement.c().e().a(), new Object[]{this.player.getScoreboardDisplayName(), advancement.j()})); - } - } - } - - if (advancementprogress.isDone()) { - this.e(advancement); - } - - return flag; - } - - public boolean revokeCritera(Advancement advancement, String s) { - boolean flag = false; - AdvancementProgress advancementprogress = this.getProgress(advancement); - - if (advancementprogress.b(s)) { - this.c(advancement); - this.i.add(advancement); - flag = true; - } - - if (!advancementprogress.b()) { - this.e(advancement); - } - - return flag; - } - - private void c(Advancement advancement) { - AdvancementProgress advancementprogress = this.getProgress(advancement); - - if (!advancementprogress.isDone()) { - Iterator iterator = advancement.getCriteria().entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - CriterionProgress criterionprogress = advancementprogress.getCriterionProgress((String) entry.getKey()); - - if (criterionprogress != null && !criterionprogress.a()) { - CriterionInstance criterioninstance = ((Criterion) entry.getValue()).a(); - - if (criterioninstance != null) { - CriterionTrigger criteriontrigger = CriterionTriggers.a(criterioninstance.a()); - - if (criteriontrigger != null) { - criteriontrigger.a(this, new CriterionTrigger.a<>(criterioninstance, advancement, (String) entry.getKey())); - } - } - } - } - - } - } - - private void d(Advancement advancement) { - AdvancementProgress advancementprogress = this.getProgress(advancement); - Iterator iterator = advancement.getCriteria().entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - CriterionProgress criterionprogress = advancementprogress.getCriterionProgress((String) entry.getKey()); - - if (criterionprogress != null && (criterionprogress.a() || advancementprogress.isDone())) { - CriterionInstance criterioninstance = ((Criterion) entry.getValue()).a(); - - if (criterioninstance != null) { - CriterionTrigger criteriontrigger = CriterionTriggers.a(criterioninstance.a()); - - if (criteriontrigger != null) { - criteriontrigger.b(this, new CriterionTrigger.a<>(criterioninstance, advancement, (String) entry.getKey())); - } - } - } - } - - } - - public void b(EntityPlayer entityplayer) { - if (this.l || !this.h.isEmpty() || !this.i.isEmpty()) { - Map map = Maps.newHashMap(); - Set set = Sets.newLinkedHashSet(); - Set set1 = Sets.newLinkedHashSet(); - Iterator iterator = this.i.iterator(); - - Advancement advancement; - - while (iterator.hasNext()) { - advancement = (Advancement) iterator.next(); - if (this.g.contains(advancement)) { - map.put(advancement.getName(), this.data.get(advancement)); - } - } - - iterator = this.h.iterator(); - - while (iterator.hasNext()) { - advancement = (Advancement) iterator.next(); - if (this.g.contains(advancement)) { - set.add(advancement); - } else { - set1.add(advancement.getName()); - } - } - - if (this.l || !map.isEmpty() || !set.isEmpty() || !set1.isEmpty()) { - entityplayer.playerConnection.sendPacket(new PacketPlayOutAdvancements(this.l, set, set1, map)); - this.h.clear(); - this.i.clear(); - } - } - - this.l = false; - } - - public void a(@Nullable Advancement advancement) { - Advancement advancement1 = this.k; - - if (advancement != null && advancement.b() == null && advancement.c() != null) { - this.k = advancement; - } else { - this.k = null; - } - - if (advancement1 != this.k) { - this.player.playerConnection.sendPacket(new PacketPlayOutSelectAdvancementTab(this.k == null ? null : this.k.getName())); - } - - } - - public AdvancementProgress getProgress(Advancement advancement) { - AdvancementProgress advancementprogress = (AdvancementProgress) this.data.get(advancement); - - if (advancementprogress == null) { - advancementprogress = new AdvancementProgress(); - this.a(advancement, advancementprogress); - } - - return advancementprogress; - } - - private void a(Advancement advancement, AdvancementProgress advancementprogress) { - advancementprogress.a(advancement.getCriteria(), advancement.i()); - this.data.put(advancement, advancementprogress); - } - - private void e(Advancement advancement) { - boolean flag = this.f(advancement); - boolean flag1 = this.g.contains(advancement); - - if (flag && !flag1) { - this.g.add(advancement); - this.h.add(advancement); - if (this.data.containsKey(advancement)) { - this.i.add(advancement); - } - } else if (!flag && flag1) { - this.g.remove(advancement); - this.h.add(advancement); - } - - if (flag != flag1 && advancement.b() != null) { - this.e(advancement.b()); - } - - Iterator iterator = advancement.e().iterator(); - - while (iterator.hasNext()) { - Advancement advancement1 = (Advancement) iterator.next(); - - this.e(advancement1); - } - - } - - private boolean f(Advancement advancement) { - for (int i = 0; advancement != null && i <= 2; ++i) { - if (i == 0 && this.g(advancement)) { - return true; - } - - if (advancement.c() == null) { - return false; - } - - AdvancementProgress advancementprogress = this.getProgress(advancement); - - if (advancementprogress.isDone()) { - return true; - } - - if (advancement.c().j()) { - return false; - } - - advancement = advancement.b(); - } - - return false; - } - - private boolean g(Advancement advancement) { - AdvancementProgress advancementprogress = this.getProgress(advancement); - - if (advancementprogress.isDone()) { - return true; - } else { - Iterator iterator = advancement.e().iterator(); - - Advancement advancement1; - - do { - if (!iterator.hasNext()) { - return false; - } - - advancement1 = (Advancement) iterator.next(); - } while (!this.g(advancement1)); - - return true; - } - } -} diff --git a/src/main/java/net/minecraft/server/AdvancementDataWorld.java b/src/main/java/net/minecraft/server/AdvancementDataWorld.java deleted file mode 100644 index 54f6331ec..000000000 --- a/src/main/java/net/minecraft/server/AdvancementDataWorld.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import java.lang.reflect.Type; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class AdvancementDataWorld extends ResourceDataJson { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final Gson DESERIALIZER = (new GsonBuilder()).registerTypeHierarchyAdapter(Advancement.SerializedAdvancement.class, (com.google.gson.JsonDeserializer) (jsonelement, type, jsondeserializationcontext) -> { - JsonObject jsonobject = ChatDeserializer.m(jsonelement, "advancement"); - - return Advancement.SerializedAdvancement.a(jsonobject, jsondeserializationcontext); - }).registerTypeAdapter(AdvancementRewards.class, new AdvancementRewards.b()).registerTypeHierarchyAdapter(IChatBaseComponent.class, new IChatBaseComponent.ChatSerializer()).registerTypeHierarchyAdapter(ChatModifier.class, new ChatModifier.ChatModifierSerializer()).registerTypeAdapterFactory(new ChatTypeAdapterFactory()).create(); - public Advancements REGISTRY = new Advancements(); - - public AdvancementDataWorld() { - super(AdvancementDataWorld.DESERIALIZER, "advancements"); - } - - protected void a(Map map, IResourceManager iresourcemanager, GameProfilerFiller gameprofilerfiller) { - Map map1 = Maps.newHashMap(); - - map.forEach((minecraftkey, jsonobject) -> { - // Spigot start - if (org.spigotmc.SpigotConfig.disabledAdvancements != null && (org.spigotmc.SpigotConfig.disabledAdvancements.contains("*") || org.spigotmc.SpigotConfig.disabledAdvancements.contains(minecraftkey.toString()))) { - return; - } - // Spigot end - - try { - Advancement.SerializedAdvancement advancement_serializedadvancement = (Advancement.SerializedAdvancement) AdvancementDataWorld.DESERIALIZER.fromJson(jsonobject, Advancement.SerializedAdvancement.class); - - map1.put(minecraftkey, advancement_serializedadvancement); - } catch (IllegalArgumentException | JsonParseException jsonparseexception) { - AdvancementDataWorld.LOGGER.error("Parsing error loading custom advancement {}: {}", minecraftkey, jsonparseexception.getMessage()); - } - - }); - Advancements advancements = new Advancements(); - - advancements.a((Map) map1); - Iterator iterator = advancements.b().iterator(); - - while (iterator.hasNext()) { - Advancement advancement = (Advancement) iterator.next(); - - if (advancement.c() != null) { - AdvancementTree.a(advancement); - } - } - - this.REGISTRY = advancements; - } - - @Nullable - public Advancement a(MinecraftKey minecraftkey) { - return this.REGISTRY.a(minecraftkey); - } - - public Collection a() { - return this.REGISTRY.c(); - } -} diff --git a/src/main/java/net/minecraft/server/Advancements.java b/src/main/java/net/minecraft/server/Advancements.java deleted file mode 100644 index bc043ad4f..000000000 --- a/src/main/java/net/minecraft/server/Advancements.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class Advancements { - - private static final Logger LOGGER = LogManager.getLogger(); - public final Map advancements = Maps.newHashMap(); - private final Set c = Sets.newLinkedHashSet(); - private final Set d = Sets.newLinkedHashSet(); - private Advancements.a e; - - public Advancements() {} - - public void a(Map map) { - Function function = Functions.forMap(this.advancements, (Object) null); - - label42: - while (!map.isEmpty()) { - boolean flag = false; - Iterator iterator = map.entrySet().iterator(); - - Entry entry; - - while (iterator.hasNext()) { - entry = (Entry) iterator.next(); - MinecraftKey minecraftkey = (MinecraftKey) entry.getKey(); - Advancement.SerializedAdvancement advancement_serializedadvancement = (Advancement.SerializedAdvancement) entry.getValue(); - - if (advancement_serializedadvancement.a((java.util.function.Function) function)) { - Advancement advancement = advancement_serializedadvancement.b(minecraftkey); - - this.advancements.put(minecraftkey, advancement); - flag = true; - iterator.remove(); - if (advancement.b() == null) { - this.c.add(advancement); - if (this.e != null) { - this.e.a(advancement); - } - } else { - this.d.add(advancement); - if (this.e != null) { - this.e.c(advancement); - } - } - } - } - - if (!flag) { - iterator = map.entrySet().iterator(); - - while (true) { - if (!iterator.hasNext()) { - break label42; - } - - entry = (Entry) iterator.next(); - Advancements.LOGGER.error("Couldn't load advancement {}: {}", entry.getKey(), entry.getValue()); - } - } - } - - // Advancements.LOGGER.info("Loaded {} advancements", this.advancements.size()); // CraftBukkit - moved to AdvancementDataWorld#reload - } - - public Iterable b() { - return this.c; - } - - public Collection c() { - return this.advancements.values(); - } - - @Nullable - public Advancement a(MinecraftKey minecraftkey) { - return (Advancement) this.advancements.get(minecraftkey); - } - - public interface a { - - void a(Advancement advancement); - - void c(Advancement advancement); - } -} diff --git a/src/main/java/net/minecraft/server/ArgumentBlock.java b/src/main/java/net/minecraft/server/ArgumentBlock.java deleted file mode 100644 index 97d85f845..000000000 --- a/src/main/java/net/minecraft/server/ArgumentBlock.java +++ /dev/null @@ -1,535 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.google.common.collect.UnmodifiableIterator; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType; -import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType; -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import com.mojang.brigadier.suggestion.Suggestions; -import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.Map.Entry; -import java.util.concurrent.CompletableFuture; -import java.util.function.Function; -import javax.annotation.Nullable; - -public class ArgumentBlock { - - public static final SimpleCommandExceptionType a = new SimpleCommandExceptionType(new ChatMessage("argument.block.tag.disallowed", new Object[0])); - public static final DynamicCommandExceptionType b = new DynamicCommandExceptionType((object) -> { - return new ChatMessage("argument.block.id.invalid", new Object[]{object}); - }); - public static final Dynamic2CommandExceptionType c = new Dynamic2CommandExceptionType((object, object1) -> { - return new ChatMessage("argument.block.property.unknown", new Object[]{object, object1}); - }); - public static final Dynamic2CommandExceptionType d = new Dynamic2CommandExceptionType((object, object1) -> { - return new ChatMessage("argument.block.property.duplicate", new Object[]{object1, object}); - }); - public static final Dynamic3CommandExceptionType e = new Dynamic3CommandExceptionType((object, object1, object2) -> { - return new ChatMessage("argument.block.property.invalid", new Object[]{object, object2, object1}); - }); - public static final Dynamic2CommandExceptionType f = new Dynamic2CommandExceptionType((object, object1) -> { - return new ChatMessage("argument.block.property.novalue", new Object[]{object, object1}); - }); - public static final SimpleCommandExceptionType g = new SimpleCommandExceptionType(new ChatMessage("argument.block.property.unclosed", new Object[0])); - private static final Function> h = SuggestionsBuilder::buildFuture; - private final StringReader i; - private final boolean j; - private final Map, Comparable> k = Maps.newLinkedHashMap(); // CraftBukkit - stable - private final Map l = Maps.newHashMap(); - private MinecraftKey m = new MinecraftKey(""); public MinecraftKey getBlockKey() { return this.m; } // Paper - OBFHELPER - private BlockStateList n; - private IBlockData o; - @Nullable - private NBTTagCompound p; - private MinecraftKey q = new MinecraftKey(""); - private int r; - private Function> s; - - public ArgumentBlock(StringReader stringreader, boolean flag) { - this.s = ArgumentBlock.h; - this.i = stringreader; - this.j = flag; - } - - public Map, Comparable> getStateMap() { - return this.k; - } - - @Nullable - public IBlockData getBlockData() { - return this.o; - } - - @Nullable - public NBTTagCompound c() { - return this.p; - } - - public @Nullable MinecraftKey getTagKey() { return d(); } // Paper - OBFHELPER - @Nullable - public MinecraftKey d() { - return this.q; - } - - public ArgumentBlock parse(boolean parseTile) throws CommandSyntaxException { return this.a(parseTile); } // Paper - OBFHELPER - public ArgumentBlock a(boolean flag) throws CommandSyntaxException { - this.s = this::l; - if (this.i.canRead() && this.i.peek() == '#') { - this.f(); - this.s = this::i; - if (this.i.canRead() && this.i.peek() == '[') { - this.h(); - this.s = this::f; - } - } else { - this.e(); - this.s = this::j; - if (this.i.canRead() && this.i.peek() == '[') { - this.g(); - this.s = this::f; - } - } - - if (flag && this.i.canRead() && this.i.peek() == '{') { - this.s = ArgumentBlock.h; - this.i(); - } - - return this; - } - - private CompletableFuture b(SuggestionsBuilder suggestionsbuilder) { - if (suggestionsbuilder.getRemaining().isEmpty()) { - suggestionsbuilder.suggest(String.valueOf(']')); - } - - return this.d(suggestionsbuilder); - } - - private CompletableFuture c(SuggestionsBuilder suggestionsbuilder) { - if (suggestionsbuilder.getRemaining().isEmpty()) { - suggestionsbuilder.suggest(String.valueOf(']')); - } - - return this.e(suggestionsbuilder); - } - - private CompletableFuture d(SuggestionsBuilder suggestionsbuilder) { - String s = suggestionsbuilder.getRemaining().toLowerCase(Locale.ROOT); - Iterator iterator = this.o.a().iterator(); - - while (iterator.hasNext()) { - IBlockState iblockstate = (IBlockState) iterator.next(); - - if (!this.k.containsKey(iblockstate) && iblockstate.a().startsWith(s)) { - suggestionsbuilder.suggest(iblockstate.a() + '='); - } - } - - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture e(SuggestionsBuilder suggestionsbuilder) { - String s = suggestionsbuilder.getRemaining().toLowerCase(Locale.ROOT); - - if (this.q != null && !this.q.getKey().isEmpty()) { - Tag tag = TagsBlock.a().a(this.q); - - if (tag != null) { - Iterator iterator = tag.a().iterator(); - - while (iterator.hasNext()) { - Block block = (Block) iterator.next(); - Iterator iterator1 = block.getStates().d().iterator(); - - while (iterator1.hasNext()) { - IBlockState iblockstate = (IBlockState) iterator1.next(); - - if (!this.l.containsKey(iblockstate.a()) && iblockstate.a().startsWith(s)) { - suggestionsbuilder.suggest(iblockstate.a() + '='); - } - } - } - } - } - - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture f(SuggestionsBuilder suggestionsbuilder) { - if (suggestionsbuilder.getRemaining().isEmpty() && this.k()) { - suggestionsbuilder.suggest(String.valueOf('{')); - } - - return suggestionsbuilder.buildFuture(); - } - - private boolean k() { - if (this.o != null) { - return this.o.getBlock().isTileEntity(); - } else { - if (this.q != null) { - Tag tag = TagsBlock.a().a(this.q); - - if (tag != null) { - Iterator iterator = tag.a().iterator(); - - while (iterator.hasNext()) { - Block block = (Block) iterator.next(); - - if (block.isTileEntity()) { - return true; - } - } - } - } - - return false; - } - } - - private CompletableFuture g(SuggestionsBuilder suggestionsbuilder) { - if (suggestionsbuilder.getRemaining().isEmpty()) { - suggestionsbuilder.suggest(String.valueOf('=')); - } - - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture h(SuggestionsBuilder suggestionsbuilder) { - if (suggestionsbuilder.getRemaining().isEmpty()) { - suggestionsbuilder.suggest(String.valueOf(']')); - } - - if (suggestionsbuilder.getRemaining().isEmpty() && this.k.size() < this.o.a().size()) { - suggestionsbuilder.suggest(String.valueOf(',')); - } - - return suggestionsbuilder.buildFuture(); - } - - private static > SuggestionsBuilder a(SuggestionsBuilder suggestionsbuilder, IBlockState iblockstate) { - Iterator iterator = iblockstate.getValues().iterator(); - - while (iterator.hasNext()) { - T t0 = (T) iterator.next(); // CraftBukkit - decompile error - - if (t0 instanceof Integer) { - suggestionsbuilder.suggest((Integer) t0); - } else { - suggestionsbuilder.suggest(iblockstate.a(t0)); - } - } - - return suggestionsbuilder; - } - - private CompletableFuture a(SuggestionsBuilder suggestionsbuilder, String s) { - boolean flag = false; - - if (this.q != null && !this.q.getKey().isEmpty()) { - Tag tag = TagsBlock.a().a(this.q); - - if (tag != null) { - Iterator iterator = tag.a().iterator(); - - while (iterator.hasNext()) { - Block block = (Block) iterator.next(); - IBlockState iblockstate = block.getStates().a(s); - - if (iblockstate != null) { - a(suggestionsbuilder, iblockstate); - } - - if (!flag) { - Iterator iterator1 = block.getStates().d().iterator(); - - while (iterator1.hasNext()) { - IBlockState iblockstate1 = (IBlockState) iterator1.next(); - - if (!this.l.containsKey(iblockstate1.a())) { - flag = true; - break; - } - } - } - } - } - } - - if (flag) { - suggestionsbuilder.suggest(String.valueOf(',')); - } - - suggestionsbuilder.suggest(String.valueOf(']')); - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture i(SuggestionsBuilder suggestionsbuilder) { - if (suggestionsbuilder.getRemaining().isEmpty()) { - Tag tag = TagsBlock.a().a(this.q); - - if (tag != null) { - boolean flag = false; - boolean flag1 = false; - Iterator iterator = tag.a().iterator(); - - while (iterator.hasNext()) { - Block block = (Block) iterator.next(); - - flag |= !block.getStates().d().isEmpty(); - flag1 |= block.isTileEntity(); - if (flag && flag1) { - break; - } - } - - if (flag) { - suggestionsbuilder.suggest(String.valueOf('[')); - } - - if (flag1) { - suggestionsbuilder.suggest(String.valueOf('{')); - } - } - } - - return this.k(suggestionsbuilder); - } - - private CompletableFuture j(SuggestionsBuilder suggestionsbuilder) { - if (suggestionsbuilder.getRemaining().isEmpty()) { - if (!this.o.getBlock().getStates().d().isEmpty()) { - suggestionsbuilder.suggest(String.valueOf('[')); - } - - if (this.o.getBlock().isTileEntity()) { - suggestionsbuilder.suggest(String.valueOf('{')); - } - } - - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture k(SuggestionsBuilder suggestionsbuilder) { - return ICompletionProvider.a((Iterable) TagsBlock.a().a(), suggestionsbuilder.createOffset(this.r).add(suggestionsbuilder)); - } - - private CompletableFuture l(SuggestionsBuilder suggestionsbuilder) { - if (this.j) { - ICompletionProvider.a((Iterable) TagsBlock.a().a(), suggestionsbuilder, String.valueOf('#')); - } - - ICompletionProvider.a((Iterable) IRegistry.BLOCK.keySet(), suggestionsbuilder); - return suggestionsbuilder.buildFuture(); - } - - public void e() throws CommandSyntaxException { - int i = this.i.getCursor(); - - this.m = MinecraftKey.a(this.i); - Block block = (Block) IRegistry.BLOCK.getOptional(this.m).orElseThrow(() -> { - this.i.setCursor(i); - return ArgumentBlock.b.createWithContext(this.i, this.m.toString()); - }); - - this.n = block.getStates(); - this.o = block.getBlockData(); - } - - public void f() throws CommandSyntaxException { - if (!this.j) { - throw ArgumentBlock.a.create(); - } else { - this.s = this::k; - this.i.expect('#'); - this.r = this.i.getCursor(); - this.q = MinecraftKey.a(this.i); - } - } - - public void g() throws CommandSyntaxException { - this.i.skip(); - this.s = this::b; - this.i.skipWhitespace(); - - while (true) { - if (this.i.canRead() && this.i.peek() != ']') { - this.i.skipWhitespace(); - int i = this.i.getCursor(); - String s = this.i.readString(); - IBlockState iblockstate = this.n.a(s); - - if (iblockstate == null) { - this.i.setCursor(i); - throw ArgumentBlock.c.createWithContext(this.i, this.m.toString(), s); - } - - if (this.k.containsKey(iblockstate)) { - this.i.setCursor(i); - throw ArgumentBlock.d.createWithContext(this.i, this.m.toString(), s); - } - - this.i.skipWhitespace(); - this.s = this::g; - if (!this.i.canRead() || this.i.peek() != '=') { - throw ArgumentBlock.f.createWithContext(this.i, this.m.toString(), s); - } - - this.i.skip(); - this.i.skipWhitespace(); - this.s = (suggestionsbuilder) -> { - return a(suggestionsbuilder, iblockstate).buildFuture(); - }; - int j = this.i.getCursor(); - - this.a(iblockstate, this.i.readString(), j); - this.s = this::h; - this.i.skipWhitespace(); - if (!this.i.canRead()) { - continue; - } - - if (this.i.peek() == ',') { - this.i.skip(); - this.s = this::d; - continue; - } - - if (this.i.peek() != ']') { - throw ArgumentBlock.g.createWithContext(this.i); - } - } - - if (this.i.canRead()) { - this.i.skip(); - return; - } - - throw ArgumentBlock.g.createWithContext(this.i); - } - } - - public void h() throws CommandSyntaxException { - this.i.skip(); - this.s = this::c; - int i = -1; - - this.i.skipWhitespace(); - - while (true) { - if (this.i.canRead() && this.i.peek() != ']') { - this.i.skipWhitespace(); - int j = this.i.getCursor(); - String s = this.i.readString(); - - if (this.l.containsKey(s)) { - this.i.setCursor(j); - throw ArgumentBlock.d.createWithContext(this.i, this.m.toString(), s); - } - - this.i.skipWhitespace(); - if (!this.i.canRead() || this.i.peek() != '=') { - this.i.setCursor(j); - throw ArgumentBlock.f.createWithContext(this.i, this.m.toString(), s); - } - - this.i.skip(); - this.i.skipWhitespace(); - this.s = (suggestionsbuilder) -> { - return this.a(suggestionsbuilder, s); - }; - i = this.i.getCursor(); - String s1 = this.i.readString(); - - this.l.put(s, s1); - this.i.skipWhitespace(); - if (!this.i.canRead()) { - continue; - } - - i = -1; - if (this.i.peek() == ',') { - this.i.skip(); - this.s = this::e; - continue; - } - - if (this.i.peek() != ']') { - throw ArgumentBlock.g.createWithContext(this.i); - } - } - - if (this.i.canRead()) { - this.i.skip(); - return; - } - - if (i >= 0) { - this.i.setCursor(i); - } - - throw ArgumentBlock.g.createWithContext(this.i); - } - } - - public void i() throws CommandSyntaxException { - this.p = (new MojangsonParser(this.i)).f(); - } - - private > void a(IBlockState iblockstate, String s, int i) throws CommandSyntaxException { - Optional optional = iblockstate.b(s); - - if (optional.isPresent()) { - this.o = (IBlockData) this.o.set(iblockstate, (T) optional.get()); // CraftBukkit - decompile error - this.k.put(iblockstate, optional.get()); - } else { - this.i.setCursor(i); - throw ArgumentBlock.e.createWithContext(this.i, this.m.toString(), iblockstate.a(), s); - } - } - - public static String a(IBlockData iblockdata) { - StringBuilder stringbuilder = new StringBuilder(IRegistry.BLOCK.getKey(iblockdata.getBlock()).toString()); - - if (!iblockdata.a().isEmpty()) { - stringbuilder.append('['); - boolean flag = false; - - for (UnmodifiableIterator unmodifiableiterator = iblockdata.getStateMap().entrySet().iterator(); unmodifiableiterator.hasNext(); flag = true) { - Entry, Comparable> entry = (Entry) unmodifiableiterator.next(); - - if (flag) { - stringbuilder.append(','); - } - - a(stringbuilder, (IBlockState) entry.getKey(), (Comparable) entry.getValue()); - } - - stringbuilder.append(']'); - } - - return stringbuilder.toString(); - } - - private static > void a(StringBuilder stringbuilder, IBlockState iblockstate, Comparable comparable) { - stringbuilder.append(iblockstate.a()); - stringbuilder.append('='); - stringbuilder.append(iblockstate.a((T) comparable)); // CraftBukkit - decompile error - } - - public CompletableFuture a(SuggestionsBuilder suggestionsbuilder) { - return (CompletableFuture) this.s.apply(suggestionsbuilder.createOffset(this.i.getCursor())); - } - - public Map j() { - return this.l; - } -} diff --git a/src/main/java/net/minecraft/server/ArgumentEntity.java b/src/main/java/net/minecraft/server/ArgumentEntity.java deleted file mode 100644 index 39a6a9ac0..000000000 --- a/src/main/java/net/minecraft/server/ArgumentEntity.java +++ /dev/null @@ -1,172 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Iterables; -import com.google.gson.JsonObject; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import com.mojang.brigadier.suggestion.Suggestions; -import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.CompletableFuture; - -public class ArgumentEntity implements ArgumentType { - - private static final Collection g = Arrays.asList("Player", "0123", "@e", "@e[type=foo]", "dd12be42-52a9-4a91-a8a1-11c01849e498"); - public static final SimpleCommandExceptionType a = new SimpleCommandExceptionType(new ChatMessage("argument.entity.toomany", new Object[0])); - public static final SimpleCommandExceptionType b = new SimpleCommandExceptionType(new ChatMessage("argument.player.toomany", new Object[0])); - public static final SimpleCommandExceptionType c = new SimpleCommandExceptionType(new ChatMessage("argument.player.entities", new Object[0])); - public static final SimpleCommandExceptionType d = new SimpleCommandExceptionType(new ChatMessage("argument.entity.notfound.entity", new Object[0])); - public static final SimpleCommandExceptionType e = new SimpleCommandExceptionType(new ChatMessage("argument.entity.notfound.player", new Object[0])); - public static final SimpleCommandExceptionType f = new SimpleCommandExceptionType(new ChatMessage("argument.entity.selector.not_allowed", new Object[0])); - private final boolean h; - private final boolean i; - - protected ArgumentEntity(boolean flag, boolean flag1) { - this.h = flag; - this.i = flag1; - } - - public static ArgumentEntity a() { - return new ArgumentEntity(true, false); - } - - public static Entity a(CommandContext commandcontext, String s) throws CommandSyntaxException { - return ((EntitySelector) commandcontext.getArgument(s, EntitySelector.class)).a((CommandListenerWrapper) commandcontext.getSource()); - } - - public static ArgumentEntity multipleEntities() { - return new ArgumentEntity(false, false); - } - - public static Collection b(CommandContext commandcontext, String s) throws CommandSyntaxException { - Collection collection = c(commandcontext, s); - - if (collection.isEmpty()) { - throw ArgumentEntity.d.create(); - } else { - return collection; - } - } - - public static Collection c(CommandContext commandcontext, String s) throws CommandSyntaxException { - return ((EntitySelector) commandcontext.getArgument(s, EntitySelector.class)).getEntities((CommandListenerWrapper) commandcontext.getSource()); - } - - public static Collection d(CommandContext commandcontext, String s) throws CommandSyntaxException { - return ((EntitySelector) commandcontext.getArgument(s, EntitySelector.class)).d((CommandListenerWrapper) commandcontext.getSource()); - } - - public static ArgumentEntity c() { - return new ArgumentEntity(true, true); - } - - public static EntityPlayer e(CommandContext commandcontext, String s) throws CommandSyntaxException { - return ((EntitySelector) commandcontext.getArgument(s, EntitySelector.class)).c((CommandListenerWrapper) commandcontext.getSource()); - } - - public static ArgumentEntity d() { - return new ArgumentEntity(false, true); - } - - public static Collection f(CommandContext commandcontext, String s) throws CommandSyntaxException { - List list = ((EntitySelector) commandcontext.getArgument(s, EntitySelector.class)).d((CommandListenerWrapper) commandcontext.getSource()); - - if (list.isEmpty()) { - throw ArgumentEntity.e.create(); - } else { - return list; - } - } - - public EntitySelector parse(StringReader stringreader) throws CommandSyntaxException { - // CraftBukkit start - return parse(stringreader, false); - } - - public EntitySelector parse(StringReader stringreader, boolean overridePermissions) throws CommandSyntaxException { - // CraftBukkit end - boolean flag = false; - ArgumentParserSelector argumentparserselector = new ArgumentParserSelector(stringreader); - EntitySelector entityselector = argumentparserselector.parse(overridePermissions); // CraftBukkit - - if (entityselector.a() > 1 && this.h) { - if (this.i) { - stringreader.setCursor(0); - throw ArgumentEntity.b.createWithContext(stringreader); - } else { - stringreader.setCursor(0); - throw ArgumentEntity.a.createWithContext(stringreader); - } - } else if (entityselector.b() && this.i && !entityselector.c()) { - stringreader.setCursor(0); - throw ArgumentEntity.c.createWithContext(stringreader); - } else { - return entityselector; - } - } - - public CompletableFuture listSuggestions(CommandContext commandcontext, SuggestionsBuilder suggestionsbuilder) { - if (commandcontext.getSource() instanceof ICompletionProvider) { - StringReader stringreader = new StringReader(suggestionsbuilder.getInput()); - - stringreader.setCursor(suggestionsbuilder.getStart()); - ICompletionProvider icompletionprovider = (ICompletionProvider) commandcontext.getSource(); - ArgumentParserSelector argumentparserselector = new ArgumentParserSelector(stringreader, icompletionprovider.hasPermission(2)); - - try { - argumentparserselector.parse(); - } catch (CommandSyntaxException commandsyntaxexception) { - ; - } - - return argumentparserselector.a(suggestionsbuilder, (suggestionsbuilder1) -> { - Collection collection = icompletionprovider.l(); - Iterable iterable = this.i ? collection : Iterables.concat(collection, icompletionprovider.p()); - - ICompletionProvider.b((Iterable) iterable, suggestionsbuilder1); - }); - } else { - return Suggestions.empty(); - } - } - - public Collection getExamples() { - return ArgumentEntity.g; - } - - public static class a implements ArgumentSerializer { - - public a() {} - - public void a(ArgumentEntity argumententity, PacketDataSerializer packetdataserializer) { - byte b0 = 0; - - if (argumententity.h) { - b0 = (byte) (b0 | 1); - } - - if (argumententity.i) { - b0 = (byte) (b0 | 2); - } - - packetdataserializer.writeByte(b0); - } - - @Override - public ArgumentEntity b(PacketDataSerializer packetdataserializer) { - byte b0 = packetdataserializer.readByte(); - - return new ArgumentEntity((b0 & 1) != 0, (b0 & 2) != 0); - } - - public void a(ArgumentEntity argumententity, JsonObject jsonobject) { - jsonobject.addProperty("amount", argumententity.h ? "single" : "multiple"); - jsonobject.addProperty("type", argumententity.i ? "players" : "entities"); - } - } -} diff --git a/src/main/java/net/minecraft/server/ArgumentParserSelector.java b/src/main/java/net/minecraft/server/ArgumentParserSelector.java deleted file mode 100644 index 75db3678a..000000000 --- a/src/main/java/net/minecraft/server/ArgumentParserSelector.java +++ /dev/null @@ -1,628 +0,0 @@ -package net.minecraft.server; - -import com.google.common.primitives.Doubles; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import com.mojang.brigadier.suggestion.Suggestions; -import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.function.BiConsumer; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.function.ToDoubleFunction; -import javax.annotation.Nullable; - -public class ArgumentParserSelector { - - public static final SimpleCommandExceptionType a = new SimpleCommandExceptionType(new ChatMessage("argument.entity.invalid", new Object[0])); - public static final DynamicCommandExceptionType b = new DynamicCommandExceptionType((object) -> { - return new ChatMessage("argument.entity.selector.unknown", new Object[]{object}); - }); - public static final SimpleCommandExceptionType c = new SimpleCommandExceptionType(new ChatMessage("argument.entity.selector.not_allowed", new Object[0])); - public static final SimpleCommandExceptionType d = new SimpleCommandExceptionType(new ChatMessage("argument.entity.selector.missing", new Object[0])); - public static final SimpleCommandExceptionType e = new SimpleCommandExceptionType(new ChatMessage("argument.entity.options.unterminated", new Object[0])); - public static final DynamicCommandExceptionType f = new DynamicCommandExceptionType((object) -> { - return new ChatMessage("argument.entity.options.valueless", new Object[]{object}); - }); - public static final BiConsumer> g = (vec3d, list) -> { - }; - public static final BiConsumer> h = (vec3d, list) -> { - list.sort((entity, entity1) -> { - return Doubles.compare(entity.c(vec3d), entity1.c(vec3d)); - }); - }; - public static final BiConsumer> i = (vec3d, list) -> { - list.sort((entity, entity1) -> { - return Doubles.compare(entity1.c(vec3d), entity.c(vec3d)); - }); - }; - public static final BiConsumer> j = (vec3d, list) -> { - Collections.shuffle(list); - }; - public static final BiFunction, CompletableFuture> k = (suggestionsbuilder, consumer) -> { - return suggestionsbuilder.buildFuture(); - }; - private final StringReader l; - private final boolean m; - private int n; - private boolean o; - private boolean p; - private CriterionConditionValue.FloatRange q; - private CriterionConditionValue.IntegerRange r; - @Nullable - private Double s; - @Nullable - private Double t; - @Nullable - private Double u; - @Nullable - private Double v; - @Nullable - private Double w; - @Nullable - private Double x; - private CriterionConditionRange y; - private CriterionConditionRange z; - private Predicate A; - private BiConsumer> B; - private boolean C; - @Nullable - private String D; - private int E; - @Nullable - private UUID F; - private BiFunction, CompletableFuture> G; - private boolean H; - private boolean I; - private boolean J; - private boolean K; - private boolean L; - private boolean M; - private boolean N; - private boolean O; - @Nullable - private EntityTypes P; - private boolean Q; - private boolean R; - private boolean S; - private boolean checkPermissions; - - public ArgumentParserSelector(StringReader stringreader) { - this(stringreader, true); - } - - public ArgumentParserSelector(StringReader stringreader, boolean flag) { - this.q = CriterionConditionValue.FloatRange.e; - this.r = CriterionConditionValue.IntegerRange.e; - this.y = CriterionConditionRange.a; - this.z = CriterionConditionRange.a; - this.A = (entity) -> { - return true; - }; - this.B = ArgumentParserSelector.g; - this.G = ArgumentParserSelector.k; - this.l = stringreader; - this.m = flag; - } - - public EntitySelector a() { - AxisAlignedBB axisalignedbb; - - if (this.v == null && this.w == null && this.x == null) { - if (this.q.b() != null) { - float f = (Float) this.q.b(); - - axisalignedbb = new AxisAlignedBB((double) (-f), (double) (-f), (double) (-f), (double) (f + 1.0F), (double) (f + 1.0F), (double) (f + 1.0F)); - } else { - axisalignedbb = null; - } - } else { - axisalignedbb = this.a(this.v == null ? 0.0D : this.v, this.w == null ? 0.0D : this.w, this.x == null ? 0.0D : this.x); - } - - Function function; // CraftBukkit - decompile error - - if (this.s == null && this.t == null && this.u == null) { - function = (vec3d) -> { - return vec3d; - }; - } else { - function = (vec3d) -> { - return new Vec3D(this.s == null ? vec3d.x : this.s, this.t == null ? vec3d.y : this.t, this.u == null ? vec3d.z : this.u); - }; - } - - return new EntitySelector(this.n, this.o, this.p, this.A, this.q, function, axisalignedbb, this.B, this.C, this.D, this.F, this.P, this.checkPermissions); - } - - private AxisAlignedBB a(double d0, double d1, double d2) { - boolean flag = d0 < 0.0D; - boolean flag1 = d1 < 0.0D; - boolean flag2 = d2 < 0.0D; - double d3 = flag ? d0 : 0.0D; - double d4 = flag1 ? d1 : 0.0D; - double d5 = flag2 ? d2 : 0.0D; - double d6 = (flag ? 0.0D : d0) + 1.0D; - double d7 = (flag1 ? 0.0D : d1) + 1.0D; - double d8 = (flag2 ? 0.0D : d2) + 1.0D; - - return new AxisAlignedBB(d3, d4, d5, d6, d7, d8); - } - - private void I() { - if (this.y != CriterionConditionRange.a) { - this.A = this.A.and(this.a(this.y, (entity) -> { - return (double) entity.pitch; - })); - } - - if (this.z != CriterionConditionRange.a) { - this.A = this.A.and(this.a(this.z, (entity) -> { - return (double) entity.yaw; - })); - } - - if (!this.r.c()) { - this.A = this.A.and((entity) -> { - return !(entity instanceof EntityPlayer) ? false : this.r.d(((EntityPlayer) entity).expLevel); - }); - } - - } - - private Predicate a(CriterionConditionRange criterionconditionrange, ToDoubleFunction todoublefunction) { - double d0 = (double) MathHelper.g(criterionconditionrange.a() == null ? 0.0F : criterionconditionrange.a()); - double d1 = (double) MathHelper.g(criterionconditionrange.b() == null ? 359.0F : criterionconditionrange.b()); - - return (entity) -> { - double d2 = MathHelper.g(todoublefunction.applyAsDouble(entity)); - - return d0 > d1 ? d2 >= d0 || d2 <= d1 : d2 >= d0 && d2 <= d1; - }; - } - - // CraftBukkit start - protected void parseSelector(boolean overridePermissions) throws CommandSyntaxException { - this.checkPermissions = !overridePermissions; - // CraftBukkit end - this.G = this::d; - if (!this.l.canRead()) { - throw ArgumentParserSelector.d.createWithContext(this.l); - } else { - int i = this.l.getCursor(); - char c0 = this.l.read(); - - if (c0 == 'p') { - this.n = 1; - this.o = false; - this.B = ArgumentParserSelector.h; - this.a(EntityTypes.PLAYER); - } else if (c0 == 'a') { - this.n = Integer.MAX_VALUE; - this.o = false; - this.B = ArgumentParserSelector.g; - this.a(EntityTypes.PLAYER); - } else if (c0 == 'r') { - this.n = 1; - this.o = false; - this.B = ArgumentParserSelector.j; - this.a(EntityTypes.PLAYER); - } else if (c0 == 's') { - this.n = 1; - this.o = true; - this.C = true; - } else { - if (c0 != 'e') { - this.l.setCursor(i); - throw ArgumentParserSelector.b.createWithContext(this.l, '@' + String.valueOf(c0)); - } - - this.n = Integer.MAX_VALUE; - this.o = true; - this.B = ArgumentParserSelector.g; - this.A = Entity::isAlive; - } - - this.G = this::e; - if (this.l.canRead() && this.l.peek() == '[') { - this.l.skip(); - this.G = this::f; - this.d(); - } - - } - } - - protected void c() throws CommandSyntaxException { - if (this.l.canRead()) { - this.G = this::c; - } - - int i = this.l.getCursor(); - String s = this.l.readString(); - - try { - this.F = UUID.fromString(s); - this.o = true; - } catch (IllegalArgumentException illegalargumentexception) { - if (s.isEmpty() || s.length() > 16) { - this.l.setCursor(i); - throw ArgumentParserSelector.a.createWithContext(this.l); - } - - this.o = false; - this.D = s; - } - - this.n = 1; - } - - protected void d() throws CommandSyntaxException { - this.G = this::g; - this.l.skipWhitespace(); - - while (true) { - if (this.l.canRead() && this.l.peek() != ']') { - this.l.skipWhitespace(); - int i = this.l.getCursor(); - String s = this.l.readString(); - PlayerSelector.a playerselector_a = PlayerSelector.a(this, s, i); - - this.l.skipWhitespace(); - if (!this.l.canRead() || this.l.peek() != '=') { - this.l.setCursor(i); - throw ArgumentParserSelector.f.createWithContext(this.l, s); - } - - this.l.skip(); - this.l.skipWhitespace(); - this.G = ArgumentParserSelector.k; - playerselector_a.handle(this); - this.l.skipWhitespace(); - this.G = this::h; - if (!this.l.canRead()) { - continue; - } - - if (this.l.peek() == ',') { - this.l.skip(); - this.G = this::g; - continue; - } - - if (this.l.peek() != ']') { - throw ArgumentParserSelector.e.createWithContext(this.l); - } - } - - if (this.l.canRead()) { - this.l.skip(); - this.G = ArgumentParserSelector.k; - return; - } - - throw ArgumentParserSelector.e.createWithContext(this.l); - } - } - - public boolean e() { - this.l.skipWhitespace(); - if (this.l.canRead() && this.l.peek() == '!') { - this.l.skip(); - this.l.skipWhitespace(); - return true; - } else { - return false; - } - } - - public boolean f() { - this.l.skipWhitespace(); - if (this.l.canRead() && this.l.peek() == '#') { - this.l.skip(); - this.l.skipWhitespace(); - return true; - } else { - return false; - } - } - - public StringReader g() { - return this.l; - } - - public void a(Predicate predicate) { - this.A = this.A.and(predicate); - } - - public void h() { - this.p = true; - } - - public CriterionConditionValue.FloatRange i() { - return this.q; - } - - public void a(CriterionConditionValue.FloatRange criterionconditionvalue_floatrange) { - this.q = criterionconditionvalue_floatrange; - } - - public CriterionConditionValue.IntegerRange j() { - return this.r; - } - - public void a(CriterionConditionValue.IntegerRange criterionconditionvalue_integerrange) { - this.r = criterionconditionvalue_integerrange; - } - - public CriterionConditionRange k() { - return this.y; - } - - public void a(CriterionConditionRange criterionconditionrange) { - this.y = criterionconditionrange; - } - - public CriterionConditionRange l() { - return this.z; - } - - public void b(CriterionConditionRange criterionconditionrange) { - this.z = criterionconditionrange; - } - - @Nullable - public Double m() { - return this.s; - } - - @Nullable - public Double n() { - return this.t; - } - - @Nullable - public Double o() { - return this.u; - } - - public void a(double d0) { - this.s = d0; - } - - public void b(double d0) { - this.t = d0; - } - - public void c(double d0) { - this.u = d0; - } - - public void d(double d0) { - this.v = d0; - } - - public void e(double d0) { - this.w = d0; - } - - public void f(double d0) { - this.x = d0; - } - - @Nullable - public Double p() { - return this.v; - } - - @Nullable - public Double q() { - return this.w; - } - - @Nullable - public Double r() { - return this.x; - } - - public void a(int i) { - this.n = i; - } - - public void a(boolean flag) { - this.o = flag; - } - - public void a(BiConsumer> biconsumer) { - this.B = biconsumer; - } - - public EntitySelector parse() throws CommandSyntaxException { - // CraftBukkit start - return parse(false); - } - - public EntitySelector parse(boolean overridePermissions) throws CommandSyntaxException { - // CraftBukkit end - this.E = this.l.getCursor(); - this.G = this::b; - if (this.l.canRead() && this.l.peek() == '@') { - if (!this.m) { - throw ArgumentParserSelector.c.createWithContext(this.l); - } - - this.l.skip(); - this.parseSelector(overridePermissions); // CraftBukkit - } else { - this.c(); - } - - this.I(); - return this.a(); - } - - private static void a(SuggestionsBuilder suggestionsbuilder) { - suggestionsbuilder.suggest("@p", new ChatMessage("argument.entity.selector.nearestPlayer", new Object[0])); - suggestionsbuilder.suggest("@a", new ChatMessage("argument.entity.selector.allPlayers", new Object[0])); - suggestionsbuilder.suggest("@r", new ChatMessage("argument.entity.selector.randomPlayer", new Object[0])); - suggestionsbuilder.suggest("@s", new ChatMessage("argument.entity.selector.self", new Object[0])); - suggestionsbuilder.suggest("@e", new ChatMessage("argument.entity.selector.allEntities", new Object[0])); - } - - private CompletableFuture b(SuggestionsBuilder suggestionsbuilder, Consumer consumer) { - consumer.accept(suggestionsbuilder); - if (this.m) { - a(suggestionsbuilder); - } - - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture c(SuggestionsBuilder suggestionsbuilder, Consumer consumer) { - SuggestionsBuilder suggestionsbuilder1 = suggestionsbuilder.createOffset(this.E); - - consumer.accept(suggestionsbuilder1); - return suggestionsbuilder.add(suggestionsbuilder1).buildFuture(); - } - - private CompletableFuture d(SuggestionsBuilder suggestionsbuilder, Consumer consumer) { - SuggestionsBuilder suggestionsbuilder1 = suggestionsbuilder.createOffset(suggestionsbuilder.getStart() - 1); - - a(suggestionsbuilder1); - suggestionsbuilder.add(suggestionsbuilder1); - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture e(SuggestionsBuilder suggestionsbuilder, Consumer consumer) { - suggestionsbuilder.suggest(String.valueOf('[')); - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture f(SuggestionsBuilder suggestionsbuilder, Consumer consumer) { - suggestionsbuilder.suggest(String.valueOf(']')); - PlayerSelector.a(this, suggestionsbuilder); - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture g(SuggestionsBuilder suggestionsbuilder, Consumer consumer) { - PlayerSelector.a(this, suggestionsbuilder); - return suggestionsbuilder.buildFuture(); - } - - private CompletableFuture h(SuggestionsBuilder suggestionsbuilder, Consumer consumer) { - suggestionsbuilder.suggest(String.valueOf(',')); - suggestionsbuilder.suggest(String.valueOf(']')); - return suggestionsbuilder.buildFuture(); - } - - public boolean u() { - return this.C; - } - - public void a(BiFunction, CompletableFuture> bifunction) { - this.G = bifunction; - } - - public CompletableFuture a(SuggestionsBuilder suggestionsbuilder, Consumer consumer) { - return (CompletableFuture) this.G.apply(suggestionsbuilder.createOffset(this.l.getCursor()), consumer); - } - - public boolean v() { - return this.H; - } - - public void c(boolean flag) { - this.H = flag; - } - - public boolean w() { - return this.I; - } - - public void d(boolean flag) { - this.I = flag; - } - - public boolean x() { - return this.J; - } - - public void e(boolean flag) { - this.J = flag; - } - - public boolean y() { - return this.K; - } - - public void f(boolean flag) { - this.K = flag; - } - - public boolean z() { - return this.L; - } - - public void g(boolean flag) { - this.L = flag; - } - - public boolean A() { - return this.M; - } - - public void h(boolean flag) { - this.M = flag; - } - - public boolean B() { - return this.N; - } - - public void i(boolean flag) { - this.N = flag; - } - - public void j(boolean flag) { - this.O = flag; - } - - public void a(EntityTypes entitytypes) { - this.P = entitytypes; - } - - public void D() { - this.Q = true; - } - - public boolean E() { - return this.P != null; - } - - public boolean F() { - return this.Q; - } - - public boolean G() { - return this.R; - } - - public void k(boolean flag) { - this.R = flag; - } - - public boolean H() { - return this.S; - } - - public void l(boolean flag) { - this.S = flag; - } -} diff --git a/src/main/java/net/minecraft/server/AttributeRanged.java b/src/main/java/net/minecraft/server/AttributeRanged.java deleted file mode 100644 index 0cbd75f14..000000000 --- a/src/main/java/net/minecraft/server/AttributeRanged.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class AttributeRanged extends AttributeBase { - - private final double a; - public double maximum; // Spigot - private String c; - - public AttributeRanged(@Nullable IAttribute iattribute, String s, double d0, double d1, double d2) { - super(iattribute, s, d0); - this.a = d1; - this.maximum = 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; - } - - @Override - public double a(double d0) { - if (d0 != d0) return getDefault(); // CraftBukkit - - d0 = MathHelper.a(d0, this.a, this.maximum); - return d0; - } -} diff --git a/src/main/java/net/minecraft/server/AxisAlignedBB.java b/src/main/java/net/minecraft/server/AxisAlignedBB.java deleted file mode 100644 index c950139c0..000000000 --- a/src/main/java/net/minecraft/server/AxisAlignedBB.java +++ /dev/null @@ -1,321 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Optional; -import javax.annotation.Nullable; - -public class AxisAlignedBB { - - public final double minX; - public final double minY; - public final double minZ; - public final double maxX; - public final double maxY; - public final double maxZ; - - public AxisAlignedBB(double d0, double d1, double d2, double d3, double d4, double d5) { - this.minX = Math.min(d0, d3); - this.minY = Math.min(d1, d4); - this.minZ = Math.min(d2, d5); - this.maxX = Math.max(d0, d3); - this.maxY = Math.max(d1, d4); - this.maxZ = Math.max(d2, d5); - } - - public AxisAlignedBB(BlockPosition blockposition) { - this((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), (double) (blockposition.getX() + 1), (double) (blockposition.getY() + 1), (double) (blockposition.getZ() + 1)); - } - - public AxisAlignedBB(BlockPosition blockposition, BlockPosition blockposition1) { - this((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), (double) blockposition1.getX(), (double) blockposition1.getY(), (double) blockposition1.getZ()); - } - - public AxisAlignedBB(Vec3D vec3d, Vec3D vec3d1) { - this(vec3d.x, vec3d.y, vec3d.z, vec3d1.x, vec3d1.y, vec3d1.z); - } - - public static AxisAlignedBB a(StructureBoundingBox structureboundingbox) { - return new AxisAlignedBB((double) structureboundingbox.a, (double) structureboundingbox.b, (double) structureboundingbox.c, (double) (structureboundingbox.d + 1), (double) (structureboundingbox.e + 1), (double) (structureboundingbox.f + 1)); - } - - public double a(EnumDirection.EnumAxis enumdirection_enumaxis) { - return enumdirection_enumaxis.a(this.minX, this.minY, this.minZ); - } - - public double b(EnumDirection.EnumAxis enumdirection_enumaxis) { - return enumdirection_enumaxis.a(this.maxX, this.maxY, this.maxZ); - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (!(object instanceof AxisAlignedBB)) { - return false; - } else { - AxisAlignedBB axisalignedbb = (AxisAlignedBB) object; - - return Double.compare(axisalignedbb.minX, this.minX) != 0 ? false : (Double.compare(axisalignedbb.minY, this.minY) != 0 ? false : (Double.compare(axisalignedbb.minZ, this.minZ) != 0 ? false : (Double.compare(axisalignedbb.maxX, this.maxX) != 0 ? false : (Double.compare(axisalignedbb.maxY, this.maxY) != 0 ? false : Double.compare(axisalignedbb.maxZ, this.maxZ) == 0)))); - } - } - - public int hashCode() { - long i = Double.doubleToLongBits(this.minX); - int j = (int) (i ^ i >>> 32); - - i = Double.doubleToLongBits(this.minY); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(this.minZ); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(this.maxX); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(this.maxY); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(this.maxZ); - j = 31 * j + (int) (i ^ i >>> 32); - return j; - } - - public AxisAlignedBB a(double d0, double d1, double d2) { - double d3 = this.minX; - double d4 = this.minY; - double d5 = this.minZ; - double d6 = this.maxX; - double d7 = this.maxY; - double d8 = this.maxZ; - - if (d0 < 0.0D) { - d3 -= d0; - } else if (d0 > 0.0D) { - d6 -= d0; - } - - if (d1 < 0.0D) { - d4 -= d1; - } else if (d1 > 0.0D) { - d7 -= d1; - } - - if (d2 < 0.0D) { - d5 -= d2; - } else if (d2 > 0.0D) { - d8 -= d2; - } - - return new AxisAlignedBB(d3, d4, d5, d6, d7, d8); - } - - public AxisAlignedBB a(Vec3D vec3d) { - return this.b(vec3d.x, vec3d.y, vec3d.z); - } - - public final AxisAlignedBB expand(double x, double y, double z) { return b(x, y, z); } // Paper - OBFHELPER - public AxisAlignedBB b(double d0, double d1, double d2) { - double d3 = this.minX; - double d4 = this.minY; - double d5 = this.minZ; - double d6 = this.maxX; - double d7 = this.maxY; - double d8 = this.maxZ; - - if (d0 < 0.0D) { - d3 += d0; - } else if (d0 > 0.0D) { - d6 += d0; - } - - if (d1 < 0.0D) { - d4 += d1; - } else if (d1 > 0.0D) { - d7 += d1; - } - - if (d2 < 0.0D) { - d5 += d2; - } else if (d2 > 0.0D) { - d8 += d2; - } - - return new AxisAlignedBB(d3, d4, d5, d6, d7, d8); - } - - // Paper start - public AxisAlignedBB grow(double d0) { - return grow(d0, d0, d0); - } - // Paper end - - public AxisAlignedBB grow(double d0, double d1, double d2) { - double d3 = this.minX - d0; - double d4 = this.minY - d1; - double d5 = this.minZ - d2; - double d6 = this.maxX + d0; - double d7 = this.maxY + d1; - double d8 = this.maxZ + d2; - - return new AxisAlignedBB(d3, d4, d5, d6, d7, d8); - } - - public AxisAlignedBB g(double d0) { - return this.grow(d0, d0, d0); - } - - public AxisAlignedBB a(AxisAlignedBB axisalignedbb) { - double d0 = Math.max(this.minX, axisalignedbb.minX); - double d1 = Math.max(this.minY, axisalignedbb.minY); - double d2 = Math.max(this.minZ, axisalignedbb.minZ); - double d3 = Math.min(this.maxX, axisalignedbb.maxX); - double d4 = Math.min(this.maxY, axisalignedbb.maxY); - double d5 = Math.min(this.maxZ, axisalignedbb.maxZ); - - return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); - } - - public AxisAlignedBB b(AxisAlignedBB axisalignedbb) { - double d0 = Math.min(this.minX, axisalignedbb.minX); - double d1 = Math.min(this.minY, axisalignedbb.minY); - double d2 = Math.min(this.minZ, axisalignedbb.minZ); - double d3 = Math.max(this.maxX, axisalignedbb.maxX); - double d4 = Math.max(this.maxY, axisalignedbb.maxY); - double d5 = Math.max(this.maxZ, axisalignedbb.maxZ); - - return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); - } - - public AxisAlignedBB d(double d0, double d1, double d2) { - return new AxisAlignedBB(this.minX + d0, this.minY + d1, this.minZ + d2, this.maxX + d0, this.maxY + d1, this.maxZ + d2); - } - - public AxisAlignedBB a(BlockPosition blockposition) { - return new AxisAlignedBB(this.minX + (double) blockposition.getX(), this.minY + (double) blockposition.getY(), this.minZ + (double) blockposition.getZ(), this.maxX + (double) blockposition.getX(), this.maxY + (double) blockposition.getY(), this.maxZ + (double) blockposition.getZ()); - } - - public AxisAlignedBB b(Vec3D vec3d) { - return this.d(vec3d.x, vec3d.y, vec3d.z); - } - - public boolean c(AxisAlignedBB axisalignedbb) { - return this.a(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ, axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ); - } - - public boolean a(double d0, double d1, double d2, double d3, double d4, double d5) { - return this.minX < d3 && this.maxX > d0 && this.minY < d4 && this.maxY > d1 && this.minZ < d5 && this.maxZ > d2; - } - - public final boolean contains(Vec3D vec3d) { return c(vec3d); } // Paper - OBFHELPER - public boolean c(Vec3D vec3d) { - return this.e(vec3d.x, vec3d.y, vec3d.z); - } - - public boolean e(double d0, double d1, double d2) { - return d0 >= this.minX && d0 < this.maxX && d1 >= this.minY && d1 < this.maxY && d2 >= this.minZ && d2 < this.maxZ; - } - - public double a() { - double d0 = this.b(); - double d1 = this.c(); - double d2 = this.d(); - - return (d0 + d1 + d2) / 3.0D; - } - - public double b() { - return this.maxX - this.minX; - } - - public double c() { - return this.maxY - this.minY; - } - - public double d() { - return this.maxZ - this.minZ; - } - - public AxisAlignedBB shrink(double d0) { - return this.g(-d0); - } - - public final Optional calculateIntercept(Vec3D vec3d, Vec3D vec3d1) { return b(vec3d, vec3d1); } // Paper - OBFHELPER - public Optional b(Vec3D vec3d, Vec3D vec3d1) { - double[] adouble = new double[]{1.0D}; - double d0 = vec3d1.x - vec3d.x; - double d1 = vec3d1.y - vec3d.y; - double d2 = vec3d1.z - vec3d.z; - EnumDirection enumdirection = a(this, vec3d, adouble, (EnumDirection) null, d0, d1, d2); - - if (enumdirection == null) { - return Optional.empty(); - } else { - double d3 = adouble[0]; - - return Optional.of(vec3d.add(d3 * d0, d3 * d1, d3 * d2)); - } - } - - @Nullable - public static MovingObjectPositionBlock a(Iterable iterable, Vec3D vec3d, Vec3D vec3d1, BlockPosition blockposition) { - double[] adouble = new double[]{1.0D}; - EnumDirection enumdirection = null; - double d0 = vec3d1.x - vec3d.x; - double d1 = vec3d1.y - vec3d.y; - double d2 = vec3d1.z - vec3d.z; - - AxisAlignedBB axisalignedbb; - - for (Iterator iterator = iterable.iterator(); iterator.hasNext(); enumdirection = a(axisalignedbb.a(blockposition), vec3d, adouble, enumdirection, d0, d1, d2)) { - axisalignedbb = (AxisAlignedBB) iterator.next(); - } - - if (enumdirection == null) { - return null; - } else { - double d3 = adouble[0]; - - return new MovingObjectPositionBlock(vec3d.add(d3 * d0, d3 * d1, d3 * d2), enumdirection, blockposition, false); - } - } - - @Nullable - private static EnumDirection a(AxisAlignedBB axisalignedbb, Vec3D vec3d, double[] adouble, @Nullable EnumDirection enumdirection, double d0, double d1, double d2) { - if (d0 > 1.0E-7D) { - enumdirection = a(adouble, enumdirection, d0, d1, d2, axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxY, axisalignedbb.minZ, axisalignedbb.maxZ, EnumDirection.WEST, vec3d.x, vec3d.y, vec3d.z); - } else if (d0 < -1.0E-7D) { - enumdirection = a(adouble, enumdirection, d0, d1, d2, axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxY, axisalignedbb.minZ, axisalignedbb.maxZ, EnumDirection.EAST, vec3d.x, vec3d.y, vec3d.z); - } - - if (d1 > 1.0E-7D) { - enumdirection = a(adouble, enumdirection, d1, d2, d0, axisalignedbb.minY, axisalignedbb.minZ, axisalignedbb.maxZ, axisalignedbb.minX, axisalignedbb.maxX, EnumDirection.DOWN, vec3d.y, vec3d.z, vec3d.x); - } else if (d1 < -1.0E-7D) { - enumdirection = a(adouble, enumdirection, d1, d2, d0, axisalignedbb.maxY, axisalignedbb.minZ, axisalignedbb.maxZ, axisalignedbb.minX, axisalignedbb.maxX, EnumDirection.UP, vec3d.y, vec3d.z, vec3d.x); - } - - if (d2 > 1.0E-7D) { - enumdirection = a(adouble, enumdirection, d2, d0, d1, axisalignedbb.minZ, axisalignedbb.minX, axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxY, EnumDirection.NORTH, vec3d.z, vec3d.x, vec3d.y); - } else if (d2 < -1.0E-7D) { - enumdirection = a(adouble, enumdirection, d2, d0, d1, axisalignedbb.maxZ, axisalignedbb.minX, axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxY, EnumDirection.SOUTH, vec3d.z, vec3d.x, vec3d.y); - } - - return enumdirection; - } - - @Nullable - private static EnumDirection a(double[] adouble, @Nullable EnumDirection enumdirection, double d0, double d1, double d2, double d3, double d4, double d5, double d6, double d7, EnumDirection enumdirection1, double d8, double d9, double d10) { - double d11 = (d3 - d8) / d0; - double d12 = d9 + d11 * d1; - double d13 = d10 + d11 * d2; - - if (0.0D < d11 && d11 < adouble[0] && d4 - 1.0E-7D < d12 && d12 < d5 + 1.0E-7D && d6 - 1.0E-7D < d13 && d13 < d7 + 1.0E-7D) { - adouble[0] = d11; - return enumdirection1; - } else { - return enumdirection; - } - } - - public String toString() { - return "box[" + this.minX + ", " + this.minY + ", " + this.minZ + "] -> [" + this.maxX + ", " + this.maxY + ", " + this.maxZ + "]"; - } - - public Vec3D f() { - return new Vec3D(MathHelper.d(0.5D, this.minX, this.maxX), MathHelper.d(0.5D, this.minY, this.maxY), MathHelper.d(0.5D, this.minZ, this.maxZ)); - } -} diff --git a/src/main/java/net/minecraft/server/BaseBlockPosition.java b/src/main/java/net/minecraft/server/BaseBlockPosition.java deleted file mode 100644 index e96428bb2..000000000 --- a/src/main/java/net/minecraft/server/BaseBlockPosition.java +++ /dev/null @@ -1,106 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.MoreObjects; -import javax.annotation.concurrent.Immutable; - -@Immutable -public class BaseBlockPosition implements Comparable { - - public static final BaseBlockPosition ZERO = new BaseBlockPosition(0, 0, 0); - // Paper start - protected int x; - protected int y; - protected int z; - public boolean isValidLocation() { - return x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y >= 0 && y < 256; - } - public boolean isInvalidYLocation() { - return y < 0 || y >= 256; - } - // Paper end - - public BaseBlockPosition(int i, int j, int k) { - this.x = i; - this.y = j; - this.z = 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 this.getX() != baseblockposition.getX() ? false : (this.getY() != baseblockposition.getY() ? false : this.getZ() == baseblockposition.getZ()); - } - } - - public int hashCode() { - return (this.getY() + this.getZ() * 31) * 31 + this.getX(); - } - - public int compareTo(BaseBlockPosition baseblockposition) { - return this.getY() == baseblockposition.getY() ? (this.getZ() == baseblockposition.getZ() ? this.getX() - baseblockposition.getX() : this.getZ() - baseblockposition.getZ()) : this.getY() - baseblockposition.getY(); - } - - // Paper start - public final int getX() { - return this.x; - } - - public int getY() { - return this.y; - } - - public int getZ() { - return this.z; - } - // Paper end - - public BaseBlockPosition d(BaseBlockPosition baseblockposition) { - return new BaseBlockPosition(this.getY() * baseblockposition.getZ() - this.getZ() * baseblockposition.getY(), this.getZ() * baseblockposition.getX() - this.getX() * baseblockposition.getZ(), this.getX() * baseblockposition.getY() - this.getY() * baseblockposition.getX()); - } - - public boolean a(BaseBlockPosition baseblockposition, double d0) { - return this.distanceSquared((double) baseblockposition.x, (double) baseblockposition.y, (double) baseblockposition.z, false) < d0 * d0; // Paper - } - - public boolean a(IPosition iposition, double d0) { - return this.distanceSquared(iposition.getX(), iposition.getY(), iposition.getZ(), true) < d0 * d0; - } - - public double m(BaseBlockPosition baseblockposition) { - return this.distanceSquared((double) baseblockposition.getX(), (double) baseblockposition.getY(), (double) baseblockposition.getZ(), true); - } - - public double a(IPosition iposition, boolean flag) { - return this.distanceSquared(iposition.getX(), iposition.getY(), iposition.getZ(), flag); - } - - public double distanceSquared(double d0, double d1, double d2, boolean flag) { - double d3 = flag ? 0.5D : 0.0D; - double d4 = (double) this.getX() + d3 - d0; - double d5 = (double) this.getY() + d3 - d1; - double d6 = (double) this.getZ() + d3 - d2; - - return d4 * d4 + d5 * d5 + d6 * d6; - } - - public int n(BaseBlockPosition baseblockposition) { - float f = (float) Math.abs(baseblockposition.getX() - this.x); // Paper - float f1 = (float) Math.abs(baseblockposition.getY() - this.y); // Paper - float f2 = (float) Math.abs(baseblockposition.getZ() - this.z); // Paper - - return (int) (f + f1 + f2); - } - - public String toString() { - return MoreObjects.toStringHelper(this).add("x", this.getX()).add("y", this.getY()).add("z", this.getZ()).toString(); - } -} diff --git a/src/main/java/net/minecraft/server/BehaviorCareer.java b/src/main/java/net/minecraft/server/BehaviorCareer.java deleted file mode 100644 index 525501608..000000000 --- a/src/main/java/net/minecraft/server/BehaviorCareer.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftVillager; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.VillagerCareerChangeEvent; -// CraftBukkit end - -public class BehaviorCareer extends Behavior { - - public BehaviorCareer() { - super(ImmutableMap.of(MemoryModuleType.JOB_SITE, MemoryStatus.VALUE_PRESENT)); - } - - protected boolean a(WorldServer worldserver, EntityVillager entityvillager) { - return entityvillager.getVillagerData().getProfession() == VillagerProfession.NONE; - } - - protected void a(WorldServer worldserver, EntityVillager entityvillager, long i) { - GlobalPos globalpos = (GlobalPos) entityvillager.getBehaviorController().getMemory(MemoryModuleType.JOB_SITE).get(); - MinecraftServer minecraftserver = worldserver.getMinecraftServer(); - - minecraftserver.getWorldServer(globalpos.getDimensionManager()).B().c(globalpos.getBlockPosition()).ifPresent((villageplacetype) -> { - IRegistry.VILLAGER_PROFESSION.d().filter((villagerprofession) -> { - return villagerprofession.b() == villageplacetype; - }).findFirst().ifPresent((villagerprofession) -> { - // CraftBukkit start - Fire VillagerCareerChangeEvent where Villager gets employed - VillagerCareerChangeEvent event = CraftEventFactory.callVillagerCareerChangeEvent(entityvillager, CraftVillager.nmsToBukkitProfession(villagerprofession), VillagerCareerChangeEvent.ChangeReason.EMPLOYED); - if (event.isCancelled()) { - return; - } - - entityvillager.setVillagerData(entityvillager.getVillagerData().withProfession(CraftVillager.bukkitToNmsProfession(event.getProfession()))); - // CraftBukkit end - entityvillager.a(worldserver); - }); - }); - } -} diff --git a/src/main/java/net/minecraft/server/BehaviorFarm.java b/src/main/java/net/minecraft/server/BehaviorFarm.java deleted file mode 100644 index 0b7fa5084..000000000 --- a/src/main/java/net/minecraft/server/BehaviorFarm.java +++ /dev/null @@ -1,169 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import java.util.List; -import javax.annotation.Nullable; - -public class BehaviorFarm extends Behavior { - - @Nullable - private BlockPosition a; - private boolean b; - private boolean c; - private long d; - private int e; - private final List f = Lists.newArrayList(); - - public BehaviorFarm() { - super(ImmutableMap.of(MemoryModuleType.LOOK_TARGET, MemoryStatus.VALUE_ABSENT, MemoryModuleType.WALK_TARGET, MemoryStatus.VALUE_ABSENT, MemoryModuleType.SECONDARY_JOB_SITE, MemoryStatus.VALUE_PRESENT)); - } - - protected boolean a(WorldServer worldserver, EntityVillager entityvillager) { - if (!worldserver.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - return false; - } else if (entityvillager.getVillagerData().getProfession() != VillagerProfession.FARMER) { - return false; - } else { - this.b = entityvillager.er(); - this.c = false; - InventorySubcontainer inventorysubcontainer = entityvillager.getInventory(); - int i = inventorysubcontainer.getSize(); - - for (int j = 0; j < i; ++j) { - ItemStack itemstack = inventorysubcontainer.getItem(j); - - if (itemstack.isEmpty()) { - this.c = true; - break; - } - - if (itemstack.getItem() == Items.WHEAT_SEEDS || itemstack.getItem() == Items.BEETROOT_SEEDS) { - this.c = true; - break; - } - } - - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(entityvillager.locX, entityvillager.locY, entityvillager.locZ); - - this.f.clear(); - - for (int k = -1; k <= 1; ++k) { - for (int l = -1; l <= 1; ++l) { - for (int i1 = -1; i1 <= 1; ++i1) { - blockposition_mutableblockposition.c(entityvillager.locX + (double) k, entityvillager.locY + (double) l, entityvillager.locZ + (double) i1); - if (this.a((BlockPosition) blockposition_mutableblockposition, worldserver)) { - this.f.add(new BlockPosition(blockposition_mutableblockposition)); - } - } - } - } - - this.a = this.a(worldserver); - return (this.b || this.c) && this.a != null; - } - } - - @Nullable - private BlockPosition a(WorldServer worldserver) { - return this.f.isEmpty() ? null : (BlockPosition) this.f.get(worldserver.getRandom().nextInt(this.f.size())); - } - - private boolean a(BlockPosition blockposition, WorldServer worldserver) { - IBlockData iblockdata = worldserver.getType(blockposition); - Block block = iblockdata.getBlock(); - Block block1 = worldserver.getType(blockposition.down()).getBlock(); - - return block instanceof BlockCrops && ((BlockCrops) block).isRipe(iblockdata) && this.c || iblockdata.isAir() && block1 instanceof BlockSoil && this.b; - } - - protected void a(WorldServer worldserver, EntityVillager entityvillager, long i) { - if (i > this.d && this.a != null) { - entityvillager.getBehaviorController().setMemory(MemoryModuleType.LOOK_TARGET, (new BehaviorTarget(this.a))); // CraftBukkit - decompile error - entityvillager.getBehaviorController().setMemory(MemoryModuleType.WALK_TARGET, (new MemoryTarget(new BehaviorTarget(this.a), 0.5F, 1))); // CraftBukkit - decompile error - } - - } - - protected void f(WorldServer worldserver, EntityVillager entityvillager, long i) { - entityvillager.getBehaviorController().removeMemory(MemoryModuleType.LOOK_TARGET); - entityvillager.getBehaviorController().removeMemory(MemoryModuleType.WALK_TARGET); - this.e = 0; - this.d = i + 40L; - } - - protected void d(WorldServer worldserver, EntityVillager entityvillager, long i) { - if (this.a != null && i > this.d) { - IBlockData iblockdata = worldserver.getType(this.a); - Block block = iblockdata.getBlock(); - Block block1 = worldserver.getType(this.a.down()).getBlock(); - - if (block instanceof BlockCrops && ((BlockCrops) block).isRipe(iblockdata) && this.c) { - // CraftBukkit start - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(entityvillager, this.a, Blocks.AIR.getBlockData()).isCancelled()) { - worldserver.b(this.a, true); - } - // CraftBukkit end - } - - if (iblockdata.isAir() && block1 instanceof BlockSoil && this.b) { - InventorySubcontainer inventorysubcontainer = entityvillager.getInventory(); - - for (int j = 0; j < inventorysubcontainer.getSize(); ++j) { - ItemStack itemstack = inventorysubcontainer.getItem(j); - boolean flag = false; - - if (!itemstack.isEmpty()) { - // CraftBukkit start - Block planted = null; - if (itemstack.getItem() == Items.WHEAT_SEEDS) { - planted = Blocks.WHEAT; - flag = true; - } else if (itemstack.getItem() == Items.POTATO) { - planted = Blocks.POTATOES; - flag = true; - } else if (itemstack.getItem() == Items.CARROT) { - planted = Blocks.CARROTS; - flag = true; - } else if (itemstack.getItem() == Items.BEETROOT_SEEDS) { - planted = Blocks.BEETROOTS; - flag = true; - } - - if (planted != null && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(entityvillager, this.a, planted.getBlockData()).isCancelled()) { - worldserver.setTypeAndData(this.a, planted.getBlockData(), 3); - } else { - flag = false; - } - // CraftBukkit end - } - - if (flag) { - worldserver.playSound((EntityHuman) null, (double) this.a.getX(), (double) this.a.getY(), (double) this.a.getZ(), SoundEffects.ITEM_CROP_PLANT, SoundCategory.BLOCKS, 1.0F, 1.0F); - itemstack.subtract(1); - if (itemstack.isEmpty()) { - inventorysubcontainer.setItem(j, ItemStack.a); - } - break; - } - } - } - - if (block instanceof BlockCrops && !((BlockCrops) block).isRipe(iblockdata)) { - this.f.remove(this.a); - this.a = this.a(worldserver); - if (this.a != null) { - this.d = i + 20L; - entityvillager.getBehaviorController().setMemory(MemoryModuleType.WALK_TARGET, (new MemoryTarget(new BehaviorTarget(this.a), 0.5F, 1))); // CraftBukkit - decompile error - entityvillager.getBehaviorController().setMemory(MemoryModuleType.LOOK_TARGET, (new BehaviorTarget(this.a))); // CraftBukkit - decompile error - } - } - } - - ++this.e; - } - - protected boolean g(WorldServer worldserver, EntityVillager entityvillager, long i) { - return this.e < 200; - } -} diff --git a/src/main/java/net/minecraft/server/BehaviorInteractDoor.java b/src/main/java/net/minecraft/server/BehaviorInteractDoor.java deleted file mode 100644 index 01d9c2d92..000000000 --- a/src/main/java/net/minecraft/server/BehaviorInteractDoor.java +++ /dev/null @@ -1,101 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Sets; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class BehaviorInteractDoor extends Behavior { - - public BehaviorInteractDoor() { - super(ImmutableMap.of(MemoryModuleType.PATH, MemoryStatus.VALUE_PRESENT, MemoryModuleType.INTERACTABLE_DOORS, MemoryStatus.VALUE_PRESENT, MemoryModuleType.OPENED_DOORS, MemoryStatus.REGISTERED)); - } - - @Override - protected void a(WorldServer worldserver, EntityLiving entityliving, long i) { - BehaviorController behaviorcontroller = entityliving.getBehaviorController(); - PathEntity pathentity = (PathEntity) behaviorcontroller.getMemory(MemoryModuleType.PATH).get(); - List list = (List) behaviorcontroller.getMemory(MemoryModuleType.INTERACTABLE_DOORS).get(); - List list1 = (List) pathentity.d().stream().map((pathpoint) -> { - return new BlockPosition(pathpoint.a, pathpoint.b, pathpoint.c); - }).collect(Collectors.toList()); - Set set = this.a(worldserver, list, list1); - int j = pathentity.f() - 1; - - this.a(worldserver, list1, set, j, entityliving, behaviorcontroller); - } - - private Set a(WorldServer worldserver, List list, List list1) { - Stream stream = list.stream().filter((globalpos) -> { - return globalpos.getDimensionManager() == worldserver.getWorldProvider().getDimensionManager(); - }).map(GlobalPos::getBlockPosition); - - list1.getClass(); - return (Set) stream.filter(list1::contains).collect(Collectors.toSet()); - } - - private void a(WorldServer worldserver, List list, Set set, int i, EntityLiving entityliving, BehaviorController behaviorcontroller) { - set.forEach((blockposition) -> { - int j = list.indexOf(blockposition); - IBlockData iblockdata = worldserver.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (TagsBlock.WOODEN_DOORS.isTagged(block) && block instanceof BlockDoor) { - boolean flag = j >= i; - - // CraftBukkit start - entities opening doors - org.bukkit.event.entity.EntityInteractEvent event = new org.bukkit.event.entity.EntityInteractEvent(entityliving.getBukkitEntity(), org.bukkit.craftbukkit.block.CraftBlock.at(entityliving.world, blockposition)); - entityliving.world.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - // CaftBukkit end - ((BlockDoor) block).setDoor(worldserver, blockposition, flag); - GlobalPos globalpos = GlobalPos.create(worldserver.getWorldProvider().getDimensionManager(), blockposition); - - if (!behaviorcontroller.getMemory(MemoryModuleType.OPENED_DOORS).isPresent() && flag) { - behaviorcontroller.setMemory(MemoryModuleType.OPENED_DOORS, Sets.newHashSet(new GlobalPos[]{globalpos})); // CraftBukkit - decompile error - } else { - behaviorcontroller.getMemory(MemoryModuleType.OPENED_DOORS).ifPresent((set1) -> { - if (flag) { - set1.add(globalpos); - } else { - set1.remove(globalpos); - } - - }); - } - } - - }); - a(worldserver, list, i, entityliving, behaviorcontroller); - } - - public static void a(WorldServer worldserver, List list, int i, EntityLiving entityliving, BehaviorController behaviorcontroller) { - behaviorcontroller.getMemory(MemoryModuleType.OPENED_DOORS).ifPresent((set) -> { - Iterator iterator = set.iterator(); - - while (iterator.hasNext()) { - GlobalPos globalpos = (GlobalPos) iterator.next(); - BlockPosition blockposition = globalpos.getBlockPosition(); - int j = list.indexOf(blockposition); - - if (worldserver.getWorldProvider().getDimensionManager() != globalpos.getDimensionManager()) { - iterator.remove(); - } else { - IBlockData iblockdata = worldserver.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (TagsBlock.WOODEN_DOORS.isTagged(block) && block instanceof BlockDoor && j < i && blockposition.a((IPosition) entityliving.getPositionVector(), 4.0D)) { - ((BlockDoor) block).setDoor(worldserver, blockposition, false); - iterator.remove(); - } - } - } - - }); - } -} diff --git a/src/main/java/net/minecraft/server/BehaviorMakeLove.java b/src/main/java/net/minecraft/server/BehaviorMakeLove.java deleted file mode 100644 index f958c46f3..000000000 --- a/src/main/java/net/minecraft/server/BehaviorMakeLove.java +++ /dev/null @@ -1,126 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import java.util.Optional; - -public class BehaviorMakeLove extends Behavior { - - private long a; - - public BehaviorMakeLove() { - super(ImmutableMap.of(MemoryModuleType.BREED_TARGET, MemoryStatus.VALUE_PRESENT, MemoryModuleType.VISIBLE_MOBS, MemoryStatus.VALUE_PRESENT), 350, 350); - } - - protected boolean a(WorldServer worldserver, EntityVillager entityvillager) { - return this.b(entityvillager); - } - - protected boolean g(WorldServer worldserver, EntityVillager entityvillager, long i) { - return i <= this.a && this.b(entityvillager); - } - - protected void a(WorldServer worldserver, EntityVillager entityvillager, long i) { - EntityVillager entityvillager1 = this.a(entityvillager); - - BehaviorUtil.a((EntityLiving) entityvillager, (EntityLiving) entityvillager1); - worldserver.broadcastEntityEffect(entityvillager1, (byte) 18); - worldserver.broadcastEntityEffect(entityvillager, (byte) 18); - int j = 275 + entityvillager.getRandom().nextInt(50); - - this.a = i + (long) j; - } - - protected void d(WorldServer worldserver, EntityVillager entityvillager, long i) { - EntityVillager entityvillager1 = this.a(entityvillager); - - if (entityvillager.h((Entity) entityvillager1) <= 5.0D) { - BehaviorUtil.a((EntityLiving) entityvillager, (EntityLiving) entityvillager1); - if (i >= this.a) { - entityvillager.eo(); - entityvillager1.eo(); - this.a(worldserver, entityvillager, entityvillager1); - } else if (entityvillager.getRandom().nextInt(35) == 0) { - worldserver.broadcastEntityEffect(entityvillager1, (byte) 12); - worldserver.broadcastEntityEffect(entityvillager, (byte) 12); - } - - } - } - - private void a(WorldServer worldserver, EntityVillager entityvillager, EntityVillager entityvillager1) { - Optional optional = this.b(worldserver, entityvillager); - - if (!optional.isPresent()) { - worldserver.broadcastEntityEffect(entityvillager1, (byte) 13); - worldserver.broadcastEntityEffect(entityvillager, (byte) 13); - } else { - Optional optional1 = this.a(entityvillager, entityvillager1); - - if (optional1.isPresent()) { - this.a(worldserver, (EntityVillager) optional1.get(), (BlockPosition) optional.get()); - } else { - worldserver.B().b((BlockPosition) optional.get()); - } - } - - } - - protected void f(WorldServer worldserver, EntityVillager entityvillager, long i) { - entityvillager.getBehaviorController().removeMemory(MemoryModuleType.BREED_TARGET); - } - - private EntityVillager a(EntityVillager entityvillager) { - return (EntityVillager) entityvillager.getBehaviorController().getMemory(MemoryModuleType.BREED_TARGET).get(); - } - - private boolean b(EntityVillager entityvillager) { - BehaviorController behaviorcontroller = entityvillager.getBehaviorController(); - - if (!behaviorcontroller.getMemory(MemoryModuleType.BREED_TARGET).isPresent()) { - return false; - } else { - EntityVillager entityvillager1 = this.a(entityvillager); - - return BehaviorUtil.a(behaviorcontroller, MemoryModuleType.BREED_TARGET, EntityTypes.VILLAGER) && entityvillager.canBreed() && entityvillager1.canBreed(); - } - } - - private Optional b(WorldServer worldserver, EntityVillager entityvillager) { - return worldserver.B().a(VillagePlaceType.q.c(), (blockposition) -> { - return this.a(entityvillager, blockposition); - }, new BlockPosition(entityvillager), 48); - } - - private boolean a(EntityVillager entityvillager, BlockPosition blockposition) { - PathEntity pathentity = entityvillager.getNavigation().a(blockposition, VillagePlaceType.q.d()); - - return pathentity != null && pathentity.h(); - } - - private Optional a(EntityVillager entityvillager, EntityVillager entityvillager1) { - EntityVillager entityvillager2 = entityvillager.createChild(entityvillager1); - // CraftBukkit start - call EntityBreedEvent - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityBreedEvent(entityvillager2, entityvillager, entityvillager1, null, null, 0).isCancelled()) { - return Optional.empty(); - } - // CraftBukkit end - - if (entityvillager2 == null) { - return Optional.empty(); - } else { - entityvillager.setAgeRaw(6000); - entityvillager1.setAgeRaw(6000); - entityvillager2.setAgeRaw(-24000); - entityvillager2.setPositionRotation(entityvillager.locX, entityvillager.locY, entityvillager.locZ, 0.0F, 0.0F); - entityvillager.world.addEntity(entityvillager2, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.BREEDING); // CraftBukkit - added SpawnReason - entityvillager.world.broadcastEntityEffect(entityvillager2, (byte) 12); - return Optional.of(entityvillager2); - } - } - - private void a(WorldServer worldserver, EntityVillager entityvillager, BlockPosition blockposition) { - GlobalPos globalpos = GlobalPos.create(worldserver.getWorldProvider().getDimensionManager(), blockposition); - - entityvillager.getBehaviorController().setMemory(MemoryModuleType.HOME, globalpos); // CraftBukkit - decompile error - } -} diff --git a/src/main/java/net/minecraft/server/BehaviorProfession.java b/src/main/java/net/minecraft/server/BehaviorProfession.java deleted file mode 100644 index 7f2d6b864..000000000 --- a/src/main/java/net/minecraft/server/BehaviorProfession.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftVillager; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.VillagerCareerChangeEvent; -// CraftBukkit end - -public class BehaviorProfession extends Behavior { - - public BehaviorProfession() { - super(ImmutableMap.of(MemoryModuleType.JOB_SITE, MemoryStatus.VALUE_ABSENT)); - } - - protected boolean a(WorldServer worldserver, EntityVillager entityvillager) { - VillagerData villagerdata = entityvillager.getVillagerData(); - - return villagerdata.getProfession() != VillagerProfession.NONE && villagerdata.getProfession() != VillagerProfession.NITWIT && entityvillager.getExperience() == 0 && villagerdata.getLevel() <= 1; - } - - protected void a(WorldServer worldserver, EntityVillager entityvillager, long i) { - // CraftBukkit start - VillagerCareerChangeEvent event = CraftEventFactory.callVillagerCareerChangeEvent(entityvillager, CraftVillager.nmsToBukkitProfession(VillagerProfession.NONE), VillagerCareerChangeEvent.ChangeReason.EMPLOYED); - if (event.isCancelled()) { - return; - } - - entityvillager.setVillagerData(entityvillager.getVillagerData().withProfession(CraftVillager.bukkitToNmsProfession(event.getProfession()))); - // CraftBukkit end - entityvillager.a(worldserver); - } -} diff --git a/src/main/java/net/minecraft/server/BehaviorUtil.java b/src/main/java/net/minecraft/server/BehaviorUtil.java deleted file mode 100644 index 306844c67..000000000 --- a/src/main/java/net/minecraft/server/BehaviorUtil.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.minecraft.server; - -import java.util.Comparator; -import java.util.List; -import java.util.stream.Stream; - -public class BehaviorUtil { - - public static void a(EntityLiving entityliving, EntityLiving entityliving1) { - b(entityliving, entityliving1); - d(entityliving, entityliving1); - } - - public static boolean a(BehaviorController behaviorcontroller, EntityLiving entityliving) { - return behaviorcontroller.getMemory(MemoryModuleType.VISIBLE_MOBS).filter((list) -> { - return list.contains(entityliving); - }).isPresent(); - } - - public static boolean a(BehaviorController behaviorcontroller, MemoryModuleType memorymoduletype, EntityTypes entitytypes) { - return behaviorcontroller.getMemory(memorymoduletype).filter((entityliving) -> { - return entityliving.getEntityType() == entitytypes; - }).filter(EntityLiving::isAlive).filter((entityliving) -> { - return a(behaviorcontroller, entityliving); - }).isPresent(); - } - - public static void b(EntityLiving entityliving, EntityLiving entityliving1) { - c(entityliving, entityliving1); - c(entityliving1, entityliving); - } - - public static void c(EntityLiving entityliving, EntityLiving entityliving1) { - entityliving.getBehaviorController().setMemory(MemoryModuleType.LOOK_TARGET, (new BehaviorPositionEntity(entityliving1))); // CraftBukkit - decompile error - } - - public static void d(EntityLiving entityliving, EntityLiving entityliving1) { - boolean flag = true; - - a(entityliving, entityliving1, 2); - a(entityliving1, entityliving, 2); - } - - public static void a(EntityLiving entityliving, EntityLiving entityliving1, int i) { - float f = (float) entityliving.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue(); - BehaviorPositionEntity behaviorpositionentity = new BehaviorPositionEntity(entityliving1); - MemoryTarget memorytarget = new MemoryTarget(behaviorpositionentity, f, i); - - entityliving.getBehaviorController().setMemory(MemoryModuleType.LOOK_TARGET, behaviorpositionentity); // CraftBukkit - decompile error - entityliving.getBehaviorController().setMemory(MemoryModuleType.WALK_TARGET, memorytarget); // CraftBukkit - decompile error - } - - public static void a(EntityLiving entityliving, ItemStack itemstack, EntityLiving entityliving1) { - if (itemstack.isEmpty()) return; // CraftBukkit - SPIGOT-4940: no empty loot - double d0 = entityliving.locY - 0.30000001192092896D + (double) entityliving.getHeadHeight(); - EntityItem entityitem = new EntityItem(entityliving.world, entityliving.locX, d0, entityliving.locZ, itemstack); - BlockPosition blockposition = new BlockPosition(entityliving1); - BlockPosition blockposition1 = new BlockPosition(entityliving); - float f = 0.3F; - Vec3D vec3d = new Vec3D(blockposition.b(blockposition1)); - - vec3d = vec3d.d().a(0.30000001192092896D); - entityitem.setMot(vec3d); - entityitem.defaultPickupDelay(); - entityliving.world.addEntity(entityitem); - } - - public static SectionPosition a(WorldServer worldserver, SectionPosition sectionposition, int i) { - int j = worldserver.b(sectionposition); - Stream stream = SectionPosition.a(sectionposition, i).filter((sectionposition1) -> { // CraftBukkit - decompile error - return worldserver.b(sectionposition1) < j; - }); - - worldserver.getClass(); - return (SectionPosition) stream.min(Comparator.comparingInt(worldserver::b)).orElse(sectionposition); - } -} diff --git a/src/main/java/net/minecraft/server/BiomeBase.java b/src/main/java/net/minecraft/server/BiomeBase.java deleted file mode 100644 index a86ece834..000000000 --- a/src/main/java/net/minecraft/server/BiomeBase.java +++ /dev/null @@ -1,515 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import it.unimi.dsi.fastutil.longs.Long2FloatLinkedOpenHashMap; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public abstract class BiomeBase { - - public static final Logger LOGGER = LogManager.getLogger(); - public static final Set b = Sets.newHashSet(); - public static final RegistryBlockID c = new RegistryBlockID<>(); - protected static final NoiseGenerator3 d = new NoiseGenerator3(new Random(1234L), 1); - public static final NoiseGenerator3 e = new NoiseGenerator3(new Random(2345L), 1); - @Nullable - protected String f; - protected final float g; - protected final float h; - protected final float i; - protected final float j; - protected final int k; - protected final int l; - @Nullable - protected final String m; - protected final WorldGenSurfaceComposite n; - protected final BiomeBase.Geography o; - protected final BiomeBase.Precipitation p; - protected final Map>> q = Maps.newHashMap(); - protected final Map>> r = Maps.newHashMap(); - protected final List> s = Lists.newArrayList(); - protected final Map, WorldGenFeatureConfiguration> t = Maps.newHashMap(); - private final java.util.EnumMap> u = Maps.newEnumMap(EnumCreatureType.class); // Paper - private final ThreadLocal v = ThreadLocal.withInitial(() -> { - return (Long2FloatLinkedOpenHashMap) SystemUtils.a(() -> { - Long2FloatLinkedOpenHashMap long2floatlinkedopenhashmap = new Long2FloatLinkedOpenHashMap(1024, 0.25F) { - protected void rehash(int i) {} - }; - - long2floatlinkedopenhashmap.defaultReturnValue(Float.NaN); - return long2floatlinkedopenhashmap; - }); - }); - - @Nullable - public static BiomeBase a(BiomeBase biomebase) { - return (BiomeBase) BiomeBase.c.fromId(IRegistry.BIOME.a(biomebase)); // Paper - decompile fix - } - - public static WorldGenCarverWrapper a(WorldGenCarverAbstract worldgencarverabstract, C c0) { - return new WorldGenCarverWrapper<>(worldgencarverabstract, c0); - } - - public static WorldGenFeatureConfigured a(WorldGenerator worldgenerator, F f0, WorldGenDecorator worldgendecorator, D d0) { - WorldGenerator worldgenerator1 = worldgenerator instanceof WorldGenFlowers ? WorldGenerator.DECORATED_FLOWER : WorldGenerator.DECORATED; - - return new WorldGenFeatureConfigured<>(worldgenerator1, new WorldGenFeatureCompositeConfiguration(worldgenerator, f0, worldgendecorator, d0)); - } - - protected BiomeBase(BiomeBase.a biomebase_a) { - if (biomebase_a.a != null && biomebase_a.b != null && biomebase_a.c != null && biomebase_a.d != null && biomebase_a.e != null && biomebase_a.f != null && biomebase_a.g != null && biomebase_a.h != null && biomebase_a.i != null) { - this.n = biomebase_a.a; - this.p = biomebase_a.b; - this.o = biomebase_a.c; - this.g = biomebase_a.d; - this.h = biomebase_a.e; - this.i = biomebase_a.f; - this.j = biomebase_a.g; - this.k = biomebase_a.h; - this.l = biomebase_a.i; - this.m = biomebase_a.j; - WorldGenStage.Decoration[] aworldgenstage_decoration = WorldGenStage.Decoration.values(); - int i = aworldgenstage_decoration.length; - - int j; - - for (j = 0; j < i; ++j) { - WorldGenStage.Decoration worldgenstage_decoration = aworldgenstage_decoration[j]; - - this.r.put(worldgenstage_decoration, Lists.newArrayList()); - } - - EnumCreatureType[] aenumcreaturetype = EnumCreatureType.values(); - - i = aenumcreaturetype.length; - - for (j = 0; j < i; ++j) { - EnumCreatureType enumcreaturetype = aenumcreaturetype[j]; - - this.u.put(enumcreaturetype, new MobList()); // Paper - } - - } else { - throw new IllegalStateException("You are missing parameters to build a proper biome for " + this.getClass().getSimpleName() + "\n" + biomebase_a); - } - } - - public boolean a() { - return this.m != null; - } - - protected void a(EnumCreatureType enumcreaturetype, BiomeBase.BiomeMeta biomebase_biomemeta) { - ((List) this.u.get(enumcreaturetype)).add(biomebase_biomemeta); - } - - public List getMobs(EnumCreatureType enumcreaturetype) { - return (List) this.u.get(enumcreaturetype); - } - - public BiomeBase.Precipitation b() { - return this.p; - } - - public boolean c() { - return this.getHumidity() > 0.85F; - } - - public float d() { - return 0.1F; - } - - protected float c(BlockPosition blockposition) { - if (blockposition.getY() > 64) { - float f = (float) (BiomeBase.d.a((double) ((float) blockposition.getX() / 8.0F), (double) ((float) blockposition.getZ() / 8.0F)) * 4.0D); - - return this.getTemperature() - (f + (float) blockposition.getY() - 64.0F) * 0.05F / 30.0F; - } else { - return this.getTemperature(); - } - } - - public final float getAdjustedTemperature(BlockPosition blockposition) { - long i = blockposition.asLong(); - Long2FloatLinkedOpenHashMap long2floatlinkedopenhashmap = (Long2FloatLinkedOpenHashMap) this.v.get(); - float f = long2floatlinkedopenhashmap.get(i); - - if (!Float.isNaN(f)) { - return f; - } else { - float f1 = this.c(blockposition); - - if (long2floatlinkedopenhashmap.size() == 1024) { - long2floatlinkedopenhashmap.removeFirstFloat(); - } - - long2floatlinkedopenhashmap.put(i, f1); - return f1; - } - } - - public boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - return this.a(iworldreader, blockposition, true); - } - - public boolean a(IWorldReader iworldreader, BlockPosition blockposition, boolean flag) { - if (this.getAdjustedTemperature(blockposition) >= 0.15F) { - return false; - } else { - if (blockposition.getY() >= 0 && blockposition.getY() < 256 && iworldreader.getBrightness(EnumSkyBlock.BLOCK, blockposition) < 10) { - IBlockData iblockdata = iworldreader.getType(blockposition); - Fluid fluid = iworldreader.getFluid(blockposition); - - if (fluid.getType() == FluidTypes.WATER && iblockdata.getBlock() instanceof BlockFluids) { - if (!flag) { - return true; - } - - boolean flag1 = iworldreader.x(blockposition.west()) && iworldreader.x(blockposition.east()) && iworldreader.x(blockposition.north()) && iworldreader.x(blockposition.south()); - - if (!flag1) { - return true; - } - } - } - - return false; - } - } - - public boolean b(IWorldReader iworldreader, BlockPosition blockposition) { - if (this.getAdjustedTemperature(blockposition) >= 0.15F) { - return false; - } else { - if (blockposition.getY() >= 0 && blockposition.getY() < 256 && iworldreader.getBrightness(EnumSkyBlock.BLOCK, blockposition) < 10) { - IBlockData iblockdata = iworldreader.getType(blockposition); - - if (iblockdata.isAir() && Blocks.SNOW.getBlockData().canPlace(iworldreader, blockposition)) { - return true; - } - } - - return false; - } - } - - public void a(WorldGenStage.Decoration worldgenstage_decoration, WorldGenFeatureConfigured worldgenfeatureconfigured) { - if (worldgenfeatureconfigured.a == WorldGenerator.DECORATED_FLOWER) { - this.s.add(worldgenfeatureconfigured); - } - - ((List) this.r.get(worldgenstage_decoration)).add(worldgenfeatureconfigured); - } - - public void a(WorldGenStage.Features worldgenstage_features, WorldGenCarverWrapper worldgencarverwrapper) { - ((List) this.q.computeIfAbsent(worldgenstage_features, (worldgenstage_features1) -> { - return Lists.newArrayList(); - })).add(worldgencarverwrapper); - } - - public List> a(WorldGenStage.Features worldgenstage_features) { - return (List) this.q.computeIfAbsent(worldgenstage_features, (worldgenstage_features1) -> { - return Lists.newArrayList(); - }); - } - - public void a(StructureGenerator structuregenerator, C c0) { - this.t.put(structuregenerator, c0); - } - - public boolean a(StructureGenerator structuregenerator) { - return this.t.containsKey(structuregenerator); - } - - @Nullable - public C b(StructureGenerator structuregenerator) { - return (C) this.t.get(structuregenerator); // Paper - decompile fix - } - - public List> e() { - return this.s; - } - - public List> a(WorldGenStage.Decoration worldgenstage_decoration) { - return (List) this.r.get(worldgenstage_decoration); - } - - public void a(WorldGenStage.Decoration worldgenstage_decoration, ChunkGenerator chunkgenerator, GeneratorAccess generatoraccess, long i, SeededRandom seededrandom, BlockPosition blockposition) { - int j = 0; - - for (Iterator iterator = ((List) this.r.get(worldgenstage_decoration)).iterator(); iterator.hasNext(); ++j) { - WorldGenFeatureConfigured worldgenfeatureconfigured = (WorldGenFeatureConfigured) iterator.next(); - - seededrandom.b(i, j, worldgenstage_decoration.ordinal()); - - try { - worldgenfeatureconfigured.a(generatoraccess, chunkgenerator, seededrandom, blockposition); - } catch (Exception exception) { - CrashReport crashreport = CrashReport.a(exception, "Feature placement"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Feature").a("Id", (Object) IRegistry.FEATURE.getKey(worldgenfeatureconfigured.a)); - WorldGenerator worldgenerator = worldgenfeatureconfigured.a; - - worldgenfeatureconfigured.a.getClass(); - crashreportsystemdetails.a("Description", worldgenerator::toString); - throw new ReportedException(crashreport); - } - } - - } - - public void a(Random random, IChunkAccess ichunkaccess, int i, int j, int k, double d0, IBlockData iblockdata, IBlockData iblockdata1, int l, long i1) { - this.n.a(i1); - this.n.a(random, ichunkaccess, this, i, j, k, d0, iblockdata, iblockdata1, l, i1); - } - - public BiomeBase.EnumTemperature f() { - return this.o == BiomeBase.Geography.OCEAN ? BiomeBase.EnumTemperature.OCEAN : ((double) this.getTemperature() < 0.2D ? BiomeBase.EnumTemperature.COLD : ((double) this.getTemperature() < 1.0D ? BiomeBase.EnumTemperature.MEDIUM : BiomeBase.EnumTemperature.WARM)); - } - - public final float g() { - return this.g; - } - - public final float getHumidity() { - return this.j; - } - - public String j() { - if (this.f == null) { - this.f = SystemUtils.a("biome", IRegistry.BIOME.getKey(this)); - } - - return this.f; - } - - public final float k() { - return this.h; - } - - public final float getTemperature() { - return this.i; - } - - public final int m() { - return this.k; - } - - public final int n() { - return this.l; - } - - public final BiomeBase.Geography o() { - return this.o; - } - - public WorldGenSurfaceComposite p() { - return this.n; - } - - public WorldGenSurfaceConfiguration q() { - return this.n.a(); - } - - @Nullable - public String r() { - return this.m; - } - - // Paper start - keep track of data in a pair set to give O(1) contains calls - we have to hook removals incase plugins mess with it - public static class MobList extends java.util.ArrayList { - java.util.Set biomes = new java.util.HashSet<>(); - - @Override - public boolean contains(Object o) { - return biomes.contains(o); - } - - @Override - public boolean add(BiomeMeta biomeMeta) { - biomes.add(biomeMeta); - return super.add(biomeMeta); - } - - @Override - public BiomeMeta remove(int index) { - BiomeMeta removed = super.remove(index); - if (removed != null) { - biomes.remove(removed); - } - return removed; - } - - @Override - public void clear() { - biomes.clear(); - super.clear(); - } - } - // Paper end - - public static class a { - - @Nullable - private WorldGenSurfaceComposite a; - @Nullable - private BiomeBase.Precipitation b; - @Nullable - private BiomeBase.Geography c; - @Nullable - private Float d; - @Nullable - private Float e; - @Nullable - private Float f; - @Nullable - private Float g; - @Nullable - private Integer h; - @Nullable - private Integer i; - @Nullable - private String j; - - public a() {} - - public BiomeBase.a a(WorldGenSurface worldgensurface, SC sc) { - this.a = new WorldGenSurfaceComposite<>(worldgensurface, sc); - return this; - } - - public BiomeBase.a a(WorldGenSurfaceComposite worldgensurfacecomposite) { - this.a = worldgensurfacecomposite; - return this; - } - - public BiomeBase.a a(BiomeBase.Precipitation biomebase_precipitation) { - this.b = biomebase_precipitation; - return this; - } - - public BiomeBase.a a(BiomeBase.Geography biomebase_geography) { - this.c = biomebase_geography; - return this; - } - - public BiomeBase.a a(float f) { - this.d = f; - return this; - } - - public BiomeBase.a b(float f) { - this.e = f; - return this; - } - - public BiomeBase.a c(float f) { - this.f = f; - return this; - } - - public BiomeBase.a d(float f) { - this.g = f; - return this; - } - - public BiomeBase.a a(int i) { - this.h = i; - return this; - } - - public BiomeBase.a b(int i) { - this.i = i; - return this; - } - - public BiomeBase.a a(@Nullable String s) { - this.j = s; - return this; - } - - public String toString() { - return "BiomeBuilder{\nsurfaceBuilder=" + this.a + ",\nprecipitation=" + this.b + ",\nbiomeCategory=" + this.c + ",\ndepth=" + this.d + ",\nscale=" + this.e + ",\ntemperature=" + this.f + ",\ndownfall=" + this.g + ",\nwaterColor=" + this.h + ",\nwaterFogColor=" + this.i + ",\nparent='" + this.j + '\'' + "\n" + '}'; - } - } - - public static class BiomeMeta extends WeightedRandom.WeightedRandomChoice { - - public final EntityTypes b; - public final int c; - public final int d; - - public BiomeMeta(EntityTypes entitytypes, int i, int j, int k) { - super(i); - this.b = entitytypes; - this.c = j; - this.d = k; - } - - public String toString() { - return EntityTypes.getName(this.b) + "*(" + this.c + "-" + this.d + "):" + this.a; - } - } - - public static enum Precipitation { - - NONE("none"), RAIN("rain"), SNOW("snow"); - - private static final Map d = (Map) Arrays.stream(values()).collect(Collectors.toMap(BiomeBase.Precipitation::a, (biomebase_precipitation) -> { - return biomebase_precipitation; - })); - private final String e; - - private Precipitation(String s) { - this.e = s; - } - - public String a() { - return this.e; - } - } - - public static enum Geography { - - NONE("none"), TAIGA("taiga"), EXTREME_HILLS("extreme_hills"), JUNGLE("jungle"), MESA("mesa"), PLAINS("plains"), SAVANNA("savanna"), ICY("icy"), THEEND("the_end"), BEACH("beach"), FOREST("forest"), OCEAN("ocean"), DESERT("desert"), RIVER("river"), SWAMP("swamp"), MUSHROOM("mushroom"), NETHER("nether"); - - private static final Map r = (Map) Arrays.stream(values()).collect(Collectors.toMap(BiomeBase.Geography::a, (biomebase_geography) -> { - return biomebase_geography; - })); - private final String s; - - private Geography(String s) { - this.s = s; - } - - public String a() { - return this.s; - } - } - - public static enum EnumTemperature { - - OCEAN("ocean"), COLD("cold"), MEDIUM("medium"), WARM("warm"); - - private static final Map e = (Map) Arrays.stream(values()).collect(Collectors.toMap(BiomeBase.EnumTemperature::a, (biomebase_enumtemperature) -> { - return biomebase_enumtemperature; - })); - private final String f; - - private EnumTemperature(String s) { - this.f = s; - } - - public String a() { - return this.f; - } - } -} diff --git a/src/main/java/net/minecraft/server/Block.java b/src/main/java/net/minecraft/server/Block.java deleted file mode 100644 index 619237d68..000000000 --- a/src/main/java/net/minecraft/server/Block.java +++ /dev/null @@ -1,871 +0,0 @@ -package net.minecraft.server; - -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class Block implements IMaterial { - - protected static final Logger LOGGER = LogManager.getLogger(); - public static final RegistryBlockID REGISTRY_ID = new RegistryBlockID<>(); - private static final EnumDirection[] a = new EnumDirection[]{EnumDirection.WEST, EnumDirection.EAST, EnumDirection.NORTH, EnumDirection.SOUTH, EnumDirection.DOWN, EnumDirection.UP}; - private static final LoadingCache b = CacheBuilder.newBuilder().maximumSize(512L).weakKeys().build(new CacheLoader() { - public Boolean load(VoxelShape voxelshape) { - return !VoxelShapes.c(VoxelShapes.b(), voxelshape, OperatorBoolean.NOT_SAME); - } - }); - private static final VoxelShape c = VoxelShapes.a(VoxelShapes.b(), a(2.0D, 0.0D, 2.0D, 14.0D, 16.0D, 14.0D), OperatorBoolean.ONLY_FIRST); - private static final VoxelShape d = a(7.0D, 0.0D, 7.0D, 9.0D, 10.0D, 9.0D); - protected final int n; - public final float strength; - protected final float durability; - protected final boolean q; - protected final SoundEffectType stepSound; - protected final Material material; - // Paper start - public co.aikar.timings.Timing timing; - public co.aikar.timings.Timing getTiming() { - if (timing == null) { - timing = co.aikar.timings.MinecraftTimings.getBlockTiming(this); - } - return timing; - } - // Paper end - protected final MaterialMapColor t; - private final float frictionFactor; - protected final BlockStateList blockStateList; - private IBlockData blockData; - public boolean randomTick = false; // Paper - fix MC-113809 - protected final boolean v; - private final boolean g; - @Nullable - private MinecraftKey h; - @Nullable - private String name; - @Nullable - private Item j; - private static final ThreadLocal> k = ThreadLocal.withInitial(() -> { - Object2ByteLinkedOpenHashMap object2bytelinkedopenhashmap = new Object2ByteLinkedOpenHashMap(200) { - protected void rehash(int i) {} - }; - - object2bytelinkedopenhashmap.defaultReturnValue((byte) 127); - return object2bytelinkedopenhashmap; - }); - - public static int getCombinedId(@Nullable IBlockData iblockdata) { - if (iblockdata == null) { - return 0; - } else { - int i = Block.REGISTRY_ID.getId(iblockdata); - - return i == -1 ? 0 : i; - } - } - - public static IBlockData getByCombinedId(int i) { - IBlockData iblockdata = (IBlockData) Block.REGISTRY_ID.fromId(i); - - return iblockdata == null ? Blocks.AIR.getBlockData() : iblockdata; - } - - public static Block asBlock(@Nullable Item item) { - return item instanceof ItemBlock ? ((ItemBlock) item).getBlock() : Blocks.AIR; - } - - public static IBlockData a(IBlockData iblockdata, IBlockData iblockdata1, World world, BlockPosition blockposition) { - VoxelShape voxelshape = VoxelShapes.b(iblockdata.getCollisionShape(world, blockposition), iblockdata1.getCollisionShape(world, blockposition), OperatorBoolean.ONLY_SECOND).a((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()); - List list = world.getEntities((Entity) null, voxelshape.getBoundingBox()); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - double d0 = VoxelShapes.a(EnumDirection.EnumAxis.Y, entity.getBoundingBox().d(0.0D, 1.0D, 0.0D), Stream.of(voxelshape), -1.0D); - - entity.enderTeleportTo(entity.locX, entity.locY + 1.0D + d0, entity.locZ); - } - - return iblockdata1; - } - - public static VoxelShape a(double d0, double d1, double d2, double d3, double d4, double d5) { - return VoxelShapes.create(d0 / 16.0D, d1 / 16.0D, d2 / 16.0D, d3 / 16.0D, d4 / 16.0D, d5 / 16.0D); - } - - @Deprecated - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EntityTypes entitytypes) { - return iblockdata.d(iblockaccess, blockposition, EnumDirection.UP) && this.n < 14; - } - - @Deprecated - public boolean e(IBlockData iblockdata) { - return false; - } - - @Deprecated - public int a(IBlockData iblockdata) { - return this.n; - } - - @Deprecated - public Material l(IBlockData iblockdata) { - return this.material; - } - - @Deprecated - public MaterialMapColor e(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.t; - } - - @Deprecated - public void a(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, int i) { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - EnumDirection[] aenumdirection = Block.a; - int j = aenumdirection.length; - - for (int k = 0; k < j; ++k) { - EnumDirection enumdirection = aenumdirection[k]; - - blockposition_pooledblockposition.g(blockposition).c(enumdirection); - IBlockData iblockdata1 = generatoraccess.getType(blockposition_pooledblockposition); - IBlockData iblockdata2 = iblockdata1.updateState(enumdirection.opposite(), iblockdata, generatoraccess, blockposition_pooledblockposition, blockposition); - - a(iblockdata1, iblockdata2, generatoraccess, blockposition_pooledblockposition, i); - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - } - - public boolean a(Tag tag) { - return tag.isTagged(this); - } - - public static IBlockData getValidBlockForPosition(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { return Block.b(iblockdata, generatoraccess, blockposition); } // Paper - OBFHELPER - public static IBlockData b(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { - IBlockData iblockdata1 = iblockdata; - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - EnumDirection[] aenumdirection = Block.a; - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - blockposition_mutableblockposition.g(blockposition).c(enumdirection); - iblockdata1 = iblockdata1.updateState(enumdirection, generatoraccess.getType(blockposition_mutableblockposition), generatoraccess, blockposition, blockposition_mutableblockposition); - } - - return iblockdata1; - } - - public static void a(IBlockData iblockdata, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, int i) { - if (iblockdata1 != iblockdata) { - if (iblockdata1.isAir()) { - if (!generatoraccess.e()) { - generatoraccess.b(blockposition, (i & 32) == 0); - } - } else { - generatoraccess.setTypeAndData(blockposition, iblockdata1, i & -33); - } - } - - } - - @Deprecated - public void b(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, int i) {} - - @Deprecated - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return iblockdata; - } - - @Deprecated - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return iblockdata; - } - - @Deprecated - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return iblockdata; - } - - public Block(Block.Info block_info) { - BlockStateList.a blockstatelist_a = new BlockStateList.a<>(this); - - this.a(blockstatelist_a); - this.material = block_info.a; - this.t = block_info.b; - this.v = block_info.c; - this.stepSound = block_info.d; - this.n = block_info.e; - this.durability = block_info.f; - this.strength = block_info.g; - this.q = block_info.h; - this.frictionFactor = block_info.i; - this.g = block_info.k; - this.h = block_info.j; - this.blockStateList = blockstatelist_a.a(IBlockData::new); - this.o((IBlockData) this.blockStateList.getBlockData()); - } - - public static boolean a(Block block) { - return block instanceof BlockLeaves || block == Blocks.BARRIER || block == Blocks.CARVED_PUMPKIN || block == Blocks.JACK_O_LANTERN || block == Blocks.MELON || block == Blocks.PUMPKIN; - } - - @Deprecated - public boolean isOccluding(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.getMaterial().f() && iblockdata.o(iblockaccess, blockposition) && !iblockdata.isPowerSource(); - } - - @Deprecated - public boolean c(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.material.isSolid() && iblockdata.o(iblockaccess, blockposition); - } - - @Deprecated - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - switch (pathmode) { - case LAND: - return !iblockdata.o(iblockaccess, blockposition); - case WATER: - return iblockaccess.getFluid(blockposition).a(TagsFluid.WATER); - case AIR: - return !iblockdata.o(iblockaccess, blockposition); - default: - return false; - } - } - - @Deprecated - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.MODEL; - } - - @Deprecated - public boolean a(IBlockData iblockdata, BlockActionContext blockactioncontext) { - return this.material.isReplaceable() && (blockactioncontext.getItemStack().isEmpty() || blockactioncontext.getItemStack().getItem() != this.getItem()); - } - - @Deprecated - public float f(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.strength; - } - - public boolean isTicking(IBlockData iblockdata) { - return this.q; - } - - public boolean isTileEntity() { - return this instanceof ITileEntity; - } - - @Deprecated - public boolean g(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return false; - } - - @Deprecated - public boolean f(IBlockData iblockdata) { - return this.v && this.c() == TextureType.SOLID; - } - - @Deprecated - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return VoxelShapes.b(); - } - - @Deprecated - public VoxelShape b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return this.v ? iblockdata.getShape(iblockaccess, blockposition) : VoxelShapes.a(); - } - - @Deprecated - public VoxelShape h(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.getShape(iblockaccess, blockposition); - } - - @Deprecated - public VoxelShape i(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return VoxelShapes.a(); - } - - public static boolean c(IBlockAccess iblockaccess, BlockPosition blockposition) { - IBlockData iblockdata = iblockaccess.getType(blockposition); - - return !iblockdata.a(TagsBlock.LEAVES) && !VoxelShapes.c(iblockdata.getCollisionShape(iblockaccess, blockposition).a(EnumDirection.UP), Block.c, OperatorBoolean.ONLY_SECOND); - } - - public static boolean a(IWorldReader iworldreader, BlockPosition blockposition, EnumDirection enumdirection) { - IBlockData iblockdata = iworldreader.getType(blockposition); - - return !iblockdata.a(TagsBlock.LEAVES) && !VoxelShapes.c(iblockdata.getCollisionShape(iworldreader, blockposition).a(enumdirection), Block.d, OperatorBoolean.ONLY_SECOND); - } - - public static boolean d(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return !iblockdata.a(TagsBlock.LEAVES) && a(iblockdata.getCollisionShape(iblockaccess, blockposition), enumdirection); - } - - public static boolean a(VoxelShape voxelshape, EnumDirection enumdirection) { - VoxelShape voxelshape1 = voxelshape.a(enumdirection); - - return a(voxelshape1); - } - - public static boolean a(VoxelShape voxelshape) { - return (Boolean) Block.b.getUnchecked(voxelshape); - } - - @Deprecated - public final boolean j(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.o() ? a(iblockdata.j(iblockaccess, blockposition)) : false; - } - - public boolean b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return !a(iblockdata.getShape(iblockaccess, blockposition)) && iblockdata.p().isEmpty(); - } - - @Deprecated - public int k(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.g(iblockaccess, blockposition) ? iblockaccess.H() : (iblockdata.a(iblockaccess, blockposition) ? 0 : 1); - } - - @Deprecated - public boolean n(IBlockData iblockdata) { - return false; - } - - @Deprecated - public void c(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - this.tick(iblockdata, world, blockposition, random); - } - - @Deprecated - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) {} - - public void postBreak(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata) {} - - @Deprecated - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - PacketDebug.a(world, blockposition); - } - - public int a(IWorldReader iworldreader) { - return 10; - } - - @Nullable - @Deprecated - public ITileInventory getInventory(IBlockData iblockdata, World world, BlockPosition blockposition) { - return null; - } - - @Deprecated - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - org.spigotmc.AsyncCatcher.catchOp("block onPlace"); // Spigot - } - - @Deprecated - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - org.spigotmc.AsyncCatcher.catchOp("block remove"); // Spigot - if (this.isTileEntity() && iblockdata.getBlock() != iblockdata1.getBlock()) { - world.removeTileEntity(blockposition); - } - - } - - @Deprecated - public float getDamage(IBlockData iblockdata, EntityHuman entityhuman, IBlockAccess iblockaccess, BlockPosition blockposition) { - float f = iblockdata.f(iblockaccess, blockposition); - - if (f == -1.0F) { - return 0.0F; - } else { - int i = entityhuman.hasBlock(iblockdata) ? 30 : 100; - - return entityhuman.b(iblockdata) / f / (float) i; - } - } - - @Deprecated - public void dropNaturally(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) {} - - public MinecraftKey i() { - if (this.h == null) { - MinecraftKey minecraftkey = IRegistry.BLOCK.getKey(this); - - this.h = new MinecraftKey(minecraftkey.getNamespace(), "blocks/" + minecraftkey.getKey()); - } - - return this.h; - } - - @Deprecated - public List a(IBlockData iblockdata, LootTableInfo.Builder loottableinfo_builder) { - MinecraftKey minecraftkey = this.i(); - - if (minecraftkey == LootTables.a) { - return Collections.emptyList(); - } else { - LootTableInfo loottableinfo = loottableinfo_builder.set(LootContextParameters.BLOCK_STATE, iblockdata).build(LootContextParameterSets.BLOCK); - WorldServer worldserver = loottableinfo.d(); - LootTable loottable = worldserver.getMinecraftServer().getLootTableRegistry().getLootTable(minecraftkey); - - return loottable.populateLoot(loottableinfo); - } - } - - public static List a(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, @Nullable TileEntity tileentity) { - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder(worldserver)).a(worldserver.random).set(LootContextParameters.POSITION, blockposition).set(LootContextParameters.TOOL, ItemStack.a).setOptional(LootContextParameters.BLOCK_ENTITY, tileentity); - - return iblockdata.a(loottableinfo_builder); - } - - public static List getDrops(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, @Nullable TileEntity tileentity, Entity entity, ItemStack itemstack) { - // CraftBukkit - make entity optional - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder(worldserver)).a(worldserver.random).set(LootContextParameters.POSITION, blockposition).set(LootContextParameters.TOOL, itemstack).setOptional(LootContextParameters.THIS_ENTITY, entity).setOptional(LootContextParameters.BLOCK_ENTITY, tileentity); - - return iblockdata.a(loottableinfo_builder); - } - - public static void b(IBlockData iblockdata, LootTableInfo.Builder loottableinfo_builder) { - WorldServer worldserver = loottableinfo_builder.a(); - BlockPosition blockposition = (BlockPosition) loottableinfo_builder.a(LootContextParameters.POSITION); - - iblockdata.a(loottableinfo_builder).forEach((itemstack) -> { - a((World) worldserver, blockposition, itemstack); - }); - iblockdata.dropNaturally(worldserver, blockposition, ItemStack.a); - } - - public static void c(IBlockData iblockdata, World world, BlockPosition blockposition) { - if (world instanceof WorldServer) { - a(iblockdata, (WorldServer) world, blockposition, (TileEntity) null).forEach((itemstack) -> { - a(world, blockposition, itemstack); - }); - } - - iblockdata.dropNaturally(world, blockposition, ItemStack.a); - } - public static void dropNaturally(IBlockData iblockdata, World world, BlockPosition blockposition, @Nullable TileEntity tileentity) { a(iblockdata, world, blockposition, tileentity); } - public static void a(IBlockData iblockdata, World world, BlockPosition blockposition, @Nullable TileEntity tileentity) { - if (world instanceof WorldServer) { - a(iblockdata, (WorldServer) world, blockposition, tileentity).forEach((itemstack) -> { - a(world, blockposition, itemstack); - }); - } - - iblockdata.dropNaturally(world, blockposition, ItemStack.a); - } - - public static void dropItems(IBlockData iblockdata, World world, BlockPosition blockposition, @Nullable TileEntity tileentity, Entity entity, ItemStack itemstack) { - if (world instanceof WorldServer) { - getDrops(iblockdata, (WorldServer) world, blockposition, tileentity, entity, itemstack).forEach((itemstack1) -> { - a(world, blockposition, itemstack1); - }); - } - - iblockdata.dropNaturally(world, blockposition, itemstack); - } - - public static void a(World world, BlockPosition blockposition, ItemStack itemstack) { - if (!world.isClientSide && !itemstack.isEmpty() && world.getGameRules().getBoolean(GameRules.DO_TILE_DROPS)) { - float f = 0.5F; - double d0 = (double) (world.random.nextFloat() * 0.5F) + 0.25D; - double d1 = (double) (world.random.nextFloat() * 0.5F) + 0.25D; - double d2 = (double) (world.random.nextFloat() * 0.5F) + 0.25D; - EntityItem entityitem = new EntityItem(world, (double) blockposition.getX() + d0, (double) blockposition.getY() + d1, (double) blockposition.getZ() + d2, itemstack); - - entityitem.defaultPickupDelay(); - // CraftBukkit start - if (world.captureDrops != null) { - world.captureDrops.add(entityitem); - } else { - world.addEntity(entityitem); - } - // CraftBukkit end - } - } - - protected void dropExperience(World world, BlockPosition blockposition, int i, EntityPlayer player) { // Paper - if (!world.isClientSide && world.getGameRules().getBoolean(GameRules.DO_TILE_DROPS)) { - while (i > 0) { - int j = EntityExperienceOrb.getOrbValue(i); - - i -= j; - world.addEntity(new EntityExperienceOrb(world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, j, org.bukkit.entity.ExperienceOrb.SpawnReason.BLOCK_BREAK, player)); // Paper - } - } - - } - - public float getDurability() { - return this.durability; - } - - public void wasExploded(World world, BlockPosition blockposition, Explosion explosion) {} - - public TextureType c() { - return TextureType.SOLID; - } - - @Deprecated - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - return true; - } - - @Deprecated - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - return false; - } - - public void stepOn(World world, BlockPosition blockposition, Entity entity) {} - - @Nullable - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return this.getBlockData(); - } - - @Deprecated - public void attack(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman) {} - - @Deprecated - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return 0; - } - - @Deprecated - public boolean isPowerSource(IBlockData iblockdata) { - return false; - } - - @Deprecated - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) {} - - @Deprecated - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return 0; - } - - public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, ItemStack itemstack) { - entityhuman.b(StatisticList.BLOCK_MINED.b(this)); - entityhuman.applyExhaustion(0.005F); - dropItems(iblockdata, world, blockposition, tileentity, entityhuman, itemstack); - } - - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, @Nullable EntityLiving entityliving, ItemStack itemstack) {} - - public boolean S_() { - return !this.material.isBuildable() && !this.material.isLiquid(); - } - - public String l() { - if (this.name == null) { - this.name = SystemUtils.a("block", IRegistry.BLOCK.getKey(this)); - } - - return this.name; - } - - @Deprecated - public boolean a(IBlockData iblockdata, World world, BlockPosition blockposition, int i, int j) { - return false; - } - - @Deprecated - public EnumPistonReaction getPushReaction(IBlockData iblockdata) { - return this.material.getPushReaction(); - } - - public void fallOn(World world, BlockPosition blockposition, Entity entity, float f) { - entity.b(f, 1.0F); - } - - public void a(IBlockAccess iblockaccess, Entity entity) { - entity.setMot(entity.getMot().d(1.0D, 0.0D, 1.0D)); - } - - public void a(CreativeModeTab creativemodetab, NonNullList nonnulllist) { - nonnulllist.add(new ItemStack(this)); - } - - @Deprecated - public Fluid g(IBlockData iblockdata) { - return FluidTypes.EMPTY.i(); - } - - public float m() { - return this.frictionFactor; - } - - public void a(World world, IBlockData iblockdata, MovingObjectPositionBlock movingobjectpositionblock, Entity entity) {} - - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { - world.a(entityhuman, 2001, blockposition, getCombinedId(iblockdata)); - } - - public void c(World world, BlockPosition blockposition) {} - - public boolean a(Explosion explosion) { - return true; - } - - @Deprecated - public boolean isComplexRedstone(IBlockData iblockdata) { - return false; - } - - @Deprecated - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - return 0; - } - - protected void a(BlockStateList.a blockstatelist_a) {} - - public BlockStateList getStates() { - return this.blockStateList; - } - - protected final void o(IBlockData iblockdata) { - this.blockData = iblockdata; - } - - public final IBlockData getBlockData() { - return this.blockData; - } - - public Block.EnumRandomOffset R_() { - return Block.EnumRandomOffset.NONE; - } - - @Deprecated - public Vec3D l(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - Block.EnumRandomOffset block_enumrandomoffset = this.R_(); - - if (block_enumrandomoffset == Block.EnumRandomOffset.NONE) { - return Vec3D.a; - } else { - long i = MathHelper.c(blockposition.getX(), 0, blockposition.getZ()); - - return new Vec3D(((double) ((float) (i & 15L) / 15.0F) - 0.5D) * 0.5D, block_enumrandomoffset == Block.EnumRandomOffset.XYZ ? ((double) ((float) (i >> 4 & 15L) / 15.0F) - 1.0D) * 0.2D : 0.0D, ((double) ((float) (i >> 8 & 15L) / 15.0F) - 0.5D) * 0.5D); - } - } - - public SoundEffectType getStepSound(IBlockData iblockdata) { - return this.stepSound; - } - - @Override - public Item getItem() { - if (this.j == null) { - this.j = Item.getItemOf(this); - } - - return this.j; - } - - public boolean p() { - return this.g; - } - - public String toString() { - return "Block{" + IRegistry.BLOCK.getKey(this) + "}"; - } - - public static boolean b(Block block) { - return block == Blocks.STONE || block == Blocks.GRANITE || block == Blocks.DIORITE || block == Blocks.ANDESITE; - } - - public static boolean c(Block block) { - return block == Blocks.DIRT || block == Blocks.COARSE_DIRT || block == Blocks.PODZOL; - } - - // CraftBukkit start - public int getExpDrop(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) { - return 0; - } - // CraftBukkit end - - // Spigot start - public static float range(float min, float value, float max) { - if (value < min) { - return min; - } - if (value > max) { - return max; - } - return value; - } - // Spigot end - - public static enum EnumRandomOffset { - - NONE, XZ, XYZ; - - private EnumRandomOffset() {} - } - - public static class Info { - - private Material a; - private MaterialMapColor b; - private boolean c = true; - private SoundEffectType d; - private int e; - private float f; - private float g; - private boolean h; - private float i; - private MinecraftKey j; - private boolean k; - - private Info(Material material, MaterialMapColor materialmapcolor) { - this.d = SoundEffectType.d; - this.i = 0.6F; - this.a = material; - this.b = materialmapcolor; - } - - public static Block.Info a(Material material) { - return a(material, material.i()); - } - - public static Block.Info a(Material material, EnumColor enumcolor) { - return a(material, enumcolor.e()); - } - - public static Block.Info a(Material material, MaterialMapColor materialmapcolor) { - return new Block.Info(material, materialmapcolor); - } - - public static Block.Info a(Block block) { - Block.Info block_info = new Block.Info(block.material, block.t); - - block_info.a = block.material; - block_info.g = block.strength; - block_info.f = block.durability; - block_info.c = block.v; - block_info.h = block.q; - block_info.e = block.n; - block_info.b = block.t; - block_info.d = block.stepSound; - block_info.i = block.m(); - block_info.k = block.g; - return block_info; - } - - public Block.Info a() { - this.c = false; - return this; - } - - public Block.Info a(float f) { - this.i = f; - return this; - } - - protected Block.Info a(SoundEffectType soundeffecttype) { - this.d = soundeffecttype; - return this; - } - - protected Block.Info a(int i) { - this.e = i; - return this; - } - - public Block.Info a(float f, float f1) { - this.g = f; - this.f = Math.max(0.0F, f1); - return this; - } - - protected Block.Info b() { - return this.b(0.0F); - } - - protected Block.Info b(float f) { - this.a(f, f); - return this; - } - - protected Block.Info c() { - this.h = true; - return this; - } - - protected Block.Info d() { - this.k = true; - return this; - } - - protected Block.Info e() { - this.j = LootTables.a; - return this; - } - - public Block.Info b(Block block) { - this.j = block.i(); - return this; - } - } - - public static final class a { - - private final IBlockData a; - private final IBlockData b; - private final EnumDirection c; - - public a(IBlockData iblockdata, IBlockData iblockdata1, EnumDirection enumdirection) { - this.a = iblockdata; - this.b = iblockdata1; - this.c = enumdirection; - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (!(object instanceof Block.a)) { - return false; - } else { - Block.a block_a = (Block.a) object; - - return this.a == block_a.a && this.b == block_a.b && this.c == block_a.c; - } - } - - public int hashCode() { - int i = this.a.hashCode(); - - i = 31 * i + this.b.hashCode(); - i = 31 * i + this.c.hashCode(); - return i; - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockAccessAir.java b/src/main/java/net/minecraft/server/BlockAccessAir.java deleted file mode 100644 index d7a68a1ef..000000000 --- a/src/main/java/net/minecraft/server/BlockAccessAir.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public enum BlockAccessAir implements IBlockAccess { - - INSTANCE; - - private BlockAccessAir() {} - - @Nullable - @Override - public TileEntity getTileEntity(BlockPosition blockposition) { - return null; - } - - // Paper start - If loaded util - @Override - public Fluid getFluidIfLoaded(BlockPosition blockposition) { - return this.getFluid(blockposition); - } - - @Override - public IBlockData getTypeIfLoaded(BlockPosition blockposition) { - return this.getType(blockposition); - } - // Paper end - - @Override - public IBlockData getType(BlockPosition blockposition) { - return Blocks.AIR.getBlockData(); - } - - @Override - public Fluid getFluid(BlockPosition blockposition) { - return FluidTypes.EMPTY.i(); - } -} diff --git a/src/main/java/net/minecraft/server/BlockBamboo.java b/src/main/java/net/minecraft/server/BlockBamboo.java deleted file mode 100644 index 3a9c3b54a..000000000 --- a/src/main/java/net/minecraft/server/BlockBamboo.java +++ /dev/null @@ -1,219 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public class BlockBamboo extends Block implements IBlockFragilePlantElement { - - protected static final VoxelShape a = Block.a(5.0D, 0.0D, 5.0D, 11.0D, 16.0D, 11.0D); - protected static final VoxelShape b = Block.a(3.0D, 0.0D, 3.0D, 13.0D, 16.0D, 13.0D); - protected static final VoxelShape c = Block.a(6.5D, 0.0D, 6.5D, 9.5D, 16.0D, 9.5D); - public static final BlockStateInteger d = BlockProperties.Y; - public static final BlockStateEnum e = BlockProperties.aF; - public static final BlockStateInteger f = BlockProperties.at; - - public BlockBamboo(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockBamboo.d, 0)).set(BlockBamboo.e, BlockPropertyBambooSize.NONE)).set(BlockBamboo.f, 0)); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockBamboo.d, BlockBamboo.e, BlockBamboo.f); - } - - @Override - public Block.EnumRandomOffset R_() { - return Block.EnumRandomOffset.XZ; - } - - @Override - public boolean b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return true; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - VoxelShape voxelshape = iblockdata.get(BlockBamboo.e) == BlockPropertyBambooSize.LARGE ? BlockBamboo.b : BlockBamboo.a; - Vec3D vec3d = iblockdata.l(iblockaccess, blockposition); - - return voxelshape.a(vec3d.x, vec3d.y, vec3d.z); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } - - @Override - public VoxelShape b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - Vec3D vec3d = iblockdata.l(iblockaccess, blockposition); - - return BlockBamboo.c.a(vec3d.x, vec3d.y, vec3d.z); - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - Fluid fluid = blockactioncontext.getWorld().getFluid(blockactioncontext.getClickPosition()); - - if (!fluid.isEmpty()) { - return null; - } else { - IBlockData iblockdata = blockactioncontext.getWorld().getType(blockactioncontext.getClickPosition().down()); - - if (iblockdata.a(TagsBlock.BAMBOO_PLANTABLE_ON)) { - Block block = iblockdata.getBlock(); - - if (block == Blocks.BAMBOO_SAPLING) { - return (IBlockData) this.getBlockData().set(BlockBamboo.d, 0); - } else if (block == Blocks.BAMBOO) { - int i = (Integer) iblockdata.get(BlockBamboo.d) > 0 ? 1 : 0; - - return (IBlockData) this.getBlockData().set(BlockBamboo.d, i); - } else { - return Blocks.BAMBOO_SAPLING.getBlockData(); - } - } else { - return null; - } - } - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!iblockdata.canPlace(world, blockposition)) { - world.b(blockposition, true); - } else if ((Integer) iblockdata.get(BlockBamboo.f) == 0) { - if (world.paperConfig.fixZeroTickInstantGrowFarms && !randomTick) return; // Paper - fix MC-113809 - if (world.random.nextInt(Math.max(1, (int) (100.0F / world.spigotConfig.bambooModifier) * 3)) == 0 && world.isEmpty(blockposition.up()) && world.getLightLevel(blockposition.up(), 0) >= 9) { // Spigot - int i = this.b((IBlockAccess) world, blockposition) + 1; - - if (i < 16) { - this.a(iblockdata, world, blockposition, random, i); - } - } - - } - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - return iworldreader.getType(blockposition.down()).a(TagsBlock.BAMBOO_PLANTABLE_ON); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (!iblockdata.canPlace(generatoraccess, blockposition)) { - generatoraccess.getBlockTickList().a(blockposition, this, 1); - } - - if (enumdirection == EnumDirection.UP && iblockdata1.getBlock() == Blocks.BAMBOO && (Integer) iblockdata1.get(BlockBamboo.d) > (Integer) iblockdata.get(BlockBamboo.d)) { - generatoraccess.setTypeAndData(blockposition, (IBlockData) iblockdata.a((IBlockState) BlockBamboo.d), 2); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - int i = this.a(iblockaccess, blockposition); - int j = this.b(iblockaccess, blockposition); - - return i + j + 1 < 16 && (Integer) iblockaccess.getType(blockposition.up(i)).get(BlockBamboo.f) != 1; - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return true; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - int i = this.a((IBlockAccess) world, blockposition); - int j = this.b((IBlockAccess) world, blockposition); - int k = i + j + 1; - int l = 1 + random.nextInt(2); - - for (int i1 = 0; i1 < l; ++i1) { - BlockPosition blockposition1 = blockposition.up(i); - IBlockData iblockdata1 = world.getType(blockposition1); - - if (k >= 16 || (Integer) iblockdata1.get(BlockBamboo.f) == 1 || !world.isEmpty(blockposition1.up())) { - return; - } - - this.a(iblockdata1, world, blockposition1, random, k); - ++i; - ++k; - } - - } - - @Override - public float getDamage(IBlockData iblockdata, EntityHuman entityhuman, IBlockAccess iblockaccess, BlockPosition blockposition) { - return entityhuman.getItemInMainHand().getItem() instanceof ItemSword ? 1.0F : super.getDamage(iblockdata, entityhuman, iblockaccess, blockposition); - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - protected void a(IBlockData iblockdata, World world, BlockPosition blockposition, Random random, int i) { - IBlockData iblockdata1 = world.getType(blockposition.down()); - BlockPosition blockposition1 = blockposition.down(2); - IBlockData iblockdata2 = world.getType(blockposition1); - BlockPropertyBambooSize blockpropertybamboosize = BlockPropertyBambooSize.NONE; - boolean shouldUpdateOthers = false; // CraftBukkit - - if (i >= 1) { - if (iblockdata1.getBlock() == Blocks.BAMBOO && iblockdata1.get(BlockBamboo.e) != BlockPropertyBambooSize.NONE) { - if (iblockdata1.getBlock() == Blocks.BAMBOO && iblockdata1.get(BlockBamboo.e) != BlockPropertyBambooSize.NONE) { - blockpropertybamboosize = BlockPropertyBambooSize.LARGE; - if (iblockdata2.getBlock() == Blocks.BAMBOO) { - // CraftBukkit start - moved down - // world.setTypeAndData(blockposition.down(), (IBlockData) iblockdata1.set(BlockBamboo.e, BlockPropertyBambooSize.SMALL), 3); - // world.setTypeAndData(blockposition1, (IBlockData) iblockdata2.set(BlockBamboo.e, BlockPropertyBambooSize.NONE), 3); - shouldUpdateOthers = true; - // CraftBukkit end - } - } - } else { - blockpropertybamboosize = BlockPropertyBambooSize.SMALL; - } - } - - int j = (Integer) iblockdata.get(BlockBamboo.d) != 1 && iblockdata2.getBlock() != Blocks.BAMBOO ? 0 : 1; - int k = (i < 11 || random.nextFloat() >= 0.25F) && i != 15 ? 0 : 1; - - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition.up(), (IBlockData) ((IBlockData) ((IBlockData) this.getBlockData().set(BlockBamboo.d, j)).set(BlockBamboo.e, blockpropertybamboosize)).set(BlockBamboo.f, k), 3)) { - if (shouldUpdateOthers) { - world.setTypeAndData(blockposition.down(), (IBlockData) iblockdata1.set(BlockBamboo.e, BlockPropertyBambooSize.SMALL), 3); - world.setTypeAndData(blockposition1, (IBlockData) iblockdata2.set(BlockBamboo.e, BlockPropertyBambooSize.NONE), 3); - } - } - // CraftBukkit end - } - - protected int a(IBlockAccess iblockaccess, BlockPosition blockposition) { - int i; - - for (i = 0; i < 16 && iblockaccess.getType(blockposition.up(i + 1)).getBlock() == Blocks.BAMBOO; ++i) { - ; - } - - return i; - } - - protected int b(IBlockAccess iblockaccess, BlockPosition blockposition) { - int i; - - for (i = 0; i < 16 && iblockaccess.getType(blockposition.down(i + 1)).getBlock() == Blocks.BAMBOO; ++i) { - ; - } - - return i; - } -} diff --git a/src/main/java/net/minecraft/server/BlockBambooSapling.java b/src/main/java/net/minecraft/server/BlockBambooSapling.java deleted file mode 100644 index 473578d61..000000000 --- a/src/main/java/net/minecraft/server/BlockBambooSapling.java +++ /dev/null @@ -1,79 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class BlockBambooSapling extends Block implements IBlockFragilePlantElement { - - protected static final VoxelShape a = Block.a(4.0D, 0.0D, 4.0D, 12.0D, 12.0D, 12.0D); - - public BlockBambooSapling(Block.Info block_info) { - super(block_info); - } - - @Override - public Block.EnumRandomOffset R_() { - return Block.EnumRandomOffset.XZ; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - Vec3D vec3d = iblockdata.l(iblockaccess, blockposition); - - return BlockBambooSapling.a.a(vec3d.x, vec3d.y, vec3d.z); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (random.nextInt(3) == 0 && world.isEmpty(blockposition.up()) && world.getLightLevel(blockposition.up(), 0) >= 9) { - this.a(world, blockposition); - } - - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - return iworldreader.getType(blockposition.down()).a(TagsBlock.BAMBOO_PLANTABLE_ON); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (!iblockdata.canPlace(generatoraccess, blockposition)) { - return Blocks.AIR.getBlockData(); - } else { - if (enumdirection == EnumDirection.UP && iblockdata1.getBlock() == Blocks.BAMBOO) { - generatoraccess.setTypeAndData(blockposition, Blocks.BAMBOO.getBlockData(), 2); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return iblockaccess.getType(blockposition.up()).isAir(); - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return true; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - this.a(world, blockposition); - } - - @Override - public float getDamage(IBlockData iblockdata, EntityHuman entityhuman, IBlockAccess iblockaccess, BlockPosition blockposition) { - return entityhuman.getItemInMainHand().getItem() instanceof ItemSword ? 1.0F : super.getDamage(iblockdata, entityhuman, iblockaccess, blockposition); - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - protected void a(World world, BlockPosition blockposition) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition.up(), (IBlockData) Blocks.BAMBOO.getBlockData().set(BlockBamboo.e, BlockPropertyBambooSize.SMALL), 3); // CraftBukkit - BlockSpreadEvent - } -} diff --git a/src/main/java/net/minecraft/server/BlockBed.java b/src/main/java/net/minecraft/server/BlockBed.java deleted file mode 100644 index b2525e2a2..000000000 --- a/src/main/java/net/minecraft/server/BlockBed.java +++ /dev/null @@ -1,376 +0,0 @@ -package net.minecraft.server; - -import java.util.Optional; -import javax.annotation.Nullable; - -public class BlockBed extends BlockFacingHorizontal implements ITileEntity { - - public static final BlockStateEnum PART = BlockProperties.aw; - public static final BlockStateBoolean OCCUPIED = BlockProperties.t; - protected static final VoxelShape c = Block.a(0.0D, 3.0D, 0.0D, 16.0D, 9.0D, 16.0D); - protected static final VoxelShape d = Block.a(0.0D, 0.0D, 0.0D, 3.0D, 3.0D, 3.0D); - protected static final VoxelShape e = Block.a(0.0D, 0.0D, 13.0D, 3.0D, 3.0D, 16.0D); - protected static final VoxelShape f = Block.a(13.0D, 0.0D, 0.0D, 16.0D, 3.0D, 3.0D); - protected static final VoxelShape g = Block.a(13.0D, 0.0D, 13.0D, 16.0D, 3.0D, 16.0D); - protected static final VoxelShape h = VoxelShapes.a(BlockBed.c, BlockBed.d, BlockBed.f); - protected static final VoxelShape i = VoxelShapes.a(BlockBed.c, BlockBed.e, BlockBed.g); - protected static final VoxelShape j = VoxelShapes.a(BlockBed.c, BlockBed.d, BlockBed.e); - protected static final VoxelShape k = VoxelShapes.a(BlockBed.c, BlockBed.f, BlockBed.g); - private final EnumColor color; - - public BlockBed(EnumColor enumcolor, Block.Info block_info) { - super(block_info); - this.color = enumcolor; - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockBed.PART, BlockPropertyBedPart.FOOT)).set(BlockBed.OCCUPIED, false)); - } - - @Override - public MaterialMapColor e(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.get(BlockBed.PART) == BlockPropertyBedPart.FOOT ? this.color.e() : MaterialMapColor.e; - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (world.isClientSide) { - return true; - } else { - if (iblockdata.get(BlockBed.PART) != BlockPropertyBedPart.HEAD) { - blockposition = blockposition.shift((EnumDirection) iblockdata.get(BlockBed.FACING)); - iblockdata = world.getType(blockposition); - if (iblockdata.getBlock() != this) { - return true; - } - } - - // CraftBukkit - moved world and biome check into EntityHuman - if (true || world.worldProvider.canRespawn() && world.getBiome(blockposition) != Biomes.NETHER) { - if ((Boolean) iblockdata.get(BlockBed.OCCUPIED)) { - entityhuman.a((IChatBaseComponent) (new ChatMessage("block.minecraft.bed.occupied", new Object[0])), true); - return true; - } else { - // CraftBukkit start - IBlockData finaliblockdata = iblockdata; - BlockPosition finalblockposition = blockposition; - // CraftBukkit end - entityhuman.sleep(blockposition).ifLeft((entityhuman_enumbedresult) -> { - // CraftBukkit start - handling bed explosion from below here - if (entityhuman_enumbedresult == EntityHuman.EnumBedResult.NOT_POSSIBLE_HERE) { - this.explodeBed(finaliblockdata, world, finalblockposition); - } else - // CraftBukkit end - if (entityhuman_enumbedresult != null) { - entityhuman.a(entityhuman_enumbedresult.a(), true); - } - - }); - return true; - } - // CraftBukkit start - moved bed explosion into separate method - } else { - return true; - } - } - } - - private boolean explodeBed(IBlockData iblockdata, World world, BlockPosition blockposition) { - world.a(blockposition, false); - BlockPosition blockposition1 = blockposition.shift(((EnumDirection) iblockdata.get(BlockBed.FACING)).opposite()); - - if (world.getType(blockposition1).getBlock() == this) { - world.a(blockposition1, false); - } - - world.createExplosion((Entity) null, DamageSource.a(), (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, 5.0F, true, Explosion.Effect.DESTROY); - return true; - // CraftBukkit end - } - - @Override - public void fallOn(World world, BlockPosition blockposition, Entity entity, float f) { - super.fallOn(world, blockposition, entity, f * 0.5F); - } - - @Override - public void a(IBlockAccess iblockaccess, Entity entity) { - if (entity.isSneaking()) { - super.a(iblockaccess, entity); - } else { - Vec3D vec3d = entity.getMot(); - - if (vec3d.y < 0.0D) { - double d0 = entity instanceof EntityLiving ? 1.0D : 0.8D; - - entity.setMot(vec3d.x, -vec3d.y * 0.6600000262260437D * d0, vec3d.z); - } - } - - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return enumdirection == a((BlockPropertyBedPart) iblockdata.get(BlockBed.PART), (EnumDirection) iblockdata.get(BlockBed.FACING)) ? (iblockdata1.getBlock() == this && iblockdata1.get(BlockBed.PART) != iblockdata.get(BlockBed.PART) ? (IBlockData) iblockdata.set(BlockBed.OCCUPIED, iblockdata1.get(BlockBed.OCCUPIED)) : Blocks.AIR.getBlockData()) : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - private static EnumDirection a(BlockPropertyBedPart blockpropertybedpart, EnumDirection enumdirection) { - return blockpropertybedpart == BlockPropertyBedPart.FOOT ? enumdirection : enumdirection.opposite(); - } - - @Override - public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, ItemStack itemstack) { - super.a(world, entityhuman, blockposition, Blocks.AIR.getBlockData(), tileentity, itemstack); - } - - @Override - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { - BlockPropertyBedPart blockpropertybedpart = (BlockPropertyBedPart) iblockdata.get(BlockBed.PART); - BlockPosition blockposition1 = blockposition.shift(a(blockpropertybedpart, (EnumDirection) iblockdata.get(BlockBed.FACING))); - IBlockData iblockdata1 = world.getType(blockposition1); - - if (iblockdata1.getBlock() == this && iblockdata1.get(BlockBed.PART) != blockpropertybedpart) { - world.setTypeAndData(blockposition1, Blocks.AIR.getBlockData(), 35); - world.a(entityhuman, 2001, blockposition1, Block.getCombinedId(iblockdata1)); - if (!world.isClientSide && !entityhuman.isCreative()) { - ItemStack itemstack = entityhuman.getItemInMainHand(); - - dropItems(iblockdata, world, blockposition, (TileEntity) null, entityhuman, itemstack); - dropItems(iblockdata1, world, blockposition1, (TileEntity) null, entityhuman, itemstack); - } - - entityhuman.b(StatisticList.BLOCK_MINED.b(this)); - } - - super.a(world, blockposition, iblockdata, entityhuman); - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - EnumDirection enumdirection = blockactioncontext.f(); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - - return blockactioncontext.getWorld().getType(blockposition1).a(blockactioncontext) ? (IBlockData) this.getBlockData().set(BlockBed.FACING, enumdirection) : null; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockBed.FACING); - EnumDirection enumdirection1 = iblockdata.get(BlockBed.PART) == BlockPropertyBedPart.HEAD ? enumdirection : enumdirection.opposite(); - - switch (enumdirection1) { - case NORTH: - return BlockBed.h; - case SOUTH: - return BlockBed.i; - case WEST: - return BlockBed.j; - default: - return BlockBed.k; - } - } - - public static Optional a(EntityTypes entitytypes, IWorldReader iworldreader, BlockPosition blockposition, int i) { - EnumDirection enumdirection = (EnumDirection) iworldreader.getType(blockposition).get(BlockBed.FACING); - // Paper start - configurable bed search radius - return findSafePosition(entitytypes, (World) iworldreader, enumdirection, blockposition); - } - /* - 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) { - BlockPosition blockposition1 = new BlockPosition(j2, k, k2); - Optional optional = a(entitytypes, iworldreader, blockposition1); - - if (optional.isPresent()) { - if (i <= 0) { - return optional; - } - - --i; - } - } - } - } - - return Optional.empty(); - } - */ - - private static Optional findSafePosition(EntityTypes entitytypes, World world, EnumDirection updirection, BlockPosition blockposition){ - int radius = world.paperConfig.bedSearchRadius; - double angle = Math.PI / 2; - int tmpX = (int)(updirection.getAdjacentX() * Math.cos(angle) - updirection.getAdjacentZ() * Math.sin(angle)); - int tmpZ = (int)(updirection.getAdjacentX() * Math.sin(angle) + updirection.getAdjacentZ() * Math.cos(angle)); - - EnumDirection rightDirection = EnumDirection.a(tmpX, 0, tmpZ); - EnumDirection downDirection = updirection.opposite(); - EnumDirection leftDirection = rightDirection.opposite(); - - EnumDirection[] corePositionOutDirection = new EnumDirection[6]; - corePositionOutDirection[0] = updirection; - corePositionOutDirection[1] = leftDirection; - corePositionOutDirection[2] = leftDirection; - corePositionOutDirection[3] = downDirection; - corePositionOutDirection[4] = rightDirection; - corePositionOutDirection[5] = rightDirection; - - BlockPosition[] corePosition = new BlockPosition[6]; - corePosition[0] = blockposition.add(updirection.getAdjacentX(), 0, updirection.getAdjacentZ()); - corePosition[1] = blockposition.add(leftDirection.getAdjacentX(), 0, leftDirection.getAdjacentZ()); - corePosition[2] = corePosition[1].add(downDirection.getAdjacentX(), 0, downDirection.getAdjacentZ()); - corePosition[3] = blockposition.add(2 * downDirection.getAdjacentX(), 0, 2 * downDirection.getAdjacentZ()); - corePosition[5] = blockposition.add(rightDirection.getAdjacentX(), 0, rightDirection.getAdjacentZ()); - corePosition[4] = corePosition[5].add(downDirection.getAdjacentX(), 0, downDirection.getAdjacentZ()); - - BlockPosition[] tmpPosition = new BlockPosition[8]; - EnumDirection[] tmpPositionDirection = new EnumDirection[8]; - tmpPositionDirection[0] = rightDirection; - tmpPositionDirection[1] = leftDirection; - tmpPositionDirection[2] = updirection; - tmpPositionDirection[3] = downDirection; - tmpPositionDirection[4] = leftDirection; - tmpPositionDirection[5] = rightDirection; - tmpPositionDirection[6] = downDirection; - tmpPositionDirection[7] = updirection; - - BlockPosition pos; - Optional vector; - for (int r = 1; r <= radius; r++) { - int h = 0; - while (h <= 1) { - int numIterated = 0; - for (int index = (int)(Math.random() * corePosition.length); numIterated < corePosition.length; index = (index+1) % corePosition.length) { - numIterated++; - - pos = corePosition[index].add(0, h, 0); - vector = isSafeRespawn(entitytypes, world, pos); - if (vector.isPresent()) { - return vector; - } - } - tmpPosition[0] = corePosition[0].add(0, h, 0); - tmpPosition[1] = corePosition[0].add(0, h, 0); - tmpPosition[2] = corePosition[1].add(0, h, 0); - tmpPosition[3] = corePosition[2].add(0, h, 0); - tmpPosition[4] = corePosition[3].add(0, h, 0); - tmpPosition[5] = corePosition[3].add(0, h, 0); - tmpPosition[6] = corePosition[4].add(0, h, 0); - tmpPosition[7] = corePosition[5].add(0, h, 0); - for (int rr = 1; rr <= r; rr++){ - numIterated = 0; - for (int index = (int)(Math.random() * tmpPosition.length); numIterated < tmpPosition.length; index = (index+1) % tmpPosition.length) { - numIterated++; - tmpPosition[index] = tmpPosition[index].add(tmpPositionDirection[index].getAdjacentX(), 0, tmpPositionDirection[index].getAdjacentZ()); - pos = tmpPosition[index]; - - vector = isSafeRespawn(entitytypes, world, pos); - if (vector.isPresent()) { - return vector; - } - } - } - switch (h) { - case -1: - h = 1; - break; - case 0: - h = -1; - break; - case 1: - h = Integer.MAX_VALUE; - break; - } - } - for (int index = 0; index < corePosition.length; index++) { - EnumDirection tmp = corePositionOutDirection[index]; - corePosition[index] = corePosition[index].add(tmp.getAdjacentX(), 0, tmp.getAdjacentZ()); - } - } - return Optional.empty(); - } - // Paper end - - protected static Optional isSafeRespawn(EntityTypes entityTypes, IWorldReader iworldreader, BlockPosition blockPosition) { return a(entityTypes, iworldreader, blockPosition); } // Paper -- obfhelper - protected static Optional a(EntityTypes entitytypes, IWorldReader iworldreader, BlockPosition blockposition) { - VoxelShape voxelshape = iworldreader.getType(blockposition).getCollisionShape(iworldreader, blockposition); - - if (voxelshape.c(EnumDirection.EnumAxis.Y) > 0.4375D) { - return Optional.empty(); - } else { - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(blockposition); - - while (blockposition_mutableblockposition.getY() >= 0 && blockposition.getY() - blockposition_mutableblockposition.getY() <= 2 && iworldreader.getType(blockposition_mutableblockposition).getCollisionShape(iworldreader, blockposition_mutableblockposition).isEmpty()) { - blockposition_mutableblockposition.c(EnumDirection.DOWN); - } - - VoxelShape voxelshape1 = iworldreader.getType(blockposition_mutableblockposition).getCollisionShape(iworldreader, blockposition_mutableblockposition); - - if (voxelshape1.isEmpty()) { - return Optional.empty(); - } else { - double d0 = (double) blockposition_mutableblockposition.getY() + voxelshape1.c(EnumDirection.EnumAxis.Y) + 2.0E-7D; - - if ((double) blockposition.getY() - d0 > 2.0D) { - return Optional.empty(); - } else { - float f = entitytypes.i() / 2.0F; - Vec3D vec3d = new Vec3D((double) blockposition_mutableblockposition.getX() + 0.5D, d0, (double) blockposition_mutableblockposition.getZ() + 0.5D); - - return iworldreader.c(new AxisAlignedBB(vec3d.x - (double) f, vec3d.y, vec3d.z - (double) f, vec3d.x + (double) f, vec3d.y + (double) entitytypes.j(), vec3d.z + (double) f)) ? Optional.of(vec3d) : Optional.empty(); - } - } - } - } - - @Override - public EnumPistonReaction getPushReaction(IBlockData iblockdata) { - return EnumPistonReaction.DESTROY; - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.ENTITYBLOCK_ANIMATED; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockBed.FACING, BlockBed.PART, BlockBed.OCCUPIED); - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityBed(this.color); - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, @Nullable EntityLiving entityliving, ItemStack itemstack) { - super.postPlace(world, blockposition, iblockdata, entityliving, itemstack); - if (!world.isClientSide) { - BlockPosition blockposition1 = blockposition.shift((EnumDirection) iblockdata.get(BlockBed.FACING)); - - world.setTypeAndData(blockposition1, (IBlockData) iblockdata.set(BlockBed.PART, BlockPropertyBedPart.HEAD), 3); - world.update(blockposition, Blocks.AIR); - iblockdata.a(world, blockposition, 3); - } - - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockButtonAbstract.java b/src/main/java/net/minecraft/server/BlockButtonAbstract.java deleted file mode 100644 index 1fa20d8a7..000000000 --- a/src/main/java/net/minecraft/server/BlockButtonAbstract.java +++ /dev/null @@ -1,226 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import java.util.Random; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.entity.EntityInteractEvent; -// CraftBukkit end - -public abstract class BlockButtonAbstract extends BlockAttachable { - - public static final BlockStateBoolean POWERED = BlockProperties.w; - protected static final VoxelShape b = Block.a(6.0D, 14.0D, 5.0D, 10.0D, 16.0D, 11.0D); - protected static final VoxelShape c = Block.a(5.0D, 14.0D, 6.0D, 11.0D, 16.0D, 10.0D); - protected static final VoxelShape d = Block.a(6.0D, 0.0D, 5.0D, 10.0D, 2.0D, 11.0D); - protected static final VoxelShape e = Block.a(5.0D, 0.0D, 6.0D, 11.0D, 2.0D, 10.0D); - protected static final VoxelShape f = Block.a(5.0D, 6.0D, 14.0D, 11.0D, 10.0D, 16.0D); - protected static final VoxelShape g = Block.a(5.0D, 6.0D, 0.0D, 11.0D, 10.0D, 2.0D); - protected static final VoxelShape h = Block.a(14.0D, 6.0D, 5.0D, 16.0D, 10.0D, 11.0D); - protected static final VoxelShape i = Block.a(0.0D, 6.0D, 5.0D, 2.0D, 10.0D, 11.0D); - protected static final VoxelShape j = Block.a(6.0D, 15.0D, 5.0D, 10.0D, 16.0D, 11.0D); - protected static final VoxelShape k = Block.a(5.0D, 15.0D, 6.0D, 11.0D, 16.0D, 10.0D); - protected static final VoxelShape w = Block.a(6.0D, 0.0D, 5.0D, 10.0D, 1.0D, 11.0D); - protected static final VoxelShape x = Block.a(5.0D, 0.0D, 6.0D, 11.0D, 1.0D, 10.0D); - protected static final VoxelShape y = Block.a(5.0D, 6.0D, 15.0D, 11.0D, 10.0D, 16.0D); - protected static final VoxelShape z = Block.a(5.0D, 6.0D, 0.0D, 11.0D, 10.0D, 1.0D); - protected static final VoxelShape A = Block.a(15.0D, 6.0D, 5.0D, 16.0D, 10.0D, 11.0D); - protected static final VoxelShape B = Block.a(0.0D, 6.0D, 5.0D, 1.0D, 10.0D, 11.0D); - private final boolean D; - - protected BlockButtonAbstract(boolean flag, Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockButtonAbstract.FACING, EnumDirection.NORTH)).set(BlockButtonAbstract.POWERED, false)).set(BlockButtonAbstract.FACE, BlockPropertyAttachPosition.WALL)); - this.D = flag; - } - - @Override - public int a(IWorldReader iworldreader) { - return this.D ? 30 : 20; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockButtonAbstract.FACING); - boolean flag = (Boolean) iblockdata.get(BlockButtonAbstract.POWERED); - - switch ((BlockPropertyAttachPosition) iblockdata.get(BlockButtonAbstract.FACE)) { - case FLOOR: - if (enumdirection.k() == EnumDirection.EnumAxis.X) { - return flag ? BlockButtonAbstract.w : BlockButtonAbstract.d; - } - - return flag ? BlockButtonAbstract.x : BlockButtonAbstract.e; - case WALL: - switch (enumdirection) { - case EAST: - return flag ? BlockButtonAbstract.B : BlockButtonAbstract.i; - case WEST: - return flag ? BlockButtonAbstract.A : BlockButtonAbstract.h; - case SOUTH: - return flag ? BlockButtonAbstract.z : BlockButtonAbstract.g; - case NORTH: - default: - return flag ? BlockButtonAbstract.y : BlockButtonAbstract.f; - } - case CEILING: - default: - return enumdirection.k() == EnumDirection.EnumAxis.X ? (flag ? BlockButtonAbstract.j : BlockButtonAbstract.b) : (flag ? BlockButtonAbstract.k : BlockButtonAbstract.c); - } - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if ((Boolean) iblockdata.get(BlockButtonAbstract.POWERED)) { - return true; - } else { - // CraftBukkit start - boolean powered = ((Boolean) 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) iblockdata.set(BlockButtonAbstract.POWERED, true), 3); - this.a(entityhuman, world, blockposition, true); - this.e(iblockdata, world, blockposition); - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world)); - return true; - } - } - - protected void a(@Nullable EntityHuman entityhuman, GeneratorAccess generatoraccess, BlockPosition blockposition, boolean flag) { - generatoraccess.playSound(flag ? entityhuman : null, blockposition, this.a(flag), SoundCategory.BLOCKS, 0.3F, flag ? 0.6F : 0.5F); - } - - protected abstract SoundEffect a(boolean flag); - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (!flag && iblockdata.getBlock() != iblockdata1.getBlock()) { - if ((Boolean) iblockdata.get(BlockButtonAbstract.POWERED)) { - this.e(iblockdata, world, blockposition); - } - - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - } - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Boolean) iblockdata.get(BlockButtonAbstract.POWERED) ? 15 : 0; - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Boolean) iblockdata.get(BlockButtonAbstract.POWERED) && j(iblockdata) == enumdirection ? 15 : 0; - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.isClientSide && (Boolean) iblockdata.get(BlockButtonAbstract.POWERED)) { - if (this.D) { - this.d(iblockdata, world, blockposition); - } 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.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockButtonAbstract.POWERED, false), 3); - this.e(iblockdata, world, blockposition); - this.a((EntityHuman) null, world, blockposition, false); - } - - } - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (!world.isClientSide && this.D && !(Boolean) iblockdata.get(BlockButtonAbstract.POWERED)) { - this.d(iblockdata, world, blockposition); - } - } - - private void d(IBlockData iblockdata, World world, BlockPosition blockposition) { - List list = world.a(EntityArrow.class, iblockdata.getShape(world, blockposition).getBoundingBox().a(blockposition)); - boolean flag = !list.isEmpty(); - boolean flag1 = (Boolean) 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 (Object object : list) { - if (object != null) { - EntityInteractEvent event = new EntityInteractEvent(((Entity) object).getBukkitEntity(), block); - world.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - allowed = true; - break; - } - } - } - - if (!allowed) { - return; - } - } - // CraftBukkit end - - if (flag != flag1) { - // CraftBukkit start - boolean powered = flag1; - 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 ((flag && eventRedstone.getNewCurrent() <= 0) || (!flag && eventRedstone.getNewCurrent() > 0)) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockButtonAbstract.POWERED, flag), 3); - this.e(iblockdata, world, blockposition); - this.a((EntityHuman) null, world, blockposition, flag); - } - - if (flag) { - world.getBlockTickList().a(new BlockPosition(blockposition), this, this.a((IWorldReader) world)); - } - - } - - private void e(IBlockData iblockdata, World world, BlockPosition blockposition) { - world.applyPhysics(blockposition, this); - world.applyPhysics(blockposition.shift(j(iblockdata).opposite()), this); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockButtonAbstract.FACING, BlockButtonAbstract.POWERED, BlockButtonAbstract.FACE); - } -} diff --git a/src/main/java/net/minecraft/server/BlockCactus.java b/src/main/java/net/minecraft/server/BlockCactus.java deleted file mode 100644 index 124b4b4b0..000000000 --- a/src/main/java/net/minecraft/server/BlockCactus.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Random; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockCactus extends Block { - - public static final BlockStateInteger AGE = BlockProperties.ad; - protected static final VoxelShape b = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 15.0D, 15.0D); - protected static final VoxelShape c = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 16.0D, 15.0D); - - protected BlockCactus(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockCactus.AGE, 0)); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!iblockdata.canPlace(world, blockposition)) { - world.b(blockposition, true); - } else { - if (world.paperConfig.fixZeroTickInstantGrowFarms && !randomTick) return; // Paper - fix MC-113809 - BlockPosition blockposition1 = blockposition.up(); - - if (world.isEmpty(blockposition1)) { - int i; - - for (i = 1; world.getType(blockposition.down(i)).getBlock() == this; ++i) { - ; - } - - if (i < world.paperConfig.cactusMaxHeight) { // Paper - Configurable growth height - int j = (Integer) iblockdata.get(BlockCactus.AGE); - - if (j >= (byte) range(3, ((100.0F / world.spigotConfig.cactusModifier) * 15) + 0.5F, 15)) { // Spigot - CraftEventFactory.handleBlockGrowEvent(world, blockposition1, this.getBlockData()); // CraftBukkit - IBlockData iblockdata1 = (IBlockData) iblockdata.set(BlockCactus.AGE, 0); - - world.setTypeAndData(blockposition, iblockdata1, 4); - iblockdata1.doPhysics(world, blockposition1, this, blockposition, false); - } else { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockCactus.AGE, j + 1), 4); - } - - } - } - } - } - - @Override - public VoxelShape b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockCactus.b; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockCactus.c; - } - - @Override - public boolean f(IBlockData iblockdata) { - return true; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (!iblockdata.canPlace(generatoraccess, blockposition)) { - generatoraccess.getBlockTickList().a(blockposition, this, 1); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - EnumDirection enumdirection; - Material material; - - do { - if (!iterator.hasNext()) { - Block block = iworldreader.getType(blockposition.down()).getBlock(); - - return (block == Blocks.CACTUS || block == Blocks.SAND || block == Blocks.RED_SAND) && !iworldreader.getType(blockposition.up()).getMaterial().isLiquid(); - } - - enumdirection = (EnumDirection) iterator.next(); - IBlockData iblockdata1 = iworldreader.getType(blockposition.shift(enumdirection)); - - material = iblockdata1.getMaterial(); - } while (!material.isBuildable() && !iworldreader.getFluid(blockposition.shift(enumdirection)).a(TagsFluid.LAVA)); - - return false; - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - CraftEventFactory.blockDamage = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); // CraftBukkit - entity.damageEntity(DamageSource.CACTUS, 1.0F); - CraftEventFactory.blockDamage = null; // CraftBukkit - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockCactus.AGE); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockCake.java b/src/main/java/net/minecraft/server/BlockCake.java deleted file mode 100644 index 815be80e0..000000000 --- a/src/main/java/net/minecraft/server/BlockCake.java +++ /dev/null @@ -1,87 +0,0 @@ -package net.minecraft.server; - -public class BlockCake extends Block { - - public static final BlockStateInteger BITES = BlockProperties.af; - protected static final VoxelShape[] b = new VoxelShape[]{Block.a(1.0D, 0.0D, 1.0D, 15.0D, 8.0D, 15.0D), Block.a(3.0D, 0.0D, 1.0D, 15.0D, 8.0D, 15.0D), Block.a(5.0D, 0.0D, 1.0D, 15.0D, 8.0D, 15.0D), Block.a(7.0D, 0.0D, 1.0D, 15.0D, 8.0D, 15.0D), Block.a(9.0D, 0.0D, 1.0D, 15.0D, 8.0D, 15.0D), Block.a(11.0D, 0.0D, 1.0D, 15.0D, 8.0D, 15.0D), Block.a(13.0D, 0.0D, 1.0D, 15.0D, 8.0D, 15.0D)}; - - protected BlockCake(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockCake.BITES, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockCake.b[(Integer) iblockdata.get(BlockCake.BITES)]; - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (!world.isClientSide) { - return this.a((GeneratorAccess) world, blockposition, iblockdata, entityhuman); - } else { - ItemStack itemstack = entityhuman.b(enumhand); - - return this.a((GeneratorAccess) world, blockposition, iblockdata, entityhuman) || itemstack.isEmpty(); - } - } - - private boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { - if (!entityhuman.p(false)) { - return false; - } else { - entityhuman.a(StatisticList.EAT_CAKE_SLICE); - // 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); - } - - ((EntityPlayer) entityhuman).getBukkitEntity().sendHealthUpdate(); - // CraftBukkit end - int i = (Integer) iblockdata.get(BlockCake.BITES); - - if (i < 6) { - generatoraccess.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockCake.BITES, i + 1), 3); - } else { - generatoraccess.a(blockposition, false); - } - - return true; - } - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return enumdirection == EnumDirection.DOWN && !iblockdata.canPlace(generatoraccess, blockposition) ? Blocks.AIR.getBlockData() : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - return iworldreader.getType(blockposition.down()).getMaterial().isBuildable(); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockCake.BITES); - } - - @Override - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - return (7 - (Integer) iblockdata.get(BlockCake.BITES)) * 2; - } - - @Override - public boolean isComplexRedstone(IBlockData iblockdata) { - return true; - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockCampfire.java b/src/main/java/net/minecraft/server/BlockCampfire.java deleted file mode 100644 index 9d59e339c..000000000 --- a/src/main/java/net/minecraft/server/BlockCampfire.java +++ /dev/null @@ -1,196 +0,0 @@ -package net.minecraft.server; - -import java.util.Optional; -import java.util.Random; -import javax.annotation.Nullable; - -public class BlockCampfire extends BlockTileEntity implements IBlockWaterlogged { - - protected static final VoxelShape a = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 7.0D, 16.0D); - public static final BlockStateBoolean b = BlockProperties.r; - public static final BlockStateBoolean c = BlockProperties.y; - public static final BlockStateBoolean d = BlockProperties.C; - public static final BlockStateDirection e = BlockProperties.N; - - public BlockCampfire(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockCampfire.b, true)).set(BlockCampfire.c, false)).set(BlockCampfire.d, false)).set(BlockCampfire.e, EnumDirection.NORTH)); - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if ((Boolean) iblockdata.get(BlockCampfire.b)) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityCampfire) { - TileEntityCampfire tileentitycampfire = (TileEntityCampfire) tileentity; - ItemStack itemstack = entityhuman.b(enumhand); - Optional optional = tileentitycampfire.a(itemstack); - - if (optional.isPresent()) { - if (!world.isClientSide && tileentitycampfire.a(entityhuman.abilities.canInstantlyBuild ? itemstack.cloneItemStack() : itemstack, ((RecipeCampfire) optional.get()).e())) { - entityhuman.a(StatisticList.INTERACT_WITH_CAMPFIRE); - } - - return true; - } - } - } - - return false; - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (!entity.isFireProof() && (Boolean) iblockdata.get(BlockCampfire.b) && entity instanceof EntityLiving && !EnchantmentManager.i((EntityLiving) entity)) { - entity.damageEntity(DamageSource.FIRE, 1.0F); - } - - super.a(iblockdata, world, blockposition, entity); - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata.getBlock() != iblockdata1.getBlock()) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityCampfire) { - InventoryUtils.a(world, blockposition, ((TileEntityCampfire) tileentity).getItems()); - } - - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - } - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - World world = blockactioncontext.getWorld(); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - boolean flag = world.getFluid(blockposition).getType() == FluidTypes.WATER; - - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.getBlockData().set(BlockCampfire.d, flag)).set(BlockCampfire.c, this.j(world.getType(blockposition.down())))).set(BlockCampfire.b, !flag)).set(BlockCampfire.e, blockactioncontext.f()); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if ((Boolean) iblockdata.get(BlockCampfire.d)) { - generatoraccess.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) generatoraccess)); - } - - return enumdirection == EnumDirection.DOWN ? (IBlockData) iblockdata.set(BlockCampfire.c, this.j(iblockdata1)) : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - private boolean j(IBlockData iblockdata) { - return iblockdata.getBlock() == Blocks.HAY_BLOCK; - } - - @Override - public int a(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockCampfire.b) ? super.a(iblockdata) : 0; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockCampfire.a; - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.MODEL; - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - public boolean place(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, Fluid fluid) { - if (!(Boolean) iblockdata.get(BlockProperties.C) && fluid.getType() == FluidTypes.WATER) { - boolean flag = (Boolean) iblockdata.get(BlockCampfire.b); - - if (flag) { - if (generatoraccess.e()) { - for (int i = 0; i < 20; ++i) { - a(generatoraccess.getMinecraftWorld(), blockposition, (Boolean) iblockdata.get(BlockCampfire.c), true); - } - } else { - generatoraccess.playSound((EntityHuman) null, blockposition, SoundEffects.ENTITY_GENERIC_EXTINGUISH_FIRE, SoundCategory.BLOCKS, 1.0F, 1.0F); - } - - TileEntity tileentity = generatoraccess.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityCampfire) { - ((TileEntityCampfire) tileentity).f(); - } - } - - generatoraccess.setTypeAndData(blockposition, (IBlockData) ((IBlockData) iblockdata.set(BlockCampfire.d, true)).set(BlockCampfire.b, false), 3); - generatoraccess.getFluidTickList().a(blockposition, fluid.getType(), fluid.getType().a((IWorldReader) generatoraccess)); - return true; - } else { - return false; - } - } - - @Override - public void a(World world, IBlockData iblockdata, MovingObjectPositionBlock movingobjectpositionblock, Entity entity) { - if (!world.isClientSide && entity instanceof EntityArrow) { - EntityArrow entityarrow = (EntityArrow) entity; - - if (entityarrow.isBurning() && !(Boolean) iblockdata.get(BlockCampfire.b) && !(Boolean) iblockdata.get(BlockCampfire.d)) { - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition(); - - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition, entityarrow).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockProperties.r, true), 11); - } - } - - } - - public static void a(World world, BlockPosition blockposition, boolean flag, boolean flag1) { - Random random = world.getRandom(); - ParticleType particletype = flag ? Particles.CAMPFIRE_SIGNAL_SMOKE : Particles.CAMPFIRE_COSY_SMOKE; - - world.b(particletype, true, (double) blockposition.getX() + 0.5D + random.nextDouble() / 3.0D * (double) (random.nextBoolean() ? 1 : -1), (double) blockposition.getY() + random.nextDouble() + random.nextDouble(), (double) blockposition.getZ() + 0.5D + random.nextDouble() / 3.0D * (double) (random.nextBoolean() ? 1 : -1), 0.0D, 0.07D, 0.0D); - if (flag1) { - world.addParticle(Particles.SMOKE, (double) blockposition.getX() + 0.25D + random.nextDouble() / 2.0D * (double) (random.nextBoolean() ? 1 : -1), (double) blockposition.getY() + 0.4D, (double) blockposition.getZ() + 0.25D + random.nextDouble() / 2.0D * (double) (random.nextBoolean() ? 1 : -1), 0.0D, 0.005D, 0.0D); - } - - } - - @Override - public Fluid g(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockCampfire.d) ? FluidTypes.WATER.a(false) : super.g(iblockdata); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return (IBlockData) iblockdata.set(BlockCampfire.e, enumblockrotation.a((EnumDirection) iblockdata.get(BlockCampfire.e))); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockCampfire.e))); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockCampfire.b, BlockCampfire.c, BlockCampfire.d, BlockCampfire.e); - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityCampfire(); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockCauldron.java b/src/main/java/net/minecraft/server/BlockCauldron.java deleted file mode 100644 index 44ffa2708..000000000 --- a/src/main/java/net/minecraft/server/BlockCauldron.java +++ /dev/null @@ -1,269 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.event.block.CauldronLevelChangeEvent; // CraftBukkit - -public class BlockCauldron extends Block { - - public static final BlockStateInteger LEVEL = BlockProperties.al; - private static final VoxelShape c = a(2.0D, 4.0D, 2.0D, 14.0D, 16.0D, 14.0D); - protected static final VoxelShape b = VoxelShapes.a(VoxelShapes.b(), VoxelShapes.a(a(0.0D, 0.0D, 4.0D, 16.0D, 3.0D, 12.0D), a(4.0D, 0.0D, 0.0D, 12.0D, 3.0D, 16.0D), a(2.0D, 0.0D, 2.0D, 14.0D, 3.0D, 14.0D), BlockCauldron.c), OperatorBoolean.ONLY_FIRST); - - public BlockCauldron(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockCauldron.LEVEL, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockCauldron.b; - } - - @Override - public boolean f(IBlockData iblockdata) { - return false; - } - - @Override - public VoxelShape i(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return BlockCauldron.c; - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - int i = (Integer) iblockdata.get(BlockCauldron.LEVEL); - float f = (float) blockposition.getY() + (6.0F + (float) (3 * i)) / 16.0F; - - if (!world.isClientSide && entity.isBurning() && i > 0 && entity.getBoundingBox().minY <= (double) f) { - // CraftBukkit start - if (!this.changeLevel(world, blockposition, iblockdata, i - 1, entity, CauldronLevelChangeEvent.ChangeReason.EXTINGUISH)) { - return; - } - entity.extinguish(); - // this.a(world, blockposition, iblockdata, i - 1); - // CraftBukkit end - } - - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.isEmpty()) { - return true; - } else { - int i = (Integer) iblockdata.get(BlockCauldron.LEVEL); - Item item = itemstack.getItem(); - - if (item == Items.WATER_BUCKET) { - if (i < 3 && !world.isClientSide) { - // CraftBukkit start - if (!this.changeLevel(world, blockposition, iblockdata, 3, entityhuman, CauldronLevelChangeEvent.ChangeReason.BUCKET_EMPTY)) { - return true; - } - if (!entityhuman.abilities.canInstantlyBuild) { - entityhuman.a(enumhand, new ItemStack(Items.BUCKET)); - } - - entityhuman.a(StatisticList.FILL_CAULDRON); - // this.a(world, blockposition, iblockdata, 3); - // CraftBukkit end - world.playSound((EntityHuman) null, blockposition, SoundEffects.ITEM_BUCKET_EMPTY, SoundCategory.BLOCKS, 1.0F, 1.0F); - } - - return true; - } else if (item == Items.BUCKET) { - if (i == 3 && !world.isClientSide) { - // CraftBukkit start - if (!this.changeLevel(world, blockposition, iblockdata, 0, entityhuman, CauldronLevelChangeEvent.ChangeReason.BUCKET_FILL)) { - return true; - } - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - if (itemstack.isEmpty()) { - entityhuman.a(enumhand, new ItemStack(Items.WATER_BUCKET)); - } else if (!entityhuman.inventory.pickup(new ItemStack(Items.WATER_BUCKET))) { - entityhuman.drop(new ItemStack(Items.WATER_BUCKET), false); - } - } - - entityhuman.a(StatisticList.USE_CAULDRON); - // this.a(world, blockposition, iblockdata, 0); - // CraftBukkit end - world.playSound((EntityHuman) null, blockposition, SoundEffects.ITEM_BUCKET_FILL, SoundCategory.BLOCKS, 1.0F, 1.0F); - } - - return true; - } else { - ItemStack itemstack1; - - if (item == Items.GLASS_BOTTLE) { - if (i > 0 && !world.isClientSide) { - // CraftBukkit start - if (!this.changeLevel(world, blockposition, iblockdata, i - 1, entityhuman, CauldronLevelChangeEvent.ChangeReason.BOTTLE_FILL)) { - return true; - } - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack1 = PotionUtil.a(new ItemStack(Items.POTION), Potions.WATER); - entityhuman.a(StatisticList.USE_CAULDRON); - itemstack.subtract(1); - if (itemstack.isEmpty()) { - entityhuman.a(enumhand, itemstack1); - } else if (!entityhuman.inventory.pickup(itemstack1)) { - entityhuman.drop(itemstack1, false); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).updateInventory(entityhuman.defaultContainer); - } - } - - world.playSound((EntityHuman) null, blockposition, SoundEffects.ITEM_BOTTLE_FILL, SoundCategory.BLOCKS, 1.0F, 1.0F); - // this.a(world, blockposition, iblockdata, i - 1); - // CraftBukkit end - } - - return true; - } else if (item == Items.POTION && PotionUtil.d(itemstack) == Potions.WATER) { - if (i < 3 && !world.isClientSide) { - // CraftBukkit start - if (!this.changeLevel(world, blockposition, iblockdata, i + 1, entityhuman, CauldronLevelChangeEvent.ChangeReason.BOTTLE_EMPTY)) { - return true; - } - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack1 = new ItemStack(Items.GLASS_BOTTLE); - entityhuman.a(StatisticList.USE_CAULDRON); - entityhuman.a(enumhand, itemstack1); - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).updateInventory(entityhuman.defaultContainer); - } - } - - world.playSound((EntityHuman) null, blockposition, SoundEffects.ITEM_BOTTLE_EMPTY, SoundCategory.BLOCKS, 1.0F, 1.0F); - // this.a(world, blockposition, iblockdata, i + 1); - // CraftBukkit end - } - - return true; - } else { - if (i > 0 && item instanceof IDyeable) { - IDyeable idyeable = (IDyeable) item; - - if (idyeable.a(itemstack) && !world.isClientSide) { - // CraftBukkit start - if (!this.changeLevel(world, blockposition, iblockdata, i - 1, entityhuman, CauldronLevelChangeEvent.ChangeReason.ARMOR_WASH)) { - return true; - } - idyeable.c(itemstack); - // this.a(world, blockposition, iblockdata, i - 1); - // CraftBukkit end - entityhuman.a(StatisticList.CLEAN_ARMOR); - return true; - } - } - - if (i > 0 && item instanceof ItemBanner) { - if (TileEntityBanner.a(itemstack) > 0 && !world.isClientSide) { - // CraftBukkit start - if (!this.changeLevel(world, blockposition, iblockdata, i - 1, entityhuman, CauldronLevelChangeEvent.ChangeReason.BANNER_WASH)) { - return true; - } - itemstack1 = itemstack.cloneItemStack(); - itemstack1.setCount(1); - TileEntityBanner.b(itemstack1); - entityhuman.a(StatisticList.CLEAN_BANNER); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - // this.a(world, blockposition, iblockdata, i - 1); - // CraftBukkit end - } - - if (itemstack.isEmpty()) { - entityhuman.a(enumhand, itemstack1); - } else if (!entityhuman.inventory.pickup(itemstack1)) { - entityhuman.drop(itemstack1, false); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).updateInventory(entityhuman.defaultContainer); - } - } - - return true; - } else if (i > 0 && item instanceof ItemBlock) { - Block block = ((ItemBlock) item).getBlock(); - - if (block instanceof BlockShulkerBox && !world.e()) { - ItemStack itemstack2 = new ItemStack(Blocks.SHULKER_BOX, 1); - - if (itemstack.hasTag()) { - itemstack2.setTag(itemstack.getTag().clone()); - } - - entityhuman.a(enumhand, itemstack2); - this.a(world, blockposition, iblockdata, i - 1); - entityhuman.a(StatisticList.CLEAN_SHULKER_BOX); - } - - return true; - } else { - return false; - } - } - } - } - } - - // CraftBukkit start - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { - this.changeLevel(world, blockposition, iblockdata, i, null, CauldronLevelChangeEvent.ChangeReason.UNKNOWN); - } - - private boolean changeLevel(World world, BlockPosition blockposition, IBlockData iblockdata, int i, Entity entity, CauldronLevelChangeEvent.ChangeReason reason) { - int newLevel = Integer.valueOf(MathHelper.clamp(i, 0, 3)); - CauldronLevelChangeEvent event = new CauldronLevelChangeEvent( - world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), - (entity == null) ? null : entity.getBukkitEntity(), reason, iblockdata.get(BlockCauldron.LEVEL), newLevel - ); - world.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return false; - } - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockCauldron.LEVEL, event.getNewLevel()), 2); - world.updateAdjacentComparators(blockposition, this); - return true; - // CraftBukkit end - } - - @Override - public void c(World world, BlockPosition blockposition) { - if (world.random.nextInt(20) == 1) { - float f = world.getBiome(blockposition).getAdjustedTemperature(blockposition); - - if (f >= 0.15F) { - IBlockData iblockdata = world.getType(blockposition); - - if ((Integer) iblockdata.get(BlockCauldron.LEVEL) < 3) { - this.a(world, blockposition, (IBlockData) iblockdata.a((IBlockState) BlockCauldron.LEVEL), 2); // CraftBukkit - } - - } - } - } - - @Override - public boolean isComplexRedstone(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - return (Integer) iblockdata.get(BlockCauldron.LEVEL); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockCauldron.LEVEL); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockChest.java b/src/main/java/net/minecraft/server/BlockChest.java deleted file mode 100644 index 8183a61c9..000000000 --- a/src/main/java/net/minecraft/server/BlockChest.java +++ /dev/null @@ -1,346 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -public class BlockChest extends BlockTileEntity implements IBlockWaterlogged { - - public static final BlockStateDirection FACING = BlockFacingHorizontal.FACING; - public static final BlockStateEnum b = BlockProperties.ax; - public static final BlockStateBoolean c = BlockProperties.C; - protected static final VoxelShape d = Block.a(1.0D, 0.0D, 0.0D, 15.0D, 14.0D, 15.0D); - protected static final VoxelShape e = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 14.0D, 16.0D); - protected static final VoxelShape f = Block.a(0.0D, 0.0D, 1.0D, 15.0D, 14.0D, 15.0D); - protected static final VoxelShape g = Block.a(1.0D, 0.0D, 1.0D, 16.0D, 14.0D, 15.0D); - protected static final VoxelShape h = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 14.0D, 15.0D); - private static final BlockChest.ChestFinder i = new BlockChest.ChestFinder() { - @Override - public IInventory b(TileEntityChest tileentitychest, TileEntityChest tileentitychest1) { - return new InventoryLargeChest(tileentitychest, tileentitychest1); - } - - @Override - public IInventory b(TileEntityChest tileentitychest) { - return tileentitychest; - } - }; - private static final BlockChest.ChestFinder j = new BlockChest.ChestFinder() { - @Override - public ITileInventory b(final TileEntityChest tileentitychest, final TileEntityChest tileentitychest1) { - final InventoryLargeChest inventorylargechest = new InventoryLargeChest(tileentitychest, tileentitychest1); - - return new DoubleInventory(tileentitychest, tileentitychest1, inventorylargechest); // CraftBukkit - } - - @Override - public ITileInventory b(TileEntityChest tileentitychest) { - return tileentitychest; - } - }; - - // CraftBukkit start - public static class DoubleInventory implements ITileInventory { - - private final TileEntityChest tileentitychest; - private final TileEntityChest tileentitychest1; - public final InventoryLargeChest inventorylargechest; - - public DoubleInventory(TileEntityChest tileentitychest, TileEntityChest tileentitychest1, InventoryLargeChest inventorylargechest) { - this.tileentitychest = tileentitychest; - this.tileentitychest1 = tileentitychest1; - this.inventorylargechest = inventorylargechest; - } - - @Nullable - @Override - public Container createMenu(int i, PlayerInventory playerinventory, EntityHuman entityhuman) { - if (tileentitychest.e(entityhuman) && tileentitychest1.e(entityhuman)) { - tileentitychest.d(playerinventory.player); - tileentitychest1.d(playerinventory.player); - return ContainerChest.b(i, playerinventory, inventorylargechest); - } else { - return null; - } - } - - @Override - public IChatBaseComponent getScoreboardDisplayName() { - return (IChatBaseComponent) (tileentitychest.hasCustomName() ? tileentitychest.getScoreboardDisplayName() : (tileentitychest1.hasCustomName() ? tileentitychest1.getScoreboardDisplayName() : new ChatMessage("container.chestDouble", new Object[0]))); - } - }; - // CraftBukkit end - - protected BlockChest(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockChest.FACING, EnumDirection.NORTH)).set(BlockChest.b, BlockPropertyChestType.SINGLE)).set(BlockChest.c, false)); - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.ENTITYBLOCK_ANIMATED; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if ((Boolean) iblockdata.get(BlockChest.c)) { - generatoraccess.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) generatoraccess)); - } - - if (iblockdata1.getBlock() == this && enumdirection.k().c()) { - BlockPropertyChestType blockpropertychesttype = (BlockPropertyChestType) iblockdata1.get(BlockChest.b); - - if (iblockdata.get(BlockChest.b) == BlockPropertyChestType.SINGLE && blockpropertychesttype != BlockPropertyChestType.SINGLE && iblockdata.get(BlockChest.FACING) == iblockdata1.get(BlockChest.FACING) && j(iblockdata1) == enumdirection.opposite()) { - return (IBlockData) iblockdata.set(BlockChest.b, blockpropertychesttype.a()); - } - } else if (j(iblockdata) == enumdirection) { - return (IBlockData) iblockdata.set(BlockChest.b, BlockPropertyChestType.SINGLE); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - if (iblockdata.get(BlockChest.b) == BlockPropertyChestType.SINGLE) { - return BlockChest.h; - } else { - switch (j(iblockdata)) { - case NORTH: - default: - return BlockChest.d; - case SOUTH: - return BlockChest.e; - case WEST: - return BlockChest.f; - case EAST: - return BlockChest.g; - } - } - } - - public static EnumDirection j(IBlockData iblockdata) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockChest.FACING); - - return iblockdata.get(BlockChest.b) == BlockPropertyChestType.LEFT ? enumdirection.e() : enumdirection.f(); - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - BlockPropertyChestType blockpropertychesttype = BlockPropertyChestType.SINGLE; - EnumDirection enumdirection = blockactioncontext.f().opposite(); - Fluid fluid = blockactioncontext.getWorld().getFluid(blockactioncontext.getClickPosition()); - boolean flag = blockactioncontext.isSneaking(); - EnumDirection enumdirection1 = blockactioncontext.getClickedFace(); - - if (enumdirection1.k().c() && flag) { - EnumDirection enumdirection2 = this.a(blockactioncontext, enumdirection1.opposite()); - - if (enumdirection2 != null && enumdirection2.k() != enumdirection1.k()) { - enumdirection = enumdirection2; - blockpropertychesttype = enumdirection2.f() == enumdirection1.opposite() ? BlockPropertyChestType.RIGHT : BlockPropertyChestType.LEFT; - } - } - - if (blockpropertychesttype == BlockPropertyChestType.SINGLE && !flag) { - if (enumdirection == this.a(blockactioncontext, enumdirection.e())) { - blockpropertychesttype = BlockPropertyChestType.LEFT; - } else if (enumdirection == this.a(blockactioncontext, enumdirection.f())) { - blockpropertychesttype = BlockPropertyChestType.RIGHT; - } - } - - return (IBlockData) ((IBlockData) ((IBlockData) this.getBlockData().set(BlockChest.FACING, enumdirection)).set(BlockChest.b, blockpropertychesttype)).set(BlockChest.c, fluid.getType() == FluidTypes.WATER); - } - - @Override - public Fluid g(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockChest.c) ? FluidTypes.WATER.a(false) : super.g(iblockdata); - } - - @Nullable - private EnumDirection a(BlockActionContext blockactioncontext, EnumDirection enumdirection) { - IBlockData iblockdata = blockactioncontext.getWorld().getType(blockactioncontext.getClickPosition().shift(enumdirection)); - - return iblockdata.getBlock() == this && iblockdata.get(BlockChest.b) == BlockPropertyChestType.SINGLE ? (EnumDirection) iblockdata.get(BlockChest.FACING) : null; - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { - if (itemstack.hasName()) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityChest) { - ((TileEntityChest) tileentity).setCustomName(itemstack.getName()); - } - } - - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata.getBlock() != iblockdata1.getBlock()) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof IInventory) { - InventoryUtils.dropInventory(world, blockposition, (IInventory) tileentity); - world.updateAdjacentComparators(blockposition, this); - } - - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - } - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (world.isClientSide) { - return true; - } else { - ITileInventory itileinventory = this.getInventory(iblockdata, world, blockposition); - - if (itileinventory != null) { - entityhuman.openContainer(itileinventory); - entityhuman.b(this.d()); - } - - return true; - } - } - - protected Statistic d() { - return StatisticList.CUSTOM.b(StatisticList.OPEN_CHEST); - } - - @Nullable - public static T getInventory(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, boolean flag, BlockChest.ChestFinder blockchest_chestfinder) { - TileEntity tileentity = generatoraccess.getTileEntity(blockposition); - - if (!(tileentity instanceof TileEntityChest)) { - return null; - } else if (!flag && a(generatoraccess, blockposition)) { - return null; - } else { - TileEntityChest tileentitychest = (TileEntityChest) tileentity; - BlockPropertyChestType blockpropertychesttype = (BlockPropertyChestType) iblockdata.get(BlockChest.b); - - if (blockpropertychesttype == BlockPropertyChestType.SINGLE) { - return blockchest_chestfinder.b(tileentitychest); - } else { - BlockPosition blockposition1 = blockposition.shift(j(iblockdata)); - // Paper start - don't load chunks if the other side of the chest is in unloaded chunk - IBlockData iblockdata1 = generatoraccess.getTypeIfLoaded(blockposition1); - if (iblockdata1 == null) { - return null; - } - // Paper end - - if (iblockdata1.getBlock() == iblockdata.getBlock()) { - BlockPropertyChestType blockpropertychesttype1 = (BlockPropertyChestType) iblockdata1.get(BlockChest.b); - - if (blockpropertychesttype1 != BlockPropertyChestType.SINGLE && blockpropertychesttype != blockpropertychesttype1 && iblockdata1.get(BlockChest.FACING) == iblockdata.get(BlockChest.FACING)) { - if (!flag && a(generatoraccess, blockposition1)) { - return null; - } - - TileEntity tileentity1 = generatoraccess.getTileEntity(blockposition1); - - if (tileentity1 instanceof TileEntityChest) { - TileEntityChest tileentitychest1 = blockpropertychesttype == BlockPropertyChestType.RIGHT ? tileentitychest : (TileEntityChest) tileentity1; - TileEntityChest tileentitychest2 = blockpropertychesttype == BlockPropertyChestType.RIGHT ? (TileEntityChest) tileentity1 : tileentitychest; - - return blockchest_chestfinder.b(tileentitychest1, tileentitychest2); - } - } - } - - return blockchest_chestfinder.b(tileentitychest); - } - } - } - - @Nullable - public static IInventory getInventory(IBlockData iblockdata, World world, BlockPosition blockposition, boolean flag) { - return (IInventory) getInventory(iblockdata, world, blockposition, flag, BlockChest.i); - } - - @Nullable - @Override - public ITileInventory getInventory(IBlockData iblockdata, World world, BlockPosition blockposition) { - return (ITileInventory) getInventory(iblockdata, world, blockposition, false, BlockChest.j); - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityChest(); - } - - private static boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - return a((IBlockAccess) generatoraccess, blockposition) || b(generatoraccess, blockposition); - } - - private static boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.up(); - - return iblockaccess.getType(blockposition1).isOccluding(iblockaccess, blockposition1); - } - - private static boolean b(GeneratorAccess generatoraccess, BlockPosition blockposition) { - // Paper start - Option to disable chest cat detection - if (((World) generatoraccess).paperConfig.disableChestCatDetection) { - return false; - } - // Paper end - List list = generatoraccess.a(EntityCat.class, new AxisAlignedBB((double) blockposition.getX(), (double) (blockposition.getY() + 1), (double) blockposition.getZ(), (double) (blockposition.getX() + 1), (double) (blockposition.getY() + 2), (double) (blockposition.getZ() + 1))); - - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityCat entitycat = (EntityCat) iterator.next(); - - if (entitycat.isSitting()) { - return true; - } - } - } - - return false; - } - - @Override - public boolean isComplexRedstone(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - return Container.b(getInventory(iblockdata, world, blockposition, false)); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return (IBlockData) iblockdata.set(BlockChest.FACING, enumblockrotation.a((EnumDirection) iblockdata.get(BlockChest.FACING))); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockChest.FACING))); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockChest.FACING, BlockChest.b, BlockChest.c); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } - - interface ChestFinder { - - T b(TileEntityChest tileentitychest, TileEntityChest tileentitychest1); - - T b(TileEntityChest tileentitychest); - } -} diff --git a/src/main/java/net/minecraft/server/BlockChorusFlower.java b/src/main/java/net/minecraft/server/BlockChorusFlower.java deleted file mode 100644 index cde2524ca..000000000 --- a/src/main/java/net/minecraft/server/BlockChorusFlower.java +++ /dev/null @@ -1,252 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Random; -import javax.annotation.Nullable; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockChorusFlower extends Block { - - public static final BlockStateInteger AGE = BlockProperties.ab; - private final BlockChorusFruit b; - - protected BlockChorusFlower(BlockChorusFruit blockchorusfruit, Block.Info block_info) { - super(block_info); - this.b = blockchorusfruit; - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockChorusFlower.AGE, 0)); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!iblockdata.canPlace(world, blockposition)) { - world.b(blockposition, true); - } else { - if (world.paperConfig.fixZeroTickInstantGrowFarms && !randomTick) return; // Paper - fix MC-113809 - BlockPosition blockposition1 = blockposition.up(); - - if (world.isEmpty(blockposition1) && blockposition1.getY() < 256) { - int i = (Integer) iblockdata.get(BlockChorusFlower.AGE); - - if (i < 5) { - boolean flag = false; - boolean flag1 = false; - IBlockData iblockdata1 = world.getType(blockposition.down()); - Block block = iblockdata1.getBlock(); - int j; - - if (block == Blocks.END_STONE) { - flag = true; - } else if (block == this.b) { - j = 1; - - for (int k = 0; k < 4; ++k) { - Block block1 = world.getType(blockposition.down(j + 1)).getBlock(); - - if (block1 != this.b) { - if (block1 == Blocks.END_STONE) { - flag1 = true; - } - break; - } - - ++j; - } - - if (j < 2 || j <= random.nextInt(flag1 ? 5 : 4)) { - flag = true; - } - } else if (iblockdata1.isAir()) { - flag = true; - } - - if (flag && b((IWorldReader) world, blockposition1, (EnumDirection) null) && world.isEmpty(blockposition.up(2))) { - // CraftBukkit start - add event - if (CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition1, this.getBlockData().set(BlockChorusFlower.AGE, Integer.valueOf(i)), 2)) { - world.setTypeAndData(blockposition, this.b.a((IBlockAccess) world, blockposition), 2); - this.b(world, blockposition1, i); - } - // CraftBukkit end - } else if (i < 4) { - j = random.nextInt(4); - if (flag1) { - ++j; - } - - boolean flag2 = false; - - for (int l = 0; l < j; ++l) { - EnumDirection enumdirection = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); - BlockPosition blockposition2 = blockposition.shift(enumdirection); - - if (world.isEmpty(blockposition2) && world.isEmpty(blockposition2.down()) && b((IWorldReader) world, blockposition2, enumdirection.opposite())) { - // CraftBukkit start - add event - if (CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition2, this.getBlockData().set(BlockChorusFlower.AGE, Integer.valueOf(i + 1)), 2)) { - this.b(world, blockposition2, i + 1); - flag2 = true; - } - // CraftBukkit end - } - } - - if (flag2) { - world.setTypeAndData(blockposition, this.b.a((IBlockAccess) world, blockposition), 2); - } else { - // CraftBukkit - add event - if (CraftEventFactory.handleBlockGrowEvent(world, blockposition, this.getBlockData().set(BlockChorusFlower.AGE, Integer.valueOf(5)), 2)) { - this.a(world, blockposition); - } - // CraftBukkit end - } - } else { - // CraftBukkit - add event - if (CraftEventFactory.handleBlockGrowEvent(world, blockposition, this.getBlockData().set(BlockChorusFlower.AGE, Integer.valueOf(5)), 2)) { - this.a(world, blockposition); - } - // CraftBukkit end - } - - } - } - } - } - - private void b(World world, BlockPosition blockposition, int i) { - world.setTypeAndData(blockposition, (IBlockData) this.getBlockData().set(BlockChorusFlower.AGE, i), 2); - world.triggerEffect(1033, blockposition, 0); - } - - private void a(World world, BlockPosition blockposition) { - world.setTypeAndData(blockposition, (IBlockData) this.getBlockData().set(BlockChorusFlower.AGE, 5), 2); - world.triggerEffect(1034, blockposition, 0); - } - - private static boolean b(IWorldReader iworldreader, BlockPosition blockposition, @Nullable EnumDirection enumdirection) { - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - EnumDirection enumdirection1; - - do { - if (!iterator.hasNext()) { - return true; - } - - enumdirection1 = (EnumDirection) iterator.next(); - } while (enumdirection1 == enumdirection || iworldreader.isEmpty(blockposition.shift(enumdirection1))); - - return false; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (enumdirection != EnumDirection.UP && !iblockdata.canPlace(generatoraccess, blockposition)) { - generatoraccess.getBlockTickList().a(blockposition, this, 1); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - IBlockData iblockdata1 = iworldreader.getType(blockposition.down()); - Block block = iblockdata1.getBlock(); - - if (block != this.b && block != Blocks.END_STONE) { - if (!iblockdata1.isAir()) { - return false; - } else { - boolean flag = false; - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - IBlockData iblockdata2 = iworldreader.getType(blockposition.shift(enumdirection)); - - if (iblockdata2.getBlock() == this.b) { - if (flag) { - return false; - } - - flag = true; - } else if (!iblockdata2.isAir()) { - return false; - } - } - - return flag; - } - } else { - return true; - } - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockChorusFlower.AGE); - } - - public static void a(GeneratorAccess generatoraccess, BlockPosition blockposition, Random random, int i) { - generatoraccess.setTypeAndData(blockposition, ((BlockChorusFruit) Blocks.CHORUS_PLANT).a((IBlockAccess) generatoraccess, blockposition), 2); - a(generatoraccess, blockposition, random, blockposition, i, 0); - } - - private static void a(GeneratorAccess generatoraccess, BlockPosition blockposition, Random random, BlockPosition blockposition1, int i, int j) { - BlockChorusFruit blockchorusfruit = (BlockChorusFruit) Blocks.CHORUS_PLANT; - int k = random.nextInt(4) + 1; - - if (j == 0) { - ++k; - } - - for (int l = 0; l < k; ++l) { - BlockPosition blockposition2 = blockposition.up(l + 1); - - if (!b((IWorldReader) generatoraccess, blockposition2, (EnumDirection) null)) { - return; - } - - generatoraccess.setTypeAndData(blockposition2, blockchorusfruit.a((IBlockAccess) generatoraccess, blockposition2), 2); - generatoraccess.setTypeAndData(blockposition2.down(), blockchorusfruit.a((IBlockAccess) generatoraccess, blockposition2.down()), 2); - } - - boolean flag = false; - - if (j < 4) { - int i1 = random.nextInt(4); - - if (j == 0) { - ++i1; - } - - for (int j1 = 0; j1 < i1; ++j1) { - EnumDirection enumdirection = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); - BlockPosition blockposition3 = blockposition.up(k).shift(enumdirection); - - if (Math.abs(blockposition3.getX() - blockposition1.getX()) < i && Math.abs(blockposition3.getZ() - blockposition1.getZ()) < i && generatoraccess.isEmpty(blockposition3) && generatoraccess.isEmpty(blockposition3.down()) && b((IWorldReader) generatoraccess, blockposition3, enumdirection.opposite())) { - flag = true; - generatoraccess.setTypeAndData(blockposition3, blockchorusfruit.a((IBlockAccess) generatoraccess, blockposition3), 2); - generatoraccess.setTypeAndData(blockposition3.shift(enumdirection.opposite()), blockchorusfruit.a((IBlockAccess) generatoraccess, blockposition3.shift(enumdirection.opposite())), 2); - a(generatoraccess, blockposition3, random, blockposition1, i, j + 1); - } - } - } - - if (!flag) { - generatoraccess.setTypeAndData(blockposition.up(k), (IBlockData) Blocks.CHORUS_FLOWER.getBlockData().set(BlockChorusFlower.AGE, 5), 2); - } - - } - - @Override - public void a(World world, IBlockData iblockdata, MovingObjectPositionBlock movingobjectpositionblock, Entity entity) { - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition(); - - a(world, blockposition, new ItemStack(this)); - world.b(blockposition, true); - } -} diff --git a/src/main/java/net/minecraft/server/BlockCocoa.java b/src/main/java/net/minecraft/server/BlockCocoa.java deleted file mode 100644 index ee9f294f4..000000000 --- a/src/main/java/net/minecraft/server/BlockCocoa.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockCocoa extends BlockFacingHorizontal implements IBlockFragilePlantElement { - - public static final BlockStateInteger AGE = BlockProperties.Z; - protected static final VoxelShape[] b = new VoxelShape[]{Block.a(11.0D, 7.0D, 6.0D, 15.0D, 12.0D, 10.0D), Block.a(9.0D, 5.0D, 5.0D, 15.0D, 12.0D, 11.0D), Block.a(7.0D, 3.0D, 4.0D, 15.0D, 12.0D, 12.0D)}; - protected static final VoxelShape[] c = new VoxelShape[]{Block.a(1.0D, 7.0D, 6.0D, 5.0D, 12.0D, 10.0D), Block.a(1.0D, 5.0D, 5.0D, 7.0D, 12.0D, 11.0D), Block.a(1.0D, 3.0D, 4.0D, 9.0D, 12.0D, 12.0D)}; - protected static final VoxelShape[] d = new VoxelShape[]{Block.a(6.0D, 7.0D, 1.0D, 10.0D, 12.0D, 5.0D), Block.a(5.0D, 5.0D, 1.0D, 11.0D, 12.0D, 7.0D), Block.a(4.0D, 3.0D, 1.0D, 12.0D, 12.0D, 9.0D)}; - protected static final VoxelShape[] e = new VoxelShape[]{Block.a(6.0D, 7.0D, 11.0D, 10.0D, 12.0D, 15.0D), Block.a(5.0D, 5.0D, 9.0D, 11.0D, 12.0D, 15.0D), Block.a(4.0D, 3.0D, 7.0D, 12.0D, 12.0D, 15.0D)}; - - public BlockCocoa(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockCocoa.FACING, EnumDirection.NORTH)).set(BlockCocoa.AGE, 0)); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (world.random.nextInt(Math.max(1, (int) (100.0F / world.spigotConfig.cocoaModifier) * 5)) == 0) { // Spigot - int i = (Integer) iblockdata.get(BlockCocoa.AGE); - - if (i < 2) { - CraftEventFactory.handleBlockGrowEvent(world, blockposition, (IBlockData) iblockdata.set(BlockCocoa.AGE, i + 1), 2); // CraftBukkkit - } - } - - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - Block block = iworldreader.getType(blockposition.shift((EnumDirection) iblockdata.get(BlockCocoa.FACING))).getBlock(); - - return block.a(TagsBlock.JUNGLE_LOGS); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - int i = (Integer) iblockdata.get(BlockCocoa.AGE); - - switch ((EnumDirection) iblockdata.get(BlockCocoa.FACING)) { - case SOUTH: - return BlockCocoa.e[i]; - case NORTH: - default: - return BlockCocoa.d[i]; - case WEST: - return BlockCocoa.c[i]; - case EAST: - return BlockCocoa.b[i]; - } - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - IBlockData iblockdata = this.getBlockData(); - World world = blockactioncontext.getWorld(); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - EnumDirection[] aenumdirection = blockactioncontext.e(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - if (enumdirection.k().c()) { - iblockdata = (IBlockData) iblockdata.set(BlockCocoa.FACING, enumdirection); - if (iblockdata.canPlace(world, blockposition)) { - return iblockdata; - } - } - } - - return null; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return enumdirection == iblockdata.get(BlockCocoa.FACING) && !iblockdata.canPlace(generatoraccess, blockposition) ? Blocks.AIR.getBlockData() : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return (Integer) iblockdata.get(BlockCocoa.AGE) < 2; - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return true; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - CraftEventFactory.handleBlockGrowEvent(world, blockposition, (IBlockData) iblockdata.set(BlockCocoa.AGE, (Integer) iblockdata.get(BlockCocoa.AGE) + 1), 2); // CraftBukkit - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockCocoa.FACING, BlockCocoa.AGE); - } -} diff --git a/src/main/java/net/minecraft/server/BlockCommand.java b/src/main/java/net/minecraft/server/BlockCommand.java deleted file mode 100644 index e3b090898..000000000 --- a/src/main/java/net/minecraft/server/BlockCommand.java +++ /dev/null @@ -1,238 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public class BlockCommand extends BlockTileEntity { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final BlockStateDirection a = BlockDirectional.FACING; - public static final BlockStateBoolean b = BlockProperties.c; - - public BlockCommand(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockCommand.a, EnumDirection.NORTH)).set(BlockCommand.b, false)); - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - TileEntityCommand tileentitycommand = new TileEntityCommand(); - - tileentitycommand.b(this == Blocks.CHAIN_COMMAND_BLOCK); - return tileentitycommand; - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (!world.isClientSide) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityCommand) { - TileEntityCommand tileentitycommand = (TileEntityCommand) tileentity; - boolean flag1 = world.isBlockIndirectlyPowered(blockposition); - boolean flag2 = tileentitycommand.f(); - // CraftBukkit start - org.bukkit.block.Block bukkitBlock = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); - int old = flag2 ? 15 : 0; - int current = flag1 ? 15 : 0; - - BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(bukkitBlock, old, current); - world.getServer().getPluginManager().callEvent(eventRedstone); - flag1 = eventRedstone.getNewCurrent() > 0; - // CraftBukkit end - - tileentitycommand.a(flag1); - if (!flag2 && !tileentitycommand.g() && tileentitycommand.u() != TileEntityCommand.Type.SEQUENCE) { - if (flag1) { - tileentitycommand.s(); - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world)); - } - - } - } - } - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.isClientSide) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityCommand) { - TileEntityCommand tileentitycommand = (TileEntityCommand) tileentity; - CommandBlockListenerAbstract commandblocklistenerabstract = tileentitycommand.getCommandBlock(); - boolean flag = !UtilColor.b(commandblocklistenerabstract.getCommand()); - TileEntityCommand.Type tileentitycommand_type = tileentitycommand.u(); - boolean flag1 = tileentitycommand.h(); - - if (tileentitycommand_type == TileEntityCommand.Type.AUTO) { - tileentitycommand.s(); - if (flag1) { - this.a(iblockdata, world, blockposition, commandblocklistenerabstract, flag); - } else if (tileentitycommand.v()) { - commandblocklistenerabstract.a(0); - } - - if (tileentitycommand.f() || tileentitycommand.g()) { - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world)); - } - } else if (tileentitycommand_type == TileEntityCommand.Type.REDSTONE) { - if (flag1) { - this.a(iblockdata, world, blockposition, commandblocklistenerabstract, flag); - } else if (tileentitycommand.v()) { - commandblocklistenerabstract.a(0); - } - } - - world.updateAdjacentComparators(blockposition, this); - } - - } - } - - private void a(IBlockData iblockdata, World world, BlockPosition blockposition, CommandBlockListenerAbstract commandblocklistenerabstract, boolean flag) { - if (flag) { - commandblocklistenerabstract.a(world); - } else { - commandblocklistenerabstract.a(0); - } - - a(world, blockposition, (EnumDirection) iblockdata.get(BlockCommand.a)); - } - - @Override - public int a(IWorldReader iworldreader) { - return 1; - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityCommand && entityhuman.isCreativeAndOp()) { - entityhuman.a((TileEntityCommand) tileentity); - return true; - } else { - return false; - } - } - - @Override - public boolean isComplexRedstone(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - TileEntity tileentity = world.getTileEntity(blockposition); - - return tileentity instanceof TileEntityCommand ? ((TileEntityCommand) tileentity).getCommandBlock().i() : 0; - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityCommand) { - TileEntityCommand tileentitycommand = (TileEntityCommand) tileentity; - CommandBlockListenerAbstract commandblocklistenerabstract = tileentitycommand.getCommandBlock(); - - if (itemstack.hasName()) { - commandblocklistenerabstract.setName(itemstack.getName()); - } - - if (!world.isClientSide) { - if (itemstack.b("BlockEntityTag") == null) { - commandblocklistenerabstract.a(world.getGameRules().getBoolean(GameRules.SEND_COMMAND_FEEDBACK)); - tileentitycommand.b(this == Blocks.CHAIN_COMMAND_BLOCK); - } - - if (tileentitycommand.u() == TileEntityCommand.Type.SEQUENCE) { - boolean flag = world.isBlockIndirectlyPowered(blockposition); - - tileentitycommand.a(flag); - } - } - - } - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.MODEL; - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return (IBlockData) iblockdata.set(BlockCommand.a, enumblockrotation.a((EnumDirection) iblockdata.get(BlockCommand.a))); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockCommand.a))); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockCommand.a, BlockCommand.b); - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return (IBlockData) this.getBlockData().set(BlockCommand.a, blockactioncontext.d().opposite()); - } - - private static void a(World world, BlockPosition blockposition, EnumDirection enumdirection) { - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(blockposition); - GameRules gamerules = world.getGameRules(); - - IBlockData iblockdata; - int i; - - for (i = gamerules.getInt(GameRules.MAX_COMMAND_CHAIN_LENGTH); i-- > 0; enumdirection = (EnumDirection) iblockdata.get(BlockCommand.a)) { - blockposition_mutableblockposition.c(enumdirection); - iblockdata = world.getType(blockposition_mutableblockposition); - Block block = iblockdata.getBlock(); - - if (block != Blocks.CHAIN_COMMAND_BLOCK) { - break; - } - - TileEntity tileentity = world.getTileEntity(blockposition_mutableblockposition); - - if (!(tileentity instanceof TileEntityCommand)) { - break; - } - - TileEntityCommand tileentitycommand = (TileEntityCommand) tileentity; - - if (tileentitycommand.u() != TileEntityCommand.Type.SEQUENCE) { - break; - } - - if (tileentitycommand.f() || tileentitycommand.g()) { - CommandBlockListenerAbstract commandblocklistenerabstract = tileentitycommand.getCommandBlock(); - - if (tileentitycommand.s()) { - if (!commandblocklistenerabstract.a(world)) { - break; - } - - world.updateAdjacentComparators(blockposition_mutableblockposition, block); - } else if (tileentitycommand.v()) { - commandblocklistenerabstract.a(0); - } - } - } - - if (i <= 0) { - int j = Math.max(gamerules.getInt(GameRules.MAX_COMMAND_CHAIN_LENGTH), 0); - - BlockCommand.LOGGER.warn("Command Block chain tried to execute more than {} steps!", j); - } - - } -} diff --git a/src/main/java/net/minecraft/server/BlockComposter.java b/src/main/java/net/minecraft/server/BlockComposter.java deleted file mode 100644 index dedb706bb..000000000 --- a/src/main/java/net/minecraft/server/BlockComposter.java +++ /dev/null @@ -1,340 +0,0 @@ -package net.minecraft.server; - -import it.unimi.dsi.fastutil.objects.Object2FloatMap; -import it.unimi.dsi.fastutil.objects.Object2FloatOpenHashMap; -import java.util.Random; -import javax.annotation.Nullable; -import org.bukkit.craftbukkit.inventory.CraftBlockInventoryHolder; // CraftBukkit - -public class BlockComposter extends Block implements IInventoryHolder { - - public static final BlockStateInteger a = BlockProperties.am; - public static final Object2FloatMap b = new Object2FloatOpenHashMap(); - public static final VoxelShape c = VoxelShapes.b(); - private static final VoxelShape[] d = (VoxelShape[]) SystemUtils.a((new VoxelShape[9]), (avoxelshape) -> { // CraftBukkit - decompile error - for (int i = 0; i < 8; ++i) { - avoxelshape[i] = VoxelShapes.a(BlockComposter.c, Block.a(2.0D, (double) Math.max(2, 1 + i * 2), 2.0D, 14.0D, 16.0D, 14.0D), OperatorBoolean.ONLY_FIRST); - } - - avoxelshape[8] = avoxelshape[7]; - }); - - public static void d() { - BlockComposter.b.defaultReturnValue(-1.0F); - float f = 0.3F; - float f1 = 0.5F; - float f2 = 0.65F; - float f3 = 0.85F; - float f4 = 1.0F; - - a(0.3F, Items.ah); - a(0.3F, Items.ae); - a(0.3F, Items.af); - a(0.3F, Items.aj); - a(0.3F, Items.ai); - a(0.3F, Items.ag); - a(0.3F, Items.t); - a(0.3F, Items.u); - a(0.3F, Items.v); - a(0.3F, Items.w); - a(0.3F, Items.x); - a(0.3F, Items.y); - a(0.3F, Items.BEETROOT_SEEDS); - a(0.3F, Items.DRIED_KELP); - a(0.3F, Items.ay); - a(0.3F, Items.kO); - a(0.3F, Items.MELON_SEEDS); - a(0.3F, Items.PUMPKIN_SEEDS); - a(0.3F, Items.aB); - a(0.3F, Items.SWEET_BERRIES); - a(0.3F, Items.WHEAT_SEEDS); - a(0.5F, Items.kP); - a(0.5F, Items.fp); - a(0.5F, Items.cw); - a(0.5F, Items.kN); - a(0.5F, Items.dh); - a(0.5F, Items.MELON_SLICE); - a(0.65F, Items.aC); - a(0.65F, Items.dr); - a(0.65F, Items.cF); - a(0.65F, Items.cG); - a(0.65F, Items.dg); - a(0.65F, Items.APPLE); - a(0.65F, Items.BEETROOT); - a(0.65F, Items.CARROT); - a(0.65F, Items.COCOA_BEANS); - a(0.65F, Items.POTATO); - a(0.65F, Items.WHEAT); - a(0.65F, Items.bh); - a(0.65F, Items.bi); - a(0.65F, Items.dd); - a(0.65F, Items.aU); - a(0.65F, Items.aV); - a(0.65F, Items.aW); - a(0.65F, Items.aX); - a(0.65F, Items.aY); - a(0.65F, Items.aZ); - a(0.65F, Items.ba); - a(0.65F, Items.bb); - a(0.65F, Items.bc); - a(0.65F, Items.bd); - a(0.65F, Items.be); - a(0.65F, Items.bf); - a(0.65F, Items.bg); - a(0.65F, Items.az); - a(0.65F, Items.fl); - a(0.65F, Items.fm); - a(0.65F, Items.fn); - a(0.65F, Items.fo); - a(0.65F, Items.fq); - a(0.85F, Items.eN); - a(0.85F, Items.db); - a(0.85F, Items.dc); - a(0.85F, Items.BREAD); - a(0.85F, Items.BAKED_POTATO); - a(0.85F, Items.COOKIE); - a(1.0F, Items.lD); - a(1.0F, Items.PUMPKIN_PIE); - } - - private static void a(float f, IMaterial imaterial) { - BlockComposter.b.put(imaterial.getItem(), f); - } - - public BlockComposter(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockComposter.a, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockComposter.d[(Integer) iblockdata.get(BlockComposter.a)]; - } - - @Override - public VoxelShape i(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return BlockComposter.c; - } - - @Override - public VoxelShape b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockComposter.d[0]; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if ((Integer) iblockdata.get(BlockComposter.a) == 7) { - world.getBlockTickList().a(blockposition, iblockdata.getBlock(), 20); - } - - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - int i = (Integer) iblockdata.get(BlockComposter.a); - ItemStack itemstack = entityhuman.b(enumhand); - - if (i < 8 && BlockComposter.b.containsKey(itemstack.getItem())) { - if (i < 7 && !world.isClientSide) { - boolean flag = b(iblockdata, (GeneratorAccess) world, blockposition, itemstack); - - world.triggerEffect(1500, blockposition, flag ? 1 : 0); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - } - - return true; - } else if (i == 8) { - if (!world.isClientSide) { - float f = 0.7F; - double d0 = (double) (world.random.nextFloat() * 0.7F) + 0.15000000596046448D; - double d1 = (double) (world.random.nextFloat() * 0.7F) + 0.06000000238418579D + 0.6D; - double d2 = (double) (world.random.nextFloat() * 0.7F) + 0.15000000596046448D; - EntityItem entityitem = new EntityItem(world, (double) blockposition.getX() + d0, (double) blockposition.getY() + d1, (double) blockposition.getZ() + d2, new ItemStack(Items.BONE_MEAL)); - - entityitem.defaultPickupDelay(); - world.addEntity(entityitem); - } - - d(iblockdata, (GeneratorAccess) world, blockposition); - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_COMPOSTER_EMPTY, SoundCategory.BLOCKS, 1.0F, 1.0F); - return true; - } else { - return false; - } - } - - private static void d(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { - generatoraccess.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockComposter.a, 0), 3); - } - - private static boolean b(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, ItemStack itemstack) { - int i = (Integer) iblockdata.get(BlockComposter.a); - float f = BlockComposter.b.getFloat(itemstack.getItem()); - - if ((i != 0 || f <= 0.0F) && generatoraccess.getRandom().nextDouble() >= (double) f) { - return false; - } else { - int j = i + 1; - - generatoraccess.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockComposter.a, j), 3); - if (j == 7) { - generatoraccess.getBlockTickList().a(blockposition, iblockdata.getBlock(), 20); - } - - return true; - } - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if ((Integer) iblockdata.get(BlockComposter.a) == 7) { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.a((IBlockState) BlockComposter.a), 3); - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_COMPOSTER_READY, SoundCategory.BLOCKS, 1.0F, 1.0F); - } - - super.tick(iblockdata, world, blockposition, random); - } - - @Override - public boolean isComplexRedstone(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - return (Integer) iblockdata.get(BlockComposter.a); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockComposter.a); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } - - @Override - public IWorldInventory a(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { - int i = (Integer) iblockdata.get(BlockComposter.a); - - // CraftBukkit - empty generatoraccess, blockposition - return (IWorldInventory) (i == 8 ? new BlockComposter.ContainerOutput(iblockdata, generatoraccess, blockposition, new ItemStack(Items.BONE_MEAL)) : (i < 7 ? new BlockComposter.ContainerInput(iblockdata, generatoraccess, blockposition) : new BlockComposter.ContainerEmpty(generatoraccess, blockposition))); - } - - static class ContainerInput extends InventorySubcontainer implements IWorldInventory { - - private final IBlockData a; - private final GeneratorAccess b; - private final BlockPosition c; - private boolean d; - - public ContainerInput(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { - super(1); - this.bukkitOwner = new CraftBlockInventoryHolder(generatoraccess, blockposition, this); // CraftBukkit - this.a = iblockdata; - this.b = generatoraccess; - this.c = blockposition; - } - - @Override - public int getMaxStackSize() { - return 1; - } - - @Override - public int[] getSlotsForFace(EnumDirection enumdirection) { - return enumdirection == EnumDirection.UP ? new int[]{0} : new int[0]; - } - - @Override - public boolean canPlaceItemThroughFace(int i, ItemStack itemstack, @Nullable EnumDirection enumdirection) { - return !this.d && enumdirection == EnumDirection.UP && BlockComposter.b.containsKey(itemstack.getItem()); - } - - @Override - public boolean canTakeItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { - return false; - } - - @Override - public void update() { - ItemStack itemstack = this.getItem(0); - - if (!itemstack.isEmpty()) { - this.d = true; - BlockComposter.b(this.a, this.b, this.c, itemstack); - this.splitWithoutUpdate(0); - } - - } - } - - static class ContainerOutput extends InventorySubcontainer implements IWorldInventory { - - private final IBlockData a; - private final GeneratorAccess b; - private final BlockPosition c; - private boolean d; - - public ContainerOutput(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, ItemStack itemstack) { - super(itemstack); - this.a = iblockdata; - this.b = generatoraccess; - this.c = blockposition; - this.bukkitOwner = new CraftBlockInventoryHolder(generatoraccess, blockposition, this); // CraftBukkit - } - - @Override - public int getMaxStackSize() { - return 1; - } - - @Override - public int[] getSlotsForFace(EnumDirection enumdirection) { - return enumdirection == EnumDirection.DOWN ? new int[]{0} : new int[0]; - } - - @Override - public boolean canPlaceItemThroughFace(int i, ItemStack itemstack, @Nullable EnumDirection enumdirection) { - return false; - } - - @Override - public boolean canTakeItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { - return !this.d && enumdirection == EnumDirection.DOWN && itemstack.getItem() == Items.BONE_MEAL; - } - - @Override - public void update() { - BlockComposter.d(this.a, this.b, this.c); - this.d = true; - } - } - - static class ContainerEmpty extends InventorySubcontainer implements IWorldInventory { - - public ContainerEmpty(GeneratorAccess generatoraccess, BlockPosition blockposition) { // CraftBukkit - super(0); - this.bukkitOwner = new CraftBlockInventoryHolder(generatoraccess, blockposition, this); // CraftBukkit - } - - @Override - public int[] getSlotsForFace(EnumDirection enumdirection) { - return new int[0]; - } - - @Override - public boolean canPlaceItemThroughFace(int i, ItemStack itemstack, @Nullable EnumDirection enumdirection) { - return false; - } - - @Override - public boolean canTakeItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { - return false; - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockConcretePowder.java b/src/main/java/net/minecraft/server/BlockConcretePowder.java deleted file mode 100644 index 618a358aa..000000000 --- a/src/main/java/net/minecraft/server/BlockConcretePowder.java +++ /dev/null @@ -1,95 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.block.CraftBlockState; -import org.bukkit.event.block.BlockFormEvent; -// CraftBukkit end - -public class BlockConcretePowder extends BlockFalling { - - private final IBlockData a; - - public BlockConcretePowder(Block block, Block.Info block_info) { - super(block_info); - this.a = block.getBlockData(); - } - - @Override - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1) { - if (canHarden(iblockdata1)) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(world, blockposition, this.a, 3); // CraftBukkit - } - - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - World world = blockactioncontext.getWorld(); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - - // CraftBukkit start - if (!canHarden(world.getType(blockposition)) && !a((IBlockAccess) world, blockposition)) { - return super.getPlacedState(blockactioncontext); - } - - // TODO: An event factory call for methods like this - CraftBlockState blockState = CraftBlockState.getBlockState(world, blockposition); - blockState.setData(this.a); - - BlockFormEvent event = new BlockFormEvent(blockState.getBlock(), blockState); - world.getMinecraftServer().server.getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - return blockState.getHandle(); - } - - return super.getPlacedState(blockactioncontext); - // CraftBukkit end - } - - private static boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { - boolean flag = false; - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(blockposition); - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - IBlockData iblockdata = iblockaccess.getType(blockposition_mutableblockposition); - - if (enumdirection != EnumDirection.DOWN || canHarden(iblockdata)) { - blockposition_mutableblockposition.g(blockposition).c(enumdirection); - iblockdata = iblockaccess.getType(blockposition_mutableblockposition); - if (canHarden(iblockdata) && !iblockdata.d(iblockaccess, blockposition, enumdirection.opposite())) { - flag = true; - break; - } - } - } - - return flag; - } - - private static boolean canHarden(IBlockData iblockdata) { - return iblockdata.p().a(TagsFluid.WATER); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - // CraftBukkit start - if (a((IBlockAccess) generatoraccess, blockposition)) { - CraftBlockState blockState = CraftBlockState.getBlockState(generatoraccess, blockposition); - blockState.setData(this.a); - - BlockFormEvent event = new BlockFormEvent(blockState.getBlock(), blockState); - generatoraccess.getMinecraftWorld().getMinecraftServer().server.getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - return blockState.getHandle(); - } - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - // CraftBukkit end - } -} diff --git a/src/main/java/net/minecraft/server/BlockCoral.java b/src/main/java/net/minecraft/server/BlockCoral.java deleted file mode 100644 index 5f35ec2a0..000000000 --- a/src/main/java/net/minecraft/server/BlockCoral.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public class BlockCoral extends Block { - - private final Block a; - - public BlockCoral(Block block, Block.Info block_info) { - super(block_info); - this.a = block; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!this.a((IBlockAccess) world, blockposition)) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, blockposition, this.a.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, this.a.getBlockData(), 2); - } - - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (!this.a((IBlockAccess) generatoraccess, blockposition)) { - generatoraccess.getBlockTickList().a(blockposition, this, 60 + generatoraccess.getRandom().nextInt(40)); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - protected boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - Fluid fluid = iblockaccess.getFluid(blockposition.shift(enumdirection)); - - if (fluid.a(TagsFluid.WATER)) { - return true; - } - } - - return false; - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - if (!this.a((IBlockAccess) blockactioncontext.getWorld(), blockactioncontext.getClickPosition())) { - blockactioncontext.getWorld().getBlockTickList().a(blockactioncontext.getClickPosition(), this, 60 + blockactioncontext.getWorld().getRandom().nextInt(40)); - } - - return this.getBlockData(); - } -} diff --git a/src/main/java/net/minecraft/server/BlockCoralFan.java b/src/main/java/net/minecraft/server/BlockCoralFan.java deleted file mode 100644 index df80a7bba..000000000 --- a/src/main/java/net/minecraft/server/BlockCoralFan.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class BlockCoralFan extends BlockCoralFanAbstract { - - private final Block a; - - protected BlockCoralFan(Block block, Block.Info block_info) { - super(block_info); - this.a = block; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - this.a(iblockdata, (GeneratorAccess) world, blockposition); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!b_(iblockdata, world, blockposition)) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, blockposition, this.a.getBlockData().set(BlockCoralFan.b, false)).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) this.a.getBlockData().set(BlockCoralFan.b, false), 2); - } - - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (enumdirection == EnumDirection.DOWN && !iblockdata.canPlace(generatoraccess, blockposition)) { - return Blocks.AIR.getBlockData(); - } else { - this.a(iblockdata, generatoraccess, blockposition); - if ((Boolean) iblockdata.get(BlockCoralFan.b)) { - generatoraccess.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) generatoraccess)); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockCoralFanWall.java b/src/main/java/net/minecraft/server/BlockCoralFanWall.java deleted file mode 100644 index 52b88bde9..000000000 --- a/src/main/java/net/minecraft/server/BlockCoralFanWall.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class BlockCoralFanWall extends BlockCoralFanWallAbstract { - - private final Block c; - - protected BlockCoralFanWall(Block block, Block.Info block_info) { - super(block_info); - this.c = block; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - this.a(iblockdata, (GeneratorAccess) world, blockposition); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!b_(iblockdata, world, blockposition)) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, blockposition, this.c.getBlockData().set(BlockCoralFanWall.b, false).set(BlockCoralFanWall.a, iblockdata.get(BlockCoralFanWall.a))).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) ((IBlockData) this.c.getBlockData().set(BlockCoralFanWall.b, false)).set(BlockCoralFanWall.a, iblockdata.get(BlockCoralFanWall.a)), 2); - } - - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (enumdirection.opposite() == iblockdata.get(BlockCoralFanWall.a) && !iblockdata.canPlace(generatoraccess, blockposition)) { - return Blocks.AIR.getBlockData(); - } else { - if ((Boolean) iblockdata.get(BlockCoralFanWall.b)) { - generatoraccess.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) generatoraccess)); - } - - this.a(iblockdata, generatoraccess, blockposition); - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockCoralPlant.java b/src/main/java/net/minecraft/server/BlockCoralPlant.java deleted file mode 100644 index 660950285..000000000 --- a/src/main/java/net/minecraft/server/BlockCoralPlant.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class BlockCoralPlant extends BlockCoralBase { - - private final Block c; - protected static final VoxelShape a = Block.a(2.0D, 0.0D, 2.0D, 14.0D, 15.0D, 14.0D); - - protected BlockCoralPlant(Block block, Block.Info block_info) { - super(block_info); - this.c = block; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - this.a(iblockdata, (GeneratorAccess) world, blockposition); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!b_(iblockdata, world, blockposition)) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, blockposition, this.c.getBlockData().set(BlockCoralPlant.b, false)).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) this.c.getBlockData().set(BlockCoralPlant.b, false), 2); - } - - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (enumdirection == EnumDirection.DOWN && !iblockdata.canPlace(generatoraccess, blockposition)) { - return Blocks.AIR.getBlockData(); - } else { - this.a(iblockdata, generatoraccess, blockposition); - if ((Boolean) iblockdata.get(BlockCoralPlant.b)) { - generatoraccess.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) generatoraccess)); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockCoralPlant.a; - } -} diff --git a/src/main/java/net/minecraft/server/BlockCrops.java b/src/main/java/net/minecraft/server/BlockCrops.java deleted file mode 100644 index e042612f5..000000000 --- a/src/main/java/net/minecraft/server/BlockCrops.java +++ /dev/null @@ -1,169 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockCrops extends BlockPlant implements IBlockFragilePlantElement { - - public static final BlockStateInteger AGE = BlockProperties.ac; - private static final VoxelShape[] a = new VoxelShape[]{Block.a(0.0D, 0.0D, 0.0D, 16.0D, 2.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 4.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 6.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 8.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 10.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 12.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 14.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D)}; - - protected BlockCrops(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(this.d(), 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockCrops.a[(Integer) iblockdata.get(this.d())]; - } - - @Override - protected boolean a_(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.getBlock() == Blocks.FARMLAND; - } - - public BlockStateInteger d() { - return BlockCrops.AGE; - } - - public int e() { - return 7; - } - - protected int j(IBlockData iblockdata) { - return (Integer) iblockdata.get(this.d()); - } - - public IBlockData setAge(int i) { - return (IBlockData) this.getBlockData().set(this.d(), i); - } - - public boolean isRipe(IBlockData iblockdata) { - return (Integer) iblockdata.get(this.d()) >= this.e(); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - super.tick(iblockdata, world, blockposition, random); - if (world.getLightLevel(blockposition, 0) >= 9) { - int i = this.j(iblockdata); - - if (i < this.e()) { - float f = a((Block) this, (IBlockAccess) world, blockposition); - - // Spigot start - int modifier; - if (this == Blocks.BEETROOTS) { - modifier = world.spigotConfig.beetrootModifier; - } else if (this == Blocks.CARROTS) { - modifier = world.spigotConfig.carrotModifier; - } else if (this == Blocks.POTATOES) { - modifier = world.spigotConfig.potatoModifier; - } else { - modifier = world.spigotConfig.wheatModifier; - } - - if (random.nextInt((int) ((100.0F / modifier) * (25.0F / f)) + 1) == 0) { - // Spigot end - CraftEventFactory.handleBlockGrowEvent(world, blockposition, this.setAge(i + 1), 2); // CraftBukkit - } - } - } - - } - - public void a(World world, BlockPosition blockposition, IBlockData iblockdata) { - int i = this.j(iblockdata) + this.a(world); - int j = this.e(); - - if (i > j) { - i = j; - } - - CraftEventFactory.handleBlockGrowEvent(world, blockposition, this.setAge(i), 2); // CraftBukkit - } - - protected int a(World world) { - return MathHelper.nextInt(world.random, 2, 5); - } - - protected static float a(Block block, IBlockAccess iblockaccess, 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 = iblockaccess.getType(blockposition1.b(i, 0, j)); - - if (iblockdata.getBlock() == Blocks.FARMLAND) { - f1 = 1.0F; - if ((Integer) iblockdata.get(BlockSoil.MOISTURE) > 0) { - f1 = 3.0F; - } - } - - if (i != 0 || j != 0) { - f1 /= 4.0F; - } - - f += f1; - } - } - - BlockPosition blockposition2 = blockposition.north(); - BlockPosition blockposition3 = blockposition.south(); - BlockPosition blockposition4 = blockposition.west(); - BlockPosition blockposition5 = blockposition.east(); - boolean flag = block == iblockaccess.getType(blockposition4).getBlock() || block == iblockaccess.getType(blockposition5).getBlock(); - boolean flag1 = block == iblockaccess.getType(blockposition2).getBlock() || block == iblockaccess.getType(blockposition3).getBlock(); - - if (flag && flag1) { - f /= 2.0F; - } else { - boolean flag2 = block == iblockaccess.getType(blockposition4.north()).getBlock() || block == iblockaccess.getType(blockposition5.north()).getBlock() || block == iblockaccess.getType(blockposition5.south()).getBlock() || block == iblockaccess.getType(blockposition4.south()).getBlock(); - - if (flag2) { - f /= 2.0F; - } - } - - return f; - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - return (iworldreader.getLightLevel(blockposition, 0) >= 8 || iworldreader.f(blockposition)) && super.canPlace(iblockdata, iworldreader, blockposition); - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (entity instanceof EntityRavager && !CraftEventFactory.callEntityChangeBlockEvent(entity, blockposition, Blocks.AIR.getBlockData(), !world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)).isCancelled()) { // CraftBukkit - world.b(blockposition, true); - } - - super.a(iblockdata, world, blockposition, entity); - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return !this.isRipe(iblockdata); - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return true; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - this.a(world, blockposition, iblockdata); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockCrops.AGE); - } -} diff --git a/src/main/java/net/minecraft/server/BlockDataAbstract.java b/src/main/java/net/minecraft/server/BlockDataAbstract.java deleted file mode 100644 index b3fe95d85..000000000 --- a/src/main/java/net/minecraft/server/BlockDataAbstract.java +++ /dev/null @@ -1,162 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ArrayTable; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.collect.Table; -import com.google.common.collect.UnmodifiableIterator; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Function; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -public abstract class BlockDataAbstract implements IBlockDataHolder { - - public static final Function, Comparable>, String> STATE_TO_VALUE = new Function, Comparable>, String>() { - public String apply(@Nullable Entry, Comparable> entry) { - if (entry == null) { - return ""; - } else { - IBlockState iblockstate = (IBlockState) entry.getKey(); - - return iblockstate.a() + "=" + this.a(iblockstate, (Comparable) entry.getValue()); - } - } - - private > String a(IBlockState iblockstate, Comparable comparable) { - return iblockstate.a((T) comparable); // Paper - decompiler fix - } - }; - protected final O a; - private final ImmutableMap, Comparable> d; - private final int e; - private Table, Comparable, S> f; - - protected BlockDataAbstract(O o0, ImmutableMap, Comparable> immutablemap) { - this.a = o0; - this.d = immutablemap; - this.e = immutablemap.hashCode(); - } - - public > S a(IBlockState iblockstate) { - return this.set(iblockstate, a(iblockstate.getValues(), this.get(iblockstate))); // Paper - decompile fix - } - - protected static T a(Collection collection, T t0) { - Iterator iterator = collection.iterator(); // Paper - decompiler fix - - 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(this.a); - if (!this.getStateMap().isEmpty()) { - stringbuilder.append('['); - stringbuilder.append((String) this.getStateMap().entrySet().stream().map(BlockDataAbstract.STATE_TO_VALUE).collect(Collectors.joining(","))); - stringbuilder.append(']'); - } - - return stringbuilder.toString(); - } - - public Collection> a() { - return Collections.unmodifiableCollection(this.d.keySet()); - } - - public final > boolean hasProperty(IBlockState iblockstate) { return this.b(iblockstate); } // Paper - OBFHELPER - public > boolean b(IBlockState iblockstate) { - return this.d.containsKey(iblockstate); - } - - @Override - public > T get(IBlockState iblockstate) { - Comparable comparable = (Comparable) this.d.get(iblockstate); - - if (comparable == null) { - throw new IllegalArgumentException("Cannot get property " + iblockstate + " as it does not exist in " + this.a); - } else { - return iblockstate.b().cast(comparable); // Paper - decompiler fix - } - } - - @Override - public , V extends T> S set(IBlockState iblockstate, V v0) { - Comparable comparable = (Comparable) this.d.get(iblockstate); - - if (comparable == null) { - throw new IllegalArgumentException("Cannot set property " + iblockstate + " as it does not exist in " + this.a); - } else if (comparable == v0) { - return (S) this; // Paper - decompiler fix - } else { - S s0 = this.f.get(iblockstate, v0); - - if (s0 == null) { - throw new IllegalArgumentException("Cannot set property " + iblockstate + " to " + v0 + " on " + this.a + ", it is not an allowed value"); - } else { - return s0; - } - } - } - - public void a(Map, Comparable>, S> map) { - if (this.f != null) { - throw new IllegalStateException(); - } else { - Table, Comparable, S> table = HashBasedTable.create(); - UnmodifiableIterator unmodifiableiterator = this.d.entrySet().iterator(); - - while (unmodifiableiterator.hasNext()) { - Entry, Comparable> entry = (Entry) unmodifiableiterator.next(); - IBlockState iblockstate = (IBlockState) entry.getKey(); - Iterator iterator = iblockstate.getValues().iterator(); - - while (iterator.hasNext()) { - Comparable comparable = (Comparable) iterator.next(); - - if (comparable != entry.getValue()) { - table.put(iblockstate, comparable, map.get(this.c(iblockstate, comparable))); - } - } - } - - this.f = (Table) (table.isEmpty() ? table : ArrayTable.create(table)); - } - } - - private Map, Comparable> c(IBlockState iblockstate, Comparable comparable) { - Map, Comparable> map = Maps.newHashMap(this.d); - - map.put(iblockstate, comparable); - return map; - } - - @Override - public ImmutableMap, Comparable> getStateMap() { - return this.d; - } - - public boolean equals(Object object) { - return this == object; - } - - public int hashCode() { - return this.e; - } -} diff --git a/src/main/java/net/minecraft/server/BlockDaylightDetector.java b/src/main/java/net/minecraft/server/BlockDaylightDetector.java deleted file mode 100644 index 783ae1d2b..000000000 --- a/src/main/java/net/minecraft/server/BlockDaylightDetector.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.minecraft.server; - -public class BlockDaylightDetector extends BlockTileEntity { - - public static final BlockStateInteger POWER = BlockProperties.as; - public static final BlockStateBoolean b = BlockProperties.p; - protected static final VoxelShape c = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 6.0D, 16.0D); - - public BlockDaylightDetector(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockDaylightDetector.POWER, 0)).set(BlockDaylightDetector.b, false)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockDaylightDetector.c; - } - - @Override - public boolean n(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Integer) iblockdata.get(BlockDaylightDetector.POWER); - } - - public static void d(IBlockData iblockdata, World world, BlockPosition blockposition) { - if (world.worldProvider.g()) { - int i = world.getBrightness(EnumSkyBlock.SKY, blockposition) - world.c(); - float f = world.b(1.0F); - boolean flag = (Boolean) iblockdata.get(BlockDaylightDetector.b); - - if (flag) { - i = 15 - i; - } else if (i > 0) { - 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 ((Integer) iblockdata.get(BlockDaylightDetector.POWER) != i) { - i = org.bukkit.craftbukkit.event.CraftEventFactory.callRedstoneChange(world, blockposition, ((Integer) iblockdata.get(POWER)), i).getNewCurrent(); // CraftBukkit - Call BlockRedstoneEvent - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockDaylightDetector.POWER, i), 3); - } - - } - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (entityhuman.dQ()) { - if (world.isClientSide) { - return true; - } else { - IBlockData iblockdata1 = (IBlockData) iblockdata.a((IBlockState) BlockDaylightDetector.b); - - world.setTypeAndData(blockposition, iblockdata1, 4); - d(iblockdata1, world, blockposition); - return true; - } - } else { - return super.interact(iblockdata, world, blockposition, entityhuman, enumhand, movingobjectpositionblock); - } - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.MODEL; - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityLightDetector(); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockDaylightDetector.POWER, BlockDaylightDetector.b); - } -} diff --git a/src/main/java/net/minecraft/server/BlockDiodeAbstract.java b/src/main/java/net/minecraft/server/BlockDiodeAbstract.java deleted file mode 100644 index d7e0684ca..000000000 --- a/src/main/java/net/minecraft/server/BlockDiodeAbstract.java +++ /dev/null @@ -1,211 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public abstract class BlockDiodeAbstract extends BlockFacingHorizontal { - - protected static final VoxelShape b = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 2.0D, 16.0D); - public static final BlockStateBoolean c = BlockProperties.w; - - protected BlockDiodeAbstract(Block.Info block_info) { - super(block_info); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockDiodeAbstract.b; - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - return c((IBlockAccess) iworldreader, blockposition.down()); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!this.a((IWorldReader) world, blockposition, iblockdata)) { - boolean flag = (Boolean) iblockdata.get(BlockDiodeAbstract.c); - boolean flag1 = this.a(world, blockposition, iblockdata); - - if (flag && !flag1) { - // CraftBukkit start - if (CraftEventFactory.callRedstoneChange(world, blockposition, 15, 0).getNewCurrent() != 0) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockDiodeAbstract.c, false), 2); - } else if (!flag) { - // CraftBukkit start - if (CraftEventFactory.callRedstoneChange(world, blockposition, 0, 15).getNewCurrent() != 15) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockDiodeAbstract.c, true), 2); - if (!flag1) { - world.getBlockTickList().a(blockposition, this, this.j(iblockdata), TickListPriority.HIGH); - } - } - - } - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return iblockdata.b(iblockaccess, blockposition, enumdirection); - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return !(Boolean) iblockdata.get(BlockDiodeAbstract.c) ? 0 : (iblockdata.get(BlockDiodeAbstract.FACING) == enumdirection ? this.b(iblockaccess, blockposition, iblockdata) : 0); - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (iblockdata.canPlace(world, blockposition)) { - this.c(world, blockposition, iblockdata); - } else { - TileEntity tileentity = this.isTileEntity() ? world.getTileEntity(blockposition) : null; - - a(iblockdata, world, blockposition, tileentity); - world.a(blockposition, false); - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - world.applyPhysics(blockposition.shift(enumdirection), this); - } - - } - } - - protected void c(World world, BlockPosition blockposition, IBlockData iblockdata) { - if (!this.a((IWorldReader) world, blockposition, iblockdata)) { - boolean flag = (Boolean) iblockdata.get(BlockDiodeAbstract.c); - boolean flag1 = this.a(world, blockposition, iblockdata); - - if (flag != flag1 && !world.getBlockTickList().b(blockposition, this)) { - TickListPriority ticklistpriority = TickListPriority.HIGH; - - if (this.c((IBlockAccess) world, blockposition, iblockdata)) { - ticklistpriority = TickListPriority.EXTREMELY_HIGH; - } else if (flag) { - ticklistpriority = TickListPriority.VERY_HIGH; - } - - world.getBlockTickList().a(blockposition, this, this.j(iblockdata), ticklistpriority); - } - - } - } - - public boolean a(IWorldReader iworldreader, BlockPosition blockposition, IBlockData iblockdata) { - return false; - } - - protected boolean a(World world, BlockPosition blockposition, IBlockData iblockdata) { - return this.b(world, blockposition, iblockdata) > 0; - } - - protected int b(World world, BlockPosition blockposition, IBlockData iblockdata) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockDiodeAbstract.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 ? (Integer) iblockdata1.get(BlockRedstoneWire.POWER) : 0); - } - } - - protected int b(IWorldReader iworldreader, BlockPosition blockposition, IBlockData iblockdata) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockDiodeAbstract.FACING); - EnumDirection enumdirection1 = enumdirection.e(); - EnumDirection enumdirection2 = enumdirection.f(); - - return Math.max(this.b(iworldreader, blockposition.shift(enumdirection1), enumdirection1), this.b(iworldreader, blockposition.shift(enumdirection2), enumdirection2)); - } - - protected int b(IWorldReader iworldreader, BlockPosition blockposition, EnumDirection enumdirection) { - IBlockData iblockdata = iworldreader.getType(blockposition); - Block block = iblockdata.getBlock(); - - return this.q(iblockdata) ? (block == Blocks.REDSTONE_BLOCK ? 15 : (block == Blocks.REDSTONE_WIRE ? (Integer) iblockdata.get(BlockRedstoneWire.POWER) : iworldreader.c(blockposition, enumdirection))) : 0; - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return (IBlockData) this.getBlockData().set(BlockDiodeAbstract.FACING, blockactioncontext.f().opposite()); - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { - if (this.a(world, blockposition, iblockdata)) { - world.getBlockTickList().a(blockposition, this, 1); - } - - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - this.d(world, blockposition, iblockdata); - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (!flag && iblockdata.getBlock() != iblockdata1.getBlock()) { - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - this.d(world, blockposition, iblockdata); - } - } - - protected void d(World world, BlockPosition blockposition, IBlockData iblockdata) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockDiodeAbstract.FACING); - BlockPosition blockposition1 = blockposition.shift(enumdirection.opposite()); - - world.a(blockposition1, (Block) this, blockposition); - world.a(blockposition1, (Block) this, enumdirection); - } - - protected boolean q(IBlockData iblockdata) { - return iblockdata.isPowerSource(); - } - - protected int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { - return 15; - } - - public static boolean isDiode(IBlockData iblockdata) { - return iblockdata.getBlock() instanceof BlockDiodeAbstract; - } - - public boolean c(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { - EnumDirection enumdirection = ((EnumDirection) iblockdata.get(BlockDiodeAbstract.FACING)).opposite(); - IBlockData iblockdata1 = iblockaccess.getType(blockposition.shift(enumdirection)); - - return isDiode(iblockdata1) && iblockdata1.get(BlockDiodeAbstract.FACING) != enumdirection; - } - - protected abstract int j(IBlockData iblockdata); - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - public boolean f(IBlockData iblockdata) { - return true; - } -} diff --git a/src/main/java/net/minecraft/server/BlockDirtSnowSpreadable.java b/src/main/java/net/minecraft/server/BlockDirtSnowSpreadable.java deleted file mode 100644 index cb90b74ca..000000000 --- a/src/main/java/net/minecraft/server/BlockDirtSnowSpreadable.java +++ /dev/null @@ -1,57 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public abstract class BlockDirtSnowSpreadable extends BlockDirtSnow { - - protected BlockDirtSnowSpreadable(Block.Info block_info) { - super(block_info); - } - - private static boolean b(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.up(); - IBlockData iblockdata1 = iworldreader.getType(blockposition1); - - if (iblockdata1.getBlock() == Blocks.SNOW && (Integer) iblockdata1.get(BlockSnow.LAYERS) == 1) { - return true; - } else { - int i = LightEngineLayer.a(iworldreader, iblockdata, blockposition, iblockdata1, blockposition1, EnumDirection.UP, iblockdata1.b((IBlockAccess) iworldreader, blockposition1)); - - return i < iworldreader.H(); - } - } - - private static boolean c(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.up(); - - return b(iblockdata, iworldreader, blockposition) && !iworldreader.getFluid(blockposition1).a(TagsFluid.WATER); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (this instanceof BlockGrass && world.paperConfig.grassUpdateRate != 1 && (world.paperConfig.grassUpdateRate < 1 || (MinecraftServer.currentTick + blockposition.hashCode()) % world.paperConfig.grassUpdateRate != 0)) { return; } // Paper - if (!world.isClientSide) { - if (!b(iblockdata, (IWorldReader) world, blockposition)) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, blockposition, Blocks.DIRT.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeUpdate(blockposition, Blocks.DIRT.getBlockData()); - } else { - if (world.getLightLevel(blockposition.up()) >= 9) { - IBlockData iblockdata1 = this.getBlockData(); - - for (int i = 0; i < 4; ++i) { - BlockPosition blockposition1 = blockposition.b(random.nextInt(3) - 1, random.nextInt(5) - 3, random.nextInt(3) - 1); - - if (world.getType(blockposition1).getBlock() == Blocks.DIRT && c(iblockdata1, (IWorldReader) world, blockposition1)) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition1, (IBlockData) iblockdata1.set(BlockDirtSnowSpreadable.a, world.getType(blockposition1.up()).getBlock() == Blocks.SNOW)); // CraftBukkit - } - } - } - - } - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockDispenser.java b/src/main/java/net/minecraft/server/BlockDispenser.java deleted file mode 100644 index 88a210b1d..000000000 --- a/src/main/java/net/minecraft/server/BlockDispenser.java +++ /dev/null @@ -1,169 +0,0 @@ -package net.minecraft.server; - -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import java.util.Map; -import java.util.Random; - -public class BlockDispenser extends BlockTileEntity { - - public static final BlockStateDirection FACING = BlockDirectional.FACING; - public static final BlockStateBoolean TRIGGERED = BlockProperties.A; - public static final Map REGISTRY = (Map) SystemUtils.a((new Object2ObjectOpenHashMap()), (object2objectopenhashmap) -> { // CraftBukkit - decompile error - object2objectopenhashmap.defaultReturnValue(new DispenseBehaviorItem()); - }); - public static boolean eventFired = false; // CraftBukkit - - public static void a(IMaterial imaterial, IDispenseBehavior idispensebehavior) { - BlockDispenser.REGISTRY.put(imaterial.getItem(), idispensebehavior); - } - - protected BlockDispenser(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockDispenser.FACING, EnumDirection.NORTH)).set(BlockDispenser.TRIGGERED, false)); - } - - @Override - public int a(IWorldReader iworldreader) { - return 4; - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (world.isClientSide) { - return true; - } else { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityDispenser) { - entityhuman.openContainer((TileEntityDispenser) tileentity); - if (tileentity instanceof TileEntityDropper) { - entityhuman.a(StatisticList.INSPECT_DROPPER); - } else { - entityhuman.a(StatisticList.INSPECT_DISPENSER); - } - } - - return true; - } - } - - public void dispense(World world, BlockPosition blockposition) { - SourceBlock sourceblock = new SourceBlock(world, blockposition); - TileEntityDispenser tileentitydispenser = (TileEntityDispenser) sourceblock.getTileEntity(); - int i = tileentitydispenser.h(); - - if (i < 0) { - world.triggerEffect(1001, blockposition, 0); - } else { - ItemStack itemstack = tileentitydispenser.getItem(i); - IDispenseBehavior idispensebehavior = this.a(itemstack); - - if (idispensebehavior != IDispenseBehavior.NONE) { - eventFired = false; // CraftBukkit - reset event status - tileentitydispenser.setItem(i, idispensebehavior.dispense(sourceblock, itemstack)); - } - - } - } - - protected IDispenseBehavior a(ItemStack itemstack) { - return (IDispenseBehavior) BlockDispenser.REGISTRY.get(itemstack.getItem()); - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - boolean flag1 = world.isBlockIndirectlyPowered(blockposition) || world.isBlockIndirectlyPowered(blockposition.up()); - boolean flag2 = (Boolean) iblockdata.get(BlockDispenser.TRIGGERED); - - if (flag1 && !flag2) { - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world)); - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockDispenser.TRIGGERED, true), 4); - } else if (!flag1 && flag2) { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockDispenser.TRIGGERED, false), 4); - } - - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.isClientSide) { - this.dispense(world, blockposition); - } - - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityDispenser(); - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return (IBlockData) this.getBlockData().set(BlockDispenser.FACING, blockactioncontext.d().opposite()); - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { - if (itemstack.hasName()) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityDispenser) { - ((TileEntityDispenser) tileentity).setCustomName(itemstack.getName()); - } - } - - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata.getBlock() != iblockdata1.getBlock()) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityDispenser) { - InventoryUtils.dropInventory(world, blockposition, (TileEntityDispenser) tileentity); - world.updateAdjacentComparators(blockposition, this); - } - - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - } - } - - public static IPosition a(ISourceBlock isourceblock) { - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - double d0 = isourceblock.getX() + 0.7D * (double) enumdirection.getAdjacentX(); - double d1 = isourceblock.getY() + 0.7D * (double) enumdirection.getAdjacentY(); - double d2 = isourceblock.getZ() + 0.7D * (double) enumdirection.getAdjacentZ(); - - return new Position(d0, d1, d2); - } - - @Override - public boolean isComplexRedstone(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - return Container.a(world.getTileEntity(blockposition)); - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.MODEL; - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return (IBlockData) iblockdata.set(BlockDispenser.FACING, enumblockrotation.a((EnumDirection) iblockdata.get(BlockDispenser.FACING))); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockDispenser.FACING))); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockDispenser.FACING, BlockDispenser.TRIGGERED); - } -} diff --git a/src/main/java/net/minecraft/server/BlockDoor.java b/src/main/java/net/minecraft/server/BlockDoor.java deleted file mode 100644 index a1a25771b..000000000 --- a/src/main/java/net/minecraft/server/BlockDoor.java +++ /dev/null @@ -1,239 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public class BlockDoor extends Block { - - public static final BlockStateDirection FACING = BlockFacingHorizontal.FACING; - public static final BlockStateBoolean OPEN = BlockProperties.u; - public static final BlockStateEnum HINGE = BlockProperties.az; - public static final BlockStateBoolean POWERED = BlockProperties.w; - public static final BlockStateEnum HALF = BlockProperties.U; - protected static final VoxelShape f = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 3.0D); - protected static final VoxelShape g = Block.a(0.0D, 0.0D, 13.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape h = Block.a(13.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape i = Block.a(0.0D, 0.0D, 0.0D, 3.0D, 16.0D, 16.0D); - - protected BlockDoor(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockDoor.FACING, EnumDirection.NORTH)).set(BlockDoor.OPEN, false)).set(BlockDoor.HINGE, BlockPropertyDoorHinge.LEFT)).set(BlockDoor.POWERED, false)).set(BlockDoor.HALF, BlockPropertyDoubleBlockHalf.LOWER)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockDoor.FACING); - boolean flag = !(Boolean) iblockdata.get(BlockDoor.OPEN); - boolean flag1 = iblockdata.get(BlockDoor.HINGE) == BlockPropertyDoorHinge.RIGHT; - - switch (enumdirection) { - case EAST: - default: - return flag ? BlockDoor.i : (flag1 ? BlockDoor.g : BlockDoor.f); - case SOUTH: - return flag ? BlockDoor.f : (flag1 ? BlockDoor.i : BlockDoor.h); - case WEST: - return flag ? BlockDoor.h : (flag1 ? BlockDoor.f : BlockDoor.g); - case NORTH: - return flag ? BlockDoor.g : (flag1 ? BlockDoor.h : BlockDoor.i); - } - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - BlockPropertyDoubleBlockHalf blockpropertydoubleblockhalf = (BlockPropertyDoubleBlockHalf) iblockdata.get(BlockDoor.HALF); - - return enumdirection.k() == EnumDirection.EnumAxis.Y && blockpropertydoubleblockhalf == BlockPropertyDoubleBlockHalf.LOWER == (enumdirection == EnumDirection.UP) ? (iblockdata1.getBlock() == this && iblockdata1.get(BlockDoor.HALF) != blockpropertydoubleblockhalf ? (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockDoor.FACING, iblockdata1.get(BlockDoor.FACING))).set(BlockDoor.OPEN, iblockdata1.get(BlockDoor.OPEN))).set(BlockDoor.HINGE, iblockdata1.get(BlockDoor.HINGE))).set(BlockDoor.POWERED, iblockdata1.get(BlockDoor.POWERED)) : Blocks.AIR.getBlockData()) : (blockpropertydoubleblockhalf == BlockPropertyDoubleBlockHalf.LOWER && enumdirection == EnumDirection.DOWN && !iblockdata.canPlace(generatoraccess, blockposition) ? Blocks.AIR.getBlockData() : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1)); - } - - @Override - public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, ItemStack itemstack) { - super.a(world, entityhuman, blockposition, Blocks.AIR.getBlockData(), tileentity, itemstack); - } - - @Override - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { - BlockPropertyDoubleBlockHalf blockpropertydoubleblockhalf = (BlockPropertyDoubleBlockHalf) iblockdata.get(BlockDoor.HALF); - BlockPosition blockposition1 = blockpropertydoubleblockhalf == BlockPropertyDoubleBlockHalf.LOWER ? blockposition.up() : blockposition.down(); - IBlockData iblockdata1 = world.getType(blockposition1); - - if (iblockdata1.getBlock() == this && iblockdata1.get(BlockDoor.HALF) != blockpropertydoubleblockhalf) { - world.setTypeAndData(blockposition1, Blocks.AIR.getBlockData(), 35); - world.a(entityhuman, 2001, blockposition1, Block.getCombinedId(iblockdata1)); - ItemStack itemstack = entityhuman.getItemInMainHand(); - - if (!world.isClientSide && !entityhuman.isCreative()) { - Block.dropItems(iblockdata, world, blockposition, (TileEntity) null, entityhuman, itemstack); - Block.dropItems(iblockdata1, world, blockposition1, (TileEntity) null, entityhuman, itemstack); - } - } - - super.a(world, blockposition, iblockdata, entityhuman); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - switch (pathmode) { - case LAND: - return (Boolean) iblockdata.get(BlockDoor.OPEN); - case WATER: - return false; - case AIR: - return (Boolean) iblockdata.get(BlockDoor.OPEN); - default: - return false; - } - } - - private int d() { - return this.material == Material.ORE ? 1011 : 1012; - } - - private int e() { - return this.material == Material.ORE ? 1005 : 1006; - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - BlockPosition blockposition = blockactioncontext.getClickPosition(); - - if (blockposition.getY() < 255 && blockactioncontext.getWorld().getType(blockposition.up()).a(blockactioncontext)) { - World world = blockactioncontext.getWorld(); - boolean flag = world.isBlockIndirectlyPowered(blockposition) || world.isBlockIndirectlyPowered(blockposition.up()); - - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.getBlockData().set(BlockDoor.FACING, blockactioncontext.f())).set(BlockDoor.HINGE, this.b(blockactioncontext))).set(BlockDoor.POWERED, flag)).set(BlockDoor.OPEN, flag)).set(BlockDoor.HALF, BlockPropertyDoubleBlockHalf.LOWER); - } else { - return null; - } - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { - world.setTypeAndData(blockposition.up(), (IBlockData) iblockdata.set(BlockDoor.HALF, BlockPropertyDoubleBlockHalf.UPPER), 3); - } - - private BlockPropertyDoorHinge b(BlockActionContext blockactioncontext) { - World world = blockactioncontext.getWorld(); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - EnumDirection enumdirection = blockactioncontext.f(); - BlockPosition blockposition1 = blockposition.up(); - EnumDirection enumdirection1 = enumdirection.f(); - BlockPosition blockposition2 = blockposition.shift(enumdirection1); - IBlockData iblockdata = world.getType(blockposition2); - BlockPosition blockposition3 = blockposition1.shift(enumdirection1); - IBlockData iblockdata1 = world.getType(blockposition3); - EnumDirection enumdirection2 = enumdirection.e(); - BlockPosition blockposition4 = blockposition.shift(enumdirection2); - IBlockData iblockdata2 = world.getType(blockposition4); - BlockPosition blockposition5 = blockposition1.shift(enumdirection2); - IBlockData iblockdata3 = world.getType(blockposition5); - int i = (iblockdata.o(world, blockposition2) ? -1 : 0) + (iblockdata1.o(world, blockposition3) ? -1 : 0) + (iblockdata2.o(world, blockposition4) ? 1 : 0) + (iblockdata3.o(world, blockposition5) ? 1 : 0); - boolean flag = iblockdata.getBlock() == this && iblockdata.get(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER; - boolean flag1 = iblockdata2.getBlock() == this && iblockdata2.get(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER; - - if ((!flag || flag1) && i <= 0) { - if ((!flag1 || flag) && i >= 0) { - int j = enumdirection.getAdjacentX(); - int k = enumdirection.getAdjacentZ(); - Vec3D vec3d = blockactioncontext.j(); - double d0 = vec3d.x - (double) blockposition.getX(); - double d1 = vec3d.z - (double) blockposition.getZ(); - - return (j >= 0 || d1 >= 0.5D) && (j <= 0 || d1 <= 0.5D) && (k >= 0 || d0 <= 0.5D) && (k <= 0 || d0 >= 0.5D) ? BlockPropertyDoorHinge.LEFT : BlockPropertyDoorHinge.RIGHT; - } else { - return BlockPropertyDoorHinge.LEFT; - } - } else { - return BlockPropertyDoorHinge.RIGHT; - } - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (this.material == Material.ORE) { - return false; - } else { - iblockdata = (IBlockData) iblockdata.a((IBlockState) BlockDoor.OPEN); - world.setTypeAndData(blockposition, iblockdata, 10); - world.a(entityhuman, (Boolean) iblockdata.get(BlockDoor.OPEN) ? this.e() : this.d(), blockposition, 0); - return true; - } - } - - public void setDoor(World world, BlockPosition blockposition, boolean flag) { - IBlockData iblockdata = world.getType(blockposition); - - if (iblockdata.getBlock() == this && (Boolean) iblockdata.get(BlockDoor.OPEN) != flag) { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockDoor.OPEN, flag), 10); - this.b(world, blockposition, flag); - } - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - // CraftBukkit start - BlockPosition otherHalf = blockposition.shift(iblockdata.get(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER ? EnumDirection.UP : EnumDirection.DOWN); - - 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(otherHalf.getX(), otherHalf.getY(), otherHalf.getZ()); - - int power = bukkitBlock.getBlockPower(); - int powerTop = blockTop.getBlockPower(); - if (powerTop > power) power = powerTop; - int oldPower = (Boolean) iblockdata.get(BlockDoor.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; - // CraftBukkit end - if (flag1 != (Boolean) iblockdata.get(BlockDoor.OPEN)) { - this.b(world, blockposition, flag1); - } - - world.setTypeAndData(blockposition, (IBlockData) ((IBlockData) iblockdata.set(BlockDoor.POWERED, flag1)).set(BlockDoor.OPEN, flag1), 2); - } - - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata1 = iworldreader.getType(blockposition1); - - return iblockdata.get(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER ? iblockdata1.d(iworldreader, blockposition1, EnumDirection.UP) : iblockdata1.getBlock() == this; - } - - private void b(World world, BlockPosition blockposition, boolean flag) { - world.a((EntityHuman) null, flag ? this.e() : this.d(), blockposition, 0); - } - - @Override - public EnumPistonReaction getPushReaction(IBlockData iblockdata) { - return EnumPistonReaction.DESTROY; - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return (IBlockData) iblockdata.set(BlockDoor.FACING, enumblockrotation.a((EnumDirection) iblockdata.get(BlockDoor.FACING))); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return enumblockmirror == EnumBlockMirror.NONE ? iblockdata : (IBlockData) iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockDoor.FACING))).a((IBlockState) BlockDoor.HINGE); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockDoor.HALF, BlockDoor.FACING, BlockDoor.OPEN, BlockDoor.HINGE, BlockDoor.POWERED); - } -} diff --git a/src/main/java/net/minecraft/server/BlockDragonEgg.java b/src/main/java/net/minecraft/server/BlockDragonEgg.java deleted file mode 100644 index 270bf7f6b..000000000 --- a/src/main/java/net/minecraft/server/BlockDragonEgg.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.event.block.BlockFromToEvent; // CraftBukkit - -public class BlockDragonEgg extends BlockFalling { - - protected static final VoxelShape a = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 16.0D, 15.0D); - - public BlockDragonEgg(Block.Info block_info) { - super(block_info); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockDragonEgg.a; - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - this.d(iblockdata, world, blockposition); - return true; - } - - @Override - public void attack(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman) { - this.d(iblockdata, world, blockposition); - } - - private void d(IBlockData iblockdata, World world, BlockPosition blockposition) { - for (int i = 0; i < 1000; ++i) { - BlockPosition blockposition1 = blockposition.b(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).isAir()) { - // 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 - if (world.isClientSide) { - for (int j = 0; j < 128; ++j) { - double d0 = world.random.nextDouble(); - float f = (world.random.nextFloat() - 0.5F) * 0.2F; - float f1 = (world.random.nextFloat() - 0.5F) * 0.2F; - float f2 = (world.random.nextFloat() - 0.5F) * 0.2F; - double d1 = MathHelper.d(d0, (double) blockposition1.getX(), (double) blockposition.getX()) + (world.random.nextDouble() - 0.5D) + 0.5D; - double d2 = MathHelper.d(d0, (double) blockposition1.getY(), (double) blockposition.getY()) + world.random.nextDouble() - 0.5D; - double d3 = MathHelper.d(d0, (double) blockposition1.getZ(), (double) blockposition.getZ()) + (world.random.nextDouble() - 0.5D) + 0.5D; - - world.addParticle(Particles.PORTAL, d1, d2, d3, (double) f, (double) f1, (double) f2); - } - } else { - world.setTypeAndData(blockposition1, iblockdata, 2); - world.a(blockposition, false); - } - - return; - } - } - - } - - @Override - public int a(IWorldReader iworldreader) { - return 5; - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockDropper.java b/src/main/java/net/minecraft/server/BlockDropper.java deleted file mode 100644 index e2f1dc02e..000000000 --- a/src/main/java/net/minecraft/server/BlockDropper.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.event.inventory.InventoryMoveItemEvent; -// CraftBukkit end - -public class BlockDropper extends BlockDispenser { - - private static final IDispenseBehavior c = new DispenseBehaviorItem(); - - public BlockDropper(Block.Info block_info) { - super(block_info); - } - - @Override - protected IDispenseBehavior a(ItemStack itemstack) { - return BlockDropper.c; - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityDropper(); - } - - @Override - public void dispense(World world, BlockPosition blockposition) { - SourceBlock sourceblock = new SourceBlock(world, blockposition); - TileEntityDispenser tileentitydispenser = (TileEntityDispenser) sourceblock.getTileEntity(); - int i = tileentitydispenser.h(); - - if (i < 0) { - world.triggerEffect(1001, blockposition, 0); - } else { - ItemStack itemstack = tileentitydispenser.getItem(i); - - if (!itemstack.isEmpty()) { - EnumDirection enumdirection = (EnumDirection) world.getType(blockposition).get(BlockDropper.FACING); - IInventory iinventory = TileEntityHopper.a(world, blockposition.shift(enumdirection)); - ItemStack itemstack1; - - if (iinventory == null) { - itemstack1 = BlockDropper.c.dispense(sourceblock, itemstack); - } else { - // CraftBukkit start - Fire event when pushing items into other inventories - CraftItemStack oitemstack = CraftItemStack.asCraftMirror(itemstack.cloneItemStack().cloneAndSubtract(1)); - - org.bukkit.inventory.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(); - } - - InventoryMoveItemEvent event = new InventoryMoveItemEvent(tileentitydispenser.getOwner().getInventory(), oitemstack.clone(), destinationInventory, true); - world.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - itemstack1 = TileEntityHopper.addItem(tileentitydispenser, iinventory, CraftItemStack.asNMSCopy(event.getItem()), enumdirection.opposite()); - if (event.getItem().equals(oitemstack) && itemstack1.isEmpty()) { - // CraftBukkit end - itemstack1 = itemstack.cloneItemStack(); - itemstack1.subtract(1); - } else { - itemstack1 = itemstack.cloneItemStack(); - } - } - - tileentitydispenser.setItem(i, itemstack1); - } - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockEnderPortal.java b/src/main/java/net/minecraft/server/BlockEnderPortal.java deleted file mode 100644 index 161996cbd..000000000 --- a/src/main/java/net/minecraft/server/BlockEnderPortal.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.event.entity.EntityPortalEnterEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -// CraftBukkit end - -public class BlockEnderPortal extends BlockTileEntity { - - protected static final VoxelShape a = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 12.0D, 16.0D); - - protected BlockEnderPortal(Block.Info block_info) { - super(block_info); - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityEnderPortal(); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockEnderPortal.a; - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (!world.isClientSide && !entity.isPassenger() && !entity.isVehicle() && entity.canPortal() && VoxelShapes.c(VoxelShapes.a(entity.getBoundingBox().d((double) (-blockposition.getX()), (double) (-blockposition.getY()), (double) (-blockposition.getZ()))), iblockdata.getShape(world, blockposition), OperatorBoolean.AND)) { - // 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); - - if (entity instanceof EntityPlayer) { - ((EntityPlayer) entity).a(world.worldProvider.getDimensionManager().getType() == DimensionManager.THE_END ? DimensionManager.OVERWORLD : DimensionManager.THE_END, PlayerTeleportEvent.TeleportCause.END_PORTAL); - return; - } - entity.a(world.worldProvider.getDimensionManager().getType() == DimensionManager.THE_END ? DimensionManager.OVERWORLD : DimensionManager.THE_END); - // CraftBukkit end - } - - } -} diff --git a/src/main/java/net/minecraft/server/BlockFire.java b/src/main/java/net/minecraft/server/BlockFire.java deleted file mode 100644 index 135c6ae47..000000000 --- a/src/main/java/net/minecraft/server/BlockFire.java +++ /dev/null @@ -1,469 +0,0 @@ -package net.minecraft.server; - -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import com.destroystokyo.paper.event.block.TNTPrimeEvent; // Paper - TNTPrimeEvent -import java.util.Map; -import java.util.Random; -import java.util.Map.Entry; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.block.CraftBlockState; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.block.BlockBurnEvent; -import org.bukkit.event.block.BlockFadeEvent; -import org.bukkit.event.block.BlockSpreadEvent; -// CraftBukkit end - -public class BlockFire extends Block { - - public static final BlockStateInteger AGE = BlockProperties.ad; - public static final BlockStateBoolean NORTH = BlockSprawling.a; - public static final BlockStateBoolean EAST = BlockSprawling.b; - public static final BlockStateBoolean SOUTH = BlockSprawling.c; - public static final BlockStateBoolean WEST = BlockSprawling.d; - public static final BlockStateBoolean UPPER = BlockSprawling.e; - private static final Map g = (Map) BlockSprawling.g.entrySet().stream().filter((entry) -> { - return entry.getKey() != EnumDirection.DOWN; - }).collect(SystemUtils.a()); - private final Object2IntMap flameChances = new Object2IntOpenHashMap(); - private final Object2IntMap i = new Object2IntOpenHashMap(); - - protected BlockFire(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockFire.AGE, 0)).set(BlockFire.NORTH, false)).set(BlockFire.EAST, false)).set(BlockFire.SOUTH, false)).set(BlockFire.WEST, false)).set(BlockFire.UPPER, false)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return VoxelShapes.a(); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - // CraftBukkit start - if (!iblockdata.canPlace(generatoraccess, blockposition)) { - CraftBlockState blockState = CraftBlockState.getBlockState(generatoraccess, blockposition); - blockState.setData(Blocks.AIR.getBlockData()); - - BlockFadeEvent event = new BlockFadeEvent(blockState.getBlock(), blockState); - generatoraccess.getMinecraftWorld().getMinecraftServer().server.getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - return blockState.getHandle(); - } - } - return this.a((IBlockAccess) generatoraccess, blockposition).set(BlockFire.AGE, iblockdata.get(BlockFire.AGE)); - // CraftBukkit end - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return this.a((IBlockAccess) blockactioncontext.getWorld(), blockactioncontext.getClickPosition()); - } - - public IBlockData a(IBlockAccess iblockaccess, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata = iblockaccess.getType(blockposition1); - - if (!this.j(iblockdata) && !iblockdata.d(iblockaccess, blockposition1, EnumDirection.UP)) { - IBlockData iblockdata1 = this.getBlockData(); - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - BlockStateBoolean blockstateboolean = (BlockStateBoolean) BlockFire.g.get(enumdirection); - - if (blockstateboolean != null) { - iblockdata1 = (IBlockData) iblockdata1.set(blockstateboolean, this.j(iblockaccess.getType(blockposition.shift(enumdirection)))); - } - } - - return iblockdata1; - } else { - return this.getBlockData(); - } - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - - return iworldreader.getType(blockposition1).d(iworldreader, blockposition1, EnumDirection.UP) || this.canBurn(iworldreader, blockposition); - } - - @Override - public int a(IWorldReader iworldreader) { - return 30; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (world.getGameRules().getBoolean(GameRules.DO_FIRE_TICK)) { - if (!iblockdata.canPlace(world, blockposition)) { - fireExtinguished(world, blockposition); // CraftBukkit - invalid place location - } - - Block block = world.getType(blockposition.down()).getBlock(); - boolean flag = world.worldProvider instanceof WorldProviderTheEnd && block == Blocks.BEDROCK || block == Blocks.NETHERRACK || block == Blocks.MAGMA_BLOCK; - int i = (Integer) iblockdata.get(BlockFire.AGE); - - if (!flag && world.isRaining() && this.a(world, blockposition) && random.nextFloat() < 0.2F + (float) i * 0.03F) { - fireExtinguished(world, blockposition); // CraftBukkit - extinguished by rain - } else { - int j = Math.min(15, i + random.nextInt(3) / 2); - - if (i != j) { - iblockdata = (IBlockData) iblockdata.set(BlockFire.AGE, j); - world.setTypeAndData(blockposition, iblockdata, 4); - } - - if (!flag) { - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world) + random.nextInt(10)); - if (!this.canBurn(world, blockposition)) { - BlockPosition blockposition1 = blockposition.down(); - - if (!world.getType(blockposition1).d(world, blockposition1, EnumDirection.UP) || i > 3) { - fireExtinguished(world, blockposition); // CraftBukkit - } - - return; - } - - if (i == 15 && random.nextInt(4) == 0 && !this.j(world.getType(blockposition.down()))) { - fireExtinguished(world, blockposition); // CraftBukkit - return; - } - } - - boolean flag1 = world.s(blockposition); - int k = flag1 ? -50 : 0; - - // CraftBukkit start - add source blockposition to burn calls - this.a(world, blockposition.east(), 300 + k, random, i, blockposition); - this.a(world, blockposition.west(), 300 + k, random, i, blockposition); - this.a(world, blockposition.down(), 250 + k, random, i, blockposition); - this.a(world, blockposition.up(), 250 + k, random, i, blockposition); - this.a(world, blockposition.north(), 300 + k, random, i, blockposition); - this.a(world, blockposition.south(), 300 + k, random, i, blockposition); - // CraftBukkit end - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - for (int l = -1; l <= 1; ++l) { - for (int i1 = -1; i1 <= 1; ++i1) { - for (int j1 = -1; j1 <= 4; ++j1) { - if (l != 0 || j1 != 0 || i1 != 0) { - int k1 = 100; - - if (j1 > 1) { - k1 += (j1 - 1) * 100; - } - - blockposition_mutableblockposition.g(blockposition).e(l, j1, i1); - if (!world.isLoaded(blockposition_mutableblockposition)) continue; // Paper - int l1 = this.a((IWorldReader) world, (BlockPosition) blockposition_mutableblockposition); - - if (l1 > 0) { - int i2 = (l1 + 40 + world.getDifficulty().a() * 7) / (i + 30); - - if (flag1) { - i2 /= 2; - } - - if (i2 > 0 && random.nextInt(k1) <= i2 && (!world.isRaining() || !this.a(world, (BlockPosition) blockposition_mutableblockposition))) { - int j2 = Math.min(15, i + random.nextInt(5) / 4); - - // CraftBukkit start - Call to stop spread of fire - if (world.getType(blockposition_mutableblockposition).getBlock() != Blocks.FIRE) { - if (CraftEventFactory.callBlockIgniteEvent(world, blockposition_mutableblockposition, blockposition).isCancelled()) { - continue; - } - - CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition_mutableblockposition, (IBlockData) this.a((IBlockAccess) world, (BlockPosition) blockposition_mutableblockposition).set(BlockFire.AGE, j2), 3); // CraftBukkit - } - // CraftBukkit end - } - } - } - } - } - } - - } - } - } - - protected boolean a(World world, BlockPosition blockposition) { - return world.isRainingAt(blockposition) || world.isRainingAt(blockposition.west()) || world.isRainingAt(blockposition.east()) || world.isRainingAt(blockposition.north()) || world.isRainingAt(blockposition.south()); - } - - private int q(IBlockData iblockdata) { - return iblockdata.b((IBlockState) BlockProperties.C) && (Boolean) iblockdata.get(BlockProperties.C) ? 0 : this.i.getInt(iblockdata.getBlock()); - } - - private int r(IBlockData iblockdata) { - return iblockdata.b((IBlockState) BlockProperties.C) && (Boolean) iblockdata.get(BlockProperties.C) ? 0 : this.flameChances.getInt(iblockdata.getBlock()); - } - - private void a(World world, BlockPosition blockposition, int i, Random random, int j, BlockPosition sourceposition) { // CraftBukkit add sourceposition - // Paper start - final IBlockData iblockdata = world.getTypeIfLoaded(blockposition); - if (iblockdata == null) { - return; - } - int k = this.q(iblockdata); - // Paper end - - if (random.nextInt(i) < k) { - //IBlockData iblockdata = world.getType(blockposition); // Paper - - // CraftBukkit start - org.bukkit.block.Block theBlock = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); - org.bukkit.block.Block sourceBlock = world.getWorld().getBlockAt(sourceposition.getX(), sourceposition.getY(), sourceposition.getZ()); - - BlockBurnEvent event = new BlockBurnEvent(theBlock, sourceBlock); - world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - // CraftBukkit end - - if (random.nextInt(j + 10) < 5 && !world.isRainingAt(blockposition)) { - int l = Math.min(j + random.nextInt(5) / 4, 15); - - world.setTypeAndData(blockposition, (IBlockData) this.a((IBlockAccess) world, blockposition).set(BlockFire.AGE, l), 3); - } else { - if(iblockdata.getBlock() != Blocks.TNT) world.a(blockposition, false); // Paper - TNTPrimeEvent - We might be cancelling it below, move the setAir down - } - - Block block = iblockdata.getBlock(); - - if (block instanceof BlockTNT) { - BlockTNT blocktnt = (BlockTNT) block; - - // Paper start - TNTPrimeEvent - org.bukkit.block.Block tntBlock = MCUtil.toBukkitBlock(world, blockposition); - if (!new TNTPrimeEvent(tntBlock, TNTPrimeEvent.PrimeReason.FIRE, null).callEvent()) { - return; - } - // Paper end - BlockTNT.a(world, blockposition); - } - } - - } - - private boolean canBurn(IBlockAccess iblockaccess, BlockPosition blockposition) { - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - if (this.j(iblockaccess.getType(blockposition.shift(enumdirection)))) { - return true; - } - } - - return false; - } - - private int a(IWorldReader iworldreader, BlockPosition blockposition) { - if (!iworldreader.isEmpty(blockposition)) { - return 0; - } else { - int i = 0; - EnumDirection[] aenumdirection = EnumDirection.values(); - int j = aenumdirection.length; - - for (int k = 0; k < j; ++k) { - EnumDirection enumdirection = aenumdirection[k]; - // Paper start - IBlockData iblockdata = iworldreader.getTypeIfLoaded(blockposition.shift(enumdirection)); - if (iblockdata == null) { - continue; - } - // Paper end - i = Math.max(this.r(iblockdata), i); - } - - return i; - } - } - - public boolean j(IBlockData iblockdata) { - return this.r(iblockdata) > 0; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata1.getBlock() != iblockdata.getBlock()) { - // CraftBukkit - getType() - if (world.worldProvider.getDimensionManager().getType() != DimensionManager.OVERWORLD && world.worldProvider.getDimensionManager().getType() != DimensionManager.NETHER || !((BlockPortal) Blocks.NETHER_PORTAL).a((GeneratorAccess) world, blockposition)) { - if (!iblockdata.canPlace(world, blockposition)) { - fireExtinguished(world, blockposition); // CraftBukkit - fuel block broke - } else { - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world) + world.random.nextInt(10)); - } - } - } - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockFire.AGE, BlockFire.NORTH, BlockFire.EAST, BlockFire.SOUTH, BlockFire.WEST, BlockFire.UPPER); - } - - public void a(Block block, int i, int j) { - this.flameChances.put(block, i); - this.i.put(block, j); - } - - public static void d() { - BlockFire blockfire = (BlockFire) Blocks.FIRE; - - blockfire.a(Blocks.OAK_PLANKS, 5, 20); - blockfire.a(Blocks.SPRUCE_PLANKS, 5, 20); - blockfire.a(Blocks.BIRCH_PLANKS, 5, 20); - blockfire.a(Blocks.JUNGLE_PLANKS, 5, 20); - blockfire.a(Blocks.ACACIA_PLANKS, 5, 20); - blockfire.a(Blocks.DARK_OAK_PLANKS, 5, 20); - blockfire.a(Blocks.OAK_SLAB, 5, 20); - blockfire.a(Blocks.SPRUCE_SLAB, 5, 20); - blockfire.a(Blocks.BIRCH_SLAB, 5, 20); - blockfire.a(Blocks.JUNGLE_SLAB, 5, 20); - blockfire.a(Blocks.ACACIA_SLAB, 5, 20); - blockfire.a(Blocks.DARK_OAK_SLAB, 5, 20); - blockfire.a(Blocks.OAK_FENCE_GATE, 5, 20); - blockfire.a(Blocks.SPRUCE_FENCE_GATE, 5, 20); - blockfire.a(Blocks.BIRCH_FENCE_GATE, 5, 20); - blockfire.a(Blocks.JUNGLE_FENCE_GATE, 5, 20); - blockfire.a(Blocks.DARK_OAK_FENCE_GATE, 5, 20); - blockfire.a(Blocks.ACACIA_FENCE_GATE, 5, 20); - blockfire.a(Blocks.OAK_FENCE, 5, 20); - blockfire.a(Blocks.SPRUCE_FENCE, 5, 20); - blockfire.a(Blocks.BIRCH_FENCE, 5, 20); - blockfire.a(Blocks.JUNGLE_FENCE, 5, 20); - blockfire.a(Blocks.DARK_OAK_FENCE, 5, 20); - blockfire.a(Blocks.ACACIA_FENCE, 5, 20); - blockfire.a(Blocks.OAK_STAIRS, 5, 20); - blockfire.a(Blocks.BIRCH_STAIRS, 5, 20); - blockfire.a(Blocks.SPRUCE_STAIRS, 5, 20); - blockfire.a(Blocks.JUNGLE_STAIRS, 5, 20); - blockfire.a(Blocks.ACACIA_STAIRS, 5, 20); - blockfire.a(Blocks.DARK_OAK_STAIRS, 5, 20); - blockfire.a(Blocks.OAK_LOG, 5, 5); - blockfire.a(Blocks.SPRUCE_LOG, 5, 5); - blockfire.a(Blocks.BIRCH_LOG, 5, 5); - blockfire.a(Blocks.JUNGLE_LOG, 5, 5); - blockfire.a(Blocks.ACACIA_LOG, 5, 5); - blockfire.a(Blocks.DARK_OAK_LOG, 5, 5); - blockfire.a(Blocks.STRIPPED_OAK_LOG, 5, 5); - blockfire.a(Blocks.STRIPPED_SPRUCE_LOG, 5, 5); - blockfire.a(Blocks.STRIPPED_BIRCH_LOG, 5, 5); - blockfire.a(Blocks.STRIPPED_JUNGLE_LOG, 5, 5); - blockfire.a(Blocks.STRIPPED_ACACIA_LOG, 5, 5); - blockfire.a(Blocks.STRIPPED_DARK_OAK_LOG, 5, 5); - blockfire.a(Blocks.STRIPPED_OAK_WOOD, 5, 5); - blockfire.a(Blocks.STRIPPED_SPRUCE_WOOD, 5, 5); - blockfire.a(Blocks.STRIPPED_BIRCH_WOOD, 5, 5); - blockfire.a(Blocks.STRIPPED_JUNGLE_WOOD, 5, 5); - blockfire.a(Blocks.STRIPPED_ACACIA_WOOD, 5, 5); - blockfire.a(Blocks.STRIPPED_DARK_OAK_WOOD, 5, 5); - blockfire.a(Blocks.OAK_WOOD, 5, 5); - blockfire.a(Blocks.SPRUCE_WOOD, 5, 5); - blockfire.a(Blocks.BIRCH_WOOD, 5, 5); - blockfire.a(Blocks.JUNGLE_WOOD, 5, 5); - blockfire.a(Blocks.ACACIA_WOOD, 5, 5); - blockfire.a(Blocks.DARK_OAK_WOOD, 5, 5); - blockfire.a(Blocks.OAK_LEAVES, 30, 60); - blockfire.a(Blocks.SPRUCE_LEAVES, 30, 60); - blockfire.a(Blocks.BIRCH_LEAVES, 30, 60); - blockfire.a(Blocks.JUNGLE_LEAVES, 30, 60); - blockfire.a(Blocks.ACACIA_LEAVES, 30, 60); - blockfire.a(Blocks.DARK_OAK_LEAVES, 30, 60); - blockfire.a(Blocks.BOOKSHELF, 30, 20); - blockfire.a(Blocks.TNT, 15, 100); - blockfire.a(Blocks.GRASS, 60, 100); - blockfire.a(Blocks.FERN, 60, 100); - blockfire.a(Blocks.DEAD_BUSH, 60, 100); - blockfire.a(Blocks.SUNFLOWER, 60, 100); - blockfire.a(Blocks.LILAC, 60, 100); - blockfire.a(Blocks.ROSE_BUSH, 60, 100); - blockfire.a(Blocks.PEONY, 60, 100); - blockfire.a(Blocks.TALL_GRASS, 60, 100); - blockfire.a(Blocks.LARGE_FERN, 60, 100); - blockfire.a(Blocks.DANDELION, 60, 100); - blockfire.a(Blocks.POPPY, 60, 100); - blockfire.a(Blocks.BLUE_ORCHID, 60, 100); - blockfire.a(Blocks.ALLIUM, 60, 100); - blockfire.a(Blocks.AZURE_BLUET, 60, 100); - blockfire.a(Blocks.RED_TULIP, 60, 100); - blockfire.a(Blocks.ORANGE_TULIP, 60, 100); - blockfire.a(Blocks.WHITE_TULIP, 60, 100); - blockfire.a(Blocks.PINK_TULIP, 60, 100); - blockfire.a(Blocks.OXEYE_DAISY, 60, 100); - blockfire.a(Blocks.CORNFLOWER, 60, 100); - blockfire.a(Blocks.LILY_OF_THE_VALLEY, 60, 100); - blockfire.a(Blocks.WITHER_ROSE, 60, 100); - blockfire.a(Blocks.WHITE_WOOL, 30, 60); - blockfire.a(Blocks.ORANGE_WOOL, 30, 60); - blockfire.a(Blocks.MAGENTA_WOOL, 30, 60); - blockfire.a(Blocks.LIGHT_BLUE_WOOL, 30, 60); - blockfire.a(Blocks.YELLOW_WOOL, 30, 60); - blockfire.a(Blocks.LIME_WOOL, 30, 60); - blockfire.a(Blocks.PINK_WOOL, 30, 60); - blockfire.a(Blocks.GRAY_WOOL, 30, 60); - blockfire.a(Blocks.LIGHT_GRAY_WOOL, 30, 60); - blockfire.a(Blocks.CYAN_WOOL, 30, 60); - blockfire.a(Blocks.PURPLE_WOOL, 30, 60); - blockfire.a(Blocks.BLUE_WOOL, 30, 60); - blockfire.a(Blocks.BROWN_WOOL, 30, 60); - blockfire.a(Blocks.GREEN_WOOL, 30, 60); - blockfire.a(Blocks.RED_WOOL, 30, 60); - blockfire.a(Blocks.BLACK_WOOL, 30, 60); - blockfire.a(Blocks.VINE, 15, 100); - blockfire.a(Blocks.COAL_BLOCK, 5, 5); - blockfire.a(Blocks.HAY_BLOCK, 60, 20); - blockfire.a(Blocks.WHITE_CARPET, 60, 20); - blockfire.a(Blocks.ORANGE_CARPET, 60, 20); - blockfire.a(Blocks.MAGENTA_CARPET, 60, 20); - blockfire.a(Blocks.LIGHT_BLUE_CARPET, 60, 20); - blockfire.a(Blocks.YELLOW_CARPET, 60, 20); - blockfire.a(Blocks.LIME_CARPET, 60, 20); - blockfire.a(Blocks.PINK_CARPET, 60, 20); - blockfire.a(Blocks.GRAY_CARPET, 60, 20); - blockfire.a(Blocks.LIGHT_GRAY_CARPET, 60, 20); - blockfire.a(Blocks.CYAN_CARPET, 60, 20); - blockfire.a(Blocks.PURPLE_CARPET, 60, 20); - blockfire.a(Blocks.BLUE_CARPET, 60, 20); - blockfire.a(Blocks.BROWN_CARPET, 60, 20); - blockfire.a(Blocks.GREEN_CARPET, 60, 20); - blockfire.a(Blocks.RED_CARPET, 60, 20); - blockfire.a(Blocks.BLACK_CARPET, 60, 20); - blockfire.a(Blocks.DRIED_KELP_BLOCK, 30, 60); - blockfire.a(Blocks.BAMBOO, 60, 60); - blockfire.a(Blocks.SCAFFOLDING, 60, 60); - blockfire.a(Blocks.LECTERN, 30, 20); - blockfire.a(Blocks.COMPOSTER, 5, 20); - blockfire.a(Blocks.SWEET_BERRY_BUSH, 60, 100); - } - - // CraftBukkit start - private void fireExtinguished(GeneratorAccess world, BlockPosition position) { - if (!CraftEventFactory.callBlockFadeEvent(world, position, Blocks.AIR.getBlockData()).isCancelled()) { - world.a(position, false); - } - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/BlockFluids.java b/src/main/java/net/minecraft/server/BlockFluids.java deleted file mode 100644 index 56bf0b1d8..000000000 --- a/src/main/java/net/minecraft/server/BlockFluids.java +++ /dev/null @@ -1,178 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -public class BlockFluids extends Block implements IFluidSource { - - public static final BlockStateInteger LEVEL = BlockProperties.ao; - protected final FluidTypeFlowing b; - private final List c; - - protected BlockFluids(FluidTypeFlowing fluidtypeflowing, Block.Info block_info) { - super(block_info); - this.b = fluidtypeflowing; - this.c = Lists.newArrayList(); - this.c.add(fluidtypeflowing.a(false)); - - for (int i = 1; i < 8; ++i) { - this.c.add(fluidtypeflowing.a(8 - i, false)); - } - - this.c.add(fluidtypeflowing.a(8, true)); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockFluids.LEVEL, 0)); - } - - @Override - public void c(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - world.getFluid(blockposition).b(world, blockposition, random); - } - - @Override - public boolean b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return false; - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return !this.b.a(TagsFluid.LAVA); - } - - @Override - public Fluid g(IBlockData iblockdata) { - int i = (Integer) iblockdata.get(BlockFluids.LEVEL); - - return (Fluid) this.c.get(Math.min(i, 8)); - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.INVISIBLE; - } - - @Override - public List a(IBlockData iblockdata, LootTableInfo.Builder loottableinfo_builder) { - return Collections.emptyList(); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return VoxelShapes.a(); - } - - @Override - public int a(IWorldReader iworldreader) { - return this.b.a(iworldreader); - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (this.a(world, blockposition, iblockdata)) { - world.getFluidTickList().a(blockposition, iblockdata.p().getType(), this.getFlowSpeed(world, blockposition)); // Paper - } - - } - - // Paper start - Get flow speed. Throttle if its water and flowing adjacent to lava - public int getFlowSpeed(World world, BlockPosition blockposition) { - if (this.material == Material.WATER) { - if ( - world.getMaterialIfLoaded(blockposition.north(1)) == Material.LAVA || - world.getMaterialIfLoaded(blockposition.south(1)) == Material.LAVA || - world.getMaterialIfLoaded(blockposition.west(1)) == Material.LAVA || - world.getMaterialIfLoaded(blockposition.east(1)) == Material.LAVA - ) { - return world.paperConfig.waterOverLavaFlowSpeed; - } - } - return this.a(world); - } - // Paper end - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (iblockdata.p().isSource() || iblockdata1.p().isSource()) { - generatoraccess.getFluidTickList().a(blockposition, iblockdata.p().getType(), this.a((IWorldReader) generatoraccess)); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (this.a(world, blockposition, iblockdata)) { - world.getFluidTickList().a(blockposition, iblockdata.p().getType(), this.getFlowSpeed(world, blockposition)); // Paper - } - - } - - public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata) { - if (this.b.a(TagsFluid.LAVA)) { - boolean flag = false; - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - if (enumdirection != EnumDirection.DOWN && world.getFluid(blockposition.shift(enumdirection)).a(TagsFluid.WATER)) { - flag = true; - break; - } - } - - if (flag) { - Fluid fluid = world.getFluid(blockposition); - - if (fluid.isSource()) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(world, blockposition, Blocks.OBSIDIAN.getBlockData())) { - this.fizz(world, blockposition); - } - // CraftBukkit end - return false; - } - - if (fluid.getHeight(world, blockposition) >= 0.44444445F) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(world, blockposition, Blocks.COBBLESTONE.getBlockData())) { - this.fizz(world, blockposition); - } - // CraftBukkit end - return false; - } - } - } - - return true; - } - - private void fizz(GeneratorAccess generatoraccess, BlockPosition blockposition) { - generatoraccess.triggerEffect(1501, blockposition, 0); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockFluids.LEVEL); - } - - @Override - public FluidType removeFluid(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata) { - if ((Integer) iblockdata.get(BlockFluids.LEVEL) == 0) { - generatoraccess.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 11); - return this.b; - } else { - return FluidTypes.EMPTY; - } - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (this.b.a(TagsFluid.LAVA)) { - entity.aC(); - } - - } -} diff --git a/src/main/java/net/minecraft/server/BlockGrass.java b/src/main/java/net/minecraft/server/BlockGrass.java deleted file mode 100644 index 7168b3ead..000000000 --- a/src/main/java/net/minecraft/server/BlockGrass.java +++ /dev/null @@ -1,86 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import java.util.Random; - -public class BlockGrass extends BlockDirtSnowSpreadable implements IBlockFragilePlantElement { - - public BlockGrass(Block.Info block_info) { - super(block_info); - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return iblockaccess.getType(blockposition.up()).isAir(); - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return true; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - BlockPosition blockposition1 = blockposition.up(); - IBlockData iblockdata1 = Blocks.GRASS.getBlockData(); - int i = 0; - - while (i < 128) { - BlockPosition blockposition2 = blockposition1; - int j = 0; - - while (true) { - if (j < i / 16) { - blockposition2 = blockposition2.b(random.nextInt(3) - 1, (random.nextInt(3) - 1) * random.nextInt(3) / 2, random.nextInt(3) - 1); - if (world.getType(blockposition2.down()).getBlock() == this && !world.getType(blockposition2).o(world, blockposition2)) { - ++j; - continue; - } - } else { - IBlockData iblockdata2 = world.getType(blockposition2); - - if (iblockdata2.getBlock() == iblockdata1.getBlock() && random.nextInt(10) == 0) { - ((IBlockFragilePlantElement) iblockdata1.getBlock()).b(world, random, blockposition2, iblockdata2); - } - - if (iblockdata2.isAir()) { - label38: - { - IBlockData iblockdata3; - - if (random.nextInt(8) == 0) { - List> list = world.getBiome(blockposition2).e(); - - if (list.isEmpty()) { - break label38; - } - - iblockdata3 = ((WorldGenFlowers) ((WorldGenFeatureCompositeConfiguration) ((WorldGenFeatureConfigured) list.get(0)).b).a.a).a(random, blockposition2); - } else { - iblockdata3 = iblockdata1; - } - - if (iblockdata3.canPlace(world, blockposition2)) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockGrowEvent(world, blockposition2, iblockdata3, 3); // CraftBukkit - } - } - } - } - - ++i; - break; - } - } - - } - - @Override - public boolean f(IBlockData iblockdata) { - return true; - } - - @Override - public TextureType c() { - return TextureType.CUTOUT_MIPPED; - } -} diff --git a/src/main/java/net/minecraft/server/BlockIce.java b/src/main/java/net/minecraft/server/BlockIce.java deleted file mode 100644 index b2043a669..000000000 --- a/src/main/java/net/minecraft/server/BlockIce.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public class BlockIce extends BlockHalfTransparent { - - public BlockIce(Block.Info block_info) { - super(block_info); - } - - @Override - public TextureType c() { - return TextureType.TRANSLUCENT; - } - - @Override - public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, ItemStack itemstack) { - super.a(world, entityhuman, blockposition, iblockdata, tileentity, itemstack); - if (EnchantmentManager.getEnchantmentLevel(Enchantments.SILK_TOUCH, itemstack) == 0) { - if (world.worldProvider.isNether()) { - world.a(blockposition, false); - return; - } - - Material material = world.getType(blockposition.down()).getMaterial(); - - if (material.isSolid() || material.isLiquid()) { - world.setTypeUpdate(blockposition, Blocks.WATER.getBlockData()); - } - } - - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (world.getBrightness(EnumSkyBlock.BLOCK, blockposition) > 11 - iblockdata.b((IBlockAccess) world, blockposition)) { - this.melt(iblockdata, world, blockposition); - } - - } - - protected void melt(IBlockData iblockdata, World world, BlockPosition blockposition) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, blockposition, world.worldProvider.isNether() ? Blocks.AIR.getBlockData() : Blocks.WATER.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - if (world.worldProvider.isNether()) { - world.a(blockposition, false); - } else { - world.setTypeUpdate(blockposition, Blocks.WATER.getBlockData()); - world.a(blockposition, Blocks.WATER, blockposition); - } - } - - @Override - public EnumPistonReaction getPushReaction(IBlockData iblockdata) { - return EnumPistonReaction.NORMAL; - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EntityTypes entitytypes) { - return entitytypes == EntityTypes.POLAR_BEAR; - } -} diff --git a/src/main/java/net/minecraft/server/BlockIceFrost.java b/src/main/java/net/minecraft/server/BlockIceFrost.java deleted file mode 100644 index 881dfb123..000000000 --- a/src/main/java/net/minecraft/server/BlockIceFrost.java +++ /dev/null @@ -1,127 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class BlockIceFrost extends BlockIce { - - public static final BlockStateInteger a = BlockProperties.aa; - - public BlockIceFrost(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockIceFrost.a, 0)); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.paperConfig.frostedIceEnabled) return; // Paper - add ability to disable frosted ice - if ((random.nextInt(3) == 0 || this.a(world, blockposition, 4)) && world.getLightLevel(blockposition) > 11 - (Integer) iblockdata.get(BlockIceFrost.a) - iblockdata.b((IBlockAccess) world, blockposition) && this.e(iblockdata, world, blockposition)) { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - blockposition_pooledblockposition.g(blockposition).c(enumdirection); - IBlockData iblockdata1 = world.getTypeIfLoaded(blockposition_pooledblockposition); // Paper - don't load chunks - if (iblockdata1 == null) continue; // Paper - - if (iblockdata1.getBlock() == this && !this.e(iblockdata1, world, blockposition_pooledblockposition)) { - world.getBlockTickList().a(blockposition_pooledblockposition, this, MathHelper.nextInt(random, world.paperConfig.frostedIceDelayMin, world.paperConfig.frostedIceDelayMax)); // Paper - use configurable min/max delay - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - } else { - world.getBlockTickList().a(blockposition, this, MathHelper.nextInt(random, world.paperConfig.frostedIceDelayMin, world.paperConfig.frostedIceDelayMax)); // Paper - use configurable min/max delay - } - } - - private boolean e(IBlockData iblockdata, World world, BlockPosition blockposition) { - int i = (Integer) iblockdata.get(BlockIceFrost.a); - - if (i < 3) { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockIceFrost.a, i + 1), 2); - return false; - } else { - this.melt(iblockdata, world, blockposition); - return true; - } - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (block == this && this.a(world, blockposition, 2)) { - this.melt(iblockdata, world, blockposition); - } - - super.doPhysics(iblockdata, world, blockposition, block, blockposition1, flag); - } - - private boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, int i) { - int j = 0; - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - EnumDirection[] aenumdirection = EnumDirection.values(); - int k = aenumdirection.length; - - for (int l = 0; l < k; ++l) { - EnumDirection enumdirection = aenumdirection[l]; - - blockposition_pooledblockposition.g(blockposition).c(enumdirection); - if (((World) iblockaccess).getBlockIfLoaded(blockposition_pooledblockposition) == this) { // Paper - don't load chunks - ++j; - if (j >= i) { - boolean flag = false; - - return flag; - } - } - } - - return true; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockIceFrost.a); - } -} diff --git a/src/main/java/net/minecraft/server/BlockJukeBox.java b/src/main/java/net/minecraft/server/BlockJukeBox.java deleted file mode 100644 index 6fc71fe76..000000000 --- a/src/main/java/net/minecraft/server/BlockJukeBox.java +++ /dev/null @@ -1,106 +0,0 @@ -package net.minecraft.server; - -public class BlockJukeBox extends BlockTileEntity { - - public static final BlockStateBoolean HAS_RECORD = BlockProperties.n; - - protected BlockJukeBox(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockJukeBox.HAS_RECORD, false)); - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if ((Boolean) 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(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, ItemStack itemstack) { - TileEntity tileentity = generatoraccess.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityJukeBox) { - // CraftBukkit start - There can only be one - itemstack = itemstack.cloneItemStack(); - if (!itemstack.isEmpty()) { - itemstack.setCount(1); - } - ((TileEntityJukeBox) tileentity).setRecord(itemstack); - // CraftBukkit end - generatoraccess.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockJukeBox.HAS_RECORD, true), 2); - } - } - - public void dropRecord(World world, BlockPosition blockposition) { - if (!world.isClientSide) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityJukeBox) { - TileEntityJukeBox tileentityjukebox = (TileEntityJukeBox) tileentity; - ItemStack itemstack = tileentityjukebox.getRecord(); - - if (!itemstack.isEmpty()) { - world.triggerEffect(1010, blockposition, 0); - tileentityjukebox.clear(); - float f = 0.7F; - double d0 = (double) (world.random.nextFloat() * 0.7F) + 0.15000000596046448D; - double d1 = (double) (world.random.nextFloat() * 0.7F) + 0.06000000238418579D + 0.6D; - double d2 = (double) (world.random.nextFloat() * 0.7F) + 0.15000000596046448D; - ItemStack itemstack1 = itemstack.cloneItemStack(); - EntityItem entityitem = new EntityItem(world, (double) blockposition.getX() + d0, (double) blockposition.getY() + d1, (double) blockposition.getZ() + d2, itemstack1); - - entityitem.defaultPickupDelay(); - world.addEntity(entityitem); - } - } - } - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata.getBlock() != iblockdata1.getBlock()) { - this.dropRecord(world, blockposition); - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - } - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityJukeBox(); - } - - @Override - public boolean isComplexRedstone(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityJukeBox) { - Item item = ((TileEntityJukeBox) tileentity).getRecord().getItem(); - - if (item instanceof ItemRecord) { - return ((ItemRecord) item).d(); - } - } - - return 0; - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.MODEL; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockJukeBox.HAS_RECORD); - } -} diff --git a/src/main/java/net/minecraft/server/BlockKelp.java b/src/main/java/net/minecraft/server/BlockKelp.java deleted file mode 100644 index 29c7d291f..000000000 --- a/src/main/java/net/minecraft/server/BlockKelp.java +++ /dev/null @@ -1,99 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public class BlockKelp extends Block implements IFluidContainer { - - public static final BlockStateInteger a = BlockProperties.ae; - protected static final VoxelShape b = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 9.0D, 16.0D); - - protected BlockKelp(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockKelp.a, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockKelp.b; - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - Fluid fluid = blockactioncontext.getWorld().getFluid(blockactioncontext.getClickPosition()); - - return fluid.a(TagsFluid.WATER) && fluid.g() == 8 ? this.a((GeneratorAccess) blockactioncontext.getWorld()) : null; - } - - public IBlockData a(GeneratorAccess generatoraccess) { - return (IBlockData) this.getBlockData().set(BlockKelp.a, generatoraccess.getRandom().nextInt(25)); - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - public Fluid g(IBlockData iblockdata) { - return FluidTypes.WATER.a(false); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!iblockdata.canPlace(world, blockposition)) { - world.b(blockposition, true); - } else { - BlockPosition blockposition1 = blockposition.up(); - IBlockData iblockdata1 = world.getType(blockposition1); - - if (iblockdata1.getBlock() == Blocks.WATER && (Integer) iblockdata.get(BlockKelp.a) < 25 && random.nextDouble() < (100.0D / world.spigotConfig.kelpModifier) * 0.14D) { // Spigot - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition1, (IBlockData) iblockdata.a((IBlockState) BlockKelp.a)); // CraftBukkit - } - - } - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata1 = iworldreader.getType(blockposition1); - Block block = iblockdata1.getBlock(); - - return block == Blocks.MAGMA_BLOCK ? false : block == this || block == Blocks.KELP_PLANT || iblockdata1.d(iworldreader, blockposition1, EnumDirection.UP); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (!iblockdata.canPlace(generatoraccess, blockposition)) { - if (enumdirection == EnumDirection.DOWN) { - return Blocks.AIR.getBlockData(); - } - - generatoraccess.getBlockTickList().a(blockposition, this, 1); - } - - if (enumdirection == EnumDirection.UP && iblockdata1.getBlock() == this) { - return Blocks.KELP_PLANT.getBlockData(); - } else { - generatoraccess.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) generatoraccess)); - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockKelp.a); - } - - @Override - public boolean canPlace(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, FluidType fluidtype) { - return false; - } - - @Override - public boolean place(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, Fluid fluid) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockLeaves.java b/src/main/java/net/minecraft/server/BlockLeaves.java deleted file mode 100644 index 840e66a05..000000000 --- a/src/main/java/net/minecraft/server/BlockLeaves.java +++ /dev/null @@ -1,133 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -import org.bukkit.event.block.LeavesDecayEvent; // CraftBukkit - -public class BlockLeaves extends Block { - - public static final BlockStateInteger DISTANCE = BlockProperties.ah; - public static final BlockStateBoolean PERSISTENT = BlockProperties.v; - protected static boolean c; - - public BlockLeaves(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockLeaves.DISTANCE, 7)).set(BlockLeaves.PERSISTENT, false)); - } - - @Override - public boolean isTicking(IBlockData iblockdata) { - return (Integer) iblockdata.get(BlockLeaves.DISTANCE) == 7 && !(Boolean) iblockdata.get(BlockLeaves.PERSISTENT); - } - - @Override - public void c(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!(Boolean) iblockdata.get(BlockLeaves.PERSISTENT) && (Integer) iblockdata.get(BlockLeaves.DISTANCE) == 7) { - // 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 - c(iblockdata, world, blockposition); - world.a(blockposition, false); - } - - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - world.setTypeAndData(blockposition, a(iblockdata, (GeneratorAccess) world, blockposition), 3); - } - - @Override - public int k(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return 1; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - int i = j(iblockdata1) + 1; - - if (i != 1 || (Integer) iblockdata.get(BlockLeaves.DISTANCE) != i) { - generatoraccess.getBlockTickList().a(blockposition, this, 1); - } - - return iblockdata; - } - - private static IBlockData a(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { - int i = 7; - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - EnumDirection[] aenumdirection = EnumDirection.values(); - int j = aenumdirection.length; - - for (int k = 0; k < j; ++k) { - EnumDirection enumdirection = aenumdirection[k]; - - blockposition_pooledblockposition.g(blockposition).c(enumdirection); - i = Math.min(i, j(generatoraccess.getType(blockposition_pooledblockposition)) + 1); - if (i == 1) { - break; - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - return (IBlockData) iblockdata.set(BlockLeaves.DISTANCE, i); - } - - private static int j(IBlockData iblockdata) { - return TagsBlock.LOGS.isTagged(iblockdata.getBlock()) ? 0 : (iblockdata.getBlock() instanceof BlockLeaves ? (Integer) iblockdata.get(BlockLeaves.DISTANCE) : 7); - } - - @Override - public boolean f(IBlockData iblockdata) { - return false; - } - - @Override - public TextureType c() { - return BlockLeaves.c ? TextureType.CUTOUT_MIPPED : TextureType.SOLID; - } - - @Override - public boolean c(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return false; - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EntityTypes entitytypes) { - return entitytypes == EntityTypes.OCELOT || entitytypes == EntityTypes.PARROT; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockLeaves.DISTANCE, BlockLeaves.PERSISTENT); - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return a((IBlockData) this.getBlockData().set(BlockLeaves.PERSISTENT, true), (GeneratorAccess) blockactioncontext.getWorld(), blockactioncontext.getClickPosition()); - } -} diff --git a/src/main/java/net/minecraft/server/BlockLever.java b/src/main/java/net/minecraft/server/BlockLever.java deleted file mode 100644 index 68b644140..000000000 --- a/src/main/java/net/minecraft/server/BlockLever.java +++ /dev/null @@ -1,137 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public class BlockLever extends BlockAttachable { - - public static final BlockStateBoolean POWERED = BlockProperties.w; - protected static final VoxelShape b = Block.a(5.0D, 4.0D, 10.0D, 11.0D, 12.0D, 16.0D); - protected static final VoxelShape c = Block.a(5.0D, 4.0D, 0.0D, 11.0D, 12.0D, 6.0D); - protected static final VoxelShape d = Block.a(10.0D, 4.0D, 5.0D, 16.0D, 12.0D, 11.0D); - protected static final VoxelShape e = Block.a(0.0D, 4.0D, 5.0D, 6.0D, 12.0D, 11.0D); - protected static final VoxelShape f = Block.a(5.0D, 0.0D, 4.0D, 11.0D, 6.0D, 12.0D); - protected static final VoxelShape g = Block.a(4.0D, 0.0D, 5.0D, 12.0D, 6.0D, 11.0D); - protected static final VoxelShape h = Block.a(5.0D, 10.0D, 4.0D, 11.0D, 16.0D, 12.0D); - protected static final VoxelShape i = Block.a(4.0D, 10.0D, 5.0D, 12.0D, 16.0D, 11.0D); - - protected BlockLever(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockLever.FACING, EnumDirection.NORTH)).set(BlockLever.POWERED, false)).set(BlockLever.FACE, BlockPropertyAttachPosition.WALL)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - switch ((BlockPropertyAttachPosition) iblockdata.get(BlockLever.FACE)) { - case FLOOR: - switch (((EnumDirection) iblockdata.get(BlockLever.FACING)).k()) { - case X: - return BlockLever.g; - case Z: - default: - return BlockLever.f; - } - case WALL: - switch ((EnumDirection) iblockdata.get(BlockLever.FACING)) { - case EAST: - return BlockLever.e; - case WEST: - return BlockLever.d; - case SOUTH: - return BlockLever.c; - case NORTH: - default: - return BlockLever.b; - } - case CEILING: - default: - switch (((EnumDirection) iblockdata.get(BlockLever.FACING)).k()) { - case X: - return BlockLever.i; - case Z: - default: - return BlockLever.h; - } - } - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - iblockdata = (IBlockData) iblockdata.a((IBlockState) BlockLever.POWERED); - boolean flag = (Boolean) iblockdata.get(BlockLever.POWERED); - - if (world.isClientSide) { - if (flag) { - a(iblockdata, world, blockposition, 1.0F); - } - - return true; - } else { - // CraftBukkit start - Interact Lever - boolean powered = !flag; // Old powered state - 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, 3); - float f = flag ? 0.6F : 0.5F; - - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_LEVER_CLICK, SoundCategory.BLOCKS, 0.3F, f); - this.d(iblockdata, world, blockposition); - return true; - } - } - - private static void a(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, float f) { - EnumDirection enumdirection = ((EnumDirection) iblockdata.get(BlockLever.FACING)).opposite(); - EnumDirection enumdirection1 = j(iblockdata).opposite(); - double d0 = (double) blockposition.getX() + 0.5D + 0.1D * (double) enumdirection.getAdjacentX() + 0.2D * (double) enumdirection1.getAdjacentX(); - double d1 = (double) blockposition.getY() + 0.5D + 0.1D * (double) enumdirection.getAdjacentY() + 0.2D * (double) enumdirection1.getAdjacentY(); - double d2 = (double) blockposition.getZ() + 0.5D + 0.1D * (double) enumdirection.getAdjacentZ() + 0.2D * (double) enumdirection1.getAdjacentZ(); - - generatoraccess.addParticle(new ParticleParamRedstone(1.0F, 0.0F, 0.0F, f), d0, d1, d2, 0.0D, 0.0D, 0.0D); - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (!flag && iblockdata.getBlock() != iblockdata1.getBlock()) { - if ((Boolean) iblockdata.get(BlockLever.POWERED)) { - this.d(iblockdata, world, blockposition); - } - - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - } - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Boolean) iblockdata.get(BlockLever.POWERED) ? 15 : 0; - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Boolean) iblockdata.get(BlockLever.POWERED) && j(iblockdata) == enumdirection ? 15 : 0; - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - private void d(IBlockData iblockdata, World world, BlockPosition blockposition) { - world.applyPhysics(blockposition, this); - world.applyPhysics(blockposition.shift(j(iblockdata).opposite()), this); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockLever.FACE, BlockLever.FACING, BlockLever.POWERED); - } -} diff --git a/src/main/java/net/minecraft/server/BlockMagma.java b/src/main/java/net/minecraft/server/BlockMagma.java deleted file mode 100644 index 89cedeac1..000000000 --- a/src/main/java/net/minecraft/server/BlockMagma.java +++ /dev/null @@ -1,68 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class BlockMagma extends Block { - - public BlockMagma(Block.Info block_info) { - super(block_info); - } - - @Override - public void stepOn(World world, BlockPosition blockposition, Entity entity) { - if (!entity.isFireProof() && entity instanceof EntityLiving && !EnchantmentManager.i((EntityLiving) entity)) { - org.bukkit.craftbukkit.event.CraftEventFactory.blockDamage = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); // CraftBukkit - entity.damageEntity(DamageSource.HOT_FLOOR, 1.0F); - org.bukkit.craftbukkit.event.CraftEventFactory.blockDamage = null; // CraftBukkit - } - - super.stepOn(world, blockposition, entity); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - BlockBubbleColumn.a(world, blockposition.up(), true); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (enumdirection == EnumDirection.UP && iblockdata1.getBlock() == Blocks.WATER) { - generatoraccess.getBlockTickList().a(blockposition, this, this.a((IWorldReader) generatoraccess)); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public void c(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - BlockPosition blockposition1 = blockposition.up(); - - if (world.getFluid(blockposition).a(TagsFluid.WATER)) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_FIRE_EXTINGUISH, SoundCategory.BLOCKS, 0.5F, 2.6F + (world.random.nextFloat() - world.random.nextFloat()) * 0.8F); - if (world instanceof WorldServer) { - ((WorldServer) world).a(Particles.LARGE_SMOKE, (double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 0.25D, (double) blockposition1.getZ() + 0.5D, 8, 0.5D, 0.25D, 0.5D, 0.0D); - } - } - - } - - @Override - public int a(IWorldReader iworldreader) { - return 20; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world)); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EntityTypes entitytypes) { - return entitytypes.c(); - } - - @Override - public boolean g(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return true; - } -} diff --git a/src/main/java/net/minecraft/server/BlockMinecartDetector.java b/src/main/java/net/minecraft/server/BlockMinecartDetector.java deleted file mode 100644 index c5481d295..000000000 --- a/src/main/java/net/minecraft/server/BlockMinecartDetector.java +++ /dev/null @@ -1,287 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public class BlockMinecartDetector extends BlockMinecartTrackAbstract { - - public static final BlockStateEnum SHAPE = BlockProperties.X; - public static final BlockStateBoolean POWERED = BlockProperties.w; - - public BlockMinecartDetector(Block.Info block_info) { - super(true, block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockMinecartDetector.POWERED, false)).set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_SOUTH)); - } - - @Override - public int a(IWorldReader iworldreader) { - return 20; - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (!world.isClientSide) { - if (!(Boolean) iblockdata.get(BlockMinecartDetector.POWERED)) { - this.a(world, blockposition, iblockdata); - } - } - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.isClientSide && (Boolean) iblockdata.get(BlockMinecartDetector.POWERED)) { - this.a(world, blockposition, iblockdata); - } - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Boolean) iblockdata.get(BlockMinecartDetector.POWERED) ? 15 : 0; - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return !(Boolean) iblockdata.get(BlockMinecartDetector.POWERED) ? 0 : (enumdirection == EnumDirection.UP ? 15 : 0); - } - - private void a(World world, BlockPosition blockposition, IBlockData iblockdata) { - boolean flag = (Boolean) iblockdata.get(BlockMinecartDetector.POWERED); - boolean flag1 = false; - List list = this.a(world, blockposition, EntityMinecartAbstract.class, (Predicate) null); - - if (!list.isEmpty()) { - flag1 = true; - } - - IBlockData iblockdata1; - // CraftBukkit start - if (flag != flag1) { - org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); - - 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) { - iblockdata1 = (IBlockData) iblockdata.set(BlockMinecartDetector.POWERED, true); - world.setTypeAndData(blockposition, iblockdata1, 3); - this.b(world, blockposition, iblockdata1, true); - world.applyPhysics(blockposition, this); - world.applyPhysics(blockposition.down(), this); - world.b(blockposition, iblockdata, iblockdata1); - } - - if (!flag1 && flag) { - iblockdata1 = (IBlockData) iblockdata.set(BlockMinecartDetector.POWERED, false); - world.setTypeAndData(blockposition, iblockdata1, 3); - this.b(world, blockposition, iblockdata1, false); - world.applyPhysics(blockposition, this); - world.applyPhysics(blockposition.down(), this); - world.b(blockposition, iblockdata, iblockdata1); - } - - if (flag1) { - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world)); - } - - world.updateAdjacentComparators(blockposition, this); - } - - protected void b(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - MinecartTrackLogic minecarttracklogic = new MinecartTrackLogic(world, blockposition, iblockdata); - List list = minecarttracklogic.a(); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition1 = (BlockPosition) iterator.next(); - IBlockData iblockdata1 = world.getType(blockposition1); - - iblockdata1.doPhysics(world, blockposition1, iblockdata1.getBlock(), blockposition, false); - } - - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata1.getBlock() != iblockdata.getBlock()) { - super.onPlace(iblockdata, world, blockposition, iblockdata1, flag); - this.a(world, blockposition, iblockdata); - } - } - - @Override - public IBlockState e() { - return BlockMinecartDetector.SHAPE; - } - - @Override - public boolean isComplexRedstone(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata, World world, BlockPosition blockposition) { - if ((Boolean) iblockdata.get(BlockMinecartDetector.POWERED)) { - List list = this.a(world, blockposition, EntityMinecartCommandBlock.class, (Predicate) null); - - if (!list.isEmpty()) { - return ((EntityMinecartCommandBlock) list.get(0)).getCommandBlock().i(); - } - - List list1 = this.a(world, blockposition, EntityMinecartAbstract.class, IEntitySelector.d); - - if (!list1.isEmpty()) { - return Container.b((IInventory) list1.get(0)); - } - } - - return 0; - } - - protected List a(World world, BlockPosition blockposition, Class oclass, @Nullable Predicate predicate) { - return world.a(oclass, this.a(blockposition), predicate); - } - - private AxisAlignedBB a(BlockPosition blockposition) { - float f = 0.2F; - - return new AxisAlignedBB((double) ((float) blockposition.getX() + 0.2F), (double) blockposition.getY(), (double) ((float) blockposition.getZ() + 0.2F), (double) ((float) (blockposition.getX() + 1) - 0.2F), (double) ((float) (blockposition.getY() + 1) - 0.2F), (double) ((float) (blockposition.getZ() + 1) - 0.2F)); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - switch (enumblockrotation) { - case CLOCKWISE_180: - switch ((BlockPropertyTrackPosition) iblockdata.get(BlockMinecartDetector.SHAPE)) { - case ASCENDING_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_WEST); - case ASCENDING_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_EAST); - case ASCENDING_NORTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_SOUTH); - case ASCENDING_SOUTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_NORTH); - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - } - case COUNTERCLOCKWISE_90: - switch ((BlockPropertyTrackPosition) iblockdata.get(BlockMinecartDetector.SHAPE)) { - case ASCENDING_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_NORTH); - case ASCENDING_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_SOUTH); - case ASCENDING_NORTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_WEST); - case ASCENDING_SOUTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_EAST); - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - case NORTH_SOUTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.EAST_WEST); - case EAST_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_SOUTH); - } - case CLOCKWISE_90: - switch ((BlockPropertyTrackPosition) iblockdata.get(BlockMinecartDetector.SHAPE)) { - case ASCENDING_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_SOUTH); - case ASCENDING_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_NORTH); - case ASCENDING_NORTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_EAST); - case ASCENDING_SOUTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_WEST); - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - case NORTH_SOUTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.EAST_WEST); - case EAST_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_SOUTH); - } - default: - return iblockdata; - } - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - BlockPropertyTrackPosition blockpropertytrackposition = (BlockPropertyTrackPosition) iblockdata.get(BlockMinecartDetector.SHAPE); - - switch (enumblockmirror) { - case LEFT_RIGHT: - switch (blockpropertytrackposition) { - case ASCENDING_NORTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_SOUTH); - case ASCENDING_SOUTH: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_NORTH); - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - default: - return super.a(iblockdata, enumblockmirror); - } - case FRONT_BACK: - switch (blockpropertytrackposition) { - case ASCENDING_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_WEST); - case ASCENDING_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.ASCENDING_EAST); - case ASCENDING_NORTH: - case ASCENDING_SOUTH: - default: - break; - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockMinecartDetector.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - } - } - - return super.a(iblockdata, enumblockmirror); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockMinecartDetector.SHAPE, BlockMinecartDetector.POWERED); - } -} diff --git a/src/main/java/net/minecraft/server/BlockMobSpawner.java b/src/main/java/net/minecraft/server/BlockMobSpawner.java deleted file mode 100644 index bb77d916a..000000000 --- a/src/main/java/net/minecraft/server/BlockMobSpawner.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.minecraft.server; - -public class BlockMobSpawner extends BlockTileEntity { - - protected BlockMobSpawner(Block.Info block_info) { - super(block_info); - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityMobSpawner(); - } - - @Override - public void dropNaturally(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) { - super.dropNaturally(iblockdata, world, blockposition, itemstack); - /* CraftBukkit start - Delegate to getExpDrop - int i = 15 + world.random.nextInt(15) + world.random.nextInt(15); - - this.dropExperience(world, blockposition, i); - */ - } - - @Override - public int getExpDrop(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) { - int i = 15 + world.random.nextInt(15) + world.random.nextInt(15); - - return i; - // CraftBukkit end - } - - @Override - public EnumRenderType c(IBlockData iblockdata) { - return EnumRenderType.MODEL; - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } -} diff --git a/src/main/java/net/minecraft/server/BlockMonsterEggs.java b/src/main/java/net/minecraft/server/BlockMonsterEggs.java deleted file mode 100644 index 46d77d172..000000000 --- a/src/main/java/net/minecraft/server/BlockMonsterEggs.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.Map; - -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; // CraftBukkit - -public class BlockMonsterEggs extends Block { - - private final Block a; - private static final Map b = Maps.newIdentityHashMap(); - - public BlockMonsterEggs(Block block, Block.Info block_info) { - super(block_info); - this.a = block; - BlockMonsterEggs.b.put(block, this); - } - - public Block d() { - return this.a; - } - - public static boolean j(IBlockData iblockdata) { - return BlockMonsterEggs.b.containsKey(iblockdata.getBlock()); - } - - @Override - public void dropNaturally(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) { - super.dropNaturally(iblockdata, world, blockposition, itemstack); - if (!world.isClientSide && world.getGameRules().getBoolean(GameRules.DO_TILE_DROPS) && EnchantmentManager.getEnchantmentLevel(Enchantments.SILK_TOUCH, itemstack) == 0) { - EntitySilverfish entitysilverfish = (EntitySilverfish) EntityTypes.SILVERFISH.a(world); - - entitysilverfish.setPositionRotation((double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, 0.0F, 0.0F); - world.addEntity(entitysilverfish, SpawnReason.SILVERFISH_BLOCK); // CraftBukkit - add SpawnReason - entitysilverfish.doSpawnEffect(); - } - - } - - public static IBlockData e(Block block) { - return ((Block) BlockMonsterEggs.b.get(block)).getBlockData(); - } -} diff --git a/src/main/java/net/minecraft/server/BlockMushroom.java b/src/main/java/net/minecraft/server/BlockMushroom.java deleted file mode 100644 index 9a260cbaa..000000000 --- a/src/main/java/net/minecraft/server/BlockMushroom.java +++ /dev/null @@ -1,111 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Random; - -// CraftBukkit start -import org.bukkit.TreeType; -// CraftBukkit end - -public class BlockMushroom extends BlockPlant implements IBlockFragilePlantElement { - - protected static final VoxelShape a = Block.a(5.0D, 0.0D, 5.0D, 11.0D, 6.0D, 11.0D); - - public BlockMushroom(Block.Info block_info) { - super(block_info); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockMushroom.a; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (random.nextInt(Math.max(1, (int) (100.0F / world.spigotConfig.mushroomModifier) * 25)) == 0) { // Spigot - int i = 5; - boolean flag = true; - Iterator iterator = BlockPosition.a(blockposition.b(-4, -1, -4), blockposition.b(4, 1, 4)).iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition1 = (BlockPosition) iterator.next(); - - if (world.getType(blockposition1).getBlock() == this) { - --i; - if (i <= 0) { - return; - } - } - } - - BlockPosition blockposition2 = blockposition.b(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) && iblockdata.canPlace(world, blockposition2)) { - blockposition = blockposition2; - } - - blockposition2 = blockposition.b(random.nextInt(3) - 1, random.nextInt(2) - random.nextInt(2), random.nextInt(3) - 1); - } - - if (world.isEmpty(blockposition2) && iblockdata.canPlace(world, blockposition2)) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition2, iblockdata, 2); // CraftBukkit - } - } - - } - - @Override - protected boolean a_(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.g(iblockaccess, blockposition); - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata1 = iworldreader.getType(blockposition1); - Block block = iblockdata1.getBlock(); - - return block != Blocks.MYCELIUM && block != Blocks.PODZOL ? iworldreader.getLightLevel(blockposition, 0) < 13 && this.a_(iblockdata1, iworldreader, blockposition1) : true; - } - - public boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, Random random) { - generatoraccess.a(blockposition, false); - WorldGenerator worldgenerator = null; - - if (this == Blocks.BROWN_MUSHROOM) { - BlockSapling.treeType = TreeType.BROWN_MUSHROOM; // CraftBukkit - worldgenerator = WorldGenerator.HUGE_BROWN_MUSHROOM; - } else if (this == Blocks.RED_MUSHROOM) { - BlockSapling.treeType = TreeType.RED_MUSHROOM; // CraftBukkit - worldgenerator = WorldGenerator.HUGE_RED_MUSHROOM; - } - - if (worldgenerator != null && worldgenerator.generate(generatoraccess, generatoraccess.getChunkProvider().getChunkGenerator(), random, blockposition, new WorldGenHugeMushroomConfiguration(true))) { - return true; - } else { - generatoraccess.setTypeAndData(blockposition, iblockdata, 3); - return false; - } - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return true; - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return (double) random.nextFloat() < 0.4D; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - this.a((GeneratorAccess) world, blockposition, iblockdata, random); - } - - @Override - public boolean g(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return true; - } -} diff --git a/src/main/java/net/minecraft/server/BlockNetherWart.java b/src/main/java/net/minecraft/server/BlockNetherWart.java deleted file mode 100644 index fbd242eb6..000000000 --- a/src/main/java/net/minecraft/server/BlockNetherWart.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class BlockNetherWart extends BlockPlant { - - public static final BlockStateInteger AGE = BlockProperties.aa; - private static final VoxelShape[] b = new VoxelShape[]{Block.a(0.0D, 0.0D, 0.0D, 16.0D, 5.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 8.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 11.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 14.0D, 16.0D)}; - - protected BlockNetherWart(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockNetherWart.AGE, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockNetherWart.b[(Integer) iblockdata.get(BlockNetherWart.AGE)]; - } - - @Override - protected boolean a_(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.getBlock() == Blocks.SOUL_SAND; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - int i = (Integer) iblockdata.get(BlockNetherWart.AGE); - - if (i < 3 && random.nextInt(Math.max(1, (int) (100.0F / world.spigotConfig.wartModifier) * 10)) == 0) { // Spigot - iblockdata = (IBlockData) iblockdata.set(BlockNetherWart.AGE, i + 1); - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockGrowEvent(world, blockposition, iblockdata, 2); // CraftBukkit - } - - super.tick(iblockdata, world, blockposition, random); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockNetherWart.AGE); - } -} diff --git a/src/main/java/net/minecraft/server/BlockNote.java b/src/main/java/net/minecraft/server/BlockNote.java deleted file mode 100644 index 703379efe..000000000 --- a/src/main/java/net/minecraft/server/BlockNote.java +++ /dev/null @@ -1,85 +0,0 @@ -package net.minecraft.server; - -public class BlockNote extends Block { - - public static final BlockStateEnum INSTRUMENT = BlockProperties.aA; - public static final BlockStateBoolean POWERED = BlockProperties.w; - public static final BlockStateInteger NOTE = BlockProperties.aq; - - public BlockNote(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockNote.INSTRUMENT, BlockPropertyInstrument.HARP)).set(BlockNote.NOTE, 0)).set(BlockNote.POWERED, false)); - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return (IBlockData) this.getBlockData().set(BlockNote.INSTRUMENT, BlockPropertyInstrument.a(blockactioncontext.getWorld().getType(blockactioncontext.getClickPosition().down()))); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return enumdirection == EnumDirection.DOWN ? (IBlockData) iblockdata.set(BlockNote.INSTRUMENT, BlockPropertyInstrument.a(iblockdata1)) : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - boolean flag1 = world.isBlockIndirectlyPowered(blockposition); - - if (flag1 != (Boolean) iblockdata.get(BlockNote.POWERED)) { - if (flag1) { - this.play(world, blockposition, iblockdata); // CraftBukkit - } - - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockNote.POWERED, flag1), 3); - } - - } - - private void play(World world, BlockPosition blockposition, IBlockData data) { // CraftBukkit - if (world.getType(blockposition.up()).isAir()) { - // CraftBukkit start - org.bukkit.event.block.NotePlayEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callNotePlayEvent(world, blockposition, data.get(BlockNote.INSTRUMENT), data.get(BlockNote.NOTE)); - if (!event.isCancelled()) { - world.playBlockAction(blockposition, this, 0, 0); - } - // CraftBukkit end - } - - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (world.isClientSide) { - return true; - } else { - iblockdata = (IBlockData) iblockdata.a((IBlockState) BlockNote.NOTE); - world.setTypeAndData(blockposition, iblockdata, 3); - this.play(world, blockposition, iblockdata); // CraftBukkit - entityhuman.a(StatisticList.TUNE_NOTEBLOCK); - return true; - } - } - - @Override - public void attack(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman) { - if (!world.isClientSide) { - this.play(world, blockposition, iblockdata); // CraftBukkit - entityhuman.a(StatisticList.PLAY_NOTEBLOCK); - } - } - - @Override - public boolean a(IBlockData iblockdata, World world, BlockPosition blockposition, int i, int j) { - int k = (Integer) iblockdata.get(BlockNote.NOTE); - float f = (float) Math.pow(2.0D, (double) (k - 12) / 12.0D); - - world.playSound((EntityHuman) null, blockposition, ((BlockPropertyInstrument) iblockdata.get(BlockNote.INSTRUMENT)).a(), SoundCategory.RECORDS, 3.0F, f); - world.addParticle(Particles.NOTE, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 1.2D, (double) blockposition.getZ() + 0.5D, (double) k / 24.0D, 0.0D, 0.0D); - return true; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockNote.INSTRUMENT, BlockNote.POWERED, BlockNote.NOTE); - } -} diff --git a/src/main/java/net/minecraft/server/BlockObserver.java b/src/main/java/net/minecraft/server/BlockObserver.java deleted file mode 100644 index 80fde17c0..000000000 --- a/src/main/java/net/minecraft/server/BlockObserver.java +++ /dev/null @@ -1,119 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockObserver extends BlockDirectional { - - public static final BlockStateBoolean b = BlockProperties.w; - - public BlockObserver(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockObserver.FACING, EnumDirection.SOUTH)).set(BlockObserver.b, false)); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockObserver.FACING, BlockObserver.b); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return (IBlockData) iblockdata.set(BlockObserver.FACING, enumblockrotation.a((EnumDirection) iblockdata.get(BlockObserver.FACING))); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockObserver.FACING))); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if ((Boolean) iblockdata.get(BlockObserver.b)) { - // CraftBukkit start - if (CraftEventFactory.callRedstoneChange(world, blockposition, 15, 0).getNewCurrent() != 0) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockObserver.b, false), 2); - } else { - // CraftBukkit start - if (CraftEventFactory.callRedstoneChange(world, blockposition, 0, 15).getNewCurrent() != 15) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockObserver.b, true), 2); - world.getBlockTickList().a(blockposition, this, 2); - } - - this.a(world, blockposition, iblockdata); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (iblockdata.get(BlockObserver.FACING) == enumdirection && !(Boolean) iblockdata.get(BlockObserver.b)) { - this.a(generatoraccess, blockposition); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - private void a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - if (!generatoraccess.e() && !generatoraccess.getBlockTickList().a(blockposition, this)) { - generatoraccess.getBlockTickList().a(blockposition, this, 2); - } - - } - - protected void a(World world, BlockPosition blockposition, IBlockData iblockdata) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockObserver.FACING); - BlockPosition blockposition1 = blockposition.shift(enumdirection.opposite()); - - world.a(blockposition1, (Block) this, blockposition); - world.a(blockposition1, (Block) this, enumdirection); - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return iblockdata.b(iblockaccess, blockposition, enumdirection); - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Boolean) iblockdata.get(BlockObserver.b) && iblockdata.get(BlockObserver.FACING) == enumdirection ? 15 : 0; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata.getBlock() != iblockdata1.getBlock()) { - if (!world.e() && (Boolean) iblockdata.get(BlockObserver.b) && !world.getBlockTickList().a(blockposition, this)) { - IBlockData iblockdata2 = (IBlockData) iblockdata.set(BlockObserver.b, false); - - world.setTypeAndData(blockposition, iblockdata2, 18); - this.a(world, blockposition, iblockdata2); - } - - } - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata.getBlock() != iblockdata1.getBlock()) { - if (!world.isClientSide && (Boolean) iblockdata.get(BlockObserver.b) && world.getBlockTickList().a(blockposition, this)) { - this.a(world, blockposition, (IBlockData) iblockdata.set(BlockObserver.b, false)); - } - - } - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return (IBlockData) this.getBlockData().set(BlockObserver.FACING, blockactioncontext.d().opposite().opposite()); - } -} diff --git a/src/main/java/net/minecraft/server/BlockOre.java b/src/main/java/net/minecraft/server/BlockOre.java deleted file mode 100644 index c9782f4fb..000000000 --- a/src/main/java/net/minecraft/server/BlockOre.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class BlockOre extends Block { - - public BlockOre(Block.Info block_info) { - super(block_info); - } - - protected int a(Random random) { - return this == Blocks.COAL_ORE ? MathHelper.nextInt(random, 0, 2) : (this == Blocks.DIAMOND_ORE ? MathHelper.nextInt(random, 3, 7) : (this == Blocks.EMERALD_ORE ? MathHelper.nextInt(random, 3, 7) : (this == Blocks.LAPIS_ORE ? MathHelper.nextInt(random, 2, 5) : (this == Blocks.NETHER_QUARTZ_ORE ? MathHelper.nextInt(random, 2, 5) : 0)))); - } - - @Override - public void dropNaturally(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) { - super.dropNaturally(iblockdata, world, blockposition, itemstack); - /* CraftBukkit start - Delegated to getExpDrop - if (EnchantmentManager.getEnchantmentLevel(Enchantments.SILK_TOUCH, itemstack) == 0) { - int i = this.a(world.random); - - if (i > 0) { - this.dropExperience(world, blockposition, i); - } - } - // */ - - } - - @Override - public int getExpDrop(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) { - if (EnchantmentManager.getEnchantmentLevel(Enchantments.SILK_TOUCH, itemstack) == 0) { - int i = this.a(world.random); - - if (i > 0) { - return i; - } - } - - return 0; - // CraftBukkit end - } -} diff --git a/src/main/java/net/minecraft/server/BlockPiston.java b/src/main/java/net/minecraft/server/BlockPiston.java deleted file mode 100644 index de804348f..000000000 --- a/src/main/java/net/minecraft/server/BlockPiston.java +++ /dev/null @@ -1,436 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -// CraftBukkit start -import com.google.common.collect.ImmutableList; -import java.util.AbstractList; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -// CraftBukkit end - -public class BlockPiston extends BlockDirectional { - - public static final BlockStateBoolean EXTENDED = BlockProperties.g; - protected static final VoxelShape c = Block.a(0.0D, 0.0D, 0.0D, 12.0D, 16.0D, 16.0D); - protected static final VoxelShape d = Block.a(4.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape e = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 12.0D); - protected static final VoxelShape f = Block.a(0.0D, 0.0D, 4.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape g = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 12.0D, 16.0D); - protected static final VoxelShape h = Block.a(0.0D, 4.0D, 0.0D, 16.0D, 16.0D, 16.0D); - private final boolean sticky; - - public BlockPiston(boolean flag, Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockPiston.FACING, EnumDirection.NORTH)).set(BlockPiston.EXTENDED, false)); - this.sticky = flag; - } - - @Override - public boolean c(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return !(Boolean) iblockdata.get(BlockPiston.EXTENDED); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - if ((Boolean) iblockdata.get(BlockPiston.EXTENDED)) { - switch ((EnumDirection) iblockdata.get(BlockPiston.FACING)) { - case DOWN: - return BlockPiston.h; - case UP: - default: - return BlockPiston.g; - case NORTH: - return BlockPiston.f; - case SOUTH: - return BlockPiston.e; - case WEST: - return BlockPiston.d; - case EAST: - return BlockPiston.c; - } - } else { - return VoxelShapes.b(); - } - } - - @Override - public boolean isOccluding(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return false; - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { - if (!world.isClientSide) { - this.a(world, blockposition, iblockdata); - } - - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (!world.isClientSide) { - this.a(world, blockposition, iblockdata); - } - - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata1.getBlock() != iblockdata.getBlock()) { - if (!world.isClientSide && world.getTileEntity(blockposition) == null) { - this.a(world, blockposition, iblockdata); - } - - } - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return (IBlockData) ((IBlockData) this.getBlockData().set(BlockPiston.FACING, blockactioncontext.d().opposite())).set(BlockPiston.EXTENDED, false); - } - - private void a(World world, BlockPosition blockposition, IBlockData iblockdata) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockPiston.FACING); - boolean flag = this.a(world, blockposition, enumdirection); - - if (flag && !(Boolean) iblockdata.get(BlockPiston.EXTENDED)) { - if ((new PistonExtendsChecker(world, blockposition, enumdirection, true)).a()) { - world.playBlockAction(blockposition, this, 0, enumdirection.a()); - } - } else if (!flag && (Boolean) iblockdata.get(BlockPiston.EXTENDED)) { - BlockPosition blockposition1 = blockposition.shift(enumdirection, 2); - IBlockData iblockdata1 = world.getType(blockposition1); - byte b0 = 1; - - if (iblockdata1.getBlock() == Blocks.MOVING_PISTON && iblockdata1.get(BlockPiston.FACING) == enumdirection) { - TileEntity tileentity = world.getTileEntity(blockposition1); - - if (tileentity instanceof TileEntityPiston) { - TileEntityPiston tileentitypiston = (TileEntityPiston) tileentity; - - if (tileentitypiston.d() && (tileentitypiston.a(0.0F) < 0.5F || world.getTime() == tileentitypiston.v() || ((WorldServer) world).b())) { - b0 = 2; - } - } - } - - // CraftBukkit start - //if (!this.sticky) { // Paper - Prevents empty sticky pistons from firing retract - history behind is odd - 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; - } - //} // Paper - // PAIL: checkME - what happened to setTypeAndData? - // CraftBukkit end - world.playBlockAction(blockposition, this, b0, enumdirection.a()); - } - - } - - private boolean a(World world, BlockPosition blockposition, EnumDirection enumdirection) { - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - int j; - - for (j = 0; j < i; ++j) { - EnumDirection enumdirection1 = aenumdirection[j]; - - if (enumdirection1 != enumdirection && world.isBlockFacePowered(blockposition.shift(enumdirection1), enumdirection1)) { - return true; - } - } - - if (world.isBlockFacePowered(blockposition, EnumDirection.DOWN)) { - return true; - } else { - BlockPosition blockposition1 = blockposition.up(); - EnumDirection[] aenumdirection1 = EnumDirection.values(); - - j = aenumdirection1.length; - - for (int k = 0; k < j; ++k) { - EnumDirection enumdirection2 = aenumdirection1[k]; - - if (enumdirection2 != EnumDirection.DOWN && world.isBlockFacePowered(blockposition1.shift(enumdirection2), enumdirection2)) { - return true; - } - } - - return false; - } - } - - @Override - public boolean a(IBlockData iblockdata, World world, BlockPosition blockposition, int i, int j) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockPiston.FACING); - - if (!world.isClientSide) { - boolean flag = this.a(world, blockposition, enumdirection); - - if (flag && (i == 1 || i == 2)) { - world.setTypeAndData(blockposition, (IBlockData) 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) iblockdata.set(BlockPiston.EXTENDED, true), 67); - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_PISTON_EXTEND, SoundCategory.BLOCKS, 0.5F, world.random.nextFloat() * 0.25F + 0.6F); - } else if (i == 1 || i == 2) { - TileEntity tileentity = world.getTileEntity(blockposition.shift(enumdirection)); - - if (tileentity instanceof TileEntityPiston) { - ((TileEntityPiston) tileentity).u(); - } - - world.setTypeAndData(blockposition, (IBlockData) ((IBlockData) Blocks.MOVING_PISTON.getBlockData().set(BlockPistonMoving.a, enumdirection)).set(BlockPistonMoving.b, this.sticky ? BlockPropertyPistonType.STICKY : BlockPropertyPistonType.DEFAULT), 3); - world.setTileEntity(blockposition, BlockPistonMoving.a((IBlockData) this.getBlockData().set(BlockPiston.FACING, EnumDirection.fromType1(j & 7)), enumdirection, false, true)); - if (this.sticky) { - BlockPosition blockposition1 = blockposition.b(enumdirection.getAdjacentX() * 2, enumdirection.getAdjacentY() * 2, enumdirection.getAdjacentZ() * 2); - IBlockData iblockdata1 = world.getType(blockposition1); - Block block = iblockdata1.getBlock(); - boolean flag1 = false; - - if (block == Blocks.MOVING_PISTON) { - TileEntity tileentity1 = world.getTileEntity(blockposition1); - - if (tileentity1 instanceof TileEntityPiston) { - TileEntityPiston tileentitypiston = (TileEntityPiston) tileentity1; - - if (tileentitypiston.f() == enumdirection && tileentitypiston.d()) { - tileentitypiston.u(); - flag1 = true; - } - } - } - - if (!flag1) { - if (i == 1 && !iblockdata1.isAir() && a(iblockdata1, world, blockposition1, enumdirection.opposite(), false, enumdirection) && (iblockdata1.getPushReaction() == EnumPistonReaction.NORMAL || block == Blocks.PISTON || block == Blocks.STICKY_PISTON)) { - this.a(world, blockposition, enumdirection, false); - } else { - world.a(blockposition.shift(enumdirection), false); - } - } - } else { - world.a(blockposition.shift(enumdirection), false); - } - - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_PISTON_CONTRACT, SoundCategory.BLOCKS, 0.5F, world.random.nextFloat() * 0.15F + 0.6F); - } - - return true; - } - - public static boolean a(IBlockData iblockdata, World world, BlockPosition blockposition, EnumDirection enumdirection, boolean flag, EnumDirection enumdirection1) { - Block block = iblockdata.getBlock(); - - 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.getBuildHeight() - 1 && (enumdirection != EnumDirection.UP || blockposition.getY() != world.getBuildHeight() - 1)) { - if (block != Blocks.PISTON && block != Blocks.STICKY_PISTON) { - if (iblockdata.f(world, blockposition) == -1.0F) { - return false; - } - - switch (iblockdata.getPushReaction()) { - case BLOCK: - return false; - case DESTROY: - return flag; - case PUSH_ONLY: - return enumdirection == enumdirection1; - } - } else if ((Boolean) iblockdata.get(BlockPiston.EXTENDED)) { - return false; - } - - return !block.isTileEntity(); - } else { - return false; - } - } else { - return false; - } - } - - private boolean a(World world, BlockPosition blockposition, EnumDirection enumdirection, boolean flag) { - BlockPosition blockposition1 = blockposition.shift(enumdirection); - - if (!flag && world.getType(blockposition1).getBlock() == Blocks.PISTON_HEAD) { - world.setTypeAndData(blockposition1, Blocks.AIR.getBlockData(), 20); - } - - PistonExtendsChecker pistonextendschecker = new PistonExtendsChecker(world, blockposition, enumdirection, flag); - - if (!pistonextendschecker.a()) { - return false; - } else { - List list = pistonextendschecker.getMovedBlocks(); - List list1 = Lists.newArrayList(); - - for (int i = 0; i < list.size(); ++i) { - BlockPosition blockposition2 = (BlockPosition) list.get(i); - - list1.add(world.getType(blockposition2)); - } - - List list2 = pistonextendschecker.getBrokenBlocks(); - int j = list.size() + list2.size(); - IBlockData[] aiblockdata = new IBlockData[j]; - EnumDirection enumdirection1 = flag ? enumdirection : enumdirection.opposite(); - Set set = Sets.newHashSet(list); - // 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 = (BlockPosition) (index < moved.size() ? moved.get(index) : broken.get(index - moved.size())); - return bblock.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); - } - }; - 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)); - } - world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - for (BlockPosition b : broken) { - world.notify(b, Blocks.AIR.getBlockData(), world.getType(b), 3); - } - for (BlockPosition b : moved) { - world.notify(b, Blocks.AIR.getBlockData(), world.getType(b), 3); - b = b.shift(enumdirection1); - world.notify(b, Blocks.AIR.getBlockData(), world.getType(b), 3); - } - return false; - } - // CraftBukkit end - - BlockPosition blockposition3; - int k; - IBlockData iblockdata; - - for (k = list2.size() - 1; k >= 0; --k) { - blockposition3 = (BlockPosition) list2.get(k); - iblockdata = world.getType(blockposition3); - TileEntity tileentity = iblockdata.getBlock().isTileEntity() ? world.getTileEntity(blockposition3) : null; - - a(iblockdata, world, blockposition3, tileentity); - world.setTypeAndData(blockposition3, Blocks.AIR.getBlockData(), 18); - --j; - aiblockdata[j] = iblockdata; - } - - for (k = list.size() - 1; k >= 0; --k) { - blockposition3 = (BlockPosition) list.get(k); - iblockdata = world.getType(blockposition3); - blockposition3 = blockposition3.shift(enumdirection1); - set.remove(blockposition3); - world.setTypeAndData(blockposition3, (IBlockData) Blocks.MOVING_PISTON.getBlockData().set(BlockPiston.FACING, enumdirection), 68); - world.setTileEntity(blockposition3, BlockPistonMoving.a((IBlockData) list1.get(k), enumdirection, flag, false)); - --j; - aiblockdata[j] = iblockdata; - } - - IBlockData iblockdata1; - - if (flag) { - BlockPropertyPistonType blockpropertypistontype = this.sticky ? BlockPropertyPistonType.STICKY : BlockPropertyPistonType.DEFAULT; - - iblockdata1 = (IBlockData) ((IBlockData) Blocks.PISTON_HEAD.getBlockData().set(BlockPistonExtension.FACING, enumdirection)).set(BlockPistonExtension.TYPE, blockpropertypistontype); - iblockdata = (IBlockData) ((IBlockData) Blocks.MOVING_PISTON.getBlockData().set(BlockPistonMoving.a, enumdirection)).set(BlockPistonMoving.b, this.sticky ? BlockPropertyPistonType.STICKY : BlockPropertyPistonType.DEFAULT); - set.remove(blockposition1); - world.setTypeAndData(blockposition1, iblockdata, 68); - world.setTileEntity(blockposition1, BlockPistonMoving.a(iblockdata1, enumdirection, true, true)); - } - - Iterator iterator = set.iterator(); - - while (iterator.hasNext()) { - blockposition3 = (BlockPosition) iterator.next(); - world.setTypeAndData(blockposition3, Blocks.AIR.getBlockData(), 66); - } - - for (k = list2.size() - 1; k >= 0; --k) { - iblockdata1 = aiblockdata[j++]; - BlockPosition blockposition4 = (BlockPosition) list2.get(k); - - iblockdata1.b(world, blockposition4, 2); - world.applyPhysics(blockposition4, iblockdata1.getBlock()); - } - - for (k = list.size() - 1; k >= 0; --k) { - world.applyPhysics((BlockPosition) list.get(k), aiblockdata[j++].getBlock()); - } - - if (flag) { - world.applyPhysics(blockposition1, Blocks.PISTON_HEAD); - } - - return true; - } - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return (IBlockData) iblockdata.set(BlockPiston.FACING, enumblockrotation.a((EnumDirection) iblockdata.get(BlockPiston.FACING))); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockPiston.FACING))); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockPiston.FACING, BlockPiston.EXTENDED); - } - - @Override - public boolean n(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockPiston.EXTENDED); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockPlant.java b/src/main/java/net/minecraft/server/BlockPlant.java deleted file mode 100644 index 0526af776..000000000 --- a/src/main/java/net/minecraft/server/BlockPlant.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.minecraft.server; - -public class BlockPlant extends Block { - - protected BlockPlant(Block.Info block_info) { - super(block_info); - } - - protected boolean a_(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - Block block = iblockdata.getBlock(); - - return block == Blocks.GRASS_BLOCK || block == Blocks.DIRT || block == Blocks.COARSE_DIRT || block == Blocks.PODZOL || block == Blocks.FARMLAND; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - // CraftBukkit start - if (!iblockdata.canPlace(generatoraccess, blockposition)) { - if (!(generatoraccess instanceof WorldServer && ((WorldServer) generatoraccess).hasPhysicsEvent) || !org.bukkit.craftbukkit.event.CraftEventFactory.callBlockPhysicsEvent(generatoraccess, blockposition).isCancelled()) { // Paper - return Blocks.AIR.getBlockData(); - } - } - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - // CraftBukkit end - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - - return this.a_(iworldreader.getType(blockposition1), iworldreader, blockposition1); - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - public boolean b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return true; - } -} diff --git a/src/main/java/net/minecraft/server/BlockPortal.java b/src/main/java/net/minecraft/server/BlockPortal.java deleted file mode 100644 index 4eef7127a..000000000 --- a/src/main/java/net/minecraft/server/BlockPortal.java +++ /dev/null @@ -1,372 +0,0 @@ -package net.minecraft.server; - -import com.google.common.cache.LoadingCache; -import java.util.Random; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.block.CraftBlockState; -import org.bukkit.event.entity.EntityPortalEnterEvent; -import org.bukkit.event.world.PortalCreateEvent; -// CraftBukkit end - -public class BlockPortal extends Block { - - public static final BlockStateEnum AXIS = BlockProperties.D; - protected static final VoxelShape b = Block.a(0.0D, 0.0D, 6.0D, 16.0D, 16.0D, 10.0D); - protected static final VoxelShape c = Block.a(6.0D, 0.0D, 0.0D, 10.0D, 16.0D, 16.0D); - - public BlockPortal(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockPortal.AXIS, EnumDirection.EnumAxis.X)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - switch ((EnumDirection.EnumAxis) iblockdata.get(BlockPortal.AXIS)) { - case Z: - return BlockPortal.c; - case X: - default: - return BlockPortal.b; - } - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (world.spigotConfig.enableZombiePigmenPortalSpawns && world.worldProvider.isOverworld() && world.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING) && random.nextInt(2000) < world.getDifficulty().a()) { // Spigot - while (world.getType(blockposition).getBlock() == this) { - blockposition = blockposition.down(); - } - - if (world.getType(blockposition).a((IBlockAccess) world, blockposition, EntityTypes.ZOMBIE_PIGMAN)) { - // CraftBukkit - set spawn reason to NETHER_PORTAL - Entity entity = EntityTypes.ZOMBIE_PIGMAN.spawnCreature(world, (NBTTagCompound) null, (IChatBaseComponent) null, (EntityHuman) null, blockposition.up(), EnumMobSpawn.STRUCTURE, false, false, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NETHER_PORTAL); - - if (entity != null) { - entity.portalCooldown = entity.aX(); - } - } - } - - } - - public boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - BlockPortal.Shape blockportal_shape = this.b(generatoraccess, blockposition); - - if (blockportal_shape != null) { - // CraftBukkit start - return portalcreator - return blockportal_shape.createPortal(); - // return true; - // CraftBukkit end - } else { - return false; - } - } - - @Nullable - public BlockPortal.Shape b(GeneratorAccess generatoraccess, BlockPosition blockposition) { - BlockPortal.Shape blockportal_shape = new BlockPortal.Shape(generatoraccess, blockposition, EnumDirection.EnumAxis.X); - - if (blockportal_shape.d() && blockportal_shape.e == 0) { - return blockportal_shape; - } else { - BlockPortal.Shape blockportal_shape1 = new BlockPortal.Shape(generatoraccess, blockposition, EnumDirection.EnumAxis.Z); - - return blockportal_shape1.d() && blockportal_shape1.e == 0 ? blockportal_shape1 : null; - } - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - EnumDirection.EnumAxis enumdirection_enumaxis = enumdirection.k(); - EnumDirection.EnumAxis enumdirection_enumaxis1 = (EnumDirection.EnumAxis) iblockdata.get(BlockPortal.AXIS); - boolean flag = enumdirection_enumaxis1 != enumdirection_enumaxis && enumdirection_enumaxis.c(); - - return !flag && iblockdata1.getBlock() != this && !(new BlockPortal.Shape(generatoraccess, blockposition, enumdirection_enumaxis1)).f() ? Blocks.AIR.getBlockData() : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public TextureType c() { - return TextureType.TRANSLUCENT; - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (!entity.isPassenger() && !entity.isVehicle() && entity.canPortal()) { - // 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(blockposition); - } - - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - switch (enumblockrotation) { - case COUNTERCLOCKWISE_90: - case CLOCKWISE_90: - switch ((EnumDirection.EnumAxis) iblockdata.get(BlockPortal.AXIS)) { - case Z: - return (IBlockData) iblockdata.set(BlockPortal.AXIS, EnumDirection.EnumAxis.X); - case X: - return (IBlockData) iblockdata.set(BlockPortal.AXIS, EnumDirection.EnumAxis.Z); - default: - return iblockdata; - } - default: - return iblockdata; - } - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockPortal.AXIS); - } - - public ShapeDetector.ShapeDetectorCollection c(GeneratorAccess generatoraccess, BlockPosition blockposition) { - EnumDirection.EnumAxis enumdirection_enumaxis = EnumDirection.EnumAxis.Z; - BlockPortal.Shape blockportal_shape = new BlockPortal.Shape(generatoraccess, blockposition, EnumDirection.EnumAxis.X); - LoadingCache loadingcache = ShapeDetector.a(generatoraccess, true); - - if (!blockportal_shape.d()) { - enumdirection_enumaxis = EnumDirection.EnumAxis.X; - blockportal_shape = new BlockPortal.Shape(generatoraccess, 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().isAir()) { - ++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 GeneratorAccess a; - private final EnumDirection.EnumAxis b; - private final EnumDirection c; - private final EnumDirection d; - private int e; - @Nullable - private BlockPosition position; - private int height; - private int width; - java.util.List blocks = new java.util.ArrayList(); // CraftBukkit - add field - - public Shape(GeneratorAccess generatoraccess, BlockPosition blockposition, EnumDirection.EnumAxis enumdirection_enumaxis) { - this.a = generatoraccess; - 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(generatoraccess.getType(blockposition.down())); 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)) || this.a.getType(blockposition1.down()).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(); - // 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); - IBlockData iblockdata = this.a.getType(blockposition); - - if (!this.a(iblockdata)) { - break label56; - } - - Block block = iblockdata.getBlock(); - - if (block == Blocks.NETHER_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(CraftBlock.at(this.a, pos).getState()); - // 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(CraftBlock.at(this.a, pos).getState()); - // 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(CraftBlock.at(this.a, pos).getState()); - // 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(IBlockData iblockdata) { - Block block = iblockdata.getBlock(); - - return iblockdata.isAir() || block == Blocks.FIRE || block == Blocks.NETHER_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.getMinecraftWorld().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); - CraftBlockState state = CraftBlockState.getBlockState(this.a.getMinecraftWorld(), pos, 18); - state.setData((IBlockData) Blocks.NETHER_PORTAL.getBlockData().set(BlockPortal.AXIS, this.b)); - blocks.add(state); - } - } - - PortalCreateEvent event = new PortalCreateEvent(blocks, bworld, null, PortalCreateEvent.CreateReason.FIRE); - this.a.getMinecraftWorld().getMinecraftServer().server.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), (IBlockData) Blocks.NETHER_PORTAL.getBlockData().set(BlockPortal.AXIS, this.b), 18); - } - } - - return true; // CraftBukkit - } - - private boolean g() { - return this.e >= this.width * this.height; - } - - public boolean f() { - return this.d() && this.g(); - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockPosition.java b/src/main/java/net/minecraft/server/BlockPosition.java deleted file mode 100644 index 16f093040..000000000 --- a/src/main/java/net/minecraft/server/BlockPosition.java +++ /dev/null @@ -1,493 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.AbstractIterator; -import com.google.common.collect.Lists; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.types.DynamicOps; -import java.util.List; -import java.util.Spliterator.OfInt; -import java.util.Spliterators.AbstractSpliterator; -import java.util.function.Consumer; -import java.util.stream.IntStream; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; -import javax.annotation.concurrent.Immutable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -@Immutable -public class BlockPosition extends BaseBlockPosition implements MinecraftSerializable { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final BlockPosition ZERO = new BlockPosition(0, 0, 0); - private static final int c = 1 + MathHelper.e(MathHelper.c(30000000)); - private static final int d = BlockPosition.c; - private static final int f = 64 - BlockPosition.c - BlockPosition.d; - private static final long g = (1L << BlockPosition.c) - 1L; - private static final long h = (1L << BlockPosition.f) - 1L; - private static final long i = (1L << BlockPosition.d) - 1L; - private static final int j = BlockPosition.f; - private static final int k = BlockPosition.f + BlockPosition.d; - - 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.x, vec3d.y, vec3d.z); - } - - public BlockPosition(IPosition iposition) { - this(iposition.getX(), iposition.getY(), iposition.getZ()); - } - - public BlockPosition(BaseBlockPosition baseblockposition) { - this(baseblockposition.getX(), baseblockposition.getY(), baseblockposition.getZ()); - } - - public static BlockPosition a(Dynamic dynamic) { - OfInt ofint = dynamic.asIntStream().spliterator(); - int[] aint = new int[3]; - - if (ofint.tryAdvance((Consumer) (i) -> { // Paper - decomile fix - aint[0] = i; - }) && ofint.tryAdvance((Consumer) (i) -> { // Paper - decompile fix - aint[1] = i; - })) { - ofint.tryAdvance((Consumer) (i) -> { // Paper - decompile fix - aint[2] = i; - }); - } - - return new BlockPosition(aint[0], aint[1], aint[2]); - } - - @Override - public T a(DynamicOps dynamicops) { - return dynamicops.createIntList(IntStream.of(new int[]{this.getX(), this.getY(), this.getZ()})); - } - - public static long a(long i, EnumDirection enumdirection) { - return a(i, enumdirection.getAdjacentX(), enumdirection.getAdjacentY(), enumdirection.getAdjacentZ()); - } - - public static long a(long i, int j, int k, int l) { - return a(b(i) + j, c(i) + k, d(i) + l); - } - - public static int b(long i) { - return (int) (i << 64 - BlockPosition.k - BlockPosition.c >> 64 - BlockPosition.c); - } - - public static int c(long i) { - return (int) (i << 64 - BlockPosition.f >> 64 - BlockPosition.f); - } - - public static int d(long i) { - return (int) (i << 64 - BlockPosition.j - BlockPosition.d >> 64 - BlockPosition.d); - } - - public static BlockPosition fromLong(long i) { - return new BlockPosition(b(i), c(i), d(i)); - } - - public static long a(int i, int j, int k) { - long l = 0L; - - l |= ((long) i & BlockPosition.g) << BlockPosition.k; - l |= ((long) j & BlockPosition.h) << 0; - l |= ((long) k & BlockPosition.i) << BlockPosition.j; - return l; - } - - public static long f(long i) { - return i & -16L; - } - - public long asLong() { - return a(this.getX(), this.getY(), this.getZ()); - } - - public BlockPosition a(double d0, double d1, double d2) { - return d0 == 0.0D && d1 == 0.0D && d2 == 0.0D ? this : new BlockPosition((double) this.getX() + d0, (double) this.getY() + d1, (double) this.getZ() + d2); - } - - public BlockPosition add(int i, int j, int k) {return b(i, j, k);} // Paper - OBFHELPER - public BlockPosition b(int i, int j, int k) { - return i == 0 && j == 0 && k == 0 ? this : new BlockPosition(this.getX() + i, this.getY() + j, this.getZ() + k); - } - - public BlockPosition a(BaseBlockPosition baseblockposition) { - return this.b(baseblockposition.getX(), baseblockposition.getY(), baseblockposition.getZ()); - } - - public BlockPosition b(BaseBlockPosition baseblockposition) { - return this.b(-baseblockposition.getX(), -baseblockposition.getY(), -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) { - return i == 0 ? this : new BlockPosition(this.getX() + enumdirection.getAdjacentX() * i, this.getY() + enumdirection.getAdjacentY() * i, this.getZ() + enumdirection.getAdjacentZ() * i); - } - - public BlockPosition a(EnumBlockRotation enumblockrotation) { - switch (enumblockrotation) { - case NONE: - default: - return this; - case CLOCKWISE_90: - return new BlockPosition(-this.getZ(), this.getY(), this.getX()); - case CLOCKWISE_180: - return new BlockPosition(-this.getX(), this.getY(), -this.getZ()); - case COUNTERCLOCKWISE_90: - return new BlockPosition(this.getZ(), this.getY(), -this.getX()); - } - } - - @Override - public BlockPosition d(BaseBlockPosition baseblockposition) { - return new BlockPosition(this.getY() * baseblockposition.getZ() - this.getZ() * baseblockposition.getY(), this.getZ() * baseblockposition.getX() - this.getX() * baseblockposition.getZ(), this.getX() * baseblockposition.getY() - this.getY() * baseblockposition.getX()); - } - - @Deprecated // We'll replace this... - public BlockPosition asImmutable() { return immutableCopy(); } // Paper - OBFHELPER - public BlockPosition immutableCopy() { - return this; - } - - public static Iterable a(BlockPosition blockposition, BlockPosition blockposition1) { - return b(Math.min(blockposition.getX(), blockposition1.getX()), Math.min(blockposition.getY(), blockposition1.getY()), Math.min(blockposition.getZ(), blockposition1.getZ()), Math.max(blockposition.getX(), blockposition1.getX()), Math.max(blockposition.getY(), blockposition1.getY()), Math.max(blockposition.getZ(), blockposition1.getZ())); - } - - public static Stream b(BlockPosition blockposition, BlockPosition blockposition1) { - return a(Math.min(blockposition.getX(), blockposition1.getX()), Math.min(blockposition.getY(), blockposition1.getY()), Math.min(blockposition.getZ(), blockposition1.getZ()), Math.max(blockposition.getX(), blockposition1.getX()), Math.max(blockposition.getY(), blockposition1.getY()), Math.max(blockposition.getZ(), blockposition1.getZ())); - } - - public static Stream a(final int i, final int j, final int k, final int l, final int i1, final int j1) { - return StreamSupport.stream(new AbstractSpliterator((long) ((l - i + 1) * (i1 - j + 1) * (j1 - k + 1)), 64) { - final CursorPosition a = new CursorPosition(i, j, k, l, i1, j1); - final BlockPosition.MutableBlockPosition b = new BlockPosition.MutableBlockPosition(); - - public boolean tryAdvance(Consumer consumer) { - if (this.a.a()) { - consumer.accept(this.b.d(this.a.b(), this.a.c(), this.a.d())); - return true; - } else { - return false; - } - } - }, false); - } - - public static Iterable b(int i, int j, int k, int l, int i1, int j1) { - return () -> { - return new AbstractIterator() { - final CursorPosition a = new CursorPosition(i, j, k, l, i1, j1); - final BlockPosition.MutableBlockPosition b = new BlockPosition.MutableBlockPosition(); - - protected BlockPosition computeNext() { - return (BlockPosition) (this.a.a() ? this.b.d(this.a.b(), this.a.c(), this.a.d()) : (BlockPosition) this.endOfData()); - } - }; - }; - } - - public static final class PooledBlockPosition extends BlockPosition.MutableBlockPosition implements AutoCloseable { - - private boolean f; - private static final List g = Lists.newArrayList(); - - private PooledBlockPosition(int i, int j, int k) { - super(i, j, k); - } - - public static BlockPosition.PooledBlockPosition r() { - return f(0, 0, 0); - } - - public static BlockPosition.PooledBlockPosition b(Entity entity) { - return d(entity.locX, entity.locY, entity.locZ); - } - - public static BlockPosition.PooledBlockPosition d(double d0, double d1, double d2) { - return f(MathHelper.floor(d0), MathHelper.floor(d1), MathHelper.floor(d2)); - } - - public static BlockPosition.PooledBlockPosition f(int i, int j, int k) { - synchronized (BlockPosition.PooledBlockPosition.g) { - if (!BlockPosition.PooledBlockPosition.g.isEmpty()) { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = (BlockPosition.PooledBlockPosition) BlockPosition.PooledBlockPosition.g.remove(BlockPosition.PooledBlockPosition.g.size() - 1); - - if (blockposition_pooledblockposition != null && blockposition_pooledblockposition.f) { - blockposition_pooledblockposition.f = false; - blockposition_pooledblockposition.d(i, j, k); - return blockposition_pooledblockposition; - } - } - } - - return new BlockPosition.PooledBlockPosition(i, j, k); - } - - @Override - public BlockPosition.PooledBlockPosition d(int i, int j, int k) { - return (BlockPosition.PooledBlockPosition) super.d(i, j, k); - } - - @Override - public BlockPosition.PooledBlockPosition a(Entity entity) { - return (BlockPosition.PooledBlockPosition) super.a(entity); - } - - @Override - public BlockPosition.PooledBlockPosition c(double d0, double d1, double d2) { - return (BlockPosition.PooledBlockPosition) super.c(d0, d1, d2); - } - - @Override - public BlockPosition.PooledBlockPosition g(BaseBlockPosition baseblockposition) { - return (BlockPosition.PooledBlockPosition) super.g(baseblockposition); - } - - @Override - public BlockPosition.PooledBlockPosition c(EnumDirection enumdirection) { - return (BlockPosition.PooledBlockPosition) super.c(enumdirection); - } - - @Override - public BlockPosition.PooledBlockPosition c(EnumDirection enumdirection, int i) { - return (BlockPosition.PooledBlockPosition) super.c(enumdirection, i); - } - - @Override - public BlockPosition.PooledBlockPosition e(int i, int j, int k) { - return (BlockPosition.PooledBlockPosition) super.e(i, j, k); - } - - public void close() { - synchronized (BlockPosition.PooledBlockPosition.g) { - if (BlockPosition.PooledBlockPosition.g.size() < 100) { - BlockPosition.PooledBlockPosition.g.add(this); - } - - this.f = true; - } - } - } - - public static class MutableBlockPosition extends BlockPosition { - // Paper start - comment out - /* - protected int b; - protected int c; - protected int d; - - @Override - public boolean isValidLocation() { - return b >= -30000000 && d >= -30000000 && b < 30000000 && d < 30000000 && c >= 0 && c < 256; - } - @Override - public boolean isInvalidYLocation() { - return c < 0 || c >= 256; - } - */ - // Paper end - - public MutableBlockPosition() { - this(0, 0, 0); - } - - public MutableBlockPosition(BlockPosition blockposition) { - this(blockposition.getX(), blockposition.getY(), blockposition.getZ()); - } - - public MutableBlockPosition(int i, int j, int k) { - // Paper start - super(i, j, k); - /* - this.b = i; - this.c = j; - this.d = k;*/ - // Paper end - } - - public MutableBlockPosition(double d0, double d1, double d2) { - this(MathHelper.floor(d0), MathHelper.floor(d1), MathHelper.floor(d2)); - } - - @Override - public BlockPosition a(double d0, double d1, double d2) { - return super.a(d0, d1, d2).immutableCopy(); - } - - @Override - public BlockPosition b(int i, int j, int k) { - return super.b(i, j, k).immutableCopy(); - } - - @Override - public BlockPosition shift(EnumDirection enumdirection, int i) { - return super.shift(enumdirection, i).immutableCopy(); - } - - @Override - public BlockPosition a(EnumBlockRotation enumblockrotation) { - return super.a(enumblockrotation).immutableCopy(); - } - - - /* - // Paper start - use parent getters - @Override - public int getX() { - return this.b; - } - - @Override - public int getY() { - return this.c; - } - - @Override - public int getZ() { - return this.d; - }*/ - // Paper end - - public BlockPosition.MutableBlockPosition setValues(int i, int j, int k) { return d(i, j, k);} // Paper - OBFHELPER - public BlockPosition.MutableBlockPosition d(int i, int j, int k) { - // Paper start - use xyz - this.x = i; - this.y = j; - this.z = k; - // Paper end - return this; - } - - public BlockPosition.MutableBlockPosition a(Entity entity) { - return this.c(entity.locX, entity.locY, entity.locZ); - } - - public BlockPosition.MutableBlockPosition setValues(double d0, double d1, double d2) { return c(d0, d1, d2);} // Paper - OBFHELPER - public BlockPosition.MutableBlockPosition c(double d0, double d1, double d2) { - return this.d(MathHelper.floor(d0), MathHelper.floor(d1), MathHelper.floor(d2)); - } - - public BlockPosition.MutableBlockPosition g(BaseBlockPosition baseblockposition) { - return this.d(baseblockposition.getX(), baseblockposition.getY(), baseblockposition.getZ()); - } - - public BlockPosition.MutableBlockPosition g(long i) { - return this.d(b(i), c(i), d(i)); - } - - public BlockPosition.MutableBlockPosition a(EnumAxisCycle enumaxiscycle, int i, int j, int k) { - return this.d(enumaxiscycle.a(i, j, k, EnumDirection.EnumAxis.X), enumaxiscycle.a(i, j, k, EnumDirection.EnumAxis.Y), enumaxiscycle.a(i, j, k, EnumDirection.EnumAxis.Z)); - } - - public BlockPosition.MutableBlockPosition c(EnumDirection enumdirection) { - return this.c(enumdirection, 1); - } - - public BlockPosition.MutableBlockPosition c(EnumDirection enumdirection, int i) { - return this.d(this.x + enumdirection.getAdjacentX() * i, this.y + enumdirection.getAdjacentY() * i, this.z + enumdirection.getAdjacentZ() * i); - } - - public BlockPosition.MutableBlockPosition e(int i, int j, int k) { - return this.d(this.x + i, this.y + j, this.z + k); - } - - public void o(int i) { - this.x = i; // Paper change to x - } - - public void p(int i) { - this.y = i; // Paper change to y - } - - public void q(int i) { - this.z = i; // Paper change to z - } - - @Override - public BlockPosition immutableCopy() { - return new BlockPosition(this); - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockPoweredRail.java b/src/main/java/net/minecraft/server/BlockPoweredRail.java deleted file mode 100644 index 8799dcdab..000000000 --- a/src/main/java/net/minecraft/server/BlockPoweredRail.java +++ /dev/null @@ -1,251 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockPoweredRail extends BlockMinecartTrackAbstract { - - public static final BlockStateEnum SHAPE = BlockProperties.X; - public static final BlockStateBoolean POWERED = BlockProperties.w; - - protected BlockPoweredRail(Block.Info block_info) { - super(true, block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_SOUTH)).set(BlockPoweredRail.POWERED, 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; - BlockPropertyTrackPosition blockpropertytrackposition = (BlockPropertyTrackPosition) iblockdata.get(BlockPoweredRail.SHAPE); - - switch (blockpropertytrackposition) { - case NORTH_SOUTH: - if (flag) { - ++l; - } else { - --l; - } - break; - case EAST_WEST: - if (flag) { - --j; - } else { - ++j; - } - break; - case ASCENDING_EAST: - if (flag) { - --j; - } else { - ++j; - ++k; - flag1 = false; - } - - blockpropertytrackposition = BlockPropertyTrackPosition.EAST_WEST; - break; - case ASCENDING_WEST: - if (flag) { - --j; - ++k; - flag1 = false; - } else { - ++j; - } - - blockpropertytrackposition = BlockPropertyTrackPosition.EAST_WEST; - break; - case ASCENDING_NORTH: - if (flag) { - ++l; - } else { - --l; - ++k; - flag1 = false; - } - - blockpropertytrackposition = BlockPropertyTrackPosition.NORTH_SOUTH; - break; - case ASCENDING_SOUTH: - if (flag) { - ++l; - ++k; - flag1 = false; - } else { - --l; - } - - blockpropertytrackposition = BlockPropertyTrackPosition.NORTH_SOUTH; - } - - return this.a(world, new BlockPosition(j, k, l), flag, i, blockpropertytrackposition) ? true : flag1 && this.a(world, new BlockPosition(j, k - 1, l), flag, i, blockpropertytrackposition); - } - } - - protected boolean a(World world, BlockPosition blockposition, boolean flag, int i, BlockPropertyTrackPosition blockpropertytrackposition) { - IBlockData iblockdata = world.getType(blockposition); - - if (iblockdata.getBlock() != this) { - return false; - } else { - BlockPropertyTrackPosition blockpropertytrackposition1 = (BlockPropertyTrackPosition) iblockdata.get(BlockPoweredRail.SHAPE); - - return blockpropertytrackposition == BlockPropertyTrackPosition.EAST_WEST && (blockpropertytrackposition1 == BlockPropertyTrackPosition.NORTH_SOUTH || blockpropertytrackposition1 == BlockPropertyTrackPosition.ASCENDING_NORTH || blockpropertytrackposition1 == BlockPropertyTrackPosition.ASCENDING_SOUTH) ? false : (blockpropertytrackposition == BlockPropertyTrackPosition.NORTH_SOUTH && (blockpropertytrackposition1 == BlockPropertyTrackPosition.EAST_WEST || blockpropertytrackposition1 == BlockPropertyTrackPosition.ASCENDING_EAST || blockpropertytrackposition1 == BlockPropertyTrackPosition.ASCENDING_WEST) ? false : ((Boolean) iblockdata.get(BlockPoweredRail.POWERED) ? (world.isBlockIndirectlyPowered(blockposition) ? true : this.a(world, blockposition, iblockdata, flag, i + 1)) : false)); - } - } - - @Override - protected void a(IBlockData iblockdata, World world, BlockPosition blockposition, Block block) { - boolean flag = (Boolean) 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 = flag ? 15 : 0; - int newPower = CraftEventFactory.callRedstoneChange(world, blockposition, power, 15 - power).getNewCurrent(); - if (newPower == power) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockPoweredRail.POWERED, flag1), 3); - world.applyPhysics(blockposition.down(), this); - if (((BlockPropertyTrackPosition) iblockdata.get(BlockPoweredRail.SHAPE)).c()) { - world.applyPhysics(blockposition.up(), this); - } - } - - } - - @Override - public IBlockState e() { - return BlockPoweredRail.SHAPE; - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - switch (enumblockrotation) { - case CLOCKWISE_180: - switch ((BlockPropertyTrackPosition) iblockdata.get(BlockPoweredRail.SHAPE)) { - case ASCENDING_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_WEST); - case ASCENDING_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_EAST); - case ASCENDING_NORTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_SOUTH); - case ASCENDING_SOUTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_NORTH); - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - } - case COUNTERCLOCKWISE_90: - switch ((BlockPropertyTrackPosition) iblockdata.get(BlockPoweredRail.SHAPE)) { - case NORTH_SOUTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.EAST_WEST); - case EAST_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_SOUTH); - case ASCENDING_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_NORTH); - case ASCENDING_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_SOUTH); - case ASCENDING_NORTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_WEST); - case ASCENDING_SOUTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_EAST); - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - } - case CLOCKWISE_90: - switch ((BlockPropertyTrackPosition) iblockdata.get(BlockPoweredRail.SHAPE)) { - case NORTH_SOUTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.EAST_WEST); - case EAST_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_SOUTH); - case ASCENDING_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_SOUTH); - case ASCENDING_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_NORTH); - case ASCENDING_NORTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_EAST); - case ASCENDING_SOUTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_WEST); - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - } - default: - return iblockdata; - } - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - BlockPropertyTrackPosition blockpropertytrackposition = (BlockPropertyTrackPosition) iblockdata.get(BlockPoweredRail.SHAPE); - - switch (enumblockmirror) { - case LEFT_RIGHT: - switch (blockpropertytrackposition) { - case ASCENDING_NORTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_SOUTH); - case ASCENDING_SOUTH: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_NORTH); - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - default: - return super.a(iblockdata, enumblockmirror); - } - case FRONT_BACK: - switch (blockpropertytrackposition) { - case ASCENDING_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_WEST); - case ASCENDING_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.ASCENDING_EAST); - case ASCENDING_NORTH: - case ASCENDING_SOUTH: - default: - break; - case SOUTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_WEST); - case SOUTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.SOUTH_EAST); - case NORTH_WEST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_EAST); - case NORTH_EAST: - return (IBlockData) iblockdata.set(BlockPoweredRail.SHAPE, BlockPropertyTrackPosition.NORTH_WEST); - } - } - - return super.a(iblockdata, enumblockmirror); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockPoweredRail.SHAPE, BlockPoweredRail.POWERED); - } -} diff --git a/src/main/java/net/minecraft/server/BlockPressurePlateAbstract.java b/src/main/java/net/minecraft/server/BlockPressurePlateAbstract.java deleted file mode 100644 index 90cdcaf73..000000000 --- a/src/main/java/net/minecraft/server/BlockPressurePlateAbstract.java +++ /dev/null @@ -1,151 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public abstract class BlockPressurePlateAbstract extends Block { - - protected static final VoxelShape a = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 0.5D, 15.0D); - protected static final VoxelShape b = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 1.0D, 15.0D); - protected static final AxisAlignedBB c = new AxisAlignedBB(0.125D, 0.0D, 0.125D, 0.875D, 0.25D, 0.875D); - - protected BlockPressurePlateAbstract(Block.Info block_info) { - super(block_info); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return this.getPower(iblockdata) > 0 ? BlockPressurePlateAbstract.a : BlockPressurePlateAbstract.b; - } - - @Override - public int a(IWorldReader iworldreader) { - return 20; - } - - @Override - public boolean S_() { - return true; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return enumdirection == EnumDirection.DOWN && !iblockdata.canPlace(generatoraccess, blockposition) ? Blocks.AIR.getBlockData() : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - - return c((IBlockAccess) iworldreader, blockposition1) || a(iworldreader, blockposition1, EnumDirection.UP); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.isClientSide) { - int i = this.getPower(iblockdata); - - if (i > 0) { - this.a(world, blockposition, iblockdata, i); - } - - } - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (!world.isClientSide) { - int i = this.getPower(iblockdata); - - if (i == 0) { - this.a(world, blockposition, iblockdata, i); - } - - } - } - - protected void a(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { - int j = this.b(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 iblockdata1 = this.a(iblockdata, j); - - world.setTypeAndData(blockposition, iblockdata1, 2); - this.a(world, blockposition); - world.b(blockposition, iblockdata, iblockdata1); - } - - if (!flag1 && flag) { - this.b((GeneratorAccess) world, blockposition); - } else if (flag1 && !flag) { - this.a((GeneratorAccess) world, blockposition); - } - - if (flag1) { - world.getBlockTickList().a(new BlockPosition(blockposition), this, this.a((IWorldReader) world)); - } - - } - - protected abstract void a(GeneratorAccess generatoraccess, BlockPosition blockposition); - - protected abstract void b(GeneratorAccess generatoraccess, BlockPosition blockposition); - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (!flag && iblockdata.getBlock() != iblockdata1.getBlock()) { - if (this.getPower(iblockdata) > 0) { - this.a(world, blockposition); - } - - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - } - } - - protected void a(World world, BlockPosition blockposition) { - world.applyPhysics(blockposition, this); - world.applyPhysics(blockposition.down(), this); - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return this.getPower(iblockdata); - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return enumdirection == EnumDirection.UP ? this.getPower(iblockdata) : 0; - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - @Override - public EnumPistonReaction getPushReaction(IBlockData iblockdata) { - return EnumPistonReaction.DESTROY; - } - - protected abstract int b(World world, BlockPosition blockposition); - - protected abstract int getPower(IBlockData iblockdata); - - protected abstract IBlockData a(IBlockData iblockdata, int i); -} diff --git a/src/main/java/net/minecraft/server/BlockPressurePlateBinary.java b/src/main/java/net/minecraft/server/BlockPressurePlateBinary.java deleted file mode 100644 index e063373e8..000000000 --- a/src/main/java/net/minecraft/server/BlockPressurePlateBinary.java +++ /dev/null @@ -1,111 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; - -import org.bukkit.event.entity.EntityInteractEvent; // CraftBukkit - -public class BlockPressurePlateBinary extends BlockPressurePlateAbstract { - - public static final BlockStateBoolean POWERED = BlockProperties.w; - private final BlockPressurePlateBinary.EnumMobType e; - - protected BlockPressurePlateBinary(BlockPressurePlateBinary.EnumMobType blockpressureplatebinary_enummobtype, Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockPressurePlateBinary.POWERED, false)); - this.e = blockpressureplatebinary_enummobtype; - } - - @Override - protected int getPower(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockPressurePlateBinary.POWERED) ? 15 : 0; - } - - @Override - protected IBlockData a(IBlockData iblockdata, int i) { - return (IBlockData) iblockdata.set(BlockPressurePlateBinary.POWERED, i > 0); - } - - @Override - protected void a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - if (this.material == Material.WOOD) { - generatoraccess.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_WOODEN_PRESSURE_PLATE_CLICK_ON, SoundCategory.BLOCKS, 0.3F, 0.8F); - } else { - generatoraccess.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_STONE_PRESSURE_PLATE_CLICK_ON, SoundCategory.BLOCKS, 0.3F, 0.6F); - } - - } - - @Override - protected void b(GeneratorAccess generatoraccess, BlockPosition blockposition) { - if (this.material == Material.WOOD) { - generatoraccess.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_WOODEN_PRESSURE_PLATE_CLICK_OFF, SoundCategory.BLOCKS, 0.3F, 0.7F); - } else { - generatoraccess.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_STONE_PRESSURE_PLATE_CLICK_OFF, SoundCategory.BLOCKS, 0.3F, 0.5F); - } - - } - - @Override - protected int b(World world, BlockPosition blockposition) { - AxisAlignedBB axisalignedbb = BlockPressurePlateBinary.c.a(blockposition); - List list; - - switch (this.e) { - case EVERYTHING: - list = world.getEntities((Entity) null, axisalignedbb); - break; - case MOBS: - list = world.a(EntityLiving.class, axisalignedbb); - break; - default: - return 0; - } - - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - // CraftBukkit start - Call interact event when turning on a pressure plate - if (this.getPower(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, 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.isIgnoreBlockTrigger()) { - return 15; - } - } - } - - return 0; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockPressurePlateBinary.POWERED); - } - - public static enum EnumMobType { - - EVERYTHING, MOBS; - - private EnumMobType() {} - } -} diff --git a/src/main/java/net/minecraft/server/BlockPressurePlateWeighted.java b/src/main/java/net/minecraft/server/BlockPressurePlateWeighted.java deleted file mode 100644 index 867d096a4..000000000 --- a/src/main/java/net/minecraft/server/BlockPressurePlateWeighted.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.event.entity.EntityInteractEvent; // CraftBukkit - -public class BlockPressurePlateWeighted extends BlockPressurePlateAbstract { - - public static final BlockStateInteger POWER = BlockProperties.as; - private final int weight; - - protected BlockPressurePlateWeighted(int i, Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockPressurePlateWeighted.POWER, 0)); - this.weight = i; - } - - @Override - protected int b(World world, BlockPosition blockposition) { - // CraftBukkit start - // int i = Math.min(world.a(Entity.class, BlockPressurePlateWeighted.c.a(blockposition)).size(), this.weight); - int i = 0; - java.util.Iterator iterator = world.a(Entity.class, BlockPressurePlateWeighted.c.a(blockposition)).iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - 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, 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) Math.min(this.weight, i) / (float) this.weight; - - return MathHelper.f(f * 15.0F); - } else { - return 0; - } - } - - @Override - protected void a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - generatoraccess.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_METAL_PRESSURE_PLATE_CLICK_ON, SoundCategory.BLOCKS, 0.3F, 0.90000004F); - } - - @Override - protected void b(GeneratorAccess generatoraccess, BlockPosition blockposition) { - generatoraccess.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_METAL_PRESSURE_PLATE_CLICK_OFF, SoundCategory.BLOCKS, 0.3F, 0.75F); - } - - @Override - protected int getPower(IBlockData iblockdata) { - return (Integer) iblockdata.get(BlockPressurePlateWeighted.POWER); - } - - @Override - protected IBlockData a(IBlockData iblockdata, int i) { - return (IBlockData) iblockdata.set(BlockPressurePlateWeighted.POWER, i); - } - - @Override - public int a(IWorldReader iworldreader) { - return 10; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockPressurePlateWeighted.POWER); - } -} diff --git a/src/main/java/net/minecraft/server/BlockPumpkinCarved.java b/src/main/java/net/minecraft/server/BlockPumpkinCarved.java deleted file mode 100644 index 27096a5cf..000000000 --- a/src/main/java/net/minecraft/server/BlockPumpkinCarved.java +++ /dev/null @@ -1,171 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.util.BlockStateListPopulator; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; -// CraftBukkit end - -public class BlockPumpkinCarved extends BlockFacingHorizontal { - - public static final BlockStateDirection a = BlockFacingHorizontal.FACING; - @Nullable - private ShapeDetector b; - @Nullable - private ShapeDetector c; - @Nullable - private ShapeDetector d; - @Nullable - private ShapeDetector e; - private static final Predicate f = (iblockdata) -> { - return iblockdata != null && (iblockdata.getBlock() == Blocks.CARVED_PUMPKIN || iblockdata.getBlock() == Blocks.JACK_O_LANTERN); - }; - - protected BlockPumpkinCarved(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockPumpkinCarved.a, EnumDirection.NORTH)); - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata1.getBlock() != iblockdata.getBlock()) { - this.a(world, blockposition); - } - } - - public boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - return this.d().a(iworldreader, blockposition) != null || this.f().a(iworldreader, blockposition) != null; - } - - private void a(World world, BlockPosition blockposition) { - ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = this.getSnowmanShape().a(world, blockposition); - int i; - Iterator iterator; - EntityPlayer entityplayer; - int j; - - BlockStateListPopulator blockList = new BlockStateListPopulator(world); // CraftBukkit - Use BlockStateListPopulator - if (shapedetector_shapedetectorcollection != null) { - for (i = 0; i < this.getSnowmanShape().b(); ++i) { - ShapeDetectorBlock shapedetectorblock = shapedetector_shapedetectorcollection.a(0, i, 0); - - blockList.setTypeAndData(shapedetectorblock.getPosition(), Blocks.AIR.getBlockData(), 2); // CraftBukkit - // world.triggerEffect(2001, shapedetectorblock.getPosition(), Block.getCombinedId(shapedetectorblock.a())); // CraftBukkit - } - - EntitySnowman entitysnowman = (EntitySnowman) EntityTypes.SNOW_GOLEM.a(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)) { - return; - } - for (BlockPosition pos : blockList.getBlocks()) { - world.triggerEffect(2001, pos, Block.getCombinedId(world.getType(pos))); - } - blockList.updateList(); - // CraftBukkit end - iterator = world.a(EntityPlayer.class, entitysnowman.getBoundingBox().g(5.0D)).iterator(); - - while (iterator.hasNext()) { - entityplayer = (EntityPlayer) iterator.next(); - CriterionTriggers.n.a(entityplayer, (Entity) entitysnowman); - } - - for (j = 0; j < this.getSnowmanShape().b(); ++j) { - ShapeDetectorBlock shapedetectorblock1 = shapedetector_shapedetectorcollection.a(0, j, 0); - - world.update(shapedetectorblock1.getPosition(), Blocks.AIR); - } - } else { - shapedetector_shapedetectorcollection = this.getIronGolemShape().a(world, blockposition); - if (shapedetector_shapedetectorcollection != null) { - for (i = 0; i < this.getIronGolemShape().c(); ++i) { - for (int k = 0; k < this.getIronGolemShape().b(); ++k) { - ShapeDetectorBlock shapedetectorblock2 = shapedetector_shapedetectorcollection.a(i, k, 0); - - blockList.setTypeAndData(shapedetectorblock2.getPosition(), Blocks.AIR.getBlockData(), 2); // CraftBukkit - // world.triggerEffect(2001, shapedetectorblock2.getPosition(), Block.getCombinedId(shapedetectorblock2.a())); // CraftBukkit - } - } - - BlockPosition blockposition2 = shapedetector_shapedetectorcollection.a(1, 2, 0).getPosition(); - EntityIronGolem entityirongolem = (EntityIronGolem) EntityTypes.IRON_GOLEM.a(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)) { - return; - } - for (BlockPosition pos : blockList.getBlocks()) { - world.triggerEffect(2001, pos, Block.getCombinedId(world.getType(pos))); - } - blockList.updateList(); - // CraftBukkit end - iterator = world.a(EntityPlayer.class, entityirongolem.getBoundingBox().g(5.0D)).iterator(); - - while (iterator.hasNext()) { - entityplayer = (EntityPlayer) iterator.next(); - CriterionTriggers.n.a(entityplayer, (Entity) entityirongolem); - } - - for (j = 0; j < this.getIronGolemShape().c(); ++j) { - for (int l = 0; l < this.getIronGolemShape().b(); ++l) { - ShapeDetectorBlock shapedetectorblock3 = shapedetector_shapedetectorcollection.a(j, l, 0); - - world.update(shapedetectorblock3.getPosition(), Blocks.AIR); - } - } - } - } - - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return (IBlockData) this.getBlockData().set(BlockPumpkinCarved.a, blockactioncontext.f().opposite()); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockPumpkinCarved.a); - } - - private ShapeDetector d() { - if (this.b == null) { - this.b = ShapeDetectorBuilder.a().a(" ", "#", "#").a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.SNOW_BLOCK))).b(); - } - - return this.b; - } - - private ShapeDetector getSnowmanShape() { - if (this.c == null) { - this.c = ShapeDetectorBuilder.a().a("^", "#", "#").a('^', ShapeDetectorBlock.a(BlockPumpkinCarved.f)).a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.SNOW_BLOCK))).b(); - } - - return this.c; - } - - private ShapeDetector f() { - if (this.d == null) { - this.d = ShapeDetectorBuilder.a().a("~ ~", "###", "~#~").a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.IRON_BLOCK))).a('~', ShapeDetectorBlock.a(MaterialPredicate.a(Material.AIR))).b(); - } - - return this.d; - } - - private ShapeDetector getIronGolemShape() { - if (this.e == null) { - this.e = ShapeDetectorBuilder.a().a("~^~", "###", "~#~").a('^', ShapeDetectorBlock.a(BlockPumpkinCarved.f)).a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.IRON_BLOCK))).a('~', ShapeDetectorBlock.a(MaterialPredicate.a(Material.AIR))).b(); - } - - return this.e; - } -} diff --git a/src/main/java/net/minecraft/server/BlockRedstoneComparator.java b/src/main/java/net/minecraft/server/BlockRedstoneComparator.java deleted file mode 100644 index 6ff9c8744..000000000 --- a/src/main/java/net/minecraft/server/BlockRedstoneComparator.java +++ /dev/null @@ -1,167 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import java.util.Random; -import javax.annotation.Nullable; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockRedstoneComparator extends BlockDiodeAbstract implements ITileEntity { - - public static final BlockStateEnum MODE = BlockProperties.ay; - - public BlockRedstoneComparator(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockRedstoneComparator.FACING, EnumDirection.NORTH)).set(BlockRedstoneComparator.c, false)).set(BlockRedstoneComparator.MODE, BlockPropertyComparatorMode.COMPARE)); - } - - @Override - protected int j(IBlockData iblockdata) { - return 2; - } - - @Override - protected int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { - TileEntity tileentity = iblockaccess.getTileEntity(blockposition); - - return tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).d() : 0; - } - - private int e(World world, BlockPosition blockposition, IBlockData iblockdata) { - return iblockdata.get(BlockRedstoneComparator.MODE) == BlockPropertyComparatorMode.SUBTRACT ? Math.max(this.b(world, blockposition, iblockdata) - this.b((IWorldReader) world, blockposition, iblockdata), 0) : this.b(world, blockposition, iblockdata); - } - - @Override - protected boolean a(World world, BlockPosition blockposition, IBlockData iblockdata) { - int i = this.b(world, blockposition, iblockdata); - - return i >= 15 ? true : (i == 0 ? false : i >= this.b((IWorldReader) world, blockposition, iblockdata)); - } - - @Override - protected int b(World world, BlockPosition blockposition, IBlockData iblockdata) { - int i = super.b(world, blockposition, iblockdata); - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockRedstoneComparator.FACING); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - IBlockData iblockdata1 = world.getType(blockposition1); - - if (iblockdata1.isComplexRedstone()) { - i = iblockdata1.a(world, blockposition1); - } else if (i < 15 && iblockdata1.isOccluding(world, blockposition1)) { - blockposition1 = blockposition1.shift(enumdirection); - iblockdata1 = world.getType(blockposition1); - if (iblockdata1.isComplexRedstone()) { - i = iblockdata1.a(world, blockposition1); - } else if (iblockdata1.isAir()) { - EntityItemFrame entityitemframe = this.a(world, enumdirection, blockposition1); - - if (entityitemframe != null) { - i = entityitemframe.q(); - } - } - } - - return i; - } - - @Nullable - private EntityItemFrame a(World world, EnumDirection enumdirection, BlockPosition blockposition) { - // CraftBukkit - decompile error - List list = world.a(EntityItemFrame.class, new AxisAlignedBB((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), (double) (blockposition.getX() + 1), (double) (blockposition.getY() + 1), (double) (blockposition.getZ() + 1)), (java.util.function.Predicate) (entityitemframe) -> { - return entityitemframe != null && entityitemframe.getDirection() == enumdirection; - }); - - return list.size() == 1 ? (EntityItemFrame) list.get(0) : null; - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (!entityhuman.abilities.mayBuild) { - return false; - } else { - iblockdata = (IBlockData) iblockdata.a((IBlockState) BlockRedstoneComparator.MODE); - float f = iblockdata.get(BlockRedstoneComparator.MODE) == BlockPropertyComparatorMode.SUBTRACT ? 0.55F : 0.5F; - - world.playSound(entityhuman, blockposition, SoundEffects.BLOCK_COMPARATOR_CLICK, SoundCategory.BLOCKS, 0.3F, f); - world.setTypeAndData(blockposition, iblockdata, 2); - this.f(world, blockposition, iblockdata); - return true; - } - } - - @Override - protected void c(World world, BlockPosition blockposition, IBlockData iblockdata) { - if (!world.getBlockTickList().b(blockposition, this)) { - int i = this.e(world, blockposition, iblockdata); - TileEntity tileentity = world.getTileEntity(blockposition); - int j = tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).d() : 0; - - if (i != j || (Boolean) iblockdata.get(BlockRedstoneComparator.c) != this.a(world, blockposition, iblockdata)) { - TickListPriority ticklistpriority = this.c((IBlockAccess) world, blockposition, iblockdata) ? TickListPriority.HIGH : TickListPriority.NORMAL; - - world.getBlockTickList().a(blockposition, this, 2, ticklistpriority); - } - - } - } - - private void f(World world, BlockPosition blockposition, IBlockData iblockdata) { - int i = this.e(world, blockposition, iblockdata); - TileEntity tileentity = world.getTileEntity(blockposition); - int j = 0; - - if (tileentity instanceof TileEntityComparator) { - TileEntityComparator tileentitycomparator = (TileEntityComparator) tileentity; - - j = tileentitycomparator.d(); - tileentitycomparator.a(i); - } - - if (j != i || iblockdata.get(BlockRedstoneComparator.MODE) == BlockPropertyComparatorMode.COMPARE) { - boolean flag = this.a(world, blockposition, iblockdata); - boolean flag1 = (Boolean) iblockdata.get(BlockRedstoneComparator.c); - - if (flag1 && !flag) { - // CraftBukkit start - if (CraftEventFactory.callRedstoneChange(world, blockposition, 15, 0).getNewCurrent() != 0) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockRedstoneComparator.c, false), 2); - } else if (!flag1 && flag) { - // CraftBukkit start - if (CraftEventFactory.callRedstoneChange(world, blockposition, 0, 15).getNewCurrent() != 15) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockRedstoneComparator.c, true), 2); - } - - this.d(world, blockposition, iblockdata); - } - - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - this.f(world, blockposition, iblockdata); - } - - @Override - public boolean a(IBlockData iblockdata, World world, BlockPosition blockposition, int i, int j) { - super.a(iblockdata, world, blockposition, i, j); - TileEntity tileentity = world.getTileEntity(blockposition); - - return tileentity != null && tileentity.setProperty(i, j); - } - - @Override - public TileEntity createTile(IBlockAccess iblockaccess) { - return new TileEntityComparator(); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockRedstoneComparator.FACING, BlockRedstoneComparator.MODE, BlockRedstoneComparator.c); - } -} diff --git a/src/main/java/net/minecraft/server/BlockRedstoneLamp.java b/src/main/java/net/minecraft/server/BlockRedstoneLamp.java deleted file mode 100644 index 907680b7d..000000000 --- a/src/main/java/net/minecraft/server/BlockRedstoneLamp.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockRedstoneLamp extends Block { - - public static final BlockStateBoolean a = BlockRedstoneTorch.LIT; - - public BlockRedstoneLamp(Block.Info block_info) { - super(block_info); - this.o((IBlockData) this.getBlockData().set(BlockRedstoneLamp.a, false)); - } - - @Override - public int a(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockRedstoneLamp.a) ? super.a(iblockdata) : 0; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - super.onPlace(iblockdata, world, blockposition, iblockdata1, flag); - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return (IBlockData) this.getBlockData().set(BlockRedstoneLamp.a, blockactioncontext.getWorld().isBlockIndirectlyPowered(blockactioncontext.getClickPosition())); - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (!world.isClientSide) { - boolean flag1 = (Boolean) iblockdata.get(BlockRedstoneLamp.a); - - if (flag1 != world.isBlockIndirectlyPowered(blockposition)) { - if (flag1) { - world.getBlockTickList().a(blockposition, this, 4); - } else { - // CraftBukkit start - if (CraftEventFactory.callRedstoneChange(world, blockposition, 0, 15).getNewCurrent() != 15) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.a((IBlockState) BlockRedstoneLamp.a), 2); - } - } - - } - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.isClientSide) { - if ((Boolean) iblockdata.get(BlockRedstoneLamp.a) && !world.isBlockIndirectlyPowered(blockposition)) { - // CraftBukkit start - if (CraftEventFactory.callRedstoneChange(world, blockposition, 15, 0).getNewCurrent() != 0) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.a((IBlockState) BlockRedstoneLamp.a), 2); - } - - } - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockRedstoneLamp.a); - } -} diff --git a/src/main/java/net/minecraft/server/BlockRedstoneOre.java b/src/main/java/net/minecraft/server/BlockRedstoneOre.java deleted file mode 100644 index 08eea0fe5..000000000 --- a/src/main/java/net/minecraft/server/BlockRedstoneOre.java +++ /dev/null @@ -1,134 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityInteractEvent; -// CraftBukkit end - -public class BlockRedstoneOre extends Block { - - public static final BlockStateBoolean a = BlockRedstoneTorch.LIT; - - public BlockRedstoneOre(Block.Info block_info) { - super(block_info); - this.o((IBlockData) this.getBlockData().set(BlockRedstoneOre.a, false)); - } - - @Override - public int a(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockRedstoneOre.a) ? super.a(iblockdata) : 0; - } - - @Override - public void attack(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman) { - interact(iblockdata, world, blockposition, entityhuman); // CraftBukkit - add entityhuman - super.attack(iblockdata, world, blockposition, entityhuman); - } - - @Override - public void stepOn(World world, BlockPosition blockposition, Entity entity) { - // CraftBukkit start - // interact(world.getType(blockposition), world, blockposition); - // super.stepOn(world, blockposition, entity); - 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, null); - if (!event.isCancelled()) { - interact(world.getType(blockposition), world, blockposition, entity); // add entity - super.stepOn(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()) { - interact(world.getType(blockposition), world, blockposition, entity); // add entity - super.stepOn(world, blockposition, entity); - } - } - // CraftBukkit end - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - interact(iblockdata, world, blockposition, entityhuman); // CraftBukkit - add entityhuman - return super.interact(iblockdata, world, blockposition, entityhuman, enumhand, movingobjectpositionblock); - } - - private static void interact(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { // CraftBukkit - add Entity - playEffect(world, blockposition); - if (!(Boolean) iblockdata.get(BlockRedstoneOre.a)) { - // CraftBukkit start - if (CraftEventFactory.callEntityChangeBlockEvent(entity, blockposition, iblockdata.set(BlockRedstoneOre.a, true)).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockRedstoneOre.a, true), 3); - } - - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if ((Boolean) iblockdata.get(BlockRedstoneOre.a)) { - // CraftBukkit start - if (CraftEventFactory.callBlockFadeEvent(world, blockposition, iblockdata.set(BlockRedstoneOre.a, false)).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockRedstoneOre.a, false), 3); - } - - } - - @Override - public void dropNaturally(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) { - super.dropNaturally(iblockdata, world, blockposition, itemstack); - /* CraftBukkit start - Delegated to getExpDrop - if (EnchantmentManager.getEnchantmentLevel(Enchantments.SILK_TOUCH, itemstack) == 0) { - int i = 1 + world.random.nextInt(5); - - this.dropExperience(world, blockposition, i); - } - // */ - - } - - @Override - public int getExpDrop(IBlockData iblockdata, World world, BlockPosition blockposition, ItemStack itemstack) { - if (EnchantmentManager.getEnchantmentLevel(Enchantments.SILK_TOUCH, itemstack) == 0) { - int i = 1 + world.random.nextInt(5); - - return i; - } - return 0; - // CraftBukkit end - } - - private static void playEffect(World world, BlockPosition blockposition) { - double d0 = 0.5625D; - Random random = world.random; - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - BlockPosition blockposition1 = blockposition.shift(enumdirection); - - if (!world.getType(blockposition1).g(world, blockposition1)) { - EnumDirection.EnumAxis enumdirection_enumaxis = enumdirection.k(); - double d1 = enumdirection_enumaxis == EnumDirection.EnumAxis.X ? 0.5D + 0.5625D * (double) enumdirection.getAdjacentX() : (double) random.nextFloat(); - double d2 = enumdirection_enumaxis == EnumDirection.EnumAxis.Y ? 0.5D + 0.5625D * (double) enumdirection.getAdjacentY() : (double) random.nextFloat(); - double d3 = enumdirection_enumaxis == EnumDirection.EnumAxis.Z ? 0.5D + 0.5625D * (double) enumdirection.getAdjacentZ() : (double) random.nextFloat(); - - world.addParticle(ParticleParamRedstone.a, (double) blockposition.getX() + d1, (double) blockposition.getY() + d2, (double) blockposition.getZ() + d3, 0.0D, 0.0D, 0.0D); - } - } - - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockRedstoneOre.a); - } -} diff --git a/src/main/java/net/minecraft/server/BlockRedstoneTorch.java b/src/main/java/net/minecraft/server/BlockRedstoneTorch.java deleted file mode 100644 index 919ba8a14..000000000 --- a/src/main/java/net/minecraft/server/BlockRedstoneTorch.java +++ /dev/null @@ -1,185 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.WeakHashMap; - -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public class BlockRedstoneTorch extends BlockTorch { - - public static final BlockStateBoolean LIT = BlockProperties.r; - // Paper - Move the mapped list to World - - protected BlockRedstoneTorch(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockRedstoneTorch.LIT, true)); - } - - @Override - public int a(IWorldReader iworldreader) { - return 2; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - world.applyPhysics(blockposition.shift(enumdirection), this); - } - - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (!flag) { - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - world.applyPhysics(blockposition.shift(enumdirection), this); - } - - } - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Boolean) iblockdata.get(BlockRedstoneTorch.LIT) && EnumDirection.UP != enumdirection ? 15 : 0; - } - - protected boolean a(World world, BlockPosition blockposition, IBlockData iblockdata) { - return world.isBlockFacePowered(blockposition.down(), EnumDirection.DOWN); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - a(iblockdata, world, blockposition, random, this.a(world, blockposition, iblockdata)); - } - - public static void a(IBlockData iblockdata, World world, BlockPosition blockposition, Random random, boolean flag) { - // Paper start - java.util.ArrayDeque redstoneUpdateInfos = world.redstoneUpdateInfos; - - if (redstoneUpdateInfos != null) { - BlockRedstoneTorch.RedstoneUpdateInfo curr; - while ((curr = redstoneUpdateInfos.peek()) != null && world.getTime() - curr.getTime() > 60L) { - redstoneUpdateInfos.poll(); - } - } - // Paper end - - // 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 = ((Boolean) iblockdata.get(BlockRedstoneTorch.LIT)).booleanValue() ? 15 : 0; - - BlockRedstoneEvent event = new BlockRedstoneEvent(block, oldCurrent, oldCurrent); - // CraftBukkit end - if ((Boolean) iblockdata.get(BlockRedstoneTorch.LIT)) { - if (flag) { - // CraftBukkit start - if (oldCurrent != 0) { - event.setNewCurrent(0); - manager.callEvent(event); - if (event.getNewCurrent() != 0) { - return; - } - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockRedstoneTorch.LIT, false), 3); - if (a(world, blockposition, true)) { - world.triggerEffect(1502, blockposition, 0); - world.getBlockTickList().a(blockposition, world.getType(blockposition).getBlock(), 160); - } - } - } else if (!flag && !a(world, blockposition, false)) { - // CraftBukkit start - if (oldCurrent != 15) { - event.setNewCurrent(15); - manager.callEvent(event); - if (event.getNewCurrent() != 15) { - return; - } - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockRedstoneTorch.LIT, true), 3); - } - - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if ((Boolean) iblockdata.get(BlockRedstoneTorch.LIT) == this.a(world, blockposition, iblockdata) && !world.getBlockTickList().b(blockposition, this)) { - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world)); - } - - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return enumdirection == EnumDirection.DOWN ? iblockdata.b(iblockaccess, blockposition, enumdirection) : 0; - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - @Override - public int a(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockRedstoneTorch.LIT) ? super.a(iblockdata) : 0; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockRedstoneTorch.LIT); - } - - private static boolean a(World world, BlockPosition blockposition, boolean flag) { - // Paper start - java.util.ArrayDeque list = world.redstoneUpdateInfos; - if (list == null) { - list = world.redstoneUpdateInfos = new java.util.ArrayDeque<>(); - } - - - if (flag) { - list.add(new BlockRedstoneTorch.RedstoneUpdateInfo(blockposition.immutableCopy(), world.getTime())); - } - - int i = 0; - - for (java.util.Iterator iterator = list.iterator(); iterator.hasNext();) { - BlockRedstoneTorch.RedstoneUpdateInfo blockredstonetorch_redstoneupdateinfo = iterator.next(); - // Paper end - if (blockredstonetorch_redstoneupdateinfo.a.equals(blockposition)) { - ++i; - if (i >= 8) { - return true; - } - } - } - - return false; - } - - public static class RedstoneUpdateInfo { - - private final BlockPosition a; - private final long b; final long getTime() { return this.b; } // Paper - OBFHELPER - - public RedstoneUpdateInfo(BlockPosition blockposition, long i) { - this.a = blockposition; - this.b = i; - } - } -} diff --git a/src/main/java/net/minecraft/server/BlockRedstoneWire.java b/src/main/java/net/minecraft/server/BlockRedstoneWire.java deleted file mode 100644 index 337c03d1d..000000000 --- a/src/main/java/net/minecraft/server/BlockRedstoneWire.java +++ /dev/null @@ -1,579 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.PaperConfig; -import com.destroystokyo.paper.util.RedstoneWireTurbo; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.annotation.Nullable; - -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public class BlockRedstoneWire extends Block { - - public static final BlockStateEnum NORTH = BlockProperties.R; - public static final BlockStateEnum EAST = BlockProperties.Q; - public static final BlockStateEnum SOUTH = BlockProperties.S; - public static final BlockStateEnum WEST = BlockProperties.T; - public static final BlockStateInteger POWER = BlockProperties.as; - public static final Map> f = Maps.newEnumMap(ImmutableMap.of(EnumDirection.NORTH, BlockRedstoneWire.NORTH, EnumDirection.EAST, BlockRedstoneWire.EAST, EnumDirection.SOUTH, BlockRedstoneWire.SOUTH, EnumDirection.WEST, BlockRedstoneWire.WEST)); - protected static final VoxelShape[] g = new VoxelShape[]{Block.a(3.0D, 0.0D, 3.0D, 13.0D, 1.0D, 13.0D), Block.a(3.0D, 0.0D, 3.0D, 13.0D, 1.0D, 16.0D), Block.a(0.0D, 0.0D, 3.0D, 13.0D, 1.0D, 13.0D), Block.a(0.0D, 0.0D, 3.0D, 13.0D, 1.0D, 16.0D), Block.a(3.0D, 0.0D, 0.0D, 13.0D, 1.0D, 13.0D), Block.a(3.0D, 0.0D, 0.0D, 13.0D, 1.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 13.0D, 1.0D, 13.0D), Block.a(0.0D, 0.0D, 0.0D, 13.0D, 1.0D, 16.0D), Block.a(3.0D, 0.0D, 3.0D, 16.0D, 1.0D, 13.0D), Block.a(3.0D, 0.0D, 3.0D, 16.0D, 1.0D, 16.0D), Block.a(0.0D, 0.0D, 3.0D, 16.0D, 1.0D, 13.0D), Block.a(0.0D, 0.0D, 3.0D, 16.0D, 1.0D, 16.0D), Block.a(3.0D, 0.0D, 0.0D, 16.0D, 1.0D, 13.0D), Block.a(3.0D, 0.0D, 0.0D, 16.0D, 1.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 1.0D, 13.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 1.0D, 16.0D)}; - private boolean h = true; public final boolean canProvidePower() { return this.h; } public final void setCanProvidePower(boolean value) { this.h = value; } // Paper - OBFHELPER - private final Set i = Sets.newHashSet(); private Set getBlocksNeedingUpdate() { return this.i; } // Paper - OBFHELPER - - public BlockRedstoneWire(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockRedstoneWire.NORTH, BlockPropertyRedstoneSide.NONE)).set(BlockRedstoneWire.EAST, BlockPropertyRedstoneSide.NONE)).set(BlockRedstoneWire.SOUTH, BlockPropertyRedstoneSide.NONE)).set(BlockRedstoneWire.WEST, BlockPropertyRedstoneSide.NONE)).set(BlockRedstoneWire.POWER, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockRedstoneWire.g[q(iblockdata)]; - } - - private static int q(IBlockData iblockdata) { - int i = 0; - boolean flag = iblockdata.get(BlockRedstoneWire.NORTH) != BlockPropertyRedstoneSide.NONE; - boolean flag1 = iblockdata.get(BlockRedstoneWire.EAST) != BlockPropertyRedstoneSide.NONE; - boolean flag2 = iblockdata.get(BlockRedstoneWire.SOUTH) != BlockPropertyRedstoneSide.NONE; - boolean flag3 = iblockdata.get(BlockRedstoneWire.WEST) != BlockPropertyRedstoneSide.NONE; - - if (flag || flag2 && !flag && !flag1 && !flag3) { - i |= 1 << EnumDirection.NORTH.get2DRotationValue(); - } - - if (flag1 || flag3 && !flag && !flag1 && !flag2) { - i |= 1 << EnumDirection.EAST.get2DRotationValue(); - } - - if (flag2 || flag && !flag1 && !flag2 && !flag3) { - i |= 1 << EnumDirection.SOUTH.get2DRotationValue(); - } - - if (flag3 || flag1 && !flag && !flag2 && !flag3) { - i |= 1 << EnumDirection.WEST.get2DRotationValue(); - } - - return i; - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - World world = blockactioncontext.getWorld(); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.getBlockData().set(BlockRedstoneWire.WEST, this.a((IBlockAccess) world, blockposition, EnumDirection.WEST))).set(BlockRedstoneWire.EAST, this.a((IBlockAccess) world, blockposition, EnumDirection.EAST))).set(BlockRedstoneWire.NORTH, this.a((IBlockAccess) world, blockposition, EnumDirection.NORTH))).set(BlockRedstoneWire.SOUTH, this.a((IBlockAccess) world, blockposition, EnumDirection.SOUTH)); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return enumdirection == EnumDirection.DOWN ? iblockdata : (enumdirection == EnumDirection.UP ? (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockRedstoneWire.WEST, this.a((IBlockAccess) generatoraccess, blockposition, EnumDirection.WEST))).set(BlockRedstoneWire.EAST, this.a((IBlockAccess) generatoraccess, blockposition, EnumDirection.EAST))).set(BlockRedstoneWire.NORTH, this.a((IBlockAccess) generatoraccess, blockposition, EnumDirection.NORTH))).set(BlockRedstoneWire.SOUTH, this.a((IBlockAccess) generatoraccess, blockposition, EnumDirection.SOUTH)) : (IBlockData) iblockdata.set((IBlockState) BlockRedstoneWire.f.get(enumdirection), this.a((IBlockAccess) generatoraccess, blockposition, enumdirection))); - } - - @Override - public void b(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, int i) { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - BlockPropertyRedstoneSide blockpropertyredstoneside = (BlockPropertyRedstoneSide) iblockdata.get((IBlockState) BlockRedstoneWire.f.get(enumdirection)); - - if (blockpropertyredstoneside != BlockPropertyRedstoneSide.NONE && generatoraccess.getType(blockposition_pooledblockposition.g(blockposition).c(enumdirection)).getBlock() != this) { - blockposition_pooledblockposition.c(EnumDirection.DOWN); - IBlockData iblockdata1 = generatoraccess.getType(blockposition_pooledblockposition); - - if (iblockdata1.getBlock() != Blocks.OBSERVER) { - BlockPosition blockposition1 = blockposition_pooledblockposition.shift(enumdirection.opposite()); - IBlockData iblockdata2 = iblockdata1.updateState(enumdirection.opposite(), generatoraccess.getType(blockposition1), generatoraccess, blockposition_pooledblockposition, blockposition1); - - a(iblockdata1, iblockdata2, generatoraccess, blockposition_pooledblockposition, i); - } - - blockposition_pooledblockposition.g(blockposition).c(enumdirection).c(EnumDirection.UP); - IBlockData iblockdata3 = generatoraccess.getType(blockposition_pooledblockposition); - - if (iblockdata3.getBlock() != Blocks.OBSERVER) { - BlockPosition blockposition2 = blockposition_pooledblockposition.shift(enumdirection.opposite()); - IBlockData iblockdata4 = iblockdata3.updateState(enumdirection.opposite(), generatoraccess.getType(blockposition2), generatoraccess, blockposition_pooledblockposition, blockposition2); - - a(iblockdata3, iblockdata4, generatoraccess, blockposition_pooledblockposition, i); - } - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - } - - private BlockPropertyRedstoneSide a(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - BlockPosition blockposition1 = blockposition.shift(enumdirection); - IBlockData iblockdata = iblockaccess.getType(blockposition1); - BlockPosition blockposition2 = blockposition.up(); - IBlockData iblockdata1 = iblockaccess.getType(blockposition2); - - if (!iblockdata1.isOccluding(iblockaccess, blockposition2)) { - boolean flag = iblockdata.d(iblockaccess, blockposition1, EnumDirection.UP) || iblockdata.getBlock() == Blocks.HOPPER; - - if (flag && j(iblockaccess.getType(blockposition1.up()))) { - if (iblockdata.o(iblockaccess, blockposition1)) { - return BlockPropertyRedstoneSide.UP; - } - - return BlockPropertyRedstoneSide.SIDE; - } - } - - return !a(iblockdata, enumdirection) && (iblockdata.isOccluding(iblockaccess, blockposition1) || !j(iblockaccess.getType(blockposition1.down()))) ? BlockPropertyRedstoneSide.NONE : BlockPropertyRedstoneSide.SIDE; - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata1 = iworldreader.getType(blockposition1); - - return iblockdata1.d(iworldreader, blockposition1, EnumDirection.UP) || iblockdata1.getBlock() == Blocks.HOPPER; - } - - // Paper start - Optimize redstone - // The bulk of the new functionality is found in RedstoneWireTurbo.java - RedstoneWireTurbo turbo = new RedstoneWireTurbo(this); - - /* - * Modified version of pre-existing updateSurroundingRedstone, which is called from - * this.neighborChanged and a few other methods in this class. - * Note: Added 'source' argument so as to help determine direction of information flow - */ - private IBlockData updateSurroundingRedstone(World worldIn, BlockPosition pos, IBlockData state, BlockPosition source) { - if (worldIn.paperConfig.useEigencraftRedstone) { - return turbo.updateSurroundingRedstone(worldIn, pos, state, source); - } - return a(worldIn, pos, state); - } - - /* - * Slightly modified method to compute redstone wire power levels from neighboring blocks. - * Modifications cut the number of power level changes by about 45% from vanilla, and this - * optimization synergizes well with the breadth-first search implemented in - * RedstoneWireTurbo. - * Note: RedstoneWireTurbo contains a faster version of this code. - * Note: Made this public so that RedstoneWireTurbo can access it. - */ - public IBlockData calculateCurrentChanges(World worldIn, BlockPosition pos1, BlockPosition pos2, IBlockData state) { - IBlockData iblockstate = state; - int i = state.get(POWER).intValue(); - int j = 0; - j = this.getPower(j, worldIn.getType(pos2)); - this.setCanProvidePower(false); - int k = worldIn.isBlockIndirectlyGettingPowered(pos1); - this.setCanProvidePower(true); - - if (!worldIn.paperConfig.useEigencraftRedstone) { - // This code is totally redundant to if statements just below the loop. - if (k > 0 && k > j - 1) { - j = k; - } - } - - 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 (!worldIn.paperConfig.useEigencraftRedstone || 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(l, worldIn.getType(blockpos)); - } - - if (worldIn.getType(blockpos).isOccluding(worldIn, blockpos) && !worldIn.getType(pos1.up()).isOccluding(worldIn, pos1)) { - if (flag && pos1.getY() >= pos2.getY()) { - l = this.getPower(l, worldIn.getType(blockpos.up())); - } - } else if (!worldIn.getType(blockpos).isOccluding(worldIn, blockpos) && flag && pos1.getY() <= pos2.getY()) { - l = this.getPower(l, worldIn.getType(blockpos.down())); - } - } - } - - if (!worldIn.paperConfig.useEigencraftRedstone) { - // The old code would decrement the wire value only by 1 at a time. - if (l > j) { - j = l - 1; - } else if (j > 0) { - --j; - } else { - j = 0; - } - - if (k > j - 1) { - j = k; - } - } else { - // 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, Integer.valueOf(j)); - - if (worldIn.getType(pos1) == iblockstate) { - worldIn.setTypeAndData(pos1, state, 2); - } - - if (!worldIn.paperConfig.useEigencraftRedstone) { - // The new search algorithm keeps track of blocks needing updates in its own data structures, - // so only add anything to blocksNeedingUpdate if we're using the vanilla update algorithm. - this.getBlocksNeedingUpdate().add(pos1); - - for (EnumDirection enumfacing1 : EnumDirection.values()) { - this.getBlocksNeedingUpdate().add(pos1.shift(enumfacing1)); - } - } - } - - return state; - } - // Paper end - private IBlockData a(World world, BlockPosition blockposition, IBlockData iblockdata) { - iblockdata = this.b(world, blockposition, iblockdata); - List list = Lists.newArrayList(this.i); - - this.i.clear(); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition1 = (BlockPosition) iterator.next(); - - world.applyPhysics(blockposition1, this); - } - - return iblockdata; - } - - private IBlockData b(World world, BlockPosition blockposition, IBlockData iblockdata) { - IBlockData iblockdata1 = iblockdata; - int i = (Integer) iblockdata.get(BlockRedstoneWire.POWER); - - this.h = false; - int j = world.q(blockposition); - - this.h = true; - int k = 0; - - if (j < 15) { - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - IBlockData iblockdata2 = world.getType(blockposition1); - - k = this.getPower(k, iblockdata2); - BlockPosition blockposition2 = blockposition.up(); - - if (iblockdata2.isOccluding(world, blockposition1) && !world.getType(blockposition2).isOccluding(world, blockposition2)) { - k = this.getPower(k, world.getType(blockposition1.up())); - } else if (!iblockdata2.isOccluding(world, blockposition1)) { - k = this.getPower(k, world.getType(blockposition1.down())); - } - } - } - - int l = k - 1; - - if (j > l) { - l = j; - } - - // CraftBukkit start - if (i != l) { - BlockRedstoneEvent event = new BlockRedstoneEvent(world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), i, l); - world.getServer().getPluginManager().callEvent(event); - - l = event.getNewCurrent(); - } - // CraftBukkit end - - if (i != l) { - iblockdata = (IBlockData) iblockdata.set(BlockRedstoneWire.POWER, l); - if (world.getType(blockposition) == iblockdata1) { - world.setTypeAndData(blockposition, iblockdata, 2); - } - - this.i.add(blockposition); - EnumDirection[] aenumdirection = EnumDirection.values(); - int i1 = aenumdirection.length; - - for (int j1 = 0; j1 < i1; ++j1) { - EnumDirection enumdirection1 = aenumdirection[j1]; - - this.i.add(blockposition.shift(enumdirection1)); - } - } - - return iblockdata; - } - - private void a(World world, BlockPosition blockposition) { - if (world.getType(blockposition).getBlock() == this) { - world.applyPhysics(blockposition, this); - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - world.applyPhysics(blockposition.shift(enumdirection), this); - } - - } - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata1.getBlock() != iblockdata.getBlock() && !world.isClientSide) { - this.updateSurroundingRedstone(world, blockposition, iblockdata, null); // Paper - Optimize redstone - Iterator iterator = EnumDirection.EnumDirectionLimit.VERTICAL.iterator(); - - EnumDirection enumdirection; - - while (iterator.hasNext()) { - enumdirection = (EnumDirection) iterator.next(); - world.applyPhysics(blockposition.shift(enumdirection), this); - } - - iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - enumdirection = (EnumDirection) iterator.next(); - this.a(world, blockposition.shift(enumdirection)); - } - - iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - enumdirection = (EnumDirection) iterator.next(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - - if (world.getType(blockposition1).isOccluding(world, blockposition1)) { - this.a(world, blockposition1.up()); - } else { - this.a(world, blockposition1.down()); - } - } - - } - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (!flag && iblockdata.getBlock() != iblockdata1.getBlock()) { - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - if (!world.isClientSide) { - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - world.applyPhysics(blockposition.shift(enumdirection), this); - } - - this.updateSurroundingRedstone(world, blockposition, iblockdata, null); // Paper - Optimize redstone - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - EnumDirection enumdirection1; - - while (iterator.hasNext()) { - enumdirection1 = (EnumDirection) iterator.next(); - this.a(world, blockposition.shift(enumdirection1)); - } - - iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - enumdirection1 = (EnumDirection) iterator.next(); - BlockPosition blockposition1 = blockposition.shift(enumdirection1); - - if (world.getType(blockposition1).isOccluding(world, blockposition1)) { - this.a(world, blockposition1.up()); - } else { - this.a(world, blockposition1.down()); - } - } - - } - } - } - - public int getPower(int i, IBlockData iblockdata) { - if (iblockdata.getBlock() != this) { - return i; - } else { - int j = (Integer) iblockdata.get(BlockRedstoneWire.POWER); - - return j > i ? j : i; - } - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (!world.isClientSide) { - if (iblockdata.canPlace(world, blockposition)) { - this.updateSurroundingRedstone(world, blockposition, iblockdata, blockposition1); // Paper - Optimize redstone - } else { - c(iblockdata, world, blockposition); - world.a(blockposition, false); - } - - } - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return !this.h ? 0 : iblockdata.b(iblockaccess, blockposition, enumdirection); - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - if (!this.h) { - return 0; - } else { - int i = (Integer) iblockdata.get(BlockRedstoneWire.POWER); - - if (i == 0) { - return 0; - } else if (enumdirection == EnumDirection.UP) { - return i; - } else { - EnumSet enumset = EnumSet.noneOf(EnumDirection.class); - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection1 = (EnumDirection) iterator.next(); - - if (this.b(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 b(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - BlockPosition blockposition1 = blockposition.shift(enumdirection); - IBlockData iblockdata = iblockaccess.getType(blockposition1); - boolean flag = iblockdata.isOccluding(iblockaccess, blockposition1); - BlockPosition blockposition2 = blockposition.up(); - boolean flag1 = iblockaccess.getType(blockposition2).isOccluding(iblockaccess, blockposition2); - - return !flag1 && flag && a(iblockaccess, blockposition1.up()) ? true : (a(iblockdata, enumdirection) ? true : (iblockdata.getBlock() == Blocks.REPEATER && (Boolean) iblockdata.get(BlockDiodeAbstract.c) && iblockdata.get(BlockDiodeAbstract.FACING) == enumdirection ? true : !flag && a(iblockaccess, blockposition1.down()))); - } - - protected static boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { - return j(iblockaccess.getType(blockposition)); - } - - protected static boolean j(IBlockData iblockdata) { - return a(iblockdata, (EnumDirection) null); - } - - protected static boolean a(IBlockData iblockdata, @Nullable EnumDirection enumdirection) { - Block block = iblockdata.getBlock(); - - if (block == Blocks.REDSTONE_WIRE) { - return true; - } else if (iblockdata.getBlock() == Blocks.REPEATER) { - EnumDirection enumdirection1 = (EnumDirection) iblockdata.get(BlockRepeater.FACING); - - return enumdirection1 == enumdirection || enumdirection1.opposite() == enumdirection; - } else { - return Blocks.OBSERVER == iblockdata.getBlock() ? enumdirection == iblockdata.get(BlockObserver.FACING) : iblockdata.isPowerSource() && enumdirection != null; - } - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return this.h; - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - switch (enumblockrotation) { - case CLOCKWISE_180: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockRedstoneWire.NORTH, iblockdata.get(BlockRedstoneWire.SOUTH))).set(BlockRedstoneWire.EAST, iblockdata.get(BlockRedstoneWire.WEST))).set(BlockRedstoneWire.SOUTH, iblockdata.get(BlockRedstoneWire.NORTH))).set(BlockRedstoneWire.WEST, iblockdata.get(BlockRedstoneWire.EAST)); - case COUNTERCLOCKWISE_90: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockRedstoneWire.NORTH, iblockdata.get(BlockRedstoneWire.EAST))).set(BlockRedstoneWire.EAST, iblockdata.get(BlockRedstoneWire.SOUTH))).set(BlockRedstoneWire.SOUTH, iblockdata.get(BlockRedstoneWire.WEST))).set(BlockRedstoneWire.WEST, iblockdata.get(BlockRedstoneWire.NORTH)); - case CLOCKWISE_90: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockRedstoneWire.NORTH, iblockdata.get(BlockRedstoneWire.WEST))).set(BlockRedstoneWire.EAST, iblockdata.get(BlockRedstoneWire.NORTH))).set(BlockRedstoneWire.SOUTH, iblockdata.get(BlockRedstoneWire.EAST))).set(BlockRedstoneWire.WEST, iblockdata.get(BlockRedstoneWire.SOUTH)); - default: - return iblockdata; - } - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - switch (enumblockmirror) { - case LEFT_RIGHT: - return (IBlockData) ((IBlockData) iblockdata.set(BlockRedstoneWire.NORTH, iblockdata.get(BlockRedstoneWire.SOUTH))).set(BlockRedstoneWire.SOUTH, iblockdata.get(BlockRedstoneWire.NORTH)); - case FRONT_BACK: - return (IBlockData) ((IBlockData) iblockdata.set(BlockRedstoneWire.EAST, iblockdata.get(BlockRedstoneWire.WEST))).set(BlockRedstoneWire.WEST, iblockdata.get(BlockRedstoneWire.EAST)); - default: - return super.a(iblockdata, enumblockmirror); - } - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockRedstoneWire.NORTH, BlockRedstoneWire.EAST, BlockRedstoneWire.SOUTH, BlockRedstoneWire.WEST, BlockRedstoneWire.POWER); - } -} diff --git a/src/main/java/net/minecraft/server/BlockReed.java b/src/main/java/net/minecraft/server/BlockReed.java deleted file mode 100644 index a4850c070..000000000 --- a/src/main/java/net/minecraft/server/BlockReed.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Random; - -public class BlockReed extends Block { - - public static final BlockStateInteger AGE = BlockProperties.ad; - protected static final VoxelShape b = Block.a(2.0D, 0.0D, 2.0D, 14.0D, 16.0D, 14.0D); - - protected BlockReed(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockReed.AGE, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockReed.b; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!iblockdata.canPlace(world, blockposition)) { - world.b(blockposition, true); - } else if (world.isEmpty(blockposition.up())) { - if (world.paperConfig.fixZeroTickInstantGrowFarms && !randomTick) return; // Paper - fix MC-113809 - int i; - - for (i = 1; world.getType(blockposition.down(i)).getBlock() == this; ++i) { - ; - } - - if (i < world.paperConfig.reedMaxHeight) { // Paper - Configurable growth height - int j = (Integer) iblockdata.get(BlockReed.AGE); - - if (j >= (byte) range(3, ((100.0F / world.spigotConfig.caneModifier) * 15) + 0.5F, 15)) { // Spigot - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockGrowEvent(world, blockposition.up(), this.getBlockData()); // CraftBukkit - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockReed.AGE, 0), 4); - } else { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockReed.AGE, j + 1), 4); - } - } - } - - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (!iblockdata.canPlace(generatoraccess, blockposition)) { - generatoraccess.getBlockTickList().a(blockposition, this, 1); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - Block block = iworldreader.getType(blockposition.down()).getBlock(); - - if (block == this) { - return true; - } else { - if (block == Blocks.GRASS_BLOCK || block == Blocks.DIRT || block == Blocks.COARSE_DIRT || block == Blocks.PODZOL || block == Blocks.SAND || block == Blocks.RED_SAND) { - BlockPosition blockposition1 = blockposition.down(); - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - IBlockData iblockdata1 = iworldreader.getType(blockposition1.shift(enumdirection)); - Fluid fluid = iworldreader.getFluid(blockposition1.shift(enumdirection)); - - if (fluid.a(TagsFluid.WATER) || iblockdata1.getBlock() == Blocks.FROSTED_ICE) { - return true; - } - } - } - - return false; - } - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockReed.AGE); - } -} diff --git a/src/main/java/net/minecraft/server/BlockSapling.java b/src/main/java/net/minecraft/server/BlockSapling.java deleted file mode 100644 index 28517b63f..000000000 --- a/src/main/java/net/minecraft/server/BlockSapling.java +++ /dev/null @@ -1,92 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -// CraftBukkit start -import java.util.List; - -import org.bukkit.Location; -import org.bukkit.TreeType; -import org.bukkit.block.BlockState; -import org.bukkit.event.world.StructureGrowEvent; -// CraftBukkit end - -public class BlockSapling extends BlockPlant implements IBlockFragilePlantElement { - - public static final BlockStateInteger STAGE = BlockProperties.at; - protected static final VoxelShape b = Block.a(2.0D, 0.0D, 2.0D, 14.0D, 12.0D, 14.0D); - private final WorldGenTreeProvider c; - public static TreeType treeType; // CraftBukkit - - protected BlockSapling(WorldGenTreeProvider worldgentreeprovider, Block.Info block_info) { - super(block_info); - this.c = worldgentreeprovider; - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockSapling.STAGE, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockSapling.b; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - super.tick(iblockdata, world, blockposition, random); - if (world.getLightLevel(blockposition.up()) >= 9 && random.nextInt(Math.max(2, (int) (((100.0F / world.spigotConfig.saplingModifier) * 7) + 0.5F))) == 0) { // Spigot - // CraftBukkit start - world.captureTreeGeneration = true; - // CraftBukkit end - this.grow(world, blockposition, iblockdata, random); - // CraftBukkit start - world.captureTreeGeneration = false; - if (world.capturedBlockStates.size() > 0) { - 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(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, Random random) { - if ((Integer) iblockdata.get(BlockSapling.STAGE) == 0) { - generatoraccess.setTypeAndData(blockposition, (IBlockData) iblockdata.a((IBlockState) BlockSapling.STAGE), 4); - } else { - this.c.a(generatoraccess, blockposition, iblockdata, random); - } - - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return true; - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return (double) world.random.nextFloat() < 0.45D; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - this.grow(world, blockposition, iblockdata, random); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockSapling.STAGE); - } -} diff --git a/src/main/java/net/minecraft/server/BlockSnow.java b/src/main/java/net/minecraft/server/BlockSnow.java deleted file mode 100644 index 7fe58ef6e..000000000 --- a/src/main/java/net/minecraft/server/BlockSnow.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public class BlockSnow extends Block { - - public static final BlockStateInteger LAYERS = BlockProperties.ak; - protected static final VoxelShape[] b = new VoxelShape[]{VoxelShapes.a(), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 2.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 4.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 6.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 8.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 10.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 12.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 14.0D, 16.0D), Block.a(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D)}; - - protected BlockSnow(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockSnow.LAYERS, 1)); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - switch (pathmode) { - case LAND: - return (Integer) iblockdata.get(BlockSnow.LAYERS) < 5; - case WATER: - return false; - case AIR: - return false; - default: - return false; - } - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockSnow.b[(Integer) iblockdata.get(BlockSnow.LAYERS)]; - } - - @Override - public VoxelShape b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockSnow.b[(Integer) iblockdata.get(BlockSnow.LAYERS) - 1]; - } - - @Override - public boolean n(IBlockData iblockdata) { - return true; - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - IBlockData iblockdata1 = iworldreader.getType(blockposition.down()); - Block block = iblockdata1.getBlock(); - - return block != Blocks.ICE && block != Blocks.PACKED_ICE && block != Blocks.BARRIER ? Block.a(iblockdata1.getCollisionShape(iworldreader, blockposition.down()), EnumDirection.UP) || block == this && (Integer) iblockdata1.get(BlockSnow.LAYERS) == 8 : false; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return !iblockdata.canPlace(generatoraccess, blockposition) ? Blocks.AIR.getBlockData() : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (world.getBrightness(EnumSkyBlock.BLOCK, blockposition) > 11) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - c(iblockdata, world, blockposition); - world.a(blockposition, false); - } - - } - - @Override - public boolean a(IBlockData iblockdata, BlockActionContext blockactioncontext) { - int i = (Integer) iblockdata.get(BlockSnow.LAYERS); - - return blockactioncontext.getItemStack().getItem() == this.getItem() && i < 8 ? (blockactioncontext.c() ? blockactioncontext.getClickedFace() == EnumDirection.UP : true) : i == 1; - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - IBlockData iblockdata = blockactioncontext.getWorld().getType(blockactioncontext.getClickPosition()); - - if (iblockdata.getBlock() == this) { - int i = (Integer) iblockdata.get(BlockSnow.LAYERS); - - return (IBlockData) iblockdata.set(BlockSnow.LAYERS, Math.min(8, i + 1)); - } else { - return super.getPlacedState(blockactioncontext); - } - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockSnow.LAYERS); - } -} diff --git a/src/main/java/net/minecraft/server/BlockSoil.java b/src/main/java/net/minecraft/server/BlockSoil.java deleted file mode 100644 index 2fc6e210d..000000000 --- a/src/main/java/net/minecraft/server/BlockSoil.java +++ /dev/null @@ -1,139 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Random; - -// CraftBukkit start -import org.bukkit.event.entity.EntityInteractEvent; -import org.bukkit.craftbukkit.event.CraftEventFactory; -// CraftBukkit end - -public class BlockSoil extends Block { - - public static final BlockStateInteger MOISTURE = BlockProperties.ap; - protected static final VoxelShape b = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 15.0D, 16.0D); - - protected BlockSoil(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockSoil.MOISTURE, 0)); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (enumdirection == EnumDirection.UP && !iblockdata.canPlace(generatoraccess, blockposition)) { - generatoraccess.getBlockTickList().a(blockposition, this, 1); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - IBlockData iblockdata1 = iworldreader.getType(blockposition.up()); - - return !iblockdata1.getMaterial().isBuildable() || iblockdata1.getBlock() instanceof BlockFenceGate; - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - return !this.getBlockData().canPlace(blockactioncontext.getWorld(), blockactioncontext.getClickPosition()) ? Blocks.DIRT.getBlockData() : super.getPlacedState(blockactioncontext); - } - - @Override - public boolean n(IBlockData iblockdata) { - return true; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockSoil.b; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!iblockdata.canPlace(world, blockposition)) { - fade(iblockdata, world, blockposition); - } else { - int i = (Integer) iblockdata.get(BlockSoil.MOISTURE); - - if (!a((IWorldReader) world, blockposition) && !world.isRainingAt(blockposition.up())) { - if (i > 0) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleMoistureChangeEvent(world, blockposition, (IBlockData) iblockdata.set(BlockSoil.MOISTURE, i - 1), 2); // CraftBukkit - } else if (!a((IBlockAccess) world, blockposition)) { - fade(iblockdata, world, blockposition); - } - } else if (i < 7) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleMoistureChangeEvent(world, blockposition, (IBlockData) iblockdata.set(BlockSoil.MOISTURE, 7), 2); // CraftBukkit - } - - } - } - - @Override - 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 (!world.isClientSide && world.random.nextFloat() < f - 0.5F && entity instanceof EntityLiving && (entity instanceof EntityHuman || world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) && entity.getWidth() * entity.getWidth() * entity.getHeight() > 0.512F) { - // 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, 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, Blocks.DIRT.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - fade(world.getType(blockposition), world, blockposition); - } - - // super.fallOn(world, blockposition, entity, f); // CraftBukkit - moved up - } - - public static void fade(IBlockData iblockdata, World world, BlockPosition blockposition) { - // CraftBukkit start - if (CraftEventFactory.callBlockFadeEvent(world, blockposition, Blocks.DIRT.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeUpdate(blockposition, a(iblockdata, Blocks.DIRT.getBlockData(), world, blockposition)); - } - - private static boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { - Block block = iblockaccess.getType(blockposition.up()).getBlock(); - - return block instanceof BlockCrops || block instanceof BlockStem || block instanceof BlockStemAttached; - } - - private static boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - Iterator iterator = BlockPosition.a(blockposition.b(-4, 0, -4), blockposition.b(4, 1, 4)).iterator(); - - BlockPosition blockposition1; - - do { - if (!iterator.hasNext()) { - return false; - } - - blockposition1 = (BlockPosition) iterator.next(); - } while (!iworldreader.getFluid(blockposition1).a(TagsFluid.WATER)); - - return true; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockSoil.MOISTURE); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockSponge.java b/src/main/java/net/minecraft/server/BlockSponge.java deleted file mode 100644 index 9edf937a6..000000000 --- a/src/main/java/net/minecraft/server/BlockSponge.java +++ /dev/null @@ -1,132 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Queue; -// CraftBukkit start -import java.util.List; -import org.bukkit.craftbukkit.block.CraftBlockState; -import org.bukkit.craftbukkit.util.BlockStateListPopulator; -import org.bukkit.event.block.SpongeAbsorbEvent; -// CraftBukkit end - -public class BlockSponge extends Block { - - protected BlockSponge(Block.Info block_info) { - super(block_info); - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata1.getBlock() != iblockdata.getBlock()) { - this.a(world, blockposition); - } - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - this.a(world, blockposition); - super.doPhysics(iblockdata, world, blockposition, block, blockposition1, flag); - } - - protected void a(World world, BlockPosition blockposition) { - if (this.b(world, blockposition)) { - world.setTypeAndData(blockposition, Blocks.WET_SPONGE.getBlockData(), 2); - world.triggerEffect(2001, blockposition, Block.getCombinedId(Blocks.WATER.getBlockData())); - } - - } - - private boolean b(World world, BlockPosition blockposition) { - Queue> queue = Lists.newLinkedList(); - - queue.add(new Tuple<>(blockposition, 0)); - int i = 0; - BlockStateListPopulator blockList = new BlockStateListPopulator(world); // CraftBukkit - Use BlockStateListPopulator - - while (!queue.isEmpty()) { - Tuple tuple = (Tuple) queue.poll(); - BlockPosition blockposition1 = (BlockPosition) tuple.a(); - int j = (Integer) tuple.b(); - EnumDirection[] aenumdirection = EnumDirection.values(); - int k = aenumdirection.length; - - for (int l = 0; l < k; ++l) { - EnumDirection enumdirection = aenumdirection[l]; - BlockPosition blockposition2 = blockposition1.shift(enumdirection); - // CraftBukkit start - IBlockData iblockdata = blockList.getType(blockposition2); - Fluid fluid = blockList.getFluid(blockposition2); - // CraftBukkit end - Material material = iblockdata.getMaterial(); - - if (fluid.a(TagsFluid.WATER)) { - if (iblockdata.getBlock() instanceof IFluidSource && ((IFluidSource) iblockdata.getBlock()).removeFluid(blockList, blockposition2, iblockdata) != FluidTypes.EMPTY) { // CraftBukkit - ++i; - if (j < 6) { - queue.add(new Tuple<>(blockposition2, j + 1)); - } - } else if (iblockdata.getBlock() instanceof BlockFluids) { - blockList.setTypeAndData(blockposition2, Blocks.AIR.getBlockData(), 3); // CraftBukkit - ++i; - if (j < 6) { - queue.add(new Tuple<>(blockposition2, j + 1)); - } - } else if (material == Material.WATER_PLANT || material == Material.REPLACEABLE_WATER_PLANT) { - // CraftBukkit start - // TileEntity tileentity = iblockdata.getBlock().isTileEntity() ? world.getTileEntity(blockposition2) : null; - - // a(iblockdata, world, blockposition2, tileentity); - blockList.setTypeAndData(blockposition2, Blocks.AIR.getBlockData(), 3); - // CraftBukkit end - ++i; - if (j < 6) { - queue.add(new Tuple<>(blockposition2, j + 1)); - } - } - } - } - - if (i > 64) { - break; - } - } - // CraftBukkit start - List blocks = blockList.getList(); // Is a clone - if (!blocks.isEmpty()) { - final org.bukkit.block.Block bblock = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); - - SpongeAbsorbEvent event = new SpongeAbsorbEvent(bblock, (List) (List) blocks); - world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return false; - } - - for (CraftBlockState block : blocks) { - BlockPosition blockposition2 = block.getPosition(); - IBlockData iblockdata = world.getType(blockposition2); - Fluid fluid = world.getFluid(blockposition2); - Material material = iblockdata.getMaterial(); - - if (fluid.a(TagsFluid.WATER)) { - if (iblockdata.getBlock() instanceof IFluidSource && ((IFluidSource) iblockdata.getBlock()).removeFluid(blockList, blockposition2, iblockdata) != FluidTypes.EMPTY) { - // NOP - } else if (iblockdata.getBlock() instanceof BlockFluids) { - // NOP - } else if (material == Material.WATER_PLANT || material == Material.REPLACEABLE_WATER_PLANT) { - TileEntity tileentity = iblockdata.getBlock().isTileEntity() ? world.getTileEntity(blockposition2) : null; - // Paper start - if (block.getHandle().getMaterial() == Material.AIR) { - dropNaturally(iblockdata, world, blockposition2, tileentity); - } - // Paper end - } - } - world.setTypeAndData(blockposition2, block.getHandle(), block.getFlag()); - } - } - // CraftBukkit end - - return i > 0; - } -} diff --git a/src/main/java/net/minecraft/server/BlockState.java b/src/main/java/net/minecraft/server/BlockState.java deleted file mode 100644 index 00e67b567..000000000 --- a/src/main/java/net/minecraft/server/BlockState.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.MoreObjects; - -public abstract class BlockState> implements IBlockState { - - private final Class a; - private final String b; - private Integer c; - - protected BlockState(String s, Class oclass) { - this.a = oclass; - this.b = s; - } - - @Override - public String a() { - return this.b; - } - - @Override - public Class b() { - return this.a; - } - - public String toString() { - return MoreObjects.toStringHelper(this).add("name", this.b).add("clazz", this.a).add("values", this.getValues()).toString(); - } - - public boolean equals(Object object) { - return this == object; // Paper - only one instance per configuration - } - - private static final java.util.concurrent.atomic.AtomicInteger hashId = new java.util.concurrent.atomic.AtomicInteger(1); // Paper - only one instance per configuration - private final int hashCode = 92821 * hashId.getAndIncrement(); // Paper - only one instance per configuration - public final int hashCode() { - return this.hashCode; // Paper - only one instance per configuration - } - - public int c() { - return 31 * this.a.hashCode() + this.b.hashCode(); - } -} diff --git a/src/main/java/net/minecraft/server/BlockStateBoolean.java b/src/main/java/net/minecraft/server/BlockStateBoolean.java deleted file mode 100644 index 7ca302b52..000000000 --- a/src/main/java/net/minecraft/server/BlockStateBoolean.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableSet; -import java.util.Collection; -import java.util.Optional; - -public class BlockStateBoolean extends BlockState { - - private final ImmutableSet a = ImmutableSet.of(true, false); - - protected BlockStateBoolean(String s) { - super(s, Boolean.class); - } - - @Override - public Collection getValues() { - return this.a; - } - - public static BlockStateBoolean of(String s) { - return new BlockStateBoolean(s); - } - - @Override - public Optional b(String s) { - return !"true".equals(s) && !"false".equals(s) ? Optional.empty() : Optional.of(Boolean.valueOf(s)); - } - - public String a(Boolean obool) { - return obool.toString(); - } - - public boolean equals_unused(Object object) { // Paper - if (this == object) { - return true; - } else if (object instanceof BlockStateBoolean && super.equals(object)) { - BlockStateBoolean blockstateboolean = (BlockStateBoolean) object; - - return this.a.equals(blockstateboolean.a); - } else { - return false; - } - } - - @Override - public int c() { - return 31 * super.c() + this.a.hashCode(); - } -} diff --git a/src/main/java/net/minecraft/server/BlockStateEnum.java b/src/main/java/net/minecraft/server/BlockStateEnum.java deleted file mode 100644 index 7cdadc6b6..000000000 --- a/src/main/java/net/minecraft/server/BlockStateEnum.java +++ /dev/null @@ -1,88 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -public class BlockStateEnum & INamable> extends BlockState { - - private final ImmutableSet a; - private final Map b = Maps.newHashMap(); - - protected BlockStateEnum(String s, Class oclass, Collection collection) { - super(s, oclass); - this.a = ImmutableSet.copyOf(collection); - Iterator iterator = collection.iterator(); // Paper - decompile fix - - while (iterator.hasNext()) { - T t0 = iterator.next(); // Paper - Decompile fix - String s1 = ((INamable) t0).getName(); - - if (this.b.containsKey(s1)) { - throw new IllegalArgumentException("Multiple values have the same name '" + s1 + "'"); - } - - this.b.put(s1, t0); - } - - } - - @Override - public Collection getValues() { - return this.a; - } - - @Override - public Optional b(String s) { - return Optional.ofNullable(this.b.get(s)); - } - - public String a(T t0) { - return ((INamable) t0).getName(); - } - - public boolean equals_unused(Object object) { // Paper - if (this == object) { - return true; - } else if (object instanceof BlockStateEnum && super.equals(object)) { - BlockStateEnum blockstateenum = (BlockStateEnum) object; - - return this.a.equals(blockstateenum.a) && this.b.equals(blockstateenum.b); - } else { - return false; - } - } - - @Override - public int c() { - int i = super.c(); - - i = 31 * i + this.a.hashCode(); - i = 31 * i + this.b.hashCode(); - return i; - } - - public static & INamable> BlockStateEnum of(String s, Class oclass) { - return a(s, oclass, (Predicate) Predicates.alwaysTrue()); - } - - public static & INamable> BlockStateEnum a(String s, Class oclass, Predicate predicate) { - return a(s, oclass, (Collection) Arrays.stream(oclass.getEnumConstants()).filter(predicate).collect(Collectors.toList())); - } - - public static & INamable> BlockStateEnum of(String s, Class oclass, T... at) { - return a(s, oclass, (Collection) Lists.newArrayList(at)); - } - - public static & INamable> BlockStateEnum a(String s, Class oclass, Collection collection) { - return new BlockStateEnum<>(s, oclass, collection); - } -} diff --git a/src/main/java/net/minecraft/server/BlockStateInteger.java b/src/main/java/net/minecraft/server/BlockStateInteger.java deleted file mode 100644 index 0499a7170..000000000 --- a/src/main/java/net/minecraft/server/BlockStateInteger.java +++ /dev/null @@ -1,76 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; -import java.util.Collection; -import java.util.Optional; -import java.util.Set; - -public class BlockStateInteger extends BlockState { - - private final ImmutableSet a; - // CraftBukkit start - public final int min; - public final int max; - - protected BlockStateInteger(String s, int i, int j) { - super(s, Integer.class); - this.min = i; - this.max = j; - // CraftBukkit end - if (i < 0) { - throw new IllegalArgumentException("Min value of " + s + " must be 0 or greater"); - } else if (j <= i) { - throw new IllegalArgumentException("Max value of " + s + " must be greater than min (" + i + ")"); - } else { - Set set = Sets.newHashSet(); - - for (int k = i; k <= j; ++k) { - set.add(k); - } - - this.a = ImmutableSet.copyOf(set); - } - } - - @Override - public Collection getValues() { - return this.a; - } - - public boolean equals_unused(Object object) { // Paper - if (this == object) { - return true; - } else if (object instanceof BlockStateInteger && super.equals(object)) { - BlockStateInteger blockstateinteger = (BlockStateInteger) object; - - return this.a.equals(blockstateinteger.a); - } else { - return false; - } - } - - @Override - public int c() { - return 31 * super.c() + this.a.hashCode(); - } - - public static BlockStateInteger of(String s, int i, int j) { - return new BlockStateInteger(s, i, j); - } - - @Override - public Optional b(String s) { - try { - Integer integer = Integer.valueOf(s); - - return this.a.contains(integer) ? Optional.of(integer) : Optional.empty(); - } catch (NumberFormatException numberformatexception) { - return Optional.empty(); - } - } - - public String a(Integer integer) { - return integer.toString(); - } -} diff --git a/src/main/java/net/minecraft/server/BlockStem.java b/src/main/java/net/minecraft/server/BlockStem.java deleted file mode 100644 index f67b0c3ef..000000000 --- a/src/main/java/net/minecraft/server/BlockStem.java +++ /dev/null @@ -1,90 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockStem extends BlockPlant implements IBlockFragilePlantElement { - - public static final BlockStateInteger AGE = BlockProperties.ac; - protected static final VoxelShape[] b = new VoxelShape[]{Block.a(7.0D, 0.0D, 7.0D, 9.0D, 2.0D, 9.0D), Block.a(7.0D, 0.0D, 7.0D, 9.0D, 4.0D, 9.0D), Block.a(7.0D, 0.0D, 7.0D, 9.0D, 6.0D, 9.0D), Block.a(7.0D, 0.0D, 7.0D, 9.0D, 8.0D, 9.0D), Block.a(7.0D, 0.0D, 7.0D, 9.0D, 10.0D, 9.0D), Block.a(7.0D, 0.0D, 7.0D, 9.0D, 12.0D, 9.0D), Block.a(7.0D, 0.0D, 7.0D, 9.0D, 14.0D, 9.0D), Block.a(7.0D, 0.0D, 7.0D, 9.0D, 16.0D, 9.0D)}; - private final BlockStemmed blockFruit; - - protected BlockStem(BlockStemmed blockstemmed, Block.Info block_info) { - super(block_info); - this.blockFruit = blockstemmed; - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockStem.AGE, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockStem.b[(Integer) iblockdata.get(BlockStem.AGE)]; - } - - @Override - protected boolean a_(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockdata.getBlock() == Blocks.FARMLAND; - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - super.tick(iblockdata, world, blockposition, random); - if (world.getLightLevel(blockposition, 0) >= 9) { - float f = BlockCrops.a((Block) this, (IBlockAccess) world, blockposition); - - if (random.nextInt((int) ((100.0F / (this == Blocks.PUMPKIN_STEM ? world.spigotConfig.pumpkinModifier : world.spigotConfig.melonModifier)) * (25.0F / f)) + 1) == 0) { // Spigot - int i = (Integer) iblockdata.get(BlockStem.AGE); - - if (i < 7) { - iblockdata = (IBlockData) iblockdata.set(BlockStem.AGE, i + 1); - CraftEventFactory.handleBlockGrowEvent(world, blockposition, iblockdata, 2); // CraftBukkit - } else { - EnumDirection enumdirection = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - Block block = world.getType(blockposition1.down()).getBlock(); - - if (world.getType(blockposition1).isAir() && (block == Blocks.FARMLAND || block == Blocks.DIRT || block == Blocks.COARSE_DIRT || block == Blocks.PODZOL || block == Blocks.GRASS_BLOCK)) { - // CraftBukkit start - if (!CraftEventFactory.handleBlockGrowEvent(world, blockposition1, this.blockFruit.getBlockData())) { - return; - } - // CraftBukkit end - world.setTypeUpdate(blockposition, (IBlockData) this.blockFruit.e().getBlockData().set(BlockFacingHorizontal.FACING, enumdirection)); - } - } - } - - } - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return (Integer) iblockdata.get(BlockStem.AGE) != 7; - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return true; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - int i = Math.min(7, (Integer) iblockdata.get(BlockStem.AGE) + MathHelper.nextInt(world.random, 2, 5)); - IBlockData iblockdata1 = (IBlockData) iblockdata.set(BlockStem.AGE, i); - - CraftEventFactory.handleBlockGrowEvent(world, blockposition, iblockdata1, 2); // CraftBukkit - if (i == 7) { - iblockdata1.a(world, blockposition, world.random); - } - - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockStem.AGE); - } - - public BlockStemmed e() { - return this.blockFruit; - } -} diff --git a/src/main/java/net/minecraft/server/BlockSweetBerryBush.java b/src/main/java/net/minecraft/server/BlockSweetBerryBush.java deleted file mode 100644 index e16b477e8..000000000 --- a/src/main/java/net/minecraft/server/BlockSweetBerryBush.java +++ /dev/null @@ -1,94 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -// CraftBukkit start -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.event.CraftEventFactory; -// CraftBukkit end - -public class BlockSweetBerryBush extends BlockPlant implements IBlockFragilePlantElement { - - public static final BlockStateInteger a = BlockProperties.aa; - private static final VoxelShape b = Block.a(3.0D, 0.0D, 3.0D, 13.0D, 8.0D, 13.0D); - private static final VoxelShape c = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 16.0D, 15.0D); - - public BlockSweetBerryBush(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockSweetBerryBush.a, 0)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return (Integer) iblockdata.get(BlockSweetBerryBush.a) == 0 ? BlockSweetBerryBush.b : ((Integer) iblockdata.get(BlockSweetBerryBush.a) < 3 ? BlockSweetBerryBush.c : super.a(iblockdata, iblockaccess, blockposition, voxelshapecollision)); - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - super.tick(iblockdata, world, blockposition, random); - int i = (Integer) iblockdata.get(BlockSweetBerryBush.a); - - if (i < 3 && world.random.nextInt(Math.max(1, (int) (100.0F / world.spigotConfig.sweetBerryModifier) * 5)) == 0 && world.getLightLevel(blockposition.up(), 0) >= 9) { // Spigot - CraftEventFactory.handleBlockGrowEvent(world, blockposition, (IBlockData) iblockdata.set(BlockSweetBerryBush.a, i + 1), 2); // CraftBukkit - } - - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (entity instanceof EntityLiving && entity.getEntityType() != EntityTypes.FOX) { - entity.a(iblockdata, new Vec3D(0.800000011920929D, 0.75D, 0.800000011920929D)); - if (!world.isClientSide && (Integer) iblockdata.get(BlockSweetBerryBush.a) > 0 && (entity.H != entity.locX || entity.J != entity.locZ)) { - double d0 = Math.abs(entity.locX - entity.H); - double d1 = Math.abs(entity.locZ - entity.J); - - if (d0 >= 0.003000000026077032D || d1 >= 0.003000000026077032D) { - CraftEventFactory.blockDamage = CraftBlock.at(world, blockposition); // CraftBukkit - entity.damageEntity(DamageSource.SWEET_BERRY_BUSH, 1.0F); - CraftEventFactory.blockDamage = null; // CraftBukkit - } - } - - } - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - int i = (Integer) iblockdata.get(BlockSweetBerryBush.a); - boolean flag = i == 3; - - if (!flag && entityhuman.b(enumhand).getItem() == Items.BONE_MEAL) { - return false; - } else if (i > 1) { - int j = 1 + world.random.nextInt(2); - - a(world, blockposition, new ItemStack(Items.SWEET_BERRIES, j + (flag ? 1 : 0))); - world.playSound((EntityHuman) null, blockposition, SoundEffects.ITEM_SWEET_BERRIES_PICK_FROM_BUSH, SoundCategory.BLOCKS, 1.0F, 0.8F + world.random.nextFloat() * 0.4F); - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockSweetBerryBush.a, 1), 2); - return true; - } else { - return super.interact(iblockdata, world, blockposition, entityhuman, enumhand, movingobjectpositionblock); - } - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockSweetBerryBush.a); - } - - @Override - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return (Integer) iblockdata.get(BlockSweetBerryBush.a) < 3; - } - - @Override - public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - return true; - } - - @Override - public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { - int i = Math.min(3, (Integer) iblockdata.get(BlockSweetBerryBush.a) + 1); - - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockSweetBerryBush.a, i), 2); - } -} diff --git a/src/main/java/net/minecraft/server/BlockTNT.java b/src/main/java/net/minecraft/server/BlockTNT.java deleted file mode 100644 index b2689ee8b..000000000 --- a/src/main/java/net/minecraft/server/BlockTNT.java +++ /dev/null @@ -1,147 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -import com.destroystokyo.paper.event.block.TNTPrimeEvent; // Paper - TNTPrimeEvent - -public class BlockTNT extends Block { - - public static final BlockStateBoolean a = BlockProperties.B; - - public BlockTNT(Block.Info block_info) { - super(block_info); - this.o((IBlockData) this.getBlockData().set(BlockTNT.a, false)); - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata1.getBlock() != iblockdata.getBlock()) { - if (world.isBlockIndirectlyPowered(blockposition)) { - // Paper start - TNTPrimeEvent - org.bukkit.block.Block tntBlock = MCUtil.toBukkitBlock(world, blockposition);; - if(!new TNTPrimeEvent(tntBlock, TNTPrimeEvent.PrimeReason.REDSTONE, null).callEvent()) - return; - // Paper end - a(world, blockposition); - world.a(blockposition, false); - } - - } - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (world.isBlockIndirectlyPowered(blockposition)) { - // Paper start - TNTPrimeEvent - org.bukkit.block.Block tntBlock = MCUtil.toBukkitBlock(world, blockposition);; - if(!new TNTPrimeEvent(tntBlock, TNTPrimeEvent.PrimeReason.REDSTONE, null).callEvent()) - return; - // Paper end - a(world, blockposition); - world.a(blockposition, false); - } - - } - - @Override - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { - if (!world.e() && !entityhuman.isCreative() && (Boolean) iblockdata.get(BlockTNT.a)) { - a(world, blockposition); - } - - super.a(world, blockposition, iblockdata, entityhuman); - } - - @Override - public void wasExploded(World world, BlockPosition blockposition, Explosion explosion) { - if (!world.isClientSide) { - // Paper start - TNTPrimeEvent - org.bukkit.block.Block tntBlock = MCUtil.toBukkitBlock(world, blockposition);; - org.bukkit.entity.Entity source = explosion.source != null ? explosion.source.getBukkitEntity() : null; - if(!new TNTPrimeEvent(tntBlock, TNTPrimeEvent.PrimeReason.EXPLOSION, source).callEvent()) - return; - // Paper end - EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(world, (double) ((float) blockposition.getX() + 0.5F), (double) blockposition.getY(), (double) ((float) blockposition.getZ() + 0.5F), explosion.getSource()); - - entitytntprimed.setFuseTicks((short) (world.random.nextInt(entitytntprimed.getFuseTicks() / 4) + entitytntprimed.getFuseTicks() / 8)); - world.addEntity(entitytntprimed); - } - } - - public static void a(World world, BlockPosition blockposition) { - a(world, blockposition, (EntityLiving) null); - } - - private static void a(World world, BlockPosition blockposition, @Nullable EntityLiving entityliving) { - if (!world.isClientSide) { - EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(world, (double) ((float) blockposition.getX() + 0.5F), (double) blockposition.getY(), (double) ((float) blockposition.getZ() + 0.5F), entityliving); - - world.addEntity(entitytntprimed); - world.playSound((EntityHuman) null, entitytntprimed.locX, entitytntprimed.locY, entitytntprimed.locZ, SoundEffects.ENTITY_TNT_PRIMED, SoundCategory.BLOCKS, 1.0F, 1.0F); - } - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - ItemStack itemstack = entityhuman.b(enumhand); - Item item = itemstack.getItem(); - - if (item != Items.FLINT_AND_STEEL && item != Items.FIRE_CHARGE) { - return super.interact(iblockdata, world, blockposition, entityhuman, enumhand, movingobjectpositionblock); - } else { - // Paper start - TNTPrimeEvent - org.bukkit.block.Block tntBlock = MCUtil.toBukkitBlock(world, blockposition); - if(!new TNTPrimeEvent(tntBlock, TNTPrimeEvent.PrimeReason.ITEM, entityhuman.getBukkitEntity()).callEvent()) - return true; - // Paper end - a(world, blockposition, (EntityLiving) entityhuman); - world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 11); - if (item == Items.FLINT_AND_STEEL) { - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(enumhand); - }); - } else { - itemstack.subtract(1); - } - - return true; - } - } - - @Override - public void a(World world, IBlockData iblockdata, MovingObjectPositionBlock movingobjectpositionblock, Entity entity) { - if (!world.isClientSide && entity instanceof EntityArrow) { - EntityArrow entityarrow = (EntityArrow) entity; - Entity entity1 = entityarrow.getShooter(); - - if (entityarrow.isBurning()) { - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition(); - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(entityarrow, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - - // Paper start - TNTPrimeEvent - org.bukkit.block.Block tntBlock = MCUtil.toBukkitBlock(world, blockposition); - if (!new TNTPrimeEvent(tntBlock, TNTPrimeEvent.PrimeReason.PROJECTILE, entityarrow.getBukkitEntity()).callEvent()) { - return; - } - // Paper end - - a(world, blockposition, entity1 instanceof EntityLiving ? (EntityLiving) entity1 : null); - world.a(blockposition, false); - } - } - - } - - @Override - public boolean a(Explosion explosion) { - return false; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockTNT.a); - } -} diff --git a/src/main/java/net/minecraft/server/BlockTallPlant.java b/src/main/java/net/minecraft/server/BlockTallPlant.java deleted file mode 100644 index 227fe073f..000000000 --- a/src/main/java/net/minecraft/server/BlockTallPlant.java +++ /dev/null @@ -1,87 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class BlockTallPlant extends BlockPlant { - - public static final BlockStateEnum HALF = BlockProperties.U; - - public BlockTallPlant(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.LOWER)); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - BlockPropertyDoubleBlockHalf blockpropertydoubleblockhalf = (BlockPropertyDoubleBlockHalf) iblockdata.get(BlockTallPlant.HALF); - - return enumdirection.k() == EnumDirection.EnumAxis.Y && blockpropertydoubleblockhalf == BlockPropertyDoubleBlockHalf.LOWER == (enumdirection == EnumDirection.UP) && (iblockdata1.getBlock() != this || iblockdata1.get(BlockTallPlant.HALF) == blockpropertydoubleblockhalf) ? Blocks.AIR.getBlockData() : (blockpropertydoubleblockhalf == BlockPropertyDoubleBlockHalf.LOWER && enumdirection == EnumDirection.DOWN && !iblockdata.canPlace(generatoraccess, blockposition) ? Blocks.AIR.getBlockData() : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1)); - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - BlockPosition blockposition = blockactioncontext.getClickPosition(); - - return blockposition.getY() < 255 && blockactioncontext.getWorld().getType(blockposition.up()).a(blockactioncontext) ? super.getPlacedState(blockactioncontext) : null; - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { - world.setTypeAndData(blockposition.up(), (IBlockData) this.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.UPPER), 3); - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - if (iblockdata.get(BlockTallPlant.HALF) != BlockPropertyDoubleBlockHalf.UPPER) { - return super.canPlace(iblockdata, iworldreader, blockposition); - } else { - IBlockData iblockdata1 = iworldreader.getType(blockposition.down()); - - return iblockdata1.getBlock() == this && iblockdata1.get(BlockTallPlant.HALF) == BlockPropertyDoubleBlockHalf.LOWER; - } - } - - public void a(GeneratorAccess generatoraccess, BlockPosition blockposition, int i) { - generatoraccess.setTypeAndData(blockposition, (IBlockData) this.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.LOWER), i); - generatoraccess.setTypeAndData(blockposition.up(), (IBlockData) this.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.UPPER), i); - } - - @Override - public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, ItemStack itemstack) { - super.a(world, entityhuman, blockposition, Blocks.AIR.getBlockData(), tileentity, itemstack); - } - - @Override - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { - // CraftBukkit start - if (((WorldServer)world).hasPhysicsEvent && org.bukkit.craftbukkit.event.CraftEventFactory.callBlockPhysicsEvent(world, blockposition).isCancelled()) { // Paper - return; - } - // CraftBukkit end - BlockPropertyDoubleBlockHalf blockpropertydoubleblockhalf = (BlockPropertyDoubleBlockHalf) iblockdata.get(BlockTallPlant.HALF); - BlockPosition blockposition1 = blockpropertydoubleblockhalf == BlockPropertyDoubleBlockHalf.LOWER ? blockposition.up() : blockposition.down(); - IBlockData iblockdata1 = world.getType(blockposition1); - - if (iblockdata1.getBlock() == this && iblockdata1.get(BlockTallPlant.HALF) != blockpropertydoubleblockhalf) { - world.setTypeAndData(blockposition1, Blocks.AIR.getBlockData(), 35); - world.a(entityhuman, 2001, blockposition1, Block.getCombinedId(iblockdata1)); - if (!world.isClientSide && !entityhuman.isCreative()) { - dropItems(iblockdata, world, blockposition, (TileEntity) null, entityhuman, entityhuman.getItemInMainHand()); - dropItems(iblockdata1, world, blockposition1, (TileEntity) null, entityhuman, entityhuman.getItemInMainHand()); - } - } - - super.a(world, blockposition, iblockdata, entityhuman); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockTallPlant.HALF); - } - - @Override - public Block.EnumRandomOffset R_() { - return Block.EnumRandomOffset.XZ; - } -} diff --git a/src/main/java/net/minecraft/server/BlockTrapdoor.java b/src/main/java/net/minecraft/server/BlockTrapdoor.java deleted file mode 100644 index 015e8b6a1..000000000 --- a/src/main/java/net/minecraft/server/BlockTrapdoor.java +++ /dev/null @@ -1,166 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public class BlockTrapdoor extends BlockFacingHorizontal implements IBlockWaterlogged { - - public static final BlockStateBoolean OPEN = BlockProperties.u; - public static final BlockStateEnum HALF = BlockProperties.V; - public static final BlockStateBoolean c = BlockProperties.w; - public static final BlockStateBoolean d = BlockProperties.C; - protected static final VoxelShape e = Block.a(0.0D, 0.0D, 0.0D, 3.0D, 16.0D, 16.0D); - protected static final VoxelShape f = Block.a(13.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape g = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 3.0D); - protected static final VoxelShape h = Block.a(0.0D, 0.0D, 13.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape i = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 3.0D, 16.0D); - protected static final VoxelShape j = Block.a(0.0D, 13.0D, 0.0D, 16.0D, 16.0D, 16.0D); - - protected BlockTrapdoor(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockTrapdoor.FACING, EnumDirection.NORTH)).set(BlockTrapdoor.OPEN, false)).set(BlockTrapdoor.HALF, BlockPropertyHalf.BOTTOM)).set(BlockTrapdoor.c, false)).set(BlockTrapdoor.d, false)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - if (!(Boolean) iblockdata.get(BlockTrapdoor.OPEN)) { - return iblockdata.get(BlockTrapdoor.HALF) == BlockPropertyHalf.TOP ? BlockTrapdoor.j : BlockTrapdoor.i; - } else { - switch ((EnumDirection) iblockdata.get(BlockTrapdoor.FACING)) { - case NORTH: - default: - return BlockTrapdoor.h; - case SOUTH: - return BlockTrapdoor.g; - case WEST: - return BlockTrapdoor.f; - case EAST: - return BlockTrapdoor.e; - } - } - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - switch (pathmode) { - case LAND: - return (Boolean) iblockdata.get(BlockTrapdoor.OPEN); - case WATER: - return (Boolean) iblockdata.get(BlockTrapdoor.d); - case AIR: - return (Boolean) iblockdata.get(BlockTrapdoor.OPEN); - default: - return false; - } - } - - @Override - public boolean interact(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - if (this.material == Material.ORE) { - return false; - } else { - iblockdata = (IBlockData) iblockdata.a((IBlockState) BlockTrapdoor.OPEN); - world.setTypeAndData(blockposition, iblockdata, 2); - if ((Boolean) iblockdata.get(BlockTrapdoor.d)) { - world.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) world)); - } - - this.a(entityhuman, world, blockposition, (Boolean) iblockdata.get(BlockTrapdoor.OPEN)); - return true; - } - } - - protected void a(@Nullable EntityHuman entityhuman, World world, BlockPosition blockposition, boolean flag) { - int i; - - if (flag) { - i = this.material == Material.ORE ? 1037 : 1007; - world.a(entityhuman, i, blockposition, 0); - } else { - i = this.material == Material.ORE ? 1036 : 1013; - world.a(entityhuman, i, blockposition, 0); - } - - } - - @Override - public void doPhysics(IBlockData iblockdata, World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - if (!world.isClientSide) { - boolean flag1 = world.isBlockIndirectlyPowered(blockposition); - - if (flag1 != (Boolean) iblockdata.get(BlockTrapdoor.c)) { - // 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 = (Boolean) iblockdata.get(OPEN) ? 15 : 0; - - if (oldPower == 0 ^ power == 0 || block.getBlockData().isPowerSource()) { - BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(bblock, oldPower, power); - world.getServer().getPluginManager().callEvent(eventRedstone); - flag1 = eventRedstone.getNewCurrent() > 0; - } - // CraftBukkit end - if ((Boolean) iblockdata.get(BlockTrapdoor.OPEN) != flag1) { - iblockdata = (IBlockData) iblockdata.set(BlockTrapdoor.OPEN, flag1); - this.a((EntityHuman) null, world, blockposition, flag1); - } - - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockTrapdoor.c, flag1), 2); - if ((Boolean) iblockdata.get(BlockTrapdoor.d)) { - world.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) world)); - } - } - - } - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - IBlockData iblockdata = this.getBlockData(); - Fluid fluid = blockactioncontext.getWorld().getFluid(blockactioncontext.getClickPosition()); - EnumDirection enumdirection = blockactioncontext.getClickedFace(); - - if (!blockactioncontext.c() && enumdirection.k().c()) { - iblockdata = (IBlockData) ((IBlockData) iblockdata.set(BlockTrapdoor.FACING, enumdirection)).set(BlockTrapdoor.HALF, blockactioncontext.j().y - (double) blockactioncontext.getClickPosition().getY() > 0.5D ? BlockPropertyHalf.TOP : BlockPropertyHalf.BOTTOM); - } else { - iblockdata = (IBlockData) ((IBlockData) iblockdata.set(BlockTrapdoor.FACING, blockactioncontext.f().opposite())).set(BlockTrapdoor.HALF, enumdirection == EnumDirection.UP ? BlockPropertyHalf.BOTTOM : BlockPropertyHalf.TOP); - } - - if (blockactioncontext.getWorld().isBlockIndirectlyPowered(blockactioncontext.getClickPosition())) { - iblockdata = (IBlockData) ((IBlockData) iblockdata.set(BlockTrapdoor.OPEN, true)).set(BlockTrapdoor.c, true); - } - - return (IBlockData) iblockdata.set(BlockTrapdoor.d, fluid.getType() == FluidTypes.WATER); - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockTrapdoor.FACING, BlockTrapdoor.OPEN, BlockTrapdoor.HALF, BlockTrapdoor.c, BlockTrapdoor.d); - } - - @Override - public Fluid g(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockTrapdoor.d) ? FluidTypes.WATER.a(false) : super.g(iblockdata); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if ((Boolean) iblockdata.get(BlockTrapdoor.d)) { - generatoraccess.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) generatoraccess)); - } - - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EntityTypes entitytypes) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/BlockTripwire.java b/src/main/java/net/minecraft/server/BlockTripwire.java deleted file mode 100644 index cc323a8f0..000000000 --- a/src/main/java/net/minecraft/server/BlockTripwire.java +++ /dev/null @@ -1,226 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import org.bukkit.event.entity.EntityInteractEvent; // CraftBukkit - -public class BlockTripwire extends Block { - - public static final BlockStateBoolean POWERED = BlockProperties.w; - public static final BlockStateBoolean ATTACHED = BlockProperties.a; - public static final BlockStateBoolean DISARMED = BlockProperties.d; - public static final BlockStateBoolean NORTH = BlockSprawling.a; - public static final BlockStateBoolean EAST = BlockSprawling.b; - public static final BlockStateBoolean SOUTH = BlockSprawling.c; - public static final BlockStateBoolean WEST = BlockSprawling.d; - private static final Map j = BlockTall.f; - protected static final VoxelShape h = Block.a(0.0D, 1.0D, 0.0D, 16.0D, 2.5D, 16.0D); - protected static final VoxelShape i = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 8.0D, 16.0D); - private final BlockTripwireHook k; - - public BlockTripwire(BlockTripwireHook blocktripwirehook, Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockTripwire.POWERED, 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.k = blocktripwirehook; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return (Boolean) iblockdata.get(BlockTripwire.ATTACHED) ? BlockTripwire.h : BlockTripwire.i; - } - - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - World world = blockactioncontext.getWorld(); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.getBlockData().set(BlockTripwire.NORTH, this.a(world.getType(blockposition.north()), EnumDirection.NORTH))).set(BlockTripwire.EAST, this.a(world.getType(blockposition.east()), EnumDirection.EAST))).set(BlockTripwire.SOUTH, this.a(world.getType(blockposition.south()), EnumDirection.SOUTH))).set(BlockTripwire.WEST, this.a(world.getType(blockposition.west()), EnumDirection.WEST)); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return enumdirection.k().c() ? (IBlockData) iblockdata.set((IBlockState) BlockTripwire.j.get(enumdirection), this.a(iblockdata1, enumdirection)) : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Override - public TextureType c() { - return TextureType.TRANSLUCENT; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (iblockdata1.getBlock() != iblockdata.getBlock()) { - this.a(world, blockposition, iblockdata); - } - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (!flag && iblockdata.getBlock() != iblockdata1.getBlock()) { - this.a(world, blockposition, (IBlockData) iblockdata.set(BlockTripwire.POWERED, true)); - } - } - - @Override - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { - if (!world.isClientSide && !entityhuman.getItemInMainHand().isEmpty() && entityhuman.getItemInMainHand().getItem() == Items.SHEARS) { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockTripwire.DISARMED, true), 4); - } - - super.a(world, blockposition, iblockdata, entityhuman); - } - - private void a(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() == this.k) { - if (iblockdata1.get(BlockTripwireHook.FACING) == enumdirection.opposite()) { - this.k.a(world, blockposition1, iblockdata1, false, true, k, iblockdata); - } - } else if (iblockdata1.getBlock() == this) { - ++k; - continue; - } - } - - ++j; - break; - } - } - - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - if (!world.isClientSide) { - if (!(Boolean) iblockdata.get(BlockTripwire.POWERED)) { - this.a(world, blockposition); - } - } - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.isClientSide) { - if ((Boolean) world.getType(blockposition).get(BlockTripwire.POWERED)) { - this.a(world, blockposition); - } - } - } - - private void a(World world, BlockPosition blockposition) { - IBlockData iblockdata = world.getType(blockposition); - boolean flag = (Boolean) iblockdata.get(BlockTripwire.POWERED); - boolean flag1 = false; - List list = world.getEntities((Entity) null, iblockdata.getShape(world, blockposition).getBoundingBox().a(blockposition)); - - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (!entity.isIgnoreBlockTrigger()) { - flag1 = true; - break; - } - } - } - - // CraftBukkit start - Call interact even when triggering connected tripwire - if (flag != flag1 && flag1 && (Boolean)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 (Object 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, null); - } else if (object instanceof Entity) { - cancellable = new EntityInteractEvent(((Entity) object).getBukkitEntity(), block); - manager.callEvent((EntityInteractEvent) cancellable); - } else { - continue; - } - - if (!cancellable.isCancelled()) { - allowed = true; - break; - } - } - } - - if (!allowed) { - return; - } - } - // CraftBukkit end - - if (flag1 != flag) { - iblockdata = (IBlockData) iblockdata.set(BlockTripwire.POWERED, flag1); - world.setTypeAndData(blockposition, iblockdata, 3); - this.a(world, blockposition, iblockdata); - } - - if (flag1) { - world.getBlockTickList().a(new BlockPosition(blockposition), this, this.a((IWorldReader) world)); - } - - } - - public boolean a(IBlockData iblockdata, EnumDirection enumdirection) { - Block block = iblockdata.getBlock(); - - return block == this.k ? iblockdata.get(BlockTripwireHook.FACING) == enumdirection.opposite() : block == this; - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - switch (enumblockrotation) { - case CLOCKWISE_180: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockTripwire.NORTH, iblockdata.get(BlockTripwire.SOUTH))).set(BlockTripwire.EAST, iblockdata.get(BlockTripwire.WEST))).set(BlockTripwire.SOUTH, iblockdata.get(BlockTripwire.NORTH))).set(BlockTripwire.WEST, iblockdata.get(BlockTripwire.EAST)); - case COUNTERCLOCKWISE_90: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockTripwire.NORTH, iblockdata.get(BlockTripwire.EAST))).set(BlockTripwire.EAST, iblockdata.get(BlockTripwire.SOUTH))).set(BlockTripwire.SOUTH, iblockdata.get(BlockTripwire.WEST))).set(BlockTripwire.WEST, iblockdata.get(BlockTripwire.NORTH)); - case CLOCKWISE_90: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockTripwire.NORTH, iblockdata.get(BlockTripwire.WEST))).set(BlockTripwire.EAST, iblockdata.get(BlockTripwire.NORTH))).set(BlockTripwire.SOUTH, iblockdata.get(BlockTripwire.EAST))).set(BlockTripwire.WEST, iblockdata.get(BlockTripwire.SOUTH)); - default: - return iblockdata; - } - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - switch (enumblockmirror) { - case LEFT_RIGHT: - return (IBlockData) ((IBlockData) iblockdata.set(BlockTripwire.NORTH, iblockdata.get(BlockTripwire.SOUTH))).set(BlockTripwire.SOUTH, iblockdata.get(BlockTripwire.NORTH)); - case FRONT_BACK: - return (IBlockData) ((IBlockData) iblockdata.set(BlockTripwire.EAST, iblockdata.get(BlockTripwire.WEST))).set(BlockTripwire.WEST, iblockdata.get(BlockTripwire.EAST)); - default: - return super.a(iblockdata, enumblockmirror); - } - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockTripwire.POWERED, BlockTripwire.ATTACHED, BlockTripwire.DISARMED, BlockTripwire.NORTH, BlockTripwire.EAST, BlockTripwire.WEST, BlockTripwire.SOUTH); - } -} diff --git a/src/main/java/net/minecraft/server/BlockTripwireHook.java b/src/main/java/net/minecraft/server/BlockTripwireHook.java deleted file mode 100644 index cc99708e8..000000000 --- a/src/main/java/net/minecraft/server/BlockTripwireHook.java +++ /dev/null @@ -1,250 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.MoreObjects; -import java.util.Random; -import javax.annotation.Nullable; - -import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit - -public class BlockTripwireHook extends Block { - - public static final BlockStateDirection FACING = BlockFacingHorizontal.FACING; - public static final BlockStateBoolean POWERED = BlockProperties.w; - public static final BlockStateBoolean ATTACHED = BlockProperties.a; - protected static final VoxelShape d = Block.a(5.0D, 0.0D, 10.0D, 11.0D, 10.0D, 16.0D); - protected static final VoxelShape e = Block.a(5.0D, 0.0D, 0.0D, 11.0D, 10.0D, 6.0D); - protected static final VoxelShape f = Block.a(10.0D, 0.0D, 5.0D, 16.0D, 10.0D, 11.0D); - protected static final VoxelShape g = Block.a(0.0D, 0.0D, 5.0D, 6.0D, 10.0D, 11.0D); - - public BlockTripwireHook(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockTripwireHook.FACING, EnumDirection.NORTH)).set(BlockTripwireHook.POWERED, false)).set(BlockTripwireHook.ATTACHED, false)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - switch ((EnumDirection) iblockdata.get(BlockTripwireHook.FACING)) { - case EAST: - default: - return BlockTripwireHook.g; - case WEST: - return BlockTripwireHook.f; - case SOUTH: - return BlockTripwireHook.e; - case NORTH: - return BlockTripwireHook.d; - } - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockTripwireHook.FACING); - BlockPosition blockposition1 = blockposition.shift(enumdirection.opposite()); - IBlockData iblockdata1 = iworldreader.getType(blockposition1); - - return enumdirection.k().c() && iblockdata1.d(iworldreader, blockposition1, enumdirection) && !iblockdata1.isPowerSource(); - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return enumdirection.opposite() == iblockdata.get(BlockTripwireHook.FACING) && !iblockdata.canPlace(generatoraccess, blockposition) ? Blocks.AIR.getBlockData() : super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - IBlockData iblockdata = (IBlockData) ((IBlockData) this.getBlockData().set(BlockTripwireHook.POWERED, false)).set(BlockTripwireHook.ATTACHED, false); - World world = blockactioncontext.getWorld(); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - EnumDirection[] aenumdirection = blockactioncontext.e(); - EnumDirection[] aenumdirection1 = aenumdirection; - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection1[j]; - - if (enumdirection.k().c()) { - EnumDirection enumdirection1 = enumdirection.opposite(); - - iblockdata = (IBlockData) iblockdata.set(BlockTripwireHook.FACING, enumdirection1); - if (iblockdata.canPlace(world, blockposition)) { - return iblockdata; - } - } - } - - return null; - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { - this.a(world, blockposition, iblockdata, false, false, -1, (IBlockData) null); - } - - public void a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag, boolean flag1, int i, @Nullable IBlockData iblockdata1) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockTripwireHook.FACING); - boolean flag2 = (Boolean) iblockdata.get(BlockTripwireHook.ATTACHED); - boolean flag3 = (Boolean) iblockdata.get(BlockTripwireHook.POWERED); - boolean flag4 = !flag; - boolean flag5 = 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; - flag4 = false; - } else { - if (k == i) { - iblockdata2 = (IBlockData) MoreObjects.firstNonNull(iblockdata1, iblockdata2); - } - - boolean flag6 = !(Boolean) iblockdata2.get(BlockTripwire.DISARMED); - boolean flag7 = (Boolean) iblockdata2.get(BlockTripwire.POWERED); - - flag5 |= flag6 && flag7; - aiblockdata[k] = iblockdata2; - if (k == i) { - world.getBlockTickList().a(blockposition, this, this.a((IWorldReader) world)); - flag4 &= flag6; - } - } - } - - flag4 &= j > 1; - flag5 &= flag4; - IBlockData iblockdata3 = (IBlockData) ((IBlockData) this.getBlockData().set(BlockTripwireHook.ATTACHED, flag4)).set(BlockTripwireHook.POWERED, flag5); - - if (j > 0) { - blockposition1 = blockposition.shift(enumdirection, j); - EnumDirection enumdirection1 = enumdirection.opposite(); - - world.setTypeAndData(blockposition1, (IBlockData) iblockdata3.set(BlockTripwireHook.FACING, enumdirection1), 3); - this.a(world, blockposition1, enumdirection1); - this.a(world, blockposition1, flag4, flag5, 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, flag4, flag5, flag2, flag3); - if (!flag) { - world.setTypeAndData(blockposition, (IBlockData) iblockdata3.set(BlockTripwireHook.FACING, enumdirection), 3); - if (flag1) { - this.a(world, blockposition, enumdirection); - } - } - - if (flag2 != flag4) { - for (int l = 1; l < j; ++l) { - BlockPosition blockposition2 = blockposition.shift(enumdirection, l); - IBlockData iblockdata4 = aiblockdata[l]; - - if (iblockdata4 != null) { - world.setTypeAndData(blockposition2, (IBlockData) iblockdata4.set(BlockTripwireHook.ATTACHED, flag4), 3); - if (!world.getType(blockposition2).isAir()) { - ; - } - } - } - } - - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - this.a(world, blockposition, iblockdata, false, true, -1, (IBlockData) null); - } - - private void a(World world, BlockPosition blockposition, boolean flag, boolean flag1, boolean flag2, boolean flag3) { - if (flag1 && !flag3) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_TRIPWIRE_CLICK_ON, SoundCategory.BLOCKS, 0.4F, 0.6F); - } else if (!flag1 && flag3) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_TRIPWIRE_CLICK_OFF, SoundCategory.BLOCKS, 0.4F, 0.5F); - } else if (flag && !flag2) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_TRIPWIRE_ATTACH, SoundCategory.BLOCKS, 0.4F, 0.7F); - } else if (!flag && flag2) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_TRIPWIRE_DETACH, SoundCategory.BLOCKS, 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); - } - - @Override - public void remove(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (!flag && iblockdata.getBlock() != iblockdata1.getBlock()) { - boolean flag1 = (Boolean) iblockdata.get(BlockTripwireHook.ATTACHED); - boolean flag2 = (Boolean) iblockdata.get(BlockTripwireHook.POWERED); - - if (flag1 || flag2) { - this.a(world, blockposition, iblockdata, true, false, -1, (IBlockData) null); - } - - if (flag2) { - world.applyPhysics(blockposition, this); - world.applyPhysics(blockposition.shift(((EnumDirection) iblockdata.get(BlockTripwireHook.FACING)).opposite()), this); - } - - super.remove(iblockdata, world, blockposition, iblockdata1, flag); - } - } - - @Override - public int a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return (Boolean) iblockdata.get(BlockTripwireHook.POWERED) ? 15 : 0; - } - - @Override - public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return !(Boolean) iblockdata.get(BlockTripwireHook.POWERED) ? 0 : (iblockdata.get(BlockTripwireHook.FACING) == enumdirection ? 15 : 0); - } - - @Override - public boolean isPowerSource(IBlockData iblockdata) { - return true; - } - - @Override - public TextureType c() { - return TextureType.CUTOUT_MIPPED; - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - return (IBlockData) iblockdata.set(BlockTripwireHook.FACING, enumblockrotation.a((EnumDirection) iblockdata.get(BlockTripwireHook.FACING))); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - return iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockTripwireHook.FACING))); - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockTripwireHook.FACING, BlockTripwireHook.POWERED, BlockTripwireHook.ATTACHED); - } -} diff --git a/src/main/java/net/minecraft/server/BlockTurtleEgg.java b/src/main/java/net/minecraft/server/BlockTurtleEgg.java deleted file mode 100644 index 0118a8451..000000000 --- a/src/main/java/net/minecraft/server/BlockTurtleEgg.java +++ /dev/null @@ -1,168 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; -import org.bukkit.craftbukkit.block.CraftBlock; - -// CraftBukkit start -import org.bukkit.event.entity.EntityInteractEvent; -import org.bukkit.craftbukkit.event.CraftEventFactory; -// CraftBukkit end - -public class BlockTurtleEgg extends Block { - - private static final VoxelShape c = Block.a(3.0D, 0.0D, 3.0D, 12.0D, 7.0D, 12.0D); - private static final VoxelShape d = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 7.0D, 15.0D); - public static final BlockStateInteger a = BlockProperties.aj; - public static final BlockStateInteger b = BlockProperties.ai; - - public BlockTurtleEgg(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockTurtleEgg.a, 0)).set(BlockTurtleEgg.b, 1)); - } - - @Override - public void stepOn(World world, BlockPosition blockposition, Entity entity) { - this.a(world, blockposition, entity, 100); - super.stepOn(world, blockposition, entity); - } - - @Override - public void fallOn(World world, BlockPosition blockposition, Entity entity, float f) { - if (!(entity instanceof EntityZombie)) { - this.a(world, blockposition, entity, 3); - } - - super.fallOn(world, blockposition, entity, f); - } - - private void a(World world, BlockPosition blockposition, Entity entity, int i) { - if (!this.a(world, entity)) { - super.stepOn(world, blockposition, entity); - } else { - if (!world.isClientSide && world.random.nextInt(i) == 0) { - // CraftBukkit start - Step on eggs - org.bukkit.event.Cancellable cancellable; - if (entity instanceof EntityHuman) { - cancellable = CraftEventFactory.callPlayerInteractEvent((EntityHuman) entity, org.bukkit.event.block.Action.PHYSICAL, blockposition, null, null, null); - } else { - cancellable = new EntityInteractEvent(entity.getBukkitEntity(), CraftBlock.at(world, blockposition)); - world.getServer().getPluginManager().callEvent((EntityInteractEvent) cancellable); - } - - if (cancellable.isCancelled()) { - return; - } - // CraftBukkit end - this.a(world, blockposition, world.getType(blockposition)); - } - - } - } - - private void a(World world, BlockPosition blockposition, IBlockData iblockdata) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.ENTITY_TURTLE_EGG_BREAK, SoundCategory.BLOCKS, 0.7F, 0.9F + world.random.nextFloat() * 0.2F); - int i = (Integer) iblockdata.get(BlockTurtleEgg.b); - - if (i <= 1) { - world.b(blockposition, false); - } else { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockTurtleEgg.b, i - 1), 2); - world.triggerEffect(2001, blockposition, Block.getCombinedId(iblockdata)); - } - - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (this.a(world) && this.a((IBlockAccess) world, blockposition)) { - int i = (Integer) iblockdata.get(BlockTurtleEgg.a); - - if (i < 2) { - // CraftBukkit start - Call BlockGrowEvent - if (!CraftEventFactory.handleBlockGrowEvent(world, blockposition, iblockdata.set(BlockTurtleEgg.a, i + 1), 2)) { - return; - } - // CraftBukkit end - world.playSound((EntityHuman) null, blockposition, SoundEffects.ENTITY_TURTLE_EGG_CRACK, SoundCategory.BLOCKS, 0.7F, 0.9F + random.nextFloat() * 0.2F); - // world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockTurtleEgg.a, i + 1), 2); // CraftBukkit - handled above - } else { - // CraftBukkit start - Call BlockFadeEvent - if (CraftEventFactory.callBlockFadeEvent(world, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - world.playSound((EntityHuman) null, blockposition, SoundEffects.ENTITY_TURTLE_EGG_HATCH, SoundCategory.BLOCKS, 0.7F, 0.9F + random.nextFloat() * 0.2F); - world.a(blockposition, false); - if (!world.isClientSide) { - for (int j = 0; j < (Integer) iblockdata.get(BlockTurtleEgg.b); ++j) { - world.triggerEffect(2001, blockposition, Block.getCombinedId(iblockdata)); - EntityTurtle entityturtle = (EntityTurtle) EntityTypes.TURTLE.a(world); - - entityturtle.setAgeRaw(-24000); - entityturtle.g(blockposition); - entityturtle.setPositionRotation((double) blockposition.getX() + 0.3D + (double) j * 0.2D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.3D, 0.0F, 0.0F); - world.addEntity(entityturtle, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.EGG); // CraftBukkit - } - } - } - } - - } - - private boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { - return iblockaccess.getType(blockposition.down()).getBlock() == Blocks.SAND; - } - - @Override - public void onPlace(IBlockData iblockdata, World world, BlockPosition blockposition, IBlockData iblockdata1, boolean flag) { - if (this.a((IBlockAccess) world, blockposition) && !world.isClientSide) { - world.triggerEffect(2005, blockposition, 0); - } - - } - - private boolean a(World world) { - float f = world.j(1.0F); - - return (double) f < 0.69D && (double) f > 0.65D ? true : world.random.nextInt(500) == 0; - } - - @Override - public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, ItemStack itemstack) { - super.a(world, entityhuman, blockposition, iblockdata, tileentity, itemstack); - this.a(world, blockposition, iblockdata); - } - - @Override - public boolean a(IBlockData iblockdata, BlockActionContext blockactioncontext) { - return blockactioncontext.getItemStack().getItem() == this.getItem() && (Integer) iblockdata.get(BlockTurtleEgg.b) < 4 ? true : super.a(iblockdata, blockactioncontext); - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - IBlockData iblockdata = blockactioncontext.getWorld().getType(blockactioncontext.getClickPosition()); - - return iblockdata.getBlock() == this ? (IBlockData) iblockdata.set(BlockTurtleEgg.b, Math.min(4, (Integer) iblockdata.get(BlockTurtleEgg.b) + 1)) : super.getPlacedState(blockactioncontext); - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return (Integer) iblockdata.get(BlockTurtleEgg.b) > 1 ? BlockTurtleEgg.d : BlockTurtleEgg.c; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockTurtleEgg.a, BlockTurtleEgg.b); - } - - private boolean a(World world, Entity entity) { - return entity instanceof EntityTurtle ? false : (entity instanceof EntityLiving && !(entity instanceof EntityHuman) ? world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) : true); - } -} diff --git a/src/main/java/net/minecraft/server/BlockVine.java b/src/main/java/net/minecraft/server/BlockVine.java deleted file mode 100644 index 455dae92a..000000000 --- a/src/main/java/net/minecraft/server/BlockVine.java +++ /dev/null @@ -1,368 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Map; -import java.util.Random; -import java.util.Map.Entry; -import javax.annotation.Nullable; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class BlockVine extends Block { - - public static final BlockStateBoolean UP = BlockSprawling.e; - public static final BlockStateBoolean NORTH = BlockSprawling.a; - public static final BlockStateBoolean EAST = BlockSprawling.b; - public static final BlockStateBoolean SOUTH = BlockSprawling.c; - public static final BlockStateBoolean WEST = BlockSprawling.d; - public static final Map f = (Map) BlockSprawling.g.entrySet().stream().filter((entry) -> { - return entry.getKey() != EnumDirection.DOWN; - }).collect(SystemUtils.a()); - protected static final VoxelShape g = Block.a(0.0D, 15.0D, 0.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape h = Block.a(0.0D, 0.0D, 0.0D, 1.0D, 16.0D, 16.0D); - protected static final VoxelShape i = Block.a(15.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape j = Block.a(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 1.0D); - protected static final VoxelShape k = Block.a(0.0D, 0.0D, 15.0D, 16.0D, 16.0D, 16.0D); - - public BlockVine(Block.Info block_info) { - super(block_info); - this.o((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockVine.UP, false)).set(BlockVine.NORTH, false)).set(BlockVine.EAST, false)).set(BlockVine.SOUTH, false)).set(BlockVine.WEST, false)); - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - VoxelShape voxelshape = VoxelShapes.a(); - - if ((Boolean) iblockdata.get(BlockVine.UP)) { - voxelshape = VoxelShapes.a(voxelshape, BlockVine.g); - } - - if ((Boolean) iblockdata.get(BlockVine.NORTH)) { - voxelshape = VoxelShapes.a(voxelshape, BlockVine.j); - } - - if ((Boolean) iblockdata.get(BlockVine.EAST)) { - voxelshape = VoxelShapes.a(voxelshape, BlockVine.i); - } - - if ((Boolean) iblockdata.get(BlockVine.SOUTH)) { - voxelshape = VoxelShapes.a(voxelshape, BlockVine.k); - } - - if ((Boolean) iblockdata.get(BlockVine.WEST)) { - voxelshape = VoxelShapes.a(voxelshape, BlockVine.h); - } - - return voxelshape; - } - - @Override - public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { - return this.j(this.m(iblockdata, iworldreader, blockposition)); - } - - private boolean j(IBlockData iblockdata) { - return this.q(iblockdata) > 0; - } - - private int q(IBlockData iblockdata) { - int i = 0; - Iterator iterator = BlockVine.f.values().iterator(); - - while (iterator.hasNext()) { - BlockStateBoolean blockstateboolean = (BlockStateBoolean) iterator.next(); - - if ((Boolean) iblockdata.get(blockstateboolean)) { - ++i; - } - } - - return i; - } - - private boolean b(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - if (enumdirection == EnumDirection.DOWN) { - return false; - } else { - BlockPosition blockposition1 = blockposition.shift(enumdirection); - - if (a(iblockaccess, blockposition1, enumdirection)) { - return true; - } else if (enumdirection.k() == EnumDirection.EnumAxis.Y) { - return false; - } else { - BlockStateBoolean blockstateboolean = (BlockStateBoolean) BlockVine.f.get(enumdirection); - IBlockData iblockdata = iblockaccess.getType(blockposition.up()); - - return iblockdata.getBlock() == this && (Boolean) iblockdata.get(blockstateboolean); - } - } - } - - public static boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - IBlockData iblockdata = iblockaccess.getType(blockposition); - - return Block.a(iblockdata.getCollisionShape(iblockaccess, blockposition), enumdirection.opposite()); - } - - private IBlockData m(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.up(); - - if ((Boolean) iblockdata.get(BlockVine.UP)) { - iblockdata = (IBlockData) iblockdata.set(BlockVine.UP, a(iblockaccess, blockposition1, EnumDirection.DOWN)); - } - - IBlockData iblockdata1 = null; - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - BlockStateBoolean blockstateboolean = getDirection(enumdirection); - - if ((Boolean) iblockdata.get(blockstateboolean)) { - boolean flag = this.b(iblockaccess, blockposition, enumdirection); - - if (!flag) { - if (iblockdata1 == null) { - iblockdata1 = iblockaccess.getType(blockposition1); - } - - flag = iblockdata1.getBlock() == this && (Boolean) iblockdata1.get(blockstateboolean); - } - - iblockdata = (IBlockData) iblockdata.set(blockstateboolean, flag); - } - } - - return iblockdata; - } - - @Override - public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - if (enumdirection == EnumDirection.DOWN) { - return super.updateState(iblockdata, enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - } else { - IBlockData iblockdata2 = this.m(iblockdata, generatoraccess, blockposition); - - return !this.j(iblockdata2) ? Blocks.AIR.getBlockData() : iblockdata2; - } - } - - @Override - public void tick(IBlockData iblockdata, World world, BlockPosition blockposition, Random random) { - if (!world.isClientSide) { - IBlockData iblockdata1 = this.m(iblockdata, world, blockposition); - - if (iblockdata1 != iblockdata) { - if (this.j(iblockdata1)) { - world.setTypeAndData(blockposition, iblockdata1, 2); - } else { - c(iblockdata, world, blockposition); - world.a(blockposition, false); - } - - } else if (world.random.nextInt(Math.max(1, (int) (100.0F / world.spigotConfig.vineModifier) * 4)) == 0) { // Spigot - EnumDirection enumdirection = EnumDirection.a(random); - BlockPosition blockposition1 = blockposition.up(); - BlockPosition blockposition2; - IBlockData iblockdata2; - EnumDirection enumdirection1; - - if (enumdirection.k().c() && !(Boolean) iblockdata.get(getDirection(enumdirection))) { - if (this.a((IBlockAccess) world, blockposition)) { - blockposition2 = blockposition.shift(enumdirection); - iblockdata2 = world.getType(blockposition2); - if (iblockdata2.isAir()) { - enumdirection1 = enumdirection.e(); - EnumDirection enumdirection2 = enumdirection.f(); - boolean flag = (Boolean) iblockdata.get(getDirection(enumdirection1)); - boolean flag1 = (Boolean) iblockdata.get(getDirection(enumdirection2)); - BlockPosition blockposition3 = blockposition2.shift(enumdirection1); - BlockPosition blockposition4 = blockposition2.shift(enumdirection2); - - // CraftBukkit start - Call BlockSpreadEvent - BlockPosition source = blockposition; - - if (flag && a((IBlockAccess) world, blockposition3, enumdirection1)) { - CraftEventFactory.handleBlockSpreadEvent(world, source, blockposition2, (IBlockData) this.getBlockData().set(getDirection(enumdirection1), true), 2); - } else if (flag1 && a((IBlockAccess) world, blockposition4, enumdirection2)) { - CraftEventFactory.handleBlockSpreadEvent(world, source, blockposition2, (IBlockData) this.getBlockData().set(getDirection(enumdirection2), true), 2); - } else { - EnumDirection enumdirection3 = enumdirection.opposite(); - - if (flag && world.isEmpty(blockposition3) && a((IBlockAccess) world, blockposition.shift(enumdirection1), enumdirection3)) { - CraftEventFactory.handleBlockSpreadEvent(world, source, blockposition3, (IBlockData) this.getBlockData().set(getDirection(enumdirection3), true), 2); - } else if (flag1 && world.isEmpty(blockposition4) && a((IBlockAccess) world, blockposition.shift(enumdirection2), enumdirection3)) { - CraftEventFactory.handleBlockSpreadEvent(world, source, blockposition4, (IBlockData) this.getBlockData().set(getDirection(enumdirection3), true), 2); - } else if ((double) world.random.nextFloat() < 0.05D && a((IBlockAccess) world, blockposition2.up(), EnumDirection.UP)) { - CraftEventFactory.handleBlockSpreadEvent(world, source, blockposition2, (IBlockData) this.getBlockData().set(BlockVine.UP, true), 2); - } - // CraftBukkit end - } - } else if (a((IBlockAccess) world, blockposition2, enumdirection)) { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(getDirection(enumdirection), true), 2); - } - - } - } else { - if (enumdirection == EnumDirection.UP && blockposition.getY() < 255) { - if (this.b((IBlockAccess) world, blockposition, enumdirection)) { - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockVine.UP, true), 2); - return; - } - - if (world.isEmpty(blockposition1)) { - if (!this.a((IBlockAccess) world, blockposition)) { - return; - } - - IBlockData iblockdata3 = iblockdata; - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - enumdirection1 = (EnumDirection) iterator.next(); - if (random.nextBoolean() || !a((IBlockAccess) world, blockposition1.shift(enumdirection1), EnumDirection.UP)) { - iblockdata3 = (IBlockData) iblockdata3.set(getDirection(enumdirection1), false); - } - } - - if (this.canSpread(iblockdata3)) { - CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition1, iblockdata3, 2); // CraftBukkit - } - - return; - } - } - - if (blockposition.getY() > 0) { - blockposition2 = blockposition.down(); - iblockdata2 = world.getType(blockposition2); - if (iblockdata2.isAir() || iblockdata2.getBlock() == this) { - IBlockData iblockdata4 = iblockdata2.isAir() ? this.getBlockData() : iblockdata2; - IBlockData iblockdata5 = this.a(iblockdata, iblockdata4, random); - - if (iblockdata4 != iblockdata5 && this.canSpread(iblockdata5)) { - CraftEventFactory.handleBlockSpreadEvent(world, blockposition, blockposition2, iblockdata5, 2); // CraftBukkit - } - } - } - - } - } - } - } - - private IBlockData a(IBlockData iblockdata, IBlockData iblockdata1, Random random) { - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - - if (random.nextBoolean()) { - BlockStateBoolean blockstateboolean = getDirection(enumdirection); - - if ((Boolean) iblockdata.get(blockstateboolean)) { - iblockdata1 = (IBlockData) iblockdata1.set(blockstateboolean, true); - } - } - } - - return iblockdata1; - } - - private boolean canSpread(IBlockData iblockdata) { - return (Boolean) iblockdata.get(BlockVine.NORTH) || (Boolean) iblockdata.get(BlockVine.EAST) || (Boolean) iblockdata.get(BlockVine.SOUTH) || (Boolean) iblockdata.get(BlockVine.WEST); - } - - private boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { - boolean flag = true; - Iterable iterable = BlockPosition.b(blockposition.getX() - 4, blockposition.getY() - 1, blockposition.getZ() - 4, blockposition.getX() + 4, blockposition.getY() + 1, blockposition.getZ() + 4); - int i = 5; - Iterator iterator = iterable.iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition1 = (BlockPosition) iterator.next(); - - if (iblockaccess.getType(blockposition1).getBlock() == this) { - --i; - if (i <= 0) { - return false; - } - } - } - - return true; - } - - @Override - public boolean a(IBlockData iblockdata, BlockActionContext blockactioncontext) { - IBlockData iblockdata1 = blockactioncontext.getWorld().getType(blockactioncontext.getClickPosition()); - - return iblockdata1.getBlock() == this ? this.q(iblockdata1) < BlockVine.f.size() : super.a(iblockdata, blockactioncontext); - } - - @Nullable - @Override - public IBlockData getPlacedState(BlockActionContext blockactioncontext) { - IBlockData iblockdata = blockactioncontext.getWorld().getType(blockactioncontext.getClickPosition()); - boolean flag = iblockdata.getBlock() == this; - IBlockData iblockdata1 = flag ? iblockdata : this.getBlockData(); - EnumDirection[] aenumdirection = blockactioncontext.e(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - if (enumdirection != EnumDirection.DOWN) { - BlockStateBoolean blockstateboolean = getDirection(enumdirection); - boolean flag1 = flag && (Boolean) iblockdata.get(blockstateboolean); - - if (!flag1 && this.b((IBlockAccess) blockactioncontext.getWorld(), blockactioncontext.getClickPosition(), enumdirection)) { - return (IBlockData) iblockdata1.set(blockstateboolean, true); - } - } - } - - return flag ? iblockdata1 : null; - } - - @Override - public TextureType c() { - return TextureType.CUTOUT; - } - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(BlockVine.UP, BlockVine.NORTH, BlockVine.EAST, BlockVine.SOUTH, BlockVine.WEST); - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { - switch (enumblockrotation) { - case CLOCKWISE_180: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockVine.NORTH, iblockdata.get(BlockVine.SOUTH))).set(BlockVine.EAST, iblockdata.get(BlockVine.WEST))).set(BlockVine.SOUTH, iblockdata.get(BlockVine.NORTH))).set(BlockVine.WEST, iblockdata.get(BlockVine.EAST)); - case COUNTERCLOCKWISE_90: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockVine.NORTH, iblockdata.get(BlockVine.EAST))).set(BlockVine.EAST, iblockdata.get(BlockVine.SOUTH))).set(BlockVine.SOUTH, iblockdata.get(BlockVine.WEST))).set(BlockVine.WEST, iblockdata.get(BlockVine.NORTH)); - case CLOCKWISE_90: - return (IBlockData) ((IBlockData) ((IBlockData) ((IBlockData) iblockdata.set(BlockVine.NORTH, iblockdata.get(BlockVine.WEST))).set(BlockVine.EAST, iblockdata.get(BlockVine.NORTH))).set(BlockVine.SOUTH, iblockdata.get(BlockVine.EAST))).set(BlockVine.WEST, iblockdata.get(BlockVine.SOUTH)); - default: - return iblockdata; - } - } - - @Override - public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { - switch (enumblockmirror) { - case LEFT_RIGHT: - return (IBlockData) ((IBlockData) iblockdata.set(BlockVine.NORTH, iblockdata.get(BlockVine.SOUTH))).set(BlockVine.SOUTH, iblockdata.get(BlockVine.NORTH)); - case FRONT_BACK: - return (IBlockData) ((IBlockData) iblockdata.set(BlockVine.EAST, iblockdata.get(BlockVine.WEST))).set(BlockVine.WEST, iblockdata.get(BlockVine.EAST)); - default: - return super.a(iblockdata, enumblockmirror); - } - } - - public static BlockStateBoolean getDirection(EnumDirection enumdirection) { - return (BlockStateBoolean) BlockVine.f.get(enumdirection); - } -} diff --git a/src/main/java/net/minecraft/server/BlockWaterLily.java b/src/main/java/net/minecraft/server/BlockWaterLily.java deleted file mode 100644 index 7dc4fd0e2..000000000 --- a/src/main/java/net/minecraft/server/BlockWaterLily.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.minecraft.server; - -public class BlockWaterLily extends BlockPlant { - - protected static final VoxelShape a = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 1.5D, 15.0D); - - protected BlockWaterLily(Block.Info block_info) { - super(block_info); - } - - @Override - public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Entity entity) { - super.a(iblockdata, world, blockposition, entity); - if (entity instanceof EntityBoat && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(entity, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { // CraftBukkit - world.b(new BlockPosition(blockposition), true); - } - - } - - @Override - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return BlockWaterLily.a; - } - - @Override - protected boolean a_(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - Fluid fluid = iblockaccess.getFluid(blockposition); - - return fluid.getType() == FluidTypes.WATER || iblockdata.getMaterial() == Material.ICE; - } -} diff --git a/src/main/java/net/minecraft/server/BlockWitherSkull.java b/src/main/java/net/minecraft/server/BlockWitherSkull.java deleted file mode 100644 index e38afada4..000000000 --- a/src/main/java/net/minecraft/server/BlockWitherSkull.java +++ /dev/null @@ -1,110 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.util.BlockStateListPopulator; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; -// CraftBukkit end - -public class BlockWitherSkull extends BlockSkull { - - @Nullable - private static ShapeDetector c; - @Nullable - private static ShapeDetector d; - - protected BlockWitherSkull(Block.Info block_info) { - super(BlockSkull.Type.WITHER_SKELETON, block_info); - } - - @Override - public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, @Nullable EntityLiving entityliving, ItemStack itemstack) { - super.postPlace(world, blockposition, iblockdata, entityliving, itemstack); - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntitySkull) { - a(world, blockposition, (TileEntitySkull) tileentity); - } - - } - - public static void a(World world, BlockPosition blockposition, TileEntitySkull tileentityskull) { - if (world.captureBlockStates) return; // CraftBukkit - if (!world.isClientSide) { - Block block = tileentityskull.getBlock().getBlock(); - boolean flag = block == Blocks.WITHER_SKELETON_SKULL || block == Blocks.WITHER_SKELETON_WALL_SKULL; - - if (flag && blockposition.getY() >= 2 && world.getDifficulty() != EnumDifficulty.PEACEFUL) { - ShapeDetector shapedetector = d(); - ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = shapedetector.a(world, blockposition); - - if (shapedetector_shapedetectorcollection != null) { - // CraftBukkit start - Use BlockStateListPopulator - BlockStateListPopulator blockList = new BlockStateListPopulator(world); - for (int i = 0; i < shapedetector.c(); ++i) { - for (int j = 0; j < shapedetector.b(); ++j) { - ShapeDetectorBlock shapedetectorblock = shapedetector_shapedetectorcollection.a(i, j, 0); - - blockList.setTypeAndData(shapedetectorblock.getPosition(), Blocks.AIR.getBlockData(), 2); // CraftBukkit - // world.triggerEffect(2001, shapedetectorblock.getPosition(), Block.getCombinedId(shapedetectorblock.a())); // CraftBukkit - } - } - - EntityWither entitywither = (EntityWither) EntityTypes.WITHER.a(world); - BlockPosition blockposition1 = shapedetector_shapedetectorcollection.a(1, 2, 0).getPosition(); - - entitywither.setPositionRotation((double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 0.55D, (double) blockposition1.getZ() + 0.5D, shapedetector_shapedetectorcollection.getFacing().k() == EnumDirection.EnumAxis.X ? 0.0F : 90.0F, 0.0F); - entitywither.aK = shapedetector_shapedetectorcollection.getFacing().k() == EnumDirection.EnumAxis.X ? 0.0F : 90.0F; - entitywither.l(); - // CraftBukkit start - if (!world.addEntity(entitywither, SpawnReason.BUILD_WITHER)) { - return; - } - for (BlockPosition pos : blockList.getBlocks()) { - world.triggerEffect(2001, pos, Block.getCombinedId(world.getType(pos))); - } - blockList.updateList(); - // CraftBukkit end - Iterator iterator = world.a(EntityPlayer.class, entitywither.getBoundingBox().g(50.0D)).iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - CriterionTriggers.n.a(entityplayer, (Entity) entitywither); - } - - // world.addEntity(entitywither); // CraftBukkit - moved up - - for (int k = 0; k < shapedetector.c(); ++k) { - for (int l = 0; l < shapedetector.b(); ++l) { - world.update(shapedetector_shapedetectorcollection.a(k, l, 0).getPosition(), Blocks.AIR); - } - } - - } - } - } - } - - public static boolean b(World world, BlockPosition blockposition, ItemStack itemstack) { - return itemstack.getItem() == Items.WITHER_SKELETON_SKULL && blockposition.getY() >= 2 && world.getDifficulty() != EnumDifficulty.PEACEFUL && !world.isClientSide ? e().a(world, blockposition) != null : false; - } - - private static ShapeDetector d() { - if (BlockWitherSkull.c == null) { - BlockWitherSkull.c = ShapeDetectorBuilder.a().a("^^^", "###", "~#~").a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.SOUL_SAND))).a('^', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.WITHER_SKELETON_SKULL).or(BlockStatePredicate.a(Blocks.WITHER_SKELETON_WALL_SKULL)))).a('~', ShapeDetectorBlock.a(MaterialPredicate.a(Material.AIR))).b(); - } - - return BlockWitherSkull.c; - } - - private static ShapeDetector e() { - if (BlockWitherSkull.d == null) { - BlockWitherSkull.d = ShapeDetectorBuilder.a().a(" ", "###", "~#~").a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.SOUL_SAND))).a('~', ShapeDetectorBlock.a(MaterialPredicate.a(Material.AIR))).b(); - } - - return BlockWitherSkull.d; - } -} diff --git a/src/main/java/net/minecraft/server/BossBattleCustom.java b/src/main/java/net/minecraft/server/BossBattleCustom.java deleted file mode 100644 index 218b97057..000000000 --- a/src/main/java/net/minecraft/server/BossBattleCustom.java +++ /dev/null @@ -1,233 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Sets; -import java.util.Collection; -import java.util.Iterator; -import java.util.Set; -import java.util.UUID; - -// CraftBukkit start -import org.bukkit.boss.KeyedBossBar; -import org.bukkit.craftbukkit.boss.CraftKeyedBossbar; -// CraftBukkit end - -public class BossBattleCustom extends BossBattleServer { - - private final MinecraftKey h; - private final Set i = Sets.newHashSet(); - private int j; - private int k = 100; - // CraftBukkit start - private KeyedBossBar bossBar; - - public KeyedBossBar getBukkitEntity() { - if (bossBar == null) { - bossBar = new CraftKeyedBossbar(this); - } - return bossBar; - } - // CraftBukkit end - - public BossBattleCustom(MinecraftKey minecraftkey, IChatBaseComponent ichatbasecomponent) { - super(ichatbasecomponent, BossBattle.BarColor.WHITE, BossBattle.BarStyle.PROGRESS); - this.h = minecraftkey; - this.setProgress(0.0F); - } - - public MinecraftKey getKey() { - return this.h; - } - - @Override - public void addPlayer(EntityPlayer entityplayer) { - super.addPlayer(entityplayer); - this.i.add(entityplayer.getUniqueID()); - } - - public void a(UUID uuid) { - this.i.add(uuid); - } - - @Override - public void removePlayer(EntityPlayer entityplayer) { - super.removePlayer(entityplayer); - this.i.remove(entityplayer.getUniqueID()); - } - - @Override - public void b() { - super.b(); - this.i.clear(); - } - - public int c() { - return this.j; - } - - public int d() { - return this.k; - } - - public void a(int i) { - this.j = i; - this.setProgress(MathHelper.a((float) i / (float) this.k, 0.0F, 1.0F)); - } - - public void b(int i) { - this.k = i; - this.setProgress(MathHelper.a((float) this.j / (float) i, 0.0F, 1.0F)); - } - - public final IChatBaseComponent e() { - return ChatComponentUtils.a(this.j()).a((chatmodifier) -> { - chatmodifier.setColor(this.l().a()).setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_TEXT, new ChatComponentText(this.getKey().toString()))).setInsertion(this.getKey().toString()); - }); - } - - public boolean a(Collection collection) { - Set set = Sets.newHashSet(); - Set set1 = Sets.newHashSet(); - Iterator iterator = this.i.iterator(); - - UUID uuid; - boolean flag; - Iterator iterator1; - - while (iterator.hasNext()) { - uuid = (UUID) iterator.next(); - flag = false; - iterator1 = collection.iterator(); - - while (true) { - if (iterator1.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator1.next(); - - if (!entityplayer.getUniqueID().equals(uuid)) { - continue; - } - - flag = true; - } - - if (!flag) { - set.add(uuid); - } - break; - } - } - - iterator = collection.iterator(); - - EntityPlayer entityplayer1; - - while (iterator.hasNext()) { - entityplayer1 = (EntityPlayer) iterator.next(); - flag = false; - iterator1 = this.i.iterator(); - - while (true) { - if (iterator1.hasNext()) { - UUID uuid1 = (UUID) iterator1.next(); - - if (!entityplayer1.getUniqueID().equals(uuid1)) { - continue; - } - - flag = true; - } - - if (!flag) { - set1.add(entityplayer1); - } - break; - } - } - - iterator = set.iterator(); - - while (iterator.hasNext()) { - uuid = (UUID) iterator.next(); - Iterator iterator2 = this.getPlayers().iterator(); - - while (true) { - if (iterator2.hasNext()) { - EntityPlayer entityplayer2 = (EntityPlayer) iterator2.next(); - - if (!entityplayer2.getUniqueID().equals(uuid)) { - continue; - } - - this.removePlayer(entityplayer2); - } - - this.i.remove(uuid); - break; - } - } - - iterator = set1.iterator(); - - while (iterator.hasNext()) { - entityplayer1 = (EntityPlayer) iterator.next(); - this.addPlayer(entityplayer1); - } - - return !set.isEmpty() || !set1.isEmpty(); - } - - public NBTTagCompound f() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setString("Name", IChatBaseComponent.ChatSerializer.a(this.title)); - nbttagcompound.setBoolean("Visible", this.g()); - nbttagcompound.setInt("Value", this.j); - nbttagcompound.setInt("Max", this.k); - nbttagcompound.setString("Color", this.l().b()); - nbttagcompound.setString("Overlay", this.m().a()); - nbttagcompound.setBoolean("DarkenScreen", this.isDarkenSky()); - nbttagcompound.setBoolean("PlayBossMusic", this.isPlayMusic()); - nbttagcompound.setBoolean("CreateWorldFog", this.isCreateFog()); - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.i.iterator(); - - while (iterator.hasNext()) { - UUID uuid = (UUID) iterator.next(); - - nbttaglist.add(GameProfileSerializer.a(uuid)); - } - - nbttagcompound.set("Players", nbttaglist); - return nbttagcompound; - } - - public static BossBattleCustom a(NBTTagCompound nbttagcompound, MinecraftKey minecraftkey) { - BossBattleCustom bossbattlecustom = new BossBattleCustom(minecraftkey, IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("Name"))); - - bossbattlecustom.setVisible(nbttagcompound.getBoolean("Visible")); - bossbattlecustom.a(nbttagcompound.getInt("Value")); - bossbattlecustom.b(nbttagcompound.getInt("Max")); - bossbattlecustom.a(BossBattle.BarColor.a(nbttagcompound.getString("Color"))); - bossbattlecustom.a(BossBattle.BarStyle.a(nbttagcompound.getString("Overlay"))); - bossbattlecustom.setDarkenSky(nbttagcompound.getBoolean("DarkenScreen")); - bossbattlecustom.setPlayMusic(nbttagcompound.getBoolean("PlayBossMusic")); - bossbattlecustom.setCreateFog(nbttagcompound.getBoolean("CreateWorldFog")); - NBTTagList nbttaglist = nbttagcompound.getList("Players", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - bossbattlecustom.a(GameProfileSerializer.b(nbttaglist.getCompound(i))); - } - - return bossbattlecustom; - } - - public void c(EntityPlayer entityplayer) { - if (this.i.contains(entityplayer.getUniqueID())) { - this.addPlayer(entityplayer); - } - - } - - public void d(EntityPlayer entityplayer) { - super.removePlayer(entityplayer); - } -} diff --git a/src/main/java/net/minecraft/server/Chunk.java b/src/main/java/net/minecraft/server/Chunk.java deleted file mode 100644 index 67dc837f4..000000000 --- a/src/main/java/net/minecraft/server/Chunk.java +++ /dev/null @@ -1,1060 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.exception.ServerInternalException; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import it.unimi.dsi.fastutil.longs.LongOpenHashSet; -import it.unimi.dsi.fastutil.longs.LongSet; -import it.unimi.dsi.fastutil.shorts.ShortList; -import it.unimi.dsi.fastutil.shorts.ShortListIterator; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.Supplier; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class Chunk implements IChunkAccess { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final ChunkSection a = null; public static final ChunkSection EMPTY_CHUNK_SECTION = Chunk.a; // Paper - OBFHELPER - private final ChunkSection[] sections; - private final BiomeBase[] d; - private final Map e; - public boolean loaded; public boolean isLoaded() { return loaded; } // Paper - OBFHELPER - public final World world; - public final Map heightMap; - private final ChunkConverter i; - public final Map tileEntities; - public final List[] entitySlices; // Spigot - private final Map l; - private final Map m; - private final ShortList[] n; - private TickList o; - private TickList p; - private boolean q; - public long lastSaved; // Paper - private volatile boolean s; - private long t; - @Nullable - private Supplier u; - @Nullable - private Consumer v; - private final ChunkCoordIntPair loc; - private volatile boolean x; - - public Chunk(World world, ChunkCoordIntPair chunkcoordintpair, BiomeBase[] abiomebase) { - this(world, chunkcoordintpair, abiomebase, ChunkConverter.a, TickListEmpty.b(), TickListEmpty.b(), 0L, (ChunkSection[]) null, (Consumer) null); - } - - // Paper start - public final co.aikar.util.Counter entityCounts = new co.aikar.util.Counter<>(); - public final co.aikar.util.Counter tileEntityCounts = new co.aikar.util.Counter<>(); - private class TileEntityHashMap extends java.util.HashMap { - @Override - public TileEntity put(BlockPosition key, TileEntity value) { - TileEntity replaced = super.put(key, value); - if (replaced != null) { - replaced.setCurrentChunk(null); - tileEntityCounts.decrement(replaced.getMinecraftKeyString()); - } - if (value != null) { - value.setCurrentChunk(Chunk.this); - tileEntityCounts.increment(value.getMinecraftKeyString()); - } - return replaced; - } - - @Override - public TileEntity remove(Object key) { - TileEntity removed = super.remove(key); - if (removed != null) { - removed.setCurrentChunk(null); - tileEntityCounts.decrement(removed.getMinecraftKeyString()); - } - return removed; - } - } - // Track the number of minecarts and items - // Keep this synced with entitySlices.add() and entitySlices.remove() - private final int[] itemCounts = new int[16]; - private final int[] inventoryEntityCounts = new int[16]; - // Paper end - - public Chunk(World world, ChunkCoordIntPair chunkcoordintpair, BiomeBase[] abiomebase, ChunkConverter chunkconverter, TickList ticklist, TickList ticklist1, long i, @Nullable ChunkSection[] achunksection, @Nullable Consumer consumer) { - this.sections = new ChunkSection[16]; - this.e = Maps.newHashMap(); - this.heightMap = Maps.newEnumMap(HeightMap.Type.class); - this.tileEntities = new TileEntityHashMap(); // Paper - this.l = Maps.newHashMap(); - this.m = Maps.newHashMap(); - this.n = new ShortList[16]; - this.entitySlices = (List[]) (new List[16]); // Spigot - this.world = world; - this.loc = chunkcoordintpair; - this.i = chunkconverter; - HeightMap.Type[] aheightmap_type = HeightMap.Type.values(); - int j = aheightmap_type.length; - - for (int k = 0; k < j; ++k) { - HeightMap.Type heightmap_type = aheightmap_type[k]; - - if (ChunkStatus.FULL.h().contains(heightmap_type)) { - this.heightMap.put(heightmap_type, new HeightMap(this, heightmap_type)); - } - } - - for (int l = 0; l < this.entitySlices.length; ++l) { - this.entitySlices[l] = new org.bukkit.craftbukkit.util.UnsafeList(); // Spigot - } - - this.d = abiomebase; - this.o = ticklist; - this.p = ticklist1; - this.t = i; - this.v = consumer; - if (achunksection != null) { - if (this.sections.length == achunksection.length) { - System.arraycopy(achunksection, 0, this.sections, 0, this.sections.length); - } else { - Chunk.LOGGER.warn("Could not set level chunk sections, array length is {} instead of {}", achunksection.length, this.sections.length); - } - } - - // CraftBukkit start - this.bukkitChunk = new org.bukkit.craftbukkit.CraftChunk(this); - } - - public org.bukkit.Chunk bukkitChunk; - public org.bukkit.Chunk getBukkitChunk() { - return bukkitChunk; - } - - public boolean mustNotSave; - public boolean needsDecoration; - // CraftBukkit end - - public Chunk(World world, ProtoChunk protochunk) { - this(world, protochunk.getPos(), protochunk.getBiomeIndex(), protochunk.p(), protochunk.n(), protochunk.o(), protochunk.q(), protochunk.getSections(), (Consumer) null); - Iterator iterator = protochunk.y().iterator(); - - while (iterator.hasNext()) { - NBTTagCompound nbttagcompound = (NBTTagCompound) iterator.next(); - - EntityTypes.a(nbttagcompound, world, (entity) -> { - this.a(entity); - return entity; - }); - } - - iterator = protochunk.x().values().iterator(); - - while (iterator.hasNext()) { - TileEntity tileentity = (TileEntity) iterator.next(); - - this.a(tileentity); - } - - this.e.putAll(protochunk.z()); - - for (int i = 0; i < protochunk.l().length; ++i) { - this.n[i] = protochunk.l()[i]; - } - - this.a(protochunk.h()); - this.b(protochunk.v()); - iterator = protochunk.f().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - if (ChunkStatus.FULL.h().contains(entry.getKey())) { - this.b((HeightMap.Type) entry.getKey()).a(((HeightMap) entry.getValue()).a()); - } - } - - this.b(protochunk.r()); - this.s = true; - this.needsDecoration = true; // CraftBukkit - } - - @Override - public HeightMap b(HeightMap.Type heightmap_type) { - return (HeightMap) this.heightMap.computeIfAbsent(heightmap_type, (heightmap_type1) -> { - return new HeightMap(this, heightmap_type1); - }); - } - - @Override - public Set c() { - Set set = Sets.newHashSet(this.e.keySet()); - - set.addAll(this.tileEntities.keySet()); - return set; - } - - @Override - public ChunkSection[] getSections() { - return this.sections; - } - - // Paper start - Optimize getBlockData to reduce instructions - public final IBlockData getBlockData(BlockPosition pos) { return getBlockData(pos.getX(), pos.getY(), pos.getZ()); } // Paper - public IBlockData getType(BlockPosition blockposition) { - return this.getBlockData(blockposition.getX(), blockposition.getY(), blockposition.getZ()); - } - - public final IBlockData getBlockData(final int x, final int y, final int z) { - // Method body / logic copied from below - final int i = y >> 4; - if (y >= 0 && i < this.sections.length && this.sections[i] != null) { - // Inlined ChunkSection.getType() and DataPaletteBlock.a(int,int,int) - return this.sections[i].blockIds.a((y & 15) << 8 | (z & 15) << 4 | x & 15); - } - return Blocks.AIR.getBlockData(); - } - - public IBlockData getBlockData_unused(int i, int j, int k) { - // Paper end - if (this.world.P() == WorldType.DEBUG_ALL_BLOCK_STATES) { - IBlockData iblockdata = null; - - if (j == 60) { - iblockdata = Blocks.BARRIER.getBlockData(); - } - - if (j == 70) { - iblockdata = ChunkProviderDebug.a(i, k); - } - - return iblockdata == null ? Blocks.AIR.getBlockData() : iblockdata; - } else { - try { - if (j >= 0 && j >> 4 < this.sections.length) { - ChunkSection chunksection = this.sections[j >> 4]; - - if (!ChunkSection.a(chunksection)) { - return chunksection.getType(i & 15, j & 15, k & 15); - } - } - - return Blocks.AIR.getBlockData(); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Getting block state"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Block being got"); - - crashreportsystemdetails.a("Location", () -> { - return CrashReportSystemDetails.a(i, j, k); - }); - throw new ReportedException(crashreport); - } - } - } - - // Paper start - If loaded util - @Override - public Fluid getFluidIfLoaded(BlockPosition blockposition) { - return this.getFluid(blockposition); - } - - @Override - public IBlockData getTypeIfLoaded(BlockPosition blockposition) { - return this.getType(blockposition); - } - // Paper end - - @Override - public Fluid getFluid(BlockPosition blockposition) { - return this.a(blockposition.getX(), blockposition.getY(), blockposition.getZ()); - } - - public Fluid a(int i, int j, int k) { - try { - if (j >= 0 && j >> 4 < this.sections.length) { - ChunkSection chunksection = this.sections[j >> 4]; - - if (!ChunkSection.a(chunksection)) { - return chunksection.b(i & 15, j & 15, k & 15); - } - } - - return FluidTypes.EMPTY.i(); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Getting fluid state"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Block being got"); - - crashreportsystemdetails.a("Location", () -> { - return CrashReportSystemDetails.a(i, j, k); - }); - throw new ReportedException(crashreport); - } - } - - // CraftBukkit start - @Nullable - @Override - public IBlockData setType(BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - return this.setType(blockposition, iblockdata, flag, true); - } - - @Nullable - public IBlockData setType(BlockPosition blockposition, IBlockData iblockdata, boolean flag, boolean doPlace) { - // CraftBukkit end - int i = blockposition.getX() & 15; - int j = blockposition.getY(); - int k = blockposition.getZ() & 15; - ChunkSection chunksection = this.sections[j >> 4]; - - if (chunksection == Chunk.a) { - if (iblockdata.isAir()) { - return null; - } - - chunksection = new ChunkSection(j >> 4 << 4, this, this.world, true); // Paper - Anti-Xray - this.sections[j >> 4] = chunksection; - } - - boolean flag1 = chunksection.c(); - IBlockData iblockdata1 = chunksection.setType(i, j & 15, k, iblockdata); - - if (iblockdata1 == iblockdata) { - return null; - } else { - Block block = iblockdata.getBlock(); - Block block1 = iblockdata1.getBlock(); - - ((HeightMap) this.heightMap.get(HeightMap.Type.MOTION_BLOCKING)).a(i, j, k, iblockdata); - ((HeightMap) this.heightMap.get(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES)).a(i, j, k, iblockdata); - ((HeightMap) this.heightMap.get(HeightMap.Type.OCEAN_FLOOR)).a(i, j, k, iblockdata); - ((HeightMap) this.heightMap.get(HeightMap.Type.WORLD_SURFACE)).a(i, j, k, iblockdata); - boolean flag2 = chunksection.c(); - - if (flag1 != flag2) { - this.world.getChunkProvider().getLightEngine().a(blockposition, flag2); - } - - if (!this.world.isClientSide) { - iblockdata1.remove(this.world, blockposition, iblockdata, flag); - } else if (block1 != block && block1 instanceof ITileEntity) { - this.world.removeTileEntity(blockposition); - } - - if (chunksection.getType(i, j & 15, k).getBlock() != block) { - return null; - } else { - TileEntity tileentity; - - if (block1 instanceof ITileEntity) { - tileentity = this.a(blockposition, Chunk.EnumTileEntityState.CHECK); - if (tileentity != null) { - tileentity.invalidateBlockCache(); - } - } - - // CraftBukkit - Don't place while processing the BlockPlaceEvent, unless it's a BlockContainer. Prevents blocks such as TNT from activating when cancelled. - if (!this.world.isClientSide && doPlace && (!this.world.captureBlockStates || block instanceof BlockTileEntity)) { - iblockdata.onPlace(this.world, blockposition, iblockdata1, flag); - } - - if (block instanceof ITileEntity) { - tileentity = this.a(blockposition, Chunk.EnumTileEntityState.CHECK); - if (tileentity == null) { - tileentity = ((ITileEntity) block).createTile(this.world); - this.world.setTileEntity(blockposition, tileentity); - } else { - tileentity.invalidateBlockCache(); - } - } - - this.s = true; - return iblockdata1; - } - } - } - - @Nullable - @Override - public LightEngine e() { - return this.world.getChunkProvider().getLightEngine(); - } - - public final int getLightSubtracted(BlockPosition blockposition, int i) { return this.a(blockposition, i); } // Paper - OBFHELPER - public int a(BlockPosition blockposition, int i) { - return this.a(blockposition, i, this.world.getWorldProvider().g()); - } - - @Override - public void a(Entity entity) { - this.q = true; - int i = MathHelper.floor(entity.locX / 16.0D); - int j = MathHelper.floor(entity.locZ / 16.0D); - - if (i != this.loc.x || j != this.loc.z) { - Chunk.LOGGER.warn("Wrong location! ({}, {}) should be ({}, {}), {}", i, j, this.loc.x, this.loc.z, entity); - entity.dead = true; - return; // Paper - } - - int k = MathHelper.floor(entity.locY / 16.0D); - - if (k < 0) { - k = 0; - } - - if (k >= this.entitySlices.length) { - k = this.entitySlices.length - 1; - } - // Paper - remove from any old list if its in one - List nextSlice = this.entitySlices[k]; // the next list to be added to - List currentSlice = entity.entitySlice; - if (nextSlice == currentSlice) { - if (World.DEBUG_ENTITIES) MinecraftServer.LOGGER.warn("Entity was already in this chunk!" + entity, new Throwable()); - return; // ??? silly plugins - } - if (currentSlice != null && currentSlice.contains(entity)) { - // Still in an old chunk... - if (World.DEBUG_ENTITIES) MinecraftServer.LOGGER.warn("Entity is still in another chunk!" + entity, new Throwable()); - Chunk chunk = entity.getCurrentChunk(); - if (chunk != null) { - chunk.removeEntity(entity); - } else { - removeEntity(entity); - } - currentSlice.remove(entity); // Just incase the above did not remove from the previous slice - } - // Paper end - - if (!entity.inChunk || entity.getCurrentChunk() != this) entityCounts.increment(entity.getMinecraftKeyString()); // Paper - entity.inChunk = true; - entity.setCurrentChunk(this); // Paper - entity.chunkX = this.loc.x; - entity.chunkY = k; - entity.chunkZ = this.loc.z; - this.entitySlices[k].add(entity); - // Paper start - if (entity instanceof EntityItem) { - itemCounts[k]++; - } else if (entity instanceof IInventory) { - inventoryEntityCounts[k]++; - } - // Paper end - entity.entitySlice = this.entitySlices[k]; // Paper - this.markDirty(); // Paper - } - - @Override - public void a(HeightMap.Type heightmap_type, long[] along) { - ((HeightMap) this.heightMap.get(heightmap_type)).a(along); - } - - public void removeEntity(Entity entity) { this.b(entity); } // Paper - OBFHELPER - public void b(Entity entity) { - this.a(entity, entity.chunkY); - } - - public void a(Entity entity, int i) { - if (i < 0) { - i = 0; - } - - if (i >= this.entitySlices.length) { - i = this.entitySlices.length - 1; - } - // Paper start - if (entity.currentChunk != null && entity.currentChunk.get() == this) entity.setCurrentChunk(null); - if (entitySlices[i] == entity.entitySlice) { - entity.entitySlice = null; - } - if (!this.entitySlices[i].remove(entity)) { - return; - } - if (entity instanceof EntityItem) { - itemCounts[i]--; - } else if (entity instanceof IInventory) { - inventoryEntityCounts[i]--; - } - entityCounts.decrement(entity.getMinecraftKeyString()); - this.markDirty(); // Paper - // Paper end - } - - @Override - public int a(HeightMap.Type heightmap_type, int i, int j) { - return ((HeightMap) this.heightMap.get(heightmap_type)).a(i & 15, j & 15) - 1; - } - - @Nullable - private TileEntity k(BlockPosition blockposition) { - IBlockData iblockdata = this.getType(blockposition); - Block block = iblockdata.getBlock(); - - return !block.isTileEntity() ? null : ((ITileEntity) block).createTile(this.world); - } - - @Nullable - @Override - public TileEntity getTileEntity(BlockPosition blockposition) { - return this.a(blockposition, Chunk.EnumTileEntityState.CHECK); - } - - @Nullable public final TileEntity getTileEntityImmediately(BlockPosition pos) { return this.a(pos, EnumTileEntityState.IMMEDIATE); } // Paper - OBFHELPER - @Nullable - public TileEntity a(BlockPosition blockposition, Chunk.EnumTileEntityState chunk_enumtileentitystate) { - // CraftBukkit start - TileEntity tileentity = world.capturedTileEntities.get(blockposition); - if (tileentity == null) { - tileentity = (TileEntity) this.tileEntities.get(blockposition); - } - // CraftBukkit end - - if (tileentity == null) { - NBTTagCompound nbttagcompound = (NBTTagCompound) this.e.remove(blockposition); - - if (nbttagcompound != null) { - TileEntity tileentity1 = this.a(blockposition, nbttagcompound); - - if (tileentity1 != null) { - return tileentity1; - } - } - } - - if (tileentity == null) { - if (chunk_enumtileentitystate == Chunk.EnumTileEntityState.IMMEDIATE) { - tileentity = this.k(blockposition); - this.world.setTileEntity(blockposition, tileentity); - } - } else if (tileentity.isRemoved()) { - this.tileEntities.remove(blockposition); - return null; - } - - return tileentity; - } - - public void a(TileEntity tileentity) { - this.setTileEntity(tileentity.getPosition(), tileentity); - if (this.loaded || this.world.e()) { - this.world.setTileEntity(tileentity.getPosition(), tileentity); - } - - } - - @Override - public void setTileEntity(BlockPosition blockposition, TileEntity tileentity) { - if (this.getType(blockposition).getBlock() instanceof ITileEntity) { - tileentity.setWorld(this.world); - tileentity.setPosition(blockposition); - tileentity.n(); - TileEntity tileentity1 = (TileEntity) this.tileEntities.put(blockposition.immutableCopy(), tileentity); - - if (tileentity1 != null && tileentity1 != tileentity) { - tileentity1.V_(); - } - - // CraftBukkit start - // Paper start - Remove invalid mob spawner tile entities - } else if (tileentity instanceof TileEntityMobSpawner && !(getBlockData(blockposition.getX(), blockposition.getY(), blockposition.getZ()).getBlock() instanceof BlockMobSpawner)) { - this.tileEntities.remove(blockposition); - // Paper end - } else { - // Paper start - ServerInternalException e = new ServerInternalException( - "Attempted to place a tile entity (" + tileentity + ") at " + tileentity.position.getX() + "," - + tileentity.position.getY() + "," + tileentity.position.getZ() - + " (" + getType(blockposition) + ") where there was no entity tile!\n" + - "Chunk coordinates: " + (this.loc.x * 16) + "," + (this.loc.z * 16)); - e.printStackTrace(); - ServerInternalException.reportInternalException(e); - - if (this.world.paperConfig.removeCorruptTEs) { - this.removeTileEntity(tileentity.getPosition()); - this.markDirty(); - org.bukkit.Bukkit.getLogger().info("Removing corrupt tile entity"); - } - // Paper end - // CraftBukkit end - } - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.e.put(new BlockPosition(nbttagcompound.getInt("x"), nbttagcompound.getInt("y"), nbttagcompound.getInt("z")), nbttagcompound); - } - - @Nullable - @Override - public NBTTagCompound j(BlockPosition blockposition) { - TileEntity tileentity = this.getTileEntity(blockposition); - NBTTagCompound nbttagcompound; - - if (tileentity != null && !tileentity.isRemoved()) { - nbttagcompound = tileentity.save(new NBTTagCompound()); - nbttagcompound.setBoolean("keepPacked", false); - return nbttagcompound; - } else { - nbttagcompound = (NBTTagCompound) this.e.get(blockposition); - if (nbttagcompound != null) { - nbttagcompound = nbttagcompound.clone(); - nbttagcompound.setBoolean("keepPacked", true); - } - - return nbttagcompound; - } - } - - @Override - public void removeTileEntity(BlockPosition blockposition) { - if (this.loaded || this.world.e()) { - TileEntity tileentity = (TileEntity) this.tileEntities.remove(blockposition); - - if (tileentity != null) { - tileentity.V_(); - } - } - - } - - public void addEntities() { - if (this.v != null) { - this.v.accept(this); - this.v = null; - } - - } - - // CraftBukkit start - public void loadCallback() { - org.bukkit.Server server = this.world.getServer(); - 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(this.bukkitChunk, this.needsDecoration)); - - if (this.needsDecoration) { - try (co.aikar.timings.Timing ignored = this.world.timings.syncChunkLoadPopulateTimer.startTiming()) { // Paper - this.needsDecoration = false; - java.util.Random random = new java.util.Random(); - random.setSeed(world.getSeed()); - long xRand = random.nextLong() / 2L * 2L + 1L; - long zRand = random.nextLong() / 2L * 2L + 1L; - random.setSeed((long) this.loc.x * xRand + (long) this.loc.z * 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, bukkitChunk); - } - } finally { - this.world.populating = false; - } - } - server.getPluginManager().callEvent(new org.bukkit.event.world.ChunkPopulateEvent(bukkitChunk)); - } // Paper - } - } - } - - public void unloadCallback() { - org.bukkit.Server server = this.world.getServer(); - org.bukkit.event.world.ChunkUnloadEvent unloadEvent = new org.bukkit.event.world.ChunkUnloadEvent(this.bukkitChunk, this.isNeedsSaving()); - server.getPluginManager().callEvent(unloadEvent); - // note: saving can be prevented, but not forced if no saving is actually required - this.mustNotSave = !unloadEvent.isSaveChunk(); - } - // CraftBukkit end - - public void markDirty() { - this.s = true; - } - - public void a(@Nullable Entity entity, AxisAlignedBB axisalignedbb, List list, @Nullable Predicate predicate) { - int i = MathHelper.floor((axisalignedbb.minY - 2.0D) / 16.0D); - int j = MathHelper.floor((axisalignedbb.maxY + 2.0D) / 16.0D); - - i = MathHelper.clamp(i, 0, this.entitySlices.length - 1); - j = MathHelper.clamp(j, 0, this.entitySlices.length - 1); - - for (int k = i; k <= j; ++k) { - if (!this.entitySlices[k].isEmpty()) { - Iterator iterator = this.entitySlices[k].iterator(); - - while (iterator.hasNext()) { - Entity entity1 = (Entity) iterator.next(); - if (entity1.shouldBeRemoved) continue; // Paper - - if (entity1.getBoundingBox().c(axisalignedbb) && entity1 != entity) { - if (predicate == null || predicate.test(entity1)) { - list.add(entity1); - } - - if (entity1 instanceof EntityEnderDragon) { - EntityComplexPart[] aentitycomplexpart = ((EntityEnderDragon) entity1).dT(); - int l = aentitycomplexpart.length; - - for (int i1 = 0; i1 < l; ++i1) { - EntityComplexPart entitycomplexpart = aentitycomplexpart[i1]; - - if (entitycomplexpart != entity && entitycomplexpart.getBoundingBox().c(axisalignedbb) && (predicate == null || predicate.test(entitycomplexpart))) { - list.add(entitycomplexpart); - } - } - } - } - } - } - } - - } - - public void a(@Nullable EntityTypes entitytypes, AxisAlignedBB axisalignedbb, List list, Predicate predicate) { - int i = MathHelper.floor((axisalignedbb.minY - 2.0D) / 16.0D); - int j = MathHelper.floor((axisalignedbb.maxY + 2.0D) / 16.0D); - - i = MathHelper.clamp(i, 0, this.entitySlices.length - 1); - j = MathHelper.clamp(j, 0, this.entitySlices.length - 1); - - for (int k = i; k <= j; ++k) { - Iterator iterator = this.entitySlices[k].iterator(); // Spigot - - // Paper 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.isInventory() && inventoryEntityCounts[k] <= 0) continue; - // Paper end - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - if (entity.shouldBeRemoved) continue; // Paper - - if ((entitytypes == null || entity.getEntityType() == entitytypes) && entity.getBoundingBox().c(axisalignedbb) && predicate.test(entity)) { - list.add(entity); - } - } - } - - } - - public void a(Class oclass, AxisAlignedBB axisalignedbb, List list, @Nullable Predicate predicate) { - int i = MathHelper.floor((axisalignedbb.minY - 2.0D) / 16.0D); - int j = MathHelper.floor((axisalignedbb.maxY + 2.0D) / 16.0D); - - i = MathHelper.clamp(i, 0, this.entitySlices.length - 1); - j = MathHelper.clamp(j, 0, this.entitySlices.length - 1); - - // Paper start - int[] counts; - if (EntityItem.class.isAssignableFrom(oclass)) { - counts = itemCounts; - } else if (IInventory.class.isAssignableFrom(oclass)) { - counts = inventoryEntityCounts; - } else { - counts = null; - } - // Paper end - for (int k = i; k <= j; ++k) { - if (counts != null && counts[k] <= 0) continue; // Paper - Don't check a chunk if it doesn't have the type we are looking for - Iterator iterator = this.entitySlices[k].iterator(); // Spigot - - while (iterator.hasNext()) { - T t0 = (T) iterator.next(); // CraftBukkit - decompile error - if (t0.shouldBeRemoved) continue; // Paper - - if (oclass.isInstance(t0) && t0.getBoundingBox().c(axisalignedbb) && (predicate == null || predicate.test(t0))) { // Spigot - instance check - list.add(t0); - } - } - } - - } - - public boolean isEmpty() { - return false; - } - - @Override - public ChunkCoordIntPair getPos() { - return this.loc; - } - - @Override - public BiomeBase[] getBiomeIndex() { - return this.d; - } - - public void setLoaded(boolean flag) { - this.loaded = flag; - } - - public World getWorld() { - return this.world; - } - - @Override - public Collection> f() { - return Collections.unmodifiableSet(this.heightMap.entrySet()); - } - - public Map getTileEntities() { - return this.tileEntities; - } - - public List[] getEntitySlices() { // Spigot - return this.entitySlices; - } - - @Override - public NBTTagCompound i(BlockPosition blockposition) { - return (NBTTagCompound) this.e.get(blockposition); - } - - @Override - public Stream m() { - return StreamSupport.stream(BlockPosition.b(this.loc.d(), 0, this.loc.e(), this.loc.f(), 255, this.loc.g()).spliterator(), false).filter((blockposition) -> { - return this.getType(blockposition).h() != 0; - }); - } - - @Override - public TickList n() { - return this.o; - } - - @Override - public TickList o() { - return this.p; - } - - @Override - public void setNeedsSaving(boolean flag) { - this.s = flag; - } - - @Override - public boolean isNeedsSaving() { - return (this.s || this.q && this.world.getTime() != this.lastSaved) && !this.mustNotSave; // CraftBukkit - } - - public void d(boolean flag) { - this.q = flag; - } - - @Override - public void setLastSaved(long i) { - this.lastSaved = i; - } - - @Nullable - @Override - public StructureStart a(String s) { - return (StructureStart) this.l.get(s); - } - - @Override - public void a(String s, StructureStart structurestart) { - this.l.put(s, structurestart); - } - - @Override - public Map h() { - return this.l; - } - - @Override - public void a(Map map) { - this.l.clear(); - this.l.putAll(map); - } - - @Override - public LongSet b(String s) { - return (LongSet) this.m.computeIfAbsent(s, (s1) -> { - return new LongOpenHashSet(); - }); - } - - @Override - public void a(String s, long i) { - ((LongSet) this.m.computeIfAbsent(s, (s1) -> { - return new LongOpenHashSet(); - })).add(i); - } - - @Override - public Map v() { - return this.m; - } - - @Override - public void b(Map map) { - this.m.clear(); - this.m.putAll(map); - } - - @Override - public long q() { - return world.paperConfig.fixedInhabitedTime < 0 ? this.t : world.paperConfig.fixedInhabitedTime; // Paper - } - - @Override - public void b(long i) { - this.t = i; - } - - public void A() { - ChunkCoordIntPair chunkcoordintpair = this.getPos(); - - for (int i = 0; i < this.n.length; ++i) { - if (this.n[i] != null) { - ShortListIterator shortlistiterator = this.n[i].iterator(); - - while (shortlistiterator.hasNext()) { - Short oshort = (Short) shortlistiterator.next(); - BlockPosition blockposition = ProtoChunk.a(oshort, i, chunkcoordintpair); - IBlockData iblockdata = this.getType(blockposition); - IBlockData iblockdata1 = Block.b(iblockdata, (GeneratorAccess) this.world, blockposition); - - this.world.setTypeAndData(blockposition, iblockdata1, 20); - } - - this.n[i].clear(); - } - } - - this.B(); - Iterator iterator = Sets.newHashSet(this.e.keySet()).iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition1 = (BlockPosition) iterator.next(); - - this.getTileEntity(blockposition1); - } - - this.e.clear(); - this.i.a(this); - } - - @Nullable - private TileEntity a(BlockPosition blockposition, NBTTagCompound nbttagcompound) { - TileEntity tileentity; - - if ("DUMMY".equals(nbttagcompound.getString("id"))) { - Block block = this.getType(blockposition).getBlock(); - - if (block instanceof ITileEntity) { - tileentity = ((ITileEntity) block).createTile(this.world); - } else { - tileentity = null; - Chunk.LOGGER.warn("Tried to load a DUMMY block entity @ {} but found not block entity block {} at location", blockposition, this.getType(blockposition)); - } - } else { - tileentity = TileEntity.create(nbttagcompound); - } - - if (tileentity != null) { - tileentity.setPosition(blockposition); - this.a(tileentity); - } else { - Chunk.LOGGER.warn("Tried to load a block entity for block {} but failed at location {}", this.getType(blockposition), blockposition); - } - - return tileentity; - } - - @Override - public ChunkConverter p() { - return this.i; - } - - @Override - public ShortList[] l() { - return this.n; - } - - public void B() { - if (this.o instanceof ProtoChunkTickList) { - ((ProtoChunkTickList) this.o).a(this.world.getBlockTickList(), (blockposition) -> { // CraftBukkit - decompile error - return this.getType(blockposition).getBlock(); - }); - this.o = TickListEmpty.b(); - } else if (this.o instanceof TickListChunk) { - this.world.getBlockTickList().a(((TickListChunk) this.o).b()); - this.o = TickListEmpty.b(); - } - - if (this.p instanceof ProtoChunkTickList) { - ((ProtoChunkTickList) this.p).a(this.world.getFluidTickList(), (blockposition) -> { // CraftBukkit - decompile error - return this.getFluid(blockposition).getType(); - }); - this.p = TickListEmpty.b(); - } else if (this.p instanceof TickListChunk) { - this.world.getFluidTickList().a(((TickListChunk) this.p).b()); - this.p = TickListEmpty.b(); - } - - } - - public void a(WorldServer worldserver) { - if (this.o == TickListEmpty.b()) { // CraftBukkit - decompile error - this.o = new TickListChunk<>(IRegistry.BLOCK::getKey, worldserver.getBlockTickList().a(this.loc, true, false)); - this.setNeedsSaving(true); - } - - if (this.p == TickListEmpty.b()) { // CraftBukkit - decompile error - this.p = new TickListChunk<>(IRegistry.FLUID::getKey, worldserver.getFluidTickList().a(this.loc, true, false)); - this.setNeedsSaving(true); - } - - } - - @Override - public ChunkStatus getChunkStatus() { - return ChunkStatus.FULL; - } - - public PlayerChunk.State getState() { - return this.u == null ? PlayerChunk.State.BORDER : (PlayerChunk.State) this.u.get(); - } - - public void a(Supplier supplier) { - this.u = supplier; - } - - @Override - public void a(LightEngine lightengine) {} - - @Override - public boolean r() { - return this.x; - } - - @Override - public void b(boolean flag) { - this.x = flag; - this.setNeedsSaving(true); - } - - public static enum EnumTileEntityState { - - IMMEDIATE, QUEUED, CHECK; - - private EnumTileEntityState() {} - } -} diff --git a/src/main/java/net/minecraft/server/ChunkCache.java b/src/main/java/net/minecraft/server/ChunkCache.java deleted file mode 100644 index beb50d206..000000000 --- a/src/main/java/net/minecraft/server/ChunkCache.java +++ /dev/null @@ -1,178 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class ChunkCache implements IWorldReader { - - protected final int a; - protected final int b; - protected final IChunkAccess[][] c; - protected boolean d; - protected final World e; - - public ChunkCache(World world, BlockPosition blockposition, BlockPosition blockposition1) { - this.e = world; - this.a = blockposition.getX() >> 4; - this.b = blockposition.getZ() >> 4; - int i = blockposition1.getX() >> 4; - int j = blockposition1.getZ() >> 4; - - this.c = new IChunkAccess[i - this.a + 1][j - this.b + 1]; - this.d = true; - - int k; - int l; - - for (k = this.a; k <= i; ++k) { - for (l = this.b; l <= j; ++l) { - this.c[k - this.a][l - this.b] = world.getChunkIfLoadedImmediately(k, l); // Paper - } - } - - for (k = blockposition.getX() >> 4; k <= blockposition1.getX() >> 4; ++k) { - for (l = blockposition.getZ() >> 4; l <= blockposition1.getZ() >> 4; ++l) { - IChunkAccess ichunkaccess = this.c[k - this.a][l - this.b]; - - if (ichunkaccess != null && !ichunkaccess.a(blockposition.getY(), blockposition1.getY())) { - this.d = false; - return; - } - } - } - - } - - @Override - public int getLightLevel(BlockPosition blockposition, int i) { - return this.e.getLightLevel(blockposition, i); - } - - // Paper start - if loaded util - @Nullable - @Override - public IChunkAccess getChunkIfLoadedImmediately(int x, int z) { - IChunkAccess chunk = this.getChunkAt(x, z, ChunkStatus.FULL, false); - if (chunk instanceof ChunkEmpty) { - return null; - } - return chunk; - } - - @Override - public Fluid getFluidIfLoaded(BlockPosition blockposition) { - IChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4); - return chunk == null ? null : chunk.getFluid(blockposition); - } - - @Override - public IBlockData getTypeIfLoaded(BlockPosition blockposition) { - IChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4); - return chunk == null ? null : chunk.getType(blockposition); - } - // Paper end - - @Nullable - @Override - public IChunkAccess getChunkAt(int i, int j, ChunkStatus chunkstatus, boolean flag) { - int k = i - this.a; - int l = j - this.b; - - if (k >= 0 && k < this.c.length && l >= 0 && l < this.c[k].length) { - IChunkAccess ichunkaccess = this.c[k][l]; - - return (IChunkAccess) (ichunkaccess != null ? ichunkaccess : new ChunkEmpty(this.e, new ChunkCoordIntPair(i, j))); - } else { - return new ChunkEmpty(this.e, new ChunkCoordIntPair(i, j)); - } - } - - @Override - public boolean isChunkLoaded(int i, int j) { - int k = i - this.a; - int l = j - this.b; - - return k >= 0 && k < this.c.length && l >= 0 && l < this.c[k].length && this.c[k][l] != null; // Paper - We don't always load chunks - } - - @Override - public BlockPosition getHighestBlockYAt(HeightMap.Type heightmap_type, BlockPosition blockposition) { - return this.e.getHighestBlockYAt(heightmap_type, blockposition); - } - - @Override - public int a(HeightMap.Type heightmap_type, int i, int j) { - return this.e.a(heightmap_type, i, j); - } - - @Override - public int c() { - return this.e.c(); - } - - @Override - public WorldBorder getWorldBorder() { - return this.e.getWorldBorder(); - } - - @Override - public boolean a(@Nullable Entity entity, VoxelShape voxelshape) { - return true; - } - - @Override - public boolean e() { - return false; - } - - @Override - public int getSeaLevel() { - return this.e.getSeaLevel(); - } - - @Override - public WorldProvider getWorldProvider() { - return this.e.getWorldProvider(); - } - - @Nullable - @Override - public TileEntity getTileEntity(BlockPosition blockposition) { - IChunkAccess ichunkaccess = this.w(blockposition); - - return ichunkaccess.getTileEntity(blockposition); - } - - @Override - public IBlockData getType(BlockPosition blockposition) { - if (World.isOutsideWorld(blockposition)) { - return Blocks.AIR.getBlockData(); - } else { - IChunkAccess ichunkaccess = this.w(blockposition); - - return ichunkaccess.getType(blockposition); - } - } - - @Override - public Fluid getFluid(BlockPosition blockposition) { - if (World.isOutsideWorld(blockposition)) { - return FluidTypes.EMPTY.i(); - } else { - IChunkAccess ichunkaccess = this.w(blockposition); - - return ichunkaccess.getFluid(blockposition); - } - } - - @Override - public BiomeBase getBiome(BlockPosition blockposition) { - IChunkAccess ichunkaccess = this.w(blockposition); - - return ichunkaccess.getBiome(blockposition); - } - - @Override - public int getBrightness(EnumSkyBlock enumskyblock, BlockPosition blockposition) { - return this.e.getBrightness(enumskyblock, blockposition); - } -} diff --git a/src/main/java/net/minecraft/server/ChunkCoordIntPair.java b/src/main/java/net/minecraft/server/ChunkCoordIntPair.java deleted file mode 100644 index bbf136614..000000000 --- a/src/main/java/net/minecraft/server/ChunkCoordIntPair.java +++ /dev/null @@ -1,148 +0,0 @@ -package net.minecraft.server; - -import java.util.Spliterators.AbstractSpliterator; -import java.util.function.Consumer; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; -import javax.annotation.Nullable; - -public class ChunkCoordIntPair { - - public static final long a = pair(1875016, 1875016); - public final int x; - public final int z; - - public ChunkCoordIntPair(int i, int j) { - this.x = i; - this.z = j; - } - - public ChunkCoordIntPair(BlockPosition blockposition) { - this.x = blockposition.getX() >> 4; - this.z = blockposition.getZ() >> 4; - } - - public ChunkCoordIntPair(long i) { - this.x = (int) i; - this.z = (int) (i >> 32); - } - - public long pair() { - return pair(this.x, this.z); - } - - public static long asLong(final BlockPosition pos) { return pair(pos.getX() >> 4, pos.getZ() >> 4); } // Paper - OBFHELPER - public static long asLong(int x, int z) { return pair(x, z); } // Paper - OBFHELPER - public static long pair(int i, int j) { - return (long) i & 4294967295L | ((long) j & 4294967295L) << 32; - } - - public static int getX(long i) { - return (int) (i & 4294967295L); - } - - public static int getZ(long i) { - return (int) (i >>> 32 & 4294967295L); - } - - 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 d() { - return this.x << 4; - } - - public int e() { - return this.z << 4; - } - - public int f() { - return (this.x << 4) + 15; - } - - public int g() { - return (this.z << 4) + 15; - } - - public int getRegionX() { - return this.x >> 5; - } - - public int getRegionZ() { - return this.z >> 5; - } - - public int j() { - return this.x & 31; - } - - public int k() { - return this.z & 31; - } - - public BlockPosition a(int i, int j, int k) { - return new BlockPosition((this.x << 4) + i, j, (this.z << 4) + k); - } - - public String toString() { - return "[" + this.x + ", " + this.z + "]"; - } - - public BlockPosition l() { - return new BlockPosition(this.x << 4, 0, this.z << 4); - } - - public static Stream a(ChunkCoordIntPair chunkcoordintpair, int i) { - return a(new ChunkCoordIntPair(chunkcoordintpair.x - i, chunkcoordintpair.z - i), new ChunkCoordIntPair(chunkcoordintpair.x + i, chunkcoordintpair.z + i)); - } - - public static Stream a(final ChunkCoordIntPair chunkcoordintpair, final ChunkCoordIntPair chunkcoordintpair1) { - int i = Math.abs(chunkcoordintpair.x - chunkcoordintpair1.x) + 1; - int j = Math.abs(chunkcoordintpair.z - chunkcoordintpair1.z) + 1; - final int k = chunkcoordintpair.x < chunkcoordintpair1.x ? 1 : -1; - final int l = chunkcoordintpair.z < chunkcoordintpair1.z ? 1 : -1; - - return StreamSupport.stream(new AbstractSpliterator((long) (i * j), 64) { - @Nullable - private ChunkCoordIntPair e; - - public boolean tryAdvance(Consumer consumer) { - if (this.e == null) { - this.e = chunkcoordintpair; - } else { - int i1 = this.e.x; - int j1 = this.e.z; - - if (i1 == chunkcoordintpair1.x) { - if (j1 == chunkcoordintpair1.z) { - return false; - } - - this.e = new ChunkCoordIntPair(chunkcoordintpair.x, j1 + l); - } else { - this.e = new ChunkCoordIntPair(i1 + k, j1); - } - } - - consumer.accept(this.e); - return true; - } - }, false); - } -} diff --git a/src/main/java/net/minecraft/server/ChunkGenerator.java b/src/main/java/net/minecraft/server/ChunkGenerator.java deleted file mode 100644 index 701b214bf..000000000 --- a/src/main/java/net/minecraft/server/ChunkGenerator.java +++ /dev/null @@ -1,225 +0,0 @@ -package net.minecraft.server; - -import java.util.BitSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Locale; -import java.util.Map.Entry; -import javax.annotation.Nullable; - -public abstract class ChunkGenerator { - - protected final GeneratorAccess a; - protected final long seed; - protected final WorldChunkManager c; - protected final C settings; - - public ChunkGenerator(GeneratorAccess generatoraccess, WorldChunkManager worldchunkmanager, C c0) { - this.a = generatoraccess; - this.seed = generatoraccess.getSeed(); - this.c = worldchunkmanager; - this.settings = c0; - } - - public void createBiomes(IChunkAccess ichunkaccess) { - ChunkCoordIntPair chunkcoordintpair = ichunkaccess.getPos(); - int i = chunkcoordintpair.x; - int j = chunkcoordintpair.z; - BiomeBase[] abiomebase = this.c.getBiomeBlock(i * 16, j * 16, 16, 16); - - ichunkaccess.a(abiomebase); - } - - protected BiomeBase getCarvingBiome(IChunkAccess ichunkaccess) { - return ichunkaccess.getBiome(BlockPosition.ZERO); - } - - protected BiomeBase getDecoratingBiome(RegionLimitedWorldAccess regionlimitedworldaccess, BlockPosition blockposition) { - return this.c.getBiome(blockposition); - } - - public void doCarving(IChunkAccess ichunkaccess, WorldGenStage.Features worldgenstage_features) { - SeededRandom seededrandom = new SeededRandom(); - boolean flag = true; - ChunkCoordIntPair chunkcoordintpair = ichunkaccess.getPos(); - int i = chunkcoordintpair.x; - int j = chunkcoordintpair.z; - BitSet bitset = ichunkaccess.a(worldgenstage_features); - - for (int k = i - 8; k <= i + 8; ++k) { - for (int l = j - 8; l <= j + 8; ++l) { - List> list = this.getCarvingBiome(ichunkaccess).a(worldgenstage_features); - ListIterator listiterator = list.listIterator(); - - while (listiterator.hasNext()) { - int i1 = listiterator.nextIndex(); - WorldGenCarverWrapper worldgencarverwrapper = (WorldGenCarverWrapper) listiterator.next(); - - seededrandom.c(this.seed + (long) i1, k, l); - if (worldgencarverwrapper.a(seededrandom, k, l)) { - worldgencarverwrapper.a(ichunkaccess, seededrandom, this.getSeaLevel(), k, l, i, j, bitset); - } - } - } - } - - } - - @Nullable - public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition, int i, boolean flag) { - StructureGenerator structuregenerator = (StructureGenerator) WorldGenerator.aP.get(s.toLowerCase(Locale.ROOT)); - - return structuregenerator != null ? structuregenerator.getNearestGeneratedFeature(world, this, blockposition, i, flag) : null; - } - - public void addDecorations(RegionLimitedWorldAccess regionlimitedworldaccess) { - int i = regionlimitedworldaccess.a(); - int j = regionlimitedworldaccess.b(); - int k = i * 16; - int l = j * 16; - BlockPosition blockposition = new BlockPosition(k, 0, l); - BiomeBase biomebase = this.getDecoratingBiome(regionlimitedworldaccess, blockposition.b(8, 8, 8)); - SeededRandom seededrandom = new SeededRandom(); - long i1 = seededrandom.a(regionlimitedworldaccess.getSeed(), k, l); - WorldGenStage.Decoration[] aworldgenstage_decoration = WorldGenStage.Decoration.values(); - int j1 = aworldgenstage_decoration.length; - - for (int k1 = 0; k1 < j1; ++k1) { - WorldGenStage.Decoration worldgenstage_decoration = aworldgenstage_decoration[k1]; - - try { - biomebase.a(worldgenstage_decoration, this, regionlimitedworldaccess, i1, seededrandom, blockposition); - } catch (Exception exception) { - CrashReport crashreport = CrashReport.a(exception, "Biome decoration"); - - crashreport.a("Generation").a("CenterX", (Object) i).a("CenterZ", (Object) j).a("Step", (Object) worldgenstage_decoration).a("Seed", (Object) i1).a("Biome", (Object) IRegistry.BIOME.getKey(biomebase)); - throw new ReportedException(crashreport); - } - } - - } - - public abstract void buildBase(IChunkAccess ichunkaccess); - - public void addMobs(RegionLimitedWorldAccess regionlimitedworldaccess) {} - - public C getSettings() { - return this.settings; - } - - public abstract int getSpawnHeight(); - - public void doMobSpawning(WorldServer worldserver, boolean flag, boolean flag1) {} - - public boolean canSpawnStructure(BiomeBase biomebase, StructureGenerator structuregenerator) { - return biomebase.a(structuregenerator); - } - - @Nullable - public C getFeatureConfiguration(BiomeBase biomebase, StructureGenerator structuregenerator) { - return biomebase.b(structuregenerator); - } - - public WorldChunkManager getWorldChunkManager() { - return this.c; - } - - public long getSeed() { - return this.seed; - } - - public int getGenerationDepth() { - return 256; - } - - public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { - return this.a.getBiome(blockposition).getMobs(enumcreaturetype); - } - - public void createStructures(IChunkAccess ichunkaccess, ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager) { - Iterator iterator = WorldGenerator.aP.values().iterator(); - - while (iterator.hasNext()) { - StructureGenerator structuregenerator = (StructureGenerator) iterator.next(); - - if (chunkgenerator.getWorldChunkManager().a(structuregenerator)) { - SeededRandom seededrandom = new SeededRandom(); - ChunkCoordIntPair chunkcoordintpair = ichunkaccess.getPos(); - StructureStart structurestart = StructureStart.a; - - // CraftBukkit start - if (structuregenerator == WorldGenerator.STRONGHOLD) { - synchronized (structuregenerator) { - if (structuregenerator.a(chunkgenerator, seededrandom, chunkcoordintpair.x, chunkcoordintpair.z)) { - BiomeBase biomebase = this.getWorldChunkManager().getBiome(new BlockPosition(chunkcoordintpair.d() + 9, 0, chunkcoordintpair.e() + 9)); - StructureStart structurestart1 = structuregenerator.a().create(structuregenerator, chunkcoordintpair.x, chunkcoordintpair.z, biomebase, StructureBoundingBox.a(), 0, chunkgenerator.getSeed()); - - structurestart1.a(this, definedstructuremanager, chunkcoordintpair.x, chunkcoordintpair.z, biomebase); - structurestart = structurestart1.e() ? structurestart1 : StructureStart.a; - } - } - } else - // CraftBukkit end - if (structuregenerator.a(chunkgenerator, seededrandom, chunkcoordintpair.x, chunkcoordintpair.z)) { - BiomeBase biomebase = this.getWorldChunkManager().getBiome(new BlockPosition(chunkcoordintpair.d() + 9, 0, chunkcoordintpair.e() + 9)); - StructureStart structurestart1 = structuregenerator.a().create(structuregenerator, chunkcoordintpair.x, chunkcoordintpair.z, biomebase, StructureBoundingBox.a(), 0, chunkgenerator.getSeed()); - - structurestart1.a(this, definedstructuremanager, chunkcoordintpair.x, chunkcoordintpair.z, biomebase); - structurestart = structurestart1.e() ? structurestart1 : StructureStart.a; - } - - ichunkaccess.a(structuregenerator.b(), structurestart); - } - } - - } - - public void storeStructures(GeneratorAccess generatoraccess, IChunkAccess ichunkaccess) { - boolean flag = true; - int i = ichunkaccess.getPos().x; - int j = ichunkaccess.getPos().z; - int k = i << 4; - int l = j << 4; - - for (int i1 = i - 8; i1 <= i + 8; ++i1) { - for (int j1 = j - 8; j1 <= j + 8; ++j1) { - long k1 = ChunkCoordIntPair.pair(i1, j1); - Iterator iterator = generatoraccess.getChunkAt(i1, j1).h().entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - StructureStart structurestart = (StructureStart) entry.getValue(); - - if (structurestart != StructureStart.a && structurestart.c().a(k, l, k + 15, l + 15)) { - ichunkaccess.a((String) entry.getKey(), k1); - PacketDebug.a(generatoraccess, structurestart); - } - } - } - } - - } - - public abstract void buildNoise(GeneratorAccess generatoraccess, IChunkAccess ichunkaccess); - - public int getSeaLevel() { - return 63; - } - - public abstract int getBaseHeight(int i, int j, HeightMap.Type heightmap_type); - - public int b(int i, int j, HeightMap.Type heightmap_type) { - return this.getBaseHeight(i, j, heightmap_type); - } - - public int c(int i, int j, HeightMap.Type heightmap_type) { - return this.getBaseHeight(i, j, heightmap_type) - 1; - } - - // Spigot start - public World getWorld() { - return this.a.getMinecraftWorld(); - } - // Spigot end -} diff --git a/src/main/java/net/minecraft/server/ChunkGeneratorAbstract.java b/src/main/java/net/minecraft/server/ChunkGeneratorAbstract.java deleted file mode 100644 index 338b67c3c..000000000 --- a/src/main/java/net/minecraft/server/ChunkGeneratorAbstract.java +++ /dev/null @@ -1,428 +0,0 @@ -package net.minecraft.server; - -import it.unimi.dsi.fastutil.longs.LongIterator; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import it.unimi.dsi.fastutil.objects.ObjectList; -import it.unimi.dsi.fastutil.objects.ObjectListIterator; -import java.util.Iterator; -import java.util.Random; - -public abstract class ChunkGeneratorAbstract extends ChunkGenerator { - - private static final float[] h = (float[]) SystemUtils.a((new float[13824]), (afloat) -> { - for (int i = 0; i < 24; ++i) { - for (int j = 0; j < 24; ++j) { - for (int k = 0; k < 24; ++k) { - afloat[i * 24 * 24 + j * 24 + k] = (float) b(j - 12, k - 12, i - 12); - } - } - } - - }); - private static final IBlockData i = Blocks.AIR.getBlockData(); - private final int j; - private final int k; - private final int l; - private final int m; - private final int n; - protected final SeededRandom e; - private final NoiseGeneratorOctaves o; - private final NoiseGeneratorOctaves p; - private final NoiseGeneratorOctaves q; - private final NoiseGenerator r; - protected final IBlockData f; - protected final IBlockData g; - - public ChunkGeneratorAbstract(GeneratorAccess generatoraccess, WorldChunkManager worldchunkmanager, int i, int j, int k, T t0, boolean flag) { - super(generatoraccess, worldchunkmanager, t0); - this.j = j; - this.k = i; - this.f = t0.r(); - this.g = t0.s(); - this.l = 16 / this.k; - this.m = k / this.j; - this.n = 16 / this.k; - this.e = new SeededRandom(this.seed); - this.o = new NoiseGeneratorOctaves(this.e, 16); - this.p = new NoiseGeneratorOctaves(this.e, 16); - this.q = new NoiseGeneratorOctaves(this.e, 8); - this.r = (NoiseGenerator) (flag ? new NoiseGenerator3(this.e, 4) : new NoiseGeneratorOctaves(this.e, 4)); - } - - private double a(int i, int j, int k, double d0, double d1, double d2, double d3) { - double d4 = 0.0D; - double d5 = 0.0D; - double d6 = 0.0D; - double d7 = 1.0D; - - for (int l = 0; l < 16; ++l) { - double d8 = NoiseGeneratorOctaves.a((double) i * d0 * d7); - double d9 = NoiseGeneratorOctaves.a((double) j * d1 * d7); - double d10 = NoiseGeneratorOctaves.a((double) k * d0 * d7); - double d11 = d1 * d7; - - d4 += this.o.a(l).a(d8, d9, d10, d11, (double) j * d11) / d7; - d5 += this.p.a(l).a(d8, d9, d10, d11, (double) j * d11) / d7; - if (l < 8) { - d6 += this.q.a(l).a(NoiseGeneratorOctaves.a((double) i * d2 * d7), NoiseGeneratorOctaves.a((double) j * d3 * d7), NoiseGeneratorOctaves.a((double) k * d2 * d7), d3 * d7, (double) j * d3 * d7) / d7; - } - - d7 /= 2.0D; - } - - return MathHelper.b(d4 / 512.0D, d5 / 512.0D, (d6 / 10.0D + 1.0D) / 2.0D); - } - - protected double[] b(int i, int j) { - double[] adouble = new double[this.m + 1]; - - this.a(adouble, i, j); - return adouble; - } - - protected void a(double[] adouble, int i, int j, double d0, double d1, double d2, double d3, int k, int l) { - double[] adouble1 = this.a(i, j); - double d4 = adouble1[0]; - double d5 = adouble1[1]; - double d6 = this.g(); - double d7 = this.h(); - - for (int i1 = 0; i1 < this.i(); ++i1) { - double d8 = this.a(i, i1, j, d0, d1, d2, d3); - - d8 -= this.a(d4, d5, i1); - if ((double) i1 > d6) { - d8 = MathHelper.b(d8, (double) l, ((double) i1 - d6) / (double) k); - } else if ((double) i1 < d7) { - d8 = MathHelper.b(d8, -30.0D, (d7 - (double) i1) / (d7 - 1.0D)); - } - - adouble[i1] = d8; - } - - } - - protected abstract double[] a(int i, int j); - - protected abstract double a(double d0, double d1, int i); - - protected double g() { - return (double) (this.i() - 4); - } - - protected double h() { - return 0.0D; - } - - @Override - public int getBaseHeight(int i, int j, HeightMap.Type heightmap_type) { - int k = Math.floorDiv(i, this.k); - int l = Math.floorDiv(j, this.k); - int i1 = Math.floorMod(i, this.k); - int j1 = Math.floorMod(j, this.k); - double d0 = (double) i1 / (double) this.k; - double d1 = (double) j1 / (double) this.k; - double[][] adouble = new double[][]{this.b(k, l), this.b(k, l + 1), this.b(k + 1, l), this.b(k + 1, l + 1)}; - int k1 = this.getSeaLevel(); - - for (int l1 = this.m - 1; l1 >= 0; --l1) { - double d2 = adouble[0][l1]; - double d3 = adouble[1][l1]; - double d4 = adouble[2][l1]; - double d5 = adouble[3][l1]; - double d6 = adouble[0][l1 + 1]; - double d7 = adouble[1][l1 + 1]; - double d8 = adouble[2][l1 + 1]; - double d9 = adouble[3][l1 + 1]; - - for (int i2 = this.j - 1; i2 >= 0; --i2) { - double d10 = (double) i2 / (double) this.j; - double d11 = MathHelper.a(d10, d0, d1, d2, d6, d4, d8, d3, d7, d5, d9); - int j2 = l1 * this.j + i2; - - if (d11 > 0.0D || j2 < k1) { - IBlockData iblockdata; - - if (d11 > 0.0D) { - iblockdata = this.f; - } else { - iblockdata = this.g; - } - - if (heightmap_type.d().test(iblockdata)) { - return j2 + 1; - } - } - } - } - - return 0; - } - - protected abstract void a(double[] adouble, int i, int j); - - public int i() { - return this.m + 1; - } - - @Override - public void buildBase(IChunkAccess ichunkaccess) { - ChunkCoordIntPair chunkcoordintpair = ichunkaccess.getPos(); - int i = chunkcoordintpair.x; - int j = chunkcoordintpair.z; - SeededRandom seededrandom = new SeededRandom(); - - seededrandom.a(i, j); - ChunkCoordIntPair chunkcoordintpair1 = ichunkaccess.getPos(); - int k = chunkcoordintpair1.d(); - int l = chunkcoordintpair1.e(); - double d0 = 0.0625D; - BiomeBase[] abiomebase = ichunkaccess.getBiomeIndex(); - - for (int i1 = 0; i1 < 16; ++i1) { - for (int j1 = 0; j1 < 16; ++j1) { - int k1 = k + i1; - int l1 = l + j1; - int i2 = ichunkaccess.a(HeightMap.Type.WORLD_SURFACE_WG, i1, j1) + 1; - double d1 = this.r.a((double) k1 * 0.0625D, (double) l1 * 0.0625D, 0.0625D, (double) i1 * 0.0625D); - - abiomebase[j1 * 16 + i1].a(seededrandom, ichunkaccess, k1, l1, i2, d1, this.getSettings().r(), this.getSettings().s(), this.getSeaLevel(), this.a.getSeed()); - } - } - - this.a(ichunkaccess, seededrandom); - } - - protected void a(IChunkAccess ichunkaccess, Random random) { - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - int i = ichunkaccess.getPos().d(); - int j = ichunkaccess.getPos().e(); - T t0 = this.getSettings(); - int k = t0.u(); final int floorHeight = k; // Paper - int l = t0.t(); final int roofHeight = l; // Paper - Iterator iterator = BlockPosition.b(i, 0, j, i + 15, 0, j + 15).iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition = (BlockPosition) iterator.next(); - int i1; - - if (l > 0) { - for (i1 = l; i1 >= l - 4; --i1) { - if (i1 >= (getWorld().paperConfig.generateFlatBedrock ? roofHeight : l - random.nextInt(5))) { // Paper - Configurable flat bedrock roof - ichunkaccess.setType(blockposition_mutableblockposition.d(blockposition.getX(), i1, blockposition.getZ()), Blocks.BEDROCK.getBlockData(), false); - } - } - } - - if (k < 256) { - for (i1 = k + 4; i1 >= k; --i1) { - if (i1 <= (getWorld().paperConfig.generateFlatBedrock ? floorHeight : k + random.nextInt(5))) { // Paper - Configurable flat bedrock floor - ichunkaccess.setType(blockposition_mutableblockposition.d(blockposition.getX(), i1, blockposition.getZ()), Blocks.BEDROCK.getBlockData(), false); - } - } - } - } - - } - - @Override - public void buildNoise(GeneratorAccess generatoraccess, IChunkAccess ichunkaccess) { - int i = this.getSeaLevel(); - ObjectList objectlist = new ObjectArrayList(10); - ObjectList objectlist1 = new ObjectArrayList(32); - ChunkCoordIntPair chunkcoordintpair = ichunkaccess.getPos(); - int j = chunkcoordintpair.x; - int k = chunkcoordintpair.z; - int l = j << 4; - int i1 = k << 4; - Iterator iterator = WorldGenerator.aQ.iterator(); - - while (iterator.hasNext()) { - StructureGenerator structuregenerator = (StructureGenerator) iterator.next(); - String s = structuregenerator.b(); - LongIterator longiterator = ichunkaccess.b(s).iterator(); - - while (longiterator.hasNext()) { - long j1 = longiterator.nextLong(); - ChunkCoordIntPair chunkcoordintpair1 = new ChunkCoordIntPair(j1); - IChunkAccess ichunkaccess1 = generatoraccess.getChunkAt(chunkcoordintpair1.x, chunkcoordintpair1.z); - StructureStart structurestart = ichunkaccess1.a(s); - - if (structurestart != null && structurestart.e()) { - Iterator iterator1 = structurestart.d().iterator(); - - while (iterator1.hasNext()) { - StructurePiece structurepiece = (StructurePiece) iterator1.next(); - - if (structurepiece.a(chunkcoordintpair, 12) && structurepiece instanceof WorldGenFeaturePillagerOutpostPoolPiece) { - WorldGenFeaturePillagerOutpostPoolPiece worldgenfeaturepillageroutpostpoolpiece = (WorldGenFeaturePillagerOutpostPoolPiece) structurepiece; - WorldGenFeatureDefinedStructurePoolTemplate.Matching worldgenfeaturedefinedstructurepooltemplate_matching = worldgenfeaturepillageroutpostpoolpiece.b().c(); - - if (worldgenfeaturedefinedstructurepooltemplate_matching == WorldGenFeatureDefinedStructurePoolTemplate.Matching.RIGID) { - objectlist.add(worldgenfeaturepillageroutpostpoolpiece); - } - - Iterator iterator2 = worldgenfeaturepillageroutpostpoolpiece.e().iterator(); - - while (iterator2.hasNext()) { - WorldGenFeatureDefinedStructureJigsawJunction worldgenfeaturedefinedstructurejigsawjunction = (WorldGenFeatureDefinedStructureJigsawJunction) iterator2.next(); - int k1 = worldgenfeaturedefinedstructurejigsawjunction.a(); - int l1 = worldgenfeaturedefinedstructurejigsawjunction.c(); - - if (k1 > l - 12 && l1 > i1 - 12 && k1 < l + 15 + 12 && l1 < i1 + 15 + 12) { - objectlist1.add(worldgenfeaturedefinedstructurejigsawjunction); - } - } - } - } - } - } - } - - double[][][] adouble = new double[2][this.n + 1][this.m + 1]; - - for (int i2 = 0; i2 < this.n + 1; ++i2) { - adouble[0][i2] = new double[this.m + 1]; - this.a(adouble[0][i2], j * this.l, k * this.n + i2); - adouble[1][i2] = new double[this.m + 1]; - } - - ProtoChunk protochunk = (ProtoChunk) ichunkaccess; - HeightMap heightmap = protochunk.b(HeightMap.Type.OCEAN_FLOOR_WG); - HeightMap heightmap1 = protochunk.b(HeightMap.Type.WORLD_SURFACE_WG); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - ObjectListIterator objectlistiterator = objectlist.iterator(); - ObjectListIterator objectlistiterator1 = objectlist1.iterator(); - - for (int j2 = 0; j2 < this.l; ++j2) { - int k2; - - for (k2 = 0; k2 < this.n + 1; ++k2) { - this.a(adouble[1][k2], j * this.l + j2 + 1, k * this.n + k2); - } - - for (k2 = 0; k2 < this.n; ++k2) { - ChunkSection chunksection = protochunk.a(15); - - chunksection.a(); - - for (int l2 = this.m - 1; l2 >= 0; --l2) { - double d0 = adouble[0][k2][l2]; - double d1 = adouble[0][k2 + 1][l2]; - double d2 = adouble[1][k2][l2]; - double d3 = adouble[1][k2 + 1][l2]; - double d4 = adouble[0][k2][l2 + 1]; - double d5 = adouble[0][k2 + 1][l2 + 1]; - double d6 = adouble[1][k2][l2 + 1]; - double d7 = adouble[1][k2 + 1][l2 + 1]; - - for (int i3 = this.j - 1; i3 >= 0; --i3) { - int j3 = l2 * this.j + i3; - int k3 = j3 & 15; - int l3 = j3 >> 4; - - if (chunksection.getYPosition() >> 4 != l3) { - chunksection.b(); - chunksection = protochunk.a(l3); - chunksection.a(); - } - - double d8 = (double) i3 / (double) this.j; - double d9 = MathHelper.d(d8, d0, d4); - double d10 = MathHelper.d(d8, d2, d6); - double d11 = MathHelper.d(d8, d1, d5); - double d12 = MathHelper.d(d8, d3, d7); - - for (int i4 = 0; i4 < this.k; ++i4) { - int j4 = l + j2 * this.k + i4; - int k4 = j4 & 15; - double d13 = (double) i4 / (double) this.k; - double d14 = MathHelper.d(d13, d9, d10); - double d15 = MathHelper.d(d13, d11, d12); - - for (int l4 = 0; l4 < this.k; ++l4) { - int i5 = i1 + k2 * this.k + l4; - int j5 = i5 & 15; - double d16 = (double) l4 / (double) this.k; - double d17 = MathHelper.d(d16, d14, d15); - double d18 = MathHelper.a(d17 / 200.0D, -1.0D, 1.0D); - - int k5; - int l5; - int i6; - - for (d18 = d18 / 2.0D - d18 * d18 * d18 / 24.0D; objectlistiterator.hasNext(); d18 += a(k5, l5, i6) * 0.8D) { - WorldGenFeaturePillagerOutpostPoolPiece worldgenfeaturepillageroutpostpoolpiece1 = (WorldGenFeaturePillagerOutpostPoolPiece) objectlistiterator.next(); - StructureBoundingBox structureboundingbox = worldgenfeaturepillageroutpostpoolpiece1.g(); - - k5 = Math.max(0, Math.max(structureboundingbox.a - j4, j4 - structureboundingbox.d)); - l5 = j3 - (structureboundingbox.b + worldgenfeaturepillageroutpostpoolpiece1.d()); - i6 = Math.max(0, Math.max(structureboundingbox.c - i5, i5 - structureboundingbox.f)); - } - - objectlistiterator.back(objectlist.size()); - - while (objectlistiterator1.hasNext()) { - WorldGenFeatureDefinedStructureJigsawJunction worldgenfeaturedefinedstructurejigsawjunction1 = (WorldGenFeatureDefinedStructureJigsawJunction) objectlistiterator1.next(); - int j6 = j4 - worldgenfeaturedefinedstructurejigsawjunction1.a(); - - k5 = j3 - worldgenfeaturedefinedstructurejigsawjunction1.b(); - l5 = i5 - worldgenfeaturedefinedstructurejigsawjunction1.c(); - d18 += a(j6, k5, l5) * 0.4D; - } - - objectlistiterator1.back(objectlist1.size()); - IBlockData iblockdata; - - if (d18 > 0.0D) { - iblockdata = this.f; - } else if (j3 < i) { - iblockdata = this.g; - } else { - iblockdata = ChunkGeneratorAbstract.i; - } - - if (iblockdata != ChunkGeneratorAbstract.i) { - if (iblockdata.h() != 0) { - blockposition_mutableblockposition.d(j4, j3, i5); - protochunk.k(blockposition_mutableblockposition); - } - - chunksection.setType(k4, k3, j5, iblockdata, false); - heightmap.a(k4, j3, j5, iblockdata); - heightmap1.a(k4, j3, j5, iblockdata); - } - } - } - } - } - - chunksection.b(); - } - - double[][] adouble1 = adouble[0]; - - adouble[0] = adouble[1]; - adouble[1] = adouble1; - } - - } - - private static double a(int i, int j, int k) { - int l = i + 12; - int i1 = j + 12; - int j1 = k + 12; - - return l >= 0 && l < 24 ? (i1 >= 0 && i1 < 24 ? (j1 >= 0 && j1 < 24 ? (double) ChunkGeneratorAbstract.h[j1 * 24 * 24 + l * 24 + i1] : 0.0D) : 0.0D) : 0.0D; - } - - private static double b(int i, int j, int k) { - double d0 = (double) (i * i + k * k); - double d1 = (double) j + 0.5D; - double d2 = d1 * d1; - double d3 = Math.pow(2.718281828459045D, -(d2 / 16.0D + d0 / 16.0D)); - double d4 = -d1 * MathHelper.i(d2 / 2.0D + d0 / 2.0D) / 2.0D; - - return d4 * d3; - } -} diff --git a/src/main/java/net/minecraft/server/ChunkMapDistance.java b/src/main/java/net/minecraft/server/ChunkMapDistance.java deleted file mode 100644 index 63a688725..000000000 --- a/src/main/java/net/minecraft/server/ChunkMapDistance.java +++ /dev/null @@ -1,493 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Sets; -import com.mojang.datafixers.util.Either; -import it.unimi.dsi.fastutil.longs.Long2ByteMap; -import it.unimi.dsi.fastutil.longs.Long2ByteOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2IntMap; -import it.unimi.dsi.fastutil.longs.Long2IntMaps; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -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 it.unimi.dsi.fastutil.longs.Long2ObjectMap.Entry; -import it.unimi.dsi.fastutil.objects.ObjectAVLTreeSet; -import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; -import it.unimi.dsi.fastutil.objects.ObjectSet; -import it.unimi.dsi.fastutil.objects.ObjectSortedSet; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public abstract class ChunkMapDistance { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final int b = 33 + ChunkStatus.a(ChunkStatus.FULL) - 2; - private final Long2ObjectMap> c = new Long2ObjectOpenHashMap(); - public final Long2ObjectOpenHashMap>> tickets = new Long2ObjectOpenHashMap(); // CraftBukkit - private -> public - private final ChunkMapDistance.a e = new ChunkMapDistance.a(); - private final ChunkMapDistance.b f = new ChunkMapDistance.b(8); - private final ChunkMapDistance.c g = new ChunkMapDistance.c(33); - private final java.util.Queue pendingChunkUpdates = new java.util.LinkedList<>(); // PAIL pendingChunkUpdates // Paper - use a queue - private final ChunkTaskQueueSorter i; - private final Mailbox> j; - private final Mailbox k; - private final LongSet l = new LongOpenHashSet(); - private final Executor m; - private long currentTick; - - protected ChunkMapDistance(Executor executor, Executor executor1) { - executor1.getClass(); - Mailbox mailbox = Mailbox.a("player ticket throttler", executor1::execute); - ChunkTaskQueueSorter chunktaskqueuesorter = new ChunkTaskQueueSorter(ImmutableList.of(mailbox), executor, 4); - - this.i = chunktaskqueuesorter; - this.j = chunktaskqueuesorter.a(mailbox, true); - this.k = chunktaskqueuesorter.a(mailbox); - this.m = executor1; - } - - protected void purgeTickets() { - ++this.currentTick; - ObjectIterator objectiterator = this.tickets.long2ObjectEntrySet().fastIterator(); - - while (objectiterator.hasNext()) { - Entry>> entry = (Entry) objectiterator.next(); - - if ((entry.getValue()).removeIf((ticket) -> { // Craftbukkit - decompile error - return ticket.a(this.currentTick); - })) { - this.e.b(entry.getLongKey(), this.a((ObjectSortedSet) entry.getValue()), false); - } - - if (((ObjectSortedSet) entry.getValue()).isEmpty()) { - objectiterator.remove(); - } - } - - } - - private int a(ObjectSortedSet> objectsortedset) { - ObjectBidirectionalIterator> objectbidirectionaliterator = objectsortedset.iterator(); - - return objectbidirectionaliterator.hasNext() ? ((Ticket) objectbidirectionaliterator.next()).b() : PlayerChunkMap.GOLDEN_TICKET + 1; - } - - protected abstract boolean a(long i); - - @Nullable - protected abstract PlayerChunk b(long i); - - @Nullable - protected abstract PlayerChunk a(long i, int j, @Nullable PlayerChunk playerchunk, int k); - - public boolean a(PlayerChunkMap playerchunkmap) { - this.f.a(); - this.g.a(); - int i = Integer.MAX_VALUE - this.e.a(Integer.MAX_VALUE); - boolean flag = i != 0; - - if (flag) { - ; - } - - // Paper start - if (!this.pendingChunkUpdates.isEmpty()) { - while(!this.pendingChunkUpdates.isEmpty()) { - this.pendingChunkUpdates.remove().a(playerchunkmap); - } - // Paper end - return true; - } else { - if (!this.l.isEmpty()) { - LongIterator longiterator = this.l.iterator(); - - while (longiterator.hasNext()) { - long j = longiterator.nextLong(); - - if (this.e(j).stream().anyMatch((ticket) -> { - return ticket.getTicketType() == TicketType.PLAYER; - })) { - PlayerChunk playerchunk = playerchunkmap.getUpdatingChunk(j); - - if (playerchunk == null) { - throw new IllegalStateException(); - } - - CompletableFuture> completablefuture = playerchunk.b(); - - completablefuture.thenAccept((either) -> { - this.m.execute(() -> { - this.k.a(ChunkTaskQueueSorter.a(() -> { // Craftbukkit - decompile error - }, j, false)); - }); - }); - } - } - - this.l.clear(); - } - - return flag; - } - } - - private boolean addTicket(long i, Ticket ticket) { // CraftBukkit - void -> boolean - ObjectSortedSet> objectsortedset = this.e(i); - ObjectBidirectionalIterator> objectbidirectionaliterator = objectsortedset.iterator(); - int j; - - if (objectbidirectionaliterator.hasNext()) { - j = ((Ticket) objectbidirectionaliterator.next()).b(); - } else { - j = PlayerChunkMap.GOLDEN_TICKET + 1; - } - - boolean ret = false; // CraftBukkit - if (objectsortedset.add(ticket)) { - ret = true; // CraftBukkit - } - - if (ticket.b() < j) { - this.e.b(i, ticket.b(), true); - } - - return ret; // CraftBukkit - } - - private boolean removeTicket(long i, Ticket ticket) { // CraftBukkit - void -> boolean - ObjectSortedSet> objectsortedset = this.e(i); - - boolean removed = false; // CraftBukkit - if (objectsortedset.remove(ticket)) { - removed = true; // CraftBukkit - } - - if (objectsortedset.isEmpty()) { - this.tickets.remove(i); - } - - this.e.b(i, this.a(objectsortedset), false); - return removed; // CraftBukkit - } - - public void a(TicketType tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) { - // CraftBukkit start - this.addTicketAtLevel(tickettype, chunkcoordintpair, i, t0); - } - - public boolean addTicketAtLevel(TicketType ticketType, ChunkCoordIntPair chunkcoordintpair, int level, T identifier) { - return this.addTicket(chunkcoordintpair.pair(), new Ticket<>(ticketType, level, identifier, this.currentTick)); - // CraftBukkit end - } - - public void b(TicketType tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) { - // CraftBukkit start - this.removeTicketAtLevel(tickettype, chunkcoordintpair, i, t0); - } - - public boolean removeTicketAtLevel(TicketType ticketType, ChunkCoordIntPair chunkcoordintpair, int level, T identifier) { - Ticket ticket = new Ticket<>(ticketType, level, identifier, this.currentTick); - - return this.removeTicket(chunkcoordintpair.pair(), ticket); - // CraftBukkit end - } - - public void addTicket(TicketType tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) { - this.addTicket(chunkcoordintpair.pair(), new Ticket<>(tickettype, 33 - i, t0, this.currentTick)); - } - - public void removeTicket(TicketType tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) { - Ticket ticket = new Ticket<>(tickettype, 33 - i, t0, this.currentTick); - - this.removeTicket(chunkcoordintpair.pair(), ticket); - } - - private ObjectSortedSet> e(long i) { - return (ObjectSortedSet) this.tickets.computeIfAbsent(i, (j) -> { - return new ObjectAVLTreeSet(); - }); - } - - protected void a(ChunkCoordIntPair chunkcoordintpair, boolean flag) { - Ticket ticket = new Ticket<>(TicketType.FORCED, 31, chunkcoordintpair, this.currentTick); - - if (flag) { - this.addTicket(chunkcoordintpair.pair(), ticket); - } else { - this.removeTicket(chunkcoordintpair.pair(), ticket); - } - - } - - public void a(SectionPosition sectionposition, EntityPlayer entityplayer) { - long i = sectionposition.u().pair(); - - ((ObjectSet) this.c.computeIfAbsent(i, (j) -> { - return new ObjectOpenHashSet(); - })).add(entityplayer); - this.f.b(i, 0, true); - this.g.b(i, 0, true); - } - - public void b(SectionPosition sectionposition, EntityPlayer entityplayer) { - long i = sectionposition.u().pair(); - ObjectSet objectset = (ObjectSet) this.c.get(i); - - objectset.remove(entityplayer); - if (objectset.isEmpty()) { - this.c.remove(i); - this.f.b(i, Integer.MAX_VALUE, false); - this.g.b(i, Integer.MAX_VALUE, false); - } - - } - - protected String c(long i) { - ObjectSortedSet> objectsortedset = (ObjectSortedSet) this.tickets.get(i); - String s; - - if (objectsortedset != null && !objectsortedset.isEmpty()) { - s = ((Ticket) objectsortedset.first()).toString(); - } else { - s = "no_ticket"; - } - - return s; - } - - protected void a(int i) { - this.g.a(i); - } - - public int b() { - this.f.a(); - return this.f.a.size(); - } - - public boolean d(long i) { - this.f.a(); - return this.f.a.containsKey(i); - } - - public String c() { - return this.i.a(); - } - - // CraftBukkit start - public void removeAllTicketsFor(TicketType ticketType, int ticketLevel, T ticketIdentifier) { - Ticket target = new Ticket<>(ticketType, ticketLevel, ticketIdentifier, this.currentTick); - - for (java.util.Iterator>> iterator = this.tickets.values().iterator(); iterator.hasNext();) { - ObjectSortedSet> tickets = iterator.next(); - tickets.remove(target); - - if (tickets.isEmpty()) { - iterator.remove(); - } - } - } - // CraftBukkit end - - class a extends ChunkMap { - - public a() { - super(PlayerChunkMap.GOLDEN_TICKET + 2, 16, 256); - } - - @Override - protected int b(long i) { - ObjectSortedSet> objectsortedset = (ObjectSortedSet) ChunkMapDistance.this.tickets.get(i); - - if (objectsortedset == null) { - return Integer.MAX_VALUE; - } else { - ObjectBidirectionalIterator> objectbidirectionaliterator = objectsortedset.iterator(); - - return !objectbidirectionaliterator.hasNext() ? Integer.MAX_VALUE : ((Ticket) objectbidirectionaliterator.next()).b(); - } - } - - @Override - protected int c(long i) { - if (!ChunkMapDistance.this.a(i)) { - PlayerChunk playerchunk = ChunkMapDistance.this.b(i); - - if (playerchunk != null) { - return playerchunk.getTicketLevel(); - } - } - - return PlayerChunkMap.GOLDEN_TICKET + 1; - } - - @Override - protected void a(long i, int j) { - PlayerChunk playerchunk = ChunkMapDistance.this.b(i); - int k = playerchunk == null ? PlayerChunkMap.GOLDEN_TICKET + 1 : playerchunk.getTicketLevel(); - - if (k != j) { - playerchunk = ChunkMapDistance.this.a(i, j, playerchunk, k); - if (playerchunk != null) { - ChunkMapDistance.this.pendingChunkUpdates.add(playerchunk); - } - - } - } - - public int a(int i) { - return this.b(i); - } - } - - class c extends ChunkMapDistance.b { - - private int e = 0; - private final Long2IntMap f = Long2IntMaps.synchronize(new Long2IntOpenHashMap()); - private final LongSet g = new LongOpenHashSet(); - - protected c(int i) { - super(i); - this.f.defaultReturnValue(i + 2); - } - - @Override - protected void a(long i, int j, int k) { - this.g.add(i); - } - - public void a(int i) { - ObjectIterator objectiterator = this.a.long2ByteEntrySet().iterator(); - - while (objectiterator.hasNext()) { - it.unimi.dsi.fastutil.longs.Long2ByteMap.Entry it_unimi_dsi_fastutil_longs_long2bytemap_entry = (it.unimi.dsi.fastutil.longs.Long2ByteMap.Entry) objectiterator.next(); - byte b0 = it_unimi_dsi_fastutil_longs_long2bytemap_entry.getByteValue(); - long j = it_unimi_dsi_fastutil_longs_long2bytemap_entry.getLongKey(); - - this.a(j, b0, this.c(b0), b0 <= i - 2); - } - - this.e = i; - } - - private void a(long i, int j, boolean flag, boolean flag1) { - if (flag != flag1) { - Ticket ticket = new Ticket<>(TicketType.PLAYER, ChunkMapDistance.b, new ChunkCoordIntPair(i), ChunkMapDistance.this.currentTick); - - if (flag1) { - ChunkMapDistance.this.j.a(ChunkTaskQueueSorter.a(() -> { // Craftbukkit - decompile error - ChunkMapDistance.this.m.execute(() -> { - if (this.c(this.c(i))) { - ChunkMapDistance.this.addTicket(i, ticket); - ChunkMapDistance.this.l.add(i); - } else { - ChunkMapDistance.this.k.a(ChunkTaskQueueSorter.a(() -> { // Craftbukkit - decompile error - }, i, false)); - } - - }); - }, i, () -> { - return j; - })); - } else { - ChunkMapDistance.this.k.a(ChunkTaskQueueSorter.a(() -> { // Craftbukkit - decompile error - ChunkMapDistance.this.m.execute(() -> { - ChunkMapDistance.this.removeTicket(i, ticket); - }); - }, i, true)); - } - } - - } - - @Override - public void a() { - super.a(); - if (!this.g.isEmpty()) { - LongIterator longiterator = this.g.iterator(); - - while (longiterator.hasNext()) { - long i = longiterator.nextLong(); - int j = this.f.get(i); - int k = this.c(i); - - if (j != k) { - ChunkMapDistance.this.i.a(new ChunkCoordIntPair(i), () -> { - return this.f.get(i); - }, k, (l) -> { - if (l >= this.f.defaultReturnValue()) { - this.f.remove(i); - } else { - this.f.put(i, l); - } - - }); - this.a(i, k, this.c(j), this.c(k)); - } - } - - this.g.clear(); - } - - } - - private boolean c(int i) { - return i <= this.e - 2; - } - } - - class b extends ChunkMap { - - protected final Long2ByteMap a = new Long2ByteOpenHashMap(); - protected final int b; - - protected b(int i) { - super(i + 2, 16, 256); - this.b = i; - this.a.defaultReturnValue((byte) (i + 2)); - } - - @Override - protected int c(long i) { - return this.a.get(i); - } - - @Override - protected void a(long i, int j) { - byte b0; - - if (j > this.b) { - b0 = this.a.remove(i); - } else { - b0 = this.a.put(i, (byte) j); - } - - this.a(i, b0, j); - } - - protected void a(long i, int j, int k) {} - - @Override - protected int b(long i) { - return this.d(i) ? 0 : Integer.MAX_VALUE; - } - - private boolean d(long i) { - ObjectSet objectset = (ObjectSet) ChunkMapDistance.this.c.get(i); - - return objectset != null && !objectset.isEmpty(); - } - - public void a() { - this.b(Integer.MAX_VALUE); - } - } -} diff --git a/src/main/java/net/minecraft/server/ChunkProviderGenerate.java b/src/main/java/net/minecraft/server/ChunkProviderGenerate.java deleted file mode 100644 index b794a39d3..000000000 --- a/src/main/java/net/minecraft/server/ChunkProviderGenerate.java +++ /dev/null @@ -1,173 +0,0 @@ -package net.minecraft.server; - -import java.util.List; - -public class ChunkProviderGenerate extends ChunkGeneratorAbstract { - - private static final float[] h = (float[]) SystemUtils.a((new float[25]), (afloat) -> { // CraftBukkit - decompile error - for (int i = -2; i <= 2; ++i) { - for (int j = -2; j <= 2; ++j) { - float f = 10.0F / MathHelper.c((float) (i * i + j * j) + 0.2F); - - afloat[i + 2 + (j + 2) * 5] = f; - } - } - - }); - private final NoiseGeneratorOctaves i; - private final boolean j; - private final MobSpawnerPhantom k = new MobSpawnerPhantom(); - private final MobSpawnerPatrol l = new MobSpawnerPatrol(); - private final MobSpawnerCat m = new MobSpawnerCat(); - private final VillageSiege n = new VillageSiege(); - - public ChunkProviderGenerate(GeneratorAccess generatoraccess, WorldChunkManager worldchunkmanager, GeneratorSettingsOverworld generatorsettingsoverworld) { - super(generatoraccess, worldchunkmanager, 4, 8, 256, generatorsettingsoverworld, true); - this.e.a(2620); - this.i = new NoiseGeneratorOctaves(this.e, 16); - this.j = generatoraccess.getWorldData().getType() == WorldType.AMPLIFIED; - } - - @Override - public void addMobs(RegionLimitedWorldAccess regionlimitedworldaccess) { - int i = regionlimitedworldaccess.a(); - int j = regionlimitedworldaccess.b(); - BiomeBase biomebase = regionlimitedworldaccess.getChunkAt(i, j).getBiomeIndex()[0]; - SeededRandom seededrandom = new SeededRandom(); - - seededrandom.a(regionlimitedworldaccess.getSeed(), i << 4, j << 4); - SpawnerCreature.a(regionlimitedworldaccess, biomebase, i, j, seededrandom); - } - - @Override - protected void a(double[] adouble, int i, int j) { - double d0 = 684.4119873046875D; - double d1 = 684.4119873046875D; - double d2 = 8.555149841308594D; - double d3 = 4.277574920654297D; - boolean flag = true; - boolean flag1 = true; - - this.a(adouble, i, j, 684.4119873046875D, 684.4119873046875D, 8.555149841308594D, 4.277574920654297D, 3, -10); - } - - @Override - protected double a(double d0, double d1, int i) { - double d2 = 8.5D; - double d3 = ((double) i - (8.5D + d0 * 8.5D / 8.0D * 4.0D)) * 12.0D * 128.0D / 256.0D / d1; - - if (d3 < 0.0D) { - d3 *= 4.0D; - } - - return d3; - } - - @Override - protected double[] a(int i, int j) { - double[] adouble = new double[2]; - float f = 0.0F; - float f1 = 0.0F; - float f2 = 0.0F; - boolean flag = true; - float f3 = this.c.b(i, j).g(); - - for (int k = -2; k <= 2; ++k) { - for (int l = -2; l <= 2; ++l) { - BiomeBase biomebase = this.c.b(i + k, j + l); - float f4 = biomebase.g(); - float f5 = biomebase.k(); - - if (this.j && f4 > 0.0F) { - f4 = 1.0F + f4 * 2.0F; - f5 = 1.0F + f5 * 4.0F; - } - // CraftBukkit start - fix MC-54738 - if (f4 < -1.8F) { - f4 = -1.8F; - } - // CraftBukkit end - - float f6 = ChunkProviderGenerate.h[k + 2 + (l + 2) * 5] / (f4 + 2.0F); - - if (biomebase.g() > f3) { - f6 /= 2.0F; - } - - f += f5 * f6; - f1 += f4 * f6; - f2 += f6; - } - } - - f /= f2; - f1 /= f2; - f = f * 0.9F + 0.1F; - f1 = (f1 * 4.0F - 1.0F) / 8.0F; - adouble[0] = (double) f1 + this.c(i, j); - adouble[1] = (double) f; - return adouble; - } - - private double c(int i, int j) { - double d0 = this.i.a((double) (i * 200), 10.0D, (double) (j * 200), 1.0D, 0.0D, true) / 8000.0D; - - if (d0 < 0.0D) { - d0 = -d0 * 0.3D; - } - - d0 = d0 * 3.0D - 2.0D; - if (d0 < 0.0D) { - d0 /= 28.0D; - } else { - if (d0 > 1.0D) { - d0 = 1.0D; - } - - d0 /= 40.0D; - } - - return d0; - } - - @Override - public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { - if (WorldGenerator.SWAMP_HUT.c(this.a, blockposition)) { - if (enumcreaturetype == EnumCreatureType.MONSTER) { - return WorldGenerator.SWAMP_HUT.e(); - } - - if (enumcreaturetype == EnumCreatureType.CREATURE) { - return WorldGenerator.SWAMP_HUT.f(); - } - } else if (enumcreaturetype == EnumCreatureType.MONSTER) { - if (WorldGenerator.PILLAGER_OUTPOST.a(this.a, blockposition)) { - return WorldGenerator.PILLAGER_OUTPOST.e(); - } - - if (WorldGenerator.OCEAN_MONUMENT.a(this.a, blockposition)) { - return WorldGenerator.OCEAN_MONUMENT.e(); - } - } - - return super.getMobsFor(enumcreaturetype, blockposition); - } - - @Override - public void doMobSpawning(WorldServer worldserver, boolean flag, boolean flag1) { - this.k.a(worldserver, flag, flag1); - this.l.a(worldserver, flag, flag1); - this.m.a(worldserver, flag, flag1); - this.n.a(worldserver, flag, flag1); - } - - @Override - public int getSpawnHeight() { - return this.a.getSeaLevel() + 1; - } - - @Override - public int getSeaLevel() { - return 63; - } -} diff --git a/src/main/java/net/minecraft/server/ChunkProviderServer.java b/src/main/java/net/minecraft/server/ChunkProviderServer.java deleted file mode 100644 index e7539dd79..000000000 --- a/src/main/java/net/minecraft/server/ChunkProviderServer.java +++ /dev/null @@ -1,819 +0,0 @@ -package net.minecraft.server; - -import com.google.common.annotations.VisibleForTesting; -import com.mojang.datafixers.DataFixer; -import com.mojang.datafixers.util.Either; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; -import java.util.function.BooleanSupplier; -import java.util.function.Function; -import java.util.function.Supplier; -import javax.annotation.Nullable; -import com.destroystokyo.paper.exception.ServerInternalException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class ChunkProviderServer extends IChunkProvider { - - private static final int b = (int) Math.pow(17.0D, 2.0D); - private static final List c = ChunkStatus.a(); static final List getPossibleChunkStatuses() { return ChunkProviderServer.c; } // Paper - OBFHELPER - private final ChunkMapDistance chunkMapDistance; - public final ChunkGenerator chunkGenerator; - private final WorldServer world; - private final Thread serverThread; - private final LightEngineThreaded lightEngine; - public final ChunkProviderServer.a serverThreadQueue; // Paper private -> public - public final PlayerChunkMap playerChunkMap; - private final WorldPersistentData worldPersistentData; - private long lastTickTime; - public boolean allowMonsters = true; - public boolean allowAnimals = true; - private final long[] cachePos = new long[4]; - private final ChunkStatus[] cacheStatus = new ChunkStatus[4]; - private final IChunkAccess[] cacheChunk = new IChunkAccess[4]; - - public ChunkProviderServer(WorldServer worldserver, File file, DataFixer datafixer, DefinedStructureManager definedstructuremanager, Executor executor, ChunkGenerator chunkgenerator, int i, WorldLoadListener worldloadlistener, Supplier supplier) { - this.world = worldserver; - this.serverThreadQueue = new ChunkProviderServer.a(worldserver); - this.chunkGenerator = chunkgenerator; - this.serverThread = Thread.currentThread(); - File file1 = worldserver.getWorldProvider().getDimensionManager().a(file); - File file2 = new File(file1, "data"); - - file2.mkdirs(); - this.worldPersistentData = new WorldPersistentData(file2, datafixer); - this.playerChunkMap = new PlayerChunkMap(worldserver, file, datafixer, definedstructuremanager, executor, this.serverThreadQueue, this, this.getChunkGenerator(), worldloadlistener, supplier, i); - this.lightEngine = this.playerChunkMap.a(); - this.chunkMapDistance = this.playerChunkMap.e(); - this.clearCache(); - } - - @Override - public LightEngineThreaded getLightEngine() { - return this.lightEngine; - } - - @Nullable - private PlayerChunk getChunk(long i) { - return this.playerChunkMap.getVisibleChunk(i); - } - - public int b() { - return this.playerChunkMap.c(); - } - - private void a(long i, IChunkAccess ichunkaccess, ChunkStatus chunkstatus) { - for (int j = 3; j > 0; --j) { - this.cachePos[j] = this.cachePos[j - 1]; - this.cacheStatus[j] = this.cacheStatus[j - 1]; - this.cacheChunk[j] = this.cacheChunk[j - 1]; - } - - this.cachePos[0] = i; - this.cacheStatus[0] = chunkstatus; - this.cacheChunk[0] = ichunkaccess; - } - - // Paper start - "real" get chunk if loaded - // Note: Partially copied from the getChunkAt method below - @Nullable - public Chunk getChunkAtIfCachedImmediately(int x, int z) { - long k = ChunkCoordIntPair.pair(x, z); - - // Note: Bypass cache to make this MT-Safe - - PlayerChunk playerChunk = this.getChunk(k); - if (playerChunk == null) { - return null; - } - - return playerChunk.getFullChunkIfCached(); - } - - @Nullable - public Chunk getChunkAtIfLoadedImmediately(int x, int z) { - long k = ChunkCoordIntPair.pair(x, z); - - // Note: Bypass cache since we need to check ticket level, and to make this MT-Safe - - PlayerChunk playerChunk = this.getChunk(k); - if (playerChunk == null) { - return null; - } - - return playerChunk.getFullChunk(); - } - - @Nullable - public IChunkAccess getChunkAtImmediately(int x, int z) { - long k = ChunkCoordIntPair.pair(x, z); - - // Note: Bypass cache to make this MT-Safe - - PlayerChunk playerChunk = this.getChunk(k); - if (playerChunk == null) { - return null; - } - - return playerChunk.getAvailableChunkNow(); - - } - - private long asyncLoadSeqCounter; - - public void getChunkAtAsynchronously(int x, int z, boolean gen, java.util.function.Consumer onComplete) { - if (Thread.currentThread() != this.serverThread) { - this.serverThreadQueue.execute(() -> { - this.getChunkAtAsynchronously(x, z, gen, onComplete); - }); - return; - } - - long k = ChunkCoordIntPair.pair(x, z); - ChunkCoordIntPair chunkPos = new ChunkCoordIntPair(x, z); - - IChunkAccess ichunkaccess; - - // try cache - for (int l = 0; l < 4; ++l) { - if (k == this.cachePos[l] && ChunkStatus.FULL == this.cacheStatus[l]) { - ichunkaccess = this.cacheChunk[l]; - if (ichunkaccess != null) { // CraftBukkit - the chunk can become accessible in the meantime TODO for non-null chunks it might also make sense to check that the chunk's state hasn't changed in the meantime - - // move to first in cache - - for (int i1 = 3; i1 > 0; --i1) { - this.cachePos[i1] = this.cachePos[i1 - 1]; - this.cacheStatus[i1] = this.cacheStatus[i1 - 1]; - this.cacheChunk[i1] = this.cacheChunk[i1 - 1]; - } - - this.cachePos[0] = k; - this.cacheStatus[0] = ChunkStatus.FULL; - this.cacheChunk[0] = ichunkaccess; - - onComplete.accept((Chunk)ichunkaccess); - - return; - } - } - } - - if (gen) { - this.bringToFullStatusAsync(x, z, chunkPos, onComplete); - return; - } - - IChunkAccess current = this.getChunkAtImmediately(x, z); // we want to bypass ticket restrictions - if (current != null) { - if (!(current instanceof ProtoChunkExtension) && !(current instanceof net.minecraft.server.Chunk)) { - onComplete.accept(null); // the chunk is not gen'd - return; - } - // we know the chunk is at full status here (either in read-only mode or the real thing) - this.bringToFullStatusAsync(x, z, chunkPos, onComplete); - return; - } - - ChunkStatus status = world.getChunkProvider().playerChunkMap.getStatusOnDiskNoLoad(x, z); - - if (status != null && status != ChunkStatus.FULL) { - // does not exist on disk - onComplete.accept(null); - return; - } - - if (status == ChunkStatus.FULL) { - this.bringToFullStatusAsync(x, z, chunkPos, onComplete); - return; - } - - // status is null here - - // here we don't know what status it is and we're not supposed to generate - // so we asynchronously load empty status - - this.bringToStatusAsync(x, z, chunkPos, ChunkStatus.EMPTY, (IChunkAccess chunk) -> { - if (!(chunk instanceof ProtoChunkExtension) && !(chunk instanceof net.minecraft.server.Chunk)) { - // the chunk on disk was not a full status chunk - onComplete.accept(null); - return; - } - this.bringToFullStatusAsync(x, z, chunkPos, onComplete); // bring to full status if required - }); - } - - private void bringToFullStatusAsync(int x, int z, ChunkCoordIntPair chunkPos, java.util.function.Consumer onComplete) { - this.bringToStatusAsync(x, z, chunkPos, ChunkStatus.FULL, (java.util.function.Consumer)onComplete); - } - - private void bringToStatusAsync(int x, int z, ChunkCoordIntPair chunkPos, ChunkStatus status, java.util.function.Consumer onComplete) { - CompletableFuture> future = this.getChunkFutureMainThread(x, z, status, true); - Long identifier = Long.valueOf(this.asyncLoadSeqCounter++); - int ticketLevel = MCUtil.getTicketLevelFor(status); - this.addTicketAtLevel(TicketType.ASYNC_LOAD, chunkPos, ticketLevel, identifier); - - future.whenCompleteAsync((Either either, Throwable throwable) -> { - // either left -> success - // either right -> failure - - if (throwable != null) { - throw new RuntimeException(throwable); - } - - this.removeTicketAtLevel(TicketType.ASYNC_LOAD, chunkPos, ticketLevel, identifier); - this.addTicketAtLevel(TicketType.UNKNOWN, chunkPos, ticketLevel, chunkPos); // allow unloading - - Optional failure = either.right(); - - if (failure.isPresent()) { - // failure - throw new IllegalStateException("Chunk failed to load: " + failure.get().toString()); - } - - onComplete.accept(either.left().get()); - - }, this.serverThreadQueue); - } - - public void addTicketAtLevel(TicketType ticketType, ChunkCoordIntPair chunkPos, int ticketLevel, T identifier) { - this.chunkMapDistance.addTicketAtLevel(ticketType, chunkPos, ticketLevel, identifier); - } - - public void removeTicketAtLevel(TicketType ticketType, ChunkCoordIntPair chunkPos, int ticketLevel, T identifier) { - this.chunkMapDistance.removeTicketAtLevel(ticketType, chunkPos, ticketLevel, identifier); - } - // Paper end - - @Nullable - @Override - public IChunkAccess getChunkAt(int i, int j, ChunkStatus chunkstatus, boolean flag) { - final int x = i; final int z = j; // Paper - conflict on variable change - if (Thread.currentThread() != this.serverThread) { - return (IChunkAccess) CompletableFuture.supplyAsync(() -> { - return this.getChunkAt(i, j, chunkstatus, flag); - }, this.serverThreadQueue).join(); - } else { - long k = ChunkCoordIntPair.pair(i, j); - - IChunkAccess ichunkaccess; - - for (int l = 0; l < 4; ++l) { - if (k == this.cachePos[l] && chunkstatus == this.cacheStatus[l]) { - ichunkaccess = this.cacheChunk[l]; - if (ichunkaccess != null) { // CraftBukkit - the chunk can become accessible in the meantime TODO for non-null chunks it might also make sense to check that the chunk's state hasn't changed in the meantime - return ichunkaccess; - } - } - } - - CompletableFuture> completablefuture = this.getChunkFutureMainThread(i, j, chunkstatus, flag); - - if (!completablefuture.isDone()) { // Paper - // Paper start - async chunk io/loading - this.world.asyncChunkTaskManager.raisePriority(x, z, com.destroystokyo.paper.io.PrioritizedTaskQueue.HIGHEST_PRIORITY); - com.destroystokyo.paper.io.chunk.ChunkTaskManager.pushChunkWait(this.world, x, z); - // Paper end - com.destroystokyo.paper.io.SyncLoadFinder.logSyncLoad(this.world, x, z); // Paper - sync load info - this.world.timings.chunkAwait.startTiming(); // Paper - this.serverThreadQueue.awaitTasks(completablefuture::isDone); - com.destroystokyo.paper.io.chunk.ChunkTaskManager.popChunkWait(); // Paper - async chunk debug - this.world.timings.chunkAwait.stopTiming(); // Paper - } // Paper - ichunkaccess = (IChunkAccess) ((Either) completablefuture.join()).map((ichunkaccess1) -> { - return ichunkaccess1; - }, (playerchunk_failure) -> { - if (flag) { - throw new IllegalStateException("Chunk not there when requested: " + playerchunk_failure); - } else { - return null; - } - }); - this.a(k, ichunkaccess, chunkstatus); - return ichunkaccess; - } - } - - @Nullable - @Override - public Chunk a(int i, int j) { - if (Thread.currentThread() != this.serverThread) { - return null; - } else { - long k = ChunkCoordIntPair.pair(i, j); - - for (int l = 0; l < 4; ++l) { - if (k == this.cachePos[l] && this.cacheStatus[l] == ChunkStatus.FULL) { - IChunkAccess ichunkaccess = this.cacheChunk[l]; - - return ichunkaccess instanceof Chunk ? (Chunk) ichunkaccess : null; - } - } - - PlayerChunk playerchunk = this.getChunk(k); - - if (playerchunk == null) { - return null; - } else { - Either either = (Either) playerchunk.b(ChunkStatus.FULL).getNow(null); // Craftbukkit - decompile error - - if (either == null) { - return null; - } else { - IChunkAccess ichunkaccess1 = (IChunkAccess) either.left().orElse(null); // Craftbukkit - decompile error - - if (ichunkaccess1 != null) { - this.a(k, ichunkaccess1, ChunkStatus.FULL); - if (ichunkaccess1 instanceof Chunk) { - return (Chunk) ichunkaccess1; - } - } - - return null; - } - } - } - } - - private void clearCache() { - Arrays.fill(this.cachePos, ChunkCoordIntPair.a); - Arrays.fill(this.cacheStatus, (Object) null); - Arrays.fill(this.cacheChunk, (Object) null); - } - - private CompletableFuture> getChunkFutureMainThread(int i, int j, ChunkStatus chunkstatus, boolean flag) { - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i, j); - long k = chunkcoordintpair.pair(); - int l = 33 + ChunkStatus.a(chunkstatus); - PlayerChunk playerchunk = this.getChunk(k); - - // CraftBukkit start - don't add new ticket for currently unloading chunk - boolean currentlyUnloading = false; - if (playerchunk != null) { - PlayerChunk.State oldChunkState = PlayerChunk.getChunkState(playerchunk.oldTicketLevel); - PlayerChunk.State currentChunkState = PlayerChunk.getChunkState(playerchunk.getTicketLevel()); - currentlyUnloading = (oldChunkState.isAtLeast(PlayerChunk.State.BORDER) && !currentChunkState.isAtLeast(PlayerChunk.State.BORDER)); - } - if (flag && !currentlyUnloading) { - // CraftBukkit end - this.chunkMapDistance.a(TicketType.UNKNOWN, chunkcoordintpair, l, chunkcoordintpair); - if (this.a(playerchunk, l)) { - GameProfilerFiller gameprofilerfiller = this.world.getMethodProfiler(); - - gameprofilerfiller.enter("chunkLoad"); - this.tickDistanceManager(); - playerchunk = this.getChunk(k); - gameprofilerfiller.exit(); - if (this.a(playerchunk, l)) { - throw new IllegalStateException("No chunk holder after ticket has been added"); - } - } - } - - return this.a(playerchunk, l) ? PlayerChunk.UNLOADED_CHUNK_ACCESS_FUTURE : playerchunk.a(chunkstatus, this.playerChunkMap); - } - - private boolean a(@Nullable PlayerChunk playerchunk, int i) { - return playerchunk == null || playerchunk.oldTicketLevel > i; // CraftBukkit using oldTicketLevel for isLoaded checks - } - - public boolean isLoaded(int i, int j) { - PlayerChunk playerchunk = this.getChunk((new ChunkCoordIntPair(i, j)).pair()); - int k = 33 + ChunkStatus.a(ChunkStatus.FULL); - - return !this.a(playerchunk, k); - } - - @Override - public IBlockAccess c(int i, int j) { - long k = ChunkCoordIntPair.pair(i, j); - PlayerChunk playerchunk = this.getChunk(k); - - if (playerchunk == null) { - return null; - } else { - int l = ChunkProviderServer.c.size() - 1; - - while (true) { - ChunkStatus chunkstatus = (ChunkStatus) ChunkProviderServer.c.get(l); - Optional optional = ((Either) playerchunk.getStatusFutureUnchecked(chunkstatus).getNow(PlayerChunk.UNLOADED_CHUNK_ACCESS)).left(); - - if (optional.isPresent()) { - return (IBlockAccess) optional.get(); - } - - if (chunkstatus == ChunkStatus.LIGHT.e()) { - return null; - } - - --l; - } - } - } - - @Override - public World getWorld() { - return this.world; - } - - public boolean runTasks() { - return this.serverThreadQueue.executeNext(); - } - - private boolean tickDistanceManager() { - boolean flag = this.chunkMapDistance.a(this.playerChunkMap); - boolean flag1 = this.playerChunkMap.b(); - - if (!flag && !flag1) { - return false; - } else { - this.clearCache(); - return true; - } - } - - @Override - public boolean a(Entity entity) { - long i = ChunkCoordIntPair.pair(MathHelper.floor(entity.locX) >> 4, MathHelper.floor(entity.locZ) >> 4); - - return this.a(i, PlayerChunk::b); - } - - @Override - public boolean a(ChunkCoordIntPair chunkcoordintpair) { - return this.a(chunkcoordintpair.pair(), PlayerChunk::b); - } - - @Override - public boolean a(BlockPosition blockposition) { - long i = ChunkCoordIntPair.pair(blockposition.getX() >> 4, blockposition.getZ() >> 4); - - return this.a(i, PlayerChunk::a); - } - - public boolean b(Entity entity) { - long i = ChunkCoordIntPair.pair(MathHelper.floor(entity.locX) >> 4, MathHelper.floor(entity.locZ) >> 4); - - return this.a(i, PlayerChunk::c); - } - - private boolean a(long i, Function>> function) { - PlayerChunk playerchunk = this.getChunk(i); - - if (playerchunk == null) { - return false; - } else { - Either either = (Either) ((CompletableFuture) function.apply(playerchunk)).getNow(PlayerChunk.UNLOADED_CHUNK); - - return either.left().isPresent(); - } - } - - public void save(boolean flag) { - this.tickDistanceManager(); - try (co.aikar.timings.Timing timed = world.timings.chunkSaveData.startTiming()) { // Paper - Timings - this.playerChunkMap.save(flag); - } // Paper - Timings - } - - // Paper start - duplicate save, but call incremental - public void saveIncrementally() { - this.tickDistanceManager(); - try (co.aikar.timings.Timing timed = world.timings.chunkSaveData.startTiming()) { // Paper - Timings - this.playerChunkMap.saveIncrementally(); - } // Paper - Timings - } - // Paper end - - @Override - public void close() throws IOException { - // CraftBukkit start - close(true); - } - - public void close(boolean save) throws IOException { - if (save) { - this.save(true); - } - // CraftBukkit end - this.lightEngine.close(); - this.playerChunkMap.close(); - } - - // CraftBukkit start - modelled on below - public void purgeUnload() { - this.world.getMethodProfiler().enter("purge"); - this.chunkMapDistance.purgeTickets(); - this.tickDistanceManager(); - this.world.getMethodProfiler().exitEnter("unload"); - this.playerChunkMap.unloadChunks(() -> true); - this.world.getMethodProfiler().exit(); - this.clearCache(); - } - // CraftBukkit end - - public void tick(BooleanSupplier booleansupplier) { - this.world.getMethodProfiler().enter("purge"); - this.world.timings.doChunkMap.startTiming(); // Spigot - this.chunkMapDistance.purgeTickets(); - this.tickDistanceManager(); - this.world.timings.doChunkMap.stopTiming(); // Spigot - this.world.getMethodProfiler().exitEnter("chunks"); - this.world.timings.chunks.startTiming(); // Paper - timings - this.tickChunks(); - this.world.timings.chunks.stopTiming(); // Paper - timings - this.world.timings.doChunkUnload.startTiming(); // Spigot - this.world.getMethodProfiler().exitEnter("unload"); - this.playerChunkMap.unloadChunks(booleansupplier); - this.world.timings.doChunkUnload.stopTiming(); // Spigot - this.world.getMethodProfiler().exit(); - this.clearCache(); - } - - private void tickChunks() { - long i = this.world.getTime(); - long j = i - this.lastTickTime; - - this.lastTickTime = i; - WorldData worlddata = this.world.getWorldData(); - boolean flag = worlddata.getType() == WorldType.DEBUG_ALL_BLOCK_STATES; - boolean flag1 = this.world.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING) && !world.getPlayers().isEmpty(); // CraftBukkit - - if (!flag) { - this.world.getMethodProfiler().enter("pollingChunks"); - int k = this.world.getGameRules().getInt(GameRules.RANDOM_TICK_SPEED); - BlockPosition blockposition = this.world.getSpawn(); - boolean flag2 = world.ticksPerAnimalSpawns != 0L && worlddata.getTime() % world.ticksPerAnimalSpawns == 0L; // CraftBukkit // PAIL: TODO monster ticks - - this.world.getMethodProfiler().enter("naturalSpawnCount"); - this.world.timings.countNaturalMobs.startTiming(); // Paper - timings - int l = this.chunkMapDistance.b(); - EnumCreatureType[] aenumcreaturetype = EnumCreatureType.values(); - // Paper start - per player mob spawning - int[] worldMobCount; - if (this.playerChunkMap.playerMobDistanceMap != null) { - // update distance map - this.world.timings.playerMobDistanceMapUpdate.startTiming(); - this.playerChunkMap.playerMobDistanceMap.update(this.world.players, this.playerChunkMap.viewDistance); - this.world.timings.playerMobDistanceMapUpdate.stopTiming(); - // re-set mob counts - for (EntityPlayer player : this.world.players) { - Arrays.fill(player.mobCounts, 0); - } - worldMobCount = this.world.countMobs(true); - } else { - worldMobCount = this.world.countMobs(false); - } - // Paper end - - this.world.timings.countNaturalMobs.stopTiming(); // Paper - timings - this.world.getMethodProfiler().exit(); - this.playerChunkMap.f().forEach((playerchunk) -> { - Optional optional = ((Either) playerchunk.b().getNow(PlayerChunk.UNLOADED_CHUNK)).left(); - - if (optional.isPresent()) { - Chunk chunk = (Chunk) optional.get(); - - this.world.getMethodProfiler().enter("broadcast"); - this.world.timings.broadcastChunkUpdates.startTiming(); // Paper - timings - playerchunk.a(chunk); - this.world.timings.broadcastChunkUpdates.stopTiming(); // Paper - timings - this.world.getMethodProfiler().exit(); - ChunkCoordIntPair chunkcoordintpair = playerchunk.i(); - - // Paper start - timings - this.world.timings.chunkRangeCheckBig.startTiming(); - // note: this is just a copy of the expression in the if - boolean bigRadiusOutsideRange = !this.playerChunkMap.isOutsideOfRange(chunkcoordintpair); - this.world.timings.chunkRangeCheckBig.stopTiming(); - if (bigRadiusOutsideRange) { - // Paper end - chunk.b(chunk.q() + j); - // Paper start - timings - this.world.timings.chunkRangeCheckSmall.startTiming(); - // note: this is just a copy of the expression in the if - boolean smallRadiusOutsideRange = flag1 && (this.allowMonsters || this.allowAnimals) && this.world.getWorldBorder().isInBounds(chunk.getPos()) && !this.playerChunkMap.isOutsideOfRange(chunkcoordintpair, true); - this.world.timings.chunkRangeCheckSmall.stopTiming(); - if (smallRadiusOutsideRange) { // Spigot - // Paper end - this.world.getMethodProfiler().enter("spawner"); - this.world.timings.mobSpawn.startTiming(); // Spigot - EnumCreatureType[] aenumcreaturetype1 = aenumcreaturetype; - int i1 = aenumcreaturetype.length; - - for (int j1 = 0; j1 < i1; ++j1) { - EnumCreatureType enumcreaturetype = aenumcreaturetype1[j1]; - - // CraftBukkit start - Use per-world spawn limits - int limit = enumcreaturetype.b(); - switch (enumcreaturetype) { - case MONSTER: - limit = world.getWorld().getMonsterSpawnLimit(); - break; - case CREATURE: - limit = world.getWorld().getAnimalSpawnLimit(); - break; - case WATER_CREATURE: - limit = world.getWorld().getWaterAnimalSpawnLimit(); - break; - case AMBIENT: - limit = world.getWorld().getAmbientSpawnLimit(); - break; - } - - if (limit == 0) { - continue; - } - // CraftBukkit end - - if (enumcreaturetype != EnumCreatureType.MISC && (!enumcreaturetype.c() || this.allowAnimals) && (enumcreaturetype.c() || this.allowMonsters) && (!enumcreaturetype.d() || flag2)) { - int k1 = limit * l / ChunkProviderServer.b; // CraftBukkit - use per-world limits - - // Paper start - only allow spawns upto the limit per chunk and update count afterwards - int currEntityCount = worldMobCount[enumcreaturetype.ordinal()]; - int difference = k1 - currEntityCount; - - if (this.world.paperConfig.perPlayerMobSpawns) { - int minDiff = Integer.MAX_VALUE; - for (EntityPlayer entityplayer : this.playerChunkMap.playerMobDistanceMap.getPlayersInRange(chunk.getPos())) { - minDiff = Math.min(limit - this.playerChunkMap.getMobCountNear(entityplayer, enumcreaturetype), minDiff); - } - difference = (minDiff == Integer.MAX_VALUE) ? 0 : minDiff; - } - - if (difference > 0) { - int spawnCount = SpawnerCreature.spawnMobs(enumcreaturetype, this.world, chunk, blockposition, difference, - this.world.paperConfig.perPlayerMobSpawns ? this.playerChunkMap::updatePlayerMobTypeMap : null); - worldMobCount[enumcreaturetype.ordinal()] += spawnCount; - // Paper end - } - } - } - - this.world.timings.mobSpawn.stopTiming(); // Spigot - this.world.getMethodProfiler().exit(); - } - - this.world.timings.chunkTicks.startTiming(); // Spigot // Paper - this.world.a(chunk, k); - this.world.timings.chunkTicks.stopTiming(); // Spigot // Paper - } - } - }); - this.world.getMethodProfiler().enter("customSpawners"); - if (flag1) { - try (co.aikar.timings.Timing ignored = this.world.timings.miscMobSpawning.startTiming()) { // Paper - timings - this.chunkGenerator.doMobSpawning(this.world, this.allowMonsters, this.allowAnimals); - } // Paper - timings - } - - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().exit(); - } - - this.playerChunkMap.g(); - } - - @Override - public String getName() { - return "ServerChunkCache: " + this.h(); - } - - @VisibleForTesting - public int f() { - return this.serverThreadQueue.be(); - } - - @Override - public ChunkGenerator getChunkGenerator() { - return this.chunkGenerator; - } - - public int h() { - return this.playerChunkMap.d(); - } - - public void flagDirty(BlockPosition blockposition) { - int i = blockposition.getX() >> 4; - int j = blockposition.getZ() >> 4; - PlayerChunk playerchunk = this.getChunk(ChunkCoordIntPair.pair(i, j)); - - if (playerchunk != null) { - playerchunk.a(blockposition.getX() & 15, blockposition.getY(), blockposition.getZ() & 15); - } - - } - - @Override - public void a(EnumSkyBlock enumskyblock, SectionPosition sectionposition) { - this.serverThreadQueue.execute(() -> { - PlayerChunk playerchunk = this.getChunk(sectionposition.u().pair()); - - if (playerchunk != null) { - playerchunk.a(enumskyblock, sectionposition.b()); - } - - }); - } - - public void addTicket(TicketType tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) { - this.chunkMapDistance.addTicket(tickettype, chunkcoordintpair, i, t0); - } - - public void removeTicket(TicketType tickettype, ChunkCoordIntPair chunkcoordintpair, int i, T t0) { - this.chunkMapDistance.removeTicket(tickettype, chunkcoordintpair, i, t0); - } - - @Override - public void a(ChunkCoordIntPair chunkcoordintpair, boolean flag) { - this.chunkMapDistance.a(chunkcoordintpair, flag); - } - - public void movePlayer(EntityPlayer entityplayer) { - this.playerChunkMap.movePlayer(entityplayer); - } - - public void removeEntity(Entity entity) { - this.playerChunkMap.removeEntity(entity); - } - - public void addEntity(Entity entity) { - this.playerChunkMap.addEntity(entity); - } - - public void broadcastIncludingSelf(Entity entity, Packet packet) { - this.playerChunkMap.broadcastIncludingSelf(entity, packet); - } - - public void broadcast(Entity entity, Packet packet) { - this.playerChunkMap.broadcast(entity, packet); - } - - public void setViewDistance(int i) { - this.playerChunkMap.setViewDistance(i); - } - - @Override - public void a(boolean flag, boolean flag1) { - this.allowMonsters = flag; - this.allowAnimals = flag1; - } - - public WorldPersistentData getWorldPersistentData() { - return this.worldPersistentData; - } - - public VillagePlace j() { - return this.playerChunkMap.h(); - } - - final class a extends IAsyncTaskHandler { - - private a(World world) { - super("Chunk source main thread executor for " + IRegistry.DIMENSION_TYPE.getKey(world.getWorldProvider().getDimensionManager())); - } - - @Override - protected Runnable postToMainThread(Runnable runnable) { - return runnable; - } - - @Override - protected boolean canExecute(Runnable runnable) { - return true; - } - - @Override - protected boolean isNotMainThread() { - return true; - } - - @Override - protected Thread getThread() { - return ChunkProviderServer.this.serverThread; - } - - @Override - protected boolean executeNext() { - // CraftBukkit start - process pending Chunk loadCallback() and unloadCallback() after each run task - try { - boolean execChunkTask = com.destroystokyo.paper.io.chunk.ChunkTaskManager.pollChunkWaitQueue() || ChunkProviderServer.this.world.asyncChunkTaskManager.pollNextChunkTask(); // Paper - if (ChunkProviderServer.this.tickDistanceManager()) { - return true; - } else { - ChunkProviderServer.this.lightEngine.queueUpdate(); - return super.executeNext() || execChunkTask; // Paper - } - } finally { - playerChunkMap.callbackExecutor.run(); - } - // CraftBukkit end - } - } -} diff --git a/src/main/java/net/minecraft/server/ChunkRegionLoader.java b/src/main/java/net/minecraft/server/ChunkRegionLoader.java deleted file mode 100644 index 98cc4efcf..000000000 --- a/src/main/java/net/minecraft/server/ChunkRegionLoader.java +++ /dev/null @@ -1,675 +0,0 @@ -package net.minecraft.server; - -import co.aikar.timings.Timings; -import com.google.common.collect.Maps; -import it.unimi.dsi.fastutil.longs.LongOpenHashSet; -import it.unimi.dsi.fastutil.longs.LongSet; -import it.unimi.dsi.fastutil.shorts.ShortList; -import it.unimi.dsi.fastutil.shorts.ShortListIterator; -import java.util.ArrayDeque; // Paper -import java.util.Arrays; -import java.util.BitSet; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Objects; -import java.util.Map.Entry; -import java.util.function.Function; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class ChunkRegionLoader { - - private static final Logger LOGGER = LogManager.getLogger(); - - // Paper start - public static final class InProgressChunkHolder { - - public final ProtoChunk protoChunk; - public final ArrayDeque tasks; - - public NBTTagCompound poiData; - - public InProgressChunkHolder(final ProtoChunk protoChunk, final ArrayDeque tasks) { - this.protoChunk = protoChunk; - this.tasks = tasks; - } - } - - public static ProtoChunk loadChunk(WorldServer worldserver, DefinedStructureManager definedstructuremanager, VillagePlace villageplace, ChunkCoordIntPair chunkcoordintpair, NBTTagCompound nbttagcompound) { - InProgressChunkHolder holder = loadChunk(worldserver, definedstructuremanager, villageplace, chunkcoordintpair, nbttagcompound, true); - holder.tasks.forEach(Runnable::run); - return holder.protoChunk; - } - - public static InProgressChunkHolder loadChunk(WorldServer worldserver, DefinedStructureManager definedstructuremanager, VillagePlace villageplace, ChunkCoordIntPair chunkcoordintpair, NBTTagCompound nbttagcompound, boolean distinguish) { - ArrayDeque tasksToExecuteOnMain = new ArrayDeque<>(); - // Paper end - ChunkGenerator chunkgenerator = worldserver.getChunkProvider().getChunkGenerator(); - WorldChunkManager worldchunkmanager = chunkgenerator.getWorldChunkManager(); - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Level"); - ChunkCoordIntPair chunkcoordintpair1 = new ChunkCoordIntPair(nbttagcompound1.getInt("xPos"), nbttagcompound1.getInt("zPos")); - - if (!Objects.equals(chunkcoordintpair, chunkcoordintpair1)) { - ChunkRegionLoader.LOGGER.error("Chunk file at {} is in the wrong location; relocating. (Expected {}, got {})", chunkcoordintpair, chunkcoordintpair, chunkcoordintpair1); - } - - BiomeBase[] abiomebase = new BiomeBase[256]; - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - if (nbttagcompound1.hasKeyOfType("Biomes", 11)) { - int[] aint = nbttagcompound1.getIntArray("Biomes"); - - for (int i = 0; i < aint.length; ++i) { - abiomebase[i] = (BiomeBase) IRegistry.BIOME.fromId(aint[i]); - if (abiomebase[i] == null) { - abiomebase[i] = worldchunkmanager.getBiome(blockposition_mutableblockposition.d((i & 15) + chunkcoordintpair.d(), 0, (i >> 4 & 15) + chunkcoordintpair.e())); - } - } - } else { - for (int j = 0; j < abiomebase.length; ++j) { - abiomebase[j] = worldchunkmanager.getBiome(blockposition_mutableblockposition.d((j & 15) + chunkcoordintpair.d(), 0, (j >> 4 & 15) + chunkcoordintpair.e())); - } - } - - ChunkConverter chunkconverter = nbttagcompound1.hasKeyOfType("UpgradeData", 10) ? new ChunkConverter(nbttagcompound1.getCompound("UpgradeData")) : ChunkConverter.a; - ProtoChunkTickList protochunkticklist = new ProtoChunkTickList<>((block) -> { - return block == null || block.getBlockData().isAir(); - }, chunkcoordintpair, nbttagcompound1.getList("ToBeTicked", 9)); - ProtoChunkTickList protochunkticklist1 = new ProtoChunkTickList<>((fluidtype) -> { - return fluidtype == null || fluidtype == FluidTypes.EMPTY; - }, chunkcoordintpair, nbttagcompound1.getList("LiquidsToBeTicked", 9)); - boolean flag = nbttagcompound1.getBoolean("isLightOn"); - NBTTagList nbttaglist = nbttagcompound1.getList("Sections", 10); - boolean flag1 = true; - ChunkSection[] achunksection = new ChunkSection[16]; - boolean flag2 = worldserver.getWorldProvider().g(); - ChunkProviderServer chunkproviderserver = worldserver.getChunkProvider(); - LightEngine lightengine = chunkproviderserver.getLightEngine(); - - if (flag) { - tasksToExecuteOnMain.add(() -> { // Paper - delay this task since we're executing off-main - lightengine.b(chunkcoordintpair, true); - }); // Paper - delay this task since we're executing off-main - } - - for (int k = 0; k < nbttaglist.size(); ++k) { - NBTTagCompound nbttagcompound2 = nbttaglist.getCompound(k); - byte b0 = nbttagcompound2.getByte("Y"); - - if (nbttagcompound2.hasKeyOfType("Palette", 9) && nbttagcompound2.hasKeyOfType("BlockStates", 12)) { - ChunkSection chunksection = new ChunkSection(b0 << 4, null, worldserver, false); // Paper - Anti-Xray - - chunksection.getBlocks().a(nbttagcompound2.getList("Palette", 10), nbttagcompound2.getLongArray("BlockStates")); - chunksection.recalcBlockCounts(); - if (!chunksection.c()) { - achunksection[b0] = chunksection; - } - - tasksToExecuteOnMain.add(() -> { // Paper - delay this task since we're executing off-main - villageplace.a(chunkcoordintpair, chunksection); - }); // Paper - delay this task since we're executing off-main - } - - if (flag) { - if (nbttagcompound2.hasKeyOfType("BlockLight", 7)) { - // Paper start - delay this task since we're executing off-main - NibbleArray blockLight = new NibbleArray(nbttagcompound2.getByteArray("BlockLight")); - // Note: We move the block light nibble array creation here for perf & in case the compound is modified - tasksToExecuteOnMain.add(() -> { - lightengine.a(EnumSkyBlock.BLOCK, SectionPosition.a(chunkcoordintpair, b0), blockLight); - }); - // Paper end - } - - if (flag2 && nbttagcompound2.hasKeyOfType("SkyLight", 7)) { - // Paper start - delay this task since we're executing off-main - NibbleArray skyLight = new NibbleArray(nbttagcompound2.getByteArray("SkyLight")); - // Note: We move the block light nibble array creation here for perf & in case the compound is modified - tasksToExecuteOnMain.add(() -> { - lightengine.a(EnumSkyBlock.SKY, SectionPosition.a(chunkcoordintpair, b0), skyLight); - }); - // Paper end - } - } - } - - long l = nbttagcompound1.getLong("InhabitedTime"); - ChunkStatus.Type chunkstatus_type = a(nbttagcompound); - Object object; - - if (chunkstatus_type == ChunkStatus.Type.LEVELCHUNK) { - NBTTagList nbttaglist1; - Function function; - RegistryBlocks registryblocks; - Object object1; - - if (nbttagcompound1.hasKeyOfType("TileTicks", 9)) { - nbttaglist1 = nbttagcompound1.getList("TileTicks", 10); - // function = IRegistry.BLOCK::getKey; - registryblocks = IRegistry.BLOCK; - registryblocks.getClass(); - object1 = TickListChunk.a(nbttaglist1, IRegistry.BLOCK::getKey, IRegistry.BLOCK::get); - } else { - object1 = protochunkticklist; - } - - Object object2; - - if (nbttagcompound1.hasKeyOfType("LiquidTicks", 9)) { - nbttaglist1 = nbttagcompound1.getList("LiquidTicks", 10); - // function = IRegistry.FLUID::getKey; - registryblocks = IRegistry.FLUID; - registryblocks.getClass(); - object2 = TickListChunk.a(nbttaglist1, IRegistry.FLUID::getKey, IRegistry.FLUID::get); - } else { - object2 = protochunkticklist1; - } - - object = new Chunk(worldserver.getMinecraftWorld(), chunkcoordintpair, abiomebase, chunkconverter, (TickList) object1, (TickList) object2, l, achunksection, (chunk) -> { - loadEntities(nbttagcompound1, chunk); - }); - } else { - ProtoChunk protochunk = new ProtoChunk(chunkcoordintpair, chunkconverter, achunksection, protochunkticklist, protochunkticklist1, worldserver); // Paper - Anti-Xray - - object = protochunk; - protochunk.a(abiomebase); - protochunk.b(l); - protochunk.a(ChunkStatus.a(nbttagcompound1.getString("Status"))); - if (protochunk.getChunkStatus().b(ChunkStatus.FEATURES)) { - protochunk.a(lightengine); - } - - if (!flag && protochunk.getChunkStatus().b(ChunkStatus.LIGHT)) { - Iterator iterator = BlockPosition.b(chunkcoordintpair.d(), 0, chunkcoordintpair.e(), chunkcoordintpair.f(), 255, chunkcoordintpair.g()).iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition = (BlockPosition) iterator.next(); - - if (((IChunkAccess) object).getType(blockposition).h() != 0) { - protochunk.k(blockposition); - } - } - } - } - - ((IChunkAccess) object).b(flag); - NBTTagCompound nbttagcompound3 = nbttagcompound1.getCompound("Heightmaps"); - EnumSet enumset = EnumSet.noneOf(HeightMap.Type.class); - Iterator iterator1 = ((IChunkAccess) object).getChunkStatus().h().iterator(); - - while (iterator1.hasNext()) { - HeightMap.Type heightmap_type = (HeightMap.Type) iterator1.next(); - String s = heightmap_type.a(); - - if (nbttagcompound3.hasKeyOfType(s, 12)) { - ((IChunkAccess) object).a(heightmap_type, nbttagcompound3.getLongArray(s)); - } else { - enumset.add(heightmap_type); - } - } - - HeightMap.a((IChunkAccess) object, enumset); - NBTTagCompound nbttagcompound4 = nbttagcompound1.getCompound("Structures"); - - ((IChunkAccess) object).a(a(chunkgenerator, definedstructuremanager, worldchunkmanager, nbttagcompound4)); - ((IChunkAccess) object).b(b(nbttagcompound4)); - if (nbttagcompound1.getBoolean("shouldSave")) { - ((IChunkAccess) object).setNeedsSaving(true); - } - - NBTTagList nbttaglist2 = nbttagcompound1.getList("PostProcessing", 9); - - NBTTagList nbttaglist3; - int i1; - - for (int j1 = 0; j1 < nbttaglist2.size(); ++j1) { - nbttaglist3 = nbttaglist2.b(j1); - - for (i1 = 0; i1 < nbttaglist3.size(); ++i1) { - ((IChunkAccess) object).a(nbttaglist3.d(i1), j1); - } - } - - if (chunkstatus_type == ChunkStatus.Type.LEVELCHUNK) { - return new InProgressChunkHolder(new ProtoChunkExtension((Chunk) object), tasksToExecuteOnMain); // Paper - Async chunk loading - } else { - ProtoChunk protochunk1 = (ProtoChunk) object; - - nbttaglist3 = nbttagcompound1.getList("Entities", 10); - - for (i1 = 0; i1 < nbttaglist3.size(); ++i1) { - protochunk1.b(nbttaglist3.getCompound(i1)); - } - - NBTTagList nbttaglist4 = nbttagcompound1.getList("TileEntities", 10); - - NBTTagCompound nbttagcompound5; - - for (int k1 = 0; k1 < nbttaglist4.size(); ++k1) { - nbttagcompound5 = nbttaglist4.getCompound(k1); - ((IChunkAccess) object).a(nbttagcompound5); - } - - NBTTagList nbttaglist5 = nbttagcompound1.getList("Lights", 9); - - for (int l1 = 0; l1 < nbttaglist5.size(); ++l1) { - NBTTagList nbttaglist6 = nbttaglist5.b(l1); - - for (int i2 = 0; i2 < nbttaglist6.size(); ++i2) { - protochunk1.b(nbttaglist6.d(i2), l1); - } - } - - nbttagcompound5 = nbttagcompound1.getCompound("CarvingMasks"); - Iterator iterator2 = nbttagcompound5.getKeys().iterator(); - - while (iterator2.hasNext()) { - String s1 = (String) iterator2.next(); - WorldGenStage.Features worldgenstage_features = WorldGenStage.Features.valueOf(s1); - - protochunk1.a(worldgenstage_features, BitSet.valueOf(nbttagcompound5.getByteArray(s1))); - } - - return new InProgressChunkHolder(protochunk1, tasksToExecuteOnMain); // Paper - Async chunk loading - } - } - - // Paper start - async chunk save for unload - public static final class AsyncSaveData { - public final NibbleArray[] blockLight; // null or size of 17 (for indices -1 through 15) - public final NibbleArray[] skyLight; - - public final NBTTagList blockTickList; // non-null if we had to go to the server's tick list - public final NBTTagList fluidTickList; // non-null if we had to go to the server's tick list - - public final long worldTime; - - public AsyncSaveData(NibbleArray[] blockLight, NibbleArray[] skyLight, NBTTagList blockTickList, NBTTagList fluidTickList, - long worldTime) { - this.blockLight = blockLight; - this.skyLight = skyLight; - this.blockTickList = blockTickList; - this.fluidTickList = fluidTickList; - this.worldTime = worldTime; - } - } - - // must be called sync - public static AsyncSaveData getAsyncSaveData(WorldServer world, IChunkAccess chunk) { - org.spigotmc.AsyncCatcher.catchOp("preparation of chunk data for async save"); - ChunkCoordIntPair chunkPos = chunk.getPos(); - - LightEngineThreaded lightenginethreaded = world.getChunkProvider().getLightEngine(); - - NibbleArray[] blockLight = new NibbleArray[17 - (-1)]; - NibbleArray[] skyLight = new NibbleArray[17 - (-1)]; - - for (int i = -1; i < 17; ++i) { - NibbleArray blockArray = lightenginethreaded.a(EnumSkyBlock.BLOCK).a(SectionPosition.a(chunkPos, i)); - NibbleArray skyArray = lightenginethreaded.a(EnumSkyBlock.SKY).a(SectionPosition.a(chunkPos, i)); - - // copy data for safety - if (blockArray != null) { - blockArray = blockArray.copy(); - } - if (skyArray != null) { - skyArray = skyArray.copy(); - } - - // apply offset of 1 for -1 starting index - blockLight[i + 1] = blockArray; - skyLight[i + 1] = skyArray; - } - - TickList blockTickList = chunk.n(); - - NBTTagList blockTickListSerialized; - if (blockTickList instanceof ProtoChunkTickList || blockTickList instanceof TickListChunk) { - blockTickListSerialized = null; - } else { - blockTickListSerialized = world.getBlockTickList().a(chunkPos); - } - - TickList fluidTickList = chunk.o(); - - NBTTagList fluidTickListSerialized; - if (fluidTickList instanceof ProtoChunkTickList || fluidTickList instanceof TickListChunk) { - fluidTickListSerialized = null; - } else { - fluidTickListSerialized = world.getFluidTickList().a(chunkPos); - } - - return new AsyncSaveData(blockLight, skyLight, blockTickListSerialized, fluidTickListSerialized, world.getTime()); - } - - public static NBTTagCompound saveChunk(WorldServer worldserver, IChunkAccess ichunkaccess) { - return saveChunk(worldserver, ichunkaccess, null); - } - public static NBTTagCompound saveChunk(WorldServer worldserver, IChunkAccess ichunkaccess, AsyncSaveData asyncsavedata) { - // Paper end - ChunkCoordIntPair chunkcoordintpair = ichunkaccess.getPos(); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - nbttagcompound.setInt("DataVersion", SharedConstants.a().getWorldVersion()); - nbttagcompound.set("Level", nbttagcompound1); - nbttagcompound1.setInt("xPos", chunkcoordintpair.x); - nbttagcompound1.setInt("zPos", chunkcoordintpair.z); - nbttagcompound1.setLong("LastUpdate", asyncsavedata != null ? asyncsavedata.worldTime : worldserver.getTime()); // Paper - async chunk unloading - nbttagcompound1.setLong("InhabitedTime", ichunkaccess.q()); - nbttagcompound1.setString("Status", ichunkaccess.getChunkStatus().d()); - ChunkConverter chunkconverter = ichunkaccess.p(); - - if (!chunkconverter.a()) { - nbttagcompound1.set("UpgradeData", chunkconverter.b()); - } - - ChunkSection[] achunksection = ichunkaccess.getSections(); - NBTTagList nbttaglist = new NBTTagList(); - LightEngineThreaded lightenginethreaded = worldserver.getChunkProvider().getLightEngine(); - boolean flag = ichunkaccess.r(); - - NBTTagCompound nbttagcompound2; - - for (int i = -1; i < 17; ++i) { // Paper - conflict on loop parameter change - int finalI = i; - ChunkSection chunksection = (ChunkSection) Arrays.stream(achunksection).filter((chunksection1) -> { - return chunksection1 != null && chunksection1.getYPosition() >> 4 == finalI; - }).findFirst().orElse(Chunk.a); - // Paper start - async chunk save for unload - NibbleArray nibblearray; // block light - NibbleArray nibblearray1; // sky light - if (asyncsavedata == null) { - nibblearray = lightenginethreaded.a(EnumSkyBlock.BLOCK).a(SectionPosition.a(chunkcoordintpair, i)); /// Paper - diff on method change (see getAsyncSaveData) - nibblearray1 = lightenginethreaded.a(EnumSkyBlock.SKY).a(SectionPosition.a(chunkcoordintpair, i)); // Paper - diff on method change (see getAsyncSaveData) - } else { - nibblearray = asyncsavedata.blockLight[i + 1]; // +1 to offset the -1 starting index - nibblearray1 = asyncsavedata.skyLight[i + 1]; // +1 to offset the -1 starting index - } - // Paper end - if (chunksection != Chunk.a || nibblearray != null || nibblearray1 != null) { - nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.setByte("Y", (byte) (i & 255)); - if (chunksection != Chunk.a) { - chunksection.getBlocks().a(nbttagcompound2, "Palette", "BlockStates"); - } - - if (nibblearray != null && !nibblearray.c()) { - nbttagcompound2.setByteArray("BlockLight", nibblearray.asBytes()); - } - - if (nibblearray1 != null && !nibblearray1.c()) { - nbttagcompound2.setByteArray("SkyLight", nibblearray1.asBytes()); - } - - nbttaglist.add(nbttagcompound2); - } - } - - nbttagcompound1.set("Sections", nbttaglist); - if (flag) { - nbttagcompound1.setBoolean("isLightOn", true); - } - - BiomeBase[] abiomebase = ichunkaccess.getBiomeIndex(); - int[] aint = abiomebase != null ? new int[abiomebase.length] : new int[0]; - - if (abiomebase != null) { - for (int j = 0; j < abiomebase.length; ++j) { - aint[j] = IRegistry.BIOME.a(abiomebase[j]); - } - } - - nbttagcompound1.setIntArray("Biomes", aint); - NBTTagList nbttaglist1 = new NBTTagList(); - Iterator iterator = ichunkaccess.c().iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition = (BlockPosition) iterator.next(); - - nbttagcompound2 = ichunkaccess.j(blockposition); - if (nbttagcompound2 != null) { - nbttaglist1.add(nbttagcompound2); - } - } - - nbttagcompound1.set("TileEntities", nbttaglist1); - NBTTagList nbttaglist2 = new NBTTagList(); - - java.util.List toUpdate = new java.util.ArrayList<>(); // Paper - if (ichunkaccess.getChunkStatus().getType() == ChunkStatus.Type.LEVELCHUNK) { - Chunk chunk = (Chunk) ichunkaccess; - - chunk.d(false); - - for (int k = 0; k < chunk.getEntitySlices().length; ++k) { - Iterator iterator1 = chunk.getEntitySlices()[k].iterator(); - - while (iterator1.hasNext()) { - Entity entity = (Entity) iterator1.next(); - NBTTagCompound nbttagcompound3 = new NBTTagCompound(); - // Paper start - if ((int)Math.floor(entity.locX) >> 4 != chunk.getPos().x || (int)Math.floor(entity.locZ) >> 4 != chunk.getPos().z) { - LogManager.getLogger().warn(entity + " is not in this chunk, skipping save. This a bug fix to a vanilla bug. Do not report this to PaperMC please."); - if (asyncsavedata == null) toUpdate.add(entity); // todo fix this broken code, entityJoinedWorld wont work in this case! - continue; - } - if (asyncsavedata == null && entity.dead) { // todo - continue; - } - // Paper end - if (entity.d(nbttagcompound3)) { - chunk.d(true); - nbttaglist2.add(nbttagcompound3); - } - } - } - - // Paper start - move entities to the correct chunk - for (Entity entity : toUpdate) { - worldserver.entityJoinedWorld(entity); - } - // Paper end - - } else { - ProtoChunk protochunk = (ProtoChunk) ichunkaccess; - - nbttaglist2.addAll(protochunk.y()); - nbttagcompound1.set("Lights", a(protochunk.w())); - nbttagcompound2 = new NBTTagCompound(); - WorldGenStage.Features[] aworldgenstage_features = WorldGenStage.Features.values(); - int l = aworldgenstage_features.length; - - for (int i1 = 0; i1 < l; ++i1) { - WorldGenStage.Features worldgenstage_features = aworldgenstage_features[i1]; - - nbttagcompound2.setByteArray(worldgenstage_features.toString(), ichunkaccess.a(worldgenstage_features).toByteArray()); - } - - nbttagcompound1.set("CarvingMasks", nbttagcompound2); - } - - nbttagcompound1.set("Entities", nbttaglist2); - TickList ticklist = ichunkaccess.n(); // Paper - diff on method change (see getAsyncSaveData) - - if (ticklist instanceof ProtoChunkTickList) { - nbttagcompound1.set("ToBeTicked", ((ProtoChunkTickList) ticklist).b()); - } else if (ticklist instanceof TickListChunk) { - nbttagcompound1.set("TileTicks", ((TickListChunk) ticklist).a(asyncsavedata != null ? asyncsavedata.worldTime : worldserver.getTime())); // Paper - async chunk unloading - // Paper start - async chunk save for unload - } else if (asyncsavedata != null) { - nbttagcompound1.set("TileTicks", asyncsavedata.blockTickList); - // Paper end - } else { - nbttagcompound1.set("TileTicks", worldserver.getBlockTickList().a(chunkcoordintpair)); // Paper - diff on method change (see getAsyncSaveData) - } - - TickList ticklist1 = ichunkaccess.o(); // Paper - diff on method change (see getAsyncSaveData) - - if (ticklist1 instanceof ProtoChunkTickList) { - nbttagcompound1.set("LiquidsToBeTicked", ((ProtoChunkTickList) ticklist1).b()); - } else if (ticklist1 instanceof TickListChunk) { - nbttagcompound1.set("LiquidTicks", ((TickListChunk) ticklist1).a(asyncsavedata != null ? asyncsavedata.worldTime : worldserver.getTime())); // Paper - async chunk unloading - // Paper start - async chunk save for unload - } else if (asyncsavedata != null) { - nbttagcompound1.set("LiquidTicks", asyncsavedata.fluidTickList); - // Paper end - } else { - nbttagcompound1.set("LiquidTicks", worldserver.getFluidTickList().a(chunkcoordintpair)); // Paper - diff on method change (see getAsyncSaveData) - } - - nbttagcompound1.set("PostProcessing", a(ichunkaccess.l())); - NBTTagCompound nbttagcompound4 = new NBTTagCompound(); - Iterator iterator2 = ichunkaccess.f().iterator(); - - while (iterator2.hasNext()) { - Entry entry = (Entry) iterator2.next(); - - if (ichunkaccess.getChunkStatus().h().contains(entry.getKey())) { - nbttagcompound4.set(((HeightMap.Type) entry.getKey()).a(), new NBTTagLongArray(((HeightMap) entry.getValue()).a())); - } - } - - nbttagcompound1.set("Heightmaps", nbttagcompound4); - nbttagcompound1.set("Structures", a(chunkcoordintpair, ichunkaccess.h(), ichunkaccess.v())); - return nbttagcompound; - } - - // Paper start - public static ChunkStatus getStatus(NBTTagCompound compound) { - if (compound == null) { - return null; - } - - // Note: Copied from below - return ChunkStatus.getStatus(compound.getCompound("Level").getString("Status")); - } - // Paper end - - public static ChunkStatus.Type a(@Nullable NBTTagCompound nbttagcompound) { - if (nbttagcompound != null) { - ChunkStatus chunkstatus = ChunkStatus.a(nbttagcompound.getCompound("Level").getString("Status")); - - if (chunkstatus != null) { - return chunkstatus.getType(); - } - } - - return ChunkStatus.Type.PROTOCHUNK; - } - - private static void loadEntities(NBTTagCompound nbttagcompound, Chunk chunk) { - NBTTagList nbttaglist = nbttagcompound.getList("Entities", 10); - World world = chunk.getWorld(); - world.timings.chunkLoadLevelTimer.startTiming(); // Spigot - - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompound(i); - - EntityTypes.a(nbttagcompound1, world, (entity) -> { - chunk.a(entity); - return entity; - }); - chunk.d(true); - } - - NBTTagList nbttaglist1 = nbttagcompound.getList("TileEntities", 10); - - for (int j = 0; j < nbttaglist1.size(); ++j) { - NBTTagCompound nbttagcompound2 = nbttaglist1.getCompound(j); - boolean flag = nbttagcompound2.getBoolean("keepPacked"); - - if (flag) { - chunk.a(nbttagcompound2); - } else { - TileEntity tileentity = TileEntity.create(nbttagcompound2); - - if (tileentity != null) { - chunk.a(tileentity); - } - } - } - world.timings.chunkLoadLevelTimer.stopTiming(); // Paper - - } - - private static NBTTagCompound a(ChunkCoordIntPair chunkcoordintpair, Map map, Map map1) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - nbttagcompound1.set((String) entry.getKey(), ((StructureStart) entry.getValue()).a(chunkcoordintpair.x, chunkcoordintpair.z)); - } - - nbttagcompound.set("Starts", nbttagcompound1); - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - Iterator iterator1 = map1.entrySet().iterator(); - - while (iterator1.hasNext()) { - Entry entry1 = (Entry) iterator1.next(); - - nbttagcompound2.set((String) entry1.getKey(), new NBTTagLongArray((LongSet) entry1.getValue())); - } - - nbttagcompound.set("References", nbttagcompound2); - return nbttagcompound; - } - - private static Map a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, WorldChunkManager worldchunkmanager, NBTTagCompound nbttagcompound) { - Map map = Maps.newHashMap(); - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Starts"); - Iterator iterator = nbttagcompound1.getKeys().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - - map.put(s, WorldGenFactory.a(chunkgenerator, definedstructuremanager, worldchunkmanager, nbttagcompound1.getCompound(s))); - } - - return map; - } - - private static Map b(NBTTagCompound nbttagcompound) { - Map map = Maps.newHashMap(); - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("References"); - Iterator iterator = nbttagcompound1.getKeys().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - - map.put(s, new LongOpenHashSet(nbttagcompound1.getLongArray(s))); - } - - return map; - } - - public static NBTTagList a(ShortList[] ashortlist) { - NBTTagList nbttaglist = new NBTTagList(); - ShortList[] ashortlist1 = ashortlist; - int i = ashortlist.length; - - for (int j = 0; j < i; ++j) { - ShortList shortlist = ashortlist1[j]; - NBTTagList nbttaglist1 = new NBTTagList(); - - if (shortlist != null) { - ShortListIterator shortlistiterator = shortlist.iterator(); - - while (shortlistiterator.hasNext()) { - Short oshort = (Short) shortlistiterator.next(); - - nbttaglist1.add(new NBTTagShort(oshort)); - } - } - - nbttaglist.add(nbttaglist1); - } - - return nbttaglist; - } -} diff --git a/src/main/java/net/minecraft/server/ChunkSection.java b/src/main/java/net/minecraft/server/ChunkSection.java deleted file mode 100644 index 584b3e639..000000000 --- a/src/main/java/net/minecraft/server/ChunkSection.java +++ /dev/null @@ -1,157 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class ChunkSection { - - public static final DataPalette GLOBAL_PALETTE = new DataPaletteGlobal<>(Block.REGISTRY_ID, Blocks.AIR.getBlockData()); - private final int yPos; - short nonEmptyBlockCount; // Paper - private -> package-private - private short tickingBlockCount; - private short e; - final DataPaletteBlock blockIds; // Paper - package - - public ChunkSection(int i) { - // Paper start - add parameters - this(i, (IChunkAccess)null, (IWorldReader)null, true); - } - public ChunkSection(int i, IChunkAccess chunk, IWorldReader world, boolean initializeBlocks) { - this(i, (short) 0, (short) 0, (short) 0, chunk, world, initializeBlocks); - // Paper end - } - - public ChunkSection(int i, short short0, short short1, short short2) { - // Paper start - add parameters - this(i, short0, short1, short2, (IChunkAccess)null, (IWorldReader)null, true); - } - public ChunkSection(int i, short short0, short short1, short short2, IChunkAccess chunk, IWorldReader world, boolean initializeBlocks) { - // Paper end - this.yPos = i; - this.nonEmptyBlockCount = short0; - this.tickingBlockCount = short1; - this.e = short2; - this.blockIds = new DataPaletteBlock<>(ChunkSection.GLOBAL_PALETTE, Block.REGISTRY_ID, GameProfileSerializer::d, GameProfileSerializer::a, Blocks.AIR.getBlockData(), world instanceof GeneratorAccess ? ((GeneratorAccess) world).getMinecraftWorld().chunkPacketBlockController.getPredefinedBlockData(world, chunk, this, initializeBlocks) : null, initializeBlocks); // Paper - Anti-Xray - Add predefined block data - } - - public IBlockData getType(int i, int j, int k) { - return (IBlockData) this.blockIds.a(i, j, k); - } - - public Fluid b(int i, int j, int k) { - return ((IBlockData) this.blockIds.a(i, j, k)).p(); - } - - public void a() { - this.blockIds.a(); - } - - public void b() { - this.blockIds.b(); - } - - public IBlockData setType(int i, int j, int k, IBlockData iblockdata) { - return this.setType(i, j, k, iblockdata, true); - } - - public IBlockData setType(int i, int j, int k, IBlockData iblockdata, boolean flag) { - IBlockData iblockdata1; - - if (flag) { - iblockdata1 = (IBlockData) this.blockIds.setBlock(i, j, k, iblockdata); - } else { - iblockdata1 = (IBlockData) this.blockIds.b(i, j, k, iblockdata); - } - - Fluid fluid = iblockdata1.p(); - Fluid fluid1 = iblockdata.p(); - - if (!iblockdata1.isAir()) { - --this.nonEmptyBlockCount; - if (iblockdata1.q()) { - --this.tickingBlockCount; - } - } - - if (!fluid.isEmpty()) { - --this.e; - } - - if (!iblockdata.isAir()) { - ++this.nonEmptyBlockCount; - if (iblockdata.q()) { - ++this.tickingBlockCount; - } - } - - if (!fluid1.isEmpty()) { - ++this.e; - } - - return iblockdata1; - } - - public boolean c() { - return this.nonEmptyBlockCount == 0; - } - - public static boolean a(@Nullable ChunkSection chunksection) { - return chunksection == Chunk.a || chunksection.c(); - } - - public boolean d() { - return this.shouldTick() || this.f(); - } - - public boolean shouldTick() { - return this.tickingBlockCount > 0; - } - - public boolean f() { - return this.e > 0; - } - - public int getYPosition() { - return this.yPos; - } - - public void recalcBlockCounts() { - this.nonEmptyBlockCount = 0; - this.tickingBlockCount = 0; - this.e = 0; - this.blockIds.a((iblockdata, i) -> { - Fluid fluid = iblockdata.p(); - - if (!iblockdata.isAir()) { - this.nonEmptyBlockCount = (short) (this.nonEmptyBlockCount + i); - if (iblockdata.q()) { - this.tickingBlockCount = (short) (this.tickingBlockCount + i); - } - } - - if (!fluid.isEmpty()) { - this.nonEmptyBlockCount = (short) (this.nonEmptyBlockCount + i); - if (fluid.h()) { - this.e = (short) (this.e + i); - } - } - - }); - } - - public DataPaletteBlock getBlocks() { - return this.blockIds; - } - - public void b(PacketDataSerializer packetdataserializer) { - packetdataserializer.writeShort(this.nonEmptyBlockCount); - this.blockIds.b(packetdataserializer); - } - - public int j() { - return 2 + this.blockIds.c(); - } - - public boolean a(IBlockData iblockdata) { - return this.blockIds.a(iblockdata); // Paper - decompile fix - } -} diff --git a/src/main/java/net/minecraft/server/ChunkStatus.java b/src/main/java/net/minecraft/server/ChunkStatus.java deleted file mode 100644 index abb0d69d2..000000000 --- a/src/main/java/net/minecraft/server/ChunkStatus.java +++ /dev/null @@ -1,261 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.mojang.datafixers.util.Either; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.function.Function; -import javax.annotation.Nullable; - -public class ChunkStatus { - - private static final EnumSet n = EnumSet.of(HeightMap.Type.OCEAN_FLOOR_WG, HeightMap.Type.WORLD_SURFACE_WG); - private static final EnumSet o = EnumSet.of(HeightMap.Type.OCEAN_FLOOR, HeightMap.Type.WORLD_SURFACE, HeightMap.Type.MOTION_BLOCKING, HeightMap.Type.MOTION_BLOCKING_NO_LEAVES); - private static final ChunkStatus.c p = (chunkstatus, worldserver, definedstructuremanager, lightenginethreaded, function, ichunkaccess) -> { - if (ichunkaccess instanceof ProtoChunk && !ichunkaccess.getChunkStatus().b(chunkstatus)) { - ((ProtoChunk) ichunkaccess).a(chunkstatus); - } - - return CompletableFuture.completedFuture(Either.left(ichunkaccess)); - }; - public static final ChunkStatus EMPTY = a("empty", (ChunkStatus) null, -1, ChunkStatus.n, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - }); - public static final ChunkStatus STRUCTURE_STARTS = a("structure_starts", ChunkStatus.EMPTY, 0, ChunkStatus.n, ChunkStatus.Type.PROTOCHUNK, (chunkstatus, worldserver, chunkgenerator, definedstructuremanager, lightenginethreaded, function, list, ichunkaccess) -> { - if (!ichunkaccess.getChunkStatus().b(chunkstatus)) { - if (worldserver.getWorldData().shouldGenerateMapFeatures()) { - chunkgenerator.createStructures(ichunkaccess, chunkgenerator, definedstructuremanager); - } - - if (ichunkaccess instanceof ProtoChunk) { - ((ProtoChunk) ichunkaccess).a(chunkstatus); - } - } - - return CompletableFuture.completedFuture(Either.left(ichunkaccess)); - }); - public static final ChunkStatus STRUCTURE_REFERENCES = a("structure_references", ChunkStatus.STRUCTURE_STARTS, 8, ChunkStatus.n, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - chunkgenerator.storeStructures(new RegionLimitedWorldAccess(worldserver, list), ichunkaccess); - }); - public static final ChunkStatus BIOMES = a("biomes", ChunkStatus.STRUCTURE_REFERENCES, 0, ChunkStatus.n, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - chunkgenerator.createBiomes(ichunkaccess); - }); - public static final ChunkStatus NOISE = a("noise", ChunkStatus.BIOMES, 8, ChunkStatus.n, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - chunkgenerator.buildNoise(new RegionLimitedWorldAccess(worldserver, list), ichunkaccess); - }); - public static final ChunkStatus SURFACE = a("surface", ChunkStatus.NOISE, 0, ChunkStatus.n, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - chunkgenerator.buildBase(ichunkaccess); - }); - public static final ChunkStatus CARVERS = a("carvers", ChunkStatus.SURFACE, 0, ChunkStatus.n, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - chunkgenerator.doCarving(ichunkaccess, WorldGenStage.Features.AIR); - }); - public static final ChunkStatus LIQUID_CARVERS = a("liquid_carvers", ChunkStatus.CARVERS, 0, ChunkStatus.o, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - chunkgenerator.doCarving(ichunkaccess, WorldGenStage.Features.LIQUID); - }); - public static final ChunkStatus FEATURES = a("features", ChunkStatus.LIQUID_CARVERS, 8, ChunkStatus.o, ChunkStatus.Type.PROTOCHUNK, (chunkstatus, worldserver, chunkgenerator, definedstructuremanager, lightenginethreaded, function, list, ichunkaccess) -> { - ichunkaccess.a((LightEngine) lightenginethreaded); - if (!ichunkaccess.getChunkStatus().b(chunkstatus)) { - HeightMap.a(ichunkaccess, EnumSet.of(HeightMap.Type.MOTION_BLOCKING, HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, HeightMap.Type.OCEAN_FLOOR, HeightMap.Type.WORLD_SURFACE)); - chunkgenerator.addDecorations(new RegionLimitedWorldAccess(worldserver, list)); - if (ichunkaccess instanceof ProtoChunk) { - ((ProtoChunk) ichunkaccess).a(chunkstatus); - } - } - - return CompletableFuture.completedFuture(Either.left(ichunkaccess)); - }); - public static final ChunkStatus LIGHT = a("light", ChunkStatus.FEATURES, 1, ChunkStatus.o, ChunkStatus.Type.PROTOCHUNK, (chunkstatus, worldserver, chunkgenerator, definedstructuremanager, lightenginethreaded, function, list, ichunkaccess) -> { - return a(chunkstatus, lightenginethreaded, ichunkaccess); - }, (chunkstatus, worldserver, definedstructuremanager, lightenginethreaded, function, ichunkaccess) -> { - return a(chunkstatus, lightenginethreaded, ichunkaccess); - }); - public static final ChunkStatus SPAWN = a("spawn", ChunkStatus.LIGHT, 0, ChunkStatus.o, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - chunkgenerator.addMobs(new RegionLimitedWorldAccess(worldserver, list)); - }); - public static final ChunkStatus HEIGHTMAPS = a("heightmaps", ChunkStatus.SPAWN, 0, ChunkStatus.o, ChunkStatus.Type.PROTOCHUNK, (worldserver, chunkgenerator, list, ichunkaccess) -> { - }); - public static final ChunkStatus FULL = a("full", ChunkStatus.HEIGHTMAPS, 0, ChunkStatus.o, ChunkStatus.Type.LEVELCHUNK, (chunkstatus, worldserver, chunkgenerator, definedstructuremanager, lightenginethreaded, function, list, ichunkaccess) -> { - return (CompletableFuture) function.apply(ichunkaccess); - }, (chunkstatus, worldserver, definedstructuremanager, lightenginethreaded, function, ichunkaccess) -> { - return (CompletableFuture) function.apply(ichunkaccess); - }); - private static final List q = ImmutableList.of(ChunkStatus.FULL, ChunkStatus.FEATURES, ChunkStatus.LIQUID_CARVERS, ChunkStatus.STRUCTURE_STARTS, ChunkStatus.STRUCTURE_STARTS, ChunkStatus.STRUCTURE_STARTS, ChunkStatus.STRUCTURE_STARTS, ChunkStatus.STRUCTURE_STARTS, ChunkStatus.STRUCTURE_STARTS, ChunkStatus.STRUCTURE_STARTS, ChunkStatus.STRUCTURE_STARTS); - private static final IntList r = (IntList) SystemUtils.a((new IntArrayList(a().size())), (java.util.function.Consumer)(IntArrayList intarraylist) -> { // Paper - decompile fix - int i = 0; - - for (int j = a().size() - 1; j >= 0; --j) { - while (i + 1 < ChunkStatus.q.size() && j <= ((ChunkStatus) ChunkStatus.q.get(i + 1)).c()) { - ++i; - } - - intarraylist.add(0, i); - } - - }); - private final String s; - private final int t; - private final ChunkStatus u; - private final ChunkStatus.b v; - private final ChunkStatus.c w; - private final int x; - private final ChunkStatus.Type y; - private final EnumSet z; - - private static CompletableFuture> a(ChunkStatus chunkstatus, LightEngineThreaded lightenginethreaded, IChunkAccess ichunkaccess) { - boolean flag = a(chunkstatus, ichunkaccess); - - if (!ichunkaccess.getChunkStatus().b(chunkstatus)) { - ((ProtoChunk) ichunkaccess).a(chunkstatus); - } - - return lightenginethreaded.a(ichunkaccess, flag).thenApply(Either::left); - } - - private static ChunkStatus a(String s, @Nullable ChunkStatus chunkstatus, int i, EnumSet enumset, ChunkStatus.Type chunkstatus_type, ChunkStatus.d chunkstatus_d) { - return a(s, chunkstatus, i, enumset, chunkstatus_type, (ChunkStatus.b) chunkstatus_d); - } - - private static ChunkStatus a(String s, @Nullable ChunkStatus chunkstatus, int i, EnumSet enumset, ChunkStatus.Type chunkstatus_type, ChunkStatus.b chunkstatus_b) { - return a(s, chunkstatus, i, enumset, chunkstatus_type, chunkstatus_b, ChunkStatus.p); - } - - private static ChunkStatus a(String s, @Nullable ChunkStatus chunkstatus, int i, EnumSet enumset, ChunkStatus.Type chunkstatus_type, ChunkStatus.b chunkstatus_b, ChunkStatus.c chunkstatus_c) { - return (ChunkStatus) IRegistry.a((IRegistry) IRegistry.CHUNK_STATUS, s, (Object) (new ChunkStatus(s, chunkstatus, i, enumset, chunkstatus_type, chunkstatus_b, chunkstatus_c))); - } - - public static List a() { - List list = Lists.newArrayList(); - - ChunkStatus chunkstatus; - - for (chunkstatus = ChunkStatus.FULL; chunkstatus.e() != chunkstatus; chunkstatus = chunkstatus.e()) { - list.add(chunkstatus); - } - - list.add(chunkstatus); - Collections.reverse(list); - return list; - } - - private static boolean a(ChunkStatus chunkstatus, IChunkAccess ichunkaccess) { - return ichunkaccess.getChunkStatus().b(chunkstatus) && ichunkaccess.r(); - } - - public static ChunkStatus a(int i) { - return i >= ChunkStatus.q.size() ? ChunkStatus.EMPTY : (i < 0 ? ChunkStatus.FULL : (ChunkStatus) ChunkStatus.q.get(i)); - } - - public static int b() { - return ChunkStatus.q.size(); - } - - public static int getTicketLevelOffset(ChunkStatus status) { return ChunkStatus.a(status); } // Paper - OBFHELPER - public static int a(ChunkStatus chunkstatus) { - return ChunkStatus.r.getInt(chunkstatus.c()); - } - - ChunkStatus(String s, @Nullable ChunkStatus chunkstatus, int i, EnumSet enumset, ChunkStatus.Type chunkstatus_type, ChunkStatus.b chunkstatus_b, ChunkStatus.c chunkstatus_c) { - this.s = s; - this.u = chunkstatus == null ? this : chunkstatus; - this.v = chunkstatus_b; - this.w = chunkstatus_c; - this.x = i; - this.y = chunkstatus_type; - this.z = enumset; - this.t = chunkstatus == null ? 0 : chunkstatus.c() + 1; - } - - public int c() { - return this.t; - } - - public String d() { - return this.s; - } - - public ChunkStatus getPreviousStatus() { return this.e(); } // Paper - OBFHELPER - public ChunkStatus e() { - return this.u; - } - - public CompletableFuture> a(WorldServer worldserver, ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, LightEngineThreaded lightenginethreaded, Function>> function, List list) { - return this.v.doWork(this, worldserver, chunkgenerator, definedstructuremanager, lightenginethreaded, function, list, (IChunkAccess) list.get(list.size() / 2)); - } - - public CompletableFuture> a(WorldServer worldserver, DefinedStructureManager definedstructuremanager, LightEngineThreaded lightenginethreaded, Function>> function, IChunkAccess ichunkaccess) { - return this.w.doWork(this, worldserver, definedstructuremanager, lightenginethreaded, function, ichunkaccess); - } - - public int f() { - return this.x; - } - - public ChunkStatus.Type getType() { - return this.y; - } - - // Paper start - public static ChunkStatus getStatus(String name) { - try { - // We need this otherwise we return EMPTY for invalid names - MinecraftKey key = new MinecraftKey(name); - return IRegistry.CHUNK_STATUS.getOptional(key).orElse(null); - } catch (Exception ex) { - return null; // invalid name - } - } - // Paper end - public static ChunkStatus a(String s) { - return (ChunkStatus) IRegistry.CHUNK_STATUS.get(MinecraftKey.a(s)); - } - - public EnumSet h() { - return this.z; - } - - public boolean b(ChunkStatus chunkstatus) { - return this.c() >= chunkstatus.c(); - } - - public String toString() { - return IRegistry.CHUNK_STATUS.getKey(this).toString(); - } - - public static enum Type { - - PROTOCHUNK, LEVELCHUNK; - - private Type() {} - } - - interface d extends ChunkStatus.b { - - @Override - default CompletableFuture> doWork(ChunkStatus chunkstatus, WorldServer worldserver, ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, LightEngineThreaded lightenginethreaded, Function>> function, List list, IChunkAccess ichunkaccess) { - if (!ichunkaccess.getChunkStatus().b(chunkstatus)) { - this.doWork(worldserver, chunkgenerator, list, ichunkaccess); - if (ichunkaccess instanceof ProtoChunk) { - ((ProtoChunk) ichunkaccess).a(chunkstatus); - } - } - - return CompletableFuture.completedFuture(Either.left(ichunkaccess)); - } - - void doWork(WorldServer worldserver, ChunkGenerator chunkgenerator, List list, IChunkAccess ichunkaccess); - } - - interface c { - - CompletableFuture> doWork(ChunkStatus chunkstatus, WorldServer worldserver, DefinedStructureManager definedstructuremanager, LightEngineThreaded lightenginethreaded, Function>> function, IChunkAccess ichunkaccess); - } - - interface b { - - CompletableFuture> doWork(ChunkStatus chunkstatus, WorldServer worldserver, ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, LightEngineThreaded lightenginethreaded, Function>> function, List list, IChunkAccess ichunkaccess); - } -} diff --git a/src/main/java/net/minecraft/server/CombatTracker.java b/src/main/java/net/minecraft/server/CombatTracker.java deleted file mode 100644 index f563a7b63..000000000 --- a/src/main/java/net/minecraft/server/CombatTracker.java +++ /dev/null @@ -1,200 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -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 entityliving) { - this.b = entityliving; - } - - public void a() { - this.k(); - if (this.b.isClimbing()) { - Block block = this.b.world.getType(new BlockPosition(this.b.locX, this.b.getBoundingBox().minY, this.b.locZ)).getBlock(); - - if (block == Blocks.LADDER) { - this.h = "ladder"; - } else if (block == Blocks.VINE) { - this.h = "vines"; - } - } else if (this.b.isInWater()) { - this.h = "water"; - } - - } - - public void trackDamage(DamageSource damagesource, float f, float f1) { - this.g(); - this.a(); - CombatEntry combatentry = new CombatEntry(damagesource, this.b.ticksLived, f, f1, this.h, this.b.fallDistance); - - this.a.add(combatentry); - this.c = this.b.ticksLived; - this.g = true; - if (combatentry.f() && !this.f && this.b.isAlive()) { - this.f = true; - this.d = this.b.ticksLived; - this.e = this.d; - this.b.enterCombat(); - } - - } - - public IChatBaseComponent getDeathMessage() { - if (this.a.isEmpty()) { - return new ChatMessage("death.attack.generic", new Object[]{this.b.getScoreboardDisplayName()}); - } else { - CombatEntry combatentry = this.j(); - CombatEntry combatentry1 = (CombatEntry) this.a.get(this.a.size() - 1); - IChatBaseComponent ichatbasecomponent = combatentry1.h(); - Entity entity = combatentry1.a().getEntity(); - Object object; - - if (combatentry != null && combatentry1.a() == DamageSource.FALL) { - IChatBaseComponent ichatbasecomponent1 = combatentry.h(); - - if (combatentry.a() != DamageSource.FALL && combatentry.a() != DamageSource.OUT_OF_WORLD) { - if (ichatbasecomponent1 != null && (ichatbasecomponent == null || !ichatbasecomponent1.equals(ichatbasecomponent))) { - Entity entity1 = combatentry.a().getEntity(); - ItemStack itemstack = entity1 instanceof EntityLiving ? ((EntityLiving) entity1).getItemInMainHand() : ItemStack.a; - - if (!itemstack.isEmpty() && itemstack.hasName()) { - object = new ChatMessage("death.fell.assist.item", new Object[]{this.b.getScoreboardDisplayName(), ichatbasecomponent1, itemstack.B()}); - } else { - object = new ChatMessage("death.fell.assist", new Object[]{this.b.getScoreboardDisplayName(), ichatbasecomponent1}); - } - } else if (ichatbasecomponent != null) { - ItemStack itemstack1 = entity instanceof EntityLiving ? ((EntityLiving) entity).getItemInMainHand() : ItemStack.a; - - if (!itemstack1.isEmpty() && itemstack1.hasName()) { - object = new ChatMessage("death.fell.finish.item", new Object[]{this.b.getScoreboardDisplayName(), ichatbasecomponent, itemstack1.B()}); - } else { - object = new ChatMessage("death.fell.finish", new Object[]{this.b.getScoreboardDisplayName(), ichatbasecomponent}); - } - } else { - object = new ChatMessage("death.fell.killer", new Object[]{this.b.getScoreboardDisplayName()}); - } - } else { - object = new ChatMessage("death.fell.accident." + this.a(combatentry), new Object[]{this.b.getScoreboardDisplayName()}); - } - } else { - object = combatentry1.a().getLocalizedDeathMessage(this.b); - } - - return (IChatBaseComponent) object; - } - } - - @Nullable - public EntityLiving c() { - EntityLiving entityliving = null; - EntityHuman entityhuman = null; - float f = 0.0F; - float f1 = 0.0F; - Iterator iterator = this.a.iterator(); - - while (iterator.hasNext()) { - CombatEntry combatentry = (CombatEntry) iterator.next(); - - if (combatentry.a().getEntity() instanceof EntityHuman && (entityhuman == null || combatentry.c() > f1)) { - f1 = combatentry.c(); - entityhuman = (EntityHuman) combatentry.a().getEntity(); - } - - if (combatentry.a().getEntity() instanceof EntityLiving && (entityliving == null || combatentry.c() > f)) { - f = combatentry.c(); - entityliving = (EntityLiving) combatentry.a().getEntity(); - } - } - - if (entityhuman != null && f1 >= f / 3.0F) { - return entityhuman; - } else { - return entityliving; - } - } - - @Nullable - private CombatEntry j() { - CombatEntry combatentry = null; - CombatEntry combatentry1 = null; - float f = 0.0F; - float f1 = 0.0F; - - for (int i = 0; i < this.a.size(); ++i) { - CombatEntry combatentry2 = (CombatEntry) this.a.get(i); - CombatEntry combatentry3 = i > 0 ? (CombatEntry) this.a.get(i - 1) : null; - - if ((combatentry2.a() == DamageSource.FALL || combatentry2.a() == DamageSource.OUT_OF_WORLD) && combatentry2.j() > 0.0F && (combatentry == null || combatentry2.j() > f1)) { - if (i > 0) { - combatentry = combatentry3; - } else { - combatentry = combatentry2; - } - - f1 = combatentry2.j(); - } - - if (combatentry2.g() != null && (combatentry1 == null || combatentry2.c() > f)) { - combatentry1 = combatentry2; - f = combatentry2.c(); - } - } - - if (f1 > 5.0F && combatentry != null) { - return combatentry; - } else if (f > 5.0F && combatentry1 != null) { - return combatentry1; - } else { - return null; - } - } - - private String a(CombatEntry combatentry) { - return combatentry.g() == null ? "generic" : combatentry.g(); - } - - public int f() { - return this.f ? this.b.ticksLived - this.d : this.e - this.d; - } - - private void k() { - this.h = null; - } - - public void reset() { this.g(); } // Paper - OBFHELPER - public void g() { - int i = this.f ? 300 : 100; - - if (this.g && (!this.b.isAlive() || this.b.ticksLived - this.c > i)) { - boolean flag = this.f; - - this.g = false; - this.f = false; - this.e = this.b.ticksLived; - if (flag) { - this.b.exitCombat(); - } - - this.a.clear(); - } - - } - - public EntityLiving h() { - return this.b; - } -} diff --git a/src/main/java/net/minecraft/server/CommandBlockListenerAbstract.java b/src/main/java/net/minecraft/server/CommandBlockListenerAbstract.java deleted file mode 100644 index 23a69ba57..000000000 --- a/src/main/java/net/minecraft/server/CommandBlockListenerAbstract.java +++ /dev/null @@ -1,198 +0,0 @@ -package net.minecraft.server; - -import com.mojang.brigadier.context.CommandContext; -import java.text.SimpleDateFormat; -import java.util.Date; -import javax.annotation.Nullable; -import org.bukkit.command.CommandSender; - -public abstract class CommandBlockListenerAbstract implements ICommandListener { - - private static final SimpleDateFormat b = new SimpleDateFormat("HH:mm:ss"); - private long lastExecution = -1L; - private boolean updateLastExecution = true; - private int successCount; - private boolean trackOutput = true; - private IChatBaseComponent lastOutput; - private String command = ""; - private IChatBaseComponent customName = new ChatComponentText("@"); - // CraftBukkit start - @Override - public abstract CommandSender getBukkitSender(CommandListenerWrapper wrapper); - // CraftBukkit end - - public CommandBlockListenerAbstract() {} - - public int i() { - return this.successCount; - } - - public void a(int i) { - this.successCount = i; - } - - public IChatBaseComponent j() { - return (IChatBaseComponent) (this.lastOutput == null ? new ChatComponentText("") : this.lastOutput); - } - - public NBTTagCompound a(NBTTagCompound nbttagcompound) { - nbttagcompound.setString("Command", this.command); - nbttagcompound.setInt("SuccessCount", this.successCount); - nbttagcompound.setString("CustomName", IChatBaseComponent.ChatSerializer.a(this.customName)); - nbttagcompound.setBoolean("TrackOutput", this.trackOutput); - if (this.lastOutput != null && this.trackOutput) { - nbttagcompound.setString("LastOutput", IChatBaseComponent.ChatSerializer.a(this.lastOutput)); - } - - nbttagcompound.setBoolean("UpdateLastExecution", this.updateLastExecution); - if (this.updateLastExecution && this.lastExecution > 0L) { - nbttagcompound.setLong("LastExecution", this.lastExecution); - } - - return nbttagcompound; - } - - public void b(NBTTagCompound nbttagcompound) { - this.command = nbttagcompound.getString("Command"); - this.successCount = nbttagcompound.getInt("SuccessCount"); - if (nbttagcompound.hasKeyOfType("CustomName", 8)) { - this.customName = MCUtil.getBaseComponentFromNbt("CustomName", nbttagcompound); // Paper - Catch ParseException - } - - if (nbttagcompound.hasKeyOfType("TrackOutput", 1)) { - this.trackOutput = nbttagcompound.getBoolean("TrackOutput"); - } - - if (nbttagcompound.hasKeyOfType("LastOutput", 8) && this.trackOutput) { - try { - this.lastOutput = IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("LastOutput")); - } catch (Throwable throwable) { - this.lastOutput = new ChatComponentText(throwable.getMessage()); - } - } else { - this.lastOutput = null; - } - - if (nbttagcompound.hasKey("UpdateLastExecution")) { - this.updateLastExecution = nbttagcompound.getBoolean("UpdateLastExecution"); - } - - if (this.updateLastExecution && nbttagcompound.hasKey("LastExecution")) { - this.lastExecution = nbttagcompound.getLong("LastExecution"); - } else { - this.lastExecution = -1L; - } - - } - - public void setCommand(String s) { - this.command = s; - this.successCount = 0; - } - - public String getCommand() { - return this.command; - } - - public boolean a(World world) { - if (!world.isClientSide && world.getTime() != this.lastExecution) { - if ("Searge".equalsIgnoreCase(this.command)) { - this.lastOutput = new ChatComponentText("#itzlipofutzli"); - this.successCount = 1; - return true; - } else { - this.successCount = 0; - MinecraftServer minecraftserver = this.d().getMinecraftServer(); - - if (minecraftserver != null && minecraftserver.F() && minecraftserver.getEnableCommandBlock() && !UtilColor.b(this.command)) { - try { - this.lastOutput = null; - this.successCount = minecraftserver.getCommandDispatcher().dispatchServerCommand(this.getWrapper(), this.command); // CraftBukkit - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Executing command block"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Command to be executed"); - - crashreportsystemdetails.a("Command", this::getCommand); - crashreportsystemdetails.a("Name", () -> { - return this.getName().getString(); - }); - throw new ReportedException(crashreport); - } - } - - if (this.updateLastExecution) { - this.lastExecution = world.getTime(); - } else { - this.lastExecution = -1L; - } - - return true; - } - } else { - return false; - } - } - - public IChatBaseComponent getName() { - return this.customName; - } - - public void setName(IChatBaseComponent ichatbasecomponent) { - // CraftBukkit start - if (ichatbasecomponent == null) { - ichatbasecomponent = new ChatComponentText("@"); - } - // CraftBukkit end - this.customName = ichatbasecomponent; - } - - @Override - public void sendMessage(IChatBaseComponent ichatbasecomponent) { - if (this.trackOutput) { - this.lastOutput = (new ChatComponentText("[" + CommandBlockListenerAbstract.b.format(new Date()) + "] ")).addSibling(ichatbasecomponent); - this.e(); - } - - } - - public abstract WorldServer d(); - - public abstract void e(); - - public void c(@Nullable IChatBaseComponent ichatbasecomponent) { - this.lastOutput = ichatbasecomponent; - } - - public void a(boolean flag) { - this.trackOutput = flag; - } - - public boolean a(EntityHuman entityhuman) { - if (!entityhuman.isCreativeAndOp()) { - return false; - } else { - if (entityhuman.getWorld().isClientSide) { - entityhuman.a(this); - } - - return true; - } - } - - public abstract CommandListenerWrapper getWrapper(); - - @Override - public boolean shouldSendSuccess() { - return this.d().getGameRules().getBoolean(GameRules.SEND_COMMAND_FEEDBACK) && this.trackOutput; - } - - @Override - public boolean shouldSendFailure() { - return this.trackOutput; - } - - @Override - public boolean shouldBroadcastCommands() { - return this.d().getGameRules().getBoolean(GameRules.COMMAND_BLOCK_OUTPUT); - } -} diff --git a/src/main/java/net/minecraft/server/CommandDispatcher.java b/src/main/java/net/minecraft/server/CommandDispatcher.java deleted file mode 100644 index 686878fb0..000000000 --- a/src/main/java/net/minecraft/server/CommandDispatcher.java +++ /dev/null @@ -1,340 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.builder.ArgumentBuilder; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.builder.RequiredArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.tree.CommandNode; -import com.mojang.brigadier.tree.RootCommandNode; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.function.Predicate; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import com.google.common.base.Joiner; -import java.util.LinkedHashSet; -import org.bukkit.craftbukkit.command.VanillaCommandWrapper; -import org.bukkit.event.player.PlayerCommandSendEvent; -import org.bukkit.event.server.ServerCommandEvent; -// CraftBukkit end - -public class CommandDispatcher { - - private static final Logger LOGGER = LogManager.getLogger(); - private final com.mojang.brigadier.CommandDispatcher b = new com.mojang.brigadier.CommandDispatcher(); - - // CraftBukkit start - public final CommandDispatcher init(boolean flag) { - CommandAdvancement.a(this.b); - CommandExecute.a(this.b); - CommandBossBar.a(this.b); - CommandClear.a(this.b); - CommandClone.a(this.b); - CommandData.a(this.b); - CommandDatapack.a(this.b); - CommandDebug.a(this.b); - CommandGamemodeDefault.a(this.b); - CommandDifficulty.a(this.b); - CommandEffect.a(this.b); - CommandMe.a(this.b); - CommandEnchant.a(this.b); - CommandXp.a(this.b); - CommandFill.a(this.b); - CommandForceload.a(this.b); - CommandFunction.a(this.b); - CommandGamemode.a(this.b); - CommandGamerule.a(this.b); - CommandGive.a(this.b); - CommandHelp.a(this.b); - CommandKick.a(this.b); - CommandKill.a(this.b); - CommandList.a(this.b); - CommandLocate.a(this.b); - CommandLoot.a(this.b); - CommandTell.a(this.b); - CommandParticle.a(this.b); - CommandPlaySound.a(this.b); - CommandPublish.a(this.b); - CommandReload.a(this.b); - CommandRecipe.a(this.b); - CommandReplaceItem.a(this.b); - CommandSay.a(this.b); - CommandSchedule.a(this.b); - CommandScoreboard.a(this.b); - CommandSeed.a(this.b); - CommandSetBlock.a(this.b); - CommandSpawnpoint.a(this.b); - CommandSetWorldSpawn.a(this.b); - CommandSpreadPlayers.a(this.b); - CommandStopSound.a(this.b); - CommandSummon.a(this.b); - CommandTag.a(this.b); - CommandTeam.a(this.b); - CommandTeamMsg.a(this.b); - CommandTeleport.a(this.b); - CommandTellRaw.a(this.b); - CommandTime.a(this.b); - CommandTitle.a(this.b); - CommandTrigger.a(this.b); - CommandWeather.a(this.b); - CommandWorldBorder.a(this.b); - if (flag) { - CommandBanIp.a(this.b); - CommandBanList.a(this.b); - CommandBan.a(this.b); - CommandDeop.a(this.b); - CommandOp.a(this.b); - CommandPardon.a(this.b); - CommandPardonIP.a(this.b); - CommandSaveAll.a(this.b); - CommandSaveOff.a(this.b); - CommandSaveOn.a(this.b); - CommandIdleTimeout.a(this.b); - CommandStop.a(this.b); - CommandWhitelist.a(this.b); - } - - this.b.findAmbiguities((commandnode, commandnode1, commandnode2, collection) -> { - // CommandDispatcher.LOGGER.warn("Ambiguity between arguments {} and {} with inputs: {}", this.b.getPath(commandnode1), this.b.getPath(commandnode2), collection); // CraftBukkit - }); - return this; - } - - public CommandDispatcher() { - // CraftBukkit end - this.b.setConsumer((commandcontext, flag1, i) -> { - ((CommandListenerWrapper) commandcontext.getSource()).a(commandcontext, flag1, i); - }); - } - - // CraftBukkit start - public int dispatchServerCommand(CommandListenerWrapper sender, String command) { - Joiner joiner = Joiner.on(" "); - if (command.startsWith("/")) { - command = command.substring(1); - } - - ServerCommandEvent event = new ServerCommandEvent(sender.getBukkitSender(), command); - org.bukkit.Bukkit.getPluginManager().callEvent(event); - if (event.isCancelled()) { - return 0; - } - command = event.getCommand(); - - String[] args = command.split(" "); - - 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; - } - - // Handle vanilla commands; - if (sender.getWorld().getServer().getCommandBlockOverride(args[0])) { - args[0] = "minecraft:" + args[0]; - } - - return this.a(sender, joiner.join(args)); - } - - public int a(CommandListenerWrapper commandlistenerwrapper, String s) { - return this.a(commandlistenerwrapper, s, s); - } - - public int a(CommandListenerWrapper commandlistenerwrapper, String s, String label) { - // CraftBukkit end - StringReader stringreader = new StringReader(s); - - if (stringreader.canRead() && stringreader.peek() == '/') { - stringreader.skip(); - } - - commandlistenerwrapper.getServer().getMethodProfiler().enter(s); - - byte b0; - - try { - ChatComponentText chatcomponenttext; - - try { - int i = this.b.execute(stringreader, commandlistenerwrapper); - - return i; - } catch (CommandException commandexception) { - commandlistenerwrapper.sendFailureMessage(commandexception.a()); - b0 = 0; - return b0; - } catch (CommandSyntaxException commandsyntaxexception) { - commandlistenerwrapper.sendFailureMessage(ChatComponentUtils.a(commandsyntaxexception.getRawMessage())); - if (commandsyntaxexception.getInput() != null && commandsyntaxexception.getCursor() >= 0) { - int j = Math.min(commandsyntaxexception.getInput().length(), commandsyntaxexception.getCursor()); - - chatcomponenttext = new ChatComponentText(""); - if (j > 10) { - chatcomponenttext.a("..."); - } - - chatcomponenttext.a(commandsyntaxexception.getInput().substring(Math.max(0, j - 10), j)); - if (j < commandsyntaxexception.getInput().length()) { - ChatComponentText chatcomponenttext1 = new ChatComponentText(commandsyntaxexception.getInput().substring(j)); - - chatcomponenttext1.getChatModifier().setColor(EnumChatFormat.RED); - chatcomponenttext1.getChatModifier().setUnderline(Boolean.valueOf(true)); - chatcomponenttext.addSibling(chatcomponenttext1); - } - - ChatMessage chatmessage = new ChatMessage("command.context.here", new Object[0]); - - chatmessage.getChatModifier().setItalic(Boolean.valueOf(true)); - chatmessage.getChatModifier().setColor(EnumChatFormat.RED); - chatcomponenttext.addSibling(chatmessage); - chatcomponenttext.getChatModifier().setColor(EnumChatFormat.GRAY); - chatcomponenttext.getChatModifier().setChatClickable(new ChatClickable(ChatClickable.EnumClickAction.SUGGEST_COMMAND, label)); // CraftBukkit - commandlistenerwrapper.sendFailureMessage(chatcomponenttext); - } - - b0 = 0; - } catch (Exception exception) { - ChatMessage chatmessage1 = new ChatMessage("command.failed", new Object[0]); - - chatcomponenttext = new ChatComponentText(exception.getMessage() == null ? exception.getClass().getName() : exception.getMessage()); - if (CommandDispatcher.LOGGER.isDebugEnabled()) { - StackTraceElement[] astacktraceelement = exception.getStackTrace(); - - for (int k = 0; k < Math.min(astacktraceelement.length, 3); ++k) { - chatcomponenttext.a("\n\n" + astacktraceelement[k].getMethodName() + "\n " + astacktraceelement[k].getFileName() + ":" + astacktraceelement[k].getLineNumber()); - } - } - - chatmessage1.getChatModifier().setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_TEXT, chatcomponenttext)); - commandlistenerwrapper.sendFailureMessage(chatmessage1); - byte b1 = 0; - - return b1; - } - } finally { - commandlistenerwrapper.getServer().getMethodProfiler().exit(); - } - - return b0; - } - - public void a(EntityPlayer entityplayer) { - if ( org.spigotmc.SpigotConfig.tabComplete < 0 ) return; // Spigot - // CraftBukkit start - // Register Vanilla commands into builtRoot as before - Map, CommandNode> map = Maps.newIdentityHashMap(); // Use identity to prevent aliasing issues - RootCommandNode vanillaRoot = new RootCommandNode(); - - RootCommandNode vanilla = entityplayer.server.vanillaCommandDispatcher.a().getRoot(); - map.put(vanilla, vanillaRoot); - this.a(vanilla, vanillaRoot, entityplayer.getCommandListener(), (Map) map); - - // Now build the global commands in a second pass - RootCommandNode rootcommandnode = new RootCommandNode(); - - map.put(this.b.getRoot(), rootcommandnode); - this.a(this.b.getRoot(), rootcommandnode, entityplayer.getCommandListener(), (Map) map); - - Collection bukkit = new LinkedHashSet<>(); - for (CommandNode node : rootcommandnode.getChildren()) { - bukkit.add(node.getName()); - } - - PlayerCommandSendEvent event = new PlayerCommandSendEvent(entityplayer.getBukkitEntity(), new LinkedHashSet<>(bukkit)); - event.getPlayer().getServer().getPluginManager().callEvent(event); - - // Remove labels that were removed during the event - for (String orig : bukkit) { - if (!event.getCommands().contains(orig)) { - rootcommandnode.removeCommand(orig); - } - } - // CraftBukkit end - entityplayer.playerConnection.sendPacket(new PacketPlayOutCommands(rootcommandnode)); - } - - private void a(CommandNode commandnode, CommandNode commandnode1, CommandListenerWrapper commandlistenerwrapper, Map, CommandNode> map) { - Iterator iterator = commandnode.getChildren().iterator(); - - while (iterator.hasNext()) { - CommandNode commandnode2 = (CommandNode) iterator.next(); - if ( !org.spigotmc.SpigotConfig.sendNamespaced && commandnode2.getName().contains( ":" ) ) continue; // Spigot - - if (commandnode2.canUse(commandlistenerwrapper)) { - ArgumentBuilder argumentbuilder = commandnode2.createBuilder(); // CraftBukkit - decompile error - - argumentbuilder.requires((icompletionprovider) -> { - return true; - }); - if (argumentbuilder.getCommand() != null) { - argumentbuilder.executes((commandcontext) -> { - return 0; - }); - } - - if (argumentbuilder instanceof RequiredArgumentBuilder) { - RequiredArgumentBuilder requiredargumentbuilder = (RequiredArgumentBuilder) argumentbuilder; - - if (requiredargumentbuilder.getSuggestionsProvider() != null) { - requiredargumentbuilder.suggests(CompletionProviders.b(requiredargumentbuilder.getSuggestionsProvider())); - } - } - - if (argumentbuilder.getRedirect() != null) { - argumentbuilder.redirect((CommandNode) map.get(argumentbuilder.getRedirect())); - } - - CommandNode commandnode3 = argumentbuilder.build(); // CraftBukkit - decompile error - - map.put(commandnode2, commandnode3); - commandnode1.addChild(commandnode3); - if (!commandnode2.getChildren().isEmpty()) { - this.a(commandnode2, commandnode3, commandlistenerwrapper, map); - } - } - } - - } - - public static LiteralArgumentBuilder a(String s) { - return LiteralArgumentBuilder.literal(s); - } - - public static RequiredArgumentBuilder a(String s, ArgumentType argumenttype) { - return RequiredArgumentBuilder.argument(s, argumenttype); - } - - public static Predicate a(CommandDispatcher.a commanddispatcher_a) { - return (s) -> { - try { - commanddispatcher_a.parse(new StringReader(s)); - return true; - } catch (CommandSyntaxException commandsyntaxexception) { - return false; - } - }; - } - - public com.mojang.brigadier.CommandDispatcher a() { - return this.b; - } - - @FunctionalInterface - public interface a { - - void parse(StringReader stringreader) throws CommandSyntaxException; - } -} diff --git a/src/main/java/net/minecraft/server/CommandEffect.java b/src/main/java/net/minecraft/server/CommandEffect.java deleted file mode 100644 index f52e6752f..000000000 --- a/src/main/java/net/minecraft/server/CommandEffect.java +++ /dev/null @@ -1,131 +0,0 @@ -package net.minecraft.server; - -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.arguments.BoolArgumentType; -import com.mojang.brigadier.arguments.IntegerArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.builder.RequiredArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import java.util.Collection; -import java.util.Iterator; -import javax.annotation.Nullable; - -public class CommandEffect { - - private static final SimpleCommandExceptionType a = new SimpleCommandExceptionType(new ChatMessage("commands.effect.give.failed", new Object[0])); - private static final SimpleCommandExceptionType b = new SimpleCommandExceptionType(new ChatMessage("commands.effect.clear.everything.failed", new Object[0])); - private static final SimpleCommandExceptionType c = new SimpleCommandExceptionType(new ChatMessage("commands.effect.clear.specific.failed", new Object[0])); - - public static void a(com.mojang.brigadier.CommandDispatcher com_mojang_brigadier_commanddispatcher) { - com_mojang_brigadier_commanddispatcher.register((LiteralArgumentBuilder) ((LiteralArgumentBuilder) ((LiteralArgumentBuilder) CommandDispatcher.a("effect").requires((commandlistenerwrapper) -> { - return commandlistenerwrapper.hasPermission(2); - })).then(CommandDispatcher.a("clear").then(((RequiredArgumentBuilder) CommandDispatcher.a("targets", (ArgumentType) ArgumentEntity.multipleEntities()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets")); - })).then(CommandDispatcher.a("effect", (ArgumentType) ArgumentMobEffect.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ArgumentMobEffect.a(commandcontext, "effect")); - }))))).then(CommandDispatcher.a("give").then(CommandDispatcher.a("targets", (ArgumentType) ArgumentEntity.multipleEntities()).then(((RequiredArgumentBuilder) CommandDispatcher.a("effect", (ArgumentType) ArgumentMobEffect.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ArgumentMobEffect.a(commandcontext, "effect"), (Integer) null, 0, true); - })).then(((RequiredArgumentBuilder) CommandDispatcher.a("seconds", (ArgumentType) IntegerArgumentType.integer(1, 1000000)).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ArgumentMobEffect.a(commandcontext, "effect"), IntegerArgumentType.getInteger(commandcontext, "seconds"), 0, true); - })).then(((RequiredArgumentBuilder) CommandDispatcher.a("amplifier", (ArgumentType) IntegerArgumentType.integer(0, 255)).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ArgumentMobEffect.a(commandcontext, "effect"), IntegerArgumentType.getInteger(commandcontext, "seconds"), IntegerArgumentType.getInteger(commandcontext, "amplifier"), true); - })).then(CommandDispatcher.a("hideParticles", (ArgumentType) BoolArgumentType.bool()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ArgumentMobEffect.a(commandcontext, "effect"), IntegerArgumentType.getInteger(commandcontext, "seconds"), IntegerArgumentType.getInteger(commandcontext, "amplifier"), !BoolArgumentType.getBool(commandcontext, "hideParticles")); - })))))))); - } - - private static int a(CommandListenerWrapper commandlistenerwrapper, Collection collection, MobEffectList mobeffectlist, @Nullable Integer integer, int i, boolean flag) throws CommandSyntaxException { - int j = 0; - int k; - - if (integer != null) { - if (mobeffectlist.isInstant()) { - k = integer; - } else { - k = integer * 20; - } - } else if (mobeffectlist.isInstant()) { - k = 1; - } else { - k = 600; - } - - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (entity instanceof EntityLiving) { - MobEffect mobeffect = new MobEffect(mobeffectlist, k, i, false, flag); - - if (((EntityLiving) entity).addEffect(mobeffect, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.COMMAND)) { // CraftBukkit - ++j; - } - } - } - - if (j == 0) { - throw CommandEffect.a.create(); - } else { - if (collection.size() == 1) { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.effect.give.success.single", new Object[]{mobeffectlist.d(), ((Entity) collection.iterator().next()).getScoreboardDisplayName(), k / 20}), true); - } else { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.effect.give.success.multiple", new Object[]{mobeffectlist.d(), collection.size(), k / 20}), true); - } - - return j; - } - } - - private static int a(CommandListenerWrapper commandlistenerwrapper, Collection collection) throws CommandSyntaxException { - int i = 0; - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (entity instanceof EntityLiving && ((EntityLiving) entity).removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.COMMAND)) { // CraftBukkit - ++i; - } - } - - if (i == 0) { - throw CommandEffect.b.create(); - } else { - if (collection.size() == 1) { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.effect.clear.everything.success.single", new Object[]{((Entity) collection.iterator().next()).getScoreboardDisplayName()}), true); - } else { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.effect.clear.everything.success.multiple", new Object[]{collection.size()}), true); - } - - return i; - } - } - - private static int a(CommandListenerWrapper commandlistenerwrapper, Collection collection, MobEffectList mobeffectlist) throws CommandSyntaxException { - int i = 0; - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (entity instanceof EntityLiving && ((EntityLiving) entity).removeEffect(mobeffectlist, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.COMMAND)) { // CraftBukkit - ++i; - } - } - - if (i == 0) { - throw CommandEffect.c.create(); - } else { - if (collection.size() == 1) { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.effect.clear.specific.success.single", new Object[]{mobeffectlist.d(), ((Entity) collection.iterator().next()).getScoreboardDisplayName()}), true); - } else { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.effect.clear.specific.success.multiple", new Object[]{mobeffectlist.d(), collection.size()}), true); - } - - return i; - } - } -} diff --git a/src/main/java/net/minecraft/server/CommandGamemode.java b/src/main/java/net/minecraft/server/CommandGamemode.java deleted file mode 100644 index fd03d57a5..000000000 --- a/src/main/java/net/minecraft/server/CommandGamemode.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.minecraft.server; - -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; - -public class CommandGamemode { - - public static void a(com.mojang.brigadier.CommandDispatcher com_mojang_brigadier_commanddispatcher) { - LiteralArgumentBuilder literalargumentbuilder = (LiteralArgumentBuilder) CommandDispatcher.a("gamemode").requires((commandlistenerwrapper) -> { - return commandlistenerwrapper.hasPermission(2); - }); - EnumGamemode[] aenumgamemode = EnumGamemode.values(); - int i = aenumgamemode.length; - - for (int j = 0; j < i; ++j) { - EnumGamemode enumgamemode = aenumgamemode[j]; - - if (enumgamemode != EnumGamemode.NOT_SET) { - literalargumentbuilder.then(((LiteralArgumentBuilder) CommandDispatcher.a(enumgamemode.b()).executes((commandcontext) -> { - return a(commandcontext, (Collection) Collections.singleton(((CommandListenerWrapper) commandcontext.getSource()).h()), enumgamemode); - })).then(CommandDispatcher.a("target", (ArgumentType) ArgumentEntity.d()).executes((commandcontext) -> { - return a(commandcontext, ArgumentEntity.f(commandcontext, "target"), enumgamemode); - }))); - } - } - - com_mojang_brigadier_commanddispatcher.register(literalargumentbuilder); - } - - private static void a(CommandListenerWrapper commandlistenerwrapper, EntityPlayer entityplayer, EnumGamemode enumgamemode) { - ChatMessage chatmessage = new ChatMessage("gameMode." + enumgamemode.b(), new Object[0]); - - if (commandlistenerwrapper.getEntity() == entityplayer) { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.gamemode.success.self", new Object[]{chatmessage}), true); - } else { - if (commandlistenerwrapper.getWorld().getGameRules().getBoolean(GameRules.SEND_COMMAND_FEEDBACK)) { - entityplayer.sendMessage(new ChatMessage("gameMode.changed", new Object[]{chatmessage})); - } - - commandlistenerwrapper.sendMessage(new ChatMessage("commands.gamemode.success.other", new Object[]{entityplayer.getScoreboardDisplayName(), chatmessage}), true); - } - - } - - private static int a(CommandContext commandcontext, Collection collection, EnumGamemode enumgamemode) { - int i = 0; - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - if (entityplayer.playerInteractManager.getGameMode() != enumgamemode) { - entityplayer.a(enumgamemode); - // CraftBukkit start - handle event cancelling the change - if (entityplayer.playerInteractManager.getGameMode() != enumgamemode) { - commandcontext.getSource().sendFailureMessage(new ChatComponentText("Failed to set the gamemode of '" + entityplayer.getName() + "'")); - continue; - } - // CraftBukkit end - a((CommandListenerWrapper) commandcontext.getSource(), entityplayer, enumgamemode); - ++i; - } - } - - return i; - } -} diff --git a/src/main/java/net/minecraft/server/CommandGamerule.java b/src/main/java/net/minecraft/server/CommandGamerule.java deleted file mode 100644 index 1ae60aae1..000000000 --- a/src/main/java/net/minecraft/server/CommandGamerule.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.minecraft.server; - -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; - -public class CommandGamerule { - - public static void a(com.mojang.brigadier.CommandDispatcher com_mojang_brigadier_commanddispatcher) { - final LiteralArgumentBuilder literalargumentbuilder = (LiteralArgumentBuilder) CommandDispatcher.a("gamerule").requires((commandlistenerwrapper) -> { - return commandlistenerwrapper.hasPermission(2); - }); - - GameRules.a(new GameRules.GameRuleVisitor() { - @Override - public > void a(GameRules.GameRuleKey gamerules_gamerulekey, GameRules.GameRuleDefinition gamerules_gameruledefinition) { - literalargumentbuilder.then(((LiteralArgumentBuilder) CommandDispatcher.a(gamerules_gamerulekey.a()).executes((commandcontext) -> { - return CommandGamerule.b((CommandListenerWrapper) commandcontext.getSource(), gamerules_gamerulekey); - })).then(gamerules_gameruledefinition.a("value").executes((commandcontext) -> { - return CommandGamerule.b(commandcontext, gamerules_gamerulekey); - }))); - } - }); - com_mojang_brigadier_commanddispatcher.register(literalargumentbuilder); - } - - private static > int b(CommandContext commandcontext, GameRules.GameRuleKey gamerules_gamerulekey) { - CommandListenerWrapper commandlistenerwrapper = (CommandListenerWrapper) commandcontext.getSource(); - T t0 = commandlistenerwrapper.getWorld().getGameRules().get(gamerules_gamerulekey); // CraftBukkit - - t0.b(commandcontext, "value"); - commandlistenerwrapper.sendMessage(new ChatMessage("commands.gamerule.set", new Object[]{gamerules_gamerulekey.a(), t0.toString()}), true); - return t0.getIntValue(); - } - - private static > int b(CommandListenerWrapper commandlistenerwrapper, GameRules.GameRuleKey gamerules_gamerulekey) { - T t0 = commandlistenerwrapper.getWorld().getGameRules().get(gamerules_gamerulekey); // CraftBukkit - - commandlistenerwrapper.sendMessage(new ChatMessage("commands.gamerule.query", new Object[]{gamerules_gamerulekey.a(), t0.toString()}), false); - return t0.getIntValue(); - } -} diff --git a/src/main/java/net/minecraft/server/CommandListenerWrapper.java b/src/main/java/net/minecraft/server/CommandListenerWrapper.java deleted file mode 100644 index 0b23a0548..000000000 --- a/src/main/java/net/minecraft/server/CommandListenerWrapper.java +++ /dev/null @@ -1,258 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.brigadier.ResultConsumer; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import com.mojang.brigadier.suggestion.Suggestions; -import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import com.mojang.brigadier.tree.CommandNode; -import java.util.Collection; -import java.util.Iterator; -import java.util.concurrent.CompletableFuture; -import java.util.function.BinaryOperator; -import java.util.stream.Stream; -import javax.annotation.Nullable; - -public class CommandListenerWrapper implements ICompletionProvider { - - public static final SimpleCommandExceptionType a = new SimpleCommandExceptionType(new ChatMessage("permissions.requires.player", new Object[0])); - public static final SimpleCommandExceptionType b = new SimpleCommandExceptionType(new ChatMessage("permissions.requires.entity", new Object[0])); - public final ICommandListener base; - private final Vec3D d; - private final WorldServer e; - private final int f; - private final String g; - private final IChatBaseComponent h; - private final MinecraftServer i; - private final boolean j; - @Nullable - private final Entity k; - private final ResultConsumer l; - private final ArgumentAnchor.Anchor m; - private final Vec2F n; - public CommandNode currentCommand; // CraftBukkit - - public CommandListenerWrapper(ICommandListener icommandlistener, Vec3D vec3d, Vec2F vec2f, WorldServer worldserver, int i, String s, IChatBaseComponent ichatbasecomponent, MinecraftServer minecraftserver, @Nullable Entity entity) { - this(icommandlistener, vec3d, vec2f, worldserver, i, s, ichatbasecomponent, minecraftserver, entity, false, (commandcontext, flag, j) -> { - }, ArgumentAnchor.Anchor.FEET); - } - - protected CommandListenerWrapper(ICommandListener icommandlistener, Vec3D vec3d, Vec2F vec2f, WorldServer worldserver, int i, String s, IChatBaseComponent ichatbasecomponent, MinecraftServer minecraftserver, @Nullable Entity entity, boolean flag, ResultConsumer resultconsumer, ArgumentAnchor.Anchor argumentanchor_anchor) { - this.base = icommandlistener; - this.d = vec3d; - this.e = worldserver; - this.j = flag; - this.k = entity; - this.f = i; - this.g = s; - this.h = ichatbasecomponent; - this.i = minecraftserver; - this.l = resultconsumer; - this.m = argumentanchor_anchor; - this.n = vec2f; - } - - public CommandListenerWrapper a(Entity entity) { - return this.k == entity ? this : new CommandListenerWrapper(this.base, this.d, this.n, this.e, this.f, entity.getDisplayName().getString(), entity.getScoreboardDisplayName(), this.i, entity, this.j, this.l, this.m); - } - - public CommandListenerWrapper a(Vec3D vec3d) { - return this.d.equals(vec3d) ? this : new CommandListenerWrapper(this.base, vec3d, this.n, this.e, this.f, this.g, this.h, this.i, this.k, this.j, this.l, this.m); - } - - public CommandListenerWrapper a(Vec2F vec2f) { - return this.n.c(vec2f) ? this : new CommandListenerWrapper(this.base, this.d, vec2f, this.e, this.f, this.g, this.h, this.i, this.k, this.j, this.l, this.m); - } - - public CommandListenerWrapper a(ResultConsumer resultconsumer) { - return this.l.equals(resultconsumer) ? this : new CommandListenerWrapper(this.base, this.d, this.n, this.e, this.f, this.g, this.h, this.i, this.k, this.j, resultconsumer, this.m); - } - - public CommandListenerWrapper a(ResultConsumer resultconsumer, BinaryOperator> binaryoperator) { - ResultConsumer resultconsumer1 = (ResultConsumer) binaryoperator.apply(this.l, resultconsumer); - - return this.a(resultconsumer1); - } - - public CommandListenerWrapper a() { - return this.j ? this : new CommandListenerWrapper(this.base, this.d, this.n, this.e, this.f, this.g, this.h, this.i, this.k, true, this.l, this.m); - } - - public CommandListenerWrapper a(int i) { - return i == this.f ? this : new CommandListenerWrapper(this.base, this.d, this.n, this.e, i, this.g, this.h, this.i, this.k, this.j, this.l, this.m); - } - - public CommandListenerWrapper b(int i) { - return i <= this.f ? this : new CommandListenerWrapper(this.base, this.d, this.n, this.e, i, this.g, this.h, this.i, this.k, this.j, this.l, this.m); - } - - public CommandListenerWrapper a(ArgumentAnchor.Anchor argumentanchor_anchor) { - return argumentanchor_anchor == this.m ? this : new CommandListenerWrapper(this.base, this.d, this.n, this.e, this.f, this.g, this.h, this.i, this.k, this.j, this.l, argumentanchor_anchor); - } - - public CommandListenerWrapper a(WorldServer worldserver) { - return worldserver == this.e ? this : new CommandListenerWrapper(this.base, this.d, this.n, worldserver, this.f, this.g, this.h, this.i, this.k, this.j, this.l, this.m); - } - - public CommandListenerWrapper a(Entity entity, ArgumentAnchor.Anchor argumentanchor_anchor) throws CommandSyntaxException { - return this.b(argumentanchor_anchor.a(entity)); - } - - public CommandListenerWrapper b(Vec3D vec3d) throws CommandSyntaxException { - Vec3D vec3d1 = this.m.a(this); - double d0 = vec3d.x - vec3d1.x; - double d1 = vec3d.y - vec3d1.y; - double d2 = vec3d.z - vec3d1.z; - double d3 = (double) MathHelper.sqrt(d0 * d0 + d2 * d2); - float f = MathHelper.g((float) (-(MathHelper.d(d1, d3) * 57.2957763671875D))); - float f1 = MathHelper.g((float) (MathHelper.d(d2, d0) * 57.2957763671875D) - 90.0F); - - return this.a(new Vec2F(f, f1)); - } - - public IChatBaseComponent getScoreboardDisplayName() { - return this.h; - } - - public String getName() { - return this.g; - } - - @Override - public boolean hasPermission(int i) { - // CraftBukkit start - if (currentCommand != null) { - return hasPermission(i, org.bukkit.craftbukkit.command.VanillaCommandWrapper.getPermission(currentCommand)); - } - // CraftBukkit end - - return this.f >= i; - } - - // CraftBukkit start - public boolean hasPermission(int i, String bukkitPermission) { - // World is null when loading functions - return ((getWorld() == null || !getWorld().getServer().ignoreVanillaPermissions) && this.f >= i) || getBukkitSender().hasPermission(bukkitPermission); - } - // CraftBukkit end - - public Vec3D getPosition() { - return this.d; - } - - public WorldServer getWorld() { - return this.e; - } - - @Nullable - public Entity getEntity() { - return this.k; - } - - public Entity g() throws CommandSyntaxException { - if (this.k == null) { - throw CommandListenerWrapper.b.create(); - } else { - return this.k; - } - } - - public EntityPlayer h() throws CommandSyntaxException { - if (!(this.k instanceof EntityPlayer)) { - throw CommandListenerWrapper.a.create(); - } else { - return (EntityPlayer) this.k; - } - } - - public Vec2F i() { - return this.n; - } - - public MinecraftServer getServer() { - return this.i; - } - - public ArgumentAnchor.Anchor k() { - return this.m; - } - - public void sendMessage(IChatBaseComponent ichatbasecomponent, boolean flag) { - if (this.base.shouldSendSuccess() && !this.j) { - this.base.sendMessage(ichatbasecomponent); - } - - if (flag && this.base.shouldBroadcastCommands() && !this.j) { - this.sendAdminMessage(ichatbasecomponent); - } - - } - - private void sendAdminMessage(IChatBaseComponent ichatbasecomponent) { - IChatBaseComponent ichatbasecomponent1 = (new ChatMessage("chat.type.admin", new Object[]{this.getScoreboardDisplayName(), ichatbasecomponent})).a(new EnumChatFormat[]{EnumChatFormat.GRAY, EnumChatFormat.ITALIC}); - - if (this.i.getGameRules().getBoolean(GameRules.SEND_COMMAND_FEEDBACK)) { - Iterator iterator = this.i.getPlayerList().getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - if (entityplayer != this.base && entityplayer.getBukkitEntity().hasPermission("minecraft.admin.command_feedback")) { // CraftBukkit - entityplayer.sendMessage(ichatbasecomponent1); - } - } - } - - if (this.base != this.i && this.i.getGameRules().getBoolean(GameRules.LOG_ADMIN_COMMANDS) && !org.spigotmc.SpigotConfig.silentCommandBlocks) { // Spigot - this.i.sendMessage(ichatbasecomponent1); - } - - } - - public void sendFailureMessage(IChatBaseComponent ichatbasecomponent) { - if (this.base.shouldSendFailure() && !this.j) { - this.base.sendMessage((new ChatComponentText("")).addSibling(ichatbasecomponent).a(EnumChatFormat.RED)); - } - - } - - public void a(CommandContext commandcontext, boolean flag, int i) { - if (this.l != null) { - this.l.onCommandComplete(commandcontext, flag, i); - } - - } - - @Override - public Collection l() { - return Lists.newArrayList(this.i.getPlayers()); - } - - @Override - public Collection m() { - return this.i.getScoreboard().f(); - } - - @Override - public Collection n() { - return IRegistry.SOUND_EVENT.keySet(); - } - - @Override - public Stream o() { - return this.i.getCraftingManager().c(); - } - - @Override - public CompletableFuture a(CommandContext commandcontext, SuggestionsBuilder suggestionsbuilder) { - return null; - } - - // CraftBukkit start - public org.bukkit.command.CommandSender getBukkitSender() { - return base.getBukkitSender(this); - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/CommandSpreadPlayers.java b/src/main/java/net/minecraft/server/CommandSpreadPlayers.java deleted file mode 100644 index e7f230c7e..000000000 --- a/src/main/java/net/minecraft/server/CommandSpreadPlayers.java +++ /dev/null @@ -1,305 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.arguments.BoolArgumentType; -import com.mojang.brigadier.arguments.FloatArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.Dynamic4CommandExceptionType; -import java.util.Collection; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -public class CommandSpreadPlayers { - - private static final Dynamic4CommandExceptionType a = new Dynamic4CommandExceptionType((object, object1, object2, object3) -> { - return new ChatMessage("commands.spreadplayers.failed.teams", new Object[]{object, object1, object2, object3}); - }); - private static final Dynamic4CommandExceptionType b = new Dynamic4CommandExceptionType((object, object1, object2, object3) -> { - return new ChatMessage("commands.spreadplayers.failed.entities", new Object[]{object, object1, object2, object3}); - }); - - public static void a(com.mojang.brigadier.CommandDispatcher com_mojang_brigadier_commanddispatcher) { - com_mojang_brigadier_commanddispatcher.register((LiteralArgumentBuilder) ((LiteralArgumentBuilder) CommandDispatcher.a("spreadplayers").requires((commandlistenerwrapper) -> { - return commandlistenerwrapper.hasPermission(2); - })).then(CommandDispatcher.a("center", (ArgumentType) ArgumentVec2.a()).then(CommandDispatcher.a("spreadDistance", (ArgumentType) FloatArgumentType.floatArg(0.0F)).then(CommandDispatcher.a("maxRange", (ArgumentType) FloatArgumentType.floatArg(1.0F)).then(CommandDispatcher.a("respectTeams", (ArgumentType) BoolArgumentType.bool()).then(CommandDispatcher.a("targets", (ArgumentType) ArgumentEntity.multipleEntities()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentVec2.a(commandcontext, "center"), FloatArgumentType.getFloat(commandcontext, "spreadDistance"), FloatArgumentType.getFloat(commandcontext, "maxRange"), BoolArgumentType.getBool(commandcontext, "respectTeams"), ArgumentEntity.b(commandcontext, "targets")); - }))))))); - } - - private static int a(CommandListenerWrapper commandlistenerwrapper, Vec2F vec2f, float f, float f1, boolean flag, Collection collection) throws CommandSyntaxException { - Random random = new Random(); - double d0 = (double) (vec2f.i - f1); - double d1 = (double) (vec2f.j - f1); - double d2 = (double) (vec2f.i + f1); - double d3 = (double) (vec2f.j + f1); - CommandSpreadPlayers.a[] acommandspreadplayers_a = a(random, flag ? a(collection) : collection.size(), d0, d1, d2, d3); - - a(vec2f, (double) f, commandlistenerwrapper.getWorld(), random, d0, d1, d2, d3, acommandspreadplayers_a, flag); - double d4 = a(collection, commandlistenerwrapper.getWorld(), acommandspreadplayers_a, flag); - - commandlistenerwrapper.sendMessage(new ChatMessage("commands.spreadplayers.success." + (flag ? "teams" : "entities"), new Object[]{acommandspreadplayers_a.length, vec2f.i, vec2f.j, String.format(Locale.ROOT, "%.2f", d4)}), true); - return acommandspreadplayers_a.length; - } - - private static int a(Collection collection) { - Set set = Sets.newHashSet(); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (entity instanceof EntityHuman) { - set.add(entity.getScoreboardTeam()); - } else { - set.add((ScoreboardTeamBase) null); // CraftBukkit - decompile error - } - } - - return set.size(); - } - - private static void a(Vec2F vec2f, double d0, WorldServer worldserver, Random random, double d1, double d2, double d3, double d4, CommandSpreadPlayers.a[] acommandspreadplayers_a, boolean flag) throws CommandSyntaxException { - boolean flag1 = true; - double d5 = 3.4028234663852886E38D; - - int i; - - for (i = 0; i < 10000 && flag1; ++i) { - flag1 = false; - d5 = 3.4028234663852886E38D; - - int j; - CommandSpreadPlayers.a commandspreadplayers_a; - - for (int k = 0; k < acommandspreadplayers_a.length; ++k) { - CommandSpreadPlayers.a commandspreadplayers_a1 = acommandspreadplayers_a[k]; - - j = 0; - commandspreadplayers_a = new CommandSpreadPlayers.a(); - - for (int l = 0; l < acommandspreadplayers_a.length; ++l) { - if (k != l) { - CommandSpreadPlayers.a commandspreadplayers_a2 = acommandspreadplayers_a[l]; - double d6 = commandspreadplayers_a1.a(commandspreadplayers_a2); - - d5 = Math.min(d6, d5); - if (d6 < d0) { - ++j; - commandspreadplayers_a.a = commandspreadplayers_a.a + (commandspreadplayers_a2.a - commandspreadplayers_a1.a); - commandspreadplayers_a.b = commandspreadplayers_a.b + (commandspreadplayers_a2.b - commandspreadplayers_a1.b); - } - } - } - - if (j > 0) { - commandspreadplayers_a.a = commandspreadplayers_a.a / (double) j; - commandspreadplayers_a.b = commandspreadplayers_a.b / (double) j; - double d7 = (double) commandspreadplayers_a.b(); - - if (d7 > 0.0D) { - commandspreadplayers_a.a(); - commandspreadplayers_a1.b(commandspreadplayers_a); - } else { - commandspreadplayers_a1.a(random, d1, d2, d3, d4); - } - - flag1 = true; - } - - if (commandspreadplayers_a1.a(d1, d2, d3, d4)) { - flag1 = true; - } - } - - if (!flag1) { - CommandSpreadPlayers.a[] acommandspreadplayers_a1 = acommandspreadplayers_a; - int i1 = acommandspreadplayers_a.length; - - for (j = 0; j < i1; ++j) { - commandspreadplayers_a = acommandspreadplayers_a1[j]; - if (!commandspreadplayers_a.b((IBlockAccess) worldserver)) { - commandspreadplayers_a.a(random, d1, d2, d3, d4); - flag1 = true; - } - } - } - } - - if (d5 == 3.4028234663852886E38D) { - d5 = 0.0D; - } - - if (i >= 10000) { - if (flag) { - throw CommandSpreadPlayers.a.create(acommandspreadplayers_a.length, vec2f.i, vec2f.j, String.format(Locale.ROOT, "%.2f", d5)); - } else { - throw CommandSpreadPlayers.b.create(acommandspreadplayers_a.length, vec2f.i, vec2f.j, String.format(Locale.ROOT, "%.2f", d5)); - } - } - } - - private static double a(Collection collection, WorldServer worldserver, CommandSpreadPlayers.a[] acommandspreadplayers_a, boolean flag) { - double d0 = 0.0D; - int i = 0; - Map map = Maps.newHashMap(); - - double d1; - - for (Iterator iterator = collection.iterator(); iterator.hasNext(); d0 += d1) { - Entity entity = (Entity) iterator.next(); - CommandSpreadPlayers.a commandspreadplayers_a; - - if (flag) { - ScoreboardTeamBase scoreboardteambase = entity instanceof EntityHuman ? entity.getScoreboardTeam() : null; - - if (!map.containsKey(scoreboardteambase)) { - map.put(scoreboardteambase, acommandspreadplayers_a[i++]); - } - - commandspreadplayers_a = (CommandSpreadPlayers.a) map.get(scoreboardteambase); - } else { - commandspreadplayers_a = acommandspreadplayers_a[i++]; - } - - entity.enderTeleportAndLoad((double) ((float) MathHelper.floor(commandspreadplayers_a.a) + 0.5F), (double) commandspreadplayers_a.a((IBlockAccess) worldserver), (double) MathHelper.floor(commandspreadplayers_a.b) + 0.5D); - d1 = Double.MAX_VALUE; - CommandSpreadPlayers.a[] acommandspreadplayers_a1 = acommandspreadplayers_a; - int j = acommandspreadplayers_a.length; - - for (int k = 0; k < j; ++k) { - CommandSpreadPlayers.a commandspreadplayers_a1 = acommandspreadplayers_a1[k]; - - if (commandspreadplayers_a != commandspreadplayers_a1) { - double d2 = commandspreadplayers_a.a(commandspreadplayers_a1); - - d1 = Math.min(d2, d1); - } - } - } - - if (collection.size() < 2) { - return 0.0D; - } else { - d0 /= (double) collection.size(); - return d0; - } - } - - private static CommandSpreadPlayers.a[] a(Random random, int i, double d0, double d1, double d2, double d3) { - CommandSpreadPlayers.a[] acommandspreadplayers_a = new CommandSpreadPlayers.a[i]; - - for (int j = 0; j < acommandspreadplayers_a.length; ++j) { - CommandSpreadPlayers.a commandspreadplayers_a = new CommandSpreadPlayers.a(); - - commandspreadplayers_a.a(random, d0, d1, d2, d3); - acommandspreadplayers_a[j] = commandspreadplayers_a; - } - - return acommandspreadplayers_a; - } - - static class a { - - private double a; - private double b; - - a() {} - - double a(CommandSpreadPlayers.a commandspreadplayers_a) { - double d0 = this.a - commandspreadplayers_a.a; - double d1 = this.b - commandspreadplayers_a.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.a commandspreadplayers_a) { - this.a -= commandspreadplayers_a.a; - this.b -= commandspreadplayers_a.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(IBlockAccess iblockaccess) { - BlockPosition blockposition = new BlockPosition(this.a, 256.0D, this.b); - - do { - if (blockposition.getY() <= 0) { - return 257; - } - - blockposition = blockposition.down(); - } while (getType(iblockaccess, blockposition).isAir()); // CraftBukkit - - return blockposition.getY() + 1; - } - - public boolean b(IBlockAccess iblockaccess) { - BlockPosition blockposition = new BlockPosition(this.a, 256.0D, this.b); - - IBlockData iblockdata; - - do { - if (blockposition.getY() <= 0) { - return false; - } - - blockposition = blockposition.down(); - iblockdata = getType(iblockaccess, blockposition); // CraftBukkit - } while (iblockdata.isAir()); - - Material material = iblockdata.getMaterial(); - - 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(IBlockAccess iblockaccess, BlockPosition position) { - ((ChunkProviderServer) ((World) iblockaccess).chunkProvider).getChunkAt(position.getX() >> 4, position.getZ() >> 4, true); - return iblockaccess.getType(position); - } - // CraftBukkit end - } -} diff --git a/src/main/java/net/minecraft/server/CommandSummon.java b/src/main/java/net/minecraft/server/CommandSummon.java deleted file mode 100644 index b9e103724..000000000 --- a/src/main/java/net/minecraft/server/CommandSummon.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.minecraft.server; - -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.builder.RequiredArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; - -public class CommandSummon { - - private static final SimpleCommandExceptionType a = new SimpleCommandExceptionType(new ChatMessage("commands.summon.failed", new Object[0])); - - public static void a(com.mojang.brigadier.CommandDispatcher com_mojang_brigadier_commanddispatcher) { - com_mojang_brigadier_commanddispatcher.register((LiteralArgumentBuilder) ((LiteralArgumentBuilder) CommandDispatcher.a("summon").requires((commandlistenerwrapper) -> { - return commandlistenerwrapper.hasPermission(2); - })).then(((RequiredArgumentBuilder) CommandDispatcher.a("entity", (ArgumentType) ArgumentEntitySummon.a()).suggests(CompletionProviders.d).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntitySummon.a(commandcontext, "entity"), ((CommandListenerWrapper) commandcontext.getSource()).getPosition(), new NBTTagCompound(), true); - })).then(((RequiredArgumentBuilder) CommandDispatcher.a("pos", (ArgumentType) ArgumentVec3.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntitySummon.a(commandcontext, "entity"), ArgumentVec3.a(commandcontext, "pos"), new NBTTagCompound(), true); - })).then(CommandDispatcher.a("nbt", (ArgumentType) ArgumentNBTTag.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntitySummon.a(commandcontext, "entity"), ArgumentVec3.a(commandcontext, "pos"), ArgumentNBTTag.a(commandcontext, "nbt"), false); - }))))); - } - - private static int a(CommandListenerWrapper commandlistenerwrapper, MinecraftKey minecraftkey, Vec3D vec3d, NBTTagCompound nbttagcompound, boolean flag) throws CommandSyntaxException { - NBTTagCompound nbttagcompound1 = nbttagcompound.clone(); - - nbttagcompound1.setString("id", minecraftkey.toString()); - if (EntityTypes.getName(EntityTypes.LIGHTNING_BOLT).equals(minecraftkey)) { - EntityLightning entitylightning = new EntityLightning(commandlistenerwrapper.getWorld(), vec3d.x, vec3d.y, vec3d.z, false); - - commandlistenerwrapper.getWorld().strikeLightning(entitylightning, org.bukkit.event.weather.LightningStrikeEvent.Cause.COMMAND); // CraftBukkit - commandlistenerwrapper.sendMessage(new ChatMessage("commands.summon.success", new Object[]{entitylightning.getScoreboardDisplayName()}), true); - return 1; - } else { - WorldServer worldserver = commandlistenerwrapper.getWorld(); - Entity entity = EntityTypes.a(nbttagcompound1, worldserver, (entity1) -> { - entity1.setPositionRotation(vec3d.x, vec3d.y, vec3d.z, entity1.yaw, entity1.pitch); - return !worldserver.addEntitySerialized(entity1) ? null : entity1; - }); - - if (entity == null) { - throw CommandSummon.a.create(); - } else { - if (flag && entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(commandlistenerwrapper.getWorld(), commandlistenerwrapper.getWorld().getDamageScaler(new BlockPosition(entity)), EnumMobSpawn.COMMAND, (GroupDataEntity) null, (NBTTagCompound) null); - } - - commandlistenerwrapper.sendMessage(new ChatMessage("commands.summon.success", new Object[]{entity.getScoreboardDisplayName()}), true); - return 1; - } - } - } -} diff --git a/src/main/java/net/minecraft/server/CommandTeleport.java b/src/main/java/net/minecraft/server/CommandTeleport.java deleted file mode 100644 index a95775fe2..000000000 --- a/src/main/java/net/minecraft/server/CommandTeleport.java +++ /dev/null @@ -1,218 +0,0 @@ -package net.minecraft.server; - -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.builder.RequiredArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.tree.LiteralCommandNode; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Set; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.event.entity.EntityTeleportEvent; -// CraftBukkit end - -public class CommandTeleport { - - public static void a(com.mojang.brigadier.CommandDispatcher com_mojang_brigadier_commanddispatcher) { - LiteralCommandNode literalcommandnode = com_mojang_brigadier_commanddispatcher.register((LiteralArgumentBuilder) ((LiteralArgumentBuilder) ((LiteralArgumentBuilder) ((LiteralArgumentBuilder) CommandDispatcher.a("teleport").requires((commandlistenerwrapper) -> { - return commandlistenerwrapper.hasPermission(2); - })).then(((RequiredArgumentBuilder) CommandDispatcher.a("targets", (ArgumentType) ArgumentEntity.multipleEntities()).then(((RequiredArgumentBuilder) ((RequiredArgumentBuilder) CommandDispatcher.a("location", (ArgumentType) ArgumentVec3.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ((CommandListenerWrapper) commandcontext.getSource()).getWorld(), ArgumentVec3.b(commandcontext, "location"), (IVectorPosition) null, (CommandTeleport.a) null); - })).then(CommandDispatcher.a("rotation", (ArgumentType) ArgumentRotation.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ((CommandListenerWrapper) commandcontext.getSource()).getWorld(), ArgumentVec3.b(commandcontext, "location"), ArgumentRotation.a(commandcontext, "rotation"), (CommandTeleport.a) null); - }))).then(((LiteralArgumentBuilder) CommandDispatcher.a("facing").then(CommandDispatcher.a("entity").then(((RequiredArgumentBuilder) CommandDispatcher.a("facingEntity", (ArgumentType) ArgumentEntity.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ((CommandListenerWrapper) commandcontext.getSource()).getWorld(), ArgumentVec3.b(commandcontext, "location"), (IVectorPosition) null, new CommandTeleport.a(ArgumentEntity.a(commandcontext, "facingEntity"), ArgumentAnchor.Anchor.FEET)); - })).then(CommandDispatcher.a("facingAnchor", (ArgumentType) ArgumentAnchor.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ((CommandListenerWrapper) commandcontext.getSource()).getWorld(), ArgumentVec3.b(commandcontext, "location"), (IVectorPosition) null, new CommandTeleport.a(ArgumentEntity.a(commandcontext, "facingEntity"), ArgumentAnchor.a(commandcontext, "facingAnchor"))); - }))))).then(CommandDispatcher.a("facingLocation", (ArgumentType) ArgumentVec3.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ((CommandListenerWrapper) commandcontext.getSource()).getWorld(), ArgumentVec3.b(commandcontext, "location"), (IVectorPosition) null, new CommandTeleport.a(ArgumentVec3.a(commandcontext, "facingLocation"))); - }))))).then(CommandDispatcher.a("destination", (ArgumentType) ArgumentEntity.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentEntity.b(commandcontext, "targets"), ArgumentEntity.a(commandcontext, "destination")); - })))).then(CommandDispatcher.a("location", (ArgumentType) ArgumentVec3.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), Collections.singleton(((CommandListenerWrapper) commandcontext.getSource()).g()), ((CommandListenerWrapper) commandcontext.getSource()).getWorld(), ArgumentVec3.b(commandcontext, "location"), VectorPosition.d(), (CommandTeleport.a) null); - }))).then(CommandDispatcher.a("destination", (ArgumentType) ArgumentEntity.a()).executes((commandcontext) -> { - return a((CommandListenerWrapper) commandcontext.getSource(), Collections.singleton(((CommandListenerWrapper) commandcontext.getSource()).g()), ArgumentEntity.a(commandcontext, "destination")); - }))); - - com_mojang_brigadier_commanddispatcher.register((LiteralArgumentBuilder) ((LiteralArgumentBuilder) CommandDispatcher.a("tp").requires((commandlistenerwrapper) -> { - return commandlistenerwrapper.hasPermission(2); - })).redirect(literalcommandnode)); - } - - private static int a(CommandListenerWrapper commandlistenerwrapper, Collection collection, Entity entity) { - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - Entity entity1 = (Entity) iterator.next(); - - a(commandlistenerwrapper, entity1, (WorldServer) entity.world, entity.locX, entity.locY, entity.locZ, EnumSet.noneOf(PacketPlayOutPosition.EnumPlayerTeleportFlags.class), entity.yaw, entity.pitch, (CommandTeleport.a) null); - } - - if (collection.size() == 1) { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.teleport.success.entity.single", new Object[]{((Entity) collection.iterator().next()).getScoreboardDisplayName(), entity.getScoreboardDisplayName()}), true); - } else { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.teleport.success.entity.multiple", new Object[]{collection.size(), entity.getScoreboardDisplayName()}), true); - } - - return collection.size(); - } - - private static int a(CommandListenerWrapper commandlistenerwrapper, Collection collection, WorldServer worldserver, IVectorPosition ivectorposition, @Nullable IVectorPosition ivectorposition1, @Nullable CommandTeleport.a commandteleport_a) throws CommandSyntaxException { - Vec3D vec3d = ivectorposition.a(commandlistenerwrapper); - Vec2F vec2f = ivectorposition1 == null ? null : ivectorposition1.b(commandlistenerwrapper); - Set set = EnumSet.noneOf(PacketPlayOutPosition.EnumPlayerTeleportFlags.class); - - if (ivectorposition.a()) { - set.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.X); - } - - if (ivectorposition.b()) { - set.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y); - } - - if (ivectorposition.c()) { - set.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Z); - } - - if (ivectorposition1 == null) { - set.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.X_ROT); - set.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y_ROT); - } else { - if (ivectorposition1.a()) { - set.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.X_ROT); - } - - if (ivectorposition1.b()) { - set.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y_ROT); - } - } - - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (ivectorposition1 == null) { - a(commandlistenerwrapper, entity, worldserver, vec3d.x, vec3d.y, vec3d.z, set, entity.yaw, entity.pitch, commandteleport_a); - } else { - a(commandlistenerwrapper, entity, worldserver, vec3d.x, vec3d.y, vec3d.z, set, vec2f.j, vec2f.i, commandteleport_a); - } - } - - if (collection.size() == 1) { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.teleport.success.location.single", new Object[]{((Entity) collection.iterator().next()).getScoreboardDisplayName(), vec3d.x, vec3d.y, vec3d.z}), true); - } else { - commandlistenerwrapper.sendMessage(new ChatMessage("commands.teleport.success.location.multiple", new Object[]{collection.size(), vec3d.x, vec3d.y, vec3d.z}), true); - } - - return collection.size(); - } - - private static void a(CommandListenerWrapper commandlistenerwrapper, Entity entity, WorldServer worldserver, double d0, double d1, double d2, Set set, float f, float f1, @Nullable CommandTeleport.a commandteleport_a) { - if (entity instanceof EntityPlayer) { - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(new BlockPosition(d0, d1, d2)); - - worldserver.getChunkProvider().addTicket(TicketType.POST_TELEPORT, chunkcoordintpair, 1, entity.getId()); - entity.stopRiding(); - if (((EntityPlayer) entity).isSleeping()) { - ((EntityPlayer) entity).wakeup(true, true, false); - } - - if (worldserver == entity.world) { - ((EntityPlayer) entity).playerConnection.a(d0, d1, d2, f, f1, set, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.COMMAND); // CraftBukkit - } else { - ((EntityPlayer) entity).a(worldserver, d0, d1, d2, f, f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.COMMAND); // CraftBukkit - } - - entity.setHeadRotation(f); - } else { - float f2 = MathHelper.g(f); - float f3 = MathHelper.g(f1); - - f3 = MathHelper.a(f3, -90.0F, 90.0F); - // CraftBukkit start - Teleport event - Location to = new Location(worldserver.getWorld(), d0, d1, d2, f2, f3); - EntityTeleportEvent event = new EntityTeleportEvent(entity.getBukkitEntity(), entity.getBukkitEntity().getLocation(), to); - worldserver.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - - d0 = to.getX(); - d1 = to.getY(); - d2 = to.getZ(); - f2 = to.getYaw(); - f3 = to.getPitch(); - worldserver = ((CraftWorld) to.getWorld()).getHandle(); - // CraftBukkit end - if (worldserver == entity.world) { - entity.setPositionRotation(d0, d1, d2, f2, f3); - entity.setHeadRotation(f2); - } else { - entity.decouple(); - entity.dimension = worldserver.worldProvider.getDimensionManager(); - Entity entity1 = entity; - - entity = entity.getEntityType().a((World) worldserver); - if (entity == null) { - return; - } - - entity.v(entity1); - entity.setPositionRotation(d0, d1, d2, f2, f3); - entity.setHeadRotation(f2); - worldserver.addEntityTeleport(entity); - entity1.dead = true; - } - } - - if (commandteleport_a != null) { - commandteleport_a.a(commandlistenerwrapper, entity); - } - - if (!(entity instanceof EntityLiving) || !((EntityLiving) entity).isGliding()) { - entity.setMot(entity.getMot().d(1.0D, 0.0D, 1.0D)); - entity.onGround = true; - } - - } - - static class a { - - private final Vec3D a; - private final Entity b; - private final ArgumentAnchor.Anchor c; - - public a(Entity entity, ArgumentAnchor.Anchor argumentanchor_anchor) { - this.b = entity; - this.c = argumentanchor_anchor; - this.a = argumentanchor_anchor.a(entity); - } - - public a(Vec3D vec3d) { - this.b = null; - this.a = vec3d; - this.c = null; - } - - public void a(CommandListenerWrapper commandlistenerwrapper, Entity entity) { - if (this.b != null) { - if (entity instanceof EntityPlayer) { - ((EntityPlayer) entity).a(commandlistenerwrapper.k(), this.b, this.c); - } else { - entity.a(commandlistenerwrapper.k(), this.a); - } - } else { - entity.a(commandlistenerwrapper.k(), this.a); - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/Container.java b/src/main/java/net/minecraft/server/Container.java deleted file mode 100644 index b38cb8dd2..000000000 --- a/src/main/java/net/minecraft/server/Container.java +++ /dev/null @@ -1,699 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import javax.annotation.Nullable; - -// CraftBukkit start -import com.google.common.base.Preconditions; -import java.util.HashMap; -import java.util.Map; -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; -// CraftBukkit end - -public abstract class Container { - - public NonNullList items = NonNullList.a(); - public List slots = Lists.newArrayList(); - private final List d = Lists.newArrayList(); - @Nullable - private final Containers e; - public final int windowId; - private int dragType = -1; - private int h; - private final Set i = Sets.newHashSet(); - private final List listeners = Lists.newArrayList(); - private final Set k = Sets.newHashSet(); - - // 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); - } - private IChatBaseComponent title; - public final IChatBaseComponent getTitle() { - Preconditions.checkState(this.title != null, "Title not set"); - return this.title; - } - public final void setTitle(IChatBaseComponent title) { - Preconditions.checkState(this.title == null, "Title already set"); - this.title = title; - } - // CraftBukkit end - - protected Container(@Nullable Containers containers, int i) { - this.e = containers; - this.windowId = i; - } - - protected static boolean a(ContainerAccess containeraccess, EntityHuman entityhuman, Block block) { - return (Boolean) containeraccess.a((world, blockposition) -> { - return world.getType(blockposition).getBlock() != block ? false : entityhuman.e((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D) <= 64.0D; - }, true); - } - - public Containers getType() { - if (this.e == null) { - throw new UnsupportedOperationException("Unable to construct this menu by type"); - } else { - return this.e; - } - } - - protected static void a(IInventory iinventory, int i) { - int j = iinventory.getSize(); - - if (j < i) { - throw new IllegalArgumentException("Container size " + j + " is smaller than expected " + i); - } - } - - protected static void a(IContainerProperties icontainerproperties, int i) { - int j = icontainerproperties.a(); - - if (j < i) { - throw new IllegalArgumentException("Container data count " + j + " is smaller than expected " + i); - } - } - - protected Slot a(Slot slot) { - slot.rawSlotIndex = this.slots.size(); - this.slots.add(slot); - this.items.add(ItemStack.a); - return slot; - } - - protected ContainerProperty a(ContainerProperty containerproperty) { - this.d.add(containerproperty); - return containerproperty; - } - - protected void a(IContainerProperties icontainerproperties) { - for (int i = 0; i < icontainerproperties.a(); ++i) { - this.a(ContainerProperty.a(icontainerproperties, i)); - } - - } - - public void addSlotListener(ICrafting icrafting) { - if (!this.listeners.contains(icrafting)) { - this.listeners.add(icrafting); - icrafting.a(this, this.b()); - this.c(); - } - } - - public NonNullList b() { - NonNullList nonnulllist = NonNullList.a(); - - for (int i = 0; i < this.slots.size(); ++i) { - nonnulllist.add(((Slot) this.slots.get(i)).getItem()); - } - - return nonnulllist; - } - - public void c() { - int i; - - for (i = 0; i < this.slots.size(); ++i) { - ItemStack itemstack = ((Slot) this.slots.get(i)).getItem(); - ItemStack itemstack1 = (ItemStack) this.items.get(i); - - if (!ItemStack.matches(itemstack1, itemstack)) { - itemstack1 = itemstack.isEmpty() ? ItemStack.a : itemstack.cloneItemStack(); - this.items.set(i, itemstack1); - Iterator iterator = this.listeners.iterator(); - - while (iterator.hasNext()) { - ICrafting icrafting = (ICrafting) iterator.next(); - - icrafting.a(this, i, itemstack1); - } - } - } - - for (i = 0; i < this.d.size(); ++i) { - ContainerProperty containerproperty = (ContainerProperty) this.d.get(i); - - if (containerproperty.c()) { - Iterator iterator1 = this.listeners.iterator(); - - while (iterator1.hasNext()) { - ICrafting icrafting1 = (ICrafting) iterator1.next(); - - icrafting1.setContainerData(this, i, containerproperty.get()); - } - } - } - - } - - public boolean a(EntityHuman entityhuman, int i) { - return false; - } - - public Slot getSlot(int i) { - return (Slot) this.slots.get(i); - } - - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - Slot slot = (Slot) this.slots.get(i); - - return slot != null ? slot.getItem() : ItemStack.a; - } - - public ItemStack a(int i, int j, InventoryClickType inventoryclicktype, EntityHuman entityhuman) { - ItemStack itemstack = ItemStack.a; - PlayerInventory playerinventory = entityhuman.inventory; - ItemStack itemstack1; - ItemStack itemstack2; - int k; - int l; - - if (inventoryclicktype == InventoryClickType.QUICK_CRAFT) { - int i1 = this.h; - - this.h = c(j); - if ((i1 != 1 || this.h != 2) && i1 != this.h) { - this.d(); - } else if (playerinventory.getCarried().isEmpty()) { - this.d(); - } else if (this.h == 0) { - this.dragType = b(j); - if (a(this.dragType, entityhuman)) { - this.h = 1; - this.i.clear(); - } else { - this.d(); - } - } else if (this.h == 1) { - Slot slot = i < this.slots.size() ? this.slots.get(i) : null; // Paper - Ensure drag in bounds - - itemstack1 = playerinventory.getCarried(); - if (slot != null && a(slot, itemstack1, true) && slot.isAllowed(itemstack1) && (this.dragType == 2 || itemstack1.getCount() > this.i.size()) && this.b(slot)) { - this.i.add(slot); - } - } else if (this.h == 2) { - if (!this.i.isEmpty()) { - itemstack2 = playerinventory.getCarried().cloneItemStack(); - k = playerinventory.getCarried().getCount(); - Iterator iterator = this.i.iterator(); - - Map draggedSlots = new HashMap(); // CraftBukkit - Store slots from drag in map (raw slot id -> new stack) - while (iterator.hasNext()) { - Slot slot1 = (Slot) iterator.next(); - ItemStack itemstack3 = playerinventory.getCarried(); - - if (slot1 != null && a(slot1, itemstack3, true) && slot1.isAllowed(itemstack3) && (this.dragType == 2 || itemstack3.getCount() >= this.i.size()) && this.b(slot1)) { - ItemStack itemstack4 = itemstack2.cloneItemStack(); - int j1 = slot1.hasItem() ? slot1.getItem().getCount() : 0; - - a(this.i, this.dragType, itemstack4, j1); - l = Math.min(itemstack4.getMaxStackSize(), slot1.getMaxStackSize(itemstack4)); - if (itemstack4.getCount() > l) { - itemstack4.setCount(l); - } - - k -= itemstack4.getCount() - j1; - // slot1.set(itemstack4); - draggedSlots.put(slot1.rawSlotIndex, itemstack4); // CraftBukkit - Put in map instead of setting - } - } - - // CraftBukkit start - InventoryDragEvent - InventoryView view = getBukkitView(); - org.bukkit.inventory.ItemStack newcursor = CraftItemStack.asCraftMirror(itemstack2); - newcursor.setAmount(k); - 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 && entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).updateInventory(this); - } - // CraftBukkit end - } - - this.d(); - } else { - this.d(); - } - } else if (this.h != 0) { - this.d(); - } else { - Slot slot2; - int k1; - - if ((inventoryclicktype == InventoryClickType.PICKUP || inventoryclicktype == InventoryClickType.QUICK_MOVE) && (j == 0 || j == 1)) { - if (i == -999) { - if (!playerinventory.getCarried().isEmpty()) { - if (j == 0) { - // CraftBukkit start - ItemStack carried = playerinventory.getCarried(); - playerinventory.setCarried(ItemStack.a); - entityhuman.drop(carried, true); - // CraftBukkit start - } - - if (j == 1) { - entityhuman.drop(playerinventory.getCarried().cloneAndSubtract(1), true); - } - } - } else if (inventoryclicktype == InventoryClickType.QUICK_MOVE) { - if (i < 0) { - return ItemStack.a; - } - - slot2 = (Slot) this.slots.get(i); - if (slot2 == null || !slot2.isAllowed(entityhuman)) { - return ItemStack.a; - } - - for (itemstack2 = this.shiftClick(entityhuman, i); !itemstack2.isEmpty() && ItemStack.c(slot2.getItem(), itemstack2); itemstack2 = this.shiftClick(entityhuman, i)) { - itemstack = itemstack2.cloneItemStack(); - } - } else { - if (i < 0) { - return ItemStack.a; - } - - slot2 = (Slot) this.slots.get(i); - if (slot2 != null) { - itemstack2 = slot2.getItem(); - itemstack1 = playerinventory.getCarried(); - if (!itemstack2.isEmpty()) { - itemstack = itemstack2.cloneItemStack(); - } - - if (itemstack2.isEmpty()) { - if (!itemstack1.isEmpty() && slot2.isAllowed(itemstack1)) { - k1 = j == 0 ? itemstack1.getCount() : 1; - if (k1 > slot2.getMaxStackSize(itemstack1)) { - k1 = slot2.getMaxStackSize(itemstack1); - } - - slot2.set(itemstack1.cloneAndSubtract(k1)); - } - } else if (slot2.isAllowed(entityhuman)) { - if (itemstack1.isEmpty()) { - if (itemstack2.isEmpty()) { - slot2.set(ItemStack.a); - playerinventory.setCarried(ItemStack.a); - } else { - k1 = j == 0 ? itemstack2.getCount() : (itemstack2.getCount() + 1) / 2; - playerinventory.setCarried(slot2.a(k1)); - if (itemstack2.isEmpty()) { - slot2.set(ItemStack.a); - } - - slot2.a(entityhuman, playerinventory.getCarried()); - } - } else if (slot2.isAllowed(itemstack1)) { - if (a(itemstack2, itemstack1)) { - k1 = j == 0 ? itemstack1.getCount() : 1; - if (k1 > slot2.getMaxStackSize(itemstack1) - itemstack2.getCount()) { - k1 = slot2.getMaxStackSize(itemstack1) - itemstack2.getCount(); - } - - if (k1 > itemstack1.getMaxStackSize() - itemstack2.getCount()) { - k1 = itemstack1.getMaxStackSize() - itemstack2.getCount(); - } - - itemstack1.subtract(k1); - itemstack2.add(k1); - } else if (itemstack1.getCount() <= slot2.getMaxStackSize(itemstack1)) { - slot2.set(itemstack1); - playerinventory.setCarried(itemstack2); - } - } else if (itemstack1.getMaxStackSize() > 1 && a(itemstack2, itemstack1) && !itemstack2.isEmpty()) { - k1 = itemstack2.getCount(); - if (k1 + itemstack1.getCount() <= itemstack1.getMaxStackSize()) { - itemstack1.add(k1); - itemstack2 = slot2.a(k1); - if (itemstack2.isEmpty()) { - slot2.set(ItemStack.a); - } - - slot2.a(entityhuman, playerinventory.getCarried()); - } - } - } - - slot2.d(); - // CraftBukkit start - Make sure the client has the right slot contents - if (entityhuman instanceof EntityPlayer && slot2.getMaxStackSize() != 64) { - ((EntityPlayer) entityhuman).playerConnection.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) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutSetSlot(this.windowId, 0, this.getSlot(0).getItem())); - } - } - // CraftBukkit end - } - } - } else if (inventoryclicktype == InventoryClickType.SWAP && j >= 0 && j < 9) { - slot2 = (Slot) this.slots.get(i); - itemstack2 = playerinventory.getItem(j); - itemstack1 = slot2.getItem(); - if (!itemstack2.isEmpty() || !itemstack1.isEmpty()) { - if (itemstack2.isEmpty()) { - if (slot2.isAllowed(entityhuman)) { - playerinventory.setItem(j, itemstack1); - slot2.b(itemstack1.getCount()); - slot2.set(ItemStack.a); - slot2.a(entityhuman, itemstack1); - } - } else if (itemstack1.isEmpty()) { - if (slot2.isAllowed(itemstack2)) { - k1 = slot2.getMaxStackSize(itemstack2); - if (itemstack2.getCount() > k1) { - slot2.set(itemstack2.cloneAndSubtract(k1)); - } else { - slot2.set(itemstack2); - playerinventory.setItem(j, ItemStack.a); - } - } - } else if (slot2.isAllowed(entityhuman) && slot2.isAllowed(itemstack2)) { - k1 = slot2.getMaxStackSize(itemstack2); - if (itemstack2.getCount() > k1) { - slot2.set(itemstack2.cloneAndSubtract(k1)); - slot2.a(entityhuman, itemstack1); - if (!playerinventory.pickup(itemstack1)) { - entityhuman.drop(itemstack1, true); - } - } else { - slot2.set(itemstack2); - playerinventory.setItem(j, itemstack1); - slot2.a(entityhuman, itemstack1); - } - } - } - } else if (inventoryclicktype == InventoryClickType.CLONE && entityhuman.abilities.canInstantlyBuild && playerinventory.getCarried().isEmpty() && i >= 0) { - slot2 = (Slot) this.slots.get(i); - if (slot2 != null && slot2.hasItem()) { - itemstack2 = slot2.getItem().cloneItemStack(); - itemstack2.setCount(itemstack2.getMaxStackSize()); - playerinventory.setCarried(itemstack2); - } - } else if (inventoryclicktype == InventoryClickType.THROW && playerinventory.getCarried().isEmpty() && i >= 0) { - slot2 = (Slot) this.slots.get(i); - if (slot2 != null && slot2.hasItem() && slot2.isAllowed(entityhuman)) { - itemstack2 = slot2.a(j == 0 ? 1 : slot2.getItem().getCount()); - slot2.a(entityhuman, itemstack2); - entityhuman.drop(itemstack2, true); - } - } else if (inventoryclicktype == InventoryClickType.PICKUP_ALL && i >= 0) { - slot2 = (Slot) this.slots.get(i); - itemstack2 = playerinventory.getCarried(); - if (!itemstack2.isEmpty() && (slot2 == null || !slot2.hasItem() || !slot2.isAllowed(entityhuman))) { - k = j == 0 ? 0 : this.slots.size() - 1; - k1 = j == 0 ? 1 : -1; - - for (int l1 = 0; l1 < 2; ++l1) { - for (int i2 = k; i2 >= 0 && i2 < this.slots.size() && itemstack2.getCount() < itemstack2.getMaxStackSize(); i2 += k1) { - Slot slot3 = (Slot) this.slots.get(i2); - - if (slot3.hasItem() && a(slot3, itemstack2, true) && slot3.isAllowed(entityhuman) && this.a(itemstack2, slot3)) { - ItemStack itemstack5 = slot3.getItem(); - - if (l1 != 0 || itemstack5.getCount() != itemstack5.getMaxStackSize()) { - l = Math.min(itemstack2.getMaxStackSize() - itemstack2.getCount(), itemstack5.getCount()); - ItemStack itemstack6 = slot3.a(l); - - itemstack2.add(l); - if (itemstack6.isEmpty()) { - slot3.set(ItemStack.a); - } - - slot3.a(entityhuman, itemstack6); - } - } - } - } - } - - this.c(); - } - } - - return itemstack; - } - - public static boolean a(ItemStack itemstack, ItemStack itemstack1) { - return itemstack.getItem() == itemstack1.getItem() && ItemStack.equals(itemstack, itemstack1); - } - - public boolean a(ItemStack itemstack, Slot slot) { - return true; - } - - public void b(EntityHuman entityhuman) { - PlayerInventory playerinventory = entityhuman.inventory; - - if (!playerinventory.getCarried().isEmpty()) { - // CraftBukkit start - SPIGOT-4556 - ItemStack carried = playerinventory.getCarried(); - playerinventory.setCarried(ItemStack.a); - entityhuman.drop(carried, false); - // CraftBukkit end - } - - } - - protected void a(EntityHuman entityhuman, World world, IInventory iinventory) { - int i; - - if (entityhuman.isAlive() && (!(entityhuman instanceof EntityPlayer) || !((EntityPlayer) entityhuman).o())) { - for (i = 0; i < iinventory.getSize(); ++i) { - entityhuman.inventory.a(world, iinventory.splitWithoutUpdate(i)); - } - - } else { - for (i = 0; i < iinventory.getSize(); ++i) { - entityhuman.drop(iinventory.splitWithoutUpdate(i), false); - } - - } - } - - public void a(IInventory iinventory) { - this.c(); - } - - public void setItem(int i, ItemStack itemstack) { - this.getSlot(i).set(itemstack); - } - - public void a(int i, int j) { - ((ContainerProperty) this.d.get(i)).set(j); - } - - public boolean c(EntityHuman entityhuman) { - return !this.k.contains(entityhuman); - } - - public void a(EntityHuman entityhuman, boolean flag) { - if (flag) { - this.k.remove(entityhuman); - } else { - this.k.add(entityhuman); - } - - } - - public abstract boolean canUse(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.isEmpty()) { - if (flag) { - if (k < i) { - break; - } - } else if (k >= j) { - break; - } - - slot = (Slot) this.slots.get(k); - itemstack1 = slot.getItem(); - if (!itemstack1.isEmpty() && a(itemstack, itemstack1)) { - int l = itemstack1.getCount() + itemstack.getCount(); - - if (l <= itemstack.getMaxStackSize()) { - itemstack.setCount(0); - itemstack1.setCount(l); - slot.d(); - flag1 = true; - } else if (itemstack1.getCount() < itemstack.getMaxStackSize()) { - itemstack.subtract(itemstack.getMaxStackSize() - itemstack1.getCount()); - itemstack1.setCount(itemstack.getMaxStackSize()); - slot.d(); - flag1 = true; - } - } - - if (flag) { - --k; - } else { - ++k; - } - } - } - - if (!itemstack.isEmpty()) { - if (flag) { - k = j - 1; - } else { - k = i; - } - - while (true) { - if (flag) { - if (k < i) { - break; - } - } else if (k >= j) { - break; - } - - slot = (Slot) this.slots.get(k); - itemstack1 = slot.getItem(); - if (itemstack1.isEmpty() && slot.isAllowed(itemstack)) { - if (itemstack.getCount() > slot.getMaxStackSize()) { - slot.set(itemstack.cloneAndSubtract(slot.getMaxStackSize())); - } else { - slot.set(itemstack.cloneAndSubtract(itemstack.getCount())); - } - - slot.d(); - 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 ? true : (i == 1 ? true : i == 2 && entityhuman.abilities.canInstantlyBuild); - } - - protected void d() { - this.h = 0; - this.i.clear(); - } - - public static boolean a(@Nullable Slot slot, ItemStack itemstack, boolean flag) { - boolean flag1 = slot == null || !slot.hasItem(); - - return !flag1 && itemstack.doMaterialsMatch(slot.getItem()) && ItemStack.equals(slot.getItem(), itemstack) ? slot.getItem().getCount() + (flag ? 0 : itemstack.getCount()) <= itemstack.getMaxStackSize() : flag1; - } - - public static void a(Set set, int i, ItemStack itemstack, int j) { - switch (i) { - case 0: - itemstack.setCount(MathHelper.d((float) itemstack.getCount() / (float) set.size())); - break; - case 1: - itemstack.setCount(1); - break; - case 2: - itemstack.setCount(itemstack.getItem().getMaxStackSize()); - } - - itemstack.add(j); - } - - public boolean b(Slot slot) { - return true; - } - - public static int a(@Nullable TileEntity tileentity) { - return tileentity instanceof IInventory ? b((IInventory) tileentity) : 0; - } - - public static int b(@Nullable 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.isEmpty()) { - f += (float) itemstack.getCount() / (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/src/main/java/net/minecraft/server/ContainerAccess.java b/src/main/java/net/minecraft/server/ContainerAccess.java deleted file mode 100644 index 6ba10d61a..000000000 --- a/src/main/java/net/minecraft/server/ContainerAccess.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.minecraft.server; - -import java.util.Optional; -import java.util.function.BiConsumer; -import java.util.function.BiFunction; - -public interface ContainerAccess { - - // CraftBukkit start - default World getWorld() { - throw new UnsupportedOperationException("Not supported yet."); - } - - default BlockPosition getPosition() { - throw new UnsupportedOperationException("Not supported yet."); - } - - default org.bukkit.Location getLocation() { - return new org.bukkit.Location(getWorld().getWorld(), getPosition().getX(), getPosition().getY(), getPosition().getZ()); - } - // CraftBukkit end - - ContainerAccess a = new ContainerAccess() { - @Override - public Optional a(BiFunction bifunction) { - return Optional.empty(); - } - }; - - static ContainerAccess at(final World world, final BlockPosition blockposition) { - return new ContainerAccess() { - // CraftBukkit start - @Override - public World getWorld() { - return world; - } - - @Override - public BlockPosition getPosition() { - return blockposition; - } - // CraftBukkit end - - @Override - public Optional a(BiFunction bifunction) { - return Optional.of(bifunction.apply(world, blockposition)); - } - }; - } - - Optional a(BiFunction bifunction); - - default T a(BiFunction bifunction, T t0) { - return this.a(bifunction).orElse(t0); - } - - default void a(BiConsumer biconsumer) { - this.a((world, blockposition) -> { - biconsumer.accept(world, blockposition); - return Optional.empty(); - }); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerAnvil.java b/src/main/java/net/minecraft/server/ContainerAnvil.java deleted file mode 100644 index 7718c5a3b..000000000 --- a/src/main/java/net/minecraft/server/ContainerAnvil.java +++ /dev/null @@ -1,409 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -// CraftBukkit end - -public class ContainerAnvil extends Container { - - private static final Logger LOGGER = LogManager.getLogger(); - private final IInventory resultInventory; - private final IInventory repairInventory; - public final ContainerProperty levelCost; - private final ContainerAccess containerAccess; - private int h; - public String renameText; - private final EntityHuman player; - // CraftBukkit start - public int maximumRepairCost = 40; - private int lastLevelCost; - private CraftInventoryView bukkitEntity; - private PlayerInventory playerInventory; - // CraftBukkit end - - public ContainerAnvil(int i, PlayerInventory playerinventory) { - this(i, playerinventory, ContainerAccess.a); - } - - public ContainerAnvil(int i, PlayerInventory playerinventory, final ContainerAccess containeraccess) { - super(Containers.ANVIL, i); - this.playerInventory = playerinventory; // CraftBukkit - this.resultInventory = new InventoryCraftResult(); - this.repairInventory = new InventorySubcontainer(2) { - @Override - public void update() { - super.update(); - ContainerAnvil.this.a((IInventory) this); - } - }; - this.levelCost = ContainerProperty.a(); - this.containerAccess = containeraccess; - this.player = playerinventory.player; - this.a(this.levelCost); - this.a(new Slot(this.repairInventory, 0, 27, 47)); - this.a(new Slot(this.repairInventory, 1, 76, 47)); - this.a(new Slot(this.resultInventory, 2, 134, 47) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return false; - } - - @Override - public boolean isAllowed(EntityHuman entityhuman) { - return (entityhuman.abilities.canInstantlyBuild || entityhuman.expLevel >= ContainerAnvil.this.levelCost.get()) && ContainerAnvil.this.levelCost.get() > 0 && this.hasItem(); - } - - @Override - public ItemStack a(EntityHuman entityhuman, ItemStack itemstack) { - if (!entityhuman.abilities.canInstantlyBuild) { - entityhuman.levelDown(-ContainerAnvil.this.levelCost.get()); - } - - ContainerAnvil.this.repairInventory.setItem(0, ItemStack.a); - if (ContainerAnvil.this.h > 0) { - ItemStack itemstack1 = ContainerAnvil.this.repairInventory.getItem(1); - - if (!itemstack1.isEmpty() && itemstack1.getCount() > ContainerAnvil.this.h) { - itemstack1.subtract(ContainerAnvil.this.h); - ContainerAnvil.this.repairInventory.setItem(1, itemstack1); - } else { - ContainerAnvil.this.repairInventory.setItem(1, ItemStack.a); - } - } else { - ContainerAnvil.this.repairInventory.setItem(1, ItemStack.a); - } - - ContainerAnvil.this.levelCost.set(0); - containeraccess.a((world, blockposition) -> { - IBlockData iblockdata = world.getType(blockposition); - - if (!entityhuman.abilities.canInstantlyBuild && iblockdata.a(TagsBlock.ANVIL) && entityhuman.getRandom().nextFloat() < 0.12F) { - IBlockData iblockdata1 = BlockAnvil.a_(iblockdata); - // Paper start - com.destroystokyo.paper.event.block.AnvilDamagedEvent event = new com.destroystokyo.paper.event.block.AnvilDamagedEvent(getBukkitView(), iblockdata1 != null ? org.bukkit.craftbukkit.block.data.CraftBlockData.fromData(iblockdata1) : null); - if (!event.callEvent()) { - return; - } else if (event.getDamageState() == com.destroystokyo.paper.event.block.AnvilDamagedEvent.DamageState.BROKEN) { - iblockdata1 = null; - } else { - iblockdata1 = ((org.bukkit.craftbukkit.block.data.CraftBlockData) event.getDamageState().getMaterial().createBlockData()).getState().set(BlockAnvil.FACING, iblockdata.get(BlockAnvil.FACING)); - } - // Paper end - - if (iblockdata1 == null) { - world.a(blockposition, false); - world.triggerEffect(1029, blockposition, 0); - } else { - world.setTypeAndData(blockposition, iblockdata1, 2); - world.triggerEffect(1030, blockposition, 0); - } - } else { - world.triggerEffect(1030, blockposition, 0); - } - - }); - return itemstack; - } - }); - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - } - - @Override - public void a(IInventory iinventory) { - super.a(iinventory); - if (iinventory == this.repairInventory) { - this.e(); - } - - } - - public void e() { - ItemStack itemstack = this.repairInventory.getItem(0); - - this.levelCost.set(1); - int i = 0; - byte b0 = 0; - byte b1 = 0; - - if (itemstack.isEmpty()) { - org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), ItemStack.a); // CraftBukkit - this.levelCost.set(0); - } else { - ItemStack itemstack1 = itemstack.cloneItemStack(); - ItemStack itemstack2 = this.repairInventory.getItem(1); - Map map = EnchantmentManager.a(itemstack1); - int j = b0 + itemstack.getRepairCost() + (itemstack2.isEmpty() ? 0 : itemstack2.getRepairCost()); - - this.h = 0; - if (!itemstack2.isEmpty()) { - boolean flag = itemstack2.getItem() == Items.ENCHANTED_BOOK && !ItemEnchantedBook.e(itemstack2).isEmpty(); - int k; - int l; - int i1; - - if (itemstack1.e() && itemstack1.getItem().a(itemstack, itemstack2)) { - k = Math.min(itemstack1.getDamage(), itemstack1.h() / 4); - if (k <= 0) { - org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), ItemStack.a); // CraftBukkit - this.levelCost.set(0); - return; - } - - for (i1 = 0; k > 0 && i1 < itemstack2.getCount(); ++i1) { - l = itemstack1.getDamage() - k; - itemstack1.setDamage(l); - ++i; - k = Math.min(itemstack1.getDamage(), itemstack1.h() / 4); - } - - this.h = i1; - } else { - if (!flag && (itemstack1.getItem() != itemstack2.getItem() || !itemstack1.e())) { - org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), ItemStack.a); // CraftBukkit - this.levelCost.set(0); - return; - } - - if (itemstack1.e() && !flag) { - k = itemstack.h() - itemstack.getDamage(); - i1 = itemstack2.h() - itemstack2.getDamage(); - l = i1 + itemstack1.h() * 12 / 100; - int j1 = k + l; - int k1 = itemstack1.h() - j1; - - if (k1 < 0) { - k1 = 0; - } - - if (k1 < itemstack1.getDamage()) { - itemstack1.setDamage(k1); - i += 2; - } - } - - Map map1 = EnchantmentManager.a(itemstack2); - boolean flag1 = false; - boolean flag2 = false; - Iterator iterator = map1.keySet().iterator(); - - while (iterator.hasNext()) { - Enchantment enchantment = (Enchantment) iterator.next(); - - if (enchantment != null) { - int l1 = map.containsKey(enchantment) ? (Integer) map.get(enchantment) : 0; - int i2 = (Integer) map1.get(enchantment); - - i2 = l1 == i2 ? i2 + 1 : Math.max(i2, l1); - boolean flag3 = enchantment.canEnchant(itemstack); - - if (this.player.abilities.canInstantlyBuild || itemstack.getItem() == Items.ENCHANTED_BOOK) { - flag3 = true; - } - - Iterator iterator1 = map.keySet().iterator(); - - while (iterator1.hasNext()) { - Enchantment enchantment1 = (Enchantment) iterator1.next(); - - if (enchantment1 != enchantment && !enchantment.isCompatible(enchantment1)) { - flag3 = false; - ++i; - } - } - - if (!flag3) { - flag2 = true; - } else { - flag1 = true; - if (i2 > enchantment.getMaxLevel()) { - i2 = enchantment.getMaxLevel(); - } - - map.put(enchantment, i2); - int j2 = 0; - - switch (enchantment.d()) { - case COMMON: - j2 = 1; - break; - case UNCOMMON: - j2 = 2; - break; - case RARE: - j2 = 4; - break; - case VERY_RARE: - j2 = 8; - } - - if (flag) { - j2 = Math.max(1, j2 / 2); - } - - i += j2 * i2; - if (itemstack.getCount() > 1) { - i = 40; - } - } - } - } - - if (flag2 && !flag1) { - org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), ItemStack.a); // CraftBukkit - this.levelCost.set(0); - return; - } - } - } - - if (StringUtils.isBlank(this.renameText)) { - if (itemstack.hasName()) { - b1 = 1; - i += b1; - itemstack1.s(); - } - } else if (!this.renameText.equals(itemstack.getName().getString())) { - b1 = 1; - i += b1; - itemstack1.a((IChatBaseComponent) (new ChatComponentText(this.renameText))); - } - - this.levelCost.set(j + i); - if (i <= 0) { - itemstack1 = ItemStack.a; - } - - if (b1 == i && b1 > 0 && this.levelCost.get() >= maximumRepairCost) { // CraftBukkit - this.levelCost.set(maximumRepairCost - 1); // CraftBukkit - } - - if (this.levelCost.get() >= maximumRepairCost && !this.player.abilities.canInstantlyBuild) { // CraftBukkit - itemstack1 = ItemStack.a; - } - - if (!itemstack1.isEmpty()) { - int k2 = itemstack1.getRepairCost(); - - if (!itemstack2.isEmpty() && k2 < itemstack2.getRepairCost()) { - k2 = itemstack2.getRepairCost(); - } - - if (b1 != i || b1 == 0) { - k2 = d(k2); - } - - itemstack1.setRepairCost(k2); - EnchantmentManager.a(map, itemstack1); - } - - org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), itemstack1); // CraftBukkit - this.c(); - } - } - - public static int d(int i) { - return i * 2 + 1; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.containerAccess.a((world, blockposition) -> { - this.a(entityhuman, world, this.repairInventory); - }); - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return (Boolean) this.containerAccess.a((world, blockposition) -> { - return !world.getType(blockposition).a(TagsBlock.ANVIL) ? false : entityhuman.e((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D) <= 64.0D; - }, true); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.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 ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } else if (i != 0 && i != 1) { - if (i >= 3 && i < 39 && !this.a(itemstack1, 0, 2, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 3, 39, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - } - - return itemstack; - } - - public void a(String s) { - this.renameText = s; - if (this.getSlot(2).hasItem()) { - ItemStack itemstack = this.getSlot(2).getItem(); - - if (StringUtils.isBlank(s)) { - itemstack.s(); - } else { - itemstack.a((IChatBaseComponent) (new ChatComponentText(this.renameText))); - } - } - - 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( - containerAccess.getLocation(), this.repairInventory, this.resultInventory, this); - bukkitEntity = new CraftInventoryView(this.player.getBukkitEntity(), inventory, this); - return bukkitEntity; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/ContainerBeacon.java b/src/main/java/net/minecraft/server/ContainerBeacon.java deleted file mode 100644 index 436c74489..000000000 --- a/src/main/java/net/minecraft/server/ContainerBeacon.java +++ /dev/null @@ -1,169 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.craftbukkit.inventory.CraftInventoryView; // CraftBukkit - -public class ContainerBeacon extends Container { - - private final IInventory beacon; - private final ContainerBeacon.SlotBeacon d; - private final ContainerAccess containerAccess; - private final IContainerProperties containerProperties; - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private PlayerInventory player; - // CraftBukkit end - - public ContainerBeacon(int i, IInventory iinventory) { - this(i, iinventory, new ContainerProperties(3), ContainerAccess.a); - } - - public ContainerBeacon(int i, IInventory iinventory, IContainerProperties icontainerproperties, ContainerAccess containeraccess) { - super(Containers.BEACON, i); - player = (PlayerInventory) iinventory; // CraftBukkit - TODO: check this - this.beacon = new InventorySubcontainer(1) { - @Override - public boolean b(int j, ItemStack itemstack) { - return itemstack.getItem() == Items.EMERALD || itemstack.getItem() == Items.DIAMOND || itemstack.getItem() == Items.GOLD_INGOT || itemstack.getItem() == Items.IRON_INGOT; - } - - @Override - public int getMaxStackSize() { - return 1; - } - }; - a(icontainerproperties, 3); - this.containerProperties = icontainerproperties; - this.containerAccess = containeraccess; - this.d = new ContainerBeacon.SlotBeacon(this.beacon, 0, 136, 110); - this.a((Slot) this.d); - this.a(icontainerproperties); - boolean flag = true; - boolean flag1 = true; - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(iinventory, k + j * 9 + 9, 36 + k * 18, 137 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(iinventory, j, 36 + j * 18, 195)); - } - - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - if (!entityhuman.world.isClientSide) { - ItemStack itemstack = this.d.a(this.d.getMaxStackSize()); - - if (!itemstack.isEmpty()) { - entityhuman.drop(itemstack, false); - } - - } - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return a(this.containerAccess, entityhuman, Blocks.BEACON); - } - - @Override - public void a(int i, int j) { - super.a(i, j); - this.c(); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.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 ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } else if (!this.d.hasItem() && this.d.isAllowed(itemstack1) && itemstack1.getCount() == 1) { - if (!this.a(itemstack1, 0, 1, false)) { - return ItemStack.a; - } - } else if (i >= 1 && i < 28) { - if (!this.a(itemstack1, 28, 37, false)) { - return ItemStack.a; - } - } else if (i >= 28 && i < 37) { - if (!this.a(itemstack1, 1, 28, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 1, 37, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - } - - return itemstack; - } - - public void c(int i, int j) { - if (this.d.hasItem()) { - this.containerProperties.setProperty(1, i); - this.containerProperties.setProperty(2, j); - this.d.a(1); - } - - } - - class SlotBeacon extends Slot { - - public SlotBeacon(IInventory iinventory, int i, int j, int k) { - super(iinventory, i, j, k); - } - - @Override - public boolean isAllowed(ItemStack itemstack) { - Item item = itemstack.getItem(); - - return item == Items.EMERALD || item == Items.DIAMOND || item == Items.GOLD_INGOT || item == Items.IRON_INGOT; - } - - @Override - 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(this.beacon); - bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); - return bukkitEntity; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/ContainerBrewingStand.java b/src/main/java/net/minecraft/server/ContainerBrewingStand.java deleted file mode 100644 index 647502efc..000000000 --- a/src/main/java/net/minecraft/server/ContainerBrewingStand.java +++ /dev/null @@ -1,199 +0,0 @@ -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 IContainerProperties d; - private final Slot e; - - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private PlayerInventory player; - // CraftBukkit end - - public ContainerBrewingStand(int i, PlayerInventory playerinventory) { - this(i, playerinventory, new InventorySubcontainer(5), new ContainerProperties(2)); - } - - public ContainerBrewingStand(int i, PlayerInventory playerinventory, IInventory iinventory, IContainerProperties icontainerproperties) { - super(Containers.BREWING_STAND, i); - player = playerinventory; // CraftBukkit - a(iinventory, 5); - a(icontainerproperties, 2); - this.brewingStand = iinventory; - this.d = icontainerproperties; - this.a((Slot) (new ContainerBrewingStand.SlotPotionBottle(iinventory, 0, 56, 51))); - this.a((Slot) (new ContainerBrewingStand.SlotPotionBottle(iinventory, 1, 79, 58))); - this.a((Slot) (new ContainerBrewingStand.SlotPotionBottle(iinventory, 2, 102, 51))); - this.e = this.a((Slot) (new ContainerBrewingStand.SlotBrewing(iinventory, 3, 79, 17))); - this.a((Slot) (new ContainerBrewingStand.a(iinventory, 4, 17, 17))); - this.a(icontainerproperties); - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return this.brewingStand.a(entityhuman); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - - itemstack = itemstack1.cloneItemStack(); - if ((i < 0 || i > 2) && i != 3 && i != 4) { - if (this.e.isAllowed(itemstack1)) { - if (!this.a(itemstack1, 3, 4, false)) { - return ItemStack.a; - } - } else if (ContainerBrewingStand.SlotPotionBottle.b_(itemstack) && itemstack.getCount() == 1) { - if (!this.a(itemstack1, 0, 3, false)) { - return ItemStack.a; - } - } else if (ContainerBrewingStand.a.a_(itemstack)) { - if (!this.a(itemstack1, 4, 5, false)) { - return ItemStack.a; - } - } else if (i >= 5 && i < 32) { - if (!this.a(itemstack1, 32, 41, false)) { - return ItemStack.a; - } - } else if (i >= 32 && i < 41) { - if (!this.a(itemstack1, 5, 32, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 5, 41, false)) { - return ItemStack.a; - } - } else { - if (!this.a(itemstack1, 5, 41, true)) { - return ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - } - - return itemstack; - } - - static class a extends Slot { - - public a(IInventory iinventory, int i, int j, int k) { - super(iinventory, i, j, k); - } - - @Override - public boolean isAllowed(ItemStack itemstack) { - return a_(itemstack); - } - - public static boolean a_(ItemStack itemstack) { - return itemstack.getItem() == Items.BLAZE_POWDER; - } - - @Override - public int getMaxStackSize() { - return 64; - } - } - - static class SlotBrewing extends Slot { - - public SlotBrewing(IInventory iinventory, int i, int j, int k) { - super(iinventory, i, j, k); - } - - @Override - public boolean isAllowed(ItemStack itemstack) { - return PotionBrewer.a(itemstack); - } - - @Override - public int getMaxStackSize() { - return 64; - } - } - - static class SlotPotionBottle extends Slot { - - public SlotPotionBottle(IInventory iinventory, int i, int j, int k) { - super(iinventory, i, j, k); - } - - @Override - public boolean isAllowed(ItemStack itemstack) { - return b_(itemstack); - } - - @Override - public int getMaxStackSize() { - return 1; - } - - @Override - public ItemStack a(EntityHuman entityhuman, ItemStack itemstack) { - PotionRegistry potionregistry = PotionUtil.d(itemstack); - - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.k.a((EntityPlayer) entityhuman, potionregistry); - } - - super.a(entityhuman, itemstack); - return itemstack; - } - - public static boolean b_(ItemStack itemstack) { - Item item = itemstack.getItem(); - - return item == Items.POTION || item == Items.SPLASH_POTION || item == Items.LINGERING_POTION || item == Items.GLASS_BOTTLE; - } - } - - // CraftBukkit start - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - CraftInventoryBrewer inventory = new CraftInventoryBrewer(this.brewingStand); - bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); - return bukkitEntity; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/ContainerCartography.java b/src/main/java/net/minecraft/server/ContainerCartography.java deleted file mode 100644 index 1806c76ed..000000000 --- a/src/main/java/net/minecraft/server/ContainerCartography.java +++ /dev/null @@ -1,272 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.craftbukkit.inventory.CraftInventoryCartography; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -import org.bukkit.entity.Player; -// CraftBukkit end - -public class ContainerCartography extends Container { - - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private Player player; - - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - CraftInventoryCartography inventory = new CraftInventoryCartography(this.inventory, this.resultInventory); - bukkitEntity = new CraftInventoryView(this.player, inventory, this); - return bukkitEntity; - } - // CraftBukkit end - private final ContainerAccess containerAccess; - private boolean e; - public final IInventory inventory; - private final InventoryCraftResult resultInventory; - - public ContainerCartography(int i, PlayerInventory playerinventory) { - this(i, playerinventory, ContainerAccess.a); - } - - public ContainerCartography(int i, PlayerInventory playerinventory, final ContainerAccess containeraccess) { - super(Containers.CARTOGRAPHY, i); - this.inventory = new InventorySubcontainer(2) { - @Override - public void update() { - ContainerCartography.this.a((IInventory) this); - super.update(); - } - }; - this.resultInventory = new InventoryCraftResult() { - @Override - public void update() { - ContainerCartography.this.a((IInventory) this); - super.update(); - } - - // CraftBukkit start - @Override - public Location getLocation() { - return containeraccess.getLocation(); - } - // CraftBukkit end - }; - this.containerAccess = containeraccess; - this.a(new Slot(this.inventory, 0, 15, 15) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return itemstack.getItem() == Items.FILLED_MAP; - } - }); - this.a(new Slot(this.inventory, 1, 15, 52) { - @Override - public boolean isAllowed(ItemStack itemstack) { - Item item = itemstack.getItem(); - - return item == Items.PAPER || item == Items.MAP || item == Items.df; - } - }); - this.a(new Slot(this.resultInventory, 2, 145, 39) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return false; - } - - @Override - public ItemStack a(int j) { - ItemStack itemstack = super.a(j); - ItemStack itemstack1 = (ItemStack) containeraccess.a((world, blockposition) -> { - if (!ContainerCartography.this.e && ContainerCartography.this.inventory.getItem(1).getItem() == Items.df) { - ItemStack itemstack2 = ItemWorldMap.b(world, ContainerCartography.this.inventory.getItem(0)); - - if (itemstack2 != null) { - itemstack2.setCount(1); - return itemstack2; - } - } - - return itemstack; - }).orElse(itemstack); - - ContainerCartography.this.inventory.splitStack(0, 1); - ContainerCartography.this.inventory.splitStack(1, 1); - return itemstack1; - } - - @Override - protected void a(ItemStack itemstack, int j) { - this.a(j); - super.a(itemstack, j); - } - - @Override - public ItemStack a(EntityHuman entityhuman, ItemStack itemstack) { - itemstack.getItem().b(itemstack, entityhuman.world, entityhuman); - containeraccess.a((world, blockposition) -> { - world.playSound((EntityHuman) null, blockposition, SoundEffects.UI_CARTOGRAPHY_TABLE_TAKE_RESULT, SoundCategory.BLOCKS, 1.0F, 1.0F); - }); - return super.a(entityhuman, itemstack); - } - }); - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - player = (Player) playerinventory.player.getBukkitEntity(); // CraftBukkit - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return a(this.containerAccess, entityhuman, Blocks.CARTOGRAPHY_TABLE); - } - - @Override - public void a(IInventory iinventory) { - ItemStack itemstack = this.inventory.getItem(0); - ItemStack itemstack1 = this.inventory.getItem(1); - ItemStack itemstack2 = this.resultInventory.getItem(2); - - if (!itemstack2.isEmpty() && (itemstack.isEmpty() || itemstack1.isEmpty())) { - this.resultInventory.splitWithoutUpdate(2); - } else if (!itemstack.isEmpty() && !itemstack1.isEmpty()) { - this.a(itemstack, itemstack1, itemstack2); - } - - } - - private void a(ItemStack itemstack, ItemStack itemstack1, ItemStack itemstack2) { - this.containerAccess.a((world, blockposition) -> { - Item item = itemstack1.getItem(); - WorldMap worldmap = ItemWorldMap.a(itemstack, world); - - if (worldmap != null) { - ItemStack itemstack3; - - if (item == Items.PAPER && !worldmap.locked && worldmap.scale < 4) { - itemstack3 = itemstack.cloneItemStack(); - itemstack3.setCount(1); - itemstack3.getOrCreateTag().setInt("map_scale_direction", 1); - this.c(); - } else if (item == Items.df && !worldmap.locked) { - itemstack3 = itemstack.cloneItemStack(); - itemstack3.setCount(1); - this.c(); - } else { - if (item != Items.MAP) { - this.resultInventory.splitWithoutUpdate(2); - this.c(); - return; - } - - itemstack3 = itemstack.cloneItemStack(); - itemstack3.setCount(2); - this.c(); - } - - if (!ItemStack.matches(itemstack3, itemstack2)) { - this.resultInventory.setItem(2, itemstack3); - this.c(); - } - - } - }); - } - - @Override - public boolean a(ItemStack itemstack, Slot slot) { - return false; - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - ItemStack itemstack2 = itemstack1; - Item item = itemstack1.getItem(); - - itemstack = itemstack1.cloneItemStack(); - if (i == 2) { - if (this.inventory.getItem(1).getItem() == Items.df) { - itemstack2 = (ItemStack) this.containerAccess.a((world, blockposition) -> { - ItemStack itemstack3 = ItemWorldMap.b(world, this.inventory.getItem(0)); - - if (itemstack3 != null) { - itemstack3.setCount(1); - return itemstack3; - } else { - return itemstack1; - } - }).orElse(itemstack1); - } - - item.b(itemstack2, entityhuman.world, entityhuman); - if (!this.a(itemstack2, 3, 39, true)) { - return ItemStack.a; - } - - slot.a(itemstack2, itemstack); - } else if (i != 1 && i != 0) { - if (item == Items.FILLED_MAP) { - if (!this.a(itemstack1, 0, 1, false)) { - return ItemStack.a; - } - } else if (item != Items.PAPER && item != Items.MAP && item != Items.df) { - if (i >= 3 && i < 30) { - if (!this.a(itemstack1, 30, 39, false)) { - return ItemStack.a; - } - } else if (i >= 30 && i < 39 && !this.a(itemstack1, 3, 30, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 1, 2, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 3, 39, false)) { - return ItemStack.a; - } - - if (itemstack2.isEmpty()) { - slot.set(ItemStack.a); - } - - slot.d(); - if (itemstack2.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - this.e = true; - slot.a(entityhuman, itemstack2); - this.e = false; - this.c(); - } - - return itemstack; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.resultInventory.splitWithoutUpdate(2); - this.containerAccess.a((world, blockposition) -> { - this.a(entityhuman, entityhuman.world, this.inventory); - }); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerChest.java b/src/main/java/net/minecraft/server/ContainerChest.java deleted file mode 100644 index 0ee6524b8..000000000 --- a/src/main/java/net/minecraft/server/ContainerChest.java +++ /dev/null @@ -1,147 +0,0 @@ -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 d; - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private 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 - - private ContainerChest(Containers containers, int i, PlayerInventory playerinventory, int j) { - this(containers, i, playerinventory, new InventorySubcontainer(9 * j), j); - } - - public static ContainerChest a(int i, PlayerInventory playerinventory) { - return new ContainerChest(Containers.GENERIC_9X1, i, playerinventory, 1); - } - - public static ContainerChest b(int i, PlayerInventory playerinventory) { - return new ContainerChest(Containers.GENERIC_9X2, i, playerinventory, 2); - } - - public static ContainerChest c(int i, PlayerInventory playerinventory) { - return new ContainerChest(Containers.GENERIC_9X3, i, playerinventory, 3); - } - - public static ContainerChest d(int i, PlayerInventory playerinventory) { - return new ContainerChest(Containers.GENERIC_9X4, i, playerinventory, 4); - } - - public static ContainerChest e(int i, PlayerInventory playerinventory) { - return new ContainerChest(Containers.GENERIC_9X5, i, playerinventory, 5); - } - - public static ContainerChest f(int i, PlayerInventory playerinventory) { - return new ContainerChest(Containers.GENERIC_9X6, i, playerinventory, 6); - } - - public static ContainerChest a(int i, PlayerInventory playerinventory, IInventory iinventory) { - return new ContainerChest(Containers.GENERIC_9X3, i, playerinventory, iinventory, 3); - } - - public static ContainerChest b(int i, PlayerInventory playerinventory, IInventory iinventory) { - return new ContainerChest(Containers.GENERIC_9X6, i, playerinventory, iinventory, 6); - } - - public ContainerChest(Containers containers, int i, PlayerInventory playerinventory, IInventory iinventory, int j) { - super(containers, i); - a(iinventory, j * 9); - this.container = iinventory; - this.d = j; - iinventory.startOpen(playerinventory.player); - int k = (this.d - 4) * 18; - - // CraftBukkit start - Save player - this.player = playerinventory; - // CraftBukkit end - - int l; - int i1; - - for (l = 0; l < this.d; ++l) { - for (i1 = 0; i1 < 9; ++i1) { - this.a(new Slot(iinventory, i1 + l * 9, 8 + i1 * 18, 18 + l * 18)); - } - } - - for (l = 0; l < 3; ++l) { - for (i1 = 0; i1 < 9; ++i1) { - this.a(new Slot(playerinventory, i1 + l * 9 + 9, 8 + i1 * 18, 103 + l * 18 + k)); - } - } - - for (l = 0; l < 9; ++l) { - this.a(new Slot(playerinventory, l, 8 + l * 18, 161 + k)); - } - - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return this.container.a(entityhuman); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - - itemstack = itemstack1.cloneItemStack(); - if (i < this.d * 9) { - if (!this.a(itemstack1, this.d * 9, this.slots.size(), true)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 0, this.d * 9, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - } - - return itemstack; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.container.closeContainer(entityhuman); - } - - public IInventory e() { - return this.container; - } -} diff --git a/src/main/java/net/minecraft/server/ContainerDispenser.java b/src/main/java/net/minecraft/server/ContainerDispenser.java deleted file mode 100644 index 1af91fb54..000000000 --- a/src/main/java/net/minecraft/server/ContainerDispenser.java +++ /dev/null @@ -1,108 +0,0 @@ -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 final IInventory items; - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private PlayerInventory player; - // CraftBukkit end - - public ContainerDispenser(int i, PlayerInventory playerinventory) { - this(i, playerinventory, new InventorySubcontainer(9)); - } - - public ContainerDispenser(int i, PlayerInventory playerinventory, IInventory iinventory) { - super(Containers.GENERIC_3X3, i); - // CraftBukkit start - Save player - this.player = playerinventory; - // CraftBukkit end - - a(iinventory, 9); - this.items = iinventory; - iinventory.startOpen(playerinventory.player); - - int j; - int k; - - for (j = 0; j < 3; ++j) { - for (k = 0; k < 3; ++k) { - this.a(new Slot(iinventory, k + j * 3, 62 + k * 18, 17 + j * 18)); - } - } - - for (j = 0; j < 3; ++j) { - for (k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return this.items.a(entityhuman); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.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 ItemStack.a; - } - } else if (!this.a(itemstack1, 0, 9, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - } - - return itemstack; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.items.closeContainer(entityhuman); - } - - // 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/src/main/java/net/minecraft/server/ContainerEnchantTable.java b/src/main/java/net/minecraft/server/ContainerEnchantTable.java deleted file mode 100644 index 19b4df4a0..000000000 --- a/src/main/java/net/minecraft/server/ContainerEnchantTable.java +++ /dev/null @@ -1,398 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import java.util.Random; - -// CraftBukkit start -import java.util.Collections; -import java.util.Map; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.inventory.CraftInventoryEnchanting; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.enchantments.EnchantmentOffer; -import org.bukkit.event.enchantment.EnchantItemEvent; -import org.bukkit.event.enchantment.PrepareItemEnchantEvent; -import org.bukkit.entity.Player; -// CraftBukkit end - -public class ContainerEnchantTable extends Container { - - private final IInventory enchantSlots; - private final ContainerAccess containerAccess; - private final Random h; - private final ContainerProperty i; - public final int[] costs; - public final int[] enchantments; - public final int[] levels; - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private Player player; - // CraftBukkit end - - public ContainerEnchantTable(int i, PlayerInventory playerinventory) { - this(i, playerinventory, ContainerAccess.a); - } - - public ContainerEnchantTable(int i, PlayerInventory playerinventory, ContainerAccess containeraccess) { - super(Containers.ENCHANTMENT, i); - this.enchantSlots = new InventorySubcontainer(2) { - @Override - public void update() { - super.update(); - ContainerEnchantTable.this.a((IInventory) this); - } - - // CraftBukkit start - @Override - public Location getLocation() { - return containeraccess.getLocation(); - } - // CraftBukkit end - }; - this.h = new Random(); - this.i = ContainerProperty.a(); - this.costs = new int[3]; - this.enchantments = new int[]{-1, -1, -1}; - this.levels = new int[]{-1, -1, -1}; - this.containerAccess = containeraccess; - this.a(new Slot(this.enchantSlots, 0, 15, 47) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return true; - } - - @Override - public int getMaxStackSize() { - return 1; - } - }); - this.a(new Slot(this.enchantSlots, 1, 35, 47) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return itemstack.getItem() == Items.LAPIS_LAZULI; - } - }); - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - this.a(ContainerProperty.a(this.costs, 0)); - this.a(ContainerProperty.a(this.costs, 1)); - this.a(ContainerProperty.a(this.costs, 2)); - this.a(this.i).set(playerinventory.player.dM()); - this.a(ContainerProperty.a(this.enchantments, 0)); - this.a(ContainerProperty.a(this.enchantments, 1)); - this.a(ContainerProperty.a(this.enchantments, 2)); - this.a(ContainerProperty.a(this.levels, 0)); - this.a(ContainerProperty.a(this.levels, 1)); - this.a(ContainerProperty.a(this.levels, 2)); - // CraftBukkit start - player = (Player) playerinventory.player.getBukkitEntity(); - // CraftBukkit end - } - - @Override - public void a(IInventory iinventory) { - if (iinventory == this.enchantSlots) { - ItemStack itemstack = iinventory.getItem(0); - - if (!itemstack.isEmpty()) { // CraftBukkit - relax condition - this.containerAccess.a((world, blockposition) -> { - int i = 0; - - int j; - - for (j = -1; j <= 1; ++j) { - for (int k = -1; k <= 1; ++k) { - if ((j != 0 || k != 0) && world.isEmpty(blockposition.b(k, 0, j)) && world.isEmpty(blockposition.b(k, 1, j))) { - if (world.getType(blockposition.b(k * 2, 0, j * 2)).getBlock() == Blocks.BOOKSHELF) { - ++i; - } - - if (world.getType(blockposition.b(k * 2, 1, j * 2)).getBlock() == Blocks.BOOKSHELF) { - ++i; - } - - if (k != 0 && j != 0) { - if (world.getType(blockposition.b(k * 2, 0, j)).getBlock() == Blocks.BOOKSHELF) { - ++i; - } - - if (world.getType(blockposition.b(k * 2, 1, j)).getBlock() == Blocks.BOOKSHELF) { - ++i; - } - - if (world.getType(blockposition.b(k, 0, j * 2)).getBlock() == Blocks.BOOKSHELF) { - ++i; - } - - if (world.getType(blockposition.b(k, 1, j * 2)).getBlock() == Blocks.BOOKSHELF) { - ++i; - } - } - } - } - } - - this.h.setSeed((long) this.i.get()); - - for (j = 0; j < 3; ++j) { - this.costs[j] = EnchantmentManager.a(this.h, j, i, itemstack); - this.enchantments[j] = -1; - this.levels[j] = -1; - if (this.costs[j] < j + 1) { - this.costs[j] = 0; - } - } - - 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 = (WeightedRandomEnchant) list.get(this.h.nextInt(list.size())); - - this.enchantments[j] = IRegistry.ENCHANTMENT.a(weightedrandomenchant.enchantment); // CraftBukkit - decompile error - this.levels[j] = weightedrandomenchant.level; - } - } - } - - // CraftBukkit start - CraftItemStack item = CraftItemStack.asCraftMirror(itemstack); - org.bukkit.enchantments.EnchantmentOffer[] offers = new EnchantmentOffer[3]; - for (j = 0; j < 3; ++j) { - org.bukkit.enchantments.Enchantment enchantment = (this.enchantments[j] >= 0) ? org.bukkit.enchantments.Enchantment.getByKey(CraftNamespacedKey.fromMinecraft(IRegistry.ENCHANTMENT.getKey(IRegistry.ENCHANTMENT.fromId(this.enchantments[j])))) : null; - offers[j] = (enchantment != null) ? new EnchantmentOffer(enchantment, this.levels[j], this.costs[j]) : null; - } - - PrepareItemEnchantEvent event = new PrepareItemEnchantEvent(player, this.getBukkitView(), containerAccess.getLocation().getBlock(), item, offers, i); - event.setCancelled(!itemstack.canEnchant()); - world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - for (j = 0; j < 3; ++j) { - this.costs[j] = 0; - this.enchantments[j] = -1; - this.levels[j] = -1; - } - return; - } - - for (j = 0; j < 3; j++) { - EnchantmentOffer offer = event.getOffers()[j]; - if (offer != null) { - this.costs[j] = offer.getCost(); - this.enchantments[j] = IRegistry.ENCHANTMENT.a(IRegistry.ENCHANTMENT.get(CraftNamespacedKey.toMinecraft(offer.getEnchantment().getKey()))); - this.levels[j] = offer.getEnchantmentLevel(); - } else { - this.costs[j] = 0; - this.enchantments[j] = -1; - this.levels[j] = -1; - } - } - // CraftBukkit end - - this.c(); - }); - } else { - for (int i = 0; i < 3; ++i) { - this.costs[i] = 0; - this.enchantments[i] = -1; - this.levels[i] = -1; - } - } - } - - } - - @Override - public boolean a(EntityHuman entityhuman, int i) { - ItemStack itemstack = this.enchantSlots.getItem(0); - ItemStack itemstack1 = this.enchantSlots.getItem(1); - int j = i + 1; - - if ((itemstack1.isEmpty() || itemstack1.getCount() < j) && !entityhuman.abilities.canInstantlyBuild) { - return false; - } else if (this.costs[i] > 0 && !itemstack.isEmpty() && (entityhuman.expLevel >= j && entityhuman.expLevel >= this.costs[i] || entityhuman.abilities.canInstantlyBuild)) { - this.containerAccess.a((world, blockposition) -> { - ItemStack itemstack2 = itemstack; - List list = this.a(itemstack, i, this.costs[i]); - - // CraftBukkit start - if (true || !list.isEmpty()) { - // entityhuman.enchantDone(itemstack, j); // Moved down - boolean flag = itemstack.getItem() == Items.BOOK; - Map enchants = new java.util.HashMap(); - for (Object obj : list) { - WeightedRandomEnchant instance = (WeightedRandomEnchant) obj; - enchants.put(org.bukkit.enchantments.Enchantment.getByKey(CraftNamespacedKey.fromMinecraft(IRegistry.ENCHANTMENT.getKey(instance.enchantment))), instance.level); - } - CraftItemStack item = CraftItemStack.asCraftMirror(itemstack2); - - EnchantItemEvent event = new EnchantItemEvent((Player) entityhuman.getBukkitEntity(), this.getBukkitView(), containerAccess.getLocation().getBlock(), item, this.costs[i], enchants, i); - world.getServer().getPluginManager().callEvent(event); - - int level = event.getExpLevelCost(); - if (event.isCancelled() || (level > entityhuman.expLevel && !entityhuman.abilities.canInstantlyBuild) || event.getEnchantsToAdd().isEmpty()) { - return; - } - - if (flag) { - itemstack2 = new ItemStack(Items.ENCHANTED_BOOK); - this.enchantSlots.setItem(0, itemstack2); - } - - for (Map.Entry entry : event.getEnchantsToAdd().entrySet()) { - try { - if (flag) { - NamespacedKey enchantId = entry.getKey().getKey(); - Enchantment nms = IRegistry.ENCHANTMENT.get(CraftNamespacedKey.toMinecraft(enchantId)); - if (nms == null) { - continue; - } - - WeightedRandomEnchant weightedrandomenchant = new WeightedRandomEnchant(nms, entry.getValue()); - ItemEnchantedBook.a(itemstack2, weightedrandomenchant); - } else { - item.addUnsafeEnchantment(entry.getKey(), entry.getValue()); - } - } catch (IllegalArgumentException e) { - /* Just swallow invalid enchantments */ - } - } - - entityhuman.enchantDone(itemstack, j); - // CraftBukkit end - - // CraftBukkit - TODO: let plugins change this - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack1.subtract(j); - if (itemstack1.isEmpty()) { - this.enchantSlots.setItem(1, ItemStack.a); - } - } - - entityhuman.a(StatisticList.ENCHANT_ITEM); - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.i.a((EntityPlayer) entityhuman, itemstack2, j); - } - - this.enchantSlots.update(); - this.i.set(entityhuman.dM()); - this.a(this.enchantSlots); - world.playSound((EntityHuman) null, blockposition, SoundEffects.BLOCK_ENCHANTMENT_TABLE_USE, SoundCategory.BLOCKS, 1.0F, world.random.nextFloat() * 0.1F + 0.9F); - } - - }); - return true; - } else { - return false; - } - } - - private List a(ItemStack itemstack, int i, int j) { - this.h.setSeed((long) (this.i.get() + i)); - List list = EnchantmentManager.b(this.h, itemstack, j, false); - - if (itemstack.getItem() == Items.BOOK && list.size() > 1) { - list.remove(this.h.nextInt(list.size())); - } - - return list; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.containerAccess.a((world, blockposition) -> { - this.a(entityhuman, entityhuman.world, this.enchantSlots); - }); - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return a(this.containerAccess, entityhuman, Blocks.ENCHANTING_TABLE); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.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 ItemStack.a; - } - } else if (i == 1) { - if (!this.a(itemstack1, 2, 38, true)) { - return ItemStack.a; - } - } else if (itemstack1.getItem() == Items.LAPIS_LAZULI) { - if (!this.a(itemstack1, 1, 2, true)) { - return ItemStack.a; - } - } else { - if (((Slot) this.slots.get(0)).hasItem() || !((Slot) this.slots.get(0)).isAllowed(itemstack1)) { - return ItemStack.a; - } - - if (itemstack1.hasTag() && itemstack1.getCount() == 1) { - ((Slot) this.slots.get(0)).set(itemstack1.cloneItemStack()); - itemstack1.setCount(0); - } else if (!itemstack1.isEmpty()) { - // Spigot start - ItemStack clone = itemstack1.cloneItemStack(); - clone.setCount(1); - ((Slot) this.slots.get(0)).set(clone); - // Spigot end - itemstack1.subtract(1); - } - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - 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/src/main/java/net/minecraft/server/ContainerFurnace.java b/src/main/java/net/minecraft/server/ContainerFurnace.java deleted file mode 100644 index 71cc65a7c..000000000 --- a/src/main/java/net/minecraft/server/ContainerFurnace.java +++ /dev/null @@ -1,165 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftInventoryFurnace; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -// CraftBukkit end - -public abstract class ContainerFurnace extends ContainerRecipeBook { - - private final IInventory furnace; - private final IContainerProperties e; - protected final World c; - private final Recipes f; - - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private 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 - - protected ContainerFurnace(Containers containers, Recipes recipes, int i, PlayerInventory playerinventory) { - this(containers, recipes, i, playerinventory, new InventorySubcontainer(3), new ContainerProperties(4)); - } - - protected ContainerFurnace(Containers containers, Recipes recipes, int i, PlayerInventory playerinventory, IInventory iinventory, IContainerProperties icontainerproperties) { - super(containers, i); - this.f = recipes; - a(iinventory, 3); - a(icontainerproperties, 4); - this.furnace = iinventory; - this.e = icontainerproperties; - this.c = playerinventory.player.world; - this.a(new Slot(iinventory, 0, 56, 17)); - this.a((Slot) (new SlotFurnaceFuel(this, iinventory, 1, 56, 53))); - this.a((Slot) (new SlotFurnaceResult(playerinventory.player, iinventory, 2, 116, 35))); - this.player = playerinventory; // CraftBukkit - save player - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - this.a(icontainerproperties); - } - - @Override - public void a(AutoRecipeStackManager autorecipestackmanager) { - if (this.furnace instanceof AutoRecipeOutput) { - ((AutoRecipeOutput) this.furnace).a(autorecipestackmanager); - } - - } - - @Override - public void e() { - this.furnace.clear(); - } - - @Override - public void a(boolean flag, IRecipe irecipe, EntityPlayer entityplayer) { - (new AutoRecipeFurnace(this)).a(entityplayer, irecipe, flag); // CraftBukkit - decompile error - } - - @Override - public boolean a(IRecipe irecipe) { - return irecipe.a(this.furnace, this.c); - } - - @Override - public int f() { - return 2; - } - - @Override - public int g() { - return 1; - } - - @Override - public int h() { - return 1; - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return this.furnace.a(entityhuman); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.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 ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } else if (i != 1 && i != 0) { - if (this.a(itemstack1)) { - if (!this.a(itemstack1, 0, 1, false)) { - return ItemStack.a; - } - } else if (this.b(itemstack1)) { - if (!this.a(itemstack1, 1, 2, false)) { - return ItemStack.a; - } - } else if (i >= 3 && i < 30) { - if (!this.a(itemstack1, 30, 39, false)) { - return ItemStack.a; - } - } else if (i >= 30 && i < 39 && !this.a(itemstack1, 3, 30, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 3, 39, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - } - - return itemstack; - } - - protected boolean a(ItemStack itemstack) { - return this.c.getCraftingManager().craft((Recipes) this.f, new InventorySubcontainer(new ItemStack[]{itemstack}), this.c).isPresent(); // Eclipse fail - } - - protected boolean b(ItemStack itemstack) { - return TileEntityFurnace.isFuel(itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerGrindstone.java b/src/main/java/net/minecraft/server/ContainerGrindstone.java deleted file mode 100644 index ed88e208d..000000000 --- a/src/main/java/net/minecraft/server/ContainerGrindstone.java +++ /dev/null @@ -1,320 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.craftbukkit.inventory.CraftInventoryGrindstone; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -import org.bukkit.entity.Player; -// CraftBukkit end - -public class ContainerGrindstone extends Container { - - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private Player player; - - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - CraftInventoryGrindstone inventory = new CraftInventoryGrindstone(this.craftInventory, this.resultInventory); - bukkitEntity = new CraftInventoryView(this.player, inventory, this); - return bukkitEntity; - } - // CraftBukkit end - private final IInventory resultInventory; - private final IInventory craftInventory; - private final ContainerAccess containerAccess; - - public ContainerGrindstone(int i, PlayerInventory playerinventory) { - this(i, playerinventory, ContainerAccess.a); - } - - public ContainerGrindstone(int i, PlayerInventory playerinventory, final ContainerAccess containeraccess) { - super(Containers.GRINDSTONE, i); - this.resultInventory = new InventoryCraftResult(); - this.craftInventory = new InventorySubcontainer(2) { - @Override - public void update() { - super.update(); - ContainerGrindstone.this.a((IInventory) this); - } - - // CraftBukkit start - @Override - public Location getLocation() { - return containeraccess.getLocation(); - } - // CraftBukkit end - }; - this.containerAccess = containeraccess; - this.a(new Slot(this.craftInventory, 0, 49, 19) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return itemstack.e() || itemstack.getItem() == Items.ENCHANTED_BOOK || itemstack.hasEnchantments(); - } - }); - this.a(new Slot(this.craftInventory, 1, 49, 40) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return itemstack.e() || itemstack.getItem() == Items.ENCHANTED_BOOK || itemstack.hasEnchantments(); - } - }); - this.a(new Slot(this.resultInventory, 2, 129, 34) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return false; - } - - @Override - public ItemStack a(EntityHuman entityhuman, ItemStack itemstack) { - containeraccess.a((world, blockposition) -> { - int j = this.a(world); - - while (j > 0) { - int k = EntityExperienceOrb.getOrbValue(j); - - j -= k; - world.addEntity(new EntityExperienceOrb(world, (double) blockposition.getX(), (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, k, org.bukkit.entity.ExperienceOrb.SpawnReason.GRINDSTONE, entityhuman)); // Paper - } - - world.triggerEffect(1042, blockposition, 0); - }); - ContainerGrindstone.this.craftInventory.setItem(0, ItemStack.a); - ContainerGrindstone.this.craftInventory.setItem(1, ItemStack.a); - return itemstack; - } - - private int a(World world) { - byte b0 = 0; - int j = b0 + this.e(ContainerGrindstone.this.craftInventory.getItem(0)); - - j += this.e(ContainerGrindstone.this.craftInventory.getItem(1)); - if (j > 0) { - int k = (int) Math.ceil((double) j / 2.0D); - - return k + world.random.nextInt(k); - } else { - return 0; - } - } - - private int e(ItemStack itemstack) { - int j = 0; - Map map = EnchantmentManager.a(itemstack); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - Enchantment enchantment = (Enchantment) entry.getKey(); - Integer integer = (Integer) entry.getValue(); - - if (!enchantment.c()) { - j += enchantment.a(integer); - } - } - - return j; - } - }); - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - player = (Player) playerinventory.player.getBukkitEntity(); // CraftBukkit - } - - @Override - public void a(IInventory iinventory) { - super.a(iinventory); - if (iinventory == this.craftInventory) { - this.e(); - } - - } - - private void e() { - ItemStack itemstack = this.craftInventory.getItem(0); - ItemStack itemstack1 = this.craftInventory.getItem(1); - boolean flag = !itemstack.isEmpty() || !itemstack1.isEmpty(); - boolean flag1 = !itemstack.isEmpty() && !itemstack1.isEmpty(); - - if (flag) { - boolean flag2 = !itemstack.isEmpty() && itemstack.getItem() != Items.ENCHANTED_BOOK && !itemstack.hasEnchantments() || !itemstack1.isEmpty() && itemstack1.getItem() != Items.ENCHANTED_BOOK && !itemstack1.hasEnchantments(); - - if (itemstack.getCount() > 1 || itemstack1.getCount() > 1 || !flag1 && flag2) { - this.resultInventory.setItem(0, ItemStack.a); - this.c(); - return; - } - - byte b0 = 1; - int i; - ItemStack itemstack2; - - if (flag1) { - if (itemstack.getItem() != itemstack1.getItem()) { - this.resultInventory.setItem(0, ItemStack.a); - this.c(); - return; - } - - Item item = itemstack.getItem(); - int j = item.getMaxDurability() - itemstack.getDamage(); - int k = item.getMaxDurability() - itemstack1.getDamage(); - int l = j + k + item.getMaxDurability() * 5 / 100; - - i = Math.max(item.getMaxDurability() - l, 0); - itemstack2 = this.b(itemstack, itemstack1); - if (!itemstack2.e()) { - if (!ItemStack.matches(itemstack, itemstack1)) { - this.resultInventory.setItem(0, ItemStack.a); - this.c(); - return; - } - - b0 = 2; - } - } else { - boolean flag3 = !itemstack.isEmpty(); - - i = flag3 ? itemstack.getDamage() : itemstack1.getDamage(); - itemstack2 = flag3 ? itemstack : itemstack1; - } - - this.resultInventory.setItem(0, this.a(itemstack2, i, b0)); - } else { - this.resultInventory.setItem(0, ItemStack.a); - } - - this.c(); - } - - private ItemStack b(ItemStack itemstack, ItemStack itemstack1) { - ItemStack itemstack2 = itemstack.cloneItemStack(); - Map map = EnchantmentManager.a(itemstack1); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - Enchantment enchantment = (Enchantment) entry.getKey(); - - if (!enchantment.c() || EnchantmentManager.getEnchantmentLevel(enchantment, itemstack2) == 0) { - itemstack2.addEnchantment(enchantment, (Integer) entry.getValue()); - } - } - - return itemstack2; - } - - private ItemStack a(ItemStack itemstack, int i, int j) { - ItemStack itemstack1 = itemstack.cloneItemStack(); - - itemstack1.removeTag("Enchantments"); - itemstack1.removeTag("StoredEnchantments"); - if (i > 0) { - itemstack1.setDamage(i); - } else { - itemstack1.removeTag("Damage"); - } - - itemstack1.setCount(j); - Map map = (Map) EnchantmentManager.a(itemstack).entrySet().stream().filter((entry) -> { - return ((Enchantment) entry.getKey()).c(); - }).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); - - EnchantmentManager.a(map, itemstack1); - itemstack1.setRepairCost(0); - if (itemstack1.getItem() == Items.ENCHANTED_BOOK && map.size() == 0) { - itemstack1 = new ItemStack(Items.BOOK); - if (itemstack.hasName()) { - itemstack1.a(itemstack.getName()); - } - } - - for (int k = 0; k < map.size(); ++k) { - itemstack1.setRepairCost(ContainerAnvil.d(itemstack1.getRepairCost())); - } - - return itemstack1; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.containerAccess.a((world, blockposition) -> { - this.a(entityhuman, world, this.craftInventory); - }); - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return a(this.containerAccess, entityhuman, Blocks.GRINDSTONE); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - - itemstack = itemstack1.cloneItemStack(); - ItemStack itemstack2 = this.craftInventory.getItem(0); - ItemStack itemstack3 = this.craftInventory.getItem(1); - - if (i == 2) { - if (!this.a(itemstack1, 3, 39, true)) { - return ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } else if (i != 0 && i != 1) { - if (!itemstack2.isEmpty() && !itemstack3.isEmpty()) { - if (i >= 3 && i < 30) { - if (!this.a(itemstack1, 30, 39, false)) { - return ItemStack.a; - } - } else if (i >= 30 && i < 39 && !this.a(itemstack1, 3, 30, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 0, 2, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 3, 39, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - } - - return itemstack; - } -} diff --git a/src/main/java/net/minecraft/server/ContainerHopper.java b/src/main/java/net/minecraft/server/ContainerHopper.java deleted file mode 100644 index 91ff331c9..000000000 --- a/src/main/java/net/minecraft/server/ContainerHopper.java +++ /dev/null @@ -1,96 +0,0 @@ -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 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(int i, PlayerInventory playerinventory) { - this(i, playerinventory, new InventorySubcontainer(5)); - } - - public ContainerHopper(int i, PlayerInventory playerinventory, IInventory iinventory) { - super(Containers.HOPPER, i); - this.hopper = iinventory; - this.player = playerinventory; // CraftBukkit - save player - a(iinventory, 5); - iinventory.startOpen(playerinventory.player); - boolean flag = true; - - int j; - - for (j = 0; j < 5; ++j) { - this.a(new Slot(iinventory, j, 44 + j * 18, 20)); - } - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, j * 18 + 51)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 109)); - } - - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return this.hopper.a(entityhuman); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.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.slots.size(), true)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 0, this.hopper.getSize(), false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - } - - return itemstack; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.hopper.closeContainer(entityhuman); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerHorse.java b/src/main/java/net/minecraft/server/ContainerHorse.java deleted file mode 100644 index ad4e0a45c..000000000 --- a/src/main/java/net/minecraft/server/ContainerHorse.java +++ /dev/null @@ -1,122 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -import org.bukkit.inventory.InventoryView; -// CraftBukkit end - -public class ContainerHorse extends Container { - - private final IInventory c; - private final EntityHorseAbstract d; - - // CraftBukkit start - org.bukkit.craftbukkit.inventory.CraftInventoryView bukkitEntity; - PlayerInventory player; - - @Override - public InventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - return bukkitEntity = new CraftInventoryView(player.player.getBukkitEntity(), c.getOwner().getInventory(), this); - } - - public ContainerHorse(int i, PlayerInventory playerinventory, IInventory iinventory, final EntityHorseAbstract entityhorseabstract) { - super((Containers) null, i); - player = playerinventory; - // CraftBukkit end - this.c = iinventory; - this.d = entityhorseabstract; - boolean flag = true; - - iinventory.startOpen(playerinventory.player); - boolean flag1 = true; - - this.a(new Slot(iinventory, 0, 8, 18) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return itemstack.getItem() == Items.SADDLE && !this.hasItem() && entityhorseabstract.ep(); - } - }); - this.a(new Slot(iinventory, 1, 8, 36) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return entityhorseabstract.j(itemstack); - } - - @Override - public int getMaxStackSize() { - return 1; - } - }); - int j; - int k; - - if (entityhorseabstract instanceof EntityHorseChestedAbstract && ((EntityHorseChestedAbstract) entityhorseabstract).isCarryingChest()) { - for (j = 0; j < 3; ++j) { - for (k = 0; k < ((EntityHorseChestedAbstract) entityhorseabstract).dZ(); ++k) { - this.a(new Slot(iinventory, 2 + k + j * ((EntityHorseChestedAbstract) entityhorseabstract).dZ(), 80 + k * 18, 18 + j * 18)); - } - } - } - - for (j = 0; j < 3; ++j) { - for (k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 102 + j * 18 + -18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - return this.c.a(entityhuman) && (this.d.isAlive() && this.d.valid) && this.d.g((Entity) entityhuman) < 8.0F; // Paper - Fix MC-161754 - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - - itemstack = itemstack1.cloneItemStack(); - if (i < this.c.getSize()) { - if (!this.a(itemstack1, this.c.getSize(), this.slots.size(), true)) { - return ItemStack.a; - } - } else if (this.getSlot(1).isAllowed(itemstack1) && !this.getSlot(1).hasItem()) { - if (!this.a(itemstack1, 1, 2, false)) { - return ItemStack.a; - } - } else if (this.getSlot(0).isAllowed(itemstack1)) { - if (!this.a(itemstack1, 0, 1, false)) { - return ItemStack.a; - } - } else if (this.c.getSize() <= 2 || !this.a(itemstack1, 2, this.c.getSize(), false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - } - - return itemstack; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.c.closeContainer(entityhuman); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerLectern.java b/src/main/java/net/minecraft/server/ContainerLectern.java deleted file mode 100644 index 5aa24831b..000000000 --- a/src/main/java/net/minecraft/server/ContainerLectern.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.inventory.CraftInventoryLectern; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerTakeLecternBookEvent; -// CraftBukkit end - -public class ContainerLectern extends Container { - - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private Player player; - - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - CraftInventoryLectern inventory = new CraftInventoryLectern(this.inventory); - bukkitEntity = new CraftInventoryView(this.player, inventory, this); - return bukkitEntity; - } - // CraftBukkit end - private final IInventory inventory; - private final IContainerProperties containerProperties; - - // CraftBukkit start - add player - public ContainerLectern(int i, PlayerInventory playerinventory) { - this(i, new InventorySubcontainer(1), new ContainerProperties(1), playerinventory); - } - - public ContainerLectern(int i, IInventory iinventory, IContainerProperties icontainerproperties, PlayerInventory playerinventory) { - // CraftBukkit end - super(Containers.LECTERN, i); - a(iinventory, 1); - a(icontainerproperties, 1); - this.inventory = iinventory; - this.containerProperties = icontainerproperties; - this.a(new Slot(iinventory, 0, 0, 0) { - @Override - public void d() { - super.d(); - ContainerLectern.this.a(this.inventory); - } - }); - this.a(icontainerproperties); - player = (Player) playerinventory.player.getBukkitEntity(); // CraftBukkit - } - - @Override - public boolean a(EntityHuman entityhuman, int i) { - int j; - - if (i >= 100) { - j = i - 100; - this.a(0, j); - return true; - } else { - switch (i) { - case 1: - j = this.containerProperties.getProperty(0); - this.a(0, j - 1); - return true; - case 2: - j = this.containerProperties.getProperty(0); - this.a(0, j + 1); - return true; - case 3: - if (!entityhuman.dQ()) { - return false; - } - - // CraftBukkit start - Event for taking the book - PlayerTakeLecternBookEvent event = new PlayerTakeLecternBookEvent(player, ((CraftInventoryLectern) getBukkitView().getTopInventory()).getHolder()); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return false; - } - // CraftBukkit end - ItemStack itemstack = this.inventory.splitWithoutUpdate(0); - - this.inventory.update(); - if (!entityhuman.inventory.pickup(itemstack)) { - entityhuman.drop(itemstack, false); - } - - return true; - default: - return false; - } - } - } - - @Override - public void a(int i, int j) { - super.a(i, j); - this.c(); - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return this.inventory.a(entityhuman); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerLoom.java b/src/main/java/net/minecraft/server/ContainerLoom.java deleted file mode 100644 index 0d69fa607..000000000 --- a/src/main/java/net/minecraft/server/ContainerLoom.java +++ /dev/null @@ -1,275 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.craftbukkit.inventory.CraftInventoryLoom; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -import org.bukkit.entity.Player; -// CraftBukkit end - -public class ContainerLoom extends Container { - - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private Player player; - - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - CraftInventoryLoom inventory = new CraftInventoryLoom(this.craftInventory, this.resultInventory); - bukkitEntity = new CraftInventoryView(this.player, inventory, this); - return bukkitEntity; - } - // CraftBukkit end - private final ContainerAccess containerAccess; - private final ContainerProperty d; - private Runnable e; - private final Slot f; - private final Slot g; - private final Slot h; - private final Slot i; - private final IInventory craftInventory; - private final IInventory resultInventory; - - public ContainerLoom(int i, PlayerInventory playerinventory) { - this(i, playerinventory, ContainerAccess.a); - } - - public ContainerLoom(int i, PlayerInventory playerinventory, final ContainerAccess containeraccess) { - super(Containers.LOOM, i); - this.d = ContainerProperty.a(); - this.e = () -> { - }; - this.craftInventory = new InventorySubcontainer(3) { - @Override - public void update() { - super.update(); - ContainerLoom.this.a((IInventory) this); - ContainerLoom.this.e.run(); - } - - // CraftBukkit start - @Override - public Location getLocation() { - return containeraccess.getLocation(); - } - // CraftBukkit end - }; - this.resultInventory = new InventorySubcontainer(1) { - @Override - public void update() { - super.update(); - ContainerLoom.this.e.run(); - } - - // CraftBukkit start - @Override - public Location getLocation() { - return containeraccess.getLocation(); - } - // CraftBukkit end - }; - this.containerAccess = containeraccess; - this.f = this.a(new Slot(this.craftInventory, 0, 13, 26) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return itemstack.getItem() instanceof ItemBanner; - } - }); - this.g = this.a(new Slot(this.craftInventory, 1, 33, 26) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return itemstack.getItem() instanceof ItemDye; - } - }); - this.h = this.a(new Slot(this.craftInventory, 2, 23, 45) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return itemstack.getItem() instanceof ItemBannerPattern; - } - }); - this.i = this.a(new Slot(this.resultInventory, 0, 143, 58) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return false; - } - - @Override - public ItemStack a(EntityHuman entityhuman, ItemStack itemstack) { - ContainerLoom.this.f.a(1); - ContainerLoom.this.g.a(1); - if (!ContainerLoom.this.f.hasItem() || !ContainerLoom.this.g.hasItem()) { - ContainerLoom.this.d.set(0); - } - - containeraccess.a((world, blockposition) -> { - world.playSound((EntityHuman) null, blockposition, SoundEffects.UI_LOOM_TAKE_RESULT, SoundCategory.BLOCKS, 1.0F, 1.0F); - }); - return super.a(entityhuman, itemstack); - } - }); - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - this.a(this.d); - player = (Player) playerinventory.player.getBukkitEntity(); // CraftBukkit - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return a(this.containerAccess, entityhuman, Blocks.LOOM); - } - - @Override - public boolean a(EntityHuman entityhuman, int i) { - if (i > 0 && i <= EnumBannerPatternType.P) { - this.d.set(i); - this.j(); - return true; - } else { - return false; - } - } - - @Override - public void a(IInventory iinventory) { - ItemStack itemstack = this.f.getItem(); - ItemStack itemstack1 = this.g.getItem(); - ItemStack itemstack2 = this.h.getItem(); - ItemStack itemstack3 = this.i.getItem(); - - if (!itemstack3.isEmpty() && (itemstack.isEmpty() || itemstack1.isEmpty() || this.d.get() <= 0 || this.d.get() >= EnumBannerPatternType.O - 5 && itemstack2.isEmpty())) { - this.i.set(ItemStack.a); - this.d.set(0); - } else if (!itemstack2.isEmpty() && itemstack2.getItem() instanceof ItemBannerPattern) { - NBTTagCompound nbttagcompound = itemstack.a("BlockEntityTag"); - boolean flag = nbttagcompound.hasKeyOfType("Patterns", 9) && !itemstack.isEmpty() && nbttagcompound.getList("Patterns", 10).size() >= 6; - - if (flag) { - this.d.set(0); - } else { - this.d.set(((ItemBannerPattern) itemstack2.getItem()).b().ordinal()); - } - } - - this.j(); - this.c(); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - - itemstack = itemstack1.cloneItemStack(); - if (i == this.i.rawSlotIndex) { - if (!this.a(itemstack1, 4, 40, true)) { - return ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } else if (i != this.g.rawSlotIndex && i != this.f.rawSlotIndex && i != this.h.rawSlotIndex) { - if (itemstack1.getItem() instanceof ItemBanner) { - if (!this.a(itemstack1, this.f.rawSlotIndex, this.f.rawSlotIndex + 1, false)) { - return ItemStack.a; - } - } else if (itemstack1.getItem() instanceof ItemDye) { - if (!this.a(itemstack1, this.g.rawSlotIndex, this.g.rawSlotIndex + 1, false)) { - return ItemStack.a; - } - } else if (itemstack1.getItem() instanceof ItemBannerPattern) { - if (!this.a(itemstack1, this.h.rawSlotIndex, this.h.rawSlotIndex + 1, false)) { - return ItemStack.a; - } - } else if (i >= 4 && i < 31) { - if (!this.a(itemstack1, 31, 40, false)) { - return ItemStack.a; - } - } else if (i >= 31 && i < 40 && !this.a(itemstack1, 4, 31, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 4, 40, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - } - - return itemstack; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.containerAccess.a((world, blockposition) -> { - this.a(entityhuman, entityhuman.world, this.craftInventory); - }); - } - - private void j() { - if (this.d.get() > 0) { - ItemStack itemstack = this.f.getItem(); - ItemStack itemstack1 = this.g.getItem(); - ItemStack itemstack2 = ItemStack.a; - - if (!itemstack.isEmpty() && !itemstack1.isEmpty()) { - itemstack2 = itemstack.cloneItemStack(); - itemstack2.setCount(1); - EnumBannerPatternType enumbannerpatterntype = EnumBannerPatternType.values()[this.d.get()]; - EnumColor enumcolor = ((ItemDye) itemstack1.getItem()).d(); - NBTTagCompound nbttagcompound = itemstack2.a("BlockEntityTag"); - NBTTagList nbttaglist; - - if (nbttagcompound.hasKeyOfType("Patterns", 9)) { - nbttaglist = nbttagcompound.getList("Patterns", 10); - // CraftBukkit start - while (nbttaglist.size() > 20) { - nbttaglist.remove(20); - } - // CraftBukkit end - } else { - nbttaglist = new NBTTagList(); - nbttagcompound.set("Patterns", nbttaglist); - } - - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - nbttagcompound1.setString("Pattern", enumbannerpatterntype.b()); - nbttagcompound1.setInt("Color", enumcolor.getColorIndex()); - nbttaglist.add(nbttagcompound1); - } - - if (!ItemStack.matches(itemstack2, this.i.getItem())) { - this.i.set(itemstack2); - } - } - - } -} diff --git a/src/main/java/net/minecraft/server/ContainerMerchant.java b/src/main/java/net/minecraft/server/ContainerMerchant.java deleted file mode 100644 index b6b62ac53..000000000 --- a/src/main/java/net/minecraft/server/ContainerMerchant.java +++ /dev/null @@ -1,212 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.craftbukkit.inventory.CraftInventoryView; // CraftBukkit - -public class ContainerMerchant extends Container { - - private final IMerchant merchant; - private final InventoryMerchant inventoryMerchant; - - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private PlayerInventory player; - - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity == null) { - bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), new org.bukkit.craftbukkit.inventory.CraftInventoryMerchant(merchant, inventoryMerchant), this); - } - return bukkitEntity; - } - // CraftBukkit end - - public ContainerMerchant(int i, PlayerInventory playerinventory) { - this(i, playerinventory, new MerchantWrapper(playerinventory.player)); - } - - public ContainerMerchant(int i, PlayerInventory playerinventory, IMerchant imerchant) { - super(Containers.MERCHANT, i); - this.merchant = imerchant; - this.inventoryMerchant = new InventoryMerchant(imerchant); - this.a(new Slot(this.inventoryMerchant, 0, 136, 37)); - this.a(new Slot(this.inventoryMerchant, 1, 162, 37)); - this.a((Slot) (new SlotMerchantResult(playerinventory.player, imerchant, this.inventoryMerchant, 2, 220, 37))); - this.player = playerinventory; // CraftBukkit - save player - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 108 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 108 + j * 18, 142)); - } - - } - - @Override - public void a(IInventory iinventory) { - this.inventoryMerchant.f(); - super.a(iinventory); - } - - public void d(int i) { - this.inventoryMerchant.c(i); - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - return this.merchant.getTrader() == entityhuman; - } - - @Override - public boolean a(ItemStack itemstack, Slot slot) { - return false; - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.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 ItemStack.a; - } - - slot.a(itemstack1, itemstack); - this.k(); - } else if (i != 0 && i != 1) { - if (i >= 3 && i < 30) { - if (!this.a(itemstack1, 30, 39, false)) { - return ItemStack.a; - } - } else if (i >= 30 && i < 39 && !this.a(itemstack1, 3, 30, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 3, 39, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - } - - return itemstack; - } - - private void k() { - if (!this.merchant.getWorld().isClientSide && this.merchant instanceof Entity) { // CraftBukkit - SPIGOT-5035 - Entity entity = (Entity) this.merchant; - - this.merchant.getWorld().a(entity.locX, entity.locY, entity.locZ, this.merchant.eb(), SoundCategory.NEUTRAL, 1.0F, 1.0F, false); - } - - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.merchant.setTradingPlayer((EntityHuman) null); - if (!this.merchant.getWorld().isClientSide) { - if (entityhuman.isAlive() && (!(entityhuman instanceof EntityPlayer) || !((EntityPlayer) entityhuman).o())) { - entityhuman.inventory.a(entityhuman.world, this.inventoryMerchant.splitWithoutUpdate(0)); - entityhuman.inventory.a(entityhuman.world, this.inventoryMerchant.splitWithoutUpdate(1)); - } else { - ItemStack itemstack = this.inventoryMerchant.splitWithoutUpdate(0); - - if (!itemstack.isEmpty()) { - entityhuman.drop(itemstack, false); - } - - itemstack = this.inventoryMerchant.splitWithoutUpdate(1); - if (!itemstack.isEmpty()) { - entityhuman.drop(itemstack, false); - } - } - - } - } - - public void g(int i) { - if (this.i().size() > i) { - ItemStack itemstack = this.inventoryMerchant.getItem(0); - - if (!itemstack.isEmpty()) { - if (!this.a(itemstack, 3, 39, true)) { - return; - } - - this.inventoryMerchant.setItem(0, itemstack); - } - - ItemStack itemstack1 = this.inventoryMerchant.getItem(1); - - if (!itemstack1.isEmpty()) { - if (!this.a(itemstack1, 3, 39, true)) { - return; - } - - this.inventoryMerchant.setItem(1, itemstack1); - } - - if (this.inventoryMerchant.getItem(0).isEmpty() && this.inventoryMerchant.getItem(1).isEmpty()) { - ItemStack itemstack2 = ((MerchantRecipe) this.i().get(i)).getBuyItem1(); - - this.c(0, itemstack2); - ItemStack itemstack3 = ((MerchantRecipe) this.i().get(i)).getBuyItem2(); - - this.c(1, itemstack3); - } - - } - } - - private void c(int i, ItemStack itemstack) { - if (!itemstack.isEmpty()) { - for (int j = 3; j < 39; ++j) { - ItemStack itemstack1 = ((Slot) this.slots.get(j)).getItem(); - - if (!itemstack1.isEmpty() && this.b(itemstack, itemstack1)) { - ItemStack itemstack2 = this.inventoryMerchant.getItem(i); - int k = itemstack2.isEmpty() ? 0 : itemstack2.getCount(); - int l = Math.min(itemstack.getMaxStackSize() - k, itemstack1.getCount()); - ItemStack itemstack3 = itemstack1.cloneItemStack(); - int i1 = k + l; - - itemstack1.subtract(l); - itemstack3.setCount(i1); - this.inventoryMerchant.setItem(i, itemstack3); - if (i1 >= itemstack.getMaxStackSize()) { - break; - } - } - } - } - - } - - private boolean b(ItemStack itemstack, ItemStack itemstack1) { - return itemstack.getItem() == itemstack1.getItem() && ItemStack.equals(itemstack, itemstack1); - } - - public MerchantRecipeList i() { - return this.merchant.getOffers(); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerPlayer.java b/src/main/java/net/minecraft/server/ContainerPlayer.java deleted file mode 100644 index e08e542f7..000000000 --- a/src/main/java/net/minecraft/server/ContainerPlayer.java +++ /dev/null @@ -1,216 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -// CraftBukkit end - -public class ContainerPlayer extends ContainerRecipeBook { - - private static final String[] d = new String[]{"item/empty_armor_slot_boots", "item/empty_armor_slot_leggings", "item/empty_armor_slot_chestplate", "item/empty_armor_slot_helmet"}; - private static final EnumItemSlot[] e = new EnumItemSlot[]{EnumItemSlot.HEAD, EnumItemSlot.CHEST, EnumItemSlot.LEGS, EnumItemSlot.FEET}; - // CraftBukkit start - private final InventoryCrafting craftInventory; - private final InventoryCraftResult resultInventory; - // CraftBukkit end - public final boolean c; - private final EntityHuman owner; - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private PlayerInventory player; - // CraftBukkit end - - public ContainerPlayer(PlayerInventory playerinventory, boolean flag, EntityHuman entityhuman) { - super((Containers) null, 0); - this.c = flag; - this.owner = entityhuman; - // CraftBukkit start - 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 - setTitle(new ChatMessage("container.crafting")); // SPIGOT-4722: Allocate title for player inventory - // CraftBukkit end - this.a((Slot) (new SlotResult(playerinventory.player, this.craftInventory, this.resultInventory, 0, 154, 28))); - - int i; - int j; - - for (i = 0; i < 2; ++i) { - for (j = 0; j < 2; ++j) { - this.a(new Slot(this.craftInventory, j + i * 2, 98 + j * 18, 18 + i * 18)); - } - } - - for (i = 0; i < 4; ++i) { - final EnumItemSlot enumitemslot = ContainerPlayer.e[i]; - - this.a(new Slot(playerinventory, 39 - i, 8, 8 + i * 18) { - @Override - public int getMaxStackSize() { - return 1; - } - - @Override - public boolean isAllowed(ItemStack itemstack) { - return enumitemslot == EntityInsentient.h(itemstack); - } - - @Override - public boolean isAllowed(EntityHuman entityhuman1) { - ItemStack itemstack = this.getItem(); - - return !itemstack.isEmpty() && !entityhuman1.isCreative() && EnchantmentManager.d(itemstack) ? false : super.isAllowed(entityhuman1); - } - }); - } - - for (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 (i = 0; i < 9; ++i) { - this.a(new Slot(playerinventory, i, 8 + i * 18, 142)); - } - - this.a(new Slot(playerinventory, 40, 77, 62) { - }); - } - - @Override - public void a(AutoRecipeStackManager autorecipestackmanager) { - this.craftInventory.a(autorecipestackmanager); - } - - @Override - public void e() { - this.resultInventory.clear(); - this.craftInventory.clear(); - } - - @Override - public boolean a(IRecipe irecipe) { - return irecipe.a(this.craftInventory, this.owner.world); - } - - @Override - public void a(IInventory iinventory) { - ContainerWorkbench.a(this.windowId, this.owner.world, this.owner, this.craftInventory, this.resultInventory, this); // CraftBukkit - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.resultInventory.clear(); - if (!entityhuman.world.isClientSide) { - this.a(entityhuman, entityhuman.world, (IInventory) this.craftInventory); - } - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - return true; - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - - itemstack = itemstack1.cloneItemStack(); - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - - if (i == 0) { - if (!this.a(itemstack1, 9, 45, true)) { - return ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } else if (i >= 1 && i < 5) { - if (!this.a(itemstack1, 9, 45, false)) { - return ItemStack.a; - } - } else if (i >= 5 && i < 9) { - if (!this.a(itemstack1, 9, 45, false)) { - return ItemStack.a; - } - } else if (enumitemslot.a() == EnumItemSlot.Function.ARMOR && !((Slot) this.slots.get(8 - enumitemslot.b())).hasItem()) { - int j = 8 - enumitemslot.b(); - - if (!this.a(itemstack1, j, j + 1, false)) { - return ItemStack.a; - } - } else if (enumitemslot == EnumItemSlot.OFFHAND && !((Slot) this.slots.get(45)).hasItem()) { - if (!this.a(itemstack1, 45, 46, false)) { - return ItemStack.a; - } - } else if (i >= 9 && i < 36) { - if (!this.a(itemstack1, 36, 45, false)) { - return ItemStack.a; - } - } else if (i >= 36 && i < 45) { - if (!this.a(itemstack1, 9, 36, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 9, 45, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - ItemStack itemstack2 = slot.a(entityhuman, itemstack1); - - if (i == 0) { - entityhuman.drop(itemstack2, false); - } - } - - return itemstack; - } - - @Override - public boolean a(ItemStack itemstack, Slot slot) { - return slot.inventory != this.resultInventory && super.a(itemstack, slot); - } - - @Override - public int f() { - return 0; - } - - @Override - public int g() { - return this.craftInventory.g(); - } - - @Override - public int h() { - return this.craftInventory.f(); - } - - // CraftBukkit start - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - CraftInventoryCrafting inventory = new CraftInventoryCrafting(this.craftInventory, this.resultInventory); - bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); - return bukkitEntity; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/ContainerShulkerBox.java b/src/main/java/net/minecraft/server/ContainerShulkerBox.java deleted file mode 100644 index 9bfd9af9c..000000000 --- a/src/main/java/net/minecraft/server/ContainerShulkerBox.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftInventory; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -// CraftBukkit end - -public class ContainerShulkerBox extends Container { - - private final IInventory c; - // CraftBukkit start - private CraftInventoryView bukkitEntity; - private PlayerInventory player; - - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), new CraftInventory(this.c), this); - return bukkitEntity; - } - // CraftBukkit end - - public ContainerShulkerBox(int i, PlayerInventory playerinventory) { - this(i, playerinventory, new InventorySubcontainer(27)); - } - - public ContainerShulkerBox(int i, PlayerInventory playerinventory, IInventory iinventory) { - super(Containers.SHULKER_BOX, i); - a(iinventory, 27); - this.c = iinventory; - this.player = playerinventory; // CraftBukkit - save player - iinventory.startOpen(playerinventory.player); - boolean flag = true; - boolean flag1 = true; - - int j; - int k; - - for (j = 0; j < 3; ++j) { - for (k = 0; k < 9; ++k) { - this.a((Slot) (new SlotShulkerBox(iinventory, 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(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - return this.c.a(entityhuman); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - - itemstack = itemstack1.cloneItemStack(); - if (i < this.c.getSize()) { - if (!this.a(itemstack1, this.c.getSize(), this.slots.size(), true)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 0, this.c.getSize(), false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - } - - return itemstack; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.c.closeContainer(entityhuman); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerStonecutter.java b/src/main/java/net/minecraft/server/ContainerStonecutter.java deleted file mode 100644 index e7fdf7273..000000000 --- a/src/main/java/net/minecraft/server/ContainerStonecutter.java +++ /dev/null @@ -1,225 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import java.util.List; -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftInventoryStonecutter; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -import org.bukkit.entity.Player; -// CraftBukkit end - -public class ContainerStonecutter extends Container { - - static final ImmutableList c = ImmutableList.of(Items.b, Items.aq, Items.ge, Items.eq, Items.m, Items.cX, Items.bL, Items.ds, Items.gm, Items.bU, Items.fX, Items.fY, new Item[]{Items.fZ, Items.g, Items.h, Items.c, Items.d, Items.e, Items.f, Items.cY, Items.bO, Items.bJ, Items.bI, Items.bH, Items.dx, Items.dy, Items.bK, Items.as, Items.gg}); - private final ContainerAccess containerAccess; - private final ContainerProperty containerProperty; - private final World world; - private List j; - private ItemStack k; - private long l; - final Slot d; - final Slot e; - private Runnable m; - public final IInventory inventory; - private final InventoryCraftResult resultInventory; - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private Player player; - - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - CraftInventoryStonecutter inventory = new CraftInventoryStonecutter(this.inventory, this.resultInventory); - bukkitEntity = new CraftInventoryView(this.player, inventory, this); - return bukkitEntity; - } - // CraftBukkit end - - public ContainerStonecutter(int i, PlayerInventory playerinventory) { - this(i, playerinventory, ContainerAccess.a); - } - - public ContainerStonecutter(int i, PlayerInventory playerinventory, final ContainerAccess containeraccess) { - super(Containers.STONECUTTER, i); - this.containerProperty = ContainerProperty.a(); - this.j = Lists.newArrayList(); - this.k = ItemStack.a; - this.m = () -> { - }; - this.inventory = new InventorySubcontainer(1) { - @Override - public void update() { - super.update(); - ContainerStonecutter.this.a((IInventory) this); - ContainerStonecutter.this.m.run(); - } - }; - this.resultInventory = new InventoryCraftResult(); - this.containerAccess = containeraccess; - this.world = playerinventory.player.world; - this.d = this.a(new Slot(this.inventory, 0, 20, 33)); - this.e = this.a(new Slot(this.resultInventory, 1, 143, 33) { - @Override - public boolean isAllowed(ItemStack itemstack) { - return false; - } - - @Override - public ItemStack a(EntityHuman entityhuman, ItemStack itemstack) { - ItemStack itemstack1 = ContainerStonecutter.this.d.a(1); - - if (!itemstack1.isEmpty()) { - ContainerStonecutter.this.i(); - } - - itemstack.getItem().b(itemstack, entityhuman.world, entityhuman); - containeraccess.a((world, blockposition) -> { - long j = world.getTime(); - - if (ContainerStonecutter.this.l != j) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.UI_STONECUTTER_TAKE_RESULT, SoundCategory.BLOCKS, 1.0F, 1.0F); - ContainerStonecutter.this.l = j; - } - - }); - return super.a(entityhuman, itemstack); - } - }); - - int j; - - for (j = 0; j < 3; ++j) { - for (int k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - this.a(this.containerProperty); - player = (Player) playerinventory.player.getBukkitEntity(); // CraftBukkit - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return a(this.containerAccess, entityhuman, Blocks.STONECUTTER); - } - - @Override - public boolean a(EntityHuman entityhuman, int i) { - if (i >= 0 && i < this.j.size()) { - this.containerProperty.set(i); - this.i(); - } - - return true; - } - - @Override - public void a(IInventory iinventory) { - ItemStack itemstack = this.d.getItem(); - - if (itemstack.getItem() != this.k.getItem()) { - this.k = itemstack.cloneItemStack(); - this.a(iinventory, itemstack); - } - - } - - private void a(IInventory iinventory, ItemStack itemstack) { - this.j.clear(); - this.containerProperty.set(-1); - this.e.set(ItemStack.a); - if (!itemstack.isEmpty()) { - this.j = this.world.getCraftingManager().b(Recipes.STONECUTTING, iinventory, this.world); - } - - } - - private void i() { - if (!this.j.isEmpty()) { - RecipeStonecutting recipestonecutting = (RecipeStonecutting) this.j.get(this.containerProperty.get()); - - this.e.set(recipestonecutting.a(this.inventory)); - } else { - this.e.set(ItemStack.a); - } - - this.c(); - } - - @Override - public Containers getType() { - return Containers.STONECUTTER; - } - - @Override - public boolean a(ItemStack itemstack, Slot slot) { - return false; - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - Item item = itemstack1.getItem(); - - itemstack = itemstack1.cloneItemStack(); - if (i == 1) { - item.b(itemstack1, entityhuman.world, entityhuman); - if (!this.a(itemstack1, 2, 38, true)) { - return ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } else if (i == 0) { - if (!this.a(itemstack1, 2, 38, false)) { - return ItemStack.a; - } - } else if (ContainerStonecutter.c.contains(item)) { - if (!this.a(itemstack1, 0, 1, false)) { - return ItemStack.a; - } - } else if (i >= 2 && i < 29) { - if (!this.a(itemstack1, 29, 38, false)) { - return ItemStack.a; - } - } else if (i >= 29 && i < 38 && !this.a(itemstack1, 2, 29, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } - - slot.d(); - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - slot.a(entityhuman, itemstack1); - this.c(); - } - - return itemstack; - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.resultInventory.splitWithoutUpdate(1); - this.containerAccess.a((world, blockposition) -> { - this.a(entityhuman, entityhuman.world, this.inventory); - }); - } -} diff --git a/src/main/java/net/minecraft/server/ContainerWorkbench.java b/src/main/java/net/minecraft/server/ContainerWorkbench.java deleted file mode 100644 index 035a45f44..000000000 --- a/src/main/java/net/minecraft/server/ContainerWorkbench.java +++ /dev/null @@ -1,196 +0,0 @@ -package net.minecraft.server; - -import java.util.Optional; -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -// CraftBukkit end - -public class ContainerWorkbench extends ContainerRecipeBook { - - private final InventoryCrafting craftInventory; - private final InventoryCraftResult resultInventory; - public final ContainerAccess containerAccess; - private final EntityHuman f; - // CraftBukkit start - private CraftInventoryView bukkitEntity = null; - private PlayerInventory player; - // CraftBukkit end - - public ContainerWorkbench(int i, PlayerInventory playerinventory) { - this(i, playerinventory, ContainerAccess.a); - } - - public ContainerWorkbench(int i, PlayerInventory playerinventory, ContainerAccess containeraccess) { - super(Containers.CRAFTING, i); - // 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.containerAccess = containeraccess; - this.f = playerinventory.player; - this.a((Slot) (new SlotResult(playerinventory.player, this.craftInventory, this.resultInventory, 0, 124, 35))); - - int j; - int k; - - for (j = 0; j < 3; ++j) { - for (k = 0; k < 3; ++k) { - this.a(new Slot(this.craftInventory, k + j * 3, 30 + k * 18, 17 + j * 18)); - } - } - - for (j = 0; j < 3; ++j) { - for (k = 0; k < 9; ++k) { - this.a(new Slot(playerinventory, k + j * 9 + 9, 8 + k * 18, 84 + j * 18)); - } - } - - for (j = 0; j < 9; ++j) { - this.a(new Slot(playerinventory, j, 8 + j * 18, 142)); - } - - } - - protected static void a(int i, World world, EntityHuman entityhuman, InventoryCrafting inventorycrafting, InventoryCraftResult inventorycraftresult, Container container) { // CraftBukkit - if (!world.isClientSide) { - EntityPlayer entityplayer = (EntityPlayer) entityhuman; - ItemStack itemstack = ItemStack.a; - Optional optional = world.getMinecraftServer().getCraftingManager().craft(Recipes.CRAFTING, inventorycrafting, world); - - if (optional.isPresent()) { - RecipeCrafting recipecrafting = (RecipeCrafting) optional.get(); - - if (inventorycraftresult.a(world, entityplayer, recipecrafting)) { - itemstack = recipecrafting.a(inventorycrafting); - } - } - itemstack = org.bukkit.craftbukkit.event.CraftEventFactory.callPreCraftEvent(inventorycrafting, inventorycraftresult, itemstack, container.getBukkitView(), false); // CraftBukkit - - inventorycraftresult.setItem(0, itemstack); - entityplayer.playerConnection.sendPacket(new PacketPlayOutSetSlot(i, 0, itemstack)); - } - } - - @Override - public void a(IInventory iinventory) { - this.containerAccess.a((world, blockposition) -> { - a(this.windowId, world, this.f, this.craftInventory, this.resultInventory, this); // CraftBukkit - }); - } - - @Override - public void a(AutoRecipeStackManager autorecipestackmanager) { - this.craftInventory.a(autorecipestackmanager); - } - - @Override - public void e() { - this.craftInventory.clear(); - this.resultInventory.clear(); - } - - @Override - public boolean a(IRecipe irecipe) { - return irecipe.a(this.craftInventory, this.f.world); - } - - @Override - public void b(EntityHuman entityhuman) { - super.b(entityhuman); - this.containerAccess.a((world, blockposition) -> { - this.a(entityhuman, world, (IInventory) this.craftInventory); - }); - } - - @Override - public boolean canUse(EntityHuman entityhuman) { - if (!this.checkReachable) return true; // CraftBukkit - return a(this.containerAccess, entityhuman, Blocks.CRAFTING_TABLE); - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - ItemStack itemstack = ItemStack.a; - Slot slot = (Slot) this.slots.get(i); - - if (slot != null && slot.hasItem()) { - ItemStack itemstack1 = slot.getItem(); - - itemstack = itemstack1.cloneItemStack(); - if (i == 0) { - this.containerAccess.a((world, blockposition) -> { - itemstack1.getItem().b(itemstack1, world, entityhuman); - }); - if (!this.a(itemstack1, 10, 46, true)) { - return ItemStack.a; - } - - slot.a(itemstack1, itemstack); - } else if (i >= 10 && i < 37) { - if (!this.a(itemstack1, 37, 46, false)) { - return ItemStack.a; - } - } else if (i >= 37 && i < 46) { - if (!this.a(itemstack1, 10, 37, false)) { - return ItemStack.a; - } - } else if (!this.a(itemstack1, 10, 46, false)) { - return ItemStack.a; - } - - if (itemstack1.isEmpty()) { - slot.set(ItemStack.a); - } else { - slot.d(); - } - - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.a; - } - - ItemStack itemstack2 = slot.a(entityhuman, itemstack1); - - if (i == 0) { - entityhuman.drop(itemstack2, false); - } - } - - return itemstack; - } - - @Override - public boolean a(ItemStack itemstack, Slot slot) { - return slot.inventory != this.resultInventory && super.a(itemstack, slot); - } - - @Override - public int f() { - return 0; - } - - @Override - public int g() { - return this.craftInventory.g(); - } - - @Override - public int h() { - return this.craftInventory.f(); - } - - // CraftBukkit start - @Override - public CraftInventoryView getBukkitView() { - if (bukkitEntity != null) { - return bukkitEntity; - } - - CraftInventoryCrafting inventory = new CraftInventoryCrafting(this.craftInventory, this.resultInventory); - bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); - return bukkitEntity; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/Containers.java b/src/main/java/net/minecraft/server/Containers.java deleted file mode 100644 index 387fb9215..000000000 --- a/src/main/java/net/minecraft/server/Containers.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.minecraft.server; - -public class Containers { - - public static final Containers GENERIC_9X1 = a("generic_9x1", ContainerChest::a); - public static final Containers GENERIC_9X2 = a("generic_9x2", ContainerChest::b); - public static final Containers GENERIC_9X3 = a("generic_9x3", ContainerChest::c); - public static final Containers GENERIC_9X4 = a("generic_9x4", ContainerChest::d); - public static final Containers GENERIC_9X5 = a("generic_9x5", ContainerChest::e); - public static final Containers GENERIC_9X6 = a("generic_9x6", ContainerChest::f); - public static final Containers GENERIC_3X3 = a("generic_3x3", ContainerDispenser::new); - public static final Containers ANVIL = a("anvil", ContainerAnvil::new); - public static final Containers BEACON = a("beacon", ContainerBeacon::new); - public static final Containers BLAST_FURNACE = a("blast_furnace", ContainerBlastFurnace::new); - public static final Containers BREWING_STAND = a("brewing_stand", ContainerBrewingStand::new); - public static final Containers CRAFTING = a("crafting", ContainerWorkbench::new); - public static final Containers ENCHANTMENT = a("enchantment", ContainerEnchantTable::new); - public static final Containers FURNACE = a("furnace", ContainerFurnaceFurnace::new); - public static final Containers GRINDSTONE = a("grindstone", ContainerGrindstone::new); - public static final Containers HOPPER = a("hopper", ContainerHopper::new); - public static final Containers LECTERN = a("lectern", (i, playerinventory) -> { - return new ContainerLectern(i, playerinventory); // CraftBukkit - }); - public static final Containers LOOM = a("loom", ContainerLoom::new); - public static final Containers MERCHANT = a("merchant", ContainerMerchant::new); - public static final Containers SHULKER_BOX = a("shulker_box", ContainerShulkerBox::new); - public static final Containers SMOKER = a("smoker", ContainerSmoker::new); - public static final Containers CARTOGRAPHY = a("cartography", ContainerCartography::new); - public static final Containers STONECUTTER = a("stonecutter", ContainerStonecutter::new); - private final Containers.Supplier x; - - private static Containers a(String s, Containers.Supplier containers_supplier) { - return (Containers) IRegistry.a(IRegistry.MENU, s, (new Containers<>(containers_supplier))); // CraftBukkit - decompile error - } - - private Containers(Containers.Supplier containers_supplier) { - this.x = containers_supplier; - } - - // CraftBukkit start - interface Supplier { - - T supply(int id, PlayerInventory playerinventory); - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/ControllerJump.java b/src/main/java/net/minecraft/server/ControllerJump.java deleted file mode 100644 index 8a6856e0f..000000000 --- a/src/main/java/net/minecraft/server/ControllerJump.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.minecraft.server; - -public class ControllerJump { - - private final EntityInsentient b; - protected boolean a; - - public ControllerJump(EntityInsentient entityinsentient) { - this.b = entityinsentient; - } - - public void jump() { - this.a = true; - } - - public void jumpIfSet() { this.b(); } // Paper - OBFHELPER - public void b() { - this.b.setJumping(this.a); - this.a = false; - } -} diff --git a/src/main/java/net/minecraft/server/CraftingManager.java b/src/main/java/net/minecraft/server/CraftingManager.java deleted file mode 100644 index 6fb734c64..000000000 --- a/src/main/java/net/minecraft/server/CraftingManager.java +++ /dev/null @@ -1,152 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.collect.ImmutableMap.Builder; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; // CraftBukkit - -public class CraftingManager extends ResourceDataJson { - - private static final Gson a = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create(); - private static final Logger LOGGER = LogManager.getLogger(); - public Map, Object2ObjectLinkedOpenHashMap>> recipes = ImmutableMap.of(); // CraftBukkit - private boolean d; - - public CraftingManager() { - super(CraftingManager.a, "recipes"); - } - - protected void a(Map map, IResourceManager iresourcemanager, GameProfilerFiller gameprofilerfiller) { - this.d = false; - Map, Object2ObjectLinkedOpenHashMap>> map1 = Maps.newHashMap(); // CraftBukkit - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - MinecraftKey minecraftkey = (MinecraftKey) entry.getKey(); - - try { - IRecipe irecipe = a(minecraftkey, (JsonObject) entry.getValue()); - - // CraftBukkit start - SPIGOT-4638: last recipe gets priority - (map1.computeIfAbsent(irecipe.g(), (recipes) -> { - return new Object2ObjectLinkedOpenHashMap<>(); - })).putAndMoveToFirst(minecraftkey, irecipe); - // CraftBukkit end - } catch (IllegalArgumentException | JsonParseException jsonparseexception) { - CraftingManager.LOGGER.error("Parsing error loading recipe {}", minecraftkey, jsonparseexception); - } - } - - this.recipes = (Map) map1.entrySet().stream().collect(ImmutableMap.toImmutableMap(Entry::getKey, (entry1) -> { - return entry1.getValue(); // CraftBukkit // Paper - decompile fix - *shrugs internally* - })); - CraftingManager.LOGGER.info("Loaded {} recipes", map1.size()); - } - - // CraftBukkit start - public void addRecipe(IRecipe irecipe) { - org.spigotmc.AsyncCatcher.catchOp("Recipe Add"); // Spigot - Object2ObjectLinkedOpenHashMap> map = this.recipes.get(irecipe.g()); // CraftBukkit - - if (map.containsKey(irecipe.getKey())) { - throw new IllegalStateException("Duplicate recipe ignored with ID " + irecipe.getKey()); - } else { - map.putAndMoveToFirst(irecipe.getKey(), irecipe); // CraftBukkit - SPIGOT-4638: last recipe gets priority - } - } - // CraftBukkit end - - public > Optional craft(Recipes recipes, C c0, World world) { - // CraftBukkit start - Optional recipe = this.a(recipes).values().stream().flatMap((irecipe) -> { - return SystemUtils.a(recipes.a(irecipe, world, c0)); - }).findFirst(); - c0.setCurrentRecipe(recipe.orElse(null)); // CraftBukkit - Clear recipe when no recipe is found - // CraftBukkit end - return recipe; - } - - public > List b(Recipes recipes, C c0, World world) { - return (List) this.a(recipes).values().stream().flatMap((irecipe) -> { - return SystemUtils.a(recipes.a(irecipe, world, c0)); - }).sorted(Comparator.comparing((irecipe) -> { - return irecipe.c().j(); - })).collect(Collectors.toList()); - } - - private > Map> a(Recipes recipes) { - return (Map) this.recipes.getOrDefault(recipes, new Object2ObjectLinkedOpenHashMap<>()); // CraftBukkit - } - - public > NonNullList c(Recipes recipes, C c0, World world) { - Optional optional = this.craft(recipes, c0, world); - - if (optional.isPresent()) { - return ((IRecipe) optional.get()).b(c0); - } else { - NonNullList nonnulllist = NonNullList.a(c0.getSize(), ItemStack.a); - - for (int i = 0; i < nonnulllist.size(); ++i) { - nonnulllist.set(i, c0.getItem(i)); - } - - return nonnulllist; - } - } - - public Optional> a(MinecraftKey minecraftkey) { - return this.recipes.values().stream().map((map) -> { - return map.get(minecraftkey); // CraftBukkit - decompile error - }).filter(Objects::nonNull).findFirst(); - } - - public Collection> b() { - return (Collection) this.recipes.values().stream().flatMap((map) -> { - return map.values().stream(); - }).collect(Collectors.toSet()); - } - - public Stream c() { - return this.recipes.values().stream().flatMap((map) -> { - return map.keySet().stream(); - }); - } - - public static IRecipe a(MinecraftKey minecraftkey, JsonObject jsonobject) { - String s = ChatDeserializer.h(jsonobject, "type"); - - return ((RecipeSerializer) IRegistry.RECIPE_SERIALIZER.getOptional(new MinecraftKey(s)).orElseThrow(() -> { - return new JsonSyntaxException("Invalid or unsupported recipe type '" + s + "'"); - })).a(minecraftkey, jsonobject); - } - - // CraftBukkit start - public void clearRecipes() { - this.recipes = Maps.newHashMap(); - - for (Recipes recipeType : IRegistry.RECIPE_TYPE) { - this.recipes.put(recipeType, new Object2ObjectLinkedOpenHashMap<>()); - } - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/CrashReport.java b/src/main/java/net/minecraft/server/CrashReport.java deleted file mode 100644 index d691a6e66..000000000 --- a/src/main/java/net/minecraft/server/CrashReport.java +++ /dev/null @@ -1,274 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.CompletionException; -import java.util.stream.Collectors; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class CrashReport { - - private static final Logger LOGGER = 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", () -> { - return SharedConstants.a().getName(); - }); - this.d.a("Minecraft Version ID", () -> { - return SharedConstants.a().getId(); - }); - this.d.a("Operating System", () -> { - return System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"); - }); - this.d.a("Java Version", () -> { - return System.getProperty("java.version") + ", " + System.getProperty("java.vendor"); - }); - this.d.a("Java VM Version", () -> { - return System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"); - }); - this.d.a("Memory", () -> { - 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)"; - }); - this.d.a("CPUs", (Object) Runtime.getRuntime().availableProcessors()); - this.d.a("JVM Flags", () -> { - List list = (List) SystemUtils.h().collect(Collectors.toList()); - - return String.format("%d total; %s", list.size(), list.stream().collect(Collectors.joining(" "))); - }); - this.d.a("CraftBukkit Information", (CrashReportCallable) 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 = (StackTraceElement[]) ArrayUtils.subarray(((CrashReportSystemDetails) this.e.get(0)).a(), 0, 1); - } - - if (this.h != null && this.h.length > 0) { - stringbuilder.append("-- Head --\n"); - stringbuilder.append("Thread: ").append(Thread.currentThread().getName()).append("\n"); - stringbuilder.append("Stacktrace:\n"); - StackTraceElement[] astacktraceelement = this.h; - int i = astacktraceelement.length; - - for (int j = 0; j < i; ++j) { - StackTraceElement stacktraceelement = astacktraceelement[j]; - - stringbuilder.append("\t").append("at ").append(stacktraceelement); - stringbuilder.append("\n"); - } - - stringbuilder.append("\n"); - } - - Iterator iterator = this.e.iterator(); - - while (iterator.hasNext()) { - CrashReportSystemDetails crashreportsystemdetails = (CrashReportSystemDetails) iterator.next(); - - crashreportsystemdetails.a(stringbuilder); - stringbuilder.append("\n\n"); - } - - this.d.a(stringbuilder); - } - - public String d() { - StringWriter stringwriter = null; - PrintWriter printwriter = null; - Object object = this.c; - - if (((Throwable) 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); - } - - ((Throwable) object).setStackTrace(this.c.getStackTrace()); - } - - String s; - - try { - stringwriter = new StringWriter(); - printwriter = new PrintWriter(stringwriter); - ((Throwable) object).printStackTrace(printwriter); - s = stringwriter.toString(); - } finally { - IOUtils.closeQuietly(stringwriter); - IOUtils.closeQuietly(printwriter); - } - - return s; - } - - 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(); - } - - OutputStreamWriter outputstreamwriter = null; - - boolean flag; - - try { - outputstreamwriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8); - outputstreamwriter.write(this.e()); - this.f = file; - boolean flag1 = true; - - return flag1; - } catch (Throwable throwable) { - CrashReport.LOGGER.error("Could not save crash report to {}", file, throwable); - flag = false; - } finally { - IOUtils.closeQuietly(outputstreamwriter); - } - - return flag; - } - } - - 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 (astacktraceelement != null && 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 = (CrashReportSystemDetails) this.e.get(this.e.size() - 1); - - crashreportsystemdetails1.b(j); - } else if (astacktraceelement != null && 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) (SystemUtils.getMonotonicNanos() % (long) astring.length)]; - } catch (Throwable throwable) { - return "Witty comment unavailable :("; - } - } - - public static CrashReport a(Throwable throwable, String s) { - while (throwable instanceof CompletionException && throwable.getCause() != null) { - throwable = throwable.getCause(); - } - - CrashReport crashreport; - - if (throwable instanceof ReportedException) { - crashreport = ((ReportedException) throwable).a(); - } else { - crashreport = new CrashReport(s, throwable); - } - - return crashreport; - } -} diff --git a/src/main/java/net/minecraft/server/CustomFunction.java b/src/main/java/net/minecraft/server/CustomFunction.java deleted file mode 100644 index 49de6e997..000000000 --- a/src/main/java/net/minecraft/server/CustomFunction.java +++ /dev/null @@ -1,172 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.brigadier.ParseResults; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import java.util.ArrayDeque; -import java.util.List; -import java.util.Optional; -import javax.annotation.Nullable; - -public class CustomFunction { - - private final CustomFunction.c[] a; - private final MinecraftKey b; - // Paper start - public co.aikar.timings.Timing timing; - public co.aikar.timings.Timing getTiming() { - if (timing == null) { - timing = co.aikar.timings.MinecraftTimings.getCommandFunctionTiming(this); - } - return timing; - } - // Paper end - - public CustomFunction(MinecraftKey minecraftkey, CustomFunction.c[] acustomfunction_c) { - this.b = minecraftkey; - this.a = acustomfunction_c; - } - - public MinecraftKey getMinecraftKey() { return this.a(); } // Paper - OBFHELPER - public MinecraftKey a() { - return this.b; - } - - public CustomFunction.c[] b() { - return this.a; - } - - public static CustomFunction a(MinecraftKey minecraftkey, CustomFunctionData customfunctiondata, List list) { - List list1 = Lists.newArrayListWithCapacity(list.size()); - - for (int i = 0; i < list.size(); ++i) { - int j = i + 1; - String s = ((String) list.get(i)).trim(); - StringReader stringreader = new StringReader(s); - - if (stringreader.canRead() && stringreader.peek() != '#') { - if (stringreader.peek() == '/') { - stringreader.skip(); - if (stringreader.peek() == '/') { - throw new IllegalArgumentException("Unknown or invalid command '" + s + "' on line " + j + " (if you intended to make a comment, use '#' not '//')"); - } - - String s1 = stringreader.readUnquotedString(); - - throw new IllegalArgumentException("Unknown or invalid command '" + s + "' on line " + j + " (did you mean '" + s1 + "'? Do not use a preceding forwards slash.)"); - } - - try { - ParseResults parseresults = customfunctiondata.d().parse(stringreader, customfunctiondata.g()); // CraftBukkit - - if (parseresults.getReader().canRead()) { - if (parseresults.getExceptions().size() == 1) { - throw (CommandSyntaxException) parseresults.getExceptions().values().iterator().next(); - } - - if (parseresults.getContext().getRange().isEmpty()) { - throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(parseresults.getReader()); - } - - throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(parseresults.getReader()); - } - - list1.add(new CustomFunction.b(parseresults)); - } catch (CommandSyntaxException commandsyntaxexception) { - throw new IllegalArgumentException("Whilst parsing command on line " + j + ": " + commandsyntaxexception.getMessage()); - } - } - } - - return new CustomFunction(minecraftkey, (CustomFunction.c[]) list1.toArray(new CustomFunction.c[0])); - } - - public static class a { - - public static final CustomFunction.a a = new CustomFunction.a((MinecraftKey) null); - @Nullable - private final MinecraftKey b; - private boolean c; - private Optional d = Optional.empty(); - - public a(@Nullable MinecraftKey minecraftkey) { - this.b = minecraftkey; - } - - public a(CustomFunction customfunction) { - this.c = true; - this.b = null; - this.d = Optional.of(customfunction); - } - - public Optional a(CustomFunctionData customfunctiondata) { - if (!this.c) { - if (this.b != null) { - this.d = customfunctiondata.a(this.b); - } - - this.c = true; - } - - return this.d; - } - - @Nullable - public MinecraftKey a() { - return (MinecraftKey) this.d.map((customfunction) -> { - return customfunction.b; - }).orElse(this.b); - } - } - - public static class d implements CustomFunction.c { - - private final CustomFunction.a a; - - public d(CustomFunction customfunction) { - this.a = new CustomFunction.a(customfunction); - } - - @Override - public void a(CustomFunctionData customfunctiondata, CommandListenerWrapper commandlistenerwrapper, ArrayDeque arraydeque, int i) { - this.a.a(customfunctiondata).ifPresent((customfunction) -> { - CustomFunction.c[] acustomfunction_c = customfunction.b(); - int j = i - arraydeque.size(); - int k = Math.min(acustomfunction_c.length, j); - - for (int l = k - 1; l >= 0; --l) { - arraydeque.addFirst(new CustomFunctionData.a(customfunctiondata, commandlistenerwrapper, acustomfunction_c[l])); - } - - }); - } - - public String toString() { - return "function " + this.a.a(); - } - } - - public static class b implements CustomFunction.c { - - private final ParseResults a; - - public b(ParseResults parseresults) { - this.a = parseresults; - } - - @Override - public void a(CustomFunctionData customfunctiondata, CommandListenerWrapper commandlistenerwrapper, ArrayDeque arraydeque, int i) throws CommandSyntaxException { - customfunctiondata.d().execute(new ParseResults(this.a.getContext().withSource(commandlistenerwrapper), this.a.getReader(), this.a.getExceptions())); - } - - public String toString() { - return this.a.getReader().getString(); - } - } - - public interface c { - - void a(CustomFunctionData customfunctiondata, CommandListenerWrapper commandlistenerwrapper, ArrayDeque arraydeque, int i) throws CommandSyntaxException; - } -} diff --git a/src/main/java/net/minecraft/server/CustomFunctionData.java b/src/main/java/net/minecraft/server/CustomFunctionData.java deleted file mode 100644 index 721839b4c..000000000 --- a/src/main/java/net/minecraft/server/CustomFunctionData.java +++ /dev/null @@ -1,269 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayDeque; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import javax.annotation.Nullable; -import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class CustomFunctionData implements IResourcePackListener { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final MinecraftKey d = new MinecraftKey("tick"); - private static final MinecraftKey e = new MinecraftKey("load"); - public static final int a = "functions/".length(); - public static final int b = ".mcfunction".length(); - private final MinecraftServer server; - private final Map g = Maps.newHashMap(); - private boolean h; - private final ArrayDeque i = new ArrayDeque(); - private final List j = Lists.newArrayList(); - private final Tags k = new Tags<>(this::a, "tags/functions", true, "function"); - private final List l = Lists.newArrayList(); - private boolean m; - - public CustomFunctionData(MinecraftServer minecraftserver) { - this.server = minecraftserver; - } - - public Optional a(MinecraftKey minecraftkey) { - return Optional.ofNullable(this.g.get(minecraftkey)); - } - - public MinecraftServer a() { - return this.server; - } - - public int b() { - return this.server.getGameRules().getInt(GameRules.MAX_COMMAND_CHAIN_LENGTH); - } - - public Map c() { - return this.g; - } - - public com.mojang.brigadier.CommandDispatcher d() { - return this.server.vanillaCommandDispatcher.a(); // CraftBukkit - } - - public void tick() { - GameProfiler gameprofiler = this.server.getMethodProfiler(); - MinecraftKey minecraftkey = CustomFunctionData.d; - - gameprofiler.a(minecraftkey::toString); - Iterator iterator = this.l.iterator(); - - while (iterator.hasNext()) { - CustomFunction customfunction = (CustomFunction) iterator.next(); - - this.a(customfunction, this.f()); - } - - this.server.getMethodProfiler().exit(); - if (this.m) { - this.m = false; - Collection collection = this.h().b(CustomFunctionData.e).a(); - - gameprofiler = this.server.getMethodProfiler(); - minecraftkey = CustomFunctionData.e; - gameprofiler.a(minecraftkey::toString); - Iterator iterator1 = collection.iterator(); - - while (iterator1.hasNext()) { - CustomFunction customfunction1 = (CustomFunction) iterator1.next(); - - this.a(customfunction1, this.f()); - } - - this.server.getMethodProfiler().exit(); - } - - } - - public int a(CustomFunction customfunction, CommandListenerWrapper commandlistenerwrapper) { - int i = this.b(); - - if (this.h) { - if (this.i.size() + this.j.size() < i) { - this.j.add(new CustomFunctionData.a(this, commandlistenerwrapper, new CustomFunction.d(customfunction))); - } - - return 0; - } else { - try (co.aikar.timings.Timing timing = customfunction.getTiming().startTiming()) { // Paper - this.h = true; - int j = 0; - CustomFunction.c[] acustomfunction_c = customfunction.b(); - - int k; - - for (k = acustomfunction_c.length - 1; k >= 0; --k) { - this.i.push(new CustomFunctionData.a(this, commandlistenerwrapper, acustomfunction_c[k])); - } - - while (!this.i.isEmpty()) { - try { - CustomFunctionData.a customfunctiondata_a = (CustomFunctionData.a) this.i.removeFirst(); - - this.server.getMethodProfiler().a(customfunctiondata_a::toString); - customfunctiondata_a.a(this.i, i); - if (!this.j.isEmpty()) { - List list = Lists.reverse(this.j); - ArrayDeque arraydeque = this.i; - - this.i.getClass(); - list.forEach(arraydeque::addFirst); - this.j.clear(); - } - } finally { - this.server.getMethodProfiler().exit(); - } - - ++j; - if (j >= i) { - k = j; - return k; - } - } - - k = j; - return k; - } finally { - this.i.clear(); - this.j.clear(); - this.h = false; - } - } - } - - @Override - public void a(IResourceManager iresourcemanager) { - this.g.clear(); - this.l.clear(); - Collection collection = iresourcemanager.a("functions", (s) -> { - return s.endsWith(".mcfunction"); - }); - List> list = Lists.newArrayList(); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - MinecraftKey minecraftkey = (MinecraftKey) iterator.next(); - String s = minecraftkey.getKey(); - MinecraftKey minecraftkey1 = new MinecraftKey(minecraftkey.getNamespace(), s.substring(CustomFunctionData.a, s.length() - CustomFunctionData.b)); - - list.add(CompletableFuture.supplyAsync(() -> { - return a(iresourcemanager, minecraftkey); - }, Resource.a).thenApplyAsync((list1) -> { - return CustomFunction.a(minecraftkey1, this, list1); - }, this.server.aU()).handle((customfunction, throwable) -> { - return this.a(customfunction, throwable, minecraftkey); - })); - } - - CompletableFuture.allOf((CompletableFuture[]) list.toArray(new CompletableFuture[0])).join(); - if (!this.g.isEmpty()) { - CustomFunctionData.LOGGER.info("Loaded {} custom command functions", this.g.size()); - } - - this.k.a((Map) this.k.a(iresourcemanager, this.server.aU()).join()); - this.l.addAll(this.k.b(CustomFunctionData.d).a()); - this.m = true; - } - - @Nullable - private CustomFunction a(CustomFunction customfunction, @Nullable Throwable throwable, MinecraftKey minecraftkey) { - if (throwable != null) { - CustomFunctionData.LOGGER.error("Couldn't load function at {}", minecraftkey, throwable); - return null; - } else { - Map map = this.g; - - synchronized (this.g) { - this.g.put(customfunction.a(), customfunction); - return customfunction; - } - } - } - - private static List a(IResourceManager iresourcemanager, MinecraftKey minecraftkey) { - try { - IResource iresource = iresourcemanager.a(minecraftkey); - Throwable throwable = null; - - List list; - - try { - list = IOUtils.readLines(iresource.b(), StandardCharsets.UTF_8); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (iresource != null) { - if (throwable != null) { - try { - iresource.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - iresource.close(); - } - } - - } - - return list; - } catch (IOException ioexception) { - throw new CompletionException(ioexception); - } - } - - public CommandListenerWrapper f() { - return this.server.getServerCommandListener().a(2).a(); - } - - public CommandListenerWrapper g() { - return new CommandListenerWrapper(ICommandListener.DUMMY, Vec3D.a, Vec2F.a, (WorldServer) null, this.server.k(), "", new ChatComponentText(""), this.server, (Entity) null); - } - - public Tags h() { - return this.k; - } - - public static class a { - - private final CustomFunctionData a; - private final CommandListenerWrapper b; - private final CustomFunction.c c; - - public a(CustomFunctionData customfunctiondata, CommandListenerWrapper commandlistenerwrapper, CustomFunction.c customfunction_c) { - this.a = customfunctiondata; - this.b = commandlistenerwrapper; - this.c = customfunction_c; - } - - public void a(ArrayDeque arraydeque, int i) { - try { - this.c.a(this.a, this.b, arraydeque, i); - } catch (Throwable throwable) { - ; - } - - } - - public String toString() { - return this.c.toString(); - } - } -} diff --git a/src/main/java/net/minecraft/server/DamageSource.java b/src/main/java/net/minecraft/server/DamageSource.java deleted file mode 100644 index 730a15f33..000000000 --- a/src/main/java/net/minecraft/server/DamageSource.java +++ /dev/null @@ -1,214 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class DamageSource { - - public static final DamageSource FIRE = (new DamageSource("inFire")).setExplosion(); - public static final DamageSource LIGHTNING = new DamageSource("lightningBolt"); - public static final DamageSource BURN = (new DamageSource("onFire")).setIgnoreArmor().setExplosion(); - public static final DamageSource LAVA = (new DamageSource("lava")).setExplosion(); - public static final DamageSource HOT_FLOOR = (new DamageSource("hotFloor")).setExplosion(); - public static final DamageSource STUCK = (new DamageSource("inWall")).setIgnoreArmor(); - public static final DamageSource CRAMMING = (new DamageSource("cramming")).setIgnoreArmor(); - public static final DamageSource DROWN = (new DamageSource("drown")).setIgnoreArmor(); - public static final DamageSource STARVE = (new DamageSource("starve")).setIgnoreArmor().n(); - public static final DamageSource CACTUS = new DamageSource("cactus"); - public static final DamageSource FALL = (new DamageSource("fall")).setIgnoreArmor(); - public static final DamageSource FLY_INTO_WALL = (new DamageSource("flyIntoWall")).setIgnoreArmor(); - public static final DamageSource OUT_OF_WORLD = (new DamageSource("outOfWorld")).setIgnoreArmor().m(); - public static final DamageSource GENERIC = (new DamageSource("generic")).setIgnoreArmor(); - public static final DamageSource MAGIC = (new DamageSource("magic")).setIgnoreArmor().setMagic(); - public static final DamageSource WITHER = (new DamageSource("wither")).setIgnoreArmor(); - public static final DamageSource ANVIL = new DamageSource("anvil"); - public static final DamageSource FALLING_BLOCK = new DamageSource("fallingBlock"); - public static final DamageSource DRAGON_BREATH = (new DamageSource("dragonBreath")).setIgnoreArmor(); - public static final DamageSource FIREWORKS = (new DamageSource("fireworks")).e(); - public static final DamageSource DRYOUT = new DamageSource("dryout"); - public static final DamageSource SWEET_BERRY_BUSH = new DamageSource("sweetBerryBush"); - private boolean x; - private boolean y; - private boolean z; - private float A = 0.1F; - private boolean B; - private boolean C; - private boolean D; - private boolean E; - private boolean F; - public final String translationIndex; - // CraftBukkit start - private boolean sweep; - - public boolean isSweep() { - return sweep; - } - - public DamageSource sweep() { - this.sweep = true; - return this; - } - // CraftBukkit end - - public static DamageSource mobAttack(EntityLiving entityliving) { - return new EntityDamageSource("mob", entityliving); - } - - public static DamageSource a(Entity entity, EntityLiving entityliving) { - return new EntityDamageSourceIndirect("mob", entity, entityliving); - } - - public static DamageSource playerAttack(EntityHuman entityhuman) { - return new EntityDamageSource("player", entityhuman); - } - - public static DamageSource arrow(EntityArrow entityarrow, @Nullable Entity entity) { - return (new EntityDamageSourceIndirect("arrow", entityarrow, entity)).c(); - } - - public static DamageSource a(Entity entity, @Nullable Entity entity1) { - return (new EntityDamageSourceIndirect("trident", entity, entity1)).c(); - } - - public static DamageSource fireball(EntityFireball entityfireball, @Nullable Entity entity) { - return entity == null ? (new EntityDamageSourceIndirect("onFire", entityfireball, entityfireball)).setExplosion().c() : (new EntityDamageSourceIndirect("fireball", entityfireball, entity)).setExplosion().c(); - } - - public static DamageSource projectile(Entity entity, @Nullable Entity entity1) { - return (new EntityDamageSourceIndirect("thrown", entity, entity1)).c(); - } - - public static DamageSource c(Entity entity, @Nullable Entity entity1) { - return (new EntityDamageSourceIndirect("indirectMagic", entity, entity1)).setIgnoreArmor().setMagic(); - } - - public static DamageSource a(Entity entity) { - return (new EntityDamageSource("thorns", entity)).x().setMagic(); - } - - public static DamageSource explosion(@Nullable Explosion explosion) { - return explosion != null && explosion.getSource() != null ? (new EntityDamageSource("explosion.player", explosion.getSource())).r().e() : (new DamageSource("explosion")).r().e(); - } - - public static DamageSource b(@Nullable EntityLiving entityliving) { - return entityliving != null ? (new EntityDamageSource("explosion.player", entityliving)).r().e() : (new DamageSource("explosion")).r().e(); - } - - public static DamageSource a() { - return new DamageSourceNetherBed(); - } - - public boolean b() { - return this.C; - } - - public DamageSource c() { - this.C = true; - return this; - } - - public boolean isExplosion() { - return this.F; - } - - public DamageSource e() { - this.F = true; - return this; - } - - public boolean ignoresArmor() { - return this.x; - } - - public float getExhaustionCost() { - return this.A; - } - - public boolean ignoresInvulnerability() { - return this.y; - } - - public boolean isStarvation() { - return this.z; - } - - protected DamageSource(String s) { - this.translationIndex = s; - } - - @Nullable - public Entity j() { - return this.getEntity(); - } - - @Nullable - public Entity getEntity() { - return null; - } - - protected DamageSource setIgnoreArmor() { - this.x = true; - this.A = 0.0F; - return this; - } - - protected DamageSource m() { - this.y = true; - return this; - } - - protected DamageSource n() { - this.z = true; - this.A = 0.0F; - return this; - } - - protected DamageSource setExplosion() { - this.B = true; - return this; - } - - public IChatBaseComponent getLocalizedDeathMessage(EntityLiving entityliving) { - EntityLiving entityliving1 = entityliving.getKillingEntity(); - String s = "death.attack." + this.translationIndex; - String s1 = s + ".player"; - - return entityliving1 != null ? new ChatMessage(s1, new Object[]{entityliving.getScoreboardDisplayName(), entityliving1.getScoreboardDisplayName()}) : new ChatMessage(s, new Object[]{entityliving.getScoreboardDisplayName()}); - } - - public boolean p() { - return this.B; - } - - public String q() { - return this.translationIndex; - } - - public DamageSource r() { - this.D = true; - return this; - } - - public boolean s() { - return this.D; - } - - public boolean isMagic() { - return this.E; - } - - public DamageSource setMagic() { - this.E = true; - return this; - } - - public boolean v() { - Entity entity = this.getEntity(); - - return entity instanceof EntityHuman && ((EntityHuman) entity).abilities.canInstantlyBuild; - } - - @Nullable - public Vec3D w() { - return null; - } -} diff --git a/src/main/java/net/minecraft/server/DataBits.java b/src/main/java/net/minecraft/server/DataBits.java deleted file mode 100644 index a75b08ee3..000000000 --- a/src/main/java/net/minecraft/server/DataBits.java +++ /dev/null @@ -1,130 +0,0 @@ -package net.minecraft.server; - -import java.util.function.IntConsumer; -import org.apache.commons.lang3.Validate; - -public class DataBits { - - private final long[] a; - private final int b; - private final long c; - private final int d; - - public DataBits(int i, int j) { - this(i, j, new long[MathHelper.c(j * i, 64) / 64]); - } - - public DataBits(int i, int j, long[] along) { - //Validate.inclusiveBetween(1L, 32L, (long) i); // Paper - this.d = j; - this.b = i; - this.a = along; - this.c = (1L << i) - 1L; - int k = MathHelper.c(j * i, 64) / 64; - - if (along.length != k) { - throw new RuntimeException("Invalid length given for storage, got: " + along.length + " but expected: " + k); - } - } - - public int a(int i, int j) { - //Validate.inclusiveBetween(0L, (long) (this.d - 1), (long) i); // Paper - //Validate.inclusiveBetween(0L, this.c, (long) j); // Paper - int k = i * this.b; - int l = k >> 6; - int i1 = (i + 1) * this.b - 1 >> 6; - int j1 = k ^ l << 6; - byte b0 = 0; - int k1 = b0 | (int) (this.a[l] >>> j1 & this.c); - - this.a[l] = this.a[l] & ~(this.c << j1) | ((long) j & this.c) << j1; - if (l != i1) { - int l1 = 64 - j1; - int i2 = this.b - l1; - - k1 |= (int) (this.a[i1] << l1 & this.c); - this.a[i1] = this.a[i1] >>> i2 << i2 | ((long) j & this.c) >> l1; - } - - return k1; - } - - public void b(int i, int j) { - //Validate.inclusiveBetween(0L, (long) (this.d - 1), (long) i); // Paper - //Validate.inclusiveBetween(0L, this.c, (long) j); // Paper - int k = i * this.b; - int l = k >> 6; - int i1 = (i + 1) * this.b - 1 >> 6; - int j1 = k ^ l << 6; - - this.a[l] = this.a[l] & ~(this.c << j1) | ((long) j & this.c) << j1; - if (l != i1) { - int k1 = 64 - j1; - int l1 = this.b - k1; - - this.a[i1] = this.a[i1] >>> l1 << l1 | ((long) j & this.c) >> k1; - } - - } - - public int a(int i) { - //Validate.inclusiveBetween(0L, (long) (this.d - 1), (long) i); // Paper - int j = i * this.b; - int k = j >> 6; - int l = (i + 1) * this.b - 1 >> 6; - int i1 = j ^ k << 6; - - if (k == l) { - return (int) (this.a[k] >>> i1 & this.c); - } else { - int j1 = 64 - i1; - - return (int) ((this.a[k] >>> i1 | this.a[l] << j1) & this.c); - } - } - - public long[] getDataBits() { return this.a(); } // Paper - OBFHELPER - public long[] a() { - return this.a; - } - - public int b() { - return this.d; - } - - public int c() { - return this.b; - } - - public void a(IntConsumer intconsumer) { - int i = this.a.length; - - if (i != 0) { - int j = 0; - long k = this.a[0]; - long l = i > 1 ? this.a[1] : 0L; - - for (int i1 = 0; i1 < this.d; ++i1) { - int j1 = i1 * this.b; - int k1 = j1 >> 6; - int l1 = (i1 + 1) * this.b - 1 >> 6; - int i2 = j1 ^ k1 << 6; - - if (k1 != j) { - k = l; - l = k1 + 1 < i ? this.a[k1 + 1] : 0L; - j = k1; - } - - if (k1 == l1) { - intconsumer.accept((int) (k >>> i2 & this.c)); - } else { - int j2 = 64 - i2; - - intconsumer.accept((int) ((k >>> i2 | l << j2) & this.c)); - } - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/DataConverterFlatten.java b/src/main/java/net/minecraft/server/DataConverterFlatten.java deleted file mode 100644 index e11f8b88b..000000000 --- a/src/main/java/net/minecraft/server/DataConverterFlatten.java +++ /dev/null @@ -1,399 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.mojang.datafixers.DSL; -import com.mojang.datafixers.DataFix; -import com.mojang.datafixers.DataFixUtils; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.OpticFinder; -import com.mojang.datafixers.TypeRewriteRule; -import com.mojang.datafixers.Typed; -import com.mojang.datafixers.schemas.Schema; -import com.mojang.datafixers.types.Type; -import com.mojang.datafixers.util.Pair; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -public class DataConverterFlatten extends DataFix { - - private static final Map a = (Map) DataFixUtils.make(Maps.newHashMap(), (hashmap) -> { - hashmap.put("minecraft:stone.0", "minecraft:stone"); - hashmap.put("minecraft:stone.1", "minecraft:granite"); - hashmap.put("minecraft:stone.2", "minecraft:polished_granite"); - hashmap.put("minecraft:stone.3", "minecraft:diorite"); - hashmap.put("minecraft:stone.4", "minecraft:polished_diorite"); - hashmap.put("minecraft:stone.5", "minecraft:andesite"); - hashmap.put("minecraft:stone.6", "minecraft:polished_andesite"); - hashmap.put("minecraft:dirt.0", "minecraft:dirt"); - hashmap.put("minecraft:dirt.1", "minecraft:coarse_dirt"); - hashmap.put("minecraft:dirt.2", "minecraft:podzol"); - hashmap.put("minecraft:leaves.0", "minecraft:oak_leaves"); - hashmap.put("minecraft:leaves.1", "minecraft:spruce_leaves"); - hashmap.put("minecraft:leaves.2", "minecraft:birch_leaves"); - hashmap.put("minecraft:leaves.3", "minecraft:jungle_leaves"); - hashmap.put("minecraft:leaves2.0", "minecraft:acacia_leaves"); - hashmap.put("minecraft:leaves2.1", "minecraft:dark_oak_leaves"); - hashmap.put("minecraft:log.0", "minecraft:oak_log"); - hashmap.put("minecraft:log.1", "minecraft:spruce_log"); - hashmap.put("minecraft:log.2", "minecraft:birch_log"); - hashmap.put("minecraft:log.3", "minecraft:jungle_log"); - hashmap.put("minecraft:log2.0", "minecraft:acacia_log"); - hashmap.put("minecraft:log2.1", "minecraft:dark_oak_log"); - hashmap.put("minecraft:sapling.0", "minecraft:oak_sapling"); - hashmap.put("minecraft:sapling.1", "minecraft:spruce_sapling"); - hashmap.put("minecraft:sapling.2", "minecraft:birch_sapling"); - hashmap.put("minecraft:sapling.3", "minecraft:jungle_sapling"); - hashmap.put("minecraft:sapling.4", "minecraft:acacia_sapling"); - hashmap.put("minecraft:sapling.5", "minecraft:dark_oak_sapling"); - hashmap.put("minecraft:planks.0", "minecraft:oak_planks"); - hashmap.put("minecraft:planks.1", "minecraft:spruce_planks"); - hashmap.put("minecraft:planks.2", "minecraft:birch_planks"); - hashmap.put("minecraft:planks.3", "minecraft:jungle_planks"); - hashmap.put("minecraft:planks.4", "minecraft:acacia_planks"); - hashmap.put("minecraft:planks.5", "minecraft:dark_oak_planks"); - hashmap.put("minecraft:sand.0", "minecraft:sand"); - hashmap.put("minecraft:sand.1", "minecraft:red_sand"); - hashmap.put("minecraft:quartz_block.0", "minecraft:quartz_block"); - hashmap.put("minecraft:quartz_block.1", "minecraft:chiseled_quartz_block"); - hashmap.put("minecraft:quartz_block.2", "minecraft:quartz_pillar"); - hashmap.put("minecraft:anvil.0", "minecraft:anvil"); - hashmap.put("minecraft:anvil.1", "minecraft:chipped_anvil"); - hashmap.put("minecraft:anvil.2", "minecraft:damaged_anvil"); - hashmap.put("minecraft:wool.0", "minecraft:white_wool"); - hashmap.put("minecraft:wool.1", "minecraft:orange_wool"); - hashmap.put("minecraft:wool.2", "minecraft:magenta_wool"); - hashmap.put("minecraft:wool.3", "minecraft:light_blue_wool"); - hashmap.put("minecraft:wool.4", "minecraft:yellow_wool"); - hashmap.put("minecraft:wool.5", "minecraft:lime_wool"); - hashmap.put("minecraft:wool.6", "minecraft:pink_wool"); - hashmap.put("minecraft:wool.7", "minecraft:gray_wool"); - hashmap.put("minecraft:wool.8", "minecraft:light_gray_wool"); - hashmap.put("minecraft:wool.9", "minecraft:cyan_wool"); - hashmap.put("minecraft:wool.10", "minecraft:purple_wool"); - hashmap.put("minecraft:wool.11", "minecraft:blue_wool"); - hashmap.put("minecraft:wool.12", "minecraft:brown_wool"); - hashmap.put("minecraft:wool.13", "minecraft:green_wool"); - hashmap.put("minecraft:wool.14", "minecraft:red_wool"); - hashmap.put("minecraft:wool.15", "minecraft:black_wool"); - hashmap.put("minecraft:carpet.0", "minecraft:white_carpet"); - hashmap.put("minecraft:carpet.1", "minecraft:orange_carpet"); - hashmap.put("minecraft:carpet.2", "minecraft:magenta_carpet"); - hashmap.put("minecraft:carpet.3", "minecraft:light_blue_carpet"); - hashmap.put("minecraft:carpet.4", "minecraft:yellow_carpet"); - hashmap.put("minecraft:carpet.5", "minecraft:lime_carpet"); - hashmap.put("minecraft:carpet.6", "minecraft:pink_carpet"); - hashmap.put("minecraft:carpet.7", "minecraft:gray_carpet"); - hashmap.put("minecraft:carpet.8", "minecraft:light_gray_carpet"); - hashmap.put("minecraft:carpet.9", "minecraft:cyan_carpet"); - hashmap.put("minecraft:carpet.10", "minecraft:purple_carpet"); - hashmap.put("minecraft:carpet.11", "minecraft:blue_carpet"); - hashmap.put("minecraft:carpet.12", "minecraft:brown_carpet"); - hashmap.put("minecraft:carpet.13", "minecraft:green_carpet"); - hashmap.put("minecraft:carpet.14", "minecraft:red_carpet"); - hashmap.put("minecraft:carpet.15", "minecraft:black_carpet"); - hashmap.put("minecraft:hardened_clay.0", "minecraft:terracotta"); - hashmap.put("minecraft:stained_hardened_clay.0", "minecraft:white_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.1", "minecraft:orange_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.2", "minecraft:magenta_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.3", "minecraft:light_blue_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.4", "minecraft:yellow_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.5", "minecraft:lime_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.6", "minecraft:pink_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.7", "minecraft:gray_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.8", "minecraft:light_gray_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.9", "minecraft:cyan_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.10", "minecraft:purple_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.11", "minecraft:blue_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.12", "minecraft:brown_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.13", "minecraft:green_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.14", "minecraft:red_terracotta"); - hashmap.put("minecraft:stained_hardened_clay.15", "minecraft:black_terracotta"); - hashmap.put("minecraft:silver_glazed_terracotta.0", "minecraft:light_gray_glazed_terracotta"); - hashmap.put("minecraft:stained_glass.0", "minecraft:white_stained_glass"); - hashmap.put("minecraft:stained_glass.1", "minecraft:orange_stained_glass"); - hashmap.put("minecraft:stained_glass.2", "minecraft:magenta_stained_glass"); - hashmap.put("minecraft:stained_glass.3", "minecraft:light_blue_stained_glass"); - hashmap.put("minecraft:stained_glass.4", "minecraft:yellow_stained_glass"); - hashmap.put("minecraft:stained_glass.5", "minecraft:lime_stained_glass"); - hashmap.put("minecraft:stained_glass.6", "minecraft:pink_stained_glass"); - hashmap.put("minecraft:stained_glass.7", "minecraft:gray_stained_glass"); - hashmap.put("minecraft:stained_glass.8", "minecraft:light_gray_stained_glass"); - hashmap.put("minecraft:stained_glass.9", "minecraft:cyan_stained_glass"); - hashmap.put("minecraft:stained_glass.10", "minecraft:purple_stained_glass"); - hashmap.put("minecraft:stained_glass.11", "minecraft:blue_stained_glass"); - hashmap.put("minecraft:stained_glass.12", "minecraft:brown_stained_glass"); - hashmap.put("minecraft:stained_glass.13", "minecraft:green_stained_glass"); - hashmap.put("minecraft:stained_glass.14", "minecraft:red_stained_glass"); - hashmap.put("minecraft:stained_glass.15", "minecraft:black_stained_glass"); - hashmap.put("minecraft:stained_glass_pane.0", "minecraft:white_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.1", "minecraft:orange_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.2", "minecraft:magenta_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.3", "minecraft:light_blue_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.4", "minecraft:yellow_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.5", "minecraft:lime_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.6", "minecraft:pink_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.7", "minecraft:gray_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.8", "minecraft:light_gray_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.9", "minecraft:cyan_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.10", "minecraft:purple_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.11", "minecraft:blue_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.12", "minecraft:brown_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.13", "minecraft:green_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.14", "minecraft:red_stained_glass_pane"); - hashmap.put("minecraft:stained_glass_pane.15", "minecraft:black_stained_glass_pane"); - hashmap.put("minecraft:prismarine.0", "minecraft:prismarine"); - hashmap.put("minecraft:prismarine.1", "minecraft:prismarine_bricks"); - hashmap.put("minecraft:prismarine.2", "minecraft:dark_prismarine"); - hashmap.put("minecraft:concrete.0", "minecraft:white_concrete"); - hashmap.put("minecraft:concrete.1", "minecraft:orange_concrete"); - hashmap.put("minecraft:concrete.2", "minecraft:magenta_concrete"); - hashmap.put("minecraft:concrete.3", "minecraft:light_blue_concrete"); - hashmap.put("minecraft:concrete.4", "minecraft:yellow_concrete"); - hashmap.put("minecraft:concrete.5", "minecraft:lime_concrete"); - hashmap.put("minecraft:concrete.6", "minecraft:pink_concrete"); - hashmap.put("minecraft:concrete.7", "minecraft:gray_concrete"); - hashmap.put("minecraft:concrete.8", "minecraft:light_gray_concrete"); - hashmap.put("minecraft:concrete.9", "minecraft:cyan_concrete"); - hashmap.put("minecraft:concrete.10", "minecraft:purple_concrete"); - hashmap.put("minecraft:concrete.11", "minecraft:blue_concrete"); - hashmap.put("minecraft:concrete.12", "minecraft:brown_concrete"); - hashmap.put("minecraft:concrete.13", "minecraft:green_concrete"); - hashmap.put("minecraft:concrete.14", "minecraft:red_concrete"); - hashmap.put("minecraft:concrete.15", "minecraft:black_concrete"); - hashmap.put("minecraft:concrete_powder.0", "minecraft:white_concrete_powder"); - hashmap.put("minecraft:concrete_powder.1", "minecraft:orange_concrete_powder"); - hashmap.put("minecraft:concrete_powder.2", "minecraft:magenta_concrete_powder"); - hashmap.put("minecraft:concrete_powder.3", "minecraft:light_blue_concrete_powder"); - hashmap.put("minecraft:concrete_powder.4", "minecraft:yellow_concrete_powder"); - hashmap.put("minecraft:concrete_powder.5", "minecraft:lime_concrete_powder"); - hashmap.put("minecraft:concrete_powder.6", "minecraft:pink_concrete_powder"); - hashmap.put("minecraft:concrete_powder.7", "minecraft:gray_concrete_powder"); - hashmap.put("minecraft:concrete_powder.8", "minecraft:light_gray_concrete_powder"); - hashmap.put("minecraft:concrete_powder.9", "minecraft:cyan_concrete_powder"); - hashmap.put("minecraft:concrete_powder.10", "minecraft:purple_concrete_powder"); - hashmap.put("minecraft:concrete_powder.11", "minecraft:blue_concrete_powder"); - hashmap.put("minecraft:concrete_powder.12", "minecraft:brown_concrete_powder"); - hashmap.put("minecraft:concrete_powder.13", "minecraft:green_concrete_powder"); - hashmap.put("minecraft:concrete_powder.14", "minecraft:red_concrete_powder"); - hashmap.put("minecraft:concrete_powder.15", "minecraft:black_concrete_powder"); - hashmap.put("minecraft:cobblestone_wall.0", "minecraft:cobblestone_wall"); - hashmap.put("minecraft:cobblestone_wall.1", "minecraft:mossy_cobblestone_wall"); - hashmap.put("minecraft:sandstone.0", "minecraft:sandstone"); - hashmap.put("minecraft:sandstone.1", "minecraft:chiseled_sandstone"); - hashmap.put("minecraft:sandstone.2", "minecraft:cut_sandstone"); - hashmap.put("minecraft:red_sandstone.0", "minecraft:red_sandstone"); - hashmap.put("minecraft:red_sandstone.1", "minecraft:chiseled_red_sandstone"); - hashmap.put("minecraft:red_sandstone.2", "minecraft:cut_red_sandstone"); - hashmap.put("minecraft:stonebrick.0", "minecraft:stone_bricks"); - hashmap.put("minecraft:stonebrick.1", "minecraft:mossy_stone_bricks"); - hashmap.put("minecraft:stonebrick.2", "minecraft:cracked_stone_bricks"); - hashmap.put("minecraft:stonebrick.3", "minecraft:chiseled_stone_bricks"); - hashmap.put("minecraft:monster_egg.0", "minecraft:infested_stone"); - hashmap.put("minecraft:monster_egg.1", "minecraft:infested_cobblestone"); - hashmap.put("minecraft:monster_egg.2", "minecraft:infested_stone_bricks"); - hashmap.put("minecraft:monster_egg.3", "minecraft:infested_mossy_stone_bricks"); - hashmap.put("minecraft:monster_egg.4", "minecraft:infested_cracked_stone_bricks"); - hashmap.put("minecraft:monster_egg.5", "minecraft:infested_chiseled_stone_bricks"); - hashmap.put("minecraft:yellow_flower.0", "minecraft:dandelion"); - hashmap.put("minecraft:red_flower.0", "minecraft:poppy"); - hashmap.put("minecraft:red_flower.1", "minecraft:blue_orchid"); - hashmap.put("minecraft:red_flower.2", "minecraft:allium"); - hashmap.put("minecraft:red_flower.3", "minecraft:azure_bluet"); - hashmap.put("minecraft:red_flower.4", "minecraft:red_tulip"); - hashmap.put("minecraft:red_flower.5", "minecraft:orange_tulip"); - hashmap.put("minecraft:red_flower.6", "minecraft:white_tulip"); - hashmap.put("minecraft:red_flower.7", "minecraft:pink_tulip"); - hashmap.put("minecraft:red_flower.8", "minecraft:oxeye_daisy"); - hashmap.put("minecraft:double_plant.0", "minecraft:sunflower"); - hashmap.put("minecraft:double_plant.1", "minecraft:lilac"); - hashmap.put("minecraft:double_plant.2", "minecraft:tall_grass"); - hashmap.put("minecraft:double_plant.3", "minecraft:large_fern"); - hashmap.put("minecraft:double_plant.4", "minecraft:rose_bush"); - hashmap.put("minecraft:double_plant.5", "minecraft:peony"); - hashmap.put("minecraft:deadbush.0", "minecraft:dead_bush"); - hashmap.put("minecraft:tallgrass.0", "minecraft:dead_bush"); - hashmap.put("minecraft:tallgrass.1", "minecraft:grass"); - hashmap.put("minecraft:tallgrass.2", "minecraft:fern"); - hashmap.put("minecraft:sponge.0", "minecraft:sponge"); - hashmap.put("minecraft:sponge.1", "minecraft:wet_sponge"); - hashmap.put("minecraft:purpur_slab.0", "minecraft:purpur_slab"); - hashmap.put("minecraft:stone_slab.0", "minecraft:stone_slab"); - hashmap.put("minecraft:stone_slab.1", "minecraft:sandstone_slab"); - hashmap.put("minecraft:stone_slab.2", "minecraft:petrified_oak_slab"); - hashmap.put("minecraft:stone_slab.3", "minecraft:cobblestone_slab"); - hashmap.put("minecraft:stone_slab.4", "minecraft:brick_slab"); - hashmap.put("minecraft:stone_slab.5", "minecraft:stone_brick_slab"); - hashmap.put("minecraft:stone_slab.6", "minecraft:nether_brick_slab"); - hashmap.put("minecraft:stone_slab.7", "minecraft:quartz_slab"); - hashmap.put("minecraft:stone_slab2.0", "minecraft:red_sandstone_slab"); - hashmap.put("minecraft:wooden_slab.0", "minecraft:oak_slab"); - hashmap.put("minecraft:wooden_slab.1", "minecraft:spruce_slab"); - hashmap.put("minecraft:wooden_slab.2", "minecraft:birch_slab"); - hashmap.put("minecraft:wooden_slab.3", "minecraft:jungle_slab"); - hashmap.put("minecraft:wooden_slab.4", "minecraft:acacia_slab"); - hashmap.put("minecraft:wooden_slab.5", "minecraft:dark_oak_slab"); - hashmap.put("minecraft:coal.0", "minecraft:coal"); - hashmap.put("minecraft:coal.1", "minecraft:charcoal"); - hashmap.put("minecraft:fish.0", "minecraft:cod"); - hashmap.put("minecraft:fish.1", "minecraft:salmon"); - hashmap.put("minecraft:fish.2", "minecraft:clownfish"); - hashmap.put("minecraft:fish.3", "minecraft:pufferfish"); - hashmap.put("minecraft:cooked_fish.0", "minecraft:cooked_cod"); - hashmap.put("minecraft:cooked_fish.1", "minecraft:cooked_salmon"); - hashmap.put("minecraft:skull.0", "minecraft:skeleton_skull"); - hashmap.put("minecraft:skull.1", "minecraft:wither_skeleton_skull"); - hashmap.put("minecraft:skull.2", "minecraft:zombie_head"); - hashmap.put("minecraft:skull.3", "minecraft:player_head"); - hashmap.put("minecraft:skull.4", "minecraft:creeper_head"); - hashmap.put("minecraft:skull.5", "minecraft:dragon_head"); - hashmap.put("minecraft:golden_apple.0", "minecraft:golden_apple"); - hashmap.put("minecraft:golden_apple.1", "minecraft:enchanted_golden_apple"); - hashmap.put("minecraft:fireworks.0", "minecraft:firework_rocket"); - hashmap.put("minecraft:firework_charge.0", "minecraft:firework_star"); - hashmap.put("minecraft:dye.0", "minecraft:ink_sac"); - hashmap.put("minecraft:dye.1", "minecraft:rose_red"); - hashmap.put("minecraft:dye.2", "minecraft:cactus_green"); - hashmap.put("minecraft:dye.3", "minecraft:cocoa_beans"); - hashmap.put("minecraft:dye.4", "minecraft:lapis_lazuli"); - hashmap.put("minecraft:dye.5", "minecraft:purple_dye"); - hashmap.put("minecraft:dye.6", "minecraft:cyan_dye"); - hashmap.put("minecraft:dye.7", "minecraft:light_gray_dye"); - hashmap.put("minecraft:dye.8", "minecraft:gray_dye"); - hashmap.put("minecraft:dye.9", "minecraft:pink_dye"); - hashmap.put("minecraft:dye.10", "minecraft:lime_dye"); - hashmap.put("minecraft:dye.11", "minecraft:dandelion_yellow"); - hashmap.put("minecraft:dye.12", "minecraft:light_blue_dye"); - hashmap.put("minecraft:dye.13", "minecraft:magenta_dye"); - hashmap.put("minecraft:dye.14", "minecraft:orange_dye"); - hashmap.put("minecraft:dye.15", "minecraft:bone_meal"); - hashmap.put("minecraft:silver_shulker_box.0", "minecraft:light_gray_shulker_box"); - hashmap.put("minecraft:fence.0", "minecraft:oak_fence"); - hashmap.put("minecraft:fence_gate.0", "minecraft:oak_fence_gate"); - hashmap.put("minecraft:wooden_door.0", "minecraft:oak_door"); - hashmap.put("minecraft:boat.0", "minecraft:oak_boat"); - hashmap.put("minecraft:lit_pumpkin.0", "minecraft:jack_o_lantern"); - hashmap.put("minecraft:pumpkin.0", "minecraft:carved_pumpkin"); - hashmap.put("minecraft:trapdoor.0", "minecraft:oak_trapdoor"); - hashmap.put("minecraft:nether_brick.0", "minecraft:nether_bricks"); - hashmap.put("minecraft:red_nether_brick.0", "minecraft:red_nether_bricks"); - hashmap.put("minecraft:netherbrick.0", "minecraft:nether_brick"); - hashmap.put("minecraft:wooden_button.0", "minecraft:oak_button"); - hashmap.put("minecraft:wooden_pressure_plate.0", "minecraft:oak_pressure_plate"); - hashmap.put("minecraft:noteblock.0", "minecraft:note_block"); - hashmap.put("minecraft:bed.0", "minecraft:white_bed"); - hashmap.put("minecraft:bed.1", "minecraft:orange_bed"); - hashmap.put("minecraft:bed.2", "minecraft:magenta_bed"); - hashmap.put("minecraft:bed.3", "minecraft:light_blue_bed"); - hashmap.put("minecraft:bed.4", "minecraft:yellow_bed"); - hashmap.put("minecraft:bed.5", "minecraft:lime_bed"); - hashmap.put("minecraft:bed.6", "minecraft:pink_bed"); - hashmap.put("minecraft:bed.7", "minecraft:gray_bed"); - hashmap.put("minecraft:bed.8", "minecraft:light_gray_bed"); - hashmap.put("minecraft:bed.9", "minecraft:cyan_bed"); - hashmap.put("minecraft:bed.10", "minecraft:purple_bed"); - hashmap.put("minecraft:bed.11", "minecraft:blue_bed"); - hashmap.put("minecraft:bed.12", "minecraft:brown_bed"); - hashmap.put("minecraft:bed.13", "minecraft:green_bed"); - hashmap.put("minecraft:bed.14", "minecraft:red_bed"); - hashmap.put("minecraft:bed.15", "minecraft:black_bed"); - hashmap.put("minecraft:banner.15", "minecraft:white_banner"); - hashmap.put("minecraft:banner.14", "minecraft:orange_banner"); - hashmap.put("minecraft:banner.13", "minecraft:magenta_banner"); - hashmap.put("minecraft:banner.12", "minecraft:light_blue_banner"); - hashmap.put("minecraft:banner.11", "minecraft:yellow_banner"); - hashmap.put("minecraft:banner.10", "minecraft:lime_banner"); - hashmap.put("minecraft:banner.9", "minecraft:pink_banner"); - hashmap.put("minecraft:banner.8", "minecraft:gray_banner"); - hashmap.put("minecraft:banner.7", "minecraft:light_gray_banner"); - hashmap.put("minecraft:banner.6", "minecraft:cyan_banner"); - hashmap.put("minecraft:banner.5", "minecraft:purple_banner"); - hashmap.put("minecraft:banner.4", "minecraft:blue_banner"); - hashmap.put("minecraft:banner.3", "minecraft:brown_banner"); - hashmap.put("minecraft:banner.2", "minecraft:green_banner"); - hashmap.put("minecraft:banner.1", "minecraft:red_banner"); - hashmap.put("minecraft:banner.0", "minecraft:black_banner"); - hashmap.put("minecraft:grass.0", "minecraft:grass_block"); - hashmap.put("minecraft:brick_block.0", "minecraft:bricks"); - hashmap.put("minecraft:end_bricks.0", "minecraft:end_stone_bricks"); - hashmap.put("minecraft:golden_rail.0", "minecraft:powered_rail"); - hashmap.put("minecraft:magma.0", "minecraft:magma_block"); - hashmap.put("minecraft:quartz_ore.0", "minecraft:nether_quartz_ore"); - hashmap.put("minecraft:reeds.0", "minecraft:sugar_cane"); - hashmap.put("minecraft:slime.0", "minecraft:slime_block"); - hashmap.put("minecraft:stone_stairs.0", "minecraft:cobblestone_stairs"); - hashmap.put("minecraft:waterlily.0", "minecraft:lily_pad"); - hashmap.put("minecraft:web.0", "minecraft:cobweb"); - hashmap.put("minecraft:snow.0", "minecraft:snow_block"); - hashmap.put("minecraft:snow_layer.0", "minecraft:snow"); - hashmap.put("minecraft:record_11.0", "minecraft:music_disc_11"); - hashmap.put("minecraft:record_13.0", "minecraft:music_disc_13"); - hashmap.put("minecraft:record_blocks.0", "minecraft:music_disc_blocks"); - hashmap.put("minecraft:record_cat.0", "minecraft:music_disc_cat"); - hashmap.put("minecraft:record_chirp.0", "minecraft:music_disc_chirp"); - hashmap.put("minecraft:record_far.0", "minecraft:music_disc_far"); - hashmap.put("minecraft:record_mall.0", "minecraft:music_disc_mall"); - hashmap.put("minecraft:record_mellohi.0", "minecraft:music_disc_mellohi"); - hashmap.put("minecraft:record_stal.0", "minecraft:music_disc_stal"); - hashmap.put("minecraft:record_strad.0", "minecraft:music_disc_strad"); - hashmap.put("minecraft:record_wait.0", "minecraft:music_disc_wait"); - hashmap.put("minecraft:record_ward.0", "minecraft:music_disc_ward"); - }); - private static final Set b = (Set) DataConverterFlatten.a.keySet().stream().map((s) -> { - return s.substring(0, s.indexOf(46)); - }).collect(Collectors.toSet()); - private static final Set c = Sets.newHashSet(new String[]{"minecraft:bow", "minecraft:carrot_on_a_stick", "minecraft:chainmail_boots", "minecraft:chainmail_chestplate", "minecraft:chainmail_helmet", "minecraft:chainmail_leggings", "minecraft:diamond_axe", "minecraft:diamond_boots", "minecraft:diamond_chestplate", "minecraft:diamond_helmet", "minecraft:diamond_hoe", "minecraft:diamond_leggings", "minecraft:diamond_pickaxe", "minecraft:diamond_shovel", "minecraft:diamond_sword", "minecraft:elytra", "minecraft:fishing_rod", "minecraft:flint_and_steel", "minecraft:golden_axe", "minecraft:golden_boots", "minecraft:golden_chestplate", "minecraft:golden_helmet", "minecraft:golden_hoe", "minecraft:golden_leggings", "minecraft:golden_pickaxe", "minecraft:golden_shovel", "minecraft:golden_sword", "minecraft:iron_axe", "minecraft:iron_boots", "minecraft:iron_chestplate", "minecraft:iron_helmet", "minecraft:iron_hoe", "minecraft:iron_leggings", "minecraft:iron_pickaxe", "minecraft:iron_shovel", "minecraft:iron_sword", "minecraft:leather_boots", "minecraft:leather_chestplate", "minecraft:leather_helmet", "minecraft:leather_leggings", "minecraft:shears", "minecraft:shield", "minecraft:stone_axe", "minecraft:stone_hoe", "minecraft:stone_pickaxe", "minecraft:stone_shovel", "minecraft:stone_sword", "minecraft:wooden_axe", "minecraft:wooden_hoe", "minecraft:wooden_pickaxe", "minecraft:wooden_shovel", "minecraft:wooden_sword"}); - - public DataConverterFlatten(Schema schema, boolean flag) { - super(schema, flag); - } - - public TypeRewriteRule makeRule() { - Type type = this.getInputSchema().getType(DataConverterTypes.ITEM_STACK); - OpticFinder> opticfinder = DSL.fieldFinder("id", DSL.named(DataConverterTypes.r.typeName(), DSL.namespacedString())); - OpticFinder opticfinder1 = type.findField("tag"); - - return this.fixTypeEverywhereTyped("ItemInstanceTheFlatteningFix", type, (typed) -> { - Optional> optional = typed.getOptional(opticfinder); - - if (!optional.isPresent()) { - return typed; - } else { - Typed typed1 = typed; - Dynamic dynamic = (Dynamic) typed.get(DSL.remainderFinder()); - int i = dynamic.get("Damage").asInt(0); - String s = a((String) ((Pair) optional.get()).getSecond(), i); - - if (s != null) { - typed1 = typed.set(opticfinder, Pair.of(DataConverterTypes.r.typeName(), s)); - } - - if (DataConverterFlatten.c.contains(((Pair) optional.get()).getSecond())) { - Typed typed2 = typed.getOrCreateTyped(opticfinder1); - Dynamic dynamic1 = (Dynamic) typed2.get(DSL.remainderFinder()); - - if (i != 0) dynamic1 = dynamic1.set("Damage", dynamic1.createInt(i)); // CraftBukkit - typed1 = typed1.set(opticfinder1, typed2.set(DSL.remainderFinder(), dynamic1)); - } - - typed1 = typed1.set(DSL.remainderFinder(), dynamic.remove("Damage")); - return typed1; - } - }); - } - - @Nullable - public static String a(@Nullable String s, int i) { - if (DataConverterFlatten.b.contains(s)) { - String s1 = (String) DataConverterFlatten.a.get(s + '.' + i); - - return s1 == null ? (String) DataConverterFlatten.a.get(s + ".0") : s1; - } else { - return null; - } - } -} diff --git a/src/main/java/net/minecraft/server/DataConverterMap.java b/src/main/java/net/minecraft/server/DataConverterMap.java deleted file mode 100644 index 49af999b7..000000000 --- a/src/main/java/net/minecraft/server/DataConverterMap.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.DSL; -import com.mojang.datafixers.DataFix; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.OpticFinder; -import com.mojang.datafixers.TypeRewriteRule; -import com.mojang.datafixers.Typed; -import com.mojang.datafixers.schemas.Schema; -import com.mojang.datafixers.types.Type; -import com.mojang.datafixers.util.Pair; -import java.util.Objects; -import java.util.Optional; - -public class DataConverterMap extends DataFix { - - public DataConverterMap(Schema schema, boolean flag) { - super(schema, flag); - } - - public TypeRewriteRule makeRule() { - Type type = this.getInputSchema().getType(DataConverterTypes.ITEM_STACK); - OpticFinder> opticfinder = DSL.fieldFinder("id", DSL.named(DataConverterTypes.r.typeName(), DSL.namespacedString())); - OpticFinder opticfinder1 = type.findField("tag"); - - return this.fixTypeEverywhereTyped("ItemInstanceMapIdFix", type, (typed) -> { - Optional> optional = typed.getOptional(opticfinder); - - if (optional.isPresent() && Objects.equals(((Pair) optional.get()).getSecond(), "minecraft:filled_map")) { - Dynamic dynamic = (Dynamic) typed.get(DSL.remainderFinder()); - Typed typed1 = typed.getOrCreateTyped(opticfinder1); - Dynamic dynamic1 = (Dynamic) typed1.get(DSL.remainderFinder()); - - if (!dynamic1.getElement("map").isPresent()) dynamic1 = dynamic1.set("map", dynamic1.createInt(dynamic.get("Damage").asInt(0))); // CraftBukkit - return typed.set(opticfinder1, typed1.set(DSL.remainderFinder(), dynamic1)); - } else { - return typed; - } - }); - } -} diff --git a/src/main/java/net/minecraft/server/DataConverterRegistry.java b/src/main/java/net/minecraft/server/DataConverterRegistry.java deleted file mode 100644 index 645857604..000000000 --- a/src/main/java/net/minecraft/server/DataConverterRegistry.java +++ /dev/null @@ -1,423 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.mojang.datafixers.DSL; -import com.mojang.datafixers.DataFixer; -import com.mojang.datafixers.DataFixerBuilder; -import com.mojang.datafixers.Typed; -import com.mojang.datafixers.schemas.Schema; -import java.util.Objects; -import java.util.function.BiFunction; - -public class DataConverterRegistry { - - private static final BiFunction a = Schema::new; - private static final BiFunction b = DataConverterSchemaNamed::new; - private static final DataFixer c = b(); - - private static DataFixer b() { - DataFixerBuilder datafixerbuilder = new DataFixerBuilder(SharedConstants.a().getWorldVersion()); - - a(datafixerbuilder); - return datafixerbuilder.build(SystemUtils.e()); - } - - public static DataFixer a() { - return DataConverterRegistry.c; - } - - private static void a(DataFixerBuilder datafixerbuilder) { - Schema schema = datafixerbuilder.addSchema(99, DataConverterSchemaV99::new); - Schema schema1 = datafixerbuilder.addSchema(100, DataConverterSchemaV100::new); - - datafixerbuilder.addFixer(new DataConverterEquipment(schema1, true)); - Schema schema2 = datafixerbuilder.addSchema(101, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterSignText(schema2, false)); - Schema schema3 = datafixerbuilder.addSchema(102, DataConverterSchemaV102::new); - - datafixerbuilder.addFixer(new DataConverterMaterialId(schema3, true)); - datafixerbuilder.addFixer(new DataConverterPotionId(schema3, false)); - Schema schema4 = datafixerbuilder.addSchema(105, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterSpawnEgg(schema4, true)); - Schema schema5 = datafixerbuilder.addSchema(106, DataConverterSchemaV106::new); - - datafixerbuilder.addFixer(new DataConverterMobSpawner(schema5, true)); - Schema schema6 = datafixerbuilder.addSchema(107, DataConverterSchemaV107::new); - - datafixerbuilder.addFixer(new DataConverterMinecart(schema6, true)); - Schema schema7 = datafixerbuilder.addSchema(108, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterUUID(schema7, true)); - Schema schema8 = datafixerbuilder.addSchema(109, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterHealth(schema8, true)); - Schema schema9 = datafixerbuilder.addSchema(110, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterSaddle(schema9, true)); - Schema schema10 = datafixerbuilder.addSchema(111, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterHanging(schema10, true)); - Schema schema11 = datafixerbuilder.addSchema(113, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterDropChances(schema11, true)); - Schema schema12 = datafixerbuilder.addSchema(135, DataConverterSchemaV135::new); - - datafixerbuilder.addFixer(new DataConverterRiding(schema12, true)); - Schema schema13 = datafixerbuilder.addSchema(143, DataConverterSchemaV143::new); - - datafixerbuilder.addFixer(new DataConverterEntityTippedArrow(schema13, true)); - Schema schema14 = datafixerbuilder.addSchema(147, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterArmorStand(schema14, true)); - Schema schema15 = datafixerbuilder.addSchema(165, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterBook(schema15, true)); - Schema schema16 = datafixerbuilder.addSchema(501, DataConverterSchemaV501::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema16, "Add 1.10 entities fix", DataConverterTypes.ENTITY)); - Schema schema17 = datafixerbuilder.addSchema(502, DataConverterRegistry.a); - - datafixerbuilder.addFixer(DataConverterItemName.a(schema17, "cooked_fished item renamer", (s) -> { - return Objects.equals(DataConverterSchemaNamed.a(s), "minecraft:cooked_fished") ? "minecraft:cooked_fish" : s; - })); - datafixerbuilder.addFixer(new DataConverterZombie(schema17, false)); - Schema schema18 = datafixerbuilder.addSchema(505, DataConverterRegistry.a); - - datafixerbuilder.addFixer(new DataConverterVBO(schema18, false)); - Schema schema19 = datafixerbuilder.addSchema(700, DataConverterSchemaV700::new); - - datafixerbuilder.addFixer(new DataConverterGuardian(schema19, true)); - Schema schema20 = datafixerbuilder.addSchema(701, DataConverterSchemaV701::new); - - datafixerbuilder.addFixer(new DataConverterSkeleton(schema20, true)); - Schema schema21 = datafixerbuilder.addSchema(702, DataConverterSchemaV702::new); - - datafixerbuilder.addFixer(new DataConverterZombieType(schema21, true)); - Schema schema22 = datafixerbuilder.addSchema(703, DataConverterSchemaV703::new); - - datafixerbuilder.addFixer(new DataConverterHorse(schema22, true)); - Schema schema23 = datafixerbuilder.addSchema(704, DataConverterSchemaV704::new); - - datafixerbuilder.addFixer(new DataConverterTileEntity(schema23, true)); - Schema schema24 = datafixerbuilder.addSchema(705, DataConverterSchemaV705::new); - - datafixerbuilder.addFixer(new DataConverterEntity(schema24, true)); - Schema schema25 = datafixerbuilder.addSchema(804, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterBanner(schema25, true)); - Schema schema26 = datafixerbuilder.addSchema(806, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterPotionWater(schema26, false)); - Schema schema27 = datafixerbuilder.addSchema(808, DataConverterSchemaV808::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema27, "added shulker box", DataConverterTypes.k)); - Schema schema28 = datafixerbuilder.addSchema(808, 1, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterShulker(schema28, false)); - Schema schema29 = datafixerbuilder.addSchema(813, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterShulkerBoxItem(schema29, false)); - datafixerbuilder.addFixer(new DataConverterShulkerBoxBlock(schema29, false)); - Schema schema30 = datafixerbuilder.addSchema(816, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterLang(schema30, false)); - Schema schema31 = datafixerbuilder.addSchema(820, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterItemName.a(schema31, "totem item renamer", (s) -> { - return Objects.equals(s, "minecraft:totem") ? "minecraft:totem_of_undying" : s; - })); - Schema schema32 = datafixerbuilder.addSchema(1022, DataConverterSchemaV1022::new); - - datafixerbuilder.addFixer(new DataConverterShoulderEntity(schema32, "added shoulder entities to players", DataConverterTypes.PLAYER)); - Schema schema33 = datafixerbuilder.addSchema(1125, DataConverterSchemaV1125::new); - - datafixerbuilder.addFixer(new DataConverterBedBlock(schema33, true)); - datafixerbuilder.addFixer(new DataConverterBedItem(schema33, false)); - Schema schema34 = datafixerbuilder.addSchema(1344, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterKeybind(schema34, false)); - Schema schema35 = datafixerbuilder.addSchema(1446, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterKeybind2(schema35, false)); - Schema schema36 = datafixerbuilder.addSchema(1450, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterFlattenState(schema36, false)); - Schema schema37 = datafixerbuilder.addSchema(1451, DataConverterSchemaV1451::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema37, "AddTrappedChestFix", DataConverterTypes.k)); - Schema schema38 = datafixerbuilder.addSchema(1451, 1, DataConverterSchemaV1451_1::new); - - datafixerbuilder.addFixer(new ChunkConverterPalette(schema38, true)); - Schema schema39 = datafixerbuilder.addSchema(1451, 2, DataConverterSchemaV1451_2::new); - - datafixerbuilder.addFixer(new DataConverterPiston(schema39, true)); - Schema schema40 = datafixerbuilder.addSchema(1451, 3, DataConverterSchemaV1451_3::new); - - datafixerbuilder.addFixer(new DataConverterEntityBlockState(schema40, true)); - datafixerbuilder.addFixer(new DataConverterMap(schema40, false)); - Schema schema41 = datafixerbuilder.addSchema(1451, 4, DataConverterSchemaV1451_4::new); - - datafixerbuilder.addFixer(new DataConverterBlockName(schema41, true)); - datafixerbuilder.addFixer(new DataConverterFlatten(schema41, false)); - Schema schema42 = datafixerbuilder.addSchema(1451, 5, DataConverterSchemaV1451_5::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema42, "RemoveNoteBlockFlowerPotFix", DataConverterTypes.k)); - datafixerbuilder.addFixer(new DataConverterFlattenSpawnEgg(schema42, false)); - datafixerbuilder.addFixer(new DataConverterWolf(schema42, false)); - datafixerbuilder.addFixer(new DataConverterBannerColour(schema42, false)); - datafixerbuilder.addFixer(new DataConverterWorldGenSettings(schema42, false)); - Schema schema43 = datafixerbuilder.addSchema(1451, 6, DataConverterSchemaV1451_6::new); - - datafixerbuilder.addFixer(new DataConverterStatistic(schema43, true)); - datafixerbuilder.addFixer(new DataConverterJukeBox(schema43, false)); - Schema schema44 = datafixerbuilder.addSchema(1451, 7, DataConverterSchemaV1451_7::new); - - datafixerbuilder.addFixer(new DataConverterVillage(schema44, true)); - Schema schema45 = datafixerbuilder.addSchema(1451, 7, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterVillagerTrade(schema45, false)); - Schema schema46 = datafixerbuilder.addSchema(1456, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterItemFrame(schema46, false)); - Schema schema47 = datafixerbuilder.addSchema(1458, DataConverterRegistry.b); - - // CraftBukkit start - datafixerbuilder.addFixer(new com.mojang.datafixers.DataFix(schema47, false) { - @Override - protected com.mojang.datafixers.TypeRewriteRule makeRule() { - return this.fixTypeEverywhereTyped("Player CustomName", this.getInputSchema().getType(DataConverterTypes.PLAYER), (typed) -> { - return typed.update(DSL.remainderFinder(), (dynamic) -> { - return DataConverterCustomNameEntity.a(dynamic); - }); - }); - } - }); - // CraftBukkit end - datafixerbuilder.addFixer(new DataConverterCustomNameEntity(schema47, false)); - datafixerbuilder.addFixer(new DataConverterCustomNameItem(schema47, false)); - datafixerbuilder.addFixer(new DataConverterCustomNameTile(schema47, false)); - Schema schema48 = datafixerbuilder.addSchema(1460, DataConverterSchemaV1460::new); - - datafixerbuilder.addFixer(new DataConverterPainting(schema48, false)); - Schema schema49 = datafixerbuilder.addSchema(1466, DataConverterSchemaV1466::new); - - datafixerbuilder.addFixer(new DataConverterProtoChunk(schema49, true)); - Schema schema50 = datafixerbuilder.addSchema(1470, DataConverterSchemaV1470::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema50, "Add 1.13 entities fix", DataConverterTypes.ENTITY)); - Schema schema51 = datafixerbuilder.addSchema(1474, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterColorlessShulkerEntity(schema51, false)); - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema51, "Colorless shulker block fixer", (s) -> { - return Objects.equals(DataConverterSchemaNamed.a(s), "minecraft:purple_shulker_box") ? "minecraft:shulker_box" : s; - })); - datafixerbuilder.addFixer(DataConverterItemName.a(schema51, "Colorless shulker item fixer", (s) -> { - return Objects.equals(DataConverterSchemaNamed.a(s), "minecraft:purple_shulker_box") ? "minecraft:shulker_box" : s; - })); - Schema schema52 = datafixerbuilder.addSchema(1475, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema52, "Flowing fixer", (s) -> { - return (String) ImmutableMap.of("minecraft:flowing_water", "minecraft:water", "minecraft:flowing_lava", "minecraft:lava").getOrDefault(s, s); - })); - Schema schema53 = datafixerbuilder.addSchema(1480, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema53, "Rename coral blocks", (s) -> { - return (String) DataConverterCoral.a.getOrDefault(s, s); - })); - datafixerbuilder.addFixer(DataConverterItemName.a(schema53, "Rename coral items", (s) -> { - return (String) DataConverterCoral.a.getOrDefault(s, s); - })); - Schema schema54 = datafixerbuilder.addSchema(1481, DataConverterSchemaV1481::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema54, "Add conduit", DataConverterTypes.k)); - Schema schema55 = datafixerbuilder.addSchema(1483, DataConverterSchemaV1483::new); - - datafixerbuilder.addFixer(new DataConverterEntityPufferfish(schema55, true)); - datafixerbuilder.addFixer(DataConverterItemName.a(schema55, "Rename pufferfish egg item", (s) -> { - return (String) DataConverterEntityPufferfish.a.getOrDefault(s, s); - })); - Schema schema56 = datafixerbuilder.addSchema(1484, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterItemName.a(schema56, "Rename seagrass items", (s) -> { - return (String) ImmutableMap.of("minecraft:sea_grass", "minecraft:seagrass", "minecraft:tall_sea_grass", "minecraft:tall_seagrass").getOrDefault(s, s); - })); - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema56, "Rename seagrass blocks", (s) -> { - return (String) ImmutableMap.of("minecraft:sea_grass", "minecraft:seagrass", "minecraft:tall_sea_grass", "minecraft:tall_seagrass").getOrDefault(s, s); - })); - datafixerbuilder.addFixer(new DataConverterHeightmapRenaming(schema56, false)); - Schema schema57 = datafixerbuilder.addSchema(1486, DataConverterSchemaV1486::new); - - datafixerbuilder.addFixer(new DataConverterEntityCodSalmon(schema57, true)); - datafixerbuilder.addFixer(DataConverterItemName.a(schema57, "Rename cod/salmon egg items", (s) -> { - return (String) DataConverterEntityCodSalmon.b.getOrDefault(s, s); - })); - Schema schema58 = datafixerbuilder.addSchema(1487, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterItemName.a(schema58, "Rename prismarine_brick(s)_* blocks", (s) -> { - return (String) ImmutableMap.of("minecraft:prismarine_bricks_slab", "minecraft:prismarine_brick_slab", "minecraft:prismarine_bricks_stairs", "minecraft:prismarine_brick_stairs").getOrDefault(s, s); - })); - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema58, "Rename prismarine_brick(s)_* items", (s) -> { - return (String) ImmutableMap.of("minecraft:prismarine_bricks_slab", "minecraft:prismarine_brick_slab", "minecraft:prismarine_bricks_stairs", "minecraft:prismarine_brick_stairs").getOrDefault(s, s); - })); - Schema schema59 = datafixerbuilder.addSchema(1488, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema59, "Rename kelp/kelptop", (s) -> { - return (String) ImmutableMap.of("minecraft:kelp_top", "minecraft:kelp", "minecraft:kelp", "minecraft:kelp_plant").getOrDefault(s, s); - })); - datafixerbuilder.addFixer(DataConverterItemName.a(schema59, "Rename kelptop", (s) -> { - return Objects.equals(s, "minecraft:kelp_top") ? "minecraft:kelp" : s; - })); - datafixerbuilder.addFixer(new DataConverterNamedEntity(schema59, false, "Command block block entity custom name fix", DataConverterTypes.k, "minecraft:command_block") { - @Override - protected Typed a(Typed typed) { - return typed.update(DSL.remainderFinder(), DataConverterCustomNameEntity::a); - } - }); - datafixerbuilder.addFixer(new DataConverterNamedEntity(schema59, false, "Command block minecart custom name fix", DataConverterTypes.ENTITY, "minecraft:commandblock_minecart") { - @Override - protected Typed a(Typed typed) { - return typed.update(DSL.remainderFinder(), DataConverterCustomNameEntity::a); - } - }); - datafixerbuilder.addFixer(new DataConverterIglooMetadataRemoval(schema59, false)); - Schema schema60 = datafixerbuilder.addSchema(1490, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema60, "Rename melon_block", (s) -> { - return Objects.equals(s, "minecraft:melon_block") ? "minecraft:melon" : s; - })); - datafixerbuilder.addFixer(DataConverterItemName.a(schema60, "Rename melon_block/melon/speckled_melon", (s) -> { - return (String) ImmutableMap.of("minecraft:melon_block", "minecraft:melon", "minecraft:melon", "minecraft:melon_slice", "minecraft:speckled_melon", "minecraft:glistering_melon_slice").getOrDefault(s, s); - })); - Schema schema61 = datafixerbuilder.addSchema(1492, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterChunkStructuresTemplateRename(schema61, false)); - Schema schema62 = datafixerbuilder.addSchema(1494, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterItemStackEnchantment(schema62, false)); - Schema schema63 = datafixerbuilder.addSchema(1496, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterLeaves(schema63, false)); - Schema schema64 = datafixerbuilder.addSchema(1500, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterBlockEntityKeepPacked(schema64, false)); - Schema schema65 = datafixerbuilder.addSchema(1501, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterAdvancement(schema65, false)); - Schema schema66 = datafixerbuilder.addSchema(1502, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterRecipes(schema66, false)); - Schema schema67 = datafixerbuilder.addSchema(1506, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterLevelDataGeneratorOptions(schema67, false)); - Schema schema68 = datafixerbuilder.addSchema(1508, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterBiome(schema68, false)); - Schema schema69 = datafixerbuilder.addSchema(1510, DataConverterSchemaV1510::new); - - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema69, "Block renamening fix", (s) -> { - return (String) DataConverterEntityRename.b.getOrDefault(s, s); - })); - datafixerbuilder.addFixer(DataConverterItemName.a(schema69, "Item renamening fix", (s) -> { - return (String) DataConverterEntityRename.c.getOrDefault(s, s); - })); - datafixerbuilder.addFixer(new DataConverterRecipeRename(schema69, false)); - datafixerbuilder.addFixer(new DataConverterEntityRename(schema69, true)); - datafixerbuilder.addFixer(new DataConverterSwimStats(schema69, false)); - Schema schema70 = datafixerbuilder.addSchema(1514, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterObjectiveDisplayName(schema70, false)); - datafixerbuilder.addFixer(new DataConverterTeamDisplayName(schema70, false)); - datafixerbuilder.addFixer(new DataConverterObjectiveRenderType(schema70, false)); - Schema schema71 = datafixerbuilder.addSchema(1515, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema71, "Rename coral fan blocks", (s) -> { - return (String) DataConverterCoralFan.a.getOrDefault(s, s); - })); - Schema schema72 = datafixerbuilder.addSchema(1624, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterTrappedChest(schema72, false)); - Schema schema73 = datafixerbuilder.addSchema(1800, DataConverterSchemaV1800::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema73, "Added 1.14 mobs fix", DataConverterTypes.ENTITY)); - datafixerbuilder.addFixer(DataConverterItemName.a(schema73, "Rename dye items", (s) -> { - return (String) DataConverterDye.a.getOrDefault(s, s); - })); - Schema schema74 = datafixerbuilder.addSchema(1801, DataConverterSchemaV1801::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema74, "Added Illager Beast", DataConverterTypes.ENTITY)); - Schema schema75 = datafixerbuilder.addSchema(1802, DataConverterRegistry.b); - - datafixerbuilder.addFixer(DataConverterBlockRename.a(schema75, "Rename sign blocks & stone slabs", (s) -> { - return (String) ImmutableMap.of("minecraft:stone_slab", "minecraft:smooth_stone_slab", "minecraft:sign", "minecraft:oak_sign", "minecraft:wall_sign", "minecraft:oak_wall_sign").getOrDefault(s, s); - })); - datafixerbuilder.addFixer(DataConverterItemName.a(schema75, "Rename sign item & stone slabs", (s) -> { - return (String) ImmutableMap.of("minecraft:stone_slab", "minecraft:smooth_stone_slab", "minecraft:sign", "minecraft:oak_sign").getOrDefault(s, s); - })); - Schema schema76 = datafixerbuilder.addSchema(1803, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterItemLoreComponentize(schema76, false)); - Schema schema77 = datafixerbuilder.addSchema(1904, DataConverterSchemaV1904::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema77, "Added Cats", DataConverterTypes.ENTITY)); - datafixerbuilder.addFixer(new DataConverterEntityCatSplit(schema77, false)); - Schema schema78 = datafixerbuilder.addSchema(1905, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterChunkStatus(schema78, false)); - Schema schema79 = datafixerbuilder.addSchema(1906, DataConverterSchemaV1906::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema79, "Add POI Blocks", DataConverterTypes.k)); - Schema schema80 = datafixerbuilder.addSchema(1909, DataConverterSchemaV1909::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema80, "Add jigsaw", DataConverterTypes.k)); - Schema schema81 = datafixerbuilder.addSchema(1911, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterChunkStatus2(schema81, false)); - Schema schema82 = datafixerbuilder.addSchema(1917, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterCatType(schema82, false)); - Schema schema83 = datafixerbuilder.addSchema(1918, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterVillagerProfession(schema83, "minecraft:villager")); - datafixerbuilder.addFixer(new DataConverterVillagerProfession(schema83, "minecraft:zombie_villager")); - Schema schema84 = datafixerbuilder.addSchema(1920, DataConverterSchemaV1920::new); - - datafixerbuilder.addFixer(new DataConverterNewVillage(schema84, false)); - datafixerbuilder.addFixer(new DataConverterAddChoices(schema84, "Add campfire", DataConverterTypes.k)); - Schema schema85 = datafixerbuilder.addSchema(1925, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterMapId(schema85, false)); - Schema schema86 = datafixerbuilder.addSchema(1928, DataConverterSchemaV1928::new); - - datafixerbuilder.addFixer(new DataConverterEntityRavagerRename(schema86, true)); - datafixerbuilder.addFixer(DataConverterItemName.a(schema86, "Rename ravager egg item", (s) -> { - return (String) DataConverterEntityRavagerRename.a.getOrDefault(s, s); - })); - Schema schema87 = datafixerbuilder.addSchema(1929, DataConverterSchemaV1929::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema87, "Add Wandering Trader and Trader Llama", DataConverterTypes.ENTITY)); - Schema schema88 = datafixerbuilder.addSchema(1931, DataConverterSchemaV1931::new); - - datafixerbuilder.addFixer(new DataConverterAddChoices(schema88, "Added Fox", DataConverterTypes.ENTITY)); - Schema schema89 = datafixerbuilder.addSchema(1936, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterOptionsAddTextBackground(schema89, false)); - Schema schema90 = datafixerbuilder.addSchema(1946, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterPOI(schema90, false)); - Schema schema91 = datafixerbuilder.addSchema(1948, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterOminousBannerRename(schema91, false)); - Schema schema92 = datafixerbuilder.addSchema(1953, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterOminousBannerBlockEntityRename(schema92, false)); - Schema schema93 = datafixerbuilder.addSchema(1955, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterVillagerLevelXp(schema93, false)); - datafixerbuilder.addFixer(new DataConverterZombieVillagerLevelXp(schema93, false)); - Schema schema94 = datafixerbuilder.addSchema(1961, DataConverterRegistry.b); - - datafixerbuilder.addFixer(new DataConverterChunkLightRemove(schema94, false)); - } -} diff --git a/src/main/java/net/minecraft/server/DataPalette.java b/src/main/java/net/minecraft/server/DataPalette.java deleted file mode 100644 index 45403fbe3..000000000 --- a/src/main/java/net/minecraft/server/DataPalette.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public interface DataPalette { - - default int getOrCreateIdFor(T object) { return this.a(object); } // Paper - OBFHELPER - int a(T t0); - - boolean b(T t0); - - @Nullable default T getObject(int dataBits) { return this.a(dataBits); } // Paper - OBFHELPER - @Nullable - T a(int i); - - void b(PacketDataSerializer packetdataserializer); - - int a(); - - void a(NBTTagList nbttaglist); -} diff --git a/src/main/java/net/minecraft/server/DataPaletteBlock.java b/src/main/java/net/minecraft/server/DataPaletteBlock.java deleted file mode 100644 index 8fba1e2f3..000000000 --- a/src/main/java/net/minecraft/server/DataPaletteBlock.java +++ /dev/null @@ -1,288 +0,0 @@ -package net.minecraft.server; - -import it.unimi.dsi.fastutil.ints.Int2IntMap; -import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; -import it.unimi.dsi.fastutil.ints.Int2IntMap.Entry; -import com.destroystokyo.paper.antixray.ChunkPacketInfo; // Paper - Anti-Xray -import java.util.Arrays; -import java.util.Objects; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Function; -import java.util.stream.Collectors; - -public class DataPaletteBlock implements DataPaletteExpandable { - - private final DataPalette b; private final DataPalette getDataPaletteGlobal() { return this.b; } // Paper - OBFHELPER - private final DataPaletteExpandable c = (i, object) -> { - return 0; - }; - private final RegistryBlockID d; - private final Function e; - private final Function f; - private final T g; - private final T[] predefinedObjects; // Paper - Anti-Xray - Add predefined objects - protected DataBits a; protected DataBits getDataBits() { return this.a; } // Paper - OBFHELPER - private DataPalette h; private DataPalette getDataPalette() { return this.h; } // Paper - OBFHELPER - private int i; private int getBitsPerObject() { return this.i; } // Paper - OBFHELPER - private final com.destroystokyo.paper.util.ReentrantLockWithGetOwner j = new com.destroystokyo.paper.util.ReentrantLockWithGetOwner(); private com.destroystokyo.paper.util.ReentrantLockWithGetOwner getLock() { return this.j; } // Paper - change type to ReentrantLockWithGetOwner // Paper - OBFHELPER - - public void a() { - // Paper start - log other thread - Thread owningThread; - if (this.j.isLocked() && (owningThread = this.getLock().getOwner()) != null && owningThread != Thread.currentThread()) { - // Paper end - String s = (String) Thread.getAllStackTraces().keySet().stream().filter(Objects::nonNull).map((thread) -> { - return thread.getName() + ": \n\tat " + (String) Arrays.stream(thread.getStackTrace()).map(Object::toString).collect(Collectors.joining("\n\tat ")); - }).collect(Collectors.joining("\n")); - CrashReport crashreport = new CrashReport("Writing into PalettedContainer from multiple threads (other thread: name: " + owningThread.getName() + ", class: " + owningThread.getClass().toString() + ")", new IllegalStateException()); // Paper - log other thread - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Thread dumps"); - - crashreportsystemdetails.a("Thread dumps", (Object) s); - throw new ReportedException(crashreport); - } else { - this.j.lock(); - } - } - - public void b() { - this.j.unlock(); - } - - public DataPaletteBlock(DataPalette datapalette, RegistryBlockID registryblockid, Function function, Function function1, T t0) { - // Paper start - Anti-Xray - Support default constructor - this(datapalette, registryblockid, function, function1, t0, null, true); - } - - public DataPaletteBlock(DataPalette datapalette, RegistryBlockID registryblockid, Function function, Function function1, T t0, T[] predefinedObjects, boolean initialize) { - // Paper end - Anti-Xray - Add predefined objects - this.b = datapalette; - this.d = registryblockid; - this.e = function; - this.f = function1; - this.g = t0; - // Paper start - Anti-Xray - Add predefined objects - this.predefinedObjects = predefinedObjects; - - if (initialize) { - if (predefinedObjects == null) { - // Default - this.initialize(4); - } else { - // MathHelper.d() is trailingBits(roundCeilPow2(n)), alternatively; (int)ceil(log2(n)); however it's trash, use numberOfLeadingZeros instead - // Count the bits of the maximum array index to initialize a data palette with enough space from the beginning - // The length of the array is used because air is also added to the data palette from the beginning - // Start with at least 4 - int maxIndex = predefinedObjects.length >> 4; - int bitCount = (32 - Integer.numberOfLeadingZeros(Math.max(16, maxIndex) - 1)); - - // Initialize with at least 15 free indixes - this.initialize((1 << bitCount) - predefinedObjects.length < 16 ? bitCount + 1 : bitCount); - this.addPredefinedObjects(); - } - } - // Paper end - } - - // Paper start - Anti-Xray - Add predefined objects - private void addPredefinedObjects() { - if (this.predefinedObjects != null && this.getDataPalette() != this.getDataPaletteGlobal()) { - for (int i = 0; i < this.predefinedObjects.length; i++) { - this.getDataPalette().getOrCreateIdFor(this.predefinedObjects[i]); - } - } - } - // Paper end - - private static int b(int i, int j, int k) { - return j << 8 | k << 4 | i; - } - - private void initialize(int bitsPerObject) { this.b(bitsPerObject); } // Paper - OBFHELPER - private void b(int i) { - if (i != this.i) { - this.i = i; - if (this.i <= 4) { - this.i = 4; - this.h = new DataPaletteLinear<>(this.d, this.i, this, this.e); - } else if (this.i < 9) { - this.h = new DataPaletteHash<>(this.d, this.i, this, this.e, this.f); - } else { - this.h = this.b; - this.i = MathHelper.d(this.d.a()); - } - - this.h.a(this.g); - this.a = new DataBits(this.i, 4096); - } - } - - @Override - public int onResize(int i, T t0) { - this.a(); - DataBits databits = this.a; - DataPalette datapalette = this.h; - - this.b(i); - - int j; - - this.addPredefinedObjects(); // Paper - Anti-Xray - Add predefined objects - for (j = 0; j < databits.b(); ++j) { - T t1 = datapalette.a(databits.a(j)); - - if (t1 != null) { - this.setBlockIndex(j, t1); - } - } - - j = this.h.a(t0); - this.b(); - return j; - } - - public T setBlock(int i, int j, int k, T t0) { - this.a(); - T t1 = this.a(b(i, j, k), t0); - - this.b(); - return t1; - } - - public T b(int i, int j, int k, T t0) { - return this.a(b(i, j, k), t0); - } - - protected T a(int i, T t0) { - int j = this.h.a(t0); - int k = this.a.a(i, j); - T t1 = this.h.a(k); - - return t1 == null ? this.g : t1; - } - - protected void setBlockIndex(int i, T t0) { - int j = this.h.a(t0); - - this.a.b(i, j); - } - - public T a(int i, int j, int k) { - return this.a(b(i, j, k)); - } - - protected T a(int i) { - T t0 = this.h.a(this.a.a(i)); - - return t0 == null ? this.g : t0; - } - - public void writeDataPaletteBlock(PacketDataSerializer packetDataSerializer) { this.b(packetDataSerializer); } // Paper - OBFHELPER - public void b(PacketDataSerializer packetdataserializer) { - // Paper start - add parameters - this.writeDataPaletteBlock(packetdataserializer, null, 0); - } - public void writeDataPaletteBlock(PacketDataSerializer packetdataserializer, ChunkPacketInfo chunkPacketInfo, int chunkSectionIndex) { - // Paper end - this.a(); - packetdataserializer.writeByte(this.i); - this.h.b(packetdataserializer); - - // Paper start - Anti-Xray - Add chunk packet info - if (chunkPacketInfo != null) { - chunkPacketInfo.setBitsPerObject(chunkSectionIndex, this.getBitsPerObject()); - chunkPacketInfo.setDataPalette(chunkSectionIndex, this.getDataPalette()); - chunkPacketInfo.setDataBitsIndex(chunkSectionIndex, packetdataserializer.writerIndex() + PacketDataSerializer.countBytes(this.getDataBits().getDataBits().length)); - chunkPacketInfo.setPredefinedObjects(chunkSectionIndex, this.predefinedObjects); - } - // Paper end - - packetdataserializer.a(this.a.a()); - this.b(); - } - - public void a(NBTTagList nbttaglist, long[] along) { - this.a(); - // Paper - Anti-Xray - TODO: Should this.predefinedObjects.length just be added here (faster) or should the contents be compared to calculate the size (less RAM)? - int i = Math.max(4, MathHelper.d(nbttaglist.size() + (this.predefinedObjects == null ? 0 : this.predefinedObjects.length))); // Paper - Anti-Xray - Calculate the size with predefined objects - - if (true || i != this.i) { // Paper - Anti-Xray - Not initialized yet - this.b(i); - } - - this.h.a(nbttaglist); - this.addPredefinedObjects(); // Paper - Anti-Xray - Add predefined objects - int j = along.length * 64 / 4096; - - if (this.h == this.b) { - DataPalette datapalette = new DataPaletteHash<>(this.d, i, this.c, this.e, this.f); - - datapalette.a(nbttaglist); - DataBits databits = new DataBits(i, 4096, along); - - for (int k = 0; k < 4096; ++k) { - this.a.b(k, this.b.a(datapalette.a(databits.a(k)))); - } - } else if (j == this.i) { - System.arraycopy(along, 0, this.a.a(), 0, along.length); - } else { - DataBits databits1 = new DataBits(j, 4096, along); - - for (int l = 0; l < 4096; ++l) { - this.a.b(l, databits1.a(l)); - } - } - - this.b(); - } - - public void a(NBTTagCompound nbttagcompound, String s, String s1) { - this.a(); - DataPaletteHash datapalettehash = new DataPaletteHash<>(this.d, this.i, this.c, this.e, this.f); - - datapalettehash.a(this.g); - int[] aint = new int[4096]; - - for (int i = 0; i < 4096; ++i) { - aint[i] = datapalettehash.a(this.a(i)); - } - - NBTTagList nbttaglist = new NBTTagList(); - - datapalettehash.b(nbttaglist); - nbttagcompound.set(s, nbttaglist); - int j = Math.max(4, MathHelper.d(nbttaglist.size())); - DataBits databits = new DataBits(j, 4096); - - for (int k = 0; k < aint.length; ++k) { - databits.b(k, aint[k]); - } - - nbttagcompound.a(s1, databits.a()); - this.b(); - } - - public int c() { - return 1 + this.h.a() + PacketDataSerializer.a(this.a.b()) + this.a.a().length * 8; - } - - public boolean a(T t0) { - return this.h.b(t0); - } - - public void a(DataPaletteBlock.a datapaletteblock_a) { - Int2IntOpenHashMap int2intopenhashmap = new Int2IntOpenHashMap(); - - this.a.a((i) -> { - int2intopenhashmap.put(i, int2intopenhashmap.get(i) + 1); - }); - int2intopenhashmap.int2IntEntrySet().forEach((entry) -> { - datapaletteblock_a.accept(this.h.a(entry.getIntKey()), entry.getIntValue()); - }); - } - - @FunctionalInterface - public interface a { - - void accept(T t0, int i); - } -} diff --git a/src/main/java/net/minecraft/server/DataWatcher.java b/src/main/java/net/minecraft/server/DataWatcher.java deleted file mode 100644 index e6f39878e..000000000 --- a/src/main/java/net/minecraft/server/DataWatcher.java +++ /dev/null @@ -1,318 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import io.netty.handler.codec.DecoderException; -import io.netty.handler.codec.EncoderException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import javax.annotation.Nullable; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class DataWatcher { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final Map, Integer> b = Maps.newHashMap(); - private final Entity entity; - private final it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap> entries = new it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<>(); // Spigot - use better map // PAIL - // private final ReadWriteLock lock = new ReentrantReadWriteLock(); // Spigot - not required - private boolean f = true; - private boolean g; - - public DataWatcher(Entity entity) { - this.entity = entity; - } - - public static DataWatcherObject a(Class oclass, DataWatcherSerializer datawatcherserializer) { - if (DataWatcher.LOGGER.isDebugEnabled()) { - try { - Class oclass1 = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName()); - - if (!oclass1.equals(oclass)) { - DataWatcher.LOGGER.debug("defineId called for: {} from {}", oclass, oclass1, new RuntimeException()); - } - } catch (ClassNotFoundException classnotfoundexception) { - ; - } - } - - int i; - - if (DataWatcher.b.containsKey(oclass)) { - i = (Integer) DataWatcher.b.get(oclass) + 1; - } else { - int j = 0; - Class oclass2 = oclass; - - while (oclass2 != Entity.class) { - oclass2 = oclass2.getSuperclass(); - if (DataWatcher.b.containsKey(oclass2)) { - j = (Integer) DataWatcher.b.get(oclass2) + 1; - break; - } - } - - i = j; - } - - if (i > 254) { - throw new IllegalArgumentException("Data value id is too big with " + i + "! (Max is " + 254 + ")"); - } else { - DataWatcher.b.put(oclass, i); - return datawatcherserializer.a(i); - } - } - - boolean registrationLocked; // Spigot - public void register(DataWatcherObject datawatcherobject, T t0) { - if (this.registrationLocked) throw new IllegalStateException("Registering datawatcher object after entity initialization"); // Spigot - int i = datawatcherobject.a(); - - if (i > 254) { - throw new IllegalArgumentException("Data value id is too big with " + i + "! (Max is " + 254 + ")"); - } else if (this.entries.containsKey(i)) { - throw new IllegalArgumentException("Duplicate id value for " + i + "!"); - } else if (DataWatcherRegistry.b(datawatcherobject.b()) < 0) { - throw new IllegalArgumentException("Unregistered serializer " + datawatcherobject.b() + " for " + i + "!"); - } else { - this.registerObject(datawatcherobject, t0); - } - } - - private void registerObject(DataWatcherObject datawatcherobject, T t0) { - DataWatcher.Item datawatcher_item = new DataWatcher.Item<>(datawatcherobject, t0); - - // this.lock.writeLock().lock(); // Spigot - not required - this.entries.put(datawatcherobject.a(), datawatcher_item); - this.f = false; - // this.lock.writeLock().unlock(); // Spigot - not required - } - - private DataWatcher.Item b(DataWatcherObject datawatcherobject) { - // Spigot start - /* - this.lock.readLock().lock(); - - DataWatcher.Item datawatcher_item; - - try { - datawatcher_item = (DataWatcher.Item) this.entries.get(datawatcherobject.a()); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Getting synched entity data"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Synched entity data"); - - crashreportsystemdetails.a("Data ID", (Object) datawatcherobject); - throw new ReportedException(crashreport); - } finally { - this.lock.readLock().unlock(); - } - - return datawatcher_item; - */ - return (DataWatcher.Item) this.entries.get(datawatcherobject.a()); - // Spigot end - } - - public T get(DataWatcherObject datawatcherobject) { - return this.b(datawatcherobject).b(); - } - - public void set(DataWatcherObject datawatcherobject, T t0) { - DataWatcher.Item datawatcher_item = this.b(datawatcherobject); - - if (ObjectUtils.notEqual(t0, datawatcher_item.b())) { - datawatcher_item.a(t0); - this.entity.a(datawatcherobject); - datawatcher_item.a(true); - this.g = true; - } - - } - - // CraftBukkit start - add method from above - public void markDirty(DataWatcherObject datawatcherobject) { - this.b(datawatcherobject).a(true); - this.g = true; - } - // CraftBukkit end - - public boolean a() { - return this.g; - } - - public static void a(List> list, PacketDataSerializer packetdataserializer) throws IOException { - if (list != null) { - int i = 0; - - for (int j = list.size(); i < j; ++i) { - a(packetdataserializer, (DataWatcher.Item) list.get(i)); - } - } - - packetdataserializer.writeByte(255); - } - - @Nullable - public List> b() { - List> list = null; - - if (this.g) { - // this.lock.readLock().lock(); // Spigot - not required - Iterator iterator = this.entries.values().iterator(); - - while (iterator.hasNext()) { - DataWatcher.Item datawatcher_item = (DataWatcher.Item) iterator.next(); - - if (datawatcher_item.c()) { - datawatcher_item.a(false); - if (list == null) { - list = Lists.newArrayList(); - } - - list.add(datawatcher_item.d()); - } - } - - // this.lock.readLock().unlock(); // Spigot - not required - } - - this.g = false; - return list; - } - - public void a(PacketDataSerializer packetdataserializer) throws IOException { - // this.lock.readLock().lock(); // Spigot - not required - Iterator iterator = this.entries.values().iterator(); - - while (iterator.hasNext()) { - DataWatcher.Item datawatcher_item = (DataWatcher.Item) iterator.next(); - - a(packetdataserializer, datawatcher_item); - } - - // this.lock.readLock().unlock(); // Spigot - not required - packetdataserializer.writeByte(255); - } - - @Nullable - public List> c() { - List> list = null; - - // this.lock.readLock().lock(); // Spigot - not required - - DataWatcher.Item datawatcher_item; - - for (Iterator iterator = this.entries.values().iterator(); iterator.hasNext(); list.add(datawatcher_item.d())) { - datawatcher_item = (DataWatcher.Item) iterator.next(); - if (list == null) { - list = Lists.newArrayList(); - } - } - - // this.lock.readLock().unlock(); // Spigot - not required - return list; - } - - private static void a(PacketDataSerializer packetdataserializer, DataWatcher.Item datawatcher_item) throws IOException { - DataWatcherObject datawatcherobject = datawatcher_item.a(); - int i = DataWatcherRegistry.b(datawatcherobject.b()); - - if (i < 0) { - throw new EncoderException("Unknown serializer type " + datawatcherobject.b()); - } else { - packetdataserializer.writeByte(datawatcherobject.a()); - packetdataserializer.d(i); - datawatcherobject.b().a(packetdataserializer, datawatcher_item.b()); - } - } - - @Nullable - public static List> b(PacketDataSerializer packetdataserializer) throws IOException { - ArrayList arraylist = null; - - short short0; - - while ((short0 = packetdataserializer.readUnsignedByte()) != 255) { - if (arraylist == null) { - arraylist = Lists.newArrayList(); - } - - int i = packetdataserializer.i(); - DataWatcherSerializer datawatcherserializer = DataWatcherRegistry.a(i); - - if (datawatcherserializer == null) { - throw new DecoderException("Unknown serializer type " + i); - } - - arraylist.add(a(packetdataserializer, short0, datawatcherserializer)); - } - - return arraylist; - } - - private static DataWatcher.Item a(PacketDataSerializer packetdataserializer, int i, DataWatcherSerializer datawatcherserializer) { - return new DataWatcher.Item<>(datawatcherserializer.a(i), datawatcherserializer.a(packetdataserializer)); - } - - public boolean d() { - return this.f; - } - - public void e() { - this.g = false; - // this.lock.readLock().lock(); // Spigot - not required - Iterator iterator = this.entries.values().iterator(); - - while (iterator.hasNext()) { - DataWatcher.Item datawatcher_item = (DataWatcher.Item) iterator.next(); - - datawatcher_item.a(false); - } - - // this.lock.readLock().unlock(); // Spigot - not required - } - - public static class Item { - - private final DataWatcherObject a; - private T b; - private boolean c; - - public Item(DataWatcherObject datawatcherobject, T t0) { - this.a = datawatcherobject; - this.b = t0; - this.c = true; - } - - public DataWatcherObject a() { - return this.a; - } - - public void a(T t0) { - this.b = t0; - } - - public T b() { - return this.b; - } - - public boolean c() { - return this.c; - } - - public void a(boolean flag) { - this.c = flag; - } - - public DataWatcher.Item d() { - return new DataWatcher.Item<>(this.a, this.a.b().a(this.b)); - } - } -} diff --git a/src/main/java/net/minecraft/server/DedicatedServer.java b/src/main/java/net/minecraft/server/DedicatedServer.java deleted file mode 100644 index 5bc19cd08..000000000 --- a/src/main/java/net/minecraft/server/DedicatedServer.java +++ /dev/null @@ -1,759 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.gson.JsonObject; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.GameProfileRepository; -import com.mojang.authlib.minecraft.MinecraftSessionService; -import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; -import com.mojang.datafixers.DataFixer; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.InetAddress; -import java.net.Proxy; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Random; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.function.BooleanSupplier; -import java.util.regex.Pattern; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import java.io.PrintStream; -import org.apache.logging.log4j.Level; - -import org.bukkit.command.CommandSender; -import org.bukkit.craftbukkit.LoggerOutputStream; -import co.aikar.timings.MinecraftTimings; // Paper -import org.bukkit.event.server.ServerCommandEvent; -import org.bukkit.craftbukkit.util.Waitable; -import org.bukkit.event.server.RemoteServerCommandEvent; -// CraftBukkit end - -public class DedicatedServer extends MinecraftServer implements IMinecraftServer { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final Pattern i = Pattern.compile("^[a-fA-F0-9]{40}$"); - private final java.util.Queue serverCommandQueue = new java.util.concurrent.ConcurrentLinkedQueue(); // Paper - use a proper queue - private RemoteStatusListener remoteStatusListener; - public final RemoteControlCommandListener remoteControlCommandListener; - private RemoteControlListener remoteControlListener; - public DedicatedServerSettings propertyManager; - private EnumGamemode o; - @Nullable - private ServerGUI p; - - // CraftBukkit start - Signature changed - public DedicatedServer(joptsimple.OptionSet options, DedicatedServerSettings dedicatedserversettings, DataFixer datafixer, YggdrasilAuthenticationService yggdrasilauthenticationservice, MinecraftSessionService minecraftsessionservice, GameProfileRepository gameprofilerepository, UserCache usercache, WorldLoadListenerFactory worldloadlistenerfactory, String s) { - super(options, Proxy.NO_PROXY, datafixer, new CommandDispatcher().init(true), yggdrasilauthenticationservice, minecraftsessionservice, gameprofilerepository, usercache, worldloadlistenerfactory, s); - // CraftBukkit end - this.propertyManager = dedicatedserversettings; - this.remoteControlCommandListener = new RemoteControlCommandListener(this); - Thread thread = new Thread("Server Infinisleeper") { - { - this.setDaemon(true); - this.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(DedicatedServer.LOGGER)); - this.start(); - } - - public void run() { - while (true) { - try { - Thread.sleep(2147483647L); - } catch (InterruptedException interruptedexception) { - ; - } - } - } - }; - } - - @Override - public boolean init() throws IOException { - Thread thread = new Thread("Server console handler") { - public void run() { - // CraftBukkit start - if (!org.bukkit.craftbukkit.Main.useConsole) { - return; - } - // Paper start - Use TerminalConsoleAppender - new com.destroystokyo.paper.console.PaperConsole(DedicatedServer.this).start(); - /* - jline.console.ConsoleReader bufferedreader = reader; - // CraftBukkit end - - String s; - - try { - // CraftBukkit start - JLine disabling compatibility - while (!DedicatedServer.this.isStopped() && DedicatedServer.this.isRunning()) { - if (org.bukkit.craftbukkit.Main.useJline) { - s = bufferedreader.readLine(">", null); - } else { - s = bufferedreader.readLine(); - } - - // SPIGOT-5220: Throttle if EOF (ctrl^d) or stdin is /dev/null - if (s == null) { - try { - Thread.sleep(50L); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - continue; - } - if (s.trim().length() > 0) { // Trim to filter lines which are just spaces - DedicatedServer.this.issueCommand(s, DedicatedServer.this.getServerCommandListener()); - } - // CraftBukkit end - } - } catch (IOException ioexception) { - DedicatedServer.LOGGER.error("Exception handling console input", ioexception); - } - - */ - // Paper end - } - }; - - // 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()); - - // Paper start - Not needed with TerminalConsoleAppender - final org.apache.logging.log4j.Logger logger = LogManager.getRootLogger(); - /* - final org.apache.logging.log4j.core.Logger logger = ((org.apache.logging.log4j.core.Logger) LogManager.getRootLogger()); - for (org.apache.logging.log4j.core.Appender appender : logger.getAppenders().values()) { - if (appender instanceof org.apache.logging.log4j.core.appender.ConsoleAppender) { - logger.removeAppender(appender); - } - } - - new org.bukkit.craftbukkit.util.TerminalConsoleWriterThread(System.out, this.reader).start(); - */ - // Paper end - - // Paper start - Use Log4j IOStreams - 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()); - // Paper end - // CraftBukkit end - - thread.setDaemon(true); - thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(DedicatedServer.LOGGER)); - thread.start(); - DedicatedServer.LOGGER.info("Starting minecraft server version " + SharedConstants.a().getName()); - if (Runtime.getRuntime().maxMemory() / 1024L / 1024L < 512L) { - DedicatedServer.LOGGER.warn("To start the server with more ram, launch it as \"java -Xmx1024M -Xms1024M -jar minecraft_server.jar\""); - } - - DedicatedServer.LOGGER.info("Loading properties"); - DedicatedServerProperties dedicatedserverproperties = this.propertyManager.getProperties(); - - if (this.isEmbeddedServer()) { - this.b("127.0.0.1"); - } else { - this.setOnlineMode(dedicatedserverproperties.onlineMode); - this.h(dedicatedserverproperties.preventProxyConnections); - this.b(dedicatedserverproperties.serverIp); - } - // Spigot start - this.a((PlayerList) (new DedicatedPlayerList(this))); - org.spigotmc.SpigotConfig.init((File) options.valueOf("spigot-settings")); - org.spigotmc.SpigotConfig.registerCommands(); - // Spigot end - // Paper start - try { - com.destroystokyo.paper.PaperConfig.init((File) options.valueOf("paper-settings")); - } catch (Exception e) { - DedicatedServer.LOGGER.error("Unable to load server configuration", e); - return false; - } - com.destroystokyo.paper.PaperConfig.registerCommands(); - com.destroystokyo.paper.VersionHistoryManager.INSTANCE.getClass(); // load version history now - // Paper end - - this.setSpawnAnimals(dedicatedserverproperties.spawnAnimals); - this.setSpawnNPCs(dedicatedserverproperties.spawnNpcs); - this.setPVP(dedicatedserverproperties.pvp); - this.setAllowFlight(dedicatedserverproperties.allowFlight); - this.setResourcePack(dedicatedserverproperties.resourcePack, this.aW()); - this.setMotd(dedicatedserverproperties.motd); - this.setForceGamemode(dedicatedserverproperties.forceGamemode); - super.setIdleTimeout((Integer) dedicatedserverproperties.playerIdleTimeout.get()); - this.n(dedicatedserverproperties.enforceWhitelist); - this.o = dedicatedserverproperties.gamemode; - DedicatedServer.LOGGER.info("Default game type: {}", this.o); - InetAddress inetaddress = null; - - if (!this.getServerIp().isEmpty()) { - inetaddress = InetAddress.getByName(this.getServerIp()); - } - - if (this.getPort() < 0) { - this.setPort(dedicatedserverproperties.serverPort); - } - - DedicatedServer.LOGGER.info("Generating keypair"); - this.a(MinecraftEncryption.b()); - DedicatedServer.LOGGER.info("Starting Minecraft server on {}:{}", this.getServerIp().isEmpty() ? "*" : this.getServerIp(), this.getPort()); - - try { - this.getServerConnection().a(inetaddress, this.getPort()); - } 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; - } - - // CraftBukkit start - // this.a((PlayerList) (new DedicatedPlayerList(this))); // Spigot - moved up - server.loadPlugins(); - server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.STARTUP); - // CraftBukkit end - - if (!this.getOnlineMode()) { - DedicatedServer.LOGGER.warn("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); - DedicatedServer.LOGGER.warn("The server will make no attempt to authenticate usernames. Beware."); - // Spigot start - if (org.spigotmc.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."); - } - // Spigot end - DedicatedServer.LOGGER.warn("To change this, set \"online-mode\" to \"true\" in the server.properties file."); - } - - if (this.convertNames()) { - this.getUserCache().c(); - } - - if (!NameReferencingFileConverter.e(this)) { - return false; - } else { - this.convertable = new Convertable(server.getWorldContainer().toPath(), server.getWorldContainer().toPath().resolve("../backups"), this.dataConverterManager); // CraftBukkit - moved from MinecraftServer constructor - long i = SystemUtils.getMonotonicNanos(); - String s = dedicatedserverproperties.levelSeed; - String s1 = dedicatedserverproperties.generatorSettings; - long j = (new Random()).nextLong(); - - if (!s.isEmpty()) { - try { - long k = Long.parseLong(s); - - if (k != 0L) { - j = k; - } - } catch (NumberFormatException numberformatexception) { - j = (long) s.hashCode(); - } - } - - WorldType worldtype = dedicatedserverproperties.levelType; - - this.b(dedicatedserverproperties.maxBuildHeight); - TileEntitySkull.a(this.getUserCache()); - TileEntitySkull.a(this.getMinecraftSessionService()); - UserCache.a(this.getOnlineMode()); - DedicatedServer.LOGGER.info("Preparing level \"{}\"", this.getWorld()); - JsonObject jsonobject = new JsonObject(); - - if (worldtype == WorldType.FLAT) { - jsonobject.addProperty("flat_world_options", s1); - } else if (!s1.isEmpty()) { - // CraftBukkit start - try { - jsonobject = ChatDeserializer.a(s1); - } catch (Exception ex) { - DedicatedServer.LOGGER.warn("Invalid generator-settings, ignoring", ex); - } - // CraftBukkit end - } - - this.a(this.getWorld(), this.getWorld(), j, worldtype, jsonobject); - long l = SystemUtils.getMonotonicNanos() - i; - String s2 = String.format(Locale.ROOT, "%.3fs", (double) l / 1.0E9D); - - DedicatedServer.LOGGER.info("Done ({})! For help, type \"help\"", s2); - if (dedicatedserverproperties.announcePlayerAchievements != null) { - ((GameRules.GameRuleBoolean) this.getGameRules().get(GameRules.ANNOUNCE_ADVANCEMENTS)).a(dedicatedserverproperties.announcePlayerAchievements, (MinecraftServer) this); - } - - if (dedicatedserverproperties.enableQuery) { - DedicatedServer.LOGGER.info("Starting GS4 status listener"); - this.remoteStatusListener = new RemoteStatusListener(this); - this.remoteStatusListener.a(); - } - - if (dedicatedserverproperties.enableRcon) { - DedicatedServer.LOGGER.info("Starting remote control listener"); - this.remoteControlListener = new RemoteControlListener(this); - this.remoteControlListener.a(); - this.remoteConsole = new org.bukkit.craftbukkit.command.CraftRemoteConsoleCommandSender(this.remoteControlCommandListener); // CraftBukkit - } - - if (false && this.getMaxTickTime() > 0L) { // Spigot - disable - Thread thread1 = new Thread(new ThreadWatchdog(this)); - - thread1.setUncaughtExceptionHandler(new ThreadNamedUncaughtExceptionHandler(DedicatedServer.LOGGER)); - thread1.setName("Server Watchdog"); - thread1.setDaemon(true); - thread1.start(); - } - - Items.AIR.a(CreativeModeTab.g, NonNullList.a()); - return true; - } - } - - public String aW() { - DedicatedServerProperties dedicatedserverproperties = this.propertyManager.getProperties(); - String s; - - if (!dedicatedserverproperties.resourcePackSha1.isEmpty()) { - s = dedicatedserverproperties.resourcePackSha1; - if (!Strings.isNullOrEmpty(dedicatedserverproperties.resourcePackHash)) { - DedicatedServer.LOGGER.warn("resource-pack-hash is deprecated and found along side resource-pack-sha1. resource-pack-hash will be ignored."); - } - } else if (!Strings.isNullOrEmpty(dedicatedserverproperties.resourcePackHash)) { - DedicatedServer.LOGGER.warn("resource-pack-hash is deprecated. Please use resource-pack-sha1 instead."); - s = dedicatedserverproperties.resourcePackHash; - } else { - s = ""; - } - - if (!s.isEmpty() && !DedicatedServer.i.matcher(s).matches()) { - DedicatedServer.LOGGER.warn("Invalid sha1 for ressource-pack-sha1"); - } - - if (!dedicatedserverproperties.resourcePack.isEmpty() && s.isEmpty()) { - DedicatedServer.LOGGER.warn("You specified a resource pack without providing a sha1 hash. Pack will be updated on the client only if you change the name of the pack."); - } - - return s; - } - - @Override - public void setGamemode(EnumGamemode enumgamemode) { - super.setGamemode(enumgamemode); - this.o = enumgamemode; - } - - @Override - public DedicatedServerProperties getDedicatedServerProperties() { - return this.propertyManager.getProperties(); - } - - @Override - public boolean getGenerateStructures() { - return this.getDedicatedServerProperties().generateStructures; - } - - @Override - public EnumGamemode getGamemode() { - return this.o; - } - - @Override - public EnumDifficulty getDifficulty() { - return this.getDedicatedServerProperties().difficulty; - } - - @Override - public boolean isHardcore() { - return this.getDedicatedServerProperties().hardcore; - } - - @Override - public CrashReport b(CrashReport crashreport) { - crashreport = super.b(crashreport); - crashreport.g().a("Is Modded", () -> { - String s = this.getServerModName(); - - return !"vanilla".equals(s) ? "Definitely; Server brand changed to '" + s + "'" : "Unknown (can't tell)"; - }); - crashreport.g().a("Type", () -> { - return "Dedicated Server (map_server.txt)"; - }); - return crashreport; - } - - @Override - public void exit() { - if (this.p != null) { - this.p.b(); - } - - if (this.remoteControlListener != null) { - this.remoteControlListener.b(); - } - - if (this.remoteStatusListener != null) { - this.remoteStatusListener.b(); - } - - System.exit(0); // CraftBukkit - } - - @Override - public void b(BooleanSupplier booleansupplier) { - super.b(booleansupplier); - this.handleCommandQueue(); - } - - @Override - public boolean getAllowNether() { - return this.getDedicatedServerProperties().allowNether; - } - - @Override - public boolean getSpawnMonsters() { - return this.getDedicatedServerProperties().spawnMonsters; - } - - @Override - public void a(MojangStatisticsGenerator mojangstatisticsgenerator) { - mojangstatisticsgenerator.a("whitelist_enabled", this.getPlayerList().getHasWhitelist()); - mojangstatisticsgenerator.a("whitelist_count", this.getPlayerList().getWhitelisted().length); - super.a(mojangstatisticsgenerator); - } - - public void issueCommand(String s, CommandListenerWrapper commandlistenerwrapper) { - this.serverCommandQueue.add(new ServerCommand(s, commandlistenerwrapper)); - } - - public void handleCommandQueue() { - MinecraftTimings.serverCommandTimer.startTiming(); // Spigot - // Paper start - use proper queue - ServerCommand servercommand; - while ((servercommand = this.serverCommandQueue.poll()) != null) { - // Paper end - - // 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); - - // this.getCommandDispatcher().a(servercommand.source, servercommand.command); // Called in dispatchServerCommand - server.dispatchServerCommand(console, servercommand); - // CraftBukkit end - } - - MinecraftTimings.serverCommandTimer.stopTiming(); // Spigot - } - - @Override - public boolean S() { - return true; - } - - @Override - public boolean X() { - return this.getDedicatedServerProperties().useNativeTransport; - } - - @Override - public DedicatedPlayerList getPlayerList() { - return (DedicatedPlayerList) super.getPlayerList(); - } - - @Override - public boolean af() { - return true; - } - - @Override - public String e_() { - return this.getServerIp(); - } - - @Override - public int e() { - return this.getPort(); - } - - @Override - public String f_() { - return this.getMotd(); - } - - public void aZ() { - if (this.p == null) { - this.p = ServerGUI.a(this); - } - - } - - @Override - public boolean ai() { - return this.p != null; - } - - @Override - public boolean a(EnumGamemode enumgamemode, boolean flag, int i) { - return false; - } - - @Override - public boolean getEnableCommandBlock() { - return this.getDedicatedServerProperties().enableCommandBlock; - } - - @Override - public int getSpawnProtection() { - return this.getDedicatedServerProperties().spawnProtection; - } - - @Override - public boolean a(World world, BlockPosition blockposition, EntityHuman entityhuman) { - if (world.worldProvider.getDimensionManager() != DimensionManager.OVERWORLD) { - return false; - } else if (this.getPlayerList().getOPs().isEmpty()) { - return false; - } else if (this.getPlayerList().isOp(entityhuman.getProfile())) { - return false; - } else if (this.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 <= this.getSpawnProtection(); - } - } - - @Override - public int j() { - return this.getDedicatedServerProperties().opPermissionLevel; - } - - @Override - public int k() { - return this.getDedicatedServerProperties().functionPermissionLevel; - } - - @Override - public void setIdleTimeout(int i) { - super.setIdleTimeout(i); - this.propertyManager.setProperty((dedicatedserverproperties) -> { - return (DedicatedServerProperties) dedicatedserverproperties.playerIdleTimeout.set(i); - }); - } - - @Override - public boolean l() { - return this.getDedicatedServerProperties().broadcastRconToOps; - } - - @Override - public boolean shouldBroadcastCommands() { - return this.getDedicatedServerProperties().broadcastConsoleToOps; - } - - @Override - public int aw() { - return this.getDedicatedServerProperties().maxWorldSize; - } - - @Override - public int az() { - return this.getDedicatedServerProperties().networkCompressionThreshold; - } - - protected boolean convertNames() { - boolean flag = false; - - int i; - - for (i = 0; !flag && i <= 2; ++i) { - if (i > 0) { - DedicatedServer.LOGGER.warn("Encountered a problem while converting the user banlist, retrying in a few seconds"); - this.bk(); - } - - flag = NameReferencingFileConverter.a((MinecraftServer) this); - } - - boolean flag1 = false; - - for (i = 0; !flag1 && i <= 2; ++i) { - if (i > 0) { - DedicatedServer.LOGGER.warn("Encountered a problem while converting the ip banlist, retrying in a few seconds"); - this.bk(); - } - - flag1 = NameReferencingFileConverter.b((MinecraftServer) this); - } - - boolean flag2 = false; - - for (i = 0; !flag2 && i <= 2; ++i) { - if (i > 0) { - DedicatedServer.LOGGER.warn("Encountered a problem while converting the op list, retrying in a few seconds"); - this.bk(); - } - - flag2 = NameReferencingFileConverter.c((MinecraftServer) this); - } - - boolean flag3 = false; - - for (i = 0; !flag3 && i <= 2; ++i) { - if (i > 0) { - DedicatedServer.LOGGER.warn("Encountered a problem while converting the whitelist, retrying in a few seconds"); - this.bk(); - } - - flag3 = NameReferencingFileConverter.d(this); - } - - boolean flag4 = false; - - for (i = 0; !flag4 && i <= 2; ++i) { - if (i > 0) { - DedicatedServer.LOGGER.warn("Encountered a problem while converting the player save files, retrying in a few seconds"); - this.bk(); - } - - flag4 = NameReferencingFileConverter.a(this); - } - - return flag || flag1 || flag2 || flag3 || flag4; - } - - private void bk() { - try { - Thread.sleep(5000L); - } catch (InterruptedException interruptedexception) { - ; - } - } - - public long getMaxTickTime() { - return this.getDedicatedServerProperties().maxTickTime; - } - - @Override - 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 - } - - @Override - public String executeRemoteCommand(String s) { - Waitable[] waitableArray = new Waitable[1]; - this.remoteControlCommandListener.clearMessages(); - this.executeSync(() -> { - // CraftBukkit start - fire RemoteServerCommandEvent - RemoteServerCommandEvent event = new RemoteServerCommandEvent(remoteConsole, s); - server.getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - // Paper start - if (s.toLowerCase().startsWith("timings") && s.toLowerCase().matches("timings (report|paste|get|merged|seperate)")) { - org.bukkit.command.BufferedCommandSender sender = new org.bukkit.command.BufferedCommandSender(); - Waitable waitable = new Waitable() { - @Override - protected String evaluate() { - return sender.getBuffer(); - } - }; - waitableArray[0] = waitable; - co.aikar.timings.Timings.generateReport(new co.aikar.timings.TimingsReportListener(sender, waitable)); - } else { - // Paper end - ServerCommand serverCommand = new ServerCommand(event.getCommand(), remoteControlCommandListener.getWrapper()); - server.dispatchServerCommand(remoteConsole, serverCommand); - } // Paper - // CraftBukkit end - }); - // Paper start - if (waitableArray[0] != null) { - //noinspection unchecked - Waitable waitable = waitableArray[0]; - 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); - } - - } - // Paper end - return this.remoteControlCommandListener.getMessages(); - } - - public void setHasWhitelist(boolean flag) { - this.propertyManager.setProperty((dedicatedserverproperties) -> { - return (DedicatedServerProperties) dedicatedserverproperties.whiteList.set(flag); - }); - } - - @Override - public void stop() { - super.stop(); - SystemUtils.f(); - } - - @Override - public boolean b(GameProfile gameprofile) { - return false; - } - - // CraftBukkit start - @Override - public boolean isDebugging() { - return this.getDedicatedServerProperties().debug; - } - - @Override - public CommandSender getBukkitSender(CommandListenerWrapper wrapper) { - return console; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/DedicatedServerProperties.java b/src/main/java/net/minecraft/server/DedicatedServerProperties.java deleted file mode 100644 index 0c3ec8357..000000000 --- a/src/main/java/net/minecraft/server/DedicatedServerProperties.java +++ /dev/null @@ -1,121 +0,0 @@ -package net.minecraft.server; - -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import joptsimple.OptionSet; // CraftBukkit - -public class DedicatedServerProperties extends PropertyManager { - - public final boolean debug = this.getBoolean("debug", false); // CraftBukkit - public final boolean onlineMode = this.getBoolean("online-mode", true); - public final boolean preventProxyConnections = this.getBoolean("prevent-proxy-connections", false); - public final String serverIp = this.getString("server-ip", ""); - public final boolean spawnAnimals = this.getBoolean("spawn-animals", true); - public final boolean spawnNpcs = this.getBoolean("spawn-npcs", true); - public final boolean pvp = this.getBoolean("pvp", true); - public final boolean allowFlight = this.getBoolean("allow-flight", false); - public final String resourcePack = this.getString("resource-pack", ""); - public final String motd = this.getString("motd", "A Minecraft Server"); - public final boolean forceGamemode = this.getBoolean("force-gamemode", false); - public final boolean enforceWhitelist = this.getBoolean("enforce-whitelist", false); - public final boolean generateStructures = this.getBoolean("generate-structures", true); - public final EnumDifficulty difficulty; - public final EnumGamemode gamemode; - public final String levelName; - public final String levelSeed; - public final WorldType levelType; - public final String generatorSettings; - public final int serverPort; - public final int maxBuildHeight; - public final Boolean announcePlayerAchievements; - public final boolean enableQuery; - public final int queryPort; - public final boolean enableRcon; - public final int rconPort; - public final String rconPassword; - public final String resourcePackHash; - public final String resourcePackSha1; - public final boolean hardcore; - public final boolean allowNether; - public final boolean spawnMonsters; - public final boolean snooperEnabled; - public final boolean useNativeTransport; - public final boolean enableCommandBlock; - public final int spawnProtection; - public final int opPermissionLevel; - public final int functionPermissionLevel; - public final long maxTickTime; - public final int viewDistance; - public final int maxPlayers; - public final int networkCompressionThreshold; - public final boolean broadcastRconToOps; - public final boolean broadcastConsoleToOps; - public final int maxWorldSize; - public final PropertyManager.EditableProperty playerIdleTimeout; - public final PropertyManager.EditableProperty whiteList; - - public final String rconIp; // Paper - Add rcon ip - - // CraftBukkit start - public DedicatedServerProperties(Properties properties, OptionSet optionset) { - super(properties, optionset); - // CraftBukkit end - this.difficulty = (EnumDifficulty) this.a("difficulty", a(EnumDifficulty::getById, EnumDifficulty::a), EnumDifficulty::c, EnumDifficulty.EASY); - this.gamemode = (EnumGamemode) this.a("gamemode", a(EnumGamemode::getById, EnumGamemode::a), EnumGamemode::b, EnumGamemode.SURVIVAL); - this.levelName = this.getString("level-name", "world"); - this.levelSeed = this.getString("level-seed", ""); - this.levelType = (WorldType) this.a("level-type", WorldType::getType, WorldType::name, WorldType.NORMAL); - this.generatorSettings = this.getString("generator-settings", ""); - this.serverPort = this.getInt("server-port", 25565); - this.maxBuildHeight = this.a("max-build-height", (integer) -> { - return MathHelper.clamp((integer + 8) / 16 * 16, 64, 256); - }, 256); - this.announcePlayerAchievements = this.b("announce-player-achievements"); - this.enableQuery = this.getBoolean("enable-query", false); - this.queryPort = this.getInt("query.port", 25565); - this.enableRcon = this.getBoolean("enable-rcon", false); - this.rconPort = this.getInt("rcon.port", 25575); - this.rconPassword = this.getString("rcon.password", ""); - this.resourcePackHash = this.a("resource-pack-hash"); - this.resourcePackSha1 = this.getString("resource-pack-sha1", ""); - this.hardcore = this.getBoolean("hardcore", false); - this.allowNether = this.getBoolean("allow-nether", true); - this.spawnMonsters = this.getBoolean("spawn-monsters", true); - if (this.getBoolean("snooper-enabled", true)) { - ; - } - - this.snooperEnabled = false; - this.useNativeTransport = this.getBoolean("use-native-transport", true); - this.enableCommandBlock = this.getBoolean("enable-command-block", false); - this.spawnProtection = this.getInt("spawn-protection", 16); - this.opPermissionLevel = this.getInt("op-permission-level", 4); - this.functionPermissionLevel = this.getInt("function-permission-level", 2); - this.maxTickTime = this.getLong("max-tick-time", TimeUnit.MINUTES.toMillis(1L)); - this.viewDistance = this.getInt("view-distance", 10); - this.maxPlayers = this.getInt("max-players", 20); - this.networkCompressionThreshold = this.getInt("network-compression-threshold", 256); - this.broadcastRconToOps = this.getBoolean("broadcast-rcon-to-ops", true); - this.broadcastConsoleToOps = this.getBoolean("broadcast-console-to-ops", true); - this.maxWorldSize = this.a("max-world-size", (integer) -> { - return MathHelper.clamp(integer, 1, 29999984); - }, 29999984); - this.playerIdleTimeout = this.b("player-idle-timeout", 0); - this.whiteList = this.b("white-list", false); - // Paper start - Configurable rcon ip - final String rconIp = this.getSettingIfExists("rcon.ip"); - this.rconIp = rconIp == null ? this.serverIp : rconIp; - // Paper end - } - - // CraftBukkit start - public static DedicatedServerProperties load(java.nio.file.Path java_nio_file_path, OptionSet optionset) { - return new DedicatedServerProperties(loadPropertiesFile(java_nio_file_path), optionset); - } - - @Override - protected DedicatedServerProperties reload(Properties properties, OptionSet optionset) { - return new DedicatedServerProperties(properties, optionset); - // CraftBukkit end - } -} diff --git a/src/main/java/net/minecraft/server/DedicatedServerSettings.java b/src/main/java/net/minecraft/server/DedicatedServerSettings.java deleted file mode 100644 index 34f2ba53d..000000000 --- a/src/main/java/net/minecraft/server/DedicatedServerSettings.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.minecraft.server; - -import java.util.function.UnaryOperator; -// CraftBukkit start -import java.io.File; -import joptsimple.OptionSet; -// CraftBukkit end - -public class DedicatedServerSettings { - - private final java.nio.file.Path path; - private DedicatedServerProperties properties; - - // CraftBukkit start - public DedicatedServerSettings(OptionSet optionset) { - this.path = ((File) optionset.valueOf("config")).toPath(); - this.properties = DedicatedServerProperties.load(path, optionset); - // CraftBukkit end - } - - public DedicatedServerProperties getProperties() { - return this.properties; - } - - public void save() { - this.properties.savePropertiesFile(this.path); - } - - public DedicatedServerSettings setProperty(UnaryOperator unaryoperator) { - (this.properties = (DedicatedServerProperties) unaryoperator.apply(this.properties)).savePropertiesFile(this.path); - return this; - } -} diff --git a/src/main/java/net/minecraft/server/DefinedStructure.java b/src/main/java/net/minecraft/server/DefinedStructure.java deleted file mode 100644 index 78dfaeeb7..000000000 --- a/src/main/java/net/minecraft/server/DefinedStructure.java +++ /dev/null @@ -1,819 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.datafixers.util.Pair; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import javax.annotation.Nullable; - -public class DefinedStructure { - - private final List> a = Lists.newArrayList(); - private final List b = Lists.newArrayList(); - private BlockPosition c; - private String d; - - public DefinedStructure() { - this.c = BlockPosition.ZERO; - this.d = "?"; - } - - public BlockPosition a() { - return this.c; - } - - public void a(String s) { - this.d = s; - } - - public String b() { - return this.d; - } - - public void a(World world, BlockPosition blockposition, BlockPosition blockposition1, boolean flag, @Nullable Block block) { - if (blockposition1.getX() >= 1 && blockposition1.getY() >= 1 && blockposition1.getZ() >= 1) { - BlockPosition blockposition2 = blockposition.a((BaseBlockPosition) blockposition1).b(-1, -1, -1); - List list = Lists.newArrayList(); - List list1 = Lists.newArrayList(); - List list2 = Lists.newArrayList(); - BlockPosition blockposition3 = new BlockPosition(Math.min(blockposition.getX(), blockposition2.getX()), Math.min(blockposition.getY(), blockposition2.getY()), Math.min(blockposition.getZ(), blockposition2.getZ())); - BlockPosition blockposition4 = new BlockPosition(Math.max(blockposition.getX(), blockposition2.getX()), Math.max(blockposition.getY(), blockposition2.getY()), Math.max(blockposition.getZ(), blockposition2.getZ())); - - this.c = blockposition1; - Iterator iterator = BlockPosition.a(blockposition3, blockposition4).iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition5 = (BlockPosition) iterator.next(); - BlockPosition blockposition6 = blockposition5.b(blockposition3); - IBlockData iblockdata = world.getType(blockposition5); - - if (block == null || block != iblockdata.getBlock()) { - TileEntity tileentity = world.getTileEntity(blockposition5); - - if (tileentity != null) { - NBTTagCompound nbttagcompound = tileentity.save(new NBTTagCompound()); - - nbttagcompound.remove("x"); - nbttagcompound.remove("y"); - nbttagcompound.remove("z"); - list1.add(new DefinedStructure.BlockInfo(blockposition6, iblockdata, nbttagcompound)); - } else if (!iblockdata.g(world, blockposition5) && !iblockdata.o(world, blockposition5)) { - list2.add(new DefinedStructure.BlockInfo(blockposition6, iblockdata, (NBTTagCompound) null)); - } else { - list.add(new DefinedStructure.BlockInfo(blockposition6, iblockdata, (NBTTagCompound) null)); - } - } - } - - List list3 = Lists.newArrayList(); - - list3.addAll(list); - list3.addAll(list1); - list3.addAll(list2); - this.a.clear(); - this.a.add(list3); - if (flag) { - this.a(world, blockposition3, blockposition4.b(1, 1, 1)); - } else { - this.b.clear(); - } - - } - } - - private void a(World world, BlockPosition blockposition, BlockPosition blockposition1) { - List list = world.a(Entity.class, new AxisAlignedBB(blockposition, blockposition1), (java.util.function.Predicate) (entity) -> { // CraftBukkit - decompile error - return !(entity instanceof EntityHuman); - }); - - this.b.clear(); - - Vec3D vec3d; - NBTTagCompound nbttagcompound; - BlockPosition blockposition2; - - for (Iterator iterator = list.iterator(); iterator.hasNext(); this.b.add(new DefinedStructure.EntityInfo(vec3d, blockposition2, nbttagcompound))) { - Entity entity = (Entity) iterator.next(); - - vec3d = new Vec3D(entity.locX - (double) blockposition.getX(), entity.locY - (double) blockposition.getY(), entity.locZ - (double) blockposition.getZ()); - nbttagcompound = new NBTTagCompound(); - entity.d(nbttagcompound); - if (entity instanceof EntityPainting) { - blockposition2 = ((EntityPainting) entity).getBlockPosition().b(blockposition); - } else { - blockposition2 = new BlockPosition(vec3d); - } - } - - } - - public List a(BlockPosition blockposition, DefinedStructureInfo definedstructureinfo, Block block) { - return this.a(blockposition, definedstructureinfo, block, true); - } - - public List a(BlockPosition blockposition, DefinedStructureInfo definedstructureinfo, Block block, boolean flag) { - List list = Lists.newArrayList(); - StructureBoundingBox structureboundingbox = definedstructureinfo.h(); - Iterator iterator = definedstructureinfo.a(this.a, blockposition).iterator(); - - while (iterator.hasNext()) { - DefinedStructure.BlockInfo definedstructure_blockinfo = (DefinedStructure.BlockInfo) iterator.next(); - BlockPosition blockposition1 = flag ? a(definedstructureinfo, definedstructure_blockinfo.a).a((BaseBlockPosition) blockposition) : definedstructure_blockinfo.a; - - if (structureboundingbox == null || structureboundingbox.b((BaseBlockPosition) blockposition1)) { - IBlockData iblockdata = definedstructure_blockinfo.b; - - if (iblockdata.getBlock() == block) { - list.add(new DefinedStructure.BlockInfo(blockposition1, iblockdata.a(definedstructureinfo.d()), definedstructure_blockinfo.c)); - } - } - } - - return list; - } - - public BlockPosition a(DefinedStructureInfo definedstructureinfo, BlockPosition blockposition, DefinedStructureInfo definedstructureinfo1, BlockPosition blockposition1) { - BlockPosition blockposition2 = a(definedstructureinfo, blockposition); - BlockPosition blockposition3 = a(definedstructureinfo1, blockposition1); - - return blockposition2.b(blockposition3); - } - - public static BlockPosition a(DefinedStructureInfo definedstructureinfo, BlockPosition blockposition) { - return a(blockposition, definedstructureinfo.c(), definedstructureinfo.d(), definedstructureinfo.e()); - } - - public void a(GeneratorAccess generatoraccess, BlockPosition blockposition, DefinedStructureInfo definedstructureinfo) { - definedstructureinfo.k(); - this.b(generatoraccess, blockposition, definedstructureinfo); - } - - public void b(GeneratorAccess generatoraccess, BlockPosition blockposition, DefinedStructureInfo definedstructureinfo) { - this.a(generatoraccess, blockposition, definedstructureinfo, 2); - } - - public boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition, DefinedStructureInfo definedstructureinfo, int i) { - if (this.a.isEmpty()) { - return false; - } else { - List list = definedstructureinfo.a(this.a, blockposition); - - if ((!list.isEmpty() || !definedstructureinfo.g() && !this.b.isEmpty()) && this.c.getX() >= 1 && this.c.getY() >= 1 && this.c.getZ() >= 1) { - StructureBoundingBox structureboundingbox = definedstructureinfo.h(); - List list1 = Lists.newArrayListWithCapacity(definedstructureinfo.l() ? list.size() : 0); - List> list2 = Lists.newArrayListWithCapacity(list.size()); - int j = Integer.MAX_VALUE; - int k = Integer.MAX_VALUE; - int l = Integer.MAX_VALUE; - int i1 = Integer.MIN_VALUE; - int j1 = Integer.MIN_VALUE; - int k1 = Integer.MIN_VALUE; - List list3 = a(generatoraccess, blockposition, definedstructureinfo, list); - Iterator iterator = list3.iterator(); - - TileEntity tileentity; - - while (iterator.hasNext()) { - DefinedStructure.BlockInfo definedstructure_blockinfo = (DefinedStructure.BlockInfo) iterator.next(); - BlockPosition blockposition1 = definedstructure_blockinfo.a; - - if (structureboundingbox == null || structureboundingbox.b((BaseBlockPosition) blockposition1)) { - Fluid fluid = definedstructureinfo.l() ? generatoraccess.getFluid(blockposition1) : null; - IBlockData iblockdata = definedstructure_blockinfo.b.a(definedstructureinfo.c()).a(definedstructureinfo.d()); - - if (definedstructure_blockinfo.c != null) { - tileentity = generatoraccess.getTileEntity(blockposition1); - Clearable.a(tileentity); - generatoraccess.setTypeAndData(blockposition1, Blocks.BARRIER.getBlockData(), 20); - } - - if (generatoraccess.setTypeAndData(blockposition1, iblockdata, i)) { - j = Math.min(j, blockposition1.getX()); - k = Math.min(k, blockposition1.getY()); - l = Math.min(l, blockposition1.getZ()); - i1 = Math.max(i1, blockposition1.getX()); - j1 = Math.max(j1, blockposition1.getY()); - k1 = Math.max(k1, blockposition1.getZ()); - list2.add(Pair.of(blockposition1, definedstructure_blockinfo.c)); - if (definedstructure_blockinfo.c != null) { - tileentity = generatoraccess.getTileEntity(blockposition1); - if (tileentity != null) { - definedstructure_blockinfo.c.setInt("x", blockposition1.getX()); - definedstructure_blockinfo.c.setInt("y", blockposition1.getY()); - definedstructure_blockinfo.c.setInt("z", blockposition1.getZ()); - tileentity.isLoadingStructure = true; // Paper - tileentity.load(definedstructure_blockinfo.c); - tileentity.a(definedstructureinfo.c()); - tileentity.a(definedstructureinfo.d()); - tileentity.isLoadingStructure = false; // Paper - } - } - - if (fluid != null && iblockdata.getBlock() instanceof IFluidContainer) { - ((IFluidContainer) iblockdata.getBlock()).place(generatoraccess, blockposition1, iblockdata, fluid); - if (!fluid.isSource()) { - list1.add(blockposition1); - } - } - } - } - } - - boolean flag = true; - EnumDirection[] aenumdirection = new EnumDirection[]{EnumDirection.UP, EnumDirection.NORTH, EnumDirection.EAST, EnumDirection.SOUTH, EnumDirection.WEST}; - - Iterator iterator1; - BlockPosition blockposition2; - IBlockData iblockdata1; - - while (flag && !list1.isEmpty()) { - flag = false; - iterator1 = list1.iterator(); - - while (iterator1.hasNext()) { - BlockPosition blockposition3 = (BlockPosition) iterator1.next(); - - blockposition2 = blockposition3; - Fluid fluid1 = generatoraccess.getFluid(blockposition3); - - for (int l1 = 0; l1 < aenumdirection.length && !fluid1.isSource(); ++l1) { - BlockPosition blockposition4 = blockposition2.shift(aenumdirection[l1]); - Fluid fluid2 = generatoraccess.getFluid(blockposition4); - - if (fluid2.getHeight(generatoraccess, blockposition4) > fluid1.getHeight(generatoraccess, blockposition2) || fluid2.isSource() && !fluid1.isSource()) { - fluid1 = fluid2; - blockposition2 = blockposition4; - } - } - - if (fluid1.isSource()) { - iblockdata1 = generatoraccess.getType(blockposition3); - Block block = iblockdata1.getBlock(); - - if (block instanceof IFluidContainer) { - ((IFluidContainer) block).place(generatoraccess, blockposition3, iblockdata1, fluid1); - flag = true; - iterator1.remove(); - } - } - } - } - - if (j <= i1) { - if (!definedstructureinfo.i()) { - VoxelShapeBitSet voxelshapebitset = new VoxelShapeBitSet(i1 - j + 1, j1 - k + 1, k1 - l + 1); - int i2 = j; - int j2 = k; - int k2 = l; - Iterator iterator2 = list2.iterator(); - - while (iterator2.hasNext()) { - Pair pair = (Pair) iterator2.next(); - BlockPosition blockposition5 = (BlockPosition) pair.getFirst(); - - voxelshapebitset.a(blockposition5.getX() - i2, blockposition5.getY() - j2, blockposition5.getZ() - k2, true, true); - } - - a(generatoraccess, i, voxelshapebitset, i2, j2, k2); - } - - iterator1 = list2.iterator(); - - while (iterator1.hasNext()) { - Pair pair1 = (Pair) iterator1.next(); - - blockposition2 = (BlockPosition) pair1.getFirst(); - if (!definedstructureinfo.i()) { - IBlockData iblockdata2 = generatoraccess.getType(blockposition2); - - iblockdata1 = Block.b(iblockdata2, generatoraccess, blockposition2); - if (iblockdata2 != iblockdata1) { - generatoraccess.setTypeAndData(blockposition2, iblockdata1, i & -2 | 16); - } - - generatoraccess.update(blockposition2, iblockdata1.getBlock()); - } - - if (pair1.getSecond() != null) { - tileentity = generatoraccess.getTileEntity(blockposition2); - if (tileentity != null) { - tileentity.update(); - } - } - } - } - - if (!definedstructureinfo.g()) { - this.a(generatoraccess, blockposition, definedstructureinfo.c(), definedstructureinfo.d(), definedstructureinfo.e(), structureboundingbox); - } - - return true; - } else { - return false; - } - } - } - - public static void a(GeneratorAccess generatoraccess, int i, VoxelShapeDiscrete voxelshapediscrete, int j, int k, int l) { - voxelshapediscrete.a((enumdirection, i1, j1, k1) -> { - BlockPosition blockposition = new BlockPosition(j + i1, k + j1, l + k1); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - IBlockData iblockdata = generatoraccess.getType(blockposition); - IBlockData iblockdata1 = generatoraccess.getType(blockposition1); - IBlockData iblockdata2 = iblockdata.updateState(enumdirection, iblockdata1, generatoraccess, blockposition, blockposition1); - - if (iblockdata != iblockdata2) { - generatoraccess.setTypeAndData(blockposition, iblockdata2, i & -2 | 16); - } - - IBlockData iblockdata3 = iblockdata1.updateState(enumdirection.opposite(), iblockdata2, generatoraccess, blockposition1, blockposition); - - if (iblockdata1 != iblockdata3) { - generatoraccess.setTypeAndData(blockposition1, iblockdata3, i & -2 | 16); - } - - }); - } - - public static List a(GeneratorAccess generatoraccess, BlockPosition blockposition, DefinedStructureInfo definedstructureinfo, List list) { - List list1 = Lists.newArrayList(); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - DefinedStructure.BlockInfo definedstructure_blockinfo = (DefinedStructure.BlockInfo) iterator.next(); - BlockPosition blockposition1 = a(definedstructureinfo, definedstructure_blockinfo.a).a((BaseBlockPosition) blockposition); - DefinedStructure.BlockInfo definedstructure_blockinfo1 = new DefinedStructure.BlockInfo(blockposition1, definedstructure_blockinfo.b, definedstructure_blockinfo.c); - - for (Iterator iterator1 = definedstructureinfo.j().iterator(); definedstructure_blockinfo1 != null && iterator1.hasNext(); definedstructure_blockinfo1 = ((DefinedStructureProcessor) iterator1.next()).a(generatoraccess, blockposition, definedstructure_blockinfo, definedstructure_blockinfo1, definedstructureinfo)) { - ; - } - - if (definedstructure_blockinfo1 != null) { - list1.add(definedstructure_blockinfo1); - } - } - - return list1; - } - - private void a(GeneratorAccess generatoraccess, BlockPosition blockposition, EnumBlockMirror enumblockmirror, EnumBlockRotation enumblockrotation, BlockPosition blockposition1, @Nullable StructureBoundingBox structureboundingbox) { - Iterator iterator = this.b.iterator(); - - while (iterator.hasNext()) { - DefinedStructure.EntityInfo definedstructure_entityinfo = (DefinedStructure.EntityInfo) iterator.next(); - BlockPosition blockposition2 = a(definedstructure_entityinfo.b, enumblockmirror, enumblockrotation, blockposition1).a((BaseBlockPosition) blockposition); - - if (structureboundingbox == null || structureboundingbox.b((BaseBlockPosition) blockposition2)) { - NBTTagCompound nbttagcompound = definedstructure_entityinfo.c; - Vec3D vec3d = a(definedstructure_entityinfo.a, enumblockmirror, enumblockrotation, blockposition1); - Vec3D vec3d1 = vec3d.add((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()); - NBTTagList nbttaglist = new NBTTagList(); - - nbttaglist.add(new NBTTagDouble(vec3d1.x)); - nbttaglist.add(new NBTTagDouble(vec3d1.y)); - nbttaglist.add(new NBTTagDouble(vec3d1.z)); - nbttagcompound.set("Pos", nbttaglist); - nbttagcompound.remove("UUIDMost"); - nbttagcompound.remove("UUIDLeast"); - a(generatoraccess, nbttagcompound).ifPresent((entity) -> { - float f = entity.a(enumblockmirror); - - f += entity.yaw - entity.a(enumblockrotation); - entity.setPositionRotation(vec3d1.x, vec3d1.y, vec3d1.z, f, entity.pitch); - generatoraccess.addEntity(entity); - }); - } - } - - } - - private static Optional a(GeneratorAccess generatoraccess, NBTTagCompound nbttagcompound) { - // CraftBukkit start - // try { - return EntityTypes.a(nbttagcompound, generatoraccess.getMinecraftWorld()); - // } catch (Exception exception) { - // return Optional.empty(); - // } - // CraftBukkit end - } - - public BlockPosition a(EnumBlockRotation enumblockrotation) { - switch (enumblockrotation) { - case COUNTERCLOCKWISE_90: - case CLOCKWISE_90: - return new BlockPosition(this.c.getZ(), this.c.getY(), this.c.getX()); - default: - return this.c; - } - } - - public static BlockPosition a(BlockPosition blockposition, EnumBlockMirror enumblockmirror, EnumBlockRotation enumblockrotation, BlockPosition blockposition1) { - int i = blockposition.getX(); - int j = blockposition.getY(); - int k = blockposition.getZ(); - boolean flag = true; - - switch (enumblockmirror) { - case LEFT_RIGHT: - k = -k; - break; - case FRONT_BACK: - i = -i; - break; - default: - flag = false; - } - - int l = blockposition1.getX(); - int i1 = blockposition1.getZ(); - - switch (enumblockrotation) { - case COUNTERCLOCKWISE_90: - return new BlockPosition(l - i1 + k, j, l + i1 - i); - case CLOCKWISE_90: - return new BlockPosition(l + i1 - k, j, i1 - l + i); - case CLOCKWISE_180: - return new BlockPosition(l + l - i, j, i1 + i1 - k); - default: - return flag ? new BlockPosition(i, j, k) : blockposition; - } - } - - private static Vec3D a(Vec3D vec3d, EnumBlockMirror enumblockmirror, EnumBlockRotation enumblockrotation, BlockPosition blockposition) { - double d0 = vec3d.x; - double d1 = vec3d.y; - double d2 = vec3d.z; - boolean flag = true; - - switch (enumblockmirror) { - case LEFT_RIGHT: - d2 = 1.0D - d2; - break; - case FRONT_BACK: - d0 = 1.0D - d0; - break; - default: - flag = false; - } - - int i = blockposition.getX(); - int j = blockposition.getZ(); - - switch (enumblockrotation) { - case COUNTERCLOCKWISE_90: - return new Vec3D((double) (i - j) + d2, d1, (double) (i + j + 1) - d0); - case CLOCKWISE_90: - return new Vec3D((double) (i + j + 1) - d2, d1, (double) (j - i) + d0); - case CLOCKWISE_180: - return new Vec3D((double) (i + i + 1) - d0, d1, (double) (j + j + 1) - d2); - default: - return flag ? new Vec3D(d0, d1, d2) : vec3d; - } - } - - public BlockPosition a(BlockPosition blockposition, EnumBlockMirror enumblockmirror, EnumBlockRotation enumblockrotation) { - return a(blockposition, enumblockmirror, enumblockrotation, this.a().getX(), this.a().getZ()); - } - - public static BlockPosition a(BlockPosition blockposition, EnumBlockMirror enumblockmirror, EnumBlockRotation enumblockrotation, int i, int j) { - --i; - --j; - int k = enumblockmirror == EnumBlockMirror.FRONT_BACK ? i : 0; - int l = enumblockmirror == EnumBlockMirror.LEFT_RIGHT ? j : 0; - BlockPosition blockposition1 = blockposition; - - switch (enumblockrotation) { - case COUNTERCLOCKWISE_90: - blockposition1 = blockposition.b(l, 0, i - k); - break; - case CLOCKWISE_90: - blockposition1 = blockposition.b(j - l, 0, k); - break; - case CLOCKWISE_180: - blockposition1 = blockposition.b(i - k, 0, j - l); - break; - case NONE: - blockposition1 = blockposition.b(k, 0, l); - } - - return blockposition1; - } - - public StructureBoundingBox b(DefinedStructureInfo definedstructureinfo, BlockPosition blockposition) { - EnumBlockRotation enumblockrotation = definedstructureinfo.d(); - BlockPosition blockposition1 = definedstructureinfo.e(); - BlockPosition blockposition2 = this.a(enumblockrotation); - EnumBlockMirror enumblockmirror = definedstructureinfo.c(); - int i = blockposition1.getX(); - int j = blockposition1.getZ(); - int k = blockposition2.getX() - 1; - int l = blockposition2.getY() - 1; - int i1 = blockposition2.getZ() - 1; - StructureBoundingBox structureboundingbox = new StructureBoundingBox(0, 0, 0, 0, 0, 0); - - switch (enumblockrotation) { - case COUNTERCLOCKWISE_90: - structureboundingbox = new StructureBoundingBox(i - j, 0, i + j - i1, i - j + k, l, i + j); - break; - case CLOCKWISE_90: - structureboundingbox = new StructureBoundingBox(i + j - k, 0, j - i, i + j, l, j - i + i1); - break; - case CLOCKWISE_180: - structureboundingbox = new StructureBoundingBox(i + i - k, 0, j + j - i1, i + i, l, j + j); - break; - case NONE: - structureboundingbox = new StructureBoundingBox(0, 0, 0, k, l, i1); - } - - switch (enumblockmirror) { - case LEFT_RIGHT: - this.a(enumblockrotation, i1, k, structureboundingbox, EnumDirection.NORTH, EnumDirection.SOUTH); - break; - case FRONT_BACK: - this.a(enumblockrotation, k, i1, structureboundingbox, EnumDirection.WEST, EnumDirection.EAST); - case NONE: - } - - structureboundingbox.a(blockposition.getX(), blockposition.getY(), blockposition.getZ()); - return structureboundingbox; - } - - private void a(EnumBlockRotation enumblockrotation, int i, int j, StructureBoundingBox structureboundingbox, EnumDirection enumdirection, EnumDirection enumdirection1) { - BlockPosition blockposition = BlockPosition.ZERO; - - if (enumblockrotation != EnumBlockRotation.CLOCKWISE_90 && enumblockrotation != EnumBlockRotation.COUNTERCLOCKWISE_90) { - if (enumblockrotation == EnumBlockRotation.CLOCKWISE_180) { - blockposition = blockposition.shift(enumdirection1, i); - } else { - blockposition = blockposition.shift(enumdirection, i); - } - } else { - blockposition = blockposition.shift(enumblockrotation.a(enumdirection), j); - } - - structureboundingbox.a(blockposition.getX(), 0, blockposition.getZ()); - } - - public NBTTagCompound a(NBTTagCompound nbttagcompound) { - if (this.a.isEmpty()) { - nbttagcompound.set("blocks", new NBTTagList()); - nbttagcompound.set("palette", new NBTTagList()); - } else { - List list = Lists.newArrayList(); - DefinedStructure.a definedstructure_a = new DefinedStructure.a(); - - list.add(definedstructure_a); - - for (int i = 1; i < this.a.size(); ++i) { - list.add(new DefinedStructure.a()); - } - - NBTTagList nbttaglist = new NBTTagList(); - List list1 = (List) this.a.get(0); - - for (int j = 0; j < list1.size(); ++j) { - DefinedStructure.BlockInfo definedstructure_blockinfo = (DefinedStructure.BlockInfo) list1.get(j); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - nbttagcompound1.set("pos", this.a(definedstructure_blockinfo.a.getX(), definedstructure_blockinfo.a.getY(), definedstructure_blockinfo.a.getZ())); - int k = definedstructure_a.a(definedstructure_blockinfo.b); - - nbttagcompound1.setInt("state", k); - if (definedstructure_blockinfo.c != null) { - nbttagcompound1.set("nbt", definedstructure_blockinfo.c); - } - - nbttaglist.add(nbttagcompound1); - - for (int l = 1; l < this.a.size(); ++l) { - DefinedStructure.a definedstructure_a1 = (DefinedStructure.a) list.get(l); - - definedstructure_a1.a(((DefinedStructure.BlockInfo) ((List) this.a.get(l)).get(j)).b, k); - } - } - - nbttagcompound.set("blocks", nbttaglist); - NBTTagList nbttaglist1; - Iterator iterator; - - if (list.size() == 1) { - nbttaglist1 = new NBTTagList(); - iterator = definedstructure_a.iterator(); - - while (iterator.hasNext()) { - IBlockData iblockdata = (IBlockData) iterator.next(); - - nbttaglist1.add(GameProfileSerializer.a(iblockdata)); - } - - nbttagcompound.set("palette", nbttaglist1); - } else { - nbttaglist1 = new NBTTagList(); - iterator = list.iterator(); - - while (iterator.hasNext()) { - DefinedStructure.a definedstructure_a2 = (DefinedStructure.a) iterator.next(); - NBTTagList nbttaglist2 = new NBTTagList(); - Iterator iterator1 = definedstructure_a2.iterator(); - - while (iterator1.hasNext()) { - IBlockData iblockdata1 = (IBlockData) iterator1.next(); - - nbttaglist2.add(GameProfileSerializer.a(iblockdata1)); - } - - nbttaglist1.add(nbttaglist2); - } - - nbttagcompound.set("palettes", nbttaglist1); - } - } - - NBTTagList nbttaglist3 = new NBTTagList(); - - NBTTagCompound nbttagcompound2; - - for (Iterator iterator2 = this.b.iterator(); iterator2.hasNext(); nbttaglist3.add(nbttagcompound2)) { - DefinedStructure.EntityInfo definedstructure_entityinfo = (DefinedStructure.EntityInfo) iterator2.next(); - - nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.set("pos", this.a(definedstructure_entityinfo.a.x, definedstructure_entityinfo.a.y, definedstructure_entityinfo.a.z)); - nbttagcompound2.set("blockPos", this.a(definedstructure_entityinfo.b.getX(), definedstructure_entityinfo.b.getY(), definedstructure_entityinfo.b.getZ())); - if (definedstructure_entityinfo.c != null) { - nbttagcompound2.set("nbt", definedstructure_entityinfo.c); - } - } - - nbttagcompound.set("entities", nbttaglist3); - nbttagcompound.set("size", this.a(this.c.getX(), this.c.getY(), this.c.getZ())); - nbttagcompound.setInt("DataVersion", SharedConstants.a().getWorldVersion()); - return nbttagcompound; - } - - public void b(NBTTagCompound nbttagcompound) { - this.a.clear(); - this.b.clear(); - NBTTagList nbttaglist = nbttagcompound.getList("size", 3); - - this.c = new BlockPosition(nbttaglist.e(0), nbttaglist.e(1), nbttaglist.e(2)); - NBTTagList nbttaglist1 = nbttagcompound.getList("blocks", 10); - NBTTagList nbttaglist2; - int i; - - if (nbttagcompound.hasKeyOfType("palettes", 9)) { - nbttaglist2 = nbttagcompound.getList("palettes", 9); - - for (i = 0; i < nbttaglist2.size(); ++i) { - this.a(nbttaglist2.b(i), nbttaglist1); - } - } else { - this.a(nbttagcompound.getList("palette", 10), nbttaglist1); - } - - nbttaglist2 = nbttagcompound.getList("entities", 10); - - for (i = 0; i < nbttaglist2.size(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist2.getCompound(i); - NBTTagList nbttaglist3 = nbttagcompound1.getList("pos", 6); - Vec3D vec3d = new Vec3D(nbttaglist3.h(0), nbttaglist3.h(1), nbttaglist3.h(2)); - NBTTagList nbttaglist4 = nbttagcompound1.getList("blockPos", 3); - BlockPosition blockposition = new BlockPosition(nbttaglist4.e(0), nbttaglist4.e(1), nbttaglist4.e(2)); - - if (nbttagcompound1.hasKey("nbt")) { - NBTTagCompound nbttagcompound2 = nbttagcompound1.getCompound("nbt"); - - this.b.add(new DefinedStructure.EntityInfo(vec3d, blockposition, nbttagcompound2)); - } - } - - } - - private void a(NBTTagList nbttaglist, NBTTagList nbttaglist1) { - DefinedStructure.a definedstructure_a = new DefinedStructure.a(); - List list = Lists.newArrayList(); - - int i; - - for (i = 0; i < nbttaglist.size(); ++i) { - definedstructure_a.a(GameProfileSerializer.d(nbttaglist.getCompound(i)), i); - } - - for (i = 0; i < nbttaglist1.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist1.getCompound(i); - NBTTagList nbttaglist2 = nbttagcompound.getList("pos", 3); - BlockPosition blockposition = new BlockPosition(nbttaglist2.e(0), nbttaglist2.e(1), nbttaglist2.e(2)); - IBlockData iblockdata = definedstructure_a.a(nbttagcompound.getInt("state")); - NBTTagCompound nbttagcompound1; - - if (nbttagcompound.hasKey("nbt")) { - nbttagcompound1 = nbttagcompound.getCompound("nbt"); - } else { - nbttagcompound1 = null; - } - - list.add(new DefinedStructure.BlockInfo(blockposition, iblockdata, nbttagcompound1)); - } - - list.sort(Comparator.comparingInt((definedstructure_blockinfo) -> { - return definedstructure_blockinfo.a.getY(); - })); - this.a.add(list); - } - - private NBTTagList a(int... aint) { - NBTTagList nbttaglist = new NBTTagList(); - int[] aint1 = aint; - int i = aint.length; - - for (int j = 0; j < i; ++j) { - int k = aint1[j]; - - nbttaglist.add(new NBTTagInt(k)); - } - - return nbttaglist; - } - - private NBTTagList a(double... adouble) { - NBTTagList nbttaglist = new NBTTagList(); - double[] adouble1 = adouble; - int i = adouble.length; - - for (int j = 0; j < i; ++j) { - double d0 = adouble1[j]; - - nbttaglist.add(new NBTTagDouble(d0)); - } - - return nbttaglist; - } - - public static class EntityInfo { - - public final Vec3D a; - public final BlockPosition b; - public final NBTTagCompound c; - - public EntityInfo(Vec3D vec3d, BlockPosition blockposition, NBTTagCompound nbttagcompound) { - this.a = vec3d; - this.b = blockposition; - this.c = nbttagcompound; - } - } - - public static class BlockInfo { - - public final BlockPosition a; - public final IBlockData b; - public final NBTTagCompound c; - - public BlockInfo(BlockPosition blockposition, IBlockData iblockdata, @Nullable NBTTagCompound nbttagcompound) { - this.a = blockposition; - this.b = iblockdata; - this.c = nbttagcompound; - } - - public String toString() { - return String.format("", this.a, this.b, this.c); - } - } - - static class a implements Iterable { - - public static final IBlockData a = Blocks.AIR.getBlockData(); - private final RegistryBlockID b; - private int c; - - private a() { - this.b = new RegistryBlockID<>(16); - } - - public int a(IBlockData iblockdata) { - int i = this.b.getId(iblockdata); - - if (i == -1) { - i = this.c++; - this.b.a(iblockdata, i); - } - - return i; - } - - @Nullable - public IBlockData a(int i) { - IBlockData iblockdata = (IBlockData) this.b.fromId(i); - - return iblockdata == null ? a : iblockdata; // CraftBukkit - decompile error - } - - public Iterator iterator() { - return this.b.iterator(); - } - - public void a(IBlockData iblockdata, int i) { - this.b.a(iblockdata, i); - } - } -} diff --git a/src/main/java/net/minecraft/server/DefinedStructureManager.java b/src/main/java/net/minecraft/server/DefinedStructureManager.java deleted file mode 100644 index fb27bd097..000000000 --- a/src/main/java/net/minecraft/server/DefinedStructureManager.java +++ /dev/null @@ -1,236 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.mojang.datafixers.DataFixer; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.InvalidPathException; -import java.nio.file.LinkOption; -import java.util.Map; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class DefinedStructureManager implements IResourcePackListener { - - private static final Logger LOGGER = LogManager.getLogger(); - private final Map b = Maps.newConcurrentMap(); // SPIGOT-5287 - private final DataFixer c; - private final MinecraftServer d; - private final java.nio.file.Path e; - - public DefinedStructureManager(MinecraftServer minecraftserver, File file, DataFixer datafixer) { - this.d = minecraftserver; - this.c = datafixer; - this.e = file.toPath().resolve("generated").normalize(); - minecraftserver.getResourceManager().a((IReloadListener) this); - } - - public DefinedStructure a(MinecraftKey minecraftkey) { - DefinedStructure definedstructure = this.b(minecraftkey); - - if (definedstructure == null) { - definedstructure = new DefinedStructure(); - this.b.put(minecraftkey, definedstructure); - } - - return definedstructure; - } - - @Nullable - public DefinedStructure b(MinecraftKey minecraftkey) { - return (DefinedStructure) this.b.computeIfAbsent(minecraftkey, (minecraftkey1) -> { - DefinedStructure definedstructure = this.f(minecraftkey1); - - return definedstructure != null ? definedstructure : this.e(minecraftkey1); - }); - } - - @Override - public void a(IResourceManager iresourcemanager) { - this.b.clear(); - } - - @Nullable - private DefinedStructure e(MinecraftKey minecraftkey) { - MinecraftKey minecraftkey1 = new MinecraftKey(minecraftkey.getNamespace(), "structures/" + minecraftkey.getKey() + ".nbt"); - - try { - IResource iresource = this.d.getResourceManager().a(minecraftkey1); - Throwable throwable = null; - - DefinedStructure definedstructure; - - try { - definedstructure = this.a(iresource.b()); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (iresource != null) { - if (throwable != null) { - try { - iresource.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - iresource.close(); - } - } - - } - - return definedstructure; - } catch (FileNotFoundException filenotfoundexception) { - return null; - } catch (Throwable throwable3) { - DefinedStructureManager.LOGGER.error("Couldn't load structure {}: {}", minecraftkey, throwable3.toString()); - return null; - } - } - - @Nullable - private DefinedStructure f(MinecraftKey minecraftkey) { - if (!this.e.toFile().isDirectory()) { - return null; - } else { - java.nio.file.Path java_nio_file_path = this.b(minecraftkey, ".nbt"); - - try { - FileInputStream fileinputstream = new FileInputStream(java_nio_file_path.toFile()); - Throwable throwable = null; - - DefinedStructure definedstructure; - - try { - definedstructure = this.a((InputStream) fileinputstream); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (fileinputstream != null) { - if (throwable != null) { - try { - fileinputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - fileinputstream.close(); - } - } - - } - - return definedstructure; - } catch (FileNotFoundException filenotfoundexception) { - return null; - } catch (IOException ioexception) { - DefinedStructureManager.LOGGER.error("Couldn't load structure from {}", java_nio_file_path, ioexception); - return null; - } - } - } - - private DefinedStructure a(InputStream inputstream) throws IOException { - NBTTagCompound nbttagcompound = NBTCompressedStreamTools.a(inputstream); - - if (!nbttagcompound.hasKeyOfType("DataVersion", 99)) { - nbttagcompound.setInt("DataVersion", 500); - } - - DefinedStructure definedstructure = new DefinedStructure(); - - definedstructure.b(GameProfileSerializer.a(this.c, DataFixTypes.STRUCTURE, nbttagcompound, nbttagcompound.getInt("DataVersion"))); - return definedstructure; - } - - public boolean c(MinecraftKey minecraftkey) { - DefinedStructure definedstructure = (DefinedStructure) this.b.get(minecraftkey); - - if (definedstructure == null) { - return false; - } else { - java.nio.file.Path java_nio_file_path = this.b(minecraftkey, ".nbt"); - java.nio.file.Path java_nio_file_path1 = java_nio_file_path.getParent(); - - if (java_nio_file_path1 == null) { - return false; - } else { - try { - Files.createDirectories(Files.exists(java_nio_file_path1, new LinkOption[0]) ? java_nio_file_path1.toRealPath() : java_nio_file_path1); - } catch (IOException ioexception) { - DefinedStructureManager.LOGGER.error("Failed to create parent directory: {}", java_nio_file_path1); - return false; - } - - NBTTagCompound nbttagcompound = definedstructure.a(new NBTTagCompound()); - - try { - FileOutputStream fileoutputstream = new FileOutputStream(java_nio_file_path.toFile()); - Throwable throwable = null; - - try { - NBTCompressedStreamTools.a(nbttagcompound, (OutputStream) fileoutputstream); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (fileoutputstream != null) { - if (throwable != null) { - try { - fileoutputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - fileoutputstream.close(); - } - } - - } - - return true; - } catch (Throwable throwable3) { - return false; - } - } - } - } - - private java.nio.file.Path a(MinecraftKey minecraftkey, String s) { - try { - java.nio.file.Path java_nio_file_path = this.e.resolve(minecraftkey.getNamespace()); - java.nio.file.Path java_nio_file_path1 = java_nio_file_path.resolve("structures"); - - return FileUtils.b(java_nio_file_path1, minecraftkey.getKey(), s); - } catch (InvalidPathException invalidpathexception) { - throw new ResourceKeyInvalidException("Invalid resource path: " + minecraftkey, invalidpathexception); - } - } - - private java.nio.file.Path b(MinecraftKey minecraftkey, String s) { - if (minecraftkey.getKey().contains("//")) { - throw new ResourceKeyInvalidException("Invalid resource path: " + minecraftkey); - } else { - java.nio.file.Path java_nio_file_path = this.a(minecraftkey, s); - - if (java_nio_file_path.startsWith(this.e) && FileUtils.a(java_nio_file_path) && FileUtils.b(java_nio_file_path)) { - return java_nio_file_path; - } else { - throw new ResourceKeyInvalidException("Invalid resource path: " + java_nio_file_path); - } - } - } - - public void d(MinecraftKey minecraftkey) { - this.b.remove(minecraftkey); - } -} diff --git a/src/main/java/net/minecraft/server/DimensionManager.java b/src/main/java/net/minecraft/server/DimensionManager.java deleted file mode 100644 index ac03498fa..000000000 --- a/src/main/java/net/minecraft/server/DimensionManager.java +++ /dev/null @@ -1,95 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.types.DynamicOps; -import java.io.File; -import java.util.function.BiFunction; -import javax.annotation.Nullable; - -public class DimensionManager implements MinecraftSerializable { - - // CraftBukkit start - public static final DimensionManager OVERWORLD = register("overworld", new DimensionManager(1, "", "", WorldProviderNormal::new, true, null)); - public static final DimensionManager NETHER = register("the_nether", new DimensionManager(0, "_nether", "DIM-1", WorldProviderHell::new, false, null)); - public static final DimensionManager THE_END = register("the_end", new DimensionManager(2, "_end", "DIM1", WorldProviderTheEnd::new, false, null)); - // CraftBukkit end - private final int id; - private final String suffix; - public final String folder; - public final BiFunction providerFactory; - private final boolean hasSkyLight; - - public static DimensionManager register(String s, DimensionManager dimensionmanager) { - return (DimensionManager) IRegistry.a(IRegistry.DIMENSION_TYPE, dimensionmanager.id, s, dimensionmanager); - } - - // CraftBukkit - add type - public DimensionManager(int i, String s, String s1, BiFunction bifunction, boolean flag, DimensionManager type) { - this.id = i; - this.suffix = s; - this.folder = s1; - this.providerFactory = bifunction; - this.hasSkyLight = flag; - this.type = type; // CraftBukkit - } - - public static DimensionManager a(Dynamic dynamic) { - return (DimensionManager) IRegistry.DIMENSION_TYPE.get(new MinecraftKey(dynamic.asString(""))); - } - - public static Iterable a() { - return IRegistry.DIMENSION_TYPE; - } - - public int getDimensionID() { - return this.id + -1; - } - - public String getSuffix() { - return this.suffix; - } - - public File a(File file) { - return this.folder.isEmpty() ? file : new File(file, this.folder); - } - - public WorldProvider getWorldProvider(World world) { - return (WorldProvider) this.providerFactory.apply(world, this); - } - - public String toString() { - return a(this).toString(); - } - - @Nullable - public static DimensionManager a(int i) { - return (DimensionManager) IRegistry.DIMENSION_TYPE.fromId(i - -1); - } - - @Nullable - public static DimensionManager a(MinecraftKey minecraftkey) { - return (DimensionManager) IRegistry.DIMENSION_TYPE.get(minecraftkey); - } - - @Nullable - public static MinecraftKey a(DimensionManager dimensionmanager) { - return IRegistry.DIMENSION_TYPE.getKey(dimensionmanager); - } - - public boolean hasSkyLight() { - return this.hasSkyLight; - } - - @Override - public T a(DynamicOps dynamicops) { - return dynamicops.createString(IRegistry.DIMENSION_TYPE.getKey(this).toString()); - } - - // CraftBukkit start - private final DimensionManager type; - - public DimensionManager getType() { - return (type == null) ? this : type; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/DispenseBehaviorBoat.java b/src/main/java/net/minecraft/server/DispenseBehaviorBoat.java deleted file mode 100644 index 174e3f92d..000000000 --- a/src/main/java/net/minecraft/server/DispenseBehaviorBoat.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.event.block.BlockDispenseEvent; -// CraftBukkit end - -public class DispenseBehaviorBoat extends DispenseBehaviorItem { - - private final DispenseBehaviorItem b = new DispenseBehaviorItem(); - private final EntityBoat.EnumBoatType c; - - public DispenseBehaviorBoat(EntityBoat.EnumBoatType entityboat_enumboattype) { - this.c = entityboat_enumboattype; - } - - @Override - public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - 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); - double d3; - - if (world.getFluid(blockposition).a(TagsFluid.WATER)) { - d3 = 1.0D; - } else { - if (!world.getType(blockposition).isAir() || !world.getFluid(blockposition.down()).a(TagsFluid.WATER)) { - return this.b.dispense(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.add(1); - return itemstack; - } - - if (!event.getItem().equals(craftItem)) { - itemstack.add(1); - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - - EntityBoat entityboat = new EntityBoat(world, event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ()); - // CraftBukkit end - - entityboat.setType(this.c); - entityboat.yaw = enumdirection.l(); - if (!world.addEntity(entityboat)) itemstack.add(1); // CraftBukkit - // itemstack.subtract(1); // CraftBukkit - handled during event processing - return itemstack; - } - - @Override - protected void a(ISourceBlock isourceblock) { - isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); - } -} diff --git a/src/main/java/net/minecraft/server/DispenseBehaviorItem.java b/src/main/java/net/minecraft/server/DispenseBehaviorItem.java deleted file mode 100644 index 722c0048c..000000000 --- a/src/main/java/net/minecraft/server/DispenseBehaviorItem.java +++ /dev/null @@ -1,96 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.CraftVector; -import org.bukkit.event.block.BlockDispenseEvent; -// CraftBukkit end - -public class DispenseBehaviorItem implements IDispenseBehavior { - - public DispenseBehaviorItem() {} - - @Override - public final ItemStack dispense(ISourceBlock isourceblock, ItemStack itemstack) { - ItemStack itemstack1 = this.a(isourceblock, itemstack); - - this.a(isourceblock); - this.a(isourceblock, (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - return itemstack1; - } - - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - IPosition iposition = BlockDispenser.a(isourceblock); - ItemStack itemstack1 = itemstack.cloneAndSubtract(1); - - // CraftBukkit start - if (!a(isourceblock.getWorld(), itemstack1, 6, enumdirection, isourceblock)) { - itemstack.add(1); - } - // CraftBukkit end - return itemstack; - } - - // CraftBukkit start - void -> boolean return, IPosition -> ISourceBlock last argument - public static boolean a(World world, ItemStack itemstack, int i, EnumDirection enumdirection, ISourceBlock isourceblock) { - if (itemstack.isEmpty()) return true; - 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.setMot(world.random.nextGaussian() * 0.007499999832361937D * (double) i + (double) enumdirection.getAdjacentX() * d3, world.random.nextGaussian() * 0.007499999832361937D * (double) i + 0.20000000298023224D, world.random.nextGaussian() * 0.007499999832361937D * (double) i + (double) enumdirection.getAdjacentZ() * d3); - - // 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(), CraftVector.toBukkit(entityitem.getMot())); - if (!BlockDispenser.eventFired) { - world.getServer().getPluginManager().callEvent(event); - } - - if (event.isCancelled()) { - return false; - } - - entityitem.setItemStack(CraftItemStack.asNMSCopy(event.getItem())); - entityitem.setMot(CraftVector.toNMS(event.getVelocity())); - - if (!event.getItem().getType().equals(craftItem.getType())) { - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior.getClass() != DispenseBehaviorItem.class) { - idispensebehavior.dispense(isourceblock, eventStack); - } else { - world.addEntity(entityitem); - } - return false; - } - - world.addEntity(entityitem); - - return true; - // CraftBukkit end - } - - protected void a(ISourceBlock isourceblock) { - isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); - } - - protected void a(ISourceBlock isourceblock, EnumDirection enumdirection) { - isourceblock.getWorld().triggerEffect(2000, isourceblock.getBlockPosition(), enumdirection.a()); - } -} diff --git a/src/main/java/net/minecraft/server/DispenseBehaviorProjectile.java b/src/main/java/net/minecraft/server/DispenseBehaviorProjectile.java deleted file mode 100644 index 38f920538..000000000 --- a/src/main/java/net/minecraft/server/DispenseBehaviorProjectile.java +++ /dev/null @@ -1,68 +0,0 @@ -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() {} - - @Override - public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - World world = isourceblock.getWorld(); - IPosition iposition = BlockDispenser.a(isourceblock); - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - IProjectile iprojectile = this.a(world, iposition, itemstack); - - // iprojectile.shoot((double) enumdirection.getAdjacentX(), (double) ((float) enumdirection.getAdjacentY() + 0.1F), (double) enumdirection.getAdjacentZ(), this.getPower(), 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((double) enumdirection.getAdjacentX(), (double) ((float) enumdirection.getAdjacentY() + 0.1F), (double) enumdirection.getAdjacentZ())); - if (!BlockDispenser.eventFired) { - world.getServer().getPluginManager().callEvent(event); - } - - if (event.isCancelled()) { - itemstack.add(1); - return itemstack; - } - - if (!event.getItem().equals(craftItem)) { - itemstack.add(1); - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(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((TileEntityDispenser) isourceblock.getTileEntity()); - // CraftBukkit end - world.addEntity((Entity) iprojectile); - // itemstack.subtract(1); // CraftBukkit - Handled during event processing - return itemstack; - } - - @Override - protected void a(ISourceBlock isourceblock) { - isourceblock.getWorld().triggerEffect(1002, isourceblock.getBlockPosition(), 0); - } - - protected abstract IProjectile a(World world, IPosition iposition, ItemStack itemstack); - - protected float a() { - return 6.0F; - } - - protected float getPower() { - return 1.1F; - } -} diff --git a/src/main/java/net/minecraft/server/DispenseBehaviorShulkerBox.java b/src/main/java/net/minecraft/server/DispenseBehaviorShulkerBox.java deleted file mode 100644 index d8f2e2f8e..000000000 --- a/src/main/java/net/minecraft/server/DispenseBehaviorShulkerBox.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.event.block.BlockDispenseEvent; -// CraftBukkit end - -public class DispenseBehaviorShulkerBox extends DispenseBehaviorMaybe { - - public DispenseBehaviorShulkerBox() {} - - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - this.dispensed = false; - Item item = itemstack.getItem(); - - if (item instanceof ItemBlock) { - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - BlockPosition blockposition = isourceblock.getBlockPosition().shift(enumdirection); - EnumDirection enumdirection1 = isourceblock.getWorld().isEmpty(blockposition.down()) ? enumdirection : EnumDirection.UP; - - // CraftBukkit start - org.bukkit.block.Block bukkitBlock = isourceblock.getWorld().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) { - isourceblock.getWorld().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 = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - // CraftBukkit end - - this.dispensed = ((ItemBlock) item).a((BlockActionContext) (new BlockActionContextDirectional(isourceblock.getWorld(), blockposition, enumdirection, itemstack, enumdirection1))) == EnumInteractionResult.SUCCESS; - } - - return itemstack; - } -} diff --git a/src/main/java/net/minecraft/server/DispenserRegistry.java b/src/main/java/net/minecraft/server/DispenserRegistry.java deleted file mode 100644 index d474197c1..000000000 --- a/src/main/java/net/minecraft/server/DispenserRegistry.java +++ /dev/null @@ -1,162 +0,0 @@ -package net.minecraft.server; - -import java.io.PrintStream; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.Function; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import java.util.List; -import org.bukkit.Location; -import org.bukkit.TreeType; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.DummyGeneratorAccess; -import org.bukkit.event.block.BlockDispenseEvent; -import org.bukkit.event.world.StructureGrowEvent; -// CraftBukkit end - -public class DispenserRegistry { - - public static final PrintStream a = System.out; - private static boolean b; - private static final Logger LOGGER = LogManager.getLogger(); - - public static void init() { - if (!DispenserRegistry.b) { - DispenserRegistry.b = true; - if (IRegistry.f.c()) { - throw new IllegalStateException("Unable to load registries"); - } else { - BlockFire.d(); - BlockComposter.d(); - if (EntityTypes.getName(EntityTypes.PLAYER) == null) { - throw new IllegalStateException("Failed loading EntityTypes"); - } else { - PotionBrewer.a(); - PlayerSelector.a(); - IDispenseBehavior.c(); - ArgumentRegistry.a(); - d(); - } - // CraftBukkit start - easier than fixing the decompile - DataConverterFlattenData.a(1008, "{Name:'minecraft:oak_sign',Properties:{rotation:'0'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'0'}}"); - DataConverterFlattenData.a(1009, "{Name:'minecraft:oak_sign',Properties:{rotation:'1'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'1'}}"); - DataConverterFlattenData.a(1010, "{Name:'minecraft:oak_sign',Properties:{rotation:'2'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'2'}}"); - DataConverterFlattenData.a(1011, "{Name:'minecraft:oak_sign',Properties:{rotation:'3'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'3'}}"); - DataConverterFlattenData.a(1012, "{Name:'minecraft:oak_sign',Properties:{rotation:'4'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'4'}}"); - DataConverterFlattenData.a(1013, "{Name:'minecraft:oak_sign',Properties:{rotation:'5'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'5'}}"); - DataConverterFlattenData.a(1014, "{Name:'minecraft:oak_sign',Properties:{rotation:'6'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'6'}}"); - DataConverterFlattenData.a(1015, "{Name:'minecraft:oak_sign',Properties:{rotation:'7'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'7'}}"); - DataConverterFlattenData.a(1016, "{Name:'minecraft:oak_sign',Properties:{rotation:'8'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'8'}}"); - DataConverterFlattenData.a(1017, "{Name:'minecraft:oak_sign',Properties:{rotation:'9'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'9'}}"); - DataConverterFlattenData.a(1018, "{Name:'minecraft:oak_sign',Properties:{rotation:'10'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'10'}}"); - DataConverterFlattenData.a(1019, "{Name:'minecraft:oak_sign',Properties:{rotation:'11'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'11'}}"); - DataConverterFlattenData.a(1020, "{Name:'minecraft:oak_sign',Properties:{rotation:'12'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'12'}}"); - DataConverterFlattenData.a(1021, "{Name:'minecraft:oak_sign',Properties:{rotation:'13'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'13'}}"); - DataConverterFlattenData.a(1022, "{Name:'minecraft:oak_sign',Properties:{rotation:'14'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'14'}}"); - DataConverterFlattenData.a(1023, "{Name:'minecraft:oak_sign',Properties:{rotation:'15'}}", "{Name:'minecraft:standing_sign',Properties:{rotation:'15'}}"); - DataConverterMaterialId.ID_MAPPING.put(323, "minecraft:oak_sign"); - - DataConverterFlattenData.a(1440, "{Name:\'minecraft:portal\',Properties:{axis:\'x\'}}", new String[]{"{Name:\'minecraft:portal\',Properties:{axis:\'x\'}}"}); - - DataConverterMaterialId.ID_MAPPING.put(409, "minecraft:prismarine_shard"); - DataConverterMaterialId.ID_MAPPING.put(410, "minecraft:prismarine_crystals"); - DataConverterMaterialId.ID_MAPPING.put(411, "minecraft:rabbit"); - DataConverterMaterialId.ID_MAPPING.put(412, "minecraft:cooked_rabbit"); - DataConverterMaterialId.ID_MAPPING.put(413, "minecraft:rabbit_stew"); - DataConverterMaterialId.ID_MAPPING.put(414, "minecraft:rabbit_foot"); - DataConverterMaterialId.ID_MAPPING.put(415, "minecraft:rabbit_hide"); - DataConverterMaterialId.ID_MAPPING.put(416, "minecraft:armor_stand"); - - DataConverterMaterialId.ID_MAPPING.put(423, "minecraft:mutton"); - DataConverterMaterialId.ID_MAPPING.put(424, "minecraft:cooked_mutton"); - DataConverterMaterialId.ID_MAPPING.put(425, "minecraft:banner"); - DataConverterMaterialId.ID_MAPPING.put(426, "minecraft:end_crystal"); - DataConverterMaterialId.ID_MAPPING.put(427, "minecraft:spruce_door"); - DataConverterMaterialId.ID_MAPPING.put(428, "minecraft:birch_door"); - DataConverterMaterialId.ID_MAPPING.put(429, "minecraft:jungle_door"); - DataConverterMaterialId.ID_MAPPING.put(430, "minecraft:acacia_door"); - DataConverterMaterialId.ID_MAPPING.put(431, "minecraft:dark_oak_door"); - DataConverterMaterialId.ID_MAPPING.put(432, "minecraft:chorus_fruit"); - DataConverterMaterialId.ID_MAPPING.put(433, "minecraft:chorus_fruit_popped"); - DataConverterMaterialId.ID_MAPPING.put(434, "minecraft:beetroot"); - DataConverterMaterialId.ID_MAPPING.put(435, "minecraft:beetroot_seeds"); - DataConverterMaterialId.ID_MAPPING.put(436, "minecraft:beetroot_soup"); - DataConverterMaterialId.ID_MAPPING.put(437, "minecraft:dragon_breath"); - DataConverterMaterialId.ID_MAPPING.put(438, "minecraft:splash_potion"); - DataConverterMaterialId.ID_MAPPING.put(439, "minecraft:spectral_arrow"); - DataConverterMaterialId.ID_MAPPING.put(440, "minecraft:tipped_arrow"); - DataConverterMaterialId.ID_MAPPING.put(441, "minecraft:lingering_potion"); - DataConverterMaterialId.ID_MAPPING.put(442, "minecraft:shield"); - DataConverterMaterialId.ID_MAPPING.put(443, "minecraft:elytra"); - DataConverterMaterialId.ID_MAPPING.put(444, "minecraft:spruce_boat"); - DataConverterMaterialId.ID_MAPPING.put(445, "minecraft:birch_boat"); - DataConverterMaterialId.ID_MAPPING.put(446, "minecraft:jungle_boat"); - DataConverterMaterialId.ID_MAPPING.put(447, "minecraft:acacia_boat"); - DataConverterMaterialId.ID_MAPPING.put(448, "minecraft:dark_oak_boat"); - DataConverterMaterialId.ID_MAPPING.put(449, "minecraft:totem_of_undying"); - DataConverterMaterialId.ID_MAPPING.put(450, "minecraft:shulker_shell"); - DataConverterMaterialId.ID_MAPPING.put(452, "minecraft:iron_nugget"); - DataConverterMaterialId.ID_MAPPING.put(453, "minecraft:knowledge_book"); - - DataConverterSpawnEgg.ID_MAPPING[23] = "Arrow"; - // CraftBukkit end - } - } - } - - private static void a(IRegistry iregistry, Function function, Set set) { - LocaleLanguage localelanguage = LocaleLanguage.a(); - - iregistry.iterator().forEachRemaining((object) -> { - String s = (String) function.apply(object); - - if (!localelanguage.b(s)) { - set.add(s); - } - - }); - } - - public static Set b() { - Set set = new TreeSet(); - - a(IRegistry.ENTITY_TYPE, EntityTypes::f, set); - a(IRegistry.MOB_EFFECT, MobEffectList::c, set); - a(IRegistry.ITEM, Item::getName, set); - a(IRegistry.ENCHANTMENT, Enchantment::g, set); - a(IRegistry.BIOME, BiomeBase::j, set); - a(IRegistry.BLOCK, Block::l, set); - a(IRegistry.CUSTOM_STAT, (minecraftkey) -> { - return "stat." + minecraftkey.toString().replace(':', '.'); - }, set); - return set; - } - - public static void c() { - if (!DispenserRegistry.b) { - throw new IllegalArgumentException("Not bootstrapped"); - } else if (!SharedConstants.b) { - b().forEach((s) -> { - DispenserRegistry.LOGGER.error("Missing translations: " + s); - }); - } - } - - private static void d() { - if (DispenserRegistry.LOGGER.isDebugEnabled()) { - System.setErr(new DebugOutputStream("STDERR", System.err)); - System.setOut(new DebugOutputStream("STDOUT", DispenserRegistry.a)); - } else { - System.setErr(new RedirectStream("STDERR", System.err)); - System.setOut(new RedirectStream("STDOUT", DispenserRegistry.a)); - } - - } - - public static void a(String s) { - DispenserRegistry.a.println(s); - } -} diff --git a/src/main/java/net/minecraft/server/DragonControllerLandedFlame.java b/src/main/java/net/minecraft/server/DragonControllerLandedFlame.java deleted file mode 100644 index 577d1d207..000000000 --- a/src/main/java/net/minecraft/server/DragonControllerLandedFlame.java +++ /dev/null @@ -1,101 +0,0 @@ -package net.minecraft.server; - -public class DragonControllerLandedFlame extends AbstractDragonControllerLanded { - - private int b; - private int c; - private EntityAreaEffectCloud d; - - public DragonControllerLandedFlame(EntityEnderDragon entityenderdragon) { - super(entityenderdragon); - } - - @Override - public void b() { - ++this.b; - if (this.b % 2 == 0 && this.b < 10) { - Vec3D vec3d = this.a.u(1.0F).d(); - - vec3d.b(-0.7853982F); - double d0 = this.a.bA.locX; - double d1 = this.a.bA.locY + (double) (this.a.bA.getHeight() / 2.0F); - double d2 = this.a.bA.locZ; - - for (int i = 0; i < 8; ++i) { - double d3 = d0 + this.a.getRandom().nextGaussian() / 2.0D; - double d4 = d1 + this.a.getRandom().nextGaussian() / 2.0D; - double d5 = d2 + this.a.getRandom().nextGaussian() / 2.0D; - - for (int j = 0; j < 6; ++j) { - this.a.world.addParticle(Particles.DRAGON_BREATH, d3, d4, d5, -vec3d.x * 0.07999999821186066D * (double) j, -vec3d.y * 0.6000000238418579D, -vec3d.z * 0.07999999821186066D * (double) j); - } - - vec3d.b(0.19634955F); - } - } - - } - - @Override - public void c() { - ++this.b; - if (this.b >= 200) { - if (this.c >= 4) { - this.a.getDragonControllerManager().setControllerPhase(DragonControllerPhase.TAKEOFF); - } else { - this.a.getDragonControllerManager().setControllerPhase(DragonControllerPhase.SITTING_SCANNING); - } - } else if (this.b == 10) { - Vec3D vec3d = (new Vec3D(this.a.bA.locX - this.a.locX, 0.0D, this.a.bA.locZ - this.a.locZ)).d(); - float f = 5.0F; - double d0 = this.a.bA.locX + vec3d.x * 5.0D / 2.0D; - double d1 = this.a.bA.locZ + vec3d.z * 5.0D / 2.0D; - double d2 = this.a.bA.locY + (double) (this.a.bA.getHeight() / 2.0F); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(d0, d2, d1); - - while (this.a.world.isEmpty(blockposition_mutableblockposition ) && d2 > 0) { // Paper - --d2; - blockposition_mutableblockposition.c(d0, d2, d1); - } - - d2 = (double) (MathHelper.floor(d2) + 1); - this.d = new EntityAreaEffectCloud(this.a.world, d0, d2, d1); - this.d.setSource(this.a); - this.d.setRadius(5.0F); - this.d.setDuration(200); - this.d.setParticle(Particles.DRAGON_BREATH); - this.d.addEffect(new MobEffect(MobEffects.HARM)); - if (new com.destroystokyo.paper.event.entity.EnderDragonFlameEvent((org.bukkit.entity.EnderDragon) this.a.getBukkitEntity(), (org.bukkit.entity.AreaEffectCloud) this.d.getBukkitEntity()).callEvent()) { // Paper - this.a.world.addEntity(this.d); - } else { - this.removeAreaEffect(); - } - } - - } - - @Override - public void d() { - this.b = 0; - ++this.c; - } - - public void removeAreaEffect() { this.e(); } // Paper - OBFHELPER - @Override - public void e() { - if (this.d != null) { - this.d.die(); - this.d = null; - } - - } - - @Override - public DragonControllerPhase getControllerPhase() { - return DragonControllerPhase.SITTING_FLAMING; - } - - public void j() { - this.c = 0; - } -} diff --git a/src/main/java/net/minecraft/server/DragonControllerManager.java b/src/main/java/net/minecraft/server/DragonControllerManager.java deleted file mode 100644 index 551387dc0..000000000 --- a/src/main/java/net/minecraft/server/DragonControllerManager.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.minecraft.server; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftEnderDragon; -import org.bukkit.event.entity.EnderDragonChangePhaseEvent; -// CraftBukkit end - -public class DragonControllerManager { - - private static final Logger LOGGER = LogManager.getLogger(); - private final EntityEnderDragon enderDragon; - private final IDragonController[] dragonControllers = new IDragonController[DragonControllerPhase.c()]; - private IDragonController currentDragonController; - - public DragonControllerManager(EntityEnderDragon entityenderdragon) { - this.enderDragon = entityenderdragon; - this.setControllerPhase(DragonControllerPhase.HOVER); - } - - public void setControllerPhase(DragonControllerPhase dragoncontrollerphase) { - if (this.currentDragonController == null || dragoncontrollerphase != this.currentDragonController.getControllerPhase()) { - if (this.currentDragonController != null) { - this.currentDragonController.e(); - } - - // CraftBukkit start - Call EnderDragonChangePhaseEvent - EnderDragonChangePhaseEvent event = new EnderDragonChangePhaseEvent( - (CraftEnderDragon) this.enderDragon.getBukkitEntity(), - (this.currentDragonController == null) ? null : CraftEnderDragon.getBukkitPhase(this.currentDragonController.getControllerPhase()), - CraftEnderDragon.getBukkitPhase(dragoncontrollerphase) - ); - this.enderDragon.world.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - dragoncontrollerphase = CraftEnderDragon.getMinecraftPhase(event.getNewPhase()); - // CraftBukkit end - - this.currentDragonController = this.b(dragoncontrollerphase); - if (!this.enderDragon.world.isClientSide) { - this.enderDragon.getDataWatcher().set(EntityEnderDragon.PHASE, dragoncontrollerphase.b()); - } - - DragonControllerManager.LOGGER.debug("Dragon is now in phase {} on the {}", dragoncontrollerphase, this.enderDragon.world.isClientSide ? "client" : "server"); - this.currentDragonController.d(); - } - } - - public IDragonController a() { - return this.currentDragonController; - } - - public T b(DragonControllerPhase dragoncontrollerphase) { - int i = dragoncontrollerphase.b(); - - if (this.dragonControllers[i] == null) { - this.dragonControllers[i] = dragoncontrollerphase.a(this.enderDragon); - } - - return (T) this.dragonControllers[i]; // CraftBukkit - decompile error - } -} diff --git a/src/main/java/net/minecraft/server/DragonControllerStrafe.java b/src/main/java/net/minecraft/server/DragonControllerStrafe.java deleted file mode 100644 index 0b0815e11..000000000 --- a/src/main/java/net/minecraft/server/DragonControllerStrafe.java +++ /dev/null @@ -1,187 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class DragonControllerStrafe extends AbstractDragonController { - - private static final Logger LOGGER = LogManager.getLogger(); - private int c; - private PathEntity d; - private Vec3D e; - private EntityLiving f; - private boolean g; - - public DragonControllerStrafe(EntityEnderDragon entityenderdragon) { - super(entityenderdragon); - } - - @Override - public void c() { - if (this.f == null) { - DragonControllerStrafe.LOGGER.warn("Skipping player strafe phase because no player was found"); - this.a.getDragonControllerManager().setControllerPhase(DragonControllerPhase.HOLDING_PATTERN); - } else { - double d0; - double d1; - double d2; - - if (this.d != null && this.d.b()) { - d0 = this.f.locX; - d1 = this.f.locZ; - double d3 = d0 - this.a.locX; - double d4 = d1 - this.a.locZ; - - d2 = (double) MathHelper.sqrt(d3 * d3 + d4 * d4); - double d5 = Math.min(0.4000000059604645D + d2 / 80.0D - 1.0D, 10.0D); - - this.e = new Vec3D(d0, this.f.locY + d5, d1); - } - - d0 = this.e == null ? 0.0D : this.e.c(this.a.locX, this.a.locY, this.a.locZ); - if (d0 < 100.0D || d0 > 22500.0D) { - this.j(); - } - - d1 = 64.0D; - if (this.f.h((Entity) this.a) < 4096.0D) { - if (this.a.hasLineOfSight(this.f)) { - ++this.c; - Vec3D vec3d = (new Vec3D(this.f.locX - this.a.locX, 0.0D, this.f.locZ - this.a.locZ)).d(); - Vec3D vec3d1 = (new Vec3D((double) MathHelper.sin(this.a.yaw * 0.017453292F), 0.0D, (double) (-MathHelper.cos(this.a.yaw * 0.017453292F)))).d(); - float f = (float) vec3d1.b(vec3d); - float f1 = (float) (Math.acos((double) f) * 57.2957763671875D); - - f1 += 0.5F; - if (this.c >= 5 && f1 >= 0.0F && f1 < 10.0F) { - d2 = 1.0D; - Vec3D vec3d2 = this.a.f(1.0F); - double d6 = this.a.bA.locX - vec3d2.x * 1.0D; - double d7 = this.a.bA.locY + (double) (this.a.bA.getHeight() / 2.0F) + 0.5D; - double d8 = this.a.bA.locZ - vec3d2.z * 1.0D; - double d9 = this.f.locX - d6; - double d10 = this.f.locY + (double) (this.f.getHeight() / 2.0F) - (d7 + (double) (this.a.bA.getHeight() / 2.0F)); - double d11 = this.f.locZ - d8; - - this.a.world.a((EntityHuman) null, 1017, new BlockPosition(this.a), 0); - EntityDragonFireball entitydragonfireball = new EntityDragonFireball(this.a.world, this.a, d9, d10, d11); - - entitydragonfireball.setPositionRotation(d6, d7, d8, 0.0F, 0.0F); - if (new com.destroystokyo.paper.event.entity.EnderDragonShootFireballEvent((org.bukkit.entity.EnderDragon) a.getBukkitEntity(), (org.bukkit.entity.DragonFireball) entitydragonfireball.getBukkitEntity()).callEvent()) // Paper - this.a.world.addEntity(entitydragonfireball); - else entitydragonfireball.die(); // Paper - this.c = 0; - if (this.d != null) { - while (!this.d.b()) { - this.d.a(); - } - } - - this.a.getDragonControllerManager().setControllerPhase(DragonControllerPhase.HOLDING_PATTERN); - } - } else if (this.c > 0) { - --this.c; - } - } else if (this.c > 0) { - --this.c; - } - - } - } - - private void j() { - if (this.d == null || this.d.b()) { - int i = this.a.l(); - int j = i; - - if (this.a.getRandom().nextInt(8) == 0) { - this.g = !this.g; - j = i + 6; - } - - if (this.g) { - ++j; - } else { - --j; - } - - if (this.a.getEnderDragonBattle() != null && this.a.getEnderDragonBattle().c() > 0) { - j %= 12; - if (j < 0) { - j += 12; - } - } else { - j -= 12; - j &= 7; - j += 12; - } - - this.d = this.a.a(i, j, (PathPoint) null); - if (this.d != null) { - this.d.a(); - } - } - - this.k(); - } - - private void k() { - if (this.d != null && !this.d.b()) { - Vec3D vec3d = this.d.g(); - - this.d.a(); - double d0 = vec3d.x; - double d1 = vec3d.z; - - double d2; - - do { - d2 = vec3d.y + (double) (this.a.getRandom().nextFloat() * 20.0F); - } while (d2 < vec3d.y); - - this.e = new Vec3D(d0, d2, d1); - } - - } - - @Override - public void d() { - this.c = 0; - this.e = null; - this.d = null; - this.f = null; - } - - public void a(EntityLiving entityliving) { - this.f = entityliving; - int i = this.a.l(); - int j = this.a.l(this.f.locX, this.f.locY, this.f.locZ); - int k = MathHelper.floor(this.f.locX); - int l = MathHelper.floor(this.f.locZ); - double d0 = (double) k - this.a.locX; - double d1 = (double) l - this.a.locZ; - double d2 = (double) MathHelper.sqrt(d0 * d0 + d1 * d1); - double d3 = Math.min(0.4000000059604645D + d2 / 80.0D - 1.0D, 10.0D); - int i1 = MathHelper.floor(this.f.locY + d3); - PathPoint pathpoint = new PathPoint(k, i1, l); - - this.d = this.a.a(i, j, pathpoint); - if (this.d != null) { - this.d.a(); - this.k(); - } - - } - - @Nullable - @Override - public Vec3D g() { - return this.e; - } - - @Override - public DragonControllerPhase getControllerPhase() { - return DragonControllerPhase.STRAFE_PLAYER; - } -} diff --git a/src/main/java/net/minecraft/server/EULA.java b/src/main/java/net/minecraft/server/EULA.java deleted file mode 100644 index 6789f6443..000000000 --- a/src/main/java/net/minecraft/server/EULA.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.minecraft.server; - -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.util.Properties; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class EULA { - - private static final Logger LOGGER = LogManager.getLogger(); - private final java.nio.file.Path b; - private final boolean c; - - public EULA(java.nio.file.Path java_nio_file_path) { - this.b = java_nio_file_path; - this.c = SharedConstants.b || this.b(); - } - - private boolean b() { - try { - InputStream inputstream = Files.newInputStream(this.b); - Throwable throwable = null; - - boolean flag; - - try { - Properties properties = new Properties(); - - properties.load(inputstream); - flag = Boolean.parseBoolean(properties.getProperty("eula", "false")); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (inputstream != null) { - if (throwable != null) { - try { - inputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - inputstream.close(); - } - } - - } - - return flag; - } catch (Exception exception) { - EULA.LOGGER.warn("Failed to load {}", this.b); - this.c(); - return false; - } - } - - public boolean a() { - return this.c; - } - - private void c() { - if (!SharedConstants.b) { - try { - OutputStream outputstream = Files.newOutputStream(this.b); - Throwable throwable = null; - - try { - Properties properties = new Properties(); - - properties.setProperty("eula", "false"); - properties.store(outputstream, "By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).\nYou also agree that Akarin is the best waifu or something :P"); // Updated by JosephWorks; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (outputstream != null) { - if (throwable != null) { - try { - outputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - outputstream.close(); - } - } - - } - } catch (Exception exception) { - EULA.LOGGER.warn("Failed to save {}", this.b, exception); - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/EnchantmentFrostWalker.java b/src/main/java/net/minecraft/server/EnchantmentFrostWalker.java deleted file mode 100644 index b5de6c740..000000000 --- a/src/main/java/net/minecraft/server/EnchantmentFrostWalker.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -// CraftBukkit start -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.event.block.EntityBlockFormEvent; -// CraftBukkit end - -public class EnchantmentFrostWalker extends Enchantment { - - public EnchantmentFrostWalker(Enchantment.Rarity enchantment_rarity, EnumItemSlot... aenumitemslot) { - super(enchantment_rarity, EnchantmentSlotType.ARMOR_FEET, aenumitemslot); - } - - @Override - public int a(int i) { - return i * 10; - } - - @Override - public int b(int i) { - return this.a(i) + 15; - } - - @Override - public boolean isTreasure() { - return true; - } - - @Override - public int getMaxLevel() { - return 2; - } - - public static void a(EntityLiving entityliving, World world, BlockPosition blockposition, int i) { - if (entityliving.onGround) { - IBlockData iblockdata = Blocks.FROSTED_ICE.getBlockData(); - float f = (float) Math.min(16, 2 + i); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - Iterator iterator = BlockPosition.a(blockposition.a((double) (-f), -1.0D, (double) (-f)), blockposition.a((double) f, -1.0D, (double) f)).iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition1 = (BlockPosition) iterator.next(); - - if (blockposition1.a((IPosition) entityliving.getPositionVector(), (double) f)) { - blockposition_mutableblockposition.d(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ()); - IBlockData iblockdata1 = world.getType(blockposition_mutableblockposition); - - if (iblockdata1.isAir()) { - IBlockData iblockdata2 = world.getType(blockposition1); - - if (iblockdata2.getMaterial() == Material.WATER && (Integer) iblockdata2.get(BlockFluids.LEVEL) == 0 && iblockdata.canPlace(world, blockposition1) && world.a(iblockdata, blockposition1, VoxelShapeCollision.a())) { - // CraftBukkit Start - Call EntityBlockFormEvent for Frost Walker - if (org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(world, blockposition1, iblockdata, entityliving)) { - world.getBlockTickList().a(blockposition1, Blocks.FROSTED_ICE, MathHelper.nextInt(entityliving.getRandom(), 60, 120)); - } - // CraftBukkit End - } - } - } - } - - } - } - - @Override - public boolean a(Enchantment enchantment) { - return super.a(enchantment) && enchantment != Enchantments.DEPTH_STRIDER; - } -} diff --git a/src/main/java/net/minecraft/server/EnchantmentManager.java b/src/main/java/net/minecraft/server/EnchantmentManager.java deleted file mode 100644 index 1d16919e6..000000000 --- a/src/main/java/net/minecraft/server/EnchantmentManager.java +++ /dev/null @@ -1,398 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Map.Entry; -import javax.annotation.Nullable; -import org.apache.commons.lang3.mutable.MutableFloat; -import org.apache.commons.lang3.mutable.MutableInt; - -public class EnchantmentManager { - - public static int getEnchantmentLevel(Enchantment enchantment, ItemStack itemstack) { - if (itemstack.isEmpty()) { - return 0; - } else { - MinecraftKey minecraftkey = IRegistry.ENCHANTMENT.getKey(enchantment); - NBTTagList nbttaglist = itemstack.getEnchantments(); - - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompound(i); - MinecraftKey minecraftkey1 = MinecraftKey.a(nbttagcompound.getString("id")); - - if (minecraftkey1 != null && minecraftkey1.equals(minecraftkey)) { - return nbttagcompound.getInt("lvl"); - } - } - - return 0; - } - } - - public static Map a(ItemStack itemstack) { - Map map = Maps.newLinkedHashMap(); - NBTTagList nbttaglist = itemstack.getItem() == Items.ENCHANTED_BOOK ? ItemEnchantedBook.e(itemstack) : itemstack.getEnchantments(); - - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompound(i); - - IRegistry.ENCHANTMENT.getOptional(MinecraftKey.a(nbttagcompound.getString("id"))).ifPresent((enchantment) -> { - Integer integer = (Integer) map.put(enchantment, nbttagcompound.getInt("lvl")); - }); - } - - return map; - } - - public static void a(Map map, ItemStack itemstack) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - Enchantment enchantment = (Enchantment) entry.getKey(); - - if (enchantment != null) { - int i = (Integer) entry.getValue(); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setString("id", String.valueOf(IRegistry.ENCHANTMENT.getKey(enchantment))); - nbttagcompound.setShort("lvl", (short) i); - nbttaglist.add(nbttagcompound); - if (itemstack.getItem() == Items.ENCHANTED_BOOK) { - ItemEnchantedBook.a(itemstack, new WeightedRandomEnchant(enchantment, i)); - } - } - } - - if (nbttaglist.isEmpty()) { - itemstack.removeTag("Enchantments"); - } else if (itemstack.getItem() != Items.ENCHANTED_BOOK) { - itemstack.a("Enchantments", (NBTBase) nbttaglist); - } - - } - - private static void a(EnchantmentManager.a enchantmentmanager_a, ItemStack itemstack) { - if (!itemstack.isEmpty()) { - NBTTagList nbttaglist = itemstack.getEnchantments(); - - for (int i = 0; i < nbttaglist.size(); ++i) { - String s = nbttaglist.getCompound(i).getString("id"); - int j = nbttaglist.getCompound(i).getInt("lvl"); - - IRegistry.ENCHANTMENT.getOptional(MinecraftKey.a(s)).ifPresent((enchantment) -> { - enchantmentmanager_a.accept(enchantment, j); - }); - } - - } - } - - private static void a(EnchantmentManager.a enchantmentmanager_a, Iterable iterable) { - Iterator iterator = iterable.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - - a(enchantmentmanager_a, itemstack); - } - - } - - public static int a(Iterable iterable, DamageSource damagesource) { - MutableInt mutableint = new MutableInt(); - - a((enchantment, i) -> { - mutableint.add(enchantment.a(i, damagesource)); - }, iterable); - return mutableint.intValue(); - } - - public static float a(ItemStack itemstack, EnumMonsterType enummonstertype) { - MutableFloat mutablefloat = new MutableFloat(); - - a((enchantment, i) -> { - mutablefloat.add(enchantment.a(i, enummonstertype)); - }, itemstack); - return mutablefloat.floatValue(); - } - - public static float a(EntityLiving entityliving) { - int i = a(Enchantments.SWEEPING, entityliving); - - return i > 0 ? EnchantmentSweeping.e(i) : 0.0F; - } - - public static void a(EntityLiving entityliving, Entity entity) { - EnchantmentManager.a enchantmentmanager_a = (enchantment, i) -> { - enchantment.b(entityliving, entity, i); - }; - - if (entityliving != null) { - a(enchantmentmanager_a, entityliving.bb()); - } - - if (entity instanceof EntityHuman) { - a(enchantmentmanager_a, entityliving.getItemInMainHand()); - } - - } - - public static void b(EntityLiving entityliving, Entity entity) { - EnchantmentManager.a enchantmentmanager_a = (enchantment, i) -> { - enchantment.a(entityliving, entity, i); - }; - - if (entityliving != null) { - a(enchantmentmanager_a, entityliving.bb()); - } - - if (entityliving instanceof EntityHuman) { - a(enchantmentmanager_a, entityliving.getItemInMainHand()); - } - - } - - public static int a(Enchantment enchantment, EntityLiving entityliving) { - Iterable iterable = enchantment.a(entityliving).values(); - - if (iterable == null) { - return 0; - } else { - int i = 0; - Iterator iterator = iterable.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - int j = getEnchantmentLevel(enchantment, itemstack); - - if (j > i) { - i = j; - } - } - - return i; - } - } - - public static int b(EntityLiving entityliving) { - return a(Enchantments.KNOCKBACK, entityliving); - } - - public static int getFireAspectEnchantmentLevel(EntityLiving entityliving) { - return a(Enchantments.FIRE_ASPECT, entityliving); - } - - public static int getOxygenEnchantmentLevel(EntityLiving entityliving) { - return a(Enchantments.OXYGEN, entityliving); - } - - public static int e(EntityLiving entityliving) { - return a(Enchantments.DEPTH_STRIDER, entityliving); - } - - public static int getDigSpeedEnchantmentLevel(EntityLiving entityliving) { - return a(Enchantments.DIG_SPEED, entityliving); - } - - public static int b(ItemStack itemstack) { - return getEnchantmentLevel(Enchantments.LUCK, itemstack); - } - - public static int c(ItemStack itemstack) { - return getEnchantmentLevel(Enchantments.LURE, itemstack); - } - - public static int g(EntityLiving entityliving) { - return a(Enchantments.LOOT_BONUS_MOBS, entityliving); - } - - public static boolean h(EntityLiving entityliving) { - return a(Enchantments.WATER_WORKER, entityliving) > 0; - } - - public static boolean i(EntityLiving entityliving) { - return a(Enchantments.FROST_WALKER, entityliving) > 0; - } - - public static boolean d(ItemStack itemstack) { - return getEnchantmentLevel(Enchantments.BINDING_CURSE, itemstack) > 0; - } - - public static boolean shouldNotDrop(ItemStack itemstack) { - return getEnchantmentLevel(Enchantments.VANISHING_CURSE, itemstack) > 0; - } - - public static int f(ItemStack itemstack) { - return getEnchantmentLevel(Enchantments.LOYALTY, itemstack); - } - - public static int g(ItemStack itemstack) { - return getEnchantmentLevel(Enchantments.RIPTIDE, itemstack); - } - - public static boolean h(ItemStack itemstack) { - return getEnchantmentLevel(Enchantments.CHANNELING, itemstack) > 0; - } - - // Paper - OBFHELPER - public static @Nullable ItemStack getRandomEquippedItemWithEnchant(Enchantment enchantment, EntityLiving entityliving) { - Entry entry = b(enchantment, entityliving); - return entry != null ? entry.getValue() : null; - } - @Nullable - public static Entry b(Enchantment enchantment, EntityLiving entityliving) { - Map map = enchantment.a(entityliving); - - if (map.isEmpty()) { - return null; - } else { - List> list = Lists.newArrayList(); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - ItemStack itemstack = (ItemStack) entry.getValue(); - - if (!itemstack.isEmpty() && getEnchantmentLevel(enchantment, itemstack) > 0) { - list.add(entry); - } - } - - return list.isEmpty() ? null : (Entry) list.get(entityliving.getRandom().nextInt(list.size())); - } - } - - public static int a(Random random, int i, int j, ItemStack itemstack) { - Item item = itemstack.getItem(); - int k = item.c(); - - 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, boolean flag) { - List list = b(random, itemstack, i, flag); - boolean flag1 = itemstack.getItem() == Items.BOOK; - - if (flag1) { - itemstack = new ItemStack(Items.ENCHANTED_BOOK); - } - - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - WeightedRandomEnchant weightedrandomenchant = (WeightedRandomEnchant) iterator.next(); - - if (flag1) { - ItemEnchantedBook.a(itemstack, weightedrandomenchant); - } else { - itemstack.addEnchantment(weightedrandomenchant.enchantment, weightedrandomenchant.level); - } - } - - return itemstack; - } - - public static List b(Random random, ItemStack itemstack, int i, boolean flag) { - List list = Lists.newArrayList(); - Item item = itemstack.getItem(); - int j = item.c(); - - if (j <= 0) { - return list; - } else { - i += 1 + random.nextInt(j / 4 + 1) + random.nextInt(j / 4 + 1); - float f = (random.nextFloat() + random.nextFloat() - 1.0F) * 0.15F; - - i = MathHelper.clamp(Math.round((float) i + (float) i * f), 1, Integer.MAX_VALUE); - List list1 = a(i, itemstack, flag); - - if (!list1.isEmpty()) { - list.add(WeightedRandom.a(random, list1)); - - while (random.nextInt(50) <= i) { - a(list1, (WeightedRandomEnchant) SystemUtils.a((List) list)); - if (list1.isEmpty()) { - break; - } - - list.add(WeightedRandom.a(random, list1)); - i /= 2; - } - } - - return list; - } - } - - public static void a(List list, WeightedRandomEnchant weightedrandomenchant) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - if (!weightedrandomenchant.enchantment.isCompatible(((WeightedRandomEnchant) iterator.next()).enchantment)) { - iterator.remove(); - } - } - - } - - public static boolean a(Collection collection, Enchantment enchantment) { - Iterator iterator = collection.iterator(); - - Enchantment enchantment1; - - do { - if (!iterator.hasNext()) { - return true; - } - - enchantment1 = (Enchantment) iterator.next(); - } while (enchantment1.isCompatible(enchantment)); - - return false; - } - - public static List a(int i, ItemStack itemstack, boolean flag) { - List list = Lists.newArrayList(); - Item item = itemstack.getItem(); - boolean flag1 = itemstack.getItem() == Items.BOOK; - Iterator iterator = IRegistry.ENCHANTMENT.iterator(); - - while (iterator.hasNext()) { - Enchantment enchantment = (Enchantment) iterator.next(); - - if ((!enchantment.isTreasure() || flag) && (enchantment.itemTarget.canEnchant(item) || flag1)) { - for (int j = enchantment.getMaxLevel(); j > enchantment.getStartLevel() - 1; --j) { - if (i >= enchantment.a(j) && i <= enchantment.b(j)) { - list.add(new WeightedRandomEnchant(enchantment, j)); - break; - } - } - } - } - - return list; - } - - @FunctionalInterface - interface a { - - void accept(Enchantment enchantment, int i); - } -} diff --git a/src/main/java/net/minecraft/server/EnchantmentThorns.java b/src/main/java/net/minecraft/server/EnchantmentThorns.java deleted file mode 100644 index 62dd5367e..000000000 --- a/src/main/java/net/minecraft/server/EnchantmentThorns.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import java.util.Map.Entry; - -public class EnchantmentThorns extends Enchantment { - - public EnchantmentThorns(Enchantment.Rarity enchantment_rarity, EnumItemSlot... aenumitemslot) { - super(enchantment_rarity, EnchantmentSlotType.ARMOR_CHEST, aenumitemslot); - } - - @Override - public int a(int i) { - return 10 + 20 * (i - 1); - } - - @Override - public int b(int i) { - return super.a(i) + 50; - } - - @Override - public int getMaxLevel() { - return 3; - } - - @Override - public boolean canEnchant(ItemStack itemstack) { - return itemstack.getItem() instanceof ItemArmor ? true : super.canEnchant(itemstack); - } - - @Override - public void b(EntityLiving entityliving, Entity entity, int i) { - Random random = entityliving.getRandom(); - Entry entry = EnchantmentManager.b(Enchantments.THORNS, entityliving); - - if (entity != null && a(i, random)) { // CraftBukkit - if (entity != null) { - entity.damageEntity(DamageSource.a(entityliving), (float) b(i, random)); - } - - if (entry != null) { - ((ItemStack) entry.getValue()).damage(3, entityliving, (entityliving1) -> { - entityliving1.c((EnumItemSlot) entry.getKey()); - }); - } - } else if (entry != null) { - ((ItemStack) entry.getValue()).damage(1, entityliving, (entityliving1) -> { - entityliving1.c((EnumItemSlot) entry.getKey()); - }); - } - - } - - public static boolean a(int i, Random random) { - return i <= 0 ? false : 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/src/main/java/net/minecraft/server/EnchantmentWeaponDamage.java b/src/main/java/net/minecraft/server/EnchantmentWeaponDamage.java deleted file mode 100644 index 4571cdf02..000000000 --- a/src/main/java/net/minecraft/server/EnchantmentWeaponDamage.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.minecraft.server; - -public class EnchantmentWeaponDamage extends Enchantment { - - private static final String[] d = new String[]{"all", "undead", "arthropods"}; - private static final int[] e = new int[]{1, 5, 5}; - private static final int[] f = new int[]{11, 8, 8}; - private static final int[] g = new int[]{20, 20, 20}; - public final int a; - - public EnchantmentWeaponDamage(Enchantment.Rarity enchantment_rarity, int i, EnumItemSlot... aenumitemslot) { - super(enchantment_rarity, EnchantmentSlotType.WEAPON, aenumitemslot); - this.a = i; - } - - @Override - public int a(int i) { - return EnchantmentWeaponDamage.e[this.a] + (i - 1) * EnchantmentWeaponDamage.f[this.a]; - } - - @Override - public int b(int i) { - return this.a(i) + EnchantmentWeaponDamage.g[this.a]; - } - - @Override - public int getMaxLevel() { - return 5; - } - - @Override - public float a(int i, EnumMonsterType enummonstertype) { - return this.a == 0 ? 1.0F + (float) Math.max(0, i - 1) * 0.5F : (this.a == 1 && enummonstertype == EnumMonsterType.UNDEAD ? (float) i * 2.5F : (this.a == 2 && enummonstertype == EnumMonsterType.ARTHROPOD ? (float) i * 2.5F : 0.0F)); - } - - @Override - public boolean a(Enchantment enchantment) { - return !(enchantment instanceof EnchantmentWeaponDamage); - } - - @Override - public boolean canEnchant(ItemStack itemstack) { - return itemstack.getItem() instanceof ItemAxe ? true : super.canEnchant(itemstack); - } - - @Override - public void a(EntityLiving entityliving, Entity entity, int i) { - if (entity instanceof EntityLiving) { - EntityLiving entityliving1 = (EntityLiving) entity; - - if (this.a == 2 && entityliving1.getMonsterType() == EnumMonsterType.ARTHROPOD) { - int j = 20 + entityliving.getRandom().nextInt(10 * i); - - entityliving1.addEffect(new MobEffect(MobEffects.SLOWER_MOVEMENT, j, 3), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - } - - } -} diff --git a/src/main/java/net/minecraft/server/Enchantments.java b/src/main/java/net/minecraft/server/Enchantments.java deleted file mode 100644 index 1105c6c5b..000000000 --- a/src/main/java/net/minecraft/server/Enchantments.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.minecraft.server; - -public class Enchantments { - - private static final EnumItemSlot[] L = new EnumItemSlot[]{EnumItemSlot.HEAD, EnumItemSlot.CHEST, EnumItemSlot.LEGS, EnumItemSlot.FEET}; - public static final Enchantment PROTECTION_ENVIRONMENTAL = a("protection", new EnchantmentProtection(Enchantment.Rarity.COMMON, EnchantmentProtection.DamageType.ALL, Enchantments.L)); - public static final Enchantment PROTECTION_FIRE = a("fire_protection", new EnchantmentProtection(Enchantment.Rarity.UNCOMMON, EnchantmentProtection.DamageType.FIRE, Enchantments.L)); - public static final Enchantment PROTECTION_FALL = a("feather_falling", new EnchantmentProtection(Enchantment.Rarity.UNCOMMON, EnchantmentProtection.DamageType.FALL, Enchantments.L)); - public static final Enchantment PROTECTION_EXPLOSIONS = a("blast_protection", new EnchantmentProtection(Enchantment.Rarity.RARE, EnchantmentProtection.DamageType.EXPLOSION, Enchantments.L)); - public static final Enchantment PROTECTION_PROJECTILE = a("projectile_protection", new EnchantmentProtection(Enchantment.Rarity.UNCOMMON, EnchantmentProtection.DamageType.PROJECTILE, Enchantments.L)); - public static final Enchantment OXYGEN = a("respiration", new EnchantmentOxygen(Enchantment.Rarity.RARE, Enchantments.L)); - public static final Enchantment WATER_WORKER = a("aqua_affinity", new EnchantmentWaterWorker(Enchantment.Rarity.RARE, Enchantments.L)); - public static final Enchantment THORNS = a("thorns", new EnchantmentThorns(Enchantment.Rarity.VERY_RARE, Enchantments.L)); - public static final Enchantment DEPTH_STRIDER = a("depth_strider", new EnchantmentDepthStrider(Enchantment.Rarity.RARE, Enchantments.L)); - public static final Enchantment FROST_WALKER = a("frost_walker", new EnchantmentFrostWalker(Enchantment.Rarity.RARE, new EnumItemSlot[]{EnumItemSlot.FEET})); - public static final Enchantment BINDING_CURSE = a("binding_curse", new EnchantmentBinding(Enchantment.Rarity.VERY_RARE, Enchantments.L)); - public static final Enchantment DAMAGE_ALL = a("sharpness", new EnchantmentWeaponDamage(Enchantment.Rarity.COMMON, 0, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment DAMAGE_UNDEAD = a("smite", new EnchantmentWeaponDamage(Enchantment.Rarity.UNCOMMON, 1, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment DAMAGE_ARTHROPODS = a("bane_of_arthropods", new EnchantmentWeaponDamage(Enchantment.Rarity.UNCOMMON, 2, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment KNOCKBACK = a("knockback", new EnchantmentKnockback(Enchantment.Rarity.UNCOMMON, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment FIRE_ASPECT = a("fire_aspect", new EnchantmentFire(Enchantment.Rarity.RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment LOOT_BONUS_MOBS = a("looting", new EnchantmentLootBonus(Enchantment.Rarity.RARE, EnchantmentSlotType.WEAPON, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment SWEEPING = a("sweeping", new EnchantmentSweeping(Enchantment.Rarity.RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment DIG_SPEED = a("efficiency", new EnchantmentDigging(Enchantment.Rarity.COMMON, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment SILK_TOUCH = a("silk_touch", new EnchantmentSilkTouch(Enchantment.Rarity.VERY_RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment DURABILITY = a("unbreaking", new EnchantmentDurability(Enchantment.Rarity.UNCOMMON, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment LOOT_BONUS_BLOCKS = a("fortune", new EnchantmentLootBonus(Enchantment.Rarity.RARE, EnchantmentSlotType.DIGGER, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment ARROW_DAMAGE = a("power", new EnchantmentArrowDamage(Enchantment.Rarity.COMMON, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment ARROW_KNOCKBACK = a("punch", new EnchantmentArrowKnockback(Enchantment.Rarity.RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment ARROW_FIRE = a("flame", new EnchantmentFlameArrows(Enchantment.Rarity.RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment ARROW_INFINITE = a("infinity", new EnchantmentInfiniteArrows(Enchantment.Rarity.VERY_RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment LUCK = a("luck_of_the_sea", new EnchantmentLootBonus(Enchantment.Rarity.RARE, EnchantmentSlotType.FISHING_ROD, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment LURE = a("lure", new EnchantmentLure(Enchantment.Rarity.RARE, EnchantmentSlotType.FISHING_ROD, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment LOYALTY = a("loyalty", new EnchantmentTridentLoyalty(Enchantment.Rarity.UNCOMMON, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment IMPALING = a("impaling", new EnchantmentTridentImpaling(Enchantment.Rarity.RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment RIPTIDE = a("riptide", new EnchantmentTridentRiptide(Enchantment.Rarity.RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment CHANNELING = a("channeling", new EnchantmentTridentChanneling(Enchantment.Rarity.VERY_RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment MULTISHOT = a("multishot", new EnchantmentMultishot(Enchantment.Rarity.RARE, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment QUICK_CHARGE = a("quick_charge", new EnchantmentQuickCharge(Enchantment.Rarity.UNCOMMON, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment PIERCING = a("piercing", new EnchantmentPiercing(Enchantment.Rarity.COMMON, new EnumItemSlot[]{EnumItemSlot.MAINHAND})); - public static final Enchantment MENDING = a("mending", new EnchantmentMending(Enchantment.Rarity.RARE, EnumItemSlot.values())); - public static final Enchantment VANISHING_CURSE = a("vanishing_curse", new EnchantmentVanishing(Enchantment.Rarity.VERY_RARE, EnumItemSlot.values())); - - // CraftBukkit start - static { - for (Object enchantment : IRegistry.ENCHANTMENT) { - org.bukkit.enchantments.Enchantment.registerEnchantment(new org.bukkit.craftbukkit.enchantments.CraftEnchantment((Enchantment) enchantment)); - } - } - // CraftBukkit end - - private static Enchantment a(String s, Enchantment enchantment) { - return (Enchantment) IRegistry.a(IRegistry.ENCHANTMENT, s, enchantment); // CraftBukkit - decompile error - } -} diff --git a/src/main/java/net/minecraft/server/EnderDragonBattle.java b/src/main/java/net/minecraft/server/EnderDragonBattle.java deleted file mode 100644 index 6700c8c65..000000000 --- a/src/main/java/net/minecraft/server/EnderDragonBattle.java +++ /dev/null @@ -1,524 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ContiguousSet; -import com.google.common.collect.DiscreteDomain; -import com.google.common.collect.Lists; -import com.google.common.collect.Range; -import com.google.common.collect.Sets; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -import java.util.function.Predicate; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class EnderDragonBattle { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final Predicate b = IEntitySelector.a.and(IEntitySelector.a(0.0D, 128.0D, 0.0D, 192.0D)); - public final BossBattleServer bossBattle; - private final WorldServer d; - private final List e; - private final ShapeDetector f; - private int g; - private int h; - private int i; - private int j; - private boolean k; private void setDragonKilled(boolean dragonKilled) { this.k = dragonKilled; } // Paper - OBFHELPER - private boolean l; - private UUID m; - private boolean n; private void setScanForLegacyFight(boolean scanForLegacyFight) { this.n = scanForLegacyFight; } private boolean scanForLegacyFight() { return this.n; } // Paper - OBFHELPER - private BlockPosition o; - private EnumDragonRespawn p; - private int q; - private List r; - - public EnderDragonBattle(WorldServer worldserver, NBTTagCompound nbttagcompound) { - this.bossBattle = (BossBattleServer) (new BossBattleServer(new ChatMessage("entity.minecraft.ender_dragon", new Object[0]), BossBattle.BarColor.PINK, BossBattle.BarStyle.PROGRESS)).setPlayMusic(true).c(true); - this.e = Lists.newArrayList(); - this.n = true; - // Paper start - setScanForLegacyFight(worldserver.paperConfig.scanForLegacyEnderDragon); - if (!scanForLegacyFight()) setDragonKilled(true); - // Paper end - this.d = worldserver; - if (nbttagcompound.hasKeyOfType("DragonKilled", 99)) { - if (nbttagcompound.b("DragonUUID")) { - this.m = nbttagcompound.a("DragonUUID"); - } - - this.k = nbttagcompound.getBoolean("DragonKilled"); - this.l = nbttagcompound.getBoolean("PreviouslyKilled"); - if (nbttagcompound.getBoolean("IsRespawning")) { - this.p = EnumDragonRespawn.START; - } - - if (nbttagcompound.hasKeyOfType("ExitPortalLocation", 10)) { - this.o = GameProfileSerializer.c(nbttagcompound.getCompound("ExitPortalLocation")); - } - } else { - this.k = true; - this.l = true; - } - - if (nbttagcompound.hasKeyOfType("Gateways", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("Gateways", 3); - - for (int i = 0; i < nbttaglist.size(); ++i) { - this.e.add(nbttaglist.e(i)); - } - } else { - this.e.addAll(ContiguousSet.create(Range.closedOpen(0, 20), DiscreteDomain.integers())); - Collections.shuffle(this.e, new Random(worldserver.getSeed())); - } - - this.f = ShapeDetectorBuilder.a().a(" ", " ", " ", " # ", " ", " ", " ").a(" ", " ", " ", " # ", " ", " ", " ").a(" ", " ", " ", " # ", " ", " ", " ").a(" ### ", " # # ", "# #", "# # #", "# #", " # # ", " ### ").a(" ", " ### ", " ##### ", " ##### ", " ##### ", " ### ", " ").a('#', ShapeDetectorBlock.a(BlockPredicate.a(Blocks.BEDROCK))).b(); - } - - public NBTTagCompound a() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - if (this.m != null) { - nbttagcompound.a("DragonUUID", this.m); - } - - nbttagcompound.setBoolean("DragonKilled", this.k); - nbttagcompound.setBoolean("PreviouslyKilled", this.l); - if (this.o != null) { - nbttagcompound.set("ExitPortalLocation", GameProfileSerializer.a(this.o)); - } - - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.e.iterator(); - - while (iterator.hasNext()) { - int i = (Integer) iterator.next(); - - nbttaglist.add(new NBTTagInt(i)); - } - - nbttagcompound.set("Gateways", nbttaglist); - return nbttagcompound; - } - - public void b() { - this.bossBattle.setVisible(!this.k); - if (++this.j >= 20) { - this.l(); - this.j = 0; - } - - if (!this.bossBattle.getPlayers().isEmpty()) { - this.d.getChunkProvider().addTicket(TicketType.DRAGON, new ChunkCoordIntPair(0, 0), 9, Unit.INSTANCE); - boolean flag = this.k(); - - if (this.n && flag) { - this.g(); - this.n = false; - } - - if (this.p != null) { - if (this.r == null && flag) { - this.p = null; - this.e(); - } - - this.p.a(this.d, this, this.r, this.q++, this.o); - } - - if (!this.k) { - if ((this.m == null || ++this.g >= 1200) && flag) { - this.h(); - this.g = 0; - } - - if (++this.i >= 100 && flag) { - this.m(); - this.i = 0; - } - } - } else { - this.d.getChunkProvider().removeTicket(TicketType.DRAGON, new ChunkCoordIntPair(0, 0), 9, Unit.INSTANCE); - } - - } - - private void g() { - EnderDragonBattle.LOGGER.info("Scanning for legacy world dragon fight..."); - boolean flag = this.i(); - - if (flag) { - EnderDragonBattle.LOGGER.info("Found that the dragon has been killed in this world already."); - this.l = true; - } else { - EnderDragonBattle.LOGGER.info("Found that the dragon has not yet been killed in this world."); - this.l = false; - this.a(false); - } - - List list = this.d.j(); - - if (list.isEmpty()) { - this.k = true; - } else { - EntityEnderDragon entityenderdragon = (EntityEnderDragon) list.get(0); - - this.m = entityenderdragon.getUniqueID(); - EnderDragonBattle.LOGGER.info("Found that there's a dragon still alive ({})", entityenderdragon); - this.k = false; - if (!flag) { - EnderDragonBattle.LOGGER.info("But we didn't have a portal, let's remove it."); - entityenderdragon.die(); - this.m = null; - } - } - - if (!this.l && this.k) { - this.k = false; - } - - } - - private void h() { - List list = this.d.j(); - - if (list.isEmpty()) { - EnderDragonBattle.LOGGER.debug("Haven't seen the dragon, respawning it"); - this.o(); - } else { - EnderDragonBattle.LOGGER.debug("Haven't seen our dragon, but found another one to use."); - this.m = ((EntityEnderDragon) list.get(0)).getUniqueID(); - } - - } - - protected void a(EnumDragonRespawn enumdragonrespawn) { - if (this.p == null) { - throw new IllegalStateException("Dragon respawn isn't in progress, can't skip ahead in the animation."); - } else { - this.q = 0; - if (enumdragonrespawn == EnumDragonRespawn.END) { - this.p = null; - this.k = false; - EntityEnderDragon entityenderdragon = this.o(); - Iterator iterator = this.bossBattle.getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - CriterionTriggers.n.a(entityplayer, (Entity) entityenderdragon); - } - } else { - this.p = enumdragonrespawn; - } - - } - } - - private boolean i() { - for (int i = -8; i <= 8; ++i) { - int j = -8; - - label27: - while (j <= 8) { - Chunk chunk = this.d.getChunkAt(i, j); - Iterator iterator = chunk.getTileEntities().values().iterator(); - - TileEntity tileentity; - - do { - if (!iterator.hasNext()) { - ++j; - continue label27; - } - - tileentity = (TileEntity) iterator.next(); - } while (!(tileentity instanceof TileEntityEnderPortal)); - - return true; - } - } - - return false; - } - - @Nullable - private ShapeDetector.ShapeDetectorCollection j() { - int i; - int j; - - for (i = -8; i <= 8; ++i) { - for (j = -8; j <= 8; ++j) { - Chunk chunk = this.d.getChunkAt(i, j); - Iterator iterator = chunk.getTileEntities().values().iterator(); - - while (iterator.hasNext()) { - TileEntity tileentity = (TileEntity) iterator.next(); - - if (tileentity instanceof TileEntityEnderPortal) { - ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = this.f.a(this.d, tileentity.getPosition()); - - if (shapedetector_shapedetectorcollection != null) { - BlockPosition blockposition = shapedetector_shapedetectorcollection.a(3, 3, 3).getPosition(); - - if (this.o == null && blockposition.getX() == 0 && blockposition.getZ() == 0) { - this.o = blockposition; - } - - return shapedetector_shapedetectorcollection; - } - } - } - } - } - - i = this.d.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, WorldGenEndTrophy.a).getY(); - - for (j = i; j >= 0; --j) { - ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection1 = this.f.a(this.d, new BlockPosition(WorldGenEndTrophy.a.getX(), j, WorldGenEndTrophy.a.getZ())); - - if (shapedetector_shapedetectorcollection1 != null) { - if (this.o == null) { - this.o = shapedetector_shapedetectorcollection1.a(3, 3, 3).getPosition(); - } - - return shapedetector_shapedetectorcollection1; - } - } - - return null; - } - - private boolean k() { - for (int i = -8; i <= 8; ++i) { - for (int j = 8; j <= 8; ++j) { - IChunkAccess ichunkaccess = this.d.getChunkAt(i, j, ChunkStatus.FULL, false); - - if (!(ichunkaccess instanceof Chunk)) { - return false; - } - - PlayerChunk.State playerchunk_state = ((Chunk) ichunkaccess).getState(); - - if (!playerchunk_state.isAtLeast(PlayerChunk.State.TICKING)) { - return false; - } - } - } - - return true; - } - - private void l() { - Set set = Sets.newHashSet(); - Iterator iterator = this.d.a(EnderDragonBattle.b).iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - this.bossBattle.addPlayer(entityplayer); - set.add(entityplayer); - } - - Set set1 = Sets.newHashSet(this.bossBattle.getPlayers()); - - set1.removeAll(set); - Iterator iterator1 = set1.iterator(); - - while (iterator1.hasNext()) { - EntityPlayer entityplayer1 = (EntityPlayer) iterator1.next(); - - this.bossBattle.removePlayer(entityplayer1); - } - - } - - private void m() { - this.i = 0; - this.h = 0; - - WorldGenEnder.Spike worldgenender_spike; - - for (Iterator iterator = WorldGenEnder.a((GeneratorAccess) this.d).iterator(); iterator.hasNext(); this.h += this.d.a(EntityEnderCrystal.class, worldgenender_spike.f()).size()) { - worldgenender_spike = (WorldGenEnder.Spike) iterator.next(); - } - - EnderDragonBattle.LOGGER.debug("Found {} end crystals still alive", this.h); - } - - public void a(EntityEnderDragon entityenderdragon) { - if (entityenderdragon.getUniqueID().equals(this.m)) { - this.bossBattle.setProgress(0.0F); - this.bossBattle.setVisible(false); - this.a(true); - this.n(); - if (!this.l) { - this.d.setTypeUpdate(this.d.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, WorldGenEndTrophy.a), Blocks.DRAGON_EGG.getBlockData()); - } - - this.l = true; - this.k = true; - } - - } - - private void n() { - if (!this.e.isEmpty()) { - int i = (Integer) this.e.remove(this.e.size() - 1); - int j = MathHelper.floor(96.0D * Math.cos(2.0D * (-3.141592653589793D + 0.15707963267948966D * (double) i))); - int k = MathHelper.floor(96.0D * Math.sin(2.0D * (-3.141592653589793D + 0.15707963267948966D * (double) i))); - - this.a(new BlockPosition(j, 75, k)); - } - } - - private void a(BlockPosition blockposition) { - this.d.triggerEffect(3000, blockposition, 0); - WorldGenerator.END_GATEWAY.generate(this.d, this.d.getChunkProvider().getChunkGenerator(), new Random(), blockposition, WorldGenEndGatewayConfiguration.a()); - } - - private void a(boolean flag) { - WorldGenEndTrophy worldgenendtrophy = new WorldGenEndTrophy(flag); - - if (this.o == null) { - for (this.o = this.d.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, WorldGenEndTrophy.a).down(); this.d.getType(this.o).getBlock() == Blocks.BEDROCK && this.o.getY() > this.d.getSeaLevel(); this.o = this.o.down()) { - ; - } - } - - worldgenendtrophy.a(this.d, this.d.getChunkProvider().getChunkGenerator(), new Random(), this.o, WorldGenFeatureConfiguration.e); - } - - private EntityEnderDragon o() { - this.d.getChunkAtWorldCoords(new BlockPosition(0, 128, 0)); - EntityEnderDragon entityenderdragon = (EntityEnderDragon) EntityTypes.ENDER_DRAGON.a((World) this.d); - - entityenderdragon.getDragonControllerManager().setControllerPhase(DragonControllerPhase.HOLDING_PATTERN); - entityenderdragon.setPositionRotation(0.0D, 128.0D, 0.0D, this.d.random.nextFloat() * 360.0F, 0.0F); - this.d.addEntity(entityenderdragon); - this.m = entityenderdragon.getUniqueID(); - return entityenderdragon; - } - - public void b(EntityEnderDragon entityenderdragon) { - if (entityenderdragon.getUniqueID().equals(this.m)) { - this.bossBattle.setProgress(entityenderdragon.getHealth() / entityenderdragon.getMaxHealth()); - this.g = 0; - if (entityenderdragon.hasCustomName()) { - this.bossBattle.a(entityenderdragon.getScoreboardDisplayName()); - } - } - - } - - public int c() { - return this.h; - } - - public void a(EntityEnderCrystal entityendercrystal, DamageSource damagesource) { - if (this.p != null && this.r.contains(entityendercrystal)) { - EnderDragonBattle.LOGGER.debug("Aborting respawn sequence"); - this.p = null; - this.q = 0; - this.f(); - this.a(true); - } else { - this.m(); - Entity entity = this.d.getEntity(this.m); - - if (entity instanceof EntityEnderDragon) { - ((EntityEnderDragon) entity).a(entityendercrystal, new BlockPosition(entityendercrystal), damagesource); - } - } - - } - - public boolean d() { - return this.l; - } - - public void e() { - if (this.k && this.p == null) { - BlockPosition blockposition = this.o; - - if (blockposition == null) { - EnderDragonBattle.LOGGER.debug("Tried to respawn, but need to find the portal first."); - ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = this.j(); - - if (shapedetector_shapedetectorcollection == null) { - EnderDragonBattle.LOGGER.debug("Couldn't find a portal, so we made one."); - this.a(true); - } else { - EnderDragonBattle.LOGGER.debug("Found the exit portal & temporarily using it."); - } - - blockposition = this.o; - } - - List list = Lists.newArrayList(); - BlockPosition blockposition1 = blockposition.up(1); - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - List list1 = this.d.a(EntityEnderCrystal.class, new AxisAlignedBB(blockposition1.shift(enumdirection, 2))); - - if (list1.isEmpty()) { - return; - } - - list.addAll(list1); - } - - EnderDragonBattle.LOGGER.debug("Found all crystals, respawning dragon."); - this.a((List) list); - } - - } - - private void a(List list) { - if (this.k && this.p == null) { - for (ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = this.j(); shapedetector_shapedetectorcollection != null; shapedetector_shapedetectorcollection = this.j()) { - for (int i = 0; i < this.f.c(); ++i) { - for (int j = 0; j < this.f.b(); ++j) { - for (int k = 0; k < this.f.a(); ++k) { - ShapeDetectorBlock shapedetectorblock = shapedetector_shapedetectorcollection.a(i, j, k); - - if (shapedetectorblock.a().getBlock() == Blocks.BEDROCK || shapedetectorblock.a().getBlock() == Blocks.END_PORTAL) { - this.d.setTypeUpdate(shapedetectorblock.getPosition(), Blocks.END_STONE.getBlockData()); - } - } - } - } - } - - this.p = EnumDragonRespawn.START; - this.q = 0; - this.a(false); - this.r = list; - } - - } - - public void f() { - Iterator iterator = WorldGenEnder.a((GeneratorAccess) this.d).iterator(); - - while (iterator.hasNext()) { - WorldGenEnder.Spike worldgenender_spike = (WorldGenEnder.Spike) iterator.next(); - List list = this.d.a(EntityEnderCrystal.class, worldgenender_spike.f()); - Iterator iterator1 = list.iterator(); - - while (iterator1.hasNext()) { - EntityEnderCrystal entityendercrystal = (EntityEnderCrystal) iterator1.next(); - - entityendercrystal.setInvulnerable(false); - entityendercrystal.setBeamTarget((BlockPosition) null); - } - } - - } -} diff --git a/src/main/java/net/minecraft/server/Entity.java b/src/main/java/net/minecraft/server/Entity.java deleted file mode 100644 index e8def7f81..000000000 --- a/src/main/java/net/minecraft/server/Entity.java +++ /dev/null @@ -1,3277 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.block.BlockFace; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Hanging; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Vehicle; -import co.aikar.timings.MinecraftTimings; // Paper -import co.aikar.timings.Timing; // Paper -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.vehicle.VehicleBlockCollisionEvent; -import org.bukkit.event.vehicle.VehicleEnterEvent; -import org.bukkit.event.vehicle.VehicleExitEvent; -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.Pose; -import org.bukkit.event.entity.EntityAirChangeEvent; -import org.bukkit.event.entity.EntityCombustEvent; -import org.bukkit.event.entity.EntityDropItemEvent; -import org.bukkit.event.entity.EntityPortalEvent; -import org.bukkit.event.entity.EntityPoseChangeEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.plugin.PluginManager; -// CraftBukkit end - -public abstract class Entity implements INamableTileEntity, ICommandListener, KeyedObject { // Paper - - // CraftBukkit start - private static final int CURRENT_LEVEL = 2; - // Paper start - public static Random SHARED_RANDOM = new Random() { - private boolean locked = false; - @Override - public synchronized void setSeed(long seed) { - if (locked) { - LogManager.getLogger().error("Ignoring setSeed on Entity.SHARED_RANDOM", new Throwable()); - } else { - super.setSeed(seed); - locked = true; - } - } - }; - List entitySlice = null; - public org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason; - // Paper end - static boolean isLevelAtLeast(NBTTagCompound tag, int level) { - return tag.hasKey("Bukkit.updateLevel") && tag.getInt("Bukkit.updateLevel") >= level; - } - - public com.destroystokyo.paper.loottable.PaperLootableInventoryData lootableData; // Paper - private CraftEntity bukkitEntity; - - PlayerChunkMap.EntityTracker tracker; // Paper - Throwable addedToWorldStack; // Paper - entity debug - public CraftEntity getBukkitEntity() { - if (bukkitEntity == null) { - bukkitEntity = CraftEntity.getEntity(world.getServer(), this); - } - return bukkitEntity; - } - - @Override - public CommandSender getBukkitSender(CommandListenerWrapper wrapper) { - return getBukkitEntity(); - } - // CraftBukkit end - - protected static final Logger LOGGER = LogManager.getLogger(); - private static final AtomicInteger entityCount = new AtomicInteger(1); // paper - start entity count from 1 - private static final List c = Collections.emptyList(); - private static final AxisAlignedBB d = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); - private static double e = 1.0D; - private final EntityTypes f; - private int id; - public boolean i; public final boolean blocksEntitySpawning() { return this.i; } // Paper - OBFHELPER - public final List passengers; - protected int j; - private Entity vehicle; - public boolean attachedToPlayer; - public World world; - public double lastX; - public double lastY; - public double lastZ; - public double locX; - public double locY; - public double locZ; - private Vec3D mot; - public float yaw; - public float pitch; - public float lastYaw; - public float lastPitch; - private AxisAlignedBB boundingBox; - public boolean onGround; - public boolean positionChanged; - public boolean y; - public boolean z; - public boolean velocityChanged; - protected Vec3D B; - public boolean dead; - public float D; - public float E; - public float F; - public boolean shouldBeRemoved; // Paper - public float fallDistance; - private float av; - private float aw; - public double H; - public double I; - public double J; - public float K; - public boolean noclip; - public float M; - protected final Random random; - public int ticksLived; - public int fireTicks; - public boolean inWater; - protected double Q; - protected boolean R; - protected boolean inLava; - public int noDamageTicks; - protected boolean justCreated; - protected final DataWatcher datawatcher; - protected static final DataWatcherObject W = DataWatcher.a(Entity.class, DataWatcherRegistry.a); - private static final DataWatcherObject AIR_TICKS = DataWatcher.a(Entity.class, DataWatcherRegistry.b); - private static final DataWatcherObject> az = DataWatcher.a(Entity.class, DataWatcherRegistry.f); - private static final DataWatcherObject aA = DataWatcher.a(Entity.class, DataWatcherRegistry.i); - private static final DataWatcherObject aB = DataWatcher.a(Entity.class, DataWatcherRegistry.i); - private static final DataWatcherObject aC = DataWatcher.a(Entity.class, DataWatcherRegistry.i); - protected static final DataWatcherObject POSE = DataWatcher.a(Entity.class, DataWatcherRegistry.s); - public boolean inChunk; public boolean isAddedToChunk() { return inChunk; } // Paper - OBFHELPER - public int chunkX; public int getChunkX() { return chunkX; } // Paper - OBFHELPER - public int chunkY; public int getChunkY() { return chunkY; } // Paper - OBFHELPER - public int chunkZ; public int getChunkZ() { return chunkZ; } // Paper - OBFHELPER - public boolean af; - public boolean impulse; - public int portalCooldown; - protected boolean ai; public final boolean inPortal() { return this.ai; } // Paper - OBFHELPER - protected int aj; - public DimensionManager dimension; - protected BlockPosition al; - protected Vec3D am; - protected EnumDirection an; - private boolean invulnerable; - protected UUID uniqueID; - protected String ap; - public boolean glowing; - private final Set aE; - private boolean aF; - private final double[] aG; - private long aH; - private EntitySize size; - private float headHeight; - // CraftBukkit start - public boolean persist = true; - public boolean valid; - public org.bukkit.projectiles.ProjectileSource projectileSource; // For projectiles only - public boolean forceExplosionKnockback; // SPIGOT-949 - public Timing tickTimer = MinecraftTimings.getEntityTimings(this); // Paper - public Location origin; // Paper - // Spigot start - public final org.spigotmc.ActivationRange.ActivationType activationType = org.spigotmc.ActivationRange.initializeEntityActivationType(this); - public final boolean defaultActivationState; - public long activatedTick = Integer.MIN_VALUE; - public boolean fromMobSpawner; - public boolean spawnedViaMobSpawner; // Paper - Yes this name is similar to above, upstream took the better one - protected int numCollisions = 0; // Paper - public void inactiveTick() { } - // Spigot end - - public float getBukkitYaw() { - return this.yaw; - } - - public boolean isChunkLoaded() { - return world.getChunkIfLoadedImmediately((int) Math.floor(this.locX) >> 4, (int) Math.floor(this.locZ) >> 4) != null; // Paper - } - // CraftBukkit end - - public Entity(EntityTypes entitytypes, World world) { - this.id = Entity.entityCount.incrementAndGet(); - this.passengers = Lists.newArrayList(); - this.mot = Vec3D.a; - this.boundingBox = Entity.d; - this.B = Vec3D.a; - this.av = 1.0F; - this.aw = 1.0F; - this.random = SHARED_RANDOM; // Paper - this.fireTicks = -this.getMaxFireTicks(); - this.justCreated = true; - this.uniqueID = MathHelper.a(this.random); - this.ap = this.uniqueID.toString(); - this.aE = Sets.newHashSet(); - this.aG = new double[]{0.0D, 0.0D, 0.0D}; - this.f = entitytypes; - this.world = world; - this.size = entitytypes.k(); - this.setPosition(0.0D, 0.0D, 0.0D); - if (world != null) { - this.dimension = world.worldProvider.getDimensionManager(); - // Spigot start - this.defaultActivationState = org.spigotmc.ActivationRange.initializeEntityActivationState(this, world.spigotConfig); - } else { - this.defaultActivationState = false; - } - // Spigot end - - this.datawatcher = new DataWatcher(this); - this.datawatcher.register(Entity.W, (byte) 0); - this.datawatcher.register(Entity.AIR_TICKS, this.bp()); - this.datawatcher.register(Entity.aA, false); - this.datawatcher.register(Entity.az, Optional.empty()); - this.datawatcher.register(Entity.aB, false); - this.datawatcher.register(Entity.aC, false); - this.datawatcher.register(Entity.POSE, EntityPose.STANDING); - this.initDatawatcher(); - this.datawatcher.registrationLocked = true; // Spigot - this.headHeight = this.getHeadHeight(EntityPose.STANDING, this.size); - } - - public boolean isSpectator() { - return false; - } - - public final void decouple() { - if (this.isVehicle()) { - this.ejectPassengers(); - } - - if (this.isPassenger()) { - this.stopRiding(); - } - - } - - public EntityTypes getEntityType() { - return this.f; - } - - public int getId() { - return this.id; - } - - public void e(int i) { - this.id = i; - } - - public Set getScoreboardTags() { - return this.aE; - } - - public boolean addScoreboardTag(String s) { - return this.aE.size() >= 1024 ? false : this.aE.add(s); - } - - public boolean removeScoreboardTag(String s) { - return this.aE.remove(s); - } - - public void killEntity() { - this.die(); - } - - protected abstract void initDatawatcher(); - - public DataWatcher getDataWatcher() { - return this.datawatcher; - } - - public boolean equals(Object object) { - return object instanceof Entity ? ((Entity) object).id == this.id : false; - } - - public int hashCode() { - return this.id; - } - - public void die() { - this.dead = true; - } - - protected void setPose(EntityPose entitypose) { - // CraftBukkit start - if (entitypose == this.getPose()) { - return; - } - this.world.getServer().getPluginManager().callEvent(new EntityPoseChangeEvent(this.getBukkitEntity(), Pose.values()[entitypose.ordinal()])); - // CraftBukkit end - this.datawatcher.set(Entity.POSE, entitypose); - } - - public EntityPose getPose() { - return (EntityPose) this.datawatcher.get(Entity.POSE); - } - - 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?)"); - } - 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?)"); - } - f1 = 0; - } - // CraftBukkit end - - this.yaw = f % 360.0F; - this.pitch = f1 % 360.0F; - } - - public void setPosition(double d0, double d1, double d2) { - this.locX = d0; - this.locY = d1; - this.locZ = d2; - float f = this.size.width / 2.0F; - float f1 = this.size.height; - - this.a(new AxisAlignedBB(d0 - (double) f, d1, d2 - (double) f, d0 + (double) f, d1 + (double) f1, d2 + (double) f)); - if (valid) ((WorldServer) world).chunkCheck(this); // CraftBukkit - } - - public void tick() { - if (!this.world.isClientSide) { - this.setFlag(6, this.bm()); - } - - this.entityBaseTick(); - } - - // CraftBukkit start - public void postTick() { - // No clean way to break out of ticking once the entity has been copied to a new world, so instead we move the portalling later in the tick cycle - if (!(this instanceof EntityPlayer)) { - this.doPortalTick(); - } - } - // CraftBukkit end - - public void entityBaseTick() { - this.world.getMethodProfiler().enter("entityBaseTick"); - if (this.isPassenger() && this.getVehicle().dead) { - this.stopRiding(); - } - - if (this.j > 0) { - --this.j; - } - - this.D = this.E; - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - this.lastPitch = this.pitch; - this.lastYaw = this.yaw; - if (this instanceof EntityPlayer) this.doPortalTick(); // CraftBukkit - // Moved up to postTick - this.aA(); - this.m(); - if (this.world.isClientSide) { - this.extinguish(); - } else if (this.fireTicks > 0) { - if (this.isFireProof()) { - this.fireTicks -= 4; - if (this.fireTicks < 0) { - this.extinguish(); - } - } else { - if (this.fireTicks % 20 == 0) { - this.damageEntity(DamageSource.BURN, 1.0F); - } - - --this.fireTicks; - } - } - - if (this.aD()) { - this.burnFromLava(); - this.fallDistance *= 0.5F; - } - - // Paper start - Configurable nether ceiling damage - // Extracted to own function - /* - if (this.locY < -64.0D) { - this.af(); - } - */ - this.performVoidDamage(); - // Paper end - - if (!this.world.isClientSide) { - this.setFlag(0, this.fireTicks > 0); - } - - this.justCreated = false; - this.world.getMethodProfiler().exit(); - } - - // Paper start - protected void performVoidDamage() { - if (this.locY < -64.0D || (this.world.getWorld().getEnvironment() == org.bukkit.World.Environment.NETHER - && world.paperConfig.doNetherTopVoidDamage() - && this.locY >= world.paperConfig.netherVoidTopDamageHeight)) { - - this.doVoidDamage(); - } - } - // Paper end - - protected void E() { - if (this.portalCooldown > 0) { - --this.portalCooldown; - } - - } - - public int ab() { - return 1; - } - - protected void burnFromLava() { - if (!this.isFireProof()) { - // CraftBukkit start - Fallen in lava TODO: this event spams! - if (this instanceof EntityLiving && fireTicks <= 0) { - // not on fire yet - // TODO: shouldn't be sending null for the block - org.bukkit.block.Block damager = null; // ((WorldServer) this.l).getWorld().getBlockAt(i, j, k); - org.bukkit.entity.Entity damagee = this.getBukkitEntity(); - EntityCombustEvent combustEvent = new org.bukkit.event.entity.EntityCombustByBlockEvent(damager, damagee, 15); - this.world.getServer().getPluginManager().callEvent(combustEvent); - - if (!combustEvent.isCancelled()) { - this.setOnFire(combustEvent.getDuration(), false); - } - } else { - // This will be called every single tick the entity is in lava, so don't throw an event - this.setOnFire(15, false); - } - // CraftBukkit end - we also don't throw an event unless the object in lava is living, to save on some event calls - this.damageEntity(DamageSource.LAVA, 4.0F); - } - } - - public void setOnFire(int i) { - // CraftBukkit start - this.setOnFire(i, true); - } - - public void setOnFire(int i, boolean callEvent) { - if (callEvent) { - EntityCombustEvent event = new EntityCombustEvent(this.getBukkitEntity(), i); - this.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - - i = event.getDuration(); - } - // CraftBukkit end - int j = i * 20; - - if (this instanceof EntityLiving) { - j = EnchantmentProtection.a((EntityLiving) this, j); - } - - if (this.fireTicks < j) { - this.fireTicks = j; - } - - } - - public void g(int i) { - this.fireTicks = i; - } - - public int ad() { - return this.fireTicks; - } - - public void extinguish() { - this.fireTicks = 0; - } - - protected final void doVoidDamage() { this.af(); } // Paper - OBFHELPER - protected void af() { - this.die(); - } - - public boolean d(double d0, double d1, double d2) { - return this.b(this.getBoundingBox().d(d0, d1, d2)); - } - - private boolean b(AxisAlignedBB axisalignedbb) { - return this.world.getCubes(this, axisalignedbb) && !this.world.containsLiquid(axisalignedbb); - } - - public void move(EnumMoveType enummovetype, Vec3D vec3d) { - if (this.noclip) { - this.a(this.getBoundingBox().b(vec3d)); - this.recalcPosition(); - } else { - if (enummovetype == EnumMoveType.PISTON) { - vec3d = this.a(vec3d); - if (vec3d.equals(Vec3D.a)) { - return; - } - } - - this.world.getMethodProfiler().enter("move"); - if (this.B.g() > 1.0E-7D) { - vec3d = vec3d.h(this.B); - this.B = Vec3D.a; - this.setMot(Vec3D.a); - } - - vec3d = this.a(vec3d, enummovetype); - Vec3D vec3d1 = this.e(vec3d); - - if (vec3d1.g() > 1.0E-7D) { - this.a(this.getBoundingBox().b(vec3d1)); - this.recalcPosition(); - } - - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("rest"); - this.positionChanged = !MathHelper.b(vec3d.x, vec3d1.x) || !MathHelper.b(vec3d.z, vec3d1.z); - this.y = vec3d.y != vec3d1.y; - this.onGround = this.y && vec3d.y < 0.0D; - this.z = this.positionChanged || this.y; - int i = MathHelper.floor(this.locX); - int j = MathHelper.floor(this.locY - 0.20000000298023224D); - int k = MathHelper.floor(this.locZ); - BlockPosition blockposition = new BlockPosition(i, j, k); - IBlockData iblockdata = this.world.getType(blockposition); - - if (iblockdata.isAir()) { - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata1 = this.world.getType(blockposition1); - Block block = iblockdata1.getBlock(); - - if (block.a(TagsBlock.FENCES) || block.a(TagsBlock.WALLS) || block instanceof BlockFenceGate) { - iblockdata = iblockdata1; - blockposition = blockposition1; - } - } - - this.a(vec3d1.y, this.onGround, iblockdata, blockposition); - Vec3D vec3d2 = this.getMot(); - - if (vec3d.x != vec3d1.x) { - this.setMot(0.0D, vec3d2.y, vec3d2.z); - } - - if (vec3d.z != vec3d1.z) { - this.setMot(vec3d2.x, vec3d2.y, 0.0D); - } - - Block block1 = iblockdata.getBlock(); - - if (vec3d.y != vec3d1.y) { - block1.a((IBlockAccess) this.world, this); - } - - // CraftBukkit start - if (positionChanged && getBukkitEntity() instanceof Vehicle) { - Vehicle vehicle = (Vehicle) this.getBukkitEntity(); - org.bukkit.block.Block bl = this.world.getWorld().getBlockAt(MathHelper.floor(this.locX), MathHelper.floor(this.locY), MathHelper.floor(this.locZ)); - - if (vec3d1.x > vec3d.x) { - bl = bl.getRelative(BlockFace.EAST); - } else if (vec3d.x < vec3d.x) { - bl = bl.getRelative(BlockFace.WEST); - } else if (vec3d1.z > vec3d.z) { - bl = bl.getRelative(BlockFace.SOUTH); - } else if (vec3d1.z < vec3d.z) { - bl = bl.getRelative(BlockFace.NORTH); - } - - if (bl.getType() != org.bukkit.Material.AIR) { - VehicleBlockCollisionEvent event = new VehicleBlockCollisionEvent(vehicle, bl); - world.getServer().getPluginManager().callEvent(event); - } - } - // CraftBukkit end - - if (this.playStepSound() && (!this.onGround || !this.isSneaking() || !(this instanceof EntityHuman)) && !this.isPassenger()) { - double d0 = vec3d1.x; - double d1 = vec3d1.y; - double d2 = vec3d1.z; - - if (block1 != Blocks.LADDER && block1 != Blocks.SCAFFOLDING) { - d1 = 0.0D; - } - - if (this.onGround) { - block1.stepOn(this.world, blockposition, this); - } - - this.E = (float) ((double) this.E + (double) MathHelper.sqrt(b(vec3d1)) * 0.6D); - this.F = (float) ((double) this.F + (double) MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 0.6D); - if (this.F > this.av && !iblockdata.isAir()) { - this.av = this.ag(); - if (this.isInWater()) { - Entity entity = this.isVehicle() && this.getRidingPassenger() != null ? this.getRidingPassenger() : this; - float f = entity == this ? 0.35F : 0.4F; - Vec3D vec3d3 = entity.getMot(); - float f1 = MathHelper.sqrt(vec3d3.x * vec3d3.x * 0.20000000298023224D + vec3d3.y * vec3d3.y + vec3d3.z * vec3d3.z * 0.20000000298023224D) * f; - - if (f1 > 1.0F) { - f1 = 1.0F; - } - - this.d(f1); - } else { - this.a(blockposition, iblockdata); - } - } else if (this.F > this.aw && this.am() && iblockdata.isAir()) { - this.aw = this.e(this.F); - } - } - - try { - this.inLava = false; - this.checkBlockCollisions(); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Checking entity block collision"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Entity being checked for collision"); - - this.appendEntityCrashDetails(crashreportsystemdetails); - throw new ReportedException(crashreport); - } - - boolean flag = this.au(); - - if (this.world.b(this.getBoundingBox().shrink(0.001D))) { - if (!flag) { - ++this.fireTicks; - if (this.fireTicks == 0) { - // CraftBukkit start - EntityCombustEvent event = new org.bukkit.event.entity.EntityCombustByBlockEvent(null, getBukkitEntity(), 8); - world.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - this.setOnFire(event.getDuration(), false); - } - // CraftBukkit end - } - } - - this.burn(1); - } else if (this.fireTicks <= 0) { - this.fireTicks = -this.getMaxFireTicks(); - } - - if (flag && this.isBurning()) { - this.a(SoundEffects.ENTITY_GENERIC_EXTINGUISH_FIRE, 0.7F, 1.6F + (this.random.nextFloat() - this.random.nextFloat()) * 0.4F); - this.fireTicks = -this.getMaxFireTicks(); - } - - this.world.getMethodProfiler().exit(); - } - } - - protected Vec3D a(Vec3D vec3d, EnumMoveType enummovetype) { - if (this instanceof EntityHuman && (enummovetype == EnumMoveType.SELF || enummovetype == EnumMoveType.PLAYER) && this.onGround && this.isSneaking()) { - double d0 = vec3d.x; - double d1 = vec3d.z; - double d2 = 0.05D; - - while (d0 != 0.0D && this.world.getCubes(this, this.getBoundingBox().d(d0, (double) (-this.K), 0.0D))) { - if (d0 < 0.05D && d0 >= -0.05D) { - d0 = 0.0D; - } else if (d0 > 0.0D) { - d0 -= 0.05D; - } else { - d0 += 0.05D; - } - } - - while (d1 != 0.0D && this.world.getCubes(this, this.getBoundingBox().d(0.0D, (double) (-this.K), d1))) { - if (d1 < 0.05D && d1 >= -0.05D) { - d1 = 0.0D; - } else if (d1 > 0.0D) { - d1 -= 0.05D; - } else { - d1 += 0.05D; - } - } - - while (d0 != 0.0D && d1 != 0.0D && this.world.getCubes(this, this.getBoundingBox().d(d0, (double) (-this.K), d1))) { - if (d0 < 0.05D && d0 >= -0.05D) { - d0 = 0.0D; - } else if (d0 > 0.0D) { - d0 -= 0.05D; - } else { - d0 += 0.05D; - } - - if (d1 < 0.05D && d1 >= -0.05D) { - d1 = 0.0D; - } else if (d1 > 0.0D) { - d1 -= 0.05D; - } else { - d1 += 0.05D; - } - } - - vec3d = new Vec3D(d0, vec3d.y, d1); - } - - return vec3d; - } - - protected Vec3D a(Vec3D vec3d) { - if (vec3d.g() <= 1.0E-7D) { - return vec3d; - } else { - long i = this.world.getTime(); - - if (i != this.aH) { - Arrays.fill(this.aG, 0.0D); - this.aH = i; - } - - double d0; - - if (vec3d.x != 0.0D) { - d0 = this.a(EnumDirection.EnumAxis.X, vec3d.x); - return Math.abs(d0) <= 9.999999747378752E-6D ? Vec3D.a : new Vec3D(d0, 0.0D, 0.0D); - } else if (vec3d.y != 0.0D) { - d0 = this.a(EnumDirection.EnumAxis.Y, vec3d.y); - return Math.abs(d0) <= 9.999999747378752E-6D ? Vec3D.a : new Vec3D(0.0D, d0, 0.0D); - } else if (vec3d.z != 0.0D) { - d0 = this.a(EnumDirection.EnumAxis.Z, vec3d.z); - return Math.abs(d0) <= 9.999999747378752E-6D ? Vec3D.a : new Vec3D(0.0D, 0.0D, d0); - } else { - return Vec3D.a; - } - } - } - - private double a(EnumDirection.EnumAxis enumdirection_enumaxis, double d0) { - int i = enumdirection_enumaxis.ordinal(); - double d1 = MathHelper.a(d0 + this.aG[i], -0.51D, 0.51D); - - d0 = d1 - this.aG[i]; - this.aG[i] = d1; - return d0; - } - - private Vec3D e(Vec3D vec3d) { - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - VoxelShapeCollision voxelshapecollision = VoxelShapeCollision.a(this); - VoxelShape voxelshape = this.world.getWorldBorder().a(); - Stream stream = VoxelShapes.c(voxelshape, VoxelShapes.a(axisalignedbb.shrink(1.0E-7D)), OperatorBoolean.AND) ? Stream.empty() : Stream.of(voxelshape); - Stream stream1 = this.world.a(this, axisalignedbb.a(vec3d), (Set) ImmutableSet.of()); - StreamAccumulator streamaccumulator = new StreamAccumulator<>(Stream.concat(stream1, stream)); - Vec3D vec3d1 = vec3d.g() == 0.0D ? vec3d : a(this, vec3d, axisalignedbb, this.world, voxelshapecollision, streamaccumulator); - boolean flag = vec3d.x != vec3d1.x; - boolean flag1 = vec3d.y != vec3d1.y; - boolean flag2 = vec3d.z != vec3d1.z; - boolean flag3 = this.onGround || flag1 && vec3d.y < 0.0D; - - if (this.K > 0.0F && flag3 && (flag || flag2)) { - Vec3D vec3d2 = a(this, new Vec3D(vec3d.x, (double) this.K, vec3d.z), axisalignedbb, this.world, voxelshapecollision, streamaccumulator); - Vec3D vec3d3 = a(this, new Vec3D(0.0D, (double) this.K, 0.0D), axisalignedbb.b(vec3d.x, 0.0D, vec3d.z), this.world, voxelshapecollision, streamaccumulator); - - if (vec3d3.y < (double) this.K) { - Vec3D vec3d4 = a(this, new Vec3D(vec3d.x, 0.0D, vec3d.z), axisalignedbb.b(vec3d3), this.world, voxelshapecollision, streamaccumulator).e(vec3d3); - - if (b(vec3d4) > b(vec3d2)) { - vec3d2 = vec3d4; - } - } - - if (b(vec3d2) > b(vec3d1)) { - return vec3d2.e(a(this, new Vec3D(0.0D, -vec3d2.y + vec3d.y, 0.0D), axisalignedbb.b(vec3d2), this.world, voxelshapecollision, streamaccumulator)); - } - } - - return vec3d1; - } - - public static double b(Vec3D vec3d) { - return vec3d.x * vec3d.x + vec3d.z * vec3d.z; - } - - public static Vec3D a(@Nullable Entity entity, Vec3D vec3d, AxisAlignedBB axisalignedbb, World world, VoxelShapeCollision voxelshapecollision, StreamAccumulator streamaccumulator) { - boolean flag = vec3d.x == 0.0D; - boolean flag1 = vec3d.y == 0.0D; - boolean flag2 = vec3d.z == 0.0D; - - if ((!flag || !flag1) && (!flag || !flag2) && (!flag1 || !flag2)) { - StreamAccumulator streamaccumulator1 = new StreamAccumulator<>(Stream.concat(streamaccumulator.a(), world.b(entity, axisalignedbb.a(vec3d)))); - - return a(vec3d, axisalignedbb, streamaccumulator1); - } else { - return a(vec3d, axisalignedbb, world, voxelshapecollision, streamaccumulator); - } - } - - public static Vec3D a(Vec3D vec3d, AxisAlignedBB axisalignedbb, StreamAccumulator streamaccumulator) { - double d0 = vec3d.x; - double d1 = vec3d.y; - double d2 = vec3d.z; - - if (d1 != 0.0D) { - d1 = VoxelShapes.a(EnumDirection.EnumAxis.Y, axisalignedbb, streamaccumulator.a(), d1); - if (d1 != 0.0D) { - axisalignedbb = axisalignedbb.d(0.0D, d1, 0.0D); - } - } - - boolean flag = Math.abs(d0) < Math.abs(d2); - - if (flag && d2 != 0.0D) { - d2 = VoxelShapes.a(EnumDirection.EnumAxis.Z, axisalignedbb, streamaccumulator.a(), d2); - if (d2 != 0.0D) { - axisalignedbb = axisalignedbb.d(0.0D, 0.0D, d2); - } - } - - if (d0 != 0.0D) { - d0 = VoxelShapes.a(EnumDirection.EnumAxis.X, axisalignedbb, streamaccumulator.a(), d0); - if (!flag && d0 != 0.0D) { - axisalignedbb = axisalignedbb.d(d0, 0.0D, 0.0D); - } - } - - if (!flag && d2 != 0.0D) { - d2 = VoxelShapes.a(EnumDirection.EnumAxis.Z, axisalignedbb, streamaccumulator.a(), d2); - } - - return new Vec3D(d0, d1, d2); - } - - public static Vec3D a(Vec3D vec3d, AxisAlignedBB axisalignedbb, IWorldReader iworldreader, VoxelShapeCollision voxelshapecollision, StreamAccumulator streamaccumulator) { - double d0 = vec3d.x; - double d1 = vec3d.y; - double d2 = vec3d.z; - - if (d1 != 0.0D) { - d1 = VoxelShapes.a(EnumDirection.EnumAxis.Y, axisalignedbb, iworldreader, d1, voxelshapecollision, streamaccumulator.a()); - if (d1 != 0.0D) { - axisalignedbb = axisalignedbb.d(0.0D, d1, 0.0D); - } - } - - boolean flag = Math.abs(d0) < Math.abs(d2); - - if (flag && d2 != 0.0D) { - d2 = VoxelShapes.a(EnumDirection.EnumAxis.Z, axisalignedbb, iworldreader, d2, voxelshapecollision, streamaccumulator.a()); - if (d2 != 0.0D) { - axisalignedbb = axisalignedbb.d(0.0D, 0.0D, d2); - } - } - - if (d0 != 0.0D) { - d0 = VoxelShapes.a(EnumDirection.EnumAxis.X, axisalignedbb, iworldreader, d0, voxelshapecollision, streamaccumulator.a()); - if (!flag && d0 != 0.0D) { - axisalignedbb = axisalignedbb.d(d0, 0.0D, 0.0D); - } - } - - if (!flag && d2 != 0.0D) { - d2 = VoxelShapes.a(EnumDirection.EnumAxis.Z, axisalignedbb, iworldreader, d2, voxelshapecollision, streamaccumulator.a()); - } - - return new Vec3D(d0, d1, d2); - } - - protected float ag() { - return (float) ((int) this.F + 1); - } - - public void recalcPosition() { - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - - this.locX = (axisalignedbb.minX + axisalignedbb.maxX) / 2.0D; - this.locY = axisalignedbb.minY; - this.locZ = (axisalignedbb.minZ + axisalignedbb.maxZ) / 2.0D; - if (valid) ((WorldServer) world).chunkCheck(this); // CraftBukkit - } - - protected SoundEffect getSoundSwim() { - return SoundEffects.ENTITY_GENERIC_SWIM; - } - - protected SoundEffect getSoundSplash() { - return SoundEffects.ENTITY_GENERIC_SPLASH; - } - - protected SoundEffect getSoundSplashHighSpeed() { - return SoundEffects.ENTITY_GENERIC_SPLASH; - } - - protected void checkBlockCollisions() { - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.d(axisalignedbb.minX + 0.001D, axisalignedbb.minY + 0.001D, axisalignedbb.minZ + 0.001D); - Throwable throwable = null; - - try { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition1 = BlockPosition.PooledBlockPosition.d(axisalignedbb.maxX - 0.001D, axisalignedbb.maxY - 0.001D, axisalignedbb.maxZ - 0.001D); - Throwable throwable1 = null; - - try { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition2 = BlockPosition.PooledBlockPosition.r(); - Throwable throwable2 = null; - - try { - if (this.world.areChunksLoadedBetween(blockposition_pooledblockposition, blockposition_pooledblockposition1)) { - for (int i = blockposition_pooledblockposition.getX(); i <= blockposition_pooledblockposition1.getX(); ++i) { - for (int j = blockposition_pooledblockposition.getY(); j <= blockposition_pooledblockposition1.getY(); ++j) { - for (int k = blockposition_pooledblockposition.getZ(); k <= blockposition_pooledblockposition1.getZ(); ++k) { - blockposition_pooledblockposition2.d(i, j, k); - IBlockData iblockdata = this.world.getType(blockposition_pooledblockposition2); - - try { - iblockdata.a(this.world, blockposition_pooledblockposition2, this); - this.a(iblockdata); - } catch (Throwable throwable3) { - CrashReport crashreport = CrashReport.a(throwable3, "Colliding entity with block"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Block being collided with"); - - CrashReportSystemDetails.a(crashreportsystemdetails, blockposition_pooledblockposition2, iblockdata); - throw new ReportedException(crashreport); - } - } - } - } - } - } catch (Throwable throwable4) { - throwable2 = throwable4; - throw throwable4; - } finally { - if (blockposition_pooledblockposition2 != null) { - if (throwable2 != null) { - try { - blockposition_pooledblockposition2.close(); - } catch (Throwable throwable5) { - throwable2.addSuppressed(throwable5); - } - } else { - blockposition_pooledblockposition2.close(); - } - } - - } - } catch (Throwable throwable6) { - throwable1 = throwable6; - throw throwable6; - } finally { - if (blockposition_pooledblockposition1 != null) { - if (throwable1 != null) { - try { - blockposition_pooledblockposition1.close(); - } catch (Throwable throwable7) { - throwable1.addSuppressed(throwable7); - } - } else { - blockposition_pooledblockposition1.close(); - } - } - - } - } catch (Throwable throwable8) { - throwable = throwable8; - throw throwable8; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable9) { - throwable.addSuppressed(throwable9); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - } - - protected void a(IBlockData iblockdata) {} - - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - if (!iblockdata.getMaterial().isLiquid()) { - IBlockData iblockdata1 = this.world.getType(blockposition.up()); - SoundEffectType soundeffecttype = iblockdata1.getBlock() == Blocks.SNOW ? iblockdata1.r() : iblockdata.r(); - - this.a(soundeffecttype.d(), soundeffecttype.a() * 0.15F, soundeffecttype.b()); - } - } - - protected void d(float f) { - this.a(this.getSoundSwim(), f, 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.4F); - } - - protected float e(float f) { - return 0.0F; - } - - protected boolean am() { - return false; - } - - public void a(SoundEffect soundeffect, float f, float f1) { - if (!this.isSilent()) { - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, soundeffect, this.getSoundCategory(), f, f1); - } - - } - - public boolean isSilent() { - return (Boolean) this.datawatcher.get(Entity.aB); - } - - public void setSilent(boolean flag) { - this.datawatcher.set(Entity.aB, flag); - } - - public boolean isNoGravity() { - return (Boolean) this.datawatcher.get(Entity.aC); - } - - public void setNoGravity(boolean flag) { - this.datawatcher.set(Entity.aC, flag); - } - - protected boolean playStepSound() { - return true; - } - - protected void a(double d0, boolean flag, IBlockData iblockdata, BlockPosition blockposition) { - if (flag) { - if (this.fallDistance > 0.0F) { - iblockdata.getBlock().fallOn(this.world, blockposition, this, this.fallDistance); - } - - this.fallDistance = 0.0F; - } else if (d0 < 0.0D) { - this.fallDistance = (float) ((double) this.fallDistance - d0); - } - - } - - @Nullable - public AxisAlignedBB aq() { - return null; - } - - protected void burn(float i) { // CraftBukkit - int -> float - if (!this.isFireProof()) { - this.damageEntity(DamageSource.FIRE, (float) i); - } - - } - - public final boolean isFireProof() { - return this.getEntityType().c(); - } - - public void b(float f, float f1) { - if (this.isVehicle()) { - Iterator iterator = this.getPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - entity.b(f, f1); - } - } - - } - - public boolean isInWater() { - return this.inWater; - } - - private boolean isInRain() { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.b(this); - Throwable throwable = null; - - boolean flag; - - try { - flag = this.world.isRainingAt(blockposition_pooledblockposition) || this.world.isRainingAt(blockposition_pooledblockposition.c(this.locX, this.locY + (double) this.size.height, this.locZ)); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - return flag; - } - - private boolean l() { - return this.world.getType(new BlockPosition(this)).getBlock() == Blocks.BUBBLE_COLUMN; - } - - public boolean isInWaterOrRain() { - return this.isInWater() || this.isInRain(); - } - - public boolean au() { - return this.isInWater() || this.isInRain() || this.l(); - } - - public boolean av() { - return this.isInWater() || this.l(); - } - - public boolean aw() { - return this.R && this.isInWater(); - } - - private void m() { - this.ay(); - this.n(); - this.ax(); - } - - public void ax() { - if (this.isSwimming()) { - this.setSwimming(this.isSprinting() && this.isInWater() && !this.isPassenger()); - } else { - this.setSwimming(this.isSprinting() && this.aw() && !this.isPassenger()); - } - - } - - public boolean ay() { - if (this.getVehicle() instanceof EntityBoat) { - this.inWater = false; - } else if (this.b(TagsFluid.WATER)) { - if (!this.inWater && !this.justCreated) { - this.az(); - } - - this.fallDistance = 0.0F; - this.inWater = true; - this.extinguish(); - } else { - this.inWater = false; - } - - return this.inWater; - } - - private void n() { - this.R = this.a(TagsFluid.WATER, true); - } - - protected void az() { - Entity entity = this.isVehicle() && this.getRidingPassenger() != null ? this.getRidingPassenger() : this; - float f = entity == this ? 0.2F : 0.9F; - Vec3D vec3d = entity.getMot(); - float f1 = MathHelper.sqrt(vec3d.x * vec3d.x * 0.20000000298023224D + vec3d.y * vec3d.y + vec3d.z * vec3d.z * 0.20000000298023224D) * f; - - if (f1 > 1.0F) { - f1 = 1.0F; - } - - if ((double) f1 < 0.25D) { - this.a(this.getSoundSplash(), f1, 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.4F); - } else { - this.a(this.getSoundSplashHighSpeed(), f1, 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.4F); - } - - float f2 = (float) MathHelper.floor(this.getBoundingBox().minY); - - float f3; - float f4; - int i; - - for (i = 0; (float) i < 1.0F + this.size.width * 20.0F; ++i) { - f3 = (this.random.nextFloat() * 2.0F - 1.0F) * this.size.width; - f4 = (this.random.nextFloat() * 2.0F - 1.0F) * this.size.width; - this.world.addParticle(Particles.BUBBLE, this.locX + (double) f3, (double) (f2 + 1.0F), this.locZ + (double) f4, vec3d.x, vec3d.y - (double) (this.random.nextFloat() * 0.2F), vec3d.z); - } - - for (i = 0; (float) i < 1.0F + this.size.width * 20.0F; ++i) { - f3 = (this.random.nextFloat() * 2.0F - 1.0F) * this.size.width; - f4 = (this.random.nextFloat() * 2.0F - 1.0F) * this.size.width; - this.world.addParticle(Particles.SPLASH, this.locX + (double) f3, (double) (f2 + 1.0F), this.locZ + (double) f4, vec3d.x, vec3d.y, vec3d.z); - } - - } - - public void aA() { - if (this.isSprinting() && !this.isInWater()) { - this.aB(); - } - - } - - protected void aB() { - int i = MathHelper.floor(this.locX); - int j = MathHelper.floor(this.locY - 0.20000000298023224D); - int k = MathHelper.floor(this.locZ); - BlockPosition blockposition = new BlockPosition(i, j, k); - IBlockData iblockdata = this.world.getType(blockposition); - - if (iblockdata.k() != EnumRenderType.INVISIBLE) { - Vec3D vec3d = this.getMot(); - - this.world.addParticle(new ParticleParamBlock(Particles.BLOCK, iblockdata), this.locX + ((double) this.random.nextFloat() - 0.5D) * (double) this.size.width, this.locY + 0.1D, this.locZ + ((double) this.random.nextFloat() - 0.5D) * (double) this.size.width, vec3d.x * -4.0D, 1.5D, vec3d.z * -4.0D); - } - - } - - public boolean a(Tag tag) { - return this.a(tag, false); - } - - public boolean a(Tag tag, boolean flag) { - if (this.getVehicle() instanceof EntityBoat) { - return false; - } else { - double d0 = this.locY + (double) this.getHeadHeight(); - BlockPosition blockposition = new BlockPosition(this.locX, d0, this.locZ); - - if (flag && !this.world.isChunkLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4)) { - return false; - } else { - Fluid fluid = this.world.getFluid(blockposition); - - return fluid.a(tag) && d0 < (double) ((float) blockposition.getY() + fluid.getHeight(this.world, blockposition) + 0.11111111F); - } - } - } - - public void aC() { - this.inLava = true; - } - - public boolean aD() { - return this.inLava; - } - - public void a(float f, Vec3D vec3d) { - Vec3D vec3d1 = a(vec3d, f, this.yaw); - - this.setMot(this.getMot().e(vec3d1)); - } - - protected static Vec3D a(Vec3D vec3d, float f, float f1) { - double d0 = vec3d.g(); - - if (d0 < 1.0E-7D) { - return Vec3D.a; - } else { - Vec3D vec3d1 = (d0 > 1.0D ? vec3d.d() : vec3d).a((double) f); - float f2 = MathHelper.sin(f1 * 0.017453292F); - float f3 = MathHelper.cos(f1 * 0.017453292F); - - return new Vec3D(vec3d1.x * (double) f3 - vec3d1.z * (double) f2, vec3d1.y, vec3d1.z * (double) f3 + vec3d1.x * (double) f2); - } - } - - public float aF() { - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(this.locX, 0.0D, this.locZ); - - if (this.world.isLoaded(blockposition_mutableblockposition)) { - blockposition_mutableblockposition.p(MathHelper.floor(this.locY + (double) this.getHeadHeight())); - return this.world.v(blockposition_mutableblockposition); - } else { - return 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.locX = MathHelper.a(d0, -3.0E7D, 3.0E7D); - this.locY = d1; - this.locZ = MathHelper.a(d2, -3.0E7D, 3.0E7D); - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - f1 = MathHelper.a(f1, -90.0F, 90.0F); - this.yaw = f; - this.pitch = f1; - this.lastYaw = this.yaw; - this.lastPitch = this.pitch; - double d3 = (double) (this.lastYaw - f); - - if (d3 < -180.0D) { - this.lastYaw += 360.0F; - } - - if (d3 >= 180.0D) { - this.lastYaw -= 360.0F; - } - - world.getChunkAt((int) Math.floor(this.locX) >> 4, (int) Math.floor(this.locZ) >> 4); // CraftBukkit - this.setPosition(this.locX, this.locY, this.locZ); - this.setYawPitch(f, f1); - } - - public void setPositionRotation(BlockPosition blockposition, float f, float f1) { - this.setPositionRotation((double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, f, f1); - } - - public void setPositionRotation(double d0, double d1, double d2, float f, float f1) { - this.locX = d0; - this.locY = d1; - this.locZ = d2; - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - this.H = this.locX; - this.I = this.locY; - this.J = this.locZ; - 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 h(Entity entity) { - return this.c(entity.getPositionVector()); - } - - public double c(Vec3D vec3d) { - double d0 = this.locX - vec3d.x; - double d1 = this.locY - vec3d.y; - double d2 = this.locZ - vec3d.z; - - return d0 * d0 + d1 * d1 + d2 * d2; - } - - public void pickup(EntityHuman entityhuman) {} - - public void collide(Entity entity) { - if (!this.x(entity)) { - 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 = (double) 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 *= (double) (1.0F - this.M); - d1 *= (double) (1.0F - this.M); - if (!this.isVehicle()) { - this.f(-d0, 0.0D, -d1); - } - - if (!entity.isVehicle()) { - entity.f(d0, 0.0D, d1); - } - } - - } - } - } - - public void f(double d0, double d1, double d2) { - this.setMot(this.getMot().add(d0, d1, d2)); - this.impulse = true; - } - - protected void velocityChanged() { - this.velocityChanged = true; - } - - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - this.velocityChanged(); - return false; - } - } - - public final Vec3D f(float f) { - return this.c(this.g(f), this.h(f)); - } - - public float g(float f) { - return f == 1.0F ? this.pitch : MathHelper.g(f, this.lastPitch, this.pitch); - } - - public float h(float f) { - return f == 1.0F ? this.yaw : MathHelper.g(f, this.lastYaw, this.yaw); - } - - protected final Vec3D c(float f, float f1) { - float f2 = f * 0.017453292F; - float f3 = -f1 * 0.017453292F; - float f4 = MathHelper.cos(f3); - float f5 = MathHelper.sin(f3); - float f6 = MathHelper.cos(f2); - float f7 = MathHelper.sin(f2); - - return new Vec3D((double) (f5 * f6), (double) (-f7), (double) (f4 * f6)); - } - - public final Vec3D i(float f) { - return this.d(this.g(f), this.h(f)); - } - - protected final Vec3D d(float f, float f1) { - return this.c(f - 90.0F, f1); - } - - public final Vec3D getEyePosition(float partialTicks) { return j(partialTicks); } // Paper - OBFHELPER - public Vec3D j(float f) { - if (f == 1.0F) { - return new Vec3D(this.locX, this.locY + (double) this.getHeadHeight(), this.locZ); - } else { - double d0 = MathHelper.d((double) f, this.lastX, this.locX); - double d1 = MathHelper.d((double) f, this.lastY, this.locY) + (double) this.getHeadHeight(); - double d2 = MathHelper.d((double) f, this.lastZ, this.locZ); - - return new Vec3D(d0, d1, d2); - } - } - - public boolean isInteractable() { - return false; - } - - public boolean isCollidable() { - return false; - } - - public void runKillTrigger(Entity entity, int kills, DamageSource damageSource) { this.a(entity, kills, damageSource); } // Paper - OBFHELPER - public void a(Entity entity, int i, DamageSource damagesource) { - if (entity instanceof EntityPlayer) { - CriterionTriggers.c.a((EntityPlayer) entity, this, damagesource); - } - - } - - public boolean c(NBTTagCompound nbttagcompound) { - String s = this.getSaveID(); - - if (this.persist && !this.dead && s != null) { // CraftBukkit - persist flag - nbttagcompound.setString("id", s); - this.save(nbttagcompound); - return true; - } else { - return false; - } - } - - public boolean d(NBTTagCompound nbttagcompound) { - return this.isPassenger() ? false : this.c(nbttagcompound); - } - - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - try { - nbttagcompound.set("Pos", this.a(this.locX, this.locY, this.locZ)); - Vec3D vec3d = this.getMot(); - - nbttagcompound.set("Motion", this.a(vec3d.x, vec3d.y, vec3d.z)); - - // 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.getType().getDimensionID()); // CraftBukkit - preserve Vanilla compat - nbttagcompound.setBoolean("Invulnerable", this.invulnerable); - nbttagcompound.setInt("PortalCooldown", this.portalCooldown); - nbttagcompound.a("UUID", this.getUniqueID()); - // CraftBukkit start - // PAIL: Check above UUID reads 1.8 properly, ie: UUIDMost / UUIDLeast - nbttagcompound.setLong("WorldUUIDLeast", ((WorldServer) this.world).getDataManager().getUUID().getLeastSignificantBits()); - nbttagcompound.setLong("WorldUUIDMost", ((WorldServer) this.world).getDataManager().getUUID().getMostSignificantBits()); - nbttagcompound.setInt("Bukkit.updateLevel", CURRENT_LEVEL); - nbttagcompound.setInt("Spigot.ticksLived", this.ticksLived); - // CraftBukkit end - IChatBaseComponent ichatbasecomponent = this.getCustomName(); - - if (ichatbasecomponent != null) { - nbttagcompound.setString("CustomName", IChatBaseComponent.ChatSerializer.a(ichatbasecomponent)); - } - - if (this.getCustomNameVisible()) { - nbttagcompound.setBoolean("CustomNameVisible", this.getCustomNameVisible()); - } - - if (this.isSilent()) { - nbttagcompound.setBoolean("Silent", this.isSilent()); - } - - if (this.isNoGravity()) { - nbttagcompound.setBoolean("NoGravity", this.isNoGravity()); - } - - if (this.glowing) { - nbttagcompound.setBoolean("Glowing", this.glowing); - } - - NBTTagList nbttaglist; - Iterator iterator; - - if (!this.aE.isEmpty()) { - nbttaglist = new NBTTagList(); - iterator = this.aE.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - - nbttaglist.add(new NBTTagString(s)); - } - - nbttagcompound.set("Tags", nbttaglist); - } - - this.b(nbttagcompound); - if (this.isVehicle()) { - nbttaglist = new NBTTagList(); - iterator = this.getPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - if (entity.c(nbttagcompound1)) { - nbttaglist.add(nbttagcompound1); - } - } - - if (!nbttaglist.isEmpty()) { - nbttagcompound.set("Passengers", nbttaglist); - } - } - - // CraftBukkit start - stores eventually existing bukkit values - if (this.bukkitEntity != null) { - this.bukkitEntity.storeBukkitValues(nbttagcompound); - } - // CraftBukkit end - // Paper start - Save the entity's origin location - if (this.origin != null) { - nbttagcompound.set("Paper.Origin", this.createList(origin.getX(), origin.getY(), origin.getZ())); - } - if (spawnReason != null) { - nbttagcompound.setString("Paper.SpawnReason", spawnReason.name()); - } - // Save entity's from mob spawner status - if (spawnedViaMobSpawner) { - nbttagcompound.setBoolean("Paper.FromMobSpawner", true); - } - // Paper end - return nbttagcompound; - } 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); - double d0 = nbttaglist1.h(0); - double d1 = nbttaglist1.h(1); - double d2 = nbttaglist1.h(2); - - this.setMot(Math.abs(d0) > 10.0D ? 0.0D : d0, Math.abs(d1) > 10.0D ? 0.0D : d1, Math.abs(d2) > 10.0D ? 0.0D : d2); - this.locX = nbttaglist.h(0); - this.locY = nbttaglist.h(1); - this.locZ = nbttaglist.h(2); - this.H = this.locX; - this.I = this.locY; - this.J = this.locZ; - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - this.yaw = nbttaglist2.i(0); - this.pitch = nbttaglist2.i(1); - this.lastYaw = this.yaw; - this.lastPitch = this.pitch; - this.setHeadRotation(this.yaw); - this.l(this.yaw); - this.fallDistance = nbttagcompound.getFloat("FallDistance"); - this.fireTicks = nbttagcompound.getShort("Fire"); - this.setAirTicks(nbttagcompound.getShort("Air")); - this.onGround = nbttagcompound.getBoolean("OnGround"); - if (nbttagcompound.hasKey("Dimension")) { - // this.dimension = DimensionManager.a(nbttagcompound.getInt("Dimension")); // CraftBukkit - redundant - } - - this.invulnerable = nbttagcompound.getBoolean("Invulnerable"); - this.portalCooldown = nbttagcompound.getInt("PortalCooldown"); - if (nbttagcompound.b("UUID")) { - this.uniqueID = nbttagcompound.a("UUID"); - this.ap = this.uniqueID.toString(); - } - - if (Double.isFinite(this.locX) && Double.isFinite(this.locY) && Double.isFinite(this.locZ)) { - if (Double.isFinite((double) this.yaw) && Double.isFinite((double) this.pitch)) { - this.setPosition(this.locX, this.locY, this.locZ); - this.setYawPitch(this.yaw, this.pitch); - if (nbttagcompound.hasKeyOfType("CustomName", 8)) { - this.setCustomName(MCUtil.getBaseComponentFromNbt("CustomName", nbttagcompound)); // Paper - Catch ParseException - } - - this.setCustomNameVisible(nbttagcompound.getBoolean("CustomNameVisible")); - this.setSilent(nbttagcompound.getBoolean("Silent")); - this.setNoGravity(nbttagcompound.getBoolean("NoGravity")); - this.h(nbttagcompound.getBoolean("Glowing")); - if (nbttagcompound.hasKeyOfType("Tags", 9)) { - this.aE.clear(); - NBTTagList nbttaglist3 = nbttagcompound.getList("Tags", 8); - int i = Math.min(nbttaglist3.size(), 1024); - - for (int j = 0; j < i; ++j) { - this.aE.add(nbttaglist3.getString(j)); - } - } - - this.a(nbttagcompound); - if (this.aJ()) { - this.setPosition(this.locX, this.locY, this.locZ); - } - - } else { - throw new IllegalStateException("Entity has invalid rotation"); - } - } else { - throw new IllegalStateException("Entity has invalid position"); - } - - // 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(0); - } - } - // CraftBukkit end - - // CraftBukkit start - Reset world - if (this instanceof EntityPlayer) { - Server server = Bukkit.getServer(); - org.bukkit.World bworld = null; - - // 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) { - bworld = ((org.bukkit.craftbukkit.CraftServer) server).getServer().getWorldServer(DimensionManager.OVERWORLD).getWorld(); - } - - spawnIn(bworld == null ? null : ((CraftWorld) bworld).getHandle()); - } - this.getBukkitEntity().readBukkitValues(nbttagcompound); - // CraftBukkit end - - // Paper start - Restore the entity's origin location - NBTTagList originTag = nbttagcompound.getList("Paper.Origin", 6); - if (!originTag.isEmpty()) { - origin = new Location(world.getWorld(), originTag.getDoubleAt(0), originTag.getDoubleAt(1), originTag.getDoubleAt(2)); - } - - spawnedViaMobSpawner = nbttagcompound.getBoolean("Paper.FromMobSpawner"); // Restore entity's from mob spawner status - 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 " + spawnReasonName + " for " + this); - } - } - if (spawnReason == null) { - if (spawnedViaMobSpawner) { - spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SPAWNER; - } else if (this instanceof EntityInsentient && (this instanceof EntityAnimal || this instanceof EntityFish) && !((EntityInsentient) this).isTypeNotPersistent(0.0)) { - if (!nbttagcompound.getBoolean("PersistenceRequired")) { - spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NATURAL; - } - } - } - if (spawnReason == null) { - spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT; - } - // Paper end - - } 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 aJ() { - return true; - } - - // Paper start - java.lang.ref.WeakReference currentChunk = null; - - public void setCurrentChunk(Chunk chunk) { - this.currentChunk = chunk != null ? new java.lang.ref.WeakReference<>(chunk) : null; - } - /** - * Returns the entities current registered chunk. If the entity is not added to a chunk yet, it will return null - */ - public Chunk getCurrentChunk() { - final Chunk chunk = currentChunk != null ? currentChunk.get() : null; - return chunk != null && chunk.isLoaded() ? chunk : (isAddedToChunk() ? world.getChunkIfLoaded(getChunkX(), getChunkZ()) : null); - } - /** - * Returns the chunk at the location, using the entities local cache if avail - * Will only return null if the location specified is not loaded - */ - public Chunk getCurrentChunkAt(int x, int z) { - if (getChunkX() == x && getChunkZ() == z) { - Chunk chunk = getCurrentChunk(); - if (chunk != null) { - return chunk; - } - } - return world.getChunkIfLoaded(x, z); - } - /** - * Returns the chunk at the entities current location, using the entities local cache if avail - * Will only return null if the location specified is not loaded - */ - public Chunk getChunkAtLocation() { - return getCurrentChunkAt((int)Math.floor(locX) >> 4, (int)Math.floor(locZ) >> 4); - } - - private MinecraftKey entityKey; - private String entityKeyString; - - @Override - public MinecraftKey getMinecraftKey() { - if (entityKey == null) { - this.entityKey = EntityTypes.getName(this.getEntityType()); - this.entityKeyString = this.entityKey != null ? this.entityKey.toString() : null; - } - return entityKey; - } - - @Override - public String getMinecraftKeyString() { - getMinecraftKey(); // Try to load if it doesn't exists. see: https://github.com/PaperMC/Paper/issues/1280 - return entityKeyString; - } - @Nullable - public final String getSaveID() { - EntityTypes entitytypes = this.getEntityType(); - MinecraftKey minecraftkey = EntityTypes.getName(entitytypes); - - return entitytypes != null && entitytypes.isPersistable() ? getMinecraftKeyString() : null; - // Paper end - } - - protected abstract void a(NBTTagCompound nbttagcompound); - - protected abstract void b(NBTTagCompound nbttagcompound); - - protected NBTTagList createList(double... adouble) { return a(adouble); } // Paper - OBFHELPER - protected NBTTagList a(double... adouble) { - NBTTagList nbttaglist = new NBTTagList(); - double[] adouble1 = adouble; - int i = adouble.length; - - for (int j = 0; j < i; ++j) { - double d0 = adouble1[j]; - - nbttaglist.add(new NBTTagDouble(d0)); - } - - return nbttaglist; - } - - protected NBTTagList a(float... afloat) { - NBTTagList nbttaglist = new NBTTagList(); - float[] afloat1 = afloat; - int i = afloat.length; - - for (int j = 0; j < i; ++j) { - float f = afloat1[j]; - - nbttaglist.add(new NBTTagFloat(f)); - } - - return nbttaglist; - } - - @Nullable - public EntityItem a(IMaterial imaterial) { - return this.a(imaterial, 0); - } - - @Nullable - public EntityItem a(IMaterial imaterial, int i) { - return this.a(new ItemStack(imaterial), (float) i); - } - - @Nullable - public EntityItem a(ItemStack itemstack) { - return this.a(itemstack, 0.0F); - } - - @Nullable public final EntityItem dropItem(ItemStack itemstack, float offset) { return this.a(itemstack, offset); } // Paper - OBFHELPER - @Nullable - public EntityItem a(ItemStack itemstack, float f) { - if (itemstack.isEmpty()) { - return null; - } else if (this.world.isClientSide) { - return null; - } else { - // CraftBukkit start - Capture drops for death event - if (this instanceof EntityLiving && !((EntityLiving) this).forceDrops) { - ((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.defaultPickupDelay(); - // CraftBukkit start - EntityDropItemEvent event = new EntityDropItemEvent(this.getBukkitEntity(), (org.bukkit.entity.Item) entityitem.getBukkitEntity()); - Bukkit.getPluginManager().callEvent(event); - if (event.isCancelled()) { - return null; - } - // CraftBukkit end - this.world.addEntity(entityitem); - return entityitem; - } - } - - public boolean isAlive() { - return !this.dead; - } - - public boolean inBlock() { - if (this.noclip) { - return false; - } else { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - for (int i = 0; i < 8; ++i) { - int j = MathHelper.floor(this.locY + (double) (((float) ((i >> 0) % 2) - 0.5F) * 0.1F) + (double) this.headHeight); - int k = MathHelper.floor(this.locX + (double) (((float) ((i >> 1) % 2) - 0.5F) * this.size.width * 0.8F)); - int l = MathHelper.floor(this.locZ + (double) (((float) ((i >> 2) % 2) - 0.5F) * this.size.width * 0.8F)); - - if (blockposition_pooledblockposition.getX() != k || blockposition_pooledblockposition.getY() != j || blockposition_pooledblockposition.getZ() != l) { - blockposition_pooledblockposition.d(k, j, l); - if (this.world.getType(blockposition_pooledblockposition).m(this.world, blockposition_pooledblockposition)) { - boolean flag = true; - - return flag; - } - } - } - - return false; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - } - } - - public boolean b(EntityHuman entityhuman, EnumHand enumhand) { - return false; - } - - @Nullable - public AxisAlignedBB j(Entity entity) { - return null; - } - - public void passengerTick() { - this.setMot(Vec3D.a); - this.tick(); - if (this.isPassenger()) { - this.getVehicle().k(this); - } - } - - public void k(Entity entity) { - if (this.w(entity)) { - entity.setPosition(this.locX, this.locY + this.aP() + entity.aO(), this.locZ); - } - } - - public double aO() { - return 0.0D; - } - - public double aP() { - return (double) this.size.height * 0.75D; - } - - public boolean startRiding(Entity entity) { - return this.a(entity, false); - } - - public boolean a(Entity entity, boolean flag) { - for (Entity entity1 = entity; entity1.vehicle != null; entity1 = entity1.vehicle) { - if (entity1.vehicle == this) { - return false; - } - } - - if (!flag && (!this.n(entity) || !entity.q(this))) { - return false; - } else { - if (this.isPassenger()) { - this.stopRiding(); - } - - this.vehicle = entity; - if (!this.vehicle.addPassenger(this)) this.vehicle = null; // CraftBukkit - return true; - } - } - - protected boolean n(Entity entity) { - return this.j <= 0; - } - - protected boolean c(EntityPose entitypose) { - return this.world.getCubes(this, this.d(entitypose)); - } - - public void ejectPassengers() { - for (int i = this.passengers.size() - 1; i >= 0; --i) { - ((Entity) this.passengers.get(i)).stopRiding(); - } - - } - - // Paper start - public void stopRiding() { stopRiding(false); } - public void stopRiding(boolean suppressCancellation) { - // Paper end - if (this.vehicle != null) { - Entity entity = this.vehicle; - - this.vehicle = null; - if (!entity.removePassenger(this, suppressCancellation)) this.vehicle = entity; // CraftBukkit // Paper - } - - } - - protected boolean addPassenger(Entity entity) { // CraftBukkit - if (entity == this) throw new IllegalArgumentException("Entities cannot become a passenger of themselves"); // Paper - issue 572 - if (entity.getVehicle() != this) { - throw new IllegalStateException("Use x.startRiding(y), not y.addPassenger(x)"); - } else { - // CraftBukkit start - com.google.common.base.Preconditions.checkState(!entity.passengers.contains(this), "Circular entity riding! %s %s", this, entity); - - CraftEntity craft = (CraftEntity) entity.getBukkitEntity().getVehicle(); - Entity orig = craft == null ? null : craft.getHandle(); - if (getBukkitEntity() instanceof Vehicle && entity.getBukkitEntity() instanceof LivingEntity) { - VehicleEnterEvent event = new VehicleEnterEvent( - (Vehicle) getBukkitEntity(), - entity.getBukkitEntity() - ); - // Suppress during worldgen - if (this.valid) { - Bukkit.getPluginManager().callEvent(event); - } - CraftEntity craftn = (CraftEntity) entity.getBukkitEntity().getVehicle(); - Entity n = craftn == null ? null : craftn.getHandle(); - if (event.isCancelled() || n != orig) { - return false; - } - } - // CraftBukkit end - // Spigot start - org.spigotmc.event.entity.EntityMountEvent event = new org.spigotmc.event.entity.EntityMountEvent(entity.getBukkitEntity(), this.getBukkitEntity()); - // Suppress during worldgen - if (this.valid) { - Bukkit.getPluginManager().callEvent(event); - } - if (event.isCancelled()) { - return false; - } - // Spigot end - if (!this.world.isClientSide && entity instanceof EntityHuman && !(this.getRidingPassenger() instanceof EntityHuman)) { - this.passengers.add(0, entity); - } else { - this.passengers.add(entity); - } - - } - return true; // CraftBukkit - } - - // Paper start - protected boolean removePassenger(Entity entity) { return removePassenger(entity, false);} - protected boolean removePassenger(Entity entity, boolean suppressCancellation) { // CraftBukkit - // Paper end - if (entity.getVehicle() == this) { - throw new IllegalStateException("Use x.stopRiding(y), not y.removePassenger(x)"); - } else { - // CraftBukkit start - CraftEntity craft = (CraftEntity) entity.getBukkitEntity().getVehicle(); - Entity orig = craft == null ? null : craft.getHandle(); - if (getBukkitEntity() instanceof Vehicle && entity.getBukkitEntity() instanceof LivingEntity) { - VehicleExitEvent event = new VehicleExitEvent( - (Vehicle) getBukkitEntity(), - (LivingEntity) entity.getBukkitEntity(), !suppressCancellation // Paper - ); - Bukkit.getPluginManager().callEvent(event); - CraftEntity craftn = (CraftEntity) entity.getBukkitEntity().getVehicle(); - Entity n = craftn == null ? null : craftn.getHandle(); - if (event.isCancelled() || n != orig) { - return false; - } - } - // CraftBukkit end - // Spigot start - org.spigotmc.event.entity.EntityDismountEvent event = new org.spigotmc.event.entity.EntityDismountEvent(entity.getBukkitEntity(), this.getBukkitEntity(), !suppressCancellation); // Paper - Bukkit.getPluginManager().callEvent(event); - if (event.isCancelled()) { - return false; - } - // Spigot end - this.passengers.remove(entity); - entity.j = 60; - } - return true; // CraftBukkit - } - - protected boolean q(Entity entity) { - return this.getPassengers().size() < 1; - } - - public final float getCollisionBorderSize() { return aS(); } // Paper - OBFHELPER - public float aS() { - return 0.0F; - } - - public Vec3D getLookDirection() { - return this.c(this.pitch, this.yaw); - } - - public Vec2F aU() { - return new Vec2F(this.pitch, this.yaw); - } - - public void c(BlockPosition blockposition) { - if (this.portalCooldown > 0) { - this.portalCooldown = this.aX(); - } else { - if (!this.world.isClientSide && !blockposition.equals(this.al)) { - this.al = new BlockPosition(blockposition); - ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = ((BlockPortal) Blocks.NETHER_PORTAL).c((GeneratorAccess) this.world, this.al); - double d0 = shapedetector_shapedetectorcollection.getFacing().k() == EnumDirection.EnumAxis.X ? (double) shapedetector_shapedetectorcollection.a().getZ() : (double) shapedetector_shapedetectorcollection.a().getX(); - double d1 = Math.abs(MathHelper.c((shapedetector_shapedetectorcollection.getFacing().k() == EnumDirection.EnumAxis.X ? this.locZ : this.locX) - (double) (shapedetector_shapedetectorcollection.getFacing().e().c() == EnumDirection.EnumAxisDirection.NEGATIVE ? 1 : 0), d0, d0 - (double) shapedetector_shapedetectorcollection.d())); - double d2 = MathHelper.c(this.locY - 1.0D, (double) shapedetector_shapedetectorcollection.a().getY(), (double) (shapedetector_shapedetectorcollection.a().getY() - shapedetector_shapedetectorcollection.e())); - - this.am = new Vec3D(d1, d2, 0.0D); - this.an = shapedetector_shapedetectorcollection.getFacing(); - } - - this.ai = true; - } - } - - protected void doPortalTick() { - if (this.world instanceof WorldServer) { - int i = this.ab(); - - if (this.ai) { - if ((true || this.world.getMinecraftServer().getAllowNether()) && !this.isPassenger() && this.aj++ >= i) { // CraftBukkit - this.world.getMethodProfiler().enter("portal"); - this.aj = i; - this.portalCooldown = this.aX(); - // CraftBukkit start - if (this instanceof EntityPlayer) { - ((EntityPlayer) this).a(this.world.worldProvider.getDimensionManager().getType() == DimensionManager.NETHER ? DimensionManager.OVERWORLD : DimensionManager.NETHER, PlayerTeleportEvent.TeleportCause.NETHER_PORTAL); - } else { - this.a(this.world.worldProvider.getDimensionManager().getType() == DimensionManager.NETHER ? DimensionManager.OVERWORLD : DimensionManager.NETHER); - } - // CraftBukkit end - this.world.getMethodProfiler().exit(); - } - - this.ai = false; - } else { - if (this.aj > 0) { - this.aj -= 4; - } - - if (this.aj < 0) { - this.aj = 0; - } - } - - this.E(); - } - } - - public int aX() { - return 300; - } - - public Iterable aZ() { - return Entity.c; - } - - public Iterable getArmorItems() { - return Entity.c; - } - - public Iterable bb() { - return Iterables.concat(this.aZ(), this.getArmorItems()); - } - - public void setEquipment(EnumItemSlot enumitemslot, ItemStack itemstack) {} - - public boolean isBurning() { - boolean flag = this.world != null && this.world.isClientSide; - - return !this.isFireProof() && (this.fireTicks > 0 || flag && this.getFlag(0)); - } - - public boolean isPassenger() { - return this.getVehicle() != null; - } - - public boolean isVehicle() { - return !this.getPassengers().isEmpty(); - } - - public boolean bf() { - return true; - } - - public boolean isSneaking() { - return this.getFlag(1); - } - - public void setSneaking(boolean flag) { - this.setFlag(1, flag); - } - - public boolean isSprinting() { - return this.getFlag(3); - } - - public void setSprinting(boolean flag) { - this.setFlag(3, flag); - } - - public boolean isSwimming() { - return this.getFlag(4); - } - - public boolean bk() { - return this.getPose() == EntityPose.SWIMMING; - } - - public void setSwimming(boolean flag) { - // CraftBukkit start - if (this.isSwimming() != flag && this instanceof EntityLiving) { - if (CraftEventFactory.callToggleSwimEvent((EntityLiving) this, flag).isCancelled()) { - return; - } - } - // CraftBukkit end - this.setFlag(4, flag); - } - - public boolean bm() { - return this.glowing || this.world.isClientSide && this.getFlag(6); - } - - public void h(boolean flag) { - this.glowing = flag; - if (!this.world.isClientSide) { - this.setFlag(6, this.glowing); - } - - } - - public boolean isInvisible() { - return this.getFlag(5); - } - - @Nullable - public ScoreboardTeamBase getScoreboardTeam() { - if (!this.world.paperConfig.nonPlayerEntitiesOnScoreboards && !(this instanceof EntityHuman)) { return null; } // Paper - return this.world.getScoreboard().getPlayerTeam(this.getName()); - } - - public boolean r(Entity entity) { - return this.a(entity.getScoreboardTeam()); - } - - public boolean a(ScoreboardTeamBase scoreboardteambase) { - return this.getScoreboardTeam() != null ? this.getScoreboardTeam().isAlly(scoreboardteambase) : false; - } - - public void setInvisible(boolean flag) { - this.setFlag(5, flag); - } - - public boolean getFlag(int i) { - return ((Byte) this.datawatcher.get(Entity.W) & 1 << i) != 0; - } - - public void setFlag(int i, boolean flag) { - byte b0 = (Byte) this.datawatcher.get(Entity.W); - - if (flag) { - this.datawatcher.set(Entity.W, (byte) (b0 | 1 << i)); - } else { - this.datawatcher.set(Entity.W, (byte) (b0 & ~(1 << i))); - } - - } - - public int getMaxAirTicks() { return bp(); } // Paper - OBFHELPER - public int bp() { - return 300; - } - - public int getAirTicks() { - return (Integer) this.datawatcher.get(Entity.AIR_TICKS); - } - - public void setAirTicks(int i) { - // CraftBukkit start - EntityAirChangeEvent event = new EntityAirChangeEvent(this.getBukkitEntity(), i); - // Suppress during worldgen - if (this.valid) { - event.getEntity().getServer().getPluginManager().callEvent(event); - } - if (event.isCancelled()) { - return; - } - this.datawatcher.set(Entity.AIR_TICKS, event.getAmount()); - // CraftBukkit end - } - - public void onLightningStrike(EntityLightning entitylightning) { - ++this.fireTicks; - // CraftBukkit start - final org.bukkit.entity.Entity thisBukkitEntity = this.getBukkitEntity(); - final org.bukkit.entity.Entity stormBukkitEntity = entitylightning.getBukkitEntity(); - final PluginManager pluginManager = Bukkit.getPluginManager(); - // CraftBukkit end - - 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(), false); - } - // CraftBukkit end - } - - // CraftBukkit start - if (thisBukkitEntity instanceof Hanging) { - HangingBreakByEntityEvent hangingEvent = new HangingBreakByEntityEvent((Hanging) thisBukkitEntity, stormBukkitEntity); - pluginManager.callEvent(hangingEvent); - - if (hangingEvent.isCancelled()) { - return; - } - } - - if (this.isFireProof()) { - return; - } - CraftEventFactory.entityDamage = entitylightning; - if (!this.damageEntity(DamageSource.LIGHTNING, 5.0F)) { - CraftEventFactory.entityDamage = null; - return; - } - // CraftBukkit end - } - - public void j(boolean flag) { - Vec3D vec3d = this.getMot(); - double d0; - - if (flag) { - d0 = Math.max(-0.9D, vec3d.y - 0.03D); - } else { - d0 = Math.min(1.8D, vec3d.y + 0.1D); - } - - this.setMot(vec3d.x, d0, vec3d.z); - } - - public void k(boolean flag) { - Vec3D vec3d = this.getMot(); - double d0; - - if (flag) { - d0 = Math.max(-0.3D, vec3d.y - 0.03D); - } else { - d0 = Math.min(0.7D, vec3d.y + 0.06D); - } - - this.setMot(vec3d.x, d0, vec3d.z); - this.fallDistance = 0.0F; - } - - public void onKill(EntityLiving entityLiving) { this.b(entityLiving); } // Paper - OBFHELPER - public void b(EntityLiving entityliving) {} - - protected void i(double d0, double d1, double d2) { - BlockPosition blockposition = new BlockPosition(d0, d1, d2); - Vec3D vec3d = new Vec3D(d0 - (double) blockposition.getX(), d1 - (double) blockposition.getY(), d2 - (double) blockposition.getZ()); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - EnumDirection enumdirection = EnumDirection.UP; - double d3 = Double.MAX_VALUE; - EnumDirection[] aenumdirection = new EnumDirection[]{EnumDirection.NORTH, EnumDirection.SOUTH, EnumDirection.WEST, EnumDirection.EAST, EnumDirection.UP}; - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection1 = aenumdirection[j]; - - blockposition_mutableblockposition.g(blockposition).c(enumdirection1); - if (!this.world.getType(blockposition_mutableblockposition).o(this.world, blockposition_mutableblockposition)) { - double d4 = vec3d.a(enumdirection1.k()); - double d5 = enumdirection1.c() == EnumDirection.EnumAxisDirection.POSITIVE ? 1.0D - d4 : d4; - - if (d5 < d3) { - d3 = d5; - enumdirection = enumdirection1; - } - } - } - - float f = this.random.nextFloat() * 0.2F + 0.1F; - float f1 = (float) enumdirection.c().a(); - Vec3D vec3d1 = this.getMot().a(0.75D); - - if (enumdirection.k() == EnumDirection.EnumAxis.X) { - this.setMot((double) (f1 * f), vec3d1.y, vec3d1.z); - } else if (enumdirection.k() == EnumDirection.EnumAxis.Y) { - this.setMot(vec3d1.x, (double) (f1 * f), vec3d1.z); - } else if (enumdirection.k() == EnumDirection.EnumAxis.Z) { - this.setMot(vec3d1.x, vec3d1.y, (double) (f1 * f)); - } - - } - - public void a(IBlockData iblockdata, Vec3D vec3d) { - this.fallDistance = 0.0F; - this.B = vec3d; - } - - private static void c(IChatBaseComponent ichatbasecomponent) { - ichatbasecomponent.a((chatmodifier) -> { - chatmodifier.setChatClickable((ChatClickable) null); - }).getSiblings().forEach(Entity::c); - } - - @Override - public IChatBaseComponent getDisplayName() { - IChatBaseComponent ichatbasecomponent = this.getCustomName(); - - if (ichatbasecomponent != null) { - IChatBaseComponent ichatbasecomponent1 = ichatbasecomponent.h(); - - c(ichatbasecomponent1); - return ichatbasecomponent1; - } else { - return this.f.g(); - } - } - - public boolean s(Entity entity) { - return this == entity; - } - - public float getHeadRotation() { - return 0.0F; - } - - public void setHeadRotation(float f) {} - - public void l(float f) {} - - public boolean bs() { - return true; - } - - public boolean t(Entity entity) { - return false; - } - - public String toString() { - return String.format(Locale.ROOT, "%s[\'%s\'/%d, uuid=\'%s\', l=\'%s\', x=%.2f, y=%.2f, z=%.2f, cx=%d, cz=%d, tl=%d, v=%b, d=%b]", new Object[] { this.getClass().getSimpleName(), this.getDisplayName().getText(), Integer.valueOf(this.id), this.uniqueID.toString(), this.world == null ? "~NULL~" : this.world.getWorldData().getName(), Double.valueOf(this.locX), Double.valueOf(this.locY), Double.valueOf(this.locZ), getChunkX(), getChunkZ(), this.ticksLived, this.valid, this.dead}); // Paper - add more information - } - - public boolean isInvulnerable(DamageSource damagesource) { - return this.invulnerable && damagesource != DamageSource.OUT_OF_WORLD && !damagesource.v(); - } - - public boolean isInvulnerable() { - return this.invulnerable; - } - - public void setInvulnerable(boolean flag) { - this.invulnerable = flag; - } - - public void u(Entity entity) { - this.setPositionRotation(entity.locX, entity.locY, entity.locZ, entity.yaw, entity.pitch); - } - - public void v(Entity entity) { - NBTTagCompound nbttagcompound = entity.save(new NBTTagCompound()); - - nbttagcompound.remove("Dimension"); - this.f(nbttagcompound); - this.portalCooldown = entity.portalCooldown; - this.al = entity.al; - this.am = entity.am; - this.an = entity.an; - } - - @Nullable - public Entity a(DimensionManager dimensionmanager) { - // CraftBukkit start - return teleportTo(dimensionmanager, null); - } - - @Nullable - public Entity teleportTo(DimensionManager dimensionmanager, BlockPosition location) { - // CraftBukkit end - if (!this.world.isClientSide && !this.dead) { - this.world.getMethodProfiler().enter("changeDimension"); - MinecraftServer minecraftserver = this.getMinecraftServer(); - DimensionManager dimensionmanager1 = this.dimension; - WorldServer worldserver = minecraftserver.getWorldServer(dimensionmanager1); - WorldServer worldserver1 = minecraftserver.getWorldServer(dimensionmanager); - // CraftBukkit start - if (worldserver1 == null){ - return null; - } - - // this.dimension = dimensionmanager; - // this.decouple(); - // CraftBukkit end - this.world.getMethodProfiler().enter("reposition"); - Vec3D vec3d = this.getMot(); - float f = 0.0F; - BlockPosition blockposition = location; // CraftBukkit - - if (blockposition == null) { // CraftBukkit - if (dimensionmanager1.getType() == DimensionManager.THE_END && dimensionmanager == DimensionManager.OVERWORLD) { // CraftBukkit - blockposition = worldserver1.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, worldserver1.getSpawn()); - } else if (dimensionmanager.getType() == DimensionManager.THE_END) { // CraftBukkit - blockposition = worldserver1.getDimensionSpawn(); - } else { - double d0 = this.locX; - double d1 = this.locZ; - double d2 = 8.0D; - - if (dimensionmanager1.getType() == DimensionManager.OVERWORLD && dimensionmanager.getType() == DimensionManager.NETHER) { // CraftBukkit - d0 /= 8.0D; - d1 /= 8.0D; - } else if (dimensionmanager1.getType() == DimensionManager.NETHER && dimensionmanager.getType() == DimensionManager.OVERWORLD) { // CraftBukkit - d0 *= 8.0D; - d1 *= 8.0D; - } - - double d3 = Math.min(-2.9999872E7D, worldserver1.getWorldBorder().c() + 16.0D); - double d4 = Math.min(-2.9999872E7D, worldserver1.getWorldBorder().d() + 16.0D); - double d5 = Math.min(2.9999872E7D, worldserver1.getWorldBorder().e() - 16.0D); - double d6 = Math.min(2.9999872E7D, worldserver1.getWorldBorder().f() - 16.0D); - - d0 = MathHelper.a(d0, d3, d5); - d1 = MathHelper.a(d1, d4, d6); - Vec3D vec3d1 = this.getPortalOffset(); - - blockposition = new BlockPosition(d0, this.locY, d1); - ShapeDetector.Shape shapedetector_shape = worldserver1.getTravelAgent().a(blockposition, vec3d, this.getPortalDirection(), vec3d1.x, vec3d1.y, this instanceof EntityHuman); - - if (shapedetector_shape == null) { - return null; - } - - blockposition = new BlockPosition(shapedetector_shape.position); - vec3d = shapedetector_shape.velocity; - f = (float) shapedetector_shape.yaw; - } - } // CraftBukkit - - // CraftBukkit start - // SPIGOT-5136 - don't fire event for CraftEntity.teleport - if (location == null) { - Location enter = this.getBukkitEntity().getLocation(); - Location exit = new Location(worldserver1.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ()); - - EntityPortalEvent event = new EntityPortalEvent(this.getBukkitEntity(), enter, exit); - event.getEntity().getServer().getPluginManager().callEvent(event); - if (event.isCancelled() || event.getTo() == null || event.getTo().getWorld() == null || !this.isAlive()) { - return null; - } - - exit = event.getTo(); - worldserver1 = ((CraftWorld) exit.getWorld()).getHandle(); - blockposition = new BlockPosition(exit.getX(), exit.getY(), exit.getZ()); - } - - this.dimension = dimensionmanager; - this.decouple(); - // CraftBukkit end - - this.world.getMethodProfiler().exitEnter("reloading"); - Entity entity = this.getEntityType().a((World) worldserver1); - - if (entity != null) { - entity.v(this); - entity.setPositionRotation(blockposition, entity.yaw + f, entity.pitch); - entity.setMot(vec3d); - worldserver1.addEntityTeleport(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; - this.world.getMethodProfiler().exit(); - worldserver.resetEmptyTime(); - worldserver1.resetEmptyTime(); - this.world.getMethodProfiler().exit(); - return entity; - } else { - return null; - } - } - - public boolean canPortal() { - return true; - } - - public float a(Explosion explosion, IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, Fluid fluid, float f) { - return f; - } - - public boolean a(Explosion explosion, IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, float f) { - return true; - } - - public int bv() { - return 3; - } - - public Vec3D getPortalOffset() { - return this.am; - } - - public EnumDirection getPortalDirection() { - return this.an; - } - - public boolean isIgnoreBlockTrigger() { - return false; - } - - public void appendEntityCrashDetails(CrashReportSystemDetails crashreportsystemdetails) { - crashreportsystemdetails.a("Entity Type", () -> { - return EntityTypes.getName(this.getEntityType()) + " (" + this.getClass().getCanonicalName() + ")"; - }); - crashreportsystemdetails.a("Entity ID", (Object) this.id); - crashreportsystemdetails.a("Entity Name", () -> { - return this.getDisplayName().getString(); - }); - crashreportsystemdetails.a("Entity's Exact location", (Object) String.format(Locale.ROOT, "%.2f, %.2f, %.2f", this.locX, this.locY, this.locZ)); - crashreportsystemdetails.a("Entity's Block location", (Object) CrashReportSystemDetails.a(MathHelper.floor(this.locX), MathHelper.floor(this.locY), MathHelper.floor(this.locZ))); - Vec3D vec3d = this.getMot(); - - crashreportsystemdetails.a("Entity's Momentum", (Object) String.format(Locale.ROOT, "%.2f, %.2f, %.2f", vec3d.x, vec3d.y, vec3d.z)); - crashreportsystemdetails.a("Entity's Passengers", () -> { - return this.getPassengers().toString(); - }); - crashreportsystemdetails.a("Entity's Vehicle", () -> { - return this.getVehicle().toString(); - }); - } - - public void setUUID(UUID uuid) { a(uuid); } // Paper - OBFHELPER - public void a(UUID uuid) { - this.uniqueID = uuid; - this.ap = this.uniqueID.toString(); - } - - public UUID getUniqueID() { - return this.uniqueID; - } - - public String getUniqueIDString() { - return this.ap; - } - - public String getName() { - return this.ap; - } - - public boolean bE() { - // Paper start - return this.pushedByWater(); - } - - public boolean pushedByWater() { - // Paper end - return true; - } - - @Override - public IChatBaseComponent getScoreboardDisplayName() { - return ScoreboardTeam.a(this.getScoreboardTeam(), this.getDisplayName()).a((chatmodifier) -> { - chatmodifier.setChatHoverable(this.bK()).setInsertion(this.getUniqueIDString()); - }); - } - - public void setCustomName(@Nullable IChatBaseComponent ichatbasecomponent) { - this.datawatcher.set(Entity.az, Optional.ofNullable(ichatbasecomponent)); - } - - @Nullable - @Override - public IChatBaseComponent getCustomName() { - return (IChatBaseComponent) ((Optional) this.datawatcher.get(Entity.az)).orElse((Object) null); - } - - @Override - public boolean hasCustomName() { - return ((Optional) this.datawatcher.get(Entity.az)).isPresent(); - } - - public void setCustomNameVisible(boolean flag) { - this.datawatcher.set(Entity.aA, flag); - } - - public boolean getCustomNameVisible() { - return (Boolean) this.datawatcher.get(Entity.aA); - } - - public final void enderTeleportAndLoad(double d0, double d1, double d2) { - if (this.world instanceof WorldServer) { - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(new BlockPosition(d0, d1, d2)); - - ((WorldServer) this.world).getChunkProvider().addTicket(TicketType.POST_TELEPORT, chunkcoordintpair, 0, this.getId()); - this.world.getChunkAt(chunkcoordintpair.x, chunkcoordintpair.z); - this.enderTeleportTo(d0, d1, d2); - } - } - - public void enderTeleportTo(double d0, double d1, double d2) { - if (this.world instanceof WorldServer) { - this.aF = true; - this.setPositionRotation(d0, d1, d2, this.yaw, this.pitch); - ((WorldServer) this.world).chunkCheck(this); - } - } - - public void a(DataWatcherObject datawatcherobject) { - if (Entity.POSE.equals(datawatcherobject)) { - this.updateSize(); - } - - } - - public void updateSize() { - EntitySize entitysize = this.size; - EntityPose entitypose = this.getPose(); - EntitySize entitysize1 = this.a(entitypose); - - this.size = entitysize1; - this.headHeight = this.getHeadHeight(entitypose, entitysize1); - if (entitysize1.width < entitysize.width) { - double d0 = (double) entitysize1.width / 2.0D; - - this.a(new AxisAlignedBB(this.locX - d0, this.locY, this.locZ - d0, this.locX + d0, this.locY + (double) entitysize1.height, this.locZ + d0)); - } else { - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - - this.a(new AxisAlignedBB(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ, axisalignedbb.minX + (double) entitysize1.width, axisalignedbb.minY + (double) entitysize1.height, axisalignedbb.minZ + (double) entitysize1.width)); - if (entitysize1.width > entitysize.width && !this.justCreated && !this.world.isClientSide) { - float f = entitysize.width - entitysize1.width; - - this.move(EnumMoveType.SELF, new Vec3D((double) f, 0.0D, (double) f)); - } - - } - } - - public EnumDirection getDirection() { - return EnumDirection.fromAngle((double) this.yaw); - } - - public EnumDirection getAdjustedDirection() { - return this.getDirection(); - } - - protected ChatHoverable bK() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - MinecraftKey minecraftkey = EntityTypes.getName(this.getEntityType()); - - nbttagcompound.setString("id", this.getUniqueIDString()); - if (minecraftkey != null) { - nbttagcompound.setString("type", minecraftkey.toString()); - } - - nbttagcompound.setString("name", IChatBaseComponent.ChatSerializer.a(this.getDisplayName())); - return new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_ENTITY, new ChatComponentText(nbttagcompound.toString())); - } - - public boolean a(EntityPlayer entityplayer) { - return true; - } - - public AxisAlignedBB getBoundingBox() { - return this.boundingBox; - } - - protected AxisAlignedBB d(EntityPose entitypose) { - EntitySize entitysize = this.a(entitypose); - float f = entitysize.width / 2.0F; - Vec3D vec3d = new Vec3D(this.locX - (double) f, this.locY, this.locZ - (double) f); - Vec3D vec3d1 = new Vec3D(this.locX + (double) f, this.locY + (double) entitysize.height, this.locZ + (double) f); - - return new AxisAlignedBB(vec3d, vec3d1); - } - - public void a(AxisAlignedBB axisalignedbb) { - // CraftBukkit start - block invalid bounding boxes - double minX = axisalignedbb.minX, - minY = axisalignedbb.minY, - minZ = axisalignedbb.minZ, - maxX = axisalignedbb.maxX, - maxY = axisalignedbb.maxY, - maxZ = axisalignedbb.maxZ; - double len = axisalignedbb.maxX - axisalignedbb.minX; - if (len < 0) maxX = minX; - if (len > 64) maxX = minX + 64.0; - - len = axisalignedbb.maxY - axisalignedbb.minY; - if (len < 0) maxY = minY; - if (len > 64) maxY = minY + 64.0; - - len = axisalignedbb.maxZ - axisalignedbb.minZ; - if (len < 0) maxZ = minZ; - if (len > 64) maxZ = minZ + 64.0; - this.boundingBox = new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); - // CraftBukkit end - } - - protected float getHeadHeight(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * 0.85F; - } - - public final float getHeadHeight() { - return this.headHeight; - } - - public boolean a_(int i, ItemStack itemstack) { - return false; - } - - @Override - public void sendMessage(IChatBaseComponent ichatbasecomponent) {} - - public BlockPosition getChunkCoordinates() { - return new BlockPosition(this); - } - - public Vec3D bP() { - return new Vec3D(this.locX, this.locY, this.locZ); - } - - public World getWorld() { - return this.world; - } - - @Nullable - public MinecraftServer getMinecraftServer() { - return this.world.getMinecraftServer(); - } - - public EnumInteractionResult a(EntityHuman entityhuman, Vec3D vec3d, EnumHand enumhand) { - return EnumInteractionResult.PASS; - } - - public boolean bS() { - return false; - } - - protected void a(EntityLiving entityliving, Entity entity) { - if (entity instanceof EntityLiving) { - EnchantmentManager.a((EntityLiving) entity, (Entity) entityliving); - } - - EnchantmentManager.b(entityliving, entity); - } - - public void b(EntityPlayer entityplayer) {} - - public void c(EntityPlayer entityplayer) {} - - public float a(EnumBlockRotation enumblockrotation) { - float f = MathHelper.g(this.yaw); - - switch (enumblockrotation) { - case CLOCKWISE_180: - return f + 180.0F; - case COUNTERCLOCKWISE_90: - return f + 270.0F; - case CLOCKWISE_90: - return f + 90.0F; - default: - return f; - } - } - - public float a(EnumBlockMirror enumblockmirror) { - float f = MathHelper.g(this.yaw); - - switch (enumblockmirror) { - case LEFT_RIGHT: - return -f; - case FRONT_BACK: - return 180.0F - f; - default: - return f; - } - } - - public boolean bT() { - return false; - } - - public boolean bU() { - boolean flag = this.aF; - - this.aF = false; - return flag; - } - - @Nullable - public Entity getRidingPassenger() { - return null; - } - - public List getPassengers() { - return (List) (this.passengers.isEmpty() ? Collections.emptyList() : Lists.newArrayList(this.passengers)); - } - - public boolean w(Entity entity) { - Iterator iterator = this.getPassengers().iterator(); - - Entity entity1; - - do { - if (!iterator.hasNext()) { - return false; - } - - entity1 = (Entity) iterator.next(); - } while (!entity1.equals(entity)); - - return true; - } - - public boolean a(Class oclass) { - Iterator iterator = this.getPassengers().iterator(); - - Entity entity; - - do { - if (!iterator.hasNext()) { - return false; - } - - entity = (Entity) iterator.next(); - } while (!oclass.isAssignableFrom(entity.getClass())); - - return true; - } - - public Collection getAllPassengers() { - Set set = Sets.newHashSet(); - Iterator iterator = this.getPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - set.add(entity); - entity.a(false, set); - } - - return set; - } - - public boolean hasSinglePlayerPassenger() { - Set set = Sets.newHashSet(); - - this.a(true, set); - return set.size() == 1; - } - - private void a(boolean flag, Set set) { - Entity entity; - - for (Iterator iterator = this.getPassengers().iterator(); iterator.hasNext(); entity.a(flag, set)) { - entity = (Entity) iterator.next(); - if (!flag || EntityPlayer.class.isAssignableFrom(entity.getClass())) { - set.add(entity); - } - } - - } - - public Entity getRootVehicle() { - Entity entity; - - for (entity = this; entity.isPassenger(); entity = entity.getVehicle()) { - ; - } - - return entity; - } - - public boolean x(Entity entity) { - return this.getRootVehicle() == entity.getRootVehicle(); - } - - public boolean y(Entity entity) { - Iterator iterator = this.getPassengers().iterator(); - - Entity entity1; - - do { - if (!iterator.hasNext()) { - return false; - } - - entity1 = (Entity) iterator.next(); - if (entity1.equals(entity)) { - return true; - } - } while (!entity1.y(entity)); - - return true; - } - - public boolean ca() { - Entity entity = this.getRidingPassenger(); - - return entity instanceof EntityHuman ? ((EntityHuman) entity).dG() : !this.world.isClientSide; - } - - @Nullable - public Entity getVehicle() { - return this.vehicle; - } - - public EnumPistonReaction getPushReaction() { - return EnumPistonReaction.NORMAL; - } - - public SoundCategory getSoundCategory() { - return SoundCategory.NEUTRAL; - } - - public int getMaxFireTicks() { - return 1; - } - - public CommandListenerWrapper getCommandListener() { - return new CommandListenerWrapper(this, new Vec3D(this.locX, this.locY, this.locZ), this.aU(), this.world instanceof WorldServer ? (WorldServer) this.world : null, this.y(), this.getDisplayName().getString(), this.getScoreboardDisplayName(), this.world.getMinecraftServer(), this); - } - - protected int y() { - return 0; - } - - public boolean k(int i) { - return this.y() >= i; - } - - @Override - public boolean shouldSendSuccess() { - return this.world.getGameRules().getBoolean(GameRules.SEND_COMMAND_FEEDBACK); - } - - @Override - public boolean shouldSendFailure() { - return true; - } - - @Override - public boolean shouldBroadcastCommands() { - return true; - } - - public void a(ArgumentAnchor.Anchor argumentanchor_anchor, Vec3D vec3d) { - Vec3D vec3d1 = argumentanchor_anchor.a(this); - double d0 = vec3d.x - vec3d1.x; - double d1 = vec3d.y - vec3d1.y; - double d2 = vec3d.z - vec3d1.z; - double d3 = (double) MathHelper.sqrt(d0 * d0 + d2 * d2); - - this.pitch = MathHelper.g((float) (-(MathHelper.d(d1, d3) * 57.2957763671875D))); - this.yaw = MathHelper.g((float) (MathHelper.d(d2, d0) * 57.2957763671875D) - 90.0F); - this.setHeadRotation(this.yaw); - this.lastPitch = this.pitch; - this.lastYaw = this.yaw; - } - - public boolean b(Tag tag) { - AxisAlignedBB axisalignedbb = this.getBoundingBox().shrink(0.001D); - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.f(axisalignedbb.maxX); - int k = MathHelper.floor(axisalignedbb.minY); - int l = MathHelper.f(axisalignedbb.maxY); - int i1 = MathHelper.floor(axisalignedbb.minZ); - int j1 = MathHelper.f(axisalignedbb.maxZ); - - if (!this.world.isAreaLoaded(i, k, i1, j, l, j1)) { - return false; - } else { - double d0 = 0.0D; - boolean flag = this.bE(); - boolean flag1 = false; - Vec3D vec3d = Vec3D.a; - int k1 = 0; - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - for (int l1 = i; l1 < j; ++l1) { - for (int i2 = k; i2 < l; ++i2) { - for (int j2 = i1; j2 < j1; ++j2) { - blockposition_pooledblockposition.d(l1, i2, j2); - Fluid fluid = this.world.getFluid(blockposition_pooledblockposition); - - if (fluid.a(tag)) { - double d1 = (double) ((float) i2 + fluid.getHeight(this.world, blockposition_pooledblockposition)); - - if (d1 >= axisalignedbb.minY) { - flag1 = true; - d0 = Math.max(d1 - axisalignedbb.minY, d0); - if (flag) { - Vec3D vec3d1 = fluid.c(this.world, blockposition_pooledblockposition); - - if (d0 < 0.4D) { - vec3d1 = vec3d1.a(d0); - } - - vec3d = vec3d.e(vec3d1); - ++k1; - } - } - } - } - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - if (vec3d.f() > 0.0D) { - if (k1 > 0) { - vec3d = vec3d.a(1.0D / (double) k1); - } - - if (!(this instanceof EntityHuman)) { - vec3d = vec3d.d(); - } - - this.setMot(this.getMot().e(vec3d.a(0.014D))); - } - - this.Q = d0; - return flag1; - } - } - - public double cf() { - return this.Q; - } - - public final float getWidth() { - return this.size.width; - } - - public final float getHeight() { - return this.size.height; - } - - public abstract Packet N(); - - public EntitySize a(EntityPose entitypose) { - return this.f.k(); - } - - public Vec3D getPositionVector() { - return new Vec3D(this.locX, this.locY, this.locZ); - } - - public Vec3D getMot() { - return this.mot; - } - - public void setMot(Vec3D vec3d) { - this.mot = vec3d; - } - - public void setMot(double d0, double d1, double d2) { - this.setMot(new Vec3D(d0, d1, d2)); - } -} diff --git a/src/main/java/net/minecraft/server/EntityAgeable.java b/src/main/java/net/minecraft/server/EntityAgeable.java deleted file mode 100644 index e87754ef3..000000000 --- a/src/main/java/net/minecraft/server/EntityAgeable.java +++ /dev/null @@ -1,184 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public abstract class EntityAgeable extends EntityCreature { - - private static final DataWatcherObject bz = DataWatcher.a(EntityAgeable.class, DataWatcherRegistry.i); - protected int b; - protected int c; - protected int d; - public boolean ageLocked; // CraftBukkit - - protected EntityAgeable(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - // Spigot start - @Override - public void inactiveTick() - { - super.inactiveTick(); - if ( this.world.isClientSide || this.ageLocked ) - { // CraftBukkit - this.updateSize(); - } else - { - int i = this.getAge(); - - if ( i < 0 ) - { - ++i; - this.setAgeRaw( i ); - } else if ( i > 0 ) - { - --i; - this.setAgeRaw( i ); - } - } - } - // Spigot end - - @Nullable - public abstract EntityAgeable createChild(EntityAgeable entityageable); - - protected void a(EntityHuman entityhuman, EntityAgeable entityageable) {} - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - Item item = itemstack.getItem(); - - if (item instanceof ItemMonsterEgg && ((ItemMonsterEgg) item).a(itemstack.getTag(), this.getEntityType())) { - if (!this.world.isClientSide) { - 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()); - } - - this.a(entityhuman, entityageable); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - } - } - - return true; - } else { - return false; - } - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityAgeable.bz, false); - } - - public int getAge() { - return this.world.isClientSide ? ((Boolean) this.datawatcher.get(EntityAgeable.bz) ? -1 : 1) : this.b; - } - - public void setAge(int i, boolean flag) { - if (ageLocked) return; // Paper - GH-1459 - int j = this.getAge(); - int k = j; - - j += i * 20; - if (j > 0) { - j = 0; - } - - int l = j - k; - - this.setAgeRaw(j); - if (flag) { - this.c += l; - if (this.d == 0) { - this.d = 40; - } - } - - if (this.getAge() == 0) { - this.setAgeRaw(this.c); - } - - } - - public void setAge(int i) { - this.setAge(i, false); - } - - public void setAgeRaw(int i) { - int j = this.b; - - this.b = i; - if (j < 0 && i >= 0 || j >= 0 && i < 0) { - this.datawatcher.set(EntityAgeable.bz, i < 0); - this.l(); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("Age", this.getAge()); - nbttagcompound.setInt("ForcedAge", this.c); - nbttagcompound.setBoolean("AgeLocked", this.ageLocked); // CraftBukkit - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setAgeRaw(nbttagcompound.getInt("Age")); - this.c = nbttagcompound.getInt("ForcedAge"); - this.ageLocked = nbttagcompound.getBoolean("AgeLocked"); // CraftBukkit - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityAgeable.bz.equals(datawatcherobject)) { - this.updateSize(); - } - - super.a(datawatcherobject); - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.world.isClientSide || ageLocked) { // CraftBukkit - if (this.d > 0) { - if (this.d % 4 == 0) { - this.world.addParticle(Particles.HAPPY_VILLAGER, this.locX + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), this.locY + 0.5D + (double) (this.random.nextFloat() * this.getHeight()), this.locZ + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), 0.0D, 0.0D, 0.0D); - } - - --this.d; - } - } else if (this.isAlive()) { - int i = this.getAge(); - - if (i < 0) { - ++i; - this.setAgeRaw(i); - } else if (i > 0) { - --i; - this.setAgeRaw(i); - } - } - - } - - protected void l() {} - - @Override - public boolean isBaby() { - return this.getAge() < 0; - } -} diff --git a/src/main/java/net/minecraft/server/EntityAnimal.java b/src/main/java/net/minecraft/server/EntityAnimal.java deleted file mode 100644 index 3e627ea08..000000000 --- a/src/main/java/net/minecraft/server/EntityAnimal.java +++ /dev/null @@ -1,178 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import java.util.UUID; -import javax.annotation.Nullable; - -public abstract class EntityAnimal extends EntityAgeable { - - public int loveTicks; - public UUID breedCause; - public ItemStack breedItem; // CraftBukkit - Add breedItem variable - - protected EntityAnimal(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void mobTick() { - if (this.getAge() != 0) { - this.loveTicks = 0; - } - - super.mobTick(); - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.getAge() != 0) { - this.loveTicks = 0; - } - - if (this.loveTicks > 0) { - --this.loveTicks; - if (this.loveTicks % 10 == 0) { - double d0 = this.random.nextGaussian() * 0.02D; - double d1 = this.random.nextGaussian() * 0.02D; - double d2 = this.random.nextGaussian() * 0.02D; - - this.world.addParticle(Particles.HEART, this.locX + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), this.locY + 0.5D + (double) (this.random.nextFloat() * this.getHeight()), this.locZ + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), d0, d1, d2); - } - } - - } - - /* CraftBukkit start - // Function disabled as it has no special function anymore after - // setSitting is disabled. - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - this.loveTicks = 0; - return super.damageEntity(damagesource, f); - } - } - // CraftBukkit end */ - - @Override - public float a(BlockPosition blockposition, IWorldReader iworldreader) { - return iworldreader.getType(blockposition.down()).getBlock() == Blocks.GRASS_BLOCK ? 10.0F : iworldreader.v(blockposition) - 0.5F; - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("InLove", this.loveTicks); - if (this.breedCause != null) { - nbttagcompound.a("LoveCause", this.breedCause); - } - - } - - @Override - public double aO() { - return 0.14D; - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.loveTicks = nbttagcompound.getInt("InLove"); - this.breedCause = nbttagcompound.b("LoveCause") ? nbttagcompound.a("LoveCause") : null; - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return generatoraccess.getType(blockposition.down()).getBlock() == Blocks.GRASS_BLOCK && generatoraccess.getLightLevel(blockposition, 0) > 8; - } - - @Override - public int A() { - return 120; - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return false; - } - - @Override - protected int getExpValue(EntityHuman entityhuman) { - return 1 + this.world.random.nextInt(3); - } - - public boolean i(ItemStack itemstack) { - return itemstack.getItem() == Items.WHEAT; - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (this.i(itemstack)) { - if (this.getAge() == 0 && this.ea()) { - this.a(entityhuman, itemstack); - this.f(entityhuman); - return true; - } - - if (this.isBaby()) { - this.a(entityhuman, itemstack); - this.setAge((int) ((float) (-this.getAge() / 20) * 0.1F), true); - return true; - } - } - - return super.a(entityhuman, enumhand); - } - - protected void a(EntityHuman entityhuman, ItemStack itemstack) { - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - } - - public boolean ea() { - return this.loveTicks <= 0; - } - - public void f(@Nullable EntityHuman entityhuman) { - this.loveTicks = 600; - if (entityhuman != null) { - this.breedCause = entityhuman.getUniqueID(); - } - this.breedItem = entityhuman.inventory.getItemInHand(); // CraftBukkit - - this.world.broadcastEntityEffect(this, (byte) 18); - } - - public void setLoveTicks(int i) { - this.loveTicks = i; - } - - @Nullable - public EntityPlayer getBreedCause() { - if (this.breedCause == null) { - return null; - } else { - EntityHuman entityhuman = this.world.b(this.breedCause); - - return entityhuman instanceof EntityPlayer ? (EntityPlayer) entityhuman : null; - } - } - - public boolean isInLove() { - return this.loveTicks > 0; - } - - public void resetLove() { - this.loveTicks = 0; - } - - public boolean mate(EntityAnimal entityanimal) { - return entityanimal == this ? false : (entityanimal.getClass() != this.getClass() ? false : this.isInLove() && entityanimal.isInLove()); - } -} diff --git a/src/main/java/net/minecraft/server/EntityAreaEffectCloud.java b/src/main/java/net/minecraft/server/EntityAreaEffectCloud.java deleted file mode 100644 index fe527aba5..000000000 --- a/src/main/java/net/minecraft/server/EntityAreaEffectCloud.java +++ /dev/null @@ -1,485 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.Map.Entry; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftLivingEntity; -import org.bukkit.entity.LivingEntity; -// CraftBukkit end - -public class EntityAreaEffectCloud extends Entity { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final DataWatcherObject c = DataWatcher.a(EntityAreaEffectCloud.class, DataWatcherRegistry.c); - private static final DataWatcherObject COLOR = DataWatcher.a(EntityAreaEffectCloud.class, DataWatcherRegistry.b); - private static final DataWatcherObject e = DataWatcher.a(EntityAreaEffectCloud.class, DataWatcherRegistry.i); - private static final DataWatcherObject f = DataWatcher.a(EntityAreaEffectCloud.class, DataWatcherRegistry.j); - private PotionRegistry potionRegistry; - public List effects; - private final Map affectedEntities; - private int at; - public int waitTime; - public int reapplicationDelay; - private boolean hasColor; - public int durationOnUse; - public float radiusOnUse; - public float radiusPerTick; - private EntityLiving aA; - private UUID aB; - - public EntityAreaEffectCloud(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.potionRegistry = Potions.EMPTY; - this.effects = Lists.newArrayList(); - this.affectedEntities = Maps.newHashMap(); - this.at = 600; - this.waitTime = 20; - this.reapplicationDelay = 20; - this.noclip = true; - this.setRadius(3.0F); - } - - public EntityAreaEffectCloud(World world, double d0, double d1, double d2) { - this(EntityTypes.AREA_EFFECT_CLOUD, world); - this.setPosition(d0, d1, d2); - } - - @Override - protected void initDatawatcher() { - this.getDataWatcher().register(EntityAreaEffectCloud.COLOR, 0); - this.getDataWatcher().register(EntityAreaEffectCloud.c, 0.5F); - this.getDataWatcher().register(EntityAreaEffectCloud.e, false); - this.getDataWatcher().register(EntityAreaEffectCloud.f, Particles.ENTITY_EFFECT); - } - - public void setRadius(float f) { - if (!this.world.isClientSide) { - this.getDataWatcher().set(EntityAreaEffectCloud.c, f); - } - - } - - @Override - public void updateSize() { - double d0 = this.locX; - double d1 = this.locY; - double d2 = this.locZ; - - super.updateSize(); - this.setPosition(d0, d1, d2); - } - - public float getRadius() { - return (Float) this.getDataWatcher().get(EntityAreaEffectCloud.c); - } - - public void a(PotionRegistry potionregistry) { - this.potionRegistry = potionregistry; - if (!this.hasColor) { - this.z(); - } - - } - - private void z() { - if (this.potionRegistry == Potions.EMPTY && this.effects.isEmpty()) { - this.getDataWatcher().set(EntityAreaEffectCloud.COLOR, 0); - } else { - this.getDataWatcher().set(EntityAreaEffectCloud.COLOR, PotionUtil.a((Collection) PotionUtil.a(this.potionRegistry, (Collection) this.effects))); - } - - } - - public void addEffect(MobEffect mobeffect) { - this.effects.add(mobeffect); - if (!this.hasColor) { - this.z(); - } - - } - - // CraftBukkit start accessor methods - public void refreshEffects() { - if (!this.hasColor) { - this.getDataWatcher().set(EntityAreaEffectCloud.COLOR, PotionUtil.a((Collection) PotionUtil.a(this.potionRegistry, (Collection) this.effects))); // PAIL: rename - } - } - - public String getType() { - return ((MinecraftKey) IRegistry.POTION.getKey(this.potionRegistry)).toString(); - } - - public void setType(String string) { - a(IRegistry.POTION.get(new MinecraftKey(string))); - } - // CraftBukkit end - - public int getColor() { - return (Integer) this.getDataWatcher().get(EntityAreaEffectCloud.COLOR); - } - - public void setColor(int i) { - this.hasColor = true; - this.getDataWatcher().set(EntityAreaEffectCloud.COLOR, i); - } - - public ParticleParam getParticle() { - return (ParticleParam) this.getDataWatcher().get(EntityAreaEffectCloud.f); - } - - public void setParticle(ParticleParam particleparam) { - this.getDataWatcher().set(EntityAreaEffectCloud.f, particleparam); - } - - protected void a(boolean flag) { - this.getDataWatcher().set(EntityAreaEffectCloud.e, flag); - } - - public boolean l() { - return (Boolean) this.getDataWatcher().get(EntityAreaEffectCloud.e); - } - - public int getDuration() { - return this.at; - } - - public void setDuration(int i) { - this.at = i; - } - - // Spigot start - copied from below - @Override - public void inactiveTick() { - super.inactiveTick(); - - if (this.ticksLived >= this.waitTime + this.at) { - this.die(); - return; - } - } - // Spigot end - - @Override - public void tick() { - super.tick(); - boolean flag = this.l(); - float f = this.getRadius(); - // Paper start - fix MC-114618 - if (f < 0.0F) { - this.die(); - return; - } - // Paper end - - if (this.world.isClientSide) { - ParticleParam particleparam = this.getParticle(); - float f1; - float f2; - float f3; - int i; - int j; - int k; - - if (flag) { - if (this.random.nextBoolean()) { - for (int l = 0; l < 2; ++l) { - float f4 = this.random.nextFloat() * 6.2831855F; - - f1 = MathHelper.c(this.random.nextFloat()) * 0.2F; - f2 = MathHelper.cos(f4) * f1; - f3 = MathHelper.sin(f4) * f1; - if (particleparam.getParticle() == Particles.ENTITY_EFFECT) { - int i1 = this.random.nextBoolean() ? 16777215 : this.getColor(); - - i = i1 >> 16 & 255; - j = i1 >> 8 & 255; - k = i1 & 255; - this.world.b(particleparam, this.locX + (double) f2, this.locY, this.locZ + (double) f3, (double) ((float) i / 255.0F), (double) ((float) j / 255.0F), (double) ((float) k / 255.0F)); - } else { - this.world.b(particleparam, this.locX + (double) f2, this.locY, this.locZ + (double) f3, 0.0D, 0.0D, 0.0D); - } - } - } - } else { - float f5 = 3.1415927F * f * f; - - for (int j1 = 0; (float) j1 < f5; ++j1) { - f1 = this.random.nextFloat() * 6.2831855F; - f2 = MathHelper.c(this.random.nextFloat()) * f; - f3 = MathHelper.cos(f1) * f2; - float f6 = MathHelper.sin(f1) * f2; - - if (particleparam.getParticle() == Particles.ENTITY_EFFECT) { - i = this.getColor(); - j = i >> 16 & 255; - k = i >> 8 & 255; - int k1 = i & 255; - - this.world.b(particleparam, this.locX + (double) f3, this.locY, this.locZ + (double) f6, (double) ((float) j / 255.0F), (double) ((float) k / 255.0F), (double) ((float) k1 / 255.0F)); - } else { - this.world.b(particleparam, this.locX + (double) f3, this.locY, this.locZ + (double) f6, (0.5D - this.random.nextDouble()) * 0.15D, 0.009999999776482582D, (0.5D - this.random.nextDouble()) * 0.15D); - } - } - } - } else { - if (this.ticksLived >= this.waitTime + this.at) { - this.die(); - return; - } - - boolean flag1 = this.ticksLived < this.waitTime; - - if (flag != flag1) { - this.a(flag1); - } - - if (flag1) { - return; - } - - if (this.radiusPerTick != 0.0F) { - f += this.radiusPerTick; - if (f < 0.5F) { - this.die(); - return; - } - - this.setRadius(f); - } - - if (this.ticksLived % 5 == 0) { - Iterator iterator = this.affectedEntities.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - if (this.ticksLived >= (Integer) entry.getValue()) { - iterator.remove(); - } - } - - List list = Lists.newArrayList(); - Iterator iterator1 = this.potionRegistry.a().iterator(); - - while (iterator1.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator1.next(); - - list.add(new MobEffect(mobeffect.getMobEffect(), mobeffect.getDuration() / 4, mobeffect.getAmplifier(), mobeffect.isAmbient(), mobeffect.isShowParticles())); - } - - list.addAll(this.effects); - if (list.isEmpty()) { - this.affectedEntities.clear(); - } else { - List list1 = this.world.a(EntityLiving.class, this.getBoundingBox()); - - if (!list1.isEmpty()) { - Iterator iterator2 = list1.iterator(); - - List entities = new java.util.ArrayList(); // CraftBukkit - while (iterator2.hasNext()) { - EntityLiving entityliving = (EntityLiving) iterator2.next(); - - if (!this.affectedEntities.containsKey(entityliving) && entityliving.dt()) { - double d0 = entityliving.locX - this.locX; - double d1 = entityliving.locZ - this.locZ; - double d2 = d0 * d0 + d1 * d1; - - if (d2 <= (double) (f * f)) { - // CraftBukkit start - entities.add((LivingEntity) entityliving.getBukkitEntity()); - } - } - } - org.bukkit.event.entity.AreaEffectCloudApplyEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callAreaEffectCloudApplyEvent(this, entities); - if (!event.isCancelled()) { - for (LivingEntity entity : event.getAffectedEntities()) { - if (entity instanceof CraftLivingEntity) { - EntityLiving entityliving = ((CraftLivingEntity) entity).getHandle(); - // CraftBukkit end - this.affectedEntities.put(entityliving, this.ticksLived + this.reapplicationDelay); - Iterator iterator3 = list.iterator(); - - while (iterator3.hasNext()) { - MobEffect mobeffect1 = (MobEffect) iterator3.next(); - - if (mobeffect1.getMobEffect().isInstant()) { - mobeffect1.getMobEffect().applyInstantEffect(this, this.getSource(), entityliving, mobeffect1.getAmplifier(), 0.5D); - } else { - entityliving.addEffect(new MobEffect(mobeffect1), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.AREA_EFFECT_CLOUD); // CraftBukkit - } - } - - if (this.radiusOnUse != 0.0F) { - f += this.radiusOnUse; - if (f < 0.5F) { - this.die(); - return; - } - - this.setRadius(f); - } - - if (this.durationOnUse != 0) { - this.at += this.durationOnUse; - if (this.at <= 0) { - this.die(); - return; - } - } - } - } - } - } - } - } - } - - } - - public void setRadiusOnUse(float f) { - this.radiusOnUse = f; - } - - public void setRadiusPerTick(float f) { - this.radiusPerTick = f; - } - - public void setWaitTime(int i) { - this.waitTime = i; - } - - public void setSource(@Nullable EntityLiving entityliving) { - this.aA = entityliving; - this.aB = entityliving == null ? null : entityliving.getUniqueID(); - } - - @Nullable - public EntityLiving getSource() { - if (this.aA == null && this.aB != null && this.world instanceof WorldServer) { - Entity entity = ((WorldServer) this.world).getEntity(this.aB); - - if (entity instanceof EntityLiving) { - this.aA = (EntityLiving) entity; - } - } - - return this.aA; - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - this.ticksLived = nbttagcompound.getInt("Age"); - this.at = nbttagcompound.getInt("Duration"); - this.waitTime = nbttagcompound.getInt("WaitTime"); - this.reapplicationDelay = nbttagcompound.getInt("ReapplicationDelay"); - this.durationOnUse = nbttagcompound.getInt("DurationOnUse"); - this.radiusOnUse = nbttagcompound.getFloat("RadiusOnUse"); - this.radiusPerTick = nbttagcompound.getFloat("RadiusPerTick"); - this.setRadius(nbttagcompound.getFloat("Radius")); - this.aB = nbttagcompound.a("OwnerUUID"); - if (nbttagcompound.hasKeyOfType("Particle", 8)) { - try { - this.setParticle(ArgumentParticle.b(new StringReader(nbttagcompound.getString("Particle")))); - } catch (CommandSyntaxException commandsyntaxexception) { - EntityAreaEffectCloud.LOGGER.warn("Couldn't load custom particle {}", nbttagcompound.getString("Particle"), commandsyntaxexception); - } - } - - if (nbttagcompound.hasKeyOfType("Color", 99)) { - this.setColor(nbttagcompound.getInt("Color")); - } - - if (nbttagcompound.hasKeyOfType("Potion", 8)) { - this.a(PotionUtil.c(nbttagcompound)); - } - - if (nbttagcompound.hasKeyOfType("Effects", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("Effects", 10); - - this.effects.clear(); - - for (int i = 0; i < nbttaglist.size(); ++i) { - MobEffect mobeffect = MobEffect.b(nbttaglist.getCompound(i)); - - if (mobeffect != null) { - this.addEffect(mobeffect); - } - } - } - - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setInt("Age", this.ticksLived); - nbttagcompound.setInt("Duration", this.at); - nbttagcompound.setInt("WaitTime", this.waitTime); - nbttagcompound.setInt("ReapplicationDelay", this.reapplicationDelay); - nbttagcompound.setInt("DurationOnUse", this.durationOnUse); - nbttagcompound.setFloat("RadiusOnUse", this.radiusOnUse); - nbttagcompound.setFloat("RadiusPerTick", this.radiusPerTick); - nbttagcompound.setFloat("Radius", this.getRadius()); - nbttagcompound.setString("Particle", this.getParticle().a()); - if (this.aB != null) { - nbttagcompound.a("OwnerUUID", this.aB); - } - - if (this.hasColor) { - nbttagcompound.setInt("Color", this.getColor()); - } - - if (this.potionRegistry != Potions.EMPTY && this.potionRegistry != null) { - nbttagcompound.setString("Potion", IRegistry.POTION.getKey(this.potionRegistry).toString()); - } - - if (!this.effects.isEmpty()) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.effects.iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - nbttaglist.add(mobeffect.a(new NBTTagCompound())); - } - - nbttagcompound.set("Effects", nbttaglist); - } - - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityAreaEffectCloud.c.equals(datawatcherobject)) { - this.updateSize(); - } - - super.a(datawatcherobject); - } - - @Override - public EnumPistonReaction getPushReaction() { - return EnumPistonReaction.IGNORE; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } - - @Override - public EntitySize a(EntityPose entitypose) { - return EntitySize.b(this.getRadius() * 2.0F, 0.5F); - } -} diff --git a/src/main/java/net/minecraft/server/EntityArmorStand.java b/src/main/java/net/minecraft/server/EntityArmorStand.java deleted file mode 100644 index 02595cfcc..000000000 --- a/src/main/java/net/minecraft/server/EntityArmorStand.java +++ /dev/null @@ -1,864 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.inventory.EquipmentSlot; -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; -// CraftBukkit end - -public class EntityArmorStand extends EntityLiving { - - private static final Vector3f bu = new Vector3f(0.0F, 0.0F, 0.0F); - private static final Vector3f bv = new Vector3f(0.0F, 0.0F, 0.0F); - private static final Vector3f bw = new Vector3f(-10.0F, 0.0F, -10.0F); - private static final Vector3f bx = new Vector3f(-15.0F, 0.0F, 10.0F); - private static final Vector3f by = new Vector3f(-1.0F, 0.0F, -1.0F); - private static final Vector3f bz = new Vector3f(1.0F, 0.0F, 1.0F); - public static final DataWatcherObject b = DataWatcher.a(EntityArmorStand.class, DataWatcherRegistry.a); - public static final DataWatcherObject c = DataWatcher.a(EntityArmorStand.class, DataWatcherRegistry.k); - public static final DataWatcherObject d = DataWatcher.a(EntityArmorStand.class, DataWatcherRegistry.k); - public static final DataWatcherObject e = DataWatcher.a(EntityArmorStand.class, DataWatcherRegistry.k); - public static final DataWatcherObject f = DataWatcher.a(EntityArmorStand.class, DataWatcherRegistry.k); - public static final DataWatcherObject g = DataWatcher.a(EntityArmorStand.class, DataWatcherRegistry.k); - public static final DataWatcherObject bs = DataWatcher.a(EntityArmorStand.class, DataWatcherRegistry.k); - private static final Predicate bA = (entity) -> { - return entity instanceof EntityMinecartAbstract && ((EntityMinecartAbstract) entity).getMinecartType() == EntityMinecartAbstract.EnumMinecartType.RIDEABLE; - }; - private final NonNullList handItems; - private final NonNullList armorItems; - private boolean bD; - public long bt; - private int bE; public void setDisabledSlots(int i) { bE = i;} public int getDisabledSlots() { return bE ;} // Paper - OBFHELPER - public Vector3f headPose; - public Vector3f bodyPose; - public Vector3f leftArmPose; - public Vector3f rightArmPose; - public Vector3f leftLegPose; - public Vector3f rightLegPose; - public boolean canMove = true; // Paper - // Paper start - Allow ArmorStands not to tick - public boolean canTick = true; - public boolean canTickSetByAPI = false; - private boolean noTickPoseDirty = false; - private boolean noTickEquipmentDirty = false; - // Paper end - - public EntityArmorStand(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.handItems = NonNullList.a(2, ItemStack.a); - this.armorItems = NonNullList.a(4, ItemStack.a); - this.headPose = EntityArmorStand.bu; - this.bodyPose = EntityArmorStand.bv; - this.leftArmPose = EntityArmorStand.bw; - this.rightArmPose = EntityArmorStand.bx; - this.leftLegPose = EntityArmorStand.by; - this.rightLegPose = EntityArmorStand.bz; - if (world != null) this.canTick = world.paperConfig.armorStandTick; // Paper - armour stand ticking - this.K = 0.0F; - } - - public EntityArmorStand(World world, double d0, double d1, double d2) { - this(EntityTypes.ARMOR_STAND, world); - this.setPosition(d0, d1, d2); - } - - // CraftBukkit start - SPIGOT-3607, SPIGOT-3637 - @Override - public float getBukkitYaw() { - return this.yaw; - } - // CraftBukkit end - - @Override - public void updateSize() { - double d0 = this.locX; - double d1 = this.locY; - double d2 = this.locZ; - - super.updateSize(); - this.setPosition(d0, d1, d2); - } - - private boolean A() { - return !this.isMarker() && !this.isNoGravity(); - } - - @Override - public boolean df() { - return super.df() && this.A(); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityArmorStand.b, (byte) 0); - this.datawatcher.register(EntityArmorStand.c, EntityArmorStand.bu); - this.datawatcher.register(EntityArmorStand.d, EntityArmorStand.bv); - this.datawatcher.register(EntityArmorStand.e, EntityArmorStand.bw); - this.datawatcher.register(EntityArmorStand.f, EntityArmorStand.bx); - this.datawatcher.register(EntityArmorStand.g, EntityArmorStand.by); - this.datawatcher.register(EntityArmorStand.bs, EntityArmorStand.bz); - } - - @Override - public Iterable aZ() { - return this.handItems; - } - - @Override - public Iterable getArmorItems() { - return this.armorItems; - } - - @Override - public ItemStack getEquipment(EnumItemSlot enumitemslot) { - switch (enumitemslot.a()) { - case HAND: - return (ItemStack) this.handItems.get(enumitemslot.b()); - case ARMOR: - return (ItemStack) this.armorItems.get(enumitemslot.b()); - default: - return ItemStack.a; - } - } - - @Override - public void setSlot(EnumItemSlot enumitemslot, ItemStack itemstack) { - switch (enumitemslot.a()) { - case HAND: - this.b(itemstack); - this.handItems.set(enumitemslot.b(), itemstack); - break; - case ARMOR: - this.b(itemstack); - this.armorItems.set(enumitemslot.b(), itemstack); - } - - this.noTickEquipmentDirty = true; // Paper - Allow equipment to be updated even when tick disabled - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - EnumItemSlot enumitemslot; - - if (i == 98) { - enumitemslot = EnumItemSlot.MAINHAND; - } else if (i == 99) { - enumitemslot = EnumItemSlot.OFFHAND; - } else if (i == 100 + EnumItemSlot.HEAD.b()) { - enumitemslot = EnumItemSlot.HEAD; - } else if (i == 100 + EnumItemSlot.CHEST.b()) { - enumitemslot = EnumItemSlot.CHEST; - } else if (i == 100 + EnumItemSlot.LEGS.b()) { - enumitemslot = EnumItemSlot.LEGS; - } else { - if (i != 100 + EnumItemSlot.FEET.b()) { - return false; - } - - enumitemslot = EnumItemSlot.FEET; - } - - if (!itemstack.isEmpty() && !EntityInsentient.b(enumitemslot, itemstack) && enumitemslot != EnumItemSlot.HEAD) { - return false; - } else { - this.setSlot(enumitemslot, itemstack); - return true; - } - } - - @Override - public boolean e(ItemStack itemstack) { - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - - return this.getEquipment(enumitemslot).isEmpty() && !this.d(enumitemslot); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - NBTTagList nbttaglist = new NBTTagList(); - - NBTTagCompound nbttagcompound1; - - for (Iterator iterator = this.armorItems.iterator(); iterator.hasNext(); nbttaglist.add(nbttagcompound1)) { - ItemStack itemstack = (ItemStack) iterator.next(); - - nbttagcompound1 = new NBTTagCompound(); - if (!itemstack.isEmpty()) { - itemstack.save(nbttagcompound1); - } - } - - nbttagcompound.set("ArmorItems", nbttaglist); - NBTTagList nbttaglist1 = new NBTTagList(); - - NBTTagCompound nbttagcompound2; - - for (Iterator iterator1 = this.handItems.iterator(); iterator1.hasNext(); nbttaglist1.add(nbttagcompound2)) { - ItemStack itemstack1 = (ItemStack) iterator1.next(); - - nbttagcompound2 = new NBTTagCompound(); - if (!itemstack1.isEmpty()) { - itemstack1.save(nbttagcompound2); - } - } - - nbttagcompound.set("HandItems", nbttaglist1); - nbttagcompound.setBoolean("Invisible", this.isInvisible()); - nbttagcompound.setBoolean("Small", this.isSmall()); - nbttagcompound.setBoolean("ShowArms", this.hasArms()); - nbttagcompound.setInt("DisabledSlots", this.bE); - nbttagcompound.setBoolean("NoBasePlate", this.hasBasePlate()); - if (this.isMarker()) { - nbttagcompound.setBoolean("Marker", this.isMarker()); - } - - nbttagcompound.set("Pose", this.B()); - if (this.canTickSetByAPI) nbttagcompound.setBoolean("Paper.CanTickOverride", this.canTick); // Paper - persist no tick setting - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - NBTTagList nbttaglist; - int i; - - if (nbttagcompound.hasKeyOfType("ArmorItems", 9)) { - nbttaglist = nbttagcompound.getList("ArmorItems", 10); - - for (i = 0; i < this.armorItems.size(); ++i) { - this.armorItems.set(i, ItemStack.a(nbttaglist.getCompound(i))); - } - } - - if (nbttagcompound.hasKeyOfType("HandItems", 9)) { - nbttaglist = nbttagcompound.getList("HandItems", 10); - - for (i = 0; i < this.handItems.size(); ++i) { - this.handItems.set(i, ItemStack.a(nbttaglist.getCompound(i))); - } - } - - this.setInvisible(nbttagcompound.getBoolean("Invisible")); - this.setSmall(nbttagcompound.getBoolean("Small")); - this.setArms(nbttagcompound.getBoolean("ShowArms")); - this.bE = nbttagcompound.getInt("DisabledSlots"); - this.setBasePlate(nbttagcompound.getBoolean("NoBasePlate")); - this.setMarker(nbttagcompound.getBoolean("Marker")); - this.noclip = !this.A(); - // Paper start - persist no tick - if (nbttagcompound.hasKey("Paper.CanTickOverride")) { - this.canTick = nbttagcompound.getBoolean("Paper.CanTickOverride"); - this.canTickSetByAPI = true; - } - // Paper end - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Pose"); - - this.g(nbttagcompound1); - } - - private void g(NBTTagCompound nbttagcompound) { - NBTTagList nbttaglist = nbttagcompound.getList("Head", 5); - - this.setHeadPose(nbttaglist.isEmpty() ? EntityArmorStand.bu : new Vector3f(nbttaglist)); - NBTTagList nbttaglist1 = nbttagcompound.getList("Body", 5); - - this.setBodyPose(nbttaglist1.isEmpty() ? EntityArmorStand.bv : new Vector3f(nbttaglist1)); - NBTTagList nbttaglist2 = nbttagcompound.getList("LeftArm", 5); - - this.setLeftArmPose(nbttaglist2.isEmpty() ? EntityArmorStand.bw : new Vector3f(nbttaglist2)); - NBTTagList nbttaglist3 = nbttagcompound.getList("RightArm", 5); - - this.setRightArmPose(nbttaglist3.isEmpty() ? EntityArmorStand.bx : new Vector3f(nbttaglist3)); - NBTTagList nbttaglist4 = nbttagcompound.getList("LeftLeg", 5); - - this.setLeftLegPose(nbttaglist4.isEmpty() ? EntityArmorStand.by : new Vector3f(nbttaglist4)); - NBTTagList nbttaglist5 = nbttagcompound.getList("RightLeg", 5); - - this.setRightLegPose(nbttaglist5.isEmpty() ? EntityArmorStand.bz : new Vector3f(nbttaglist5)); - } - - private NBTTagCompound B() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - if (!EntityArmorStand.bu.equals(this.headPose)) { - nbttagcompound.set("Head", this.headPose.a()); - } - - if (!EntityArmorStand.bv.equals(this.bodyPose)) { - nbttagcompound.set("Body", this.bodyPose.a()); - } - - if (!EntityArmorStand.bw.equals(this.leftArmPose)) { - nbttagcompound.set("LeftArm", this.leftArmPose.a()); - } - - if (!EntityArmorStand.bx.equals(this.rightArmPose)) { - nbttagcompound.set("RightArm", this.rightArmPose.a()); - } - - if (!EntityArmorStand.by.equals(this.leftLegPose)) { - nbttagcompound.set("LeftLeg", this.leftLegPose.a()); - } - - if (!EntityArmorStand.bz.equals(this.rightLegPose)) { - nbttagcompound.set("RightLeg", this.rightLegPose.a()); - } - - return nbttagcompound; - } - - @Override - public boolean isCollidable() { - return false; - } - - @Override - protected void D(Entity entity) {} - - @Override - protected void collideNearby() { - List list = this.world.getEntities(this, this.getBoundingBox(), EntityArmorStand.bA); - - for (int i = 0; i < list.size(); ++i) { - Entity entity = (Entity) list.get(i); - - if (this.h(entity) <= 0.2D) { - entity.collide(this); - } - } - - } - - @Override - public EnumInteractionResult a(EntityHuman entityhuman, Vec3D vec3d, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (!this.isMarker() && itemstack.getItem() != Items.NAME_TAG) { - if (!this.world.isClientSide && !entityhuman.isSpectator()) { - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - - if (itemstack.isEmpty()) { - EnumItemSlot enumitemslot1 = this.f(vec3d); - EnumItemSlot enumitemslot2 = this.d(enumitemslot1) ? enumitemslot : enumitemslot1; - - if (this.a(enumitemslot2)) { - this.a(entityhuman, enumitemslot2, itemstack, enumhand); - } - } else { - if (this.d(enumitemslot)) { - return EnumInteractionResult.FAIL; - } - - if (enumitemslot.a() == EnumItemSlot.Function.HAND && !this.hasArms()) { - return EnumInteractionResult.FAIL; - } - - this.a(entityhuman, enumitemslot, itemstack, enumhand); - } - - return EnumInteractionResult.SUCCESS; - } else { - return EnumInteractionResult.SUCCESS; - } - } else { - return EnumInteractionResult.PASS; - } - } - - protected EnumItemSlot f(Vec3D vec3d) { - EnumItemSlot enumitemslot = EnumItemSlot.MAINHAND; - boolean flag = this.isSmall(); - double d0 = flag ? vec3d.y * 2.0D : vec3d.y; - EnumItemSlot enumitemslot1 = EnumItemSlot.FEET; - - if (d0 >= 0.1D && d0 < 0.1D + (flag ? 0.8D : 0.45D) && this.a(enumitemslot1)) { - enumitemslot = EnumItemSlot.FEET; - } else if (d0 >= 0.9D + (flag ? 0.3D : 0.0D) && d0 < 0.9D + (flag ? 1.0D : 0.7D) && this.a(EnumItemSlot.CHEST)) { - enumitemslot = EnumItemSlot.CHEST; - } else if (d0 >= 0.4D && d0 < 0.4D + (flag ? 1.0D : 0.8D) && this.a(EnumItemSlot.LEGS)) { - enumitemslot = EnumItemSlot.LEGS; - } else if (d0 >= 1.6D && this.a(EnumItemSlot.HEAD)) { - enumitemslot = EnumItemSlot.HEAD; - } else if (!this.a(EnumItemSlot.MAINHAND) && this.a(EnumItemSlot.OFFHAND)) { - enumitemslot = EnumItemSlot.OFFHAND; - } - - return enumitemslot; - } - - public boolean isSlotDisabled(EnumItemSlot slot) { return this.d(slot); } // Paper - OBFHELPER - public boolean d(EnumItemSlot enumitemslot) { - return (this.bE & 1 << enumitemslot.c()) != 0 || enumitemslot.a() == EnumItemSlot.Function.HAND && !this.hasArms(); - } - - private void a(EntityHuman entityhuman, EnumItemSlot enumitemslot, ItemStack itemstack, EnumHand enumhand) { - ItemStack itemstack1 = this.getEquipment(enumitemslot); - - if (itemstack1.isEmpty() || (this.bE & 1 << enumitemslot.c() + 8) == 0) { - if (!itemstack1.isEmpty() || (this.bE & 1 << enumitemslot.c() + 16) == 0) { - ItemStack itemstack2; - // CraftBukkit start - org.bukkit.inventory.ItemStack armorStandItem = CraftItemStack.asCraftMirror(itemstack1); - org.bukkit.inventory.ItemStack playerHeldItem = CraftItemStack.asCraftMirror(itemstack); - - Player player = (Player) entityhuman.getBukkitEntity(); - ArmorStand self = (ArmorStand) this.getBukkitEntity(); - - EquipmentSlot slot = CraftEquipmentSlot.getSlot(enumitemslot); - 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 && itemstack1.isEmpty() && !itemstack.isEmpty()) { - itemstack2 = itemstack.cloneItemStack(); - itemstack2.setCount(1); - this.setSlot(enumitemslot, itemstack2); - } else if (!itemstack.isEmpty() && itemstack.getCount() > 1) { - if (itemstack1.isEmpty()) { - itemstack2 = itemstack.cloneItemStack(); - itemstack2.setCount(1); - this.setSlot(enumitemslot, itemstack2); - itemstack.subtract(1); - } - } else { - this.setSlot(enumitemslot, itemstack); - entityhuman.a(enumhand, itemstack1); - } - } - } - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (!this.world.isClientSide && !this.dead) { - if (DamageSource.OUT_OF_WORLD.equals(damagesource)) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f)) { - return false; - } - // CraftBukkit end - this.killEntity(); // CraftBukkit - this.die() -> this.killEntity() - return false; - } else if (!this.isInvulnerable(damagesource) && (true || !this.bD) && !this.isMarker()) { // CraftBukkit - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f, true, this.bD)) { // PAIL: armorStandInvisible - return false; - } - // CraftBukkit end - if (damagesource.isExplosion()) { - this.g(damagesource); - this.killEntity(); // CraftBukkit - this.die() -> this.killEntity() - return false; - } else if (DamageSource.FIRE.equals(damagesource)) { - if (this.isBurning()) { - this.e(damagesource, 0.15F); - } else { - this.setOnFire(5); - } - - return false; - } else if (DamageSource.BURN.equals(damagesource) && this.getHealth() > 0.5F) { - this.e(damagesource, 4.0F); - return false; - } else { - boolean flag = damagesource.j() instanceof EntityArrow; - boolean flag1 = flag && ((EntityArrow) damagesource.j()).getPierceLevel() > 0; - boolean flag2 = "player".equals(damagesource.q()); - - if (!flag2 && !flag) { - return false; - } else if (damagesource.getEntity() instanceof EntityHuman && !((EntityHuman) damagesource.getEntity()).abilities.mayBuild) { - return false; - } else if (damagesource.v()) { - this.F(); - this.D(); - this.killEntity(); // CraftBukkit - this.die() -> this.killEntity() - return flag1; - } else { - long i = this.world.getTime(); - - if (i - this.bt > 5L && !flag) { - this.world.broadcastEntityEffect(this, (byte) 32); - this.bt = i; - } else { - this.f(damagesource); - this.D(); - this.die(); // CraftBukkit - SPIGOT-4890: remain as this.die() since above damagesource method will call death event - } - - return true; - } - } - } else { - return false; - } - } else { - return false; - } - } - - private void D() { - if (this.world instanceof WorldServer) { - ((WorldServer) this.world).a(new ParticleParamBlock(Particles.BLOCK, Blocks.OAK_PLANKS.getBlockData()), this.locX, this.locY + (double) this.getHeight() / 1.5D, this.locZ, 10, (double) (this.getWidth() / 4.0F), (double) (this.getHeight() / 4.0F), (double) (this.getWidth() / 4.0F), 0.05D); - } - - } - - private void e(DamageSource damagesource, float f) { - float f1 = this.getHealth(); - - f1 -= f; - if (f1 <= 0.5F) { - this.g(damagesource); - this.killEntity(); // CraftBukkit - this.die() -> this.killEntity() - } else { - this.setHealth(f1); - } - - } - - private void f(DamageSource damagesource) { - drops.add(org.bukkit.craftbukkit.inventory.CraftItemStack.asBukkitCopy(new ItemStack(Items.ARMOR_STAND))); // CraftBukkit - add to drops - this.g(damagesource); - } - - private void g(DamageSource damagesource) { - this.F(); - // this.d(damagesource); // CraftBukkit - moved down - - ItemStack itemstack; - int i; - - for (i = 0; i < this.handItems.size(); ++i) { - itemstack = (ItemStack) this.handItems.get(i); - if (!itemstack.isEmpty()) { - drops.add(org.bukkit.craftbukkit.inventory.CraftItemStack.asBukkitCopy(itemstack)); // CraftBukkit - add to drops - this.handItems.set(i, ItemStack.a); - } - } - - for (i = 0; i < this.armorItems.size(); ++i) { - itemstack = (ItemStack) this.armorItems.get(i); - if (!itemstack.isEmpty()) { - drops.add(org.bukkit.craftbukkit.inventory.CraftItemStack.asBukkitCopy(itemstack)); // CraftBukkit - add to drops - this.armorItems.set(i, ItemStack.a); - } - } - this.d(damagesource); // CraftBukkit - moved from above - - } - - private void F() { - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_ARMOR_STAND_BREAK, this.getSoundCategory(), 1.0F, 1.0F); - } - - @Override - protected float e(float f, float f1) { - this.aL = this.lastYaw; - this.aK = this.yaw; - return 0.0F; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * (this.isBaby() ? 0.5F : 0.9F); - } - - @Override - public double aO() { - return this.isMarker() ? 0.0D : 0.10000000149011612D; - } - - @Override - public void e(Vec3D vec3d) { - if (this.A()) { - super.e(vec3d); - } - } - - @Override - public void l(float f) { - this.aL = this.lastYaw = f; - this.aN = this.aM = f; - } - - @Override - public void setHeadRotation(float f) { - this.aL = this.lastYaw = f; - this.aN = this.aM = f; - } - - @Override - public void tick() { - // Paper start - if (!this.canTick) { - if (this.noTickPoseDirty) { - this.noTickPoseDirty = false; - this.updatePose(); - } - - if (this.noTickEquipmentDirty) { - this.noTickEquipmentDirty = false; - this.updateEntityEquipment(); - } - - return; - } - // Paper end - - super.tick(); - // Paper start - Split into separate method - updatePose(); - } - - public void updatePose() { - // Paper end - Vector3f vector3f = (Vector3f) this.datawatcher.get(EntityArmorStand.c); - - if (!this.headPose.equals(vector3f)) { - this.setHeadPose(vector3f); - } - - Vector3f vector3f1 = (Vector3f) this.datawatcher.get(EntityArmorStand.d); - - if (!this.bodyPose.equals(vector3f1)) { - this.setBodyPose(vector3f1); - } - - Vector3f vector3f2 = (Vector3f) this.datawatcher.get(EntityArmorStand.e); - - if (!this.leftArmPose.equals(vector3f2)) { - this.setLeftArmPose(vector3f2); - } - - Vector3f vector3f3 = (Vector3f) this.datawatcher.get(EntityArmorStand.f); - - if (!this.rightArmPose.equals(vector3f3)) { - this.setRightArmPose(vector3f3); - } - - Vector3f vector3f4 = (Vector3f) this.datawatcher.get(EntityArmorStand.g); - - if (!this.leftLegPose.equals(vector3f4)) { - this.setLeftLegPose(vector3f4); - } - - Vector3f vector3f5 = (Vector3f) this.datawatcher.get(EntityArmorStand.bs); - - if (!this.rightLegPose.equals(vector3f5)) { - this.setRightLegPose(vector3f5); - } - - } - - @Override - protected void C() { - this.setInvisible(this.bD); - } - - @Override - public void setInvisible(boolean flag) { - this.bD = flag; - super.setInvisible(flag); - } - - @Override - public boolean isBaby() { - return this.isSmall(); - } - - // CraftBukkit start - @Override - protected boolean isDropExperience() { - return true; // MC-157395, SPIGOT-5193 even baby (small) armor stands should drop - } - // CraftBukkit end - - @Override - public void killEntity() { - org.bukkit.event.entity.EntityDeathEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityDeathEvent(this, drops); // CraftBukkit - call event // Paper - make cancellable - if (event.isCancelled()) return; // Paper - make cancellable - this.die(); - } - - @Override - public boolean bS() { - return this.isInvisible(); - } - - @Override - public EnumPistonReaction getPushReaction() { - return this.isMarker() ? EnumPistonReaction.IGNORE : super.getPushReaction(); - } - - public void setSmall(boolean flag) { - this.datawatcher.set(EntityArmorStand.b, this.a((Byte) this.datawatcher.get(EntityArmorStand.b), 1, flag)); - } - - public boolean isSmall() { - return ((Byte) this.datawatcher.get(EntityArmorStand.b) & 1) != 0; - } - - public void setArms(boolean flag) { - this.datawatcher.set(EntityArmorStand.b, this.a((Byte) this.datawatcher.get(EntityArmorStand.b), 4, flag)); - } - - public boolean hasArms() { - return ((Byte) this.datawatcher.get(EntityArmorStand.b) & 4) != 0; - } - - public void setBasePlate(boolean flag) { - this.datawatcher.set(EntityArmorStand.b, this.a((Byte) this.datawatcher.get(EntityArmorStand.b), 8, flag)); - } - - public boolean hasBasePlate() { - return ((Byte) this.datawatcher.get(EntityArmorStand.b) & 8) != 0; - } - - public void setMarker(boolean flag) { - this.datawatcher.set(EntityArmorStand.b, this.a((Byte) this.datawatcher.get(EntityArmorStand.b), 16, flag)); - } - - public boolean isMarker() { - return ((Byte) this.datawatcher.get(EntityArmorStand.b) & 16) != 0; - } - - private byte a(byte b0, int i, boolean flag) { - if (flag) { - b0 = (byte) (b0 | i); - } else { - b0 = (byte) (b0 & ~i); - } - - return b0; - } - - public void setHeadPose(Vector3f vector3f) { - this.headPose = vector3f; - this.datawatcher.set(EntityArmorStand.c, vector3f); - this.noTickPoseDirty = true; // Paper - Allow updates when not ticking - } - - public void setBodyPose(Vector3f vector3f) { - this.bodyPose = vector3f; - this.datawatcher.set(EntityArmorStand.d, vector3f); - this.noTickPoseDirty = true; // Paper - Allow updates when not ticking - } - - public void setLeftArmPose(Vector3f vector3f) { - this.leftArmPose = vector3f; - this.datawatcher.set(EntityArmorStand.e, vector3f); - this.noTickPoseDirty = true; // Paper - Allow updates when not ticking - } - - public void setRightArmPose(Vector3f vector3f) { - this.rightArmPose = vector3f; - this.datawatcher.set(EntityArmorStand.f, vector3f); - this.noTickPoseDirty = true; // Paper - Allow updates when not ticking - } - - public void setLeftLegPose(Vector3f vector3f) { - this.leftLegPose = vector3f; - this.datawatcher.set(EntityArmorStand.g, vector3f); - this.noTickPoseDirty = true; // Paper - Allow updates when not ticking - } - - public void setRightLegPose(Vector3f vector3f) { - this.rightLegPose = vector3f; - this.datawatcher.set(EntityArmorStand.bs, vector3f); - this.noTickPoseDirty = true; // Paper - Allow updates when not ticking - } - - public Vector3f r() { - return this.headPose; - } - - public Vector3f s() { - return this.bodyPose; - } - - @Override - public boolean isInteractable() { - return super.isInteractable() && !this.isMarker(); - } - - @Override - public EnumMainHand getMainHand() { - return EnumMainHand.RIGHT; - } - - @Override - protected SoundEffect getSoundFall(int i) { - return SoundEffects.ENTITY_ARMOR_STAND_FALL; - } - - @Nullable - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_ARMOR_STAND_HIT; - } - - @Nullable - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_ARMOR_STAND_BREAK; - } - - @Override - public void onLightningStrike(EntityLightning entitylightning) {} - - @Override - public boolean dt() { - return false; - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityArmorStand.b.equals(datawatcherobject)) { - this.updateSize(); - this.i = !this.isMarker(); - } - - super.a(datawatcherobject); - } - - @Override - public boolean du() { - return false; - } - - @Override - public EntitySize a(EntityPose entitypose) { - float f = this.isMarker() ? 0.0F : (this.isBaby() ? 0.5F : 1.0F); - - return this.getEntityType().k().a(f); - } - - // Paper start - @Override - public void move(EnumMoveType moveType, Vec3D vec3d) { - if (this.canMove) { - super.move(moveType, vec3d); - } - } - - @Override - public boolean canBreatheUnderwater() { // Skips a bit of damage handling code, probably a micro-optimization - return true; - } - // Paper end -} diff --git a/src/main/java/net/minecraft/server/EntityArrow.java b/src/main/java/net/minecraft/server/EntityArrow.java deleted file mode 100644 index 5f3e1ccb4..000000000 --- a/src/main/java/net/minecraft/server/EntityArrow.java +++ /dev/null @@ -1,674 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import it.unimi.dsi.fastutil.ints.IntOpenHashSet; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.player.PlayerPickupArrowEvent; -// CraftBukkit end - -public abstract class EntityArrow extends Entity implements IProjectile { - - private static final DataWatcherObject ar = DataWatcher.a(EntityArrow.class, DataWatcherRegistry.a); - protected static final DataWatcherObject> b = DataWatcher.a(EntityArrow.class, DataWatcherRegistry.o); - private static final DataWatcherObject as = DataWatcher.a(EntityArrow.class, DataWatcherRegistry.a); - @Nullable - private IBlockData at; - public boolean inGround; - protected int d; - public EntityArrow.PickupStatus fromPlayer; - public int shake; - public UUID shooter; - public int despawnCounter; - private int av; - private double damage; - public int knockbackStrength; - private SoundEffect ay; - private IntOpenHashSet az; - private List aA; - - // Spigot Start - @Override - public void inactiveTick() - { - if ( this.inGround ) - { - this.despawnCounter += 1; - } - super.inactiveTick(); - } - // Spigot End - - protected EntityArrow(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.fromPlayer = EntityArrow.PickupStatus.DISALLOWED; - this.damage = 2.0D; - this.ay = this.k(); - } - - protected EntityArrow(EntityTypes entitytypes, double d0, double d1, double d2, World world) { - this(entitytypes, world); - this.setPosition(d0, d1, d2); - } - - protected EntityArrow(EntityTypes entitytypes, EntityLiving entityliving, World world) { - this(entitytypes, entityliving.locX, entityliving.locY + (double) entityliving.getHeadHeight() - 0.10000000149011612D, entityliving.locZ, world); - this.setShooter(entityliving); - if (entityliving instanceof EntityHuman) { - this.fromPlayer = EntityArrow.PickupStatus.ALLOWED; - } - - } - - public void a(SoundEffect soundeffect) { - this.ay = soundeffect; - } - - @Override - protected void initDatawatcher() { - this.datawatcher.register(EntityArrow.ar, (byte) 0); - this.datawatcher.register(EntityArrow.b, Optional.empty()); - this.datawatcher.register(EntityArrow.as, (byte) 0); - } - - public void a(Entity entity, float f, float f1, float f2, float f3, float f4) { - float f5 = -MathHelper.sin(f1 * 0.017453292F) * MathHelper.cos(f * 0.017453292F); - float f6 = -MathHelper.sin(f * 0.017453292F); - float f7 = MathHelper.cos(f1 * 0.017453292F) * MathHelper.cos(f * 0.017453292F); - - this.shoot((double) f5, (double) f6, (double) f7, f3, f4); - if (!entity.world.paperConfig.disableRelativeProjectileVelocity) this.setMot(this.getMot().add(entity.getMot().x, entity.onGround ? 0.0D : entity.getMot().y, entity.getMot().z)); // Paper - allow disabling relative velocity - } - - @Override - public void shoot(double d0, double d1, double d2, float f, float f1) { - Vec3D vec3d = (new Vec3D(d0, d1, d2)).d().add(this.random.nextGaussian() * 0.007499999832361937D * (double) f1, this.random.nextGaussian() * 0.007499999832361937D * (double) f1, this.random.nextGaussian() * 0.007499999832361937D * (double) f1).a((double) f); - - this.setMot(vec3d); - float f2 = MathHelper.sqrt(b(vec3d)); - - this.yaw = (float) (MathHelper.d(vec3d.x, vec3d.z) * 57.2957763671875D); - this.pitch = (float) (MathHelper.d(vec3d.y, (double) f2) * 57.2957763671875D); - this.lastYaw = this.yaw; - this.lastPitch = this.pitch; - this.despawnCounter = 0; - } - - @Override - public void tick() { - super.tick(); - boolean flag = this.v(); - Vec3D vec3d = this.getMot(); - - if (this.lastPitch == 0.0F && this.lastYaw == 0.0F) { - float f = MathHelper.sqrt(b(vec3d)); - - this.yaw = (float) (MathHelper.d(vec3d.x, vec3d.z) * 57.2957763671875D); - this.pitch = (float) (MathHelper.d(vec3d.y, (double) f) * 57.2957763671875D); - this.lastYaw = this.yaw; - this.lastPitch = this.pitch; - } - - BlockPosition blockposition = new BlockPosition(this.locX, this.locY, this.locZ); - IBlockData iblockdata = this.world.getType(blockposition); - - if (!iblockdata.isAir() && !flag) { - VoxelShape voxelshape = iblockdata.getCollisionShape(this.world, blockposition); - - if (!voxelshape.isEmpty()) { - Iterator iterator = voxelshape.d().iterator(); - - while (iterator.hasNext()) { - AxisAlignedBB axisalignedbb = (AxisAlignedBB) iterator.next(); - - if (axisalignedbb.a(blockposition).c(new Vec3D(this.locX, this.locY, this.locZ))) { - this.inGround = true; - break; - } - } - } - } - - if (this.shake > 0) { - --this.shake; - } - - if (this.isInWaterOrRain()) { - this.extinguish(); - } - - if (this.inGround && !flag) { - if (this.at != iblockdata && this.world.c(this.getBoundingBox().g(0.06D))) { - this.inGround = false; - this.setMot(vec3d.d((double) (this.random.nextFloat() * 0.2F), (double) (this.random.nextFloat() * 0.2F), (double) (this.random.nextFloat() * 0.2F))); - this.despawnCounter = 0; - this.av = 0; - } else if (!this.world.isClientSide) { - this.i(); - } - - ++this.d; - } else { - this.d = 0; - ++this.av; - Vec3D vec3d1 = new Vec3D(this.locX, this.locY, this.locZ); - Vec3D vec3d2 = vec3d1.e(vec3d); - Object object = this.world.rayTrace(new RayTrace(vec3d1, vec3d2, RayTrace.BlockCollisionOption.COLLIDER, RayTrace.FluidCollisionOption.NONE, this)); - - if (((MovingObjectPosition) object).getType() != MovingObjectPosition.EnumMovingObjectType.MISS) { - vec3d2 = ((MovingObjectPosition) object).getPos(); - } - - while (!this.dead) { - MovingObjectPositionEntity movingobjectpositionentity = this.a(vec3d1, vec3d2); - - if (movingobjectpositionentity != null) { - object = movingobjectpositionentity; - } - - if (object != null && ((MovingObjectPosition) object).getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - Entity entity = ((MovingObjectPositionEntity) object).getEntity(); - Entity entity1 = this.getShooter(); - - if (entity instanceof EntityHuman && entity1 instanceof EntityHuman && !((EntityHuman) entity1).a((EntityHuman) entity)) { - object = null; - movingobjectpositionentity = null; - } - } - - // Paper start - Call ProjectileCollideEvent - // TODO: flag - noclip - call cancelled? - if (object instanceof MovingObjectPositionEntity) { - com.destroystokyo.paper.event.entity.ProjectileCollideEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileCollideEvent(this, (MovingObjectPositionEntity)object); - if (event.isCancelled()) { - object = null; - movingobjectpositionentity = null; - } - } - // Paper end - - if (object != null && !flag) { - this.a((MovingObjectPosition) object); - this.impulse = true; - } - - if (movingobjectpositionentity == null || this.getPierceLevel() <= 0) { - break; - } - - object = null; - } - - vec3d = this.getMot(); - double d0 = vec3d.x; - double d1 = vec3d.y; - double d2 = vec3d.z; - - if (this.isCritical()) { - for (int i = 0; i < 4; ++i) { - this.world.addParticle(Particles.CRIT, this.locX + d0 * (double) i / 4.0D, this.locY + d1 * (double) i / 4.0D, this.locZ + d2 * (double) i / 4.0D, -d0, -d1 + 0.2D, -d2); - } - } - - this.locX += d0; - this.locY += d1; - this.locZ += d2; - float f1 = MathHelper.sqrt(b(vec3d)); - - if (flag) { - this.yaw = (float) (MathHelper.d(-d0, -d2) * 57.2957763671875D); - } else { - this.yaw = (float) (MathHelper.d(d0, d2) * 57.2957763671875D); - } - - for (this.pitch = (float) (MathHelper.d(d1, (double) f1) * 57.2957763671875D); 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 = MathHelper.g(0.2F, this.lastPitch, this.pitch); - this.yaw = MathHelper.g(0.2F, this.lastYaw, this.yaw); - float f2 = 0.99F; - float f3 = 0.05F; - - if (this.isInWater()) { - for (int j = 0; j < 4; ++j) { - float f4 = 0.25F; - - this.world.addParticle(Particles.BUBBLE, this.locX - d0 * 0.25D, this.locY - d1 * 0.25D, this.locZ - d2 * 0.25D, d0, d1, d2); - } - - f2 = this.u(); - } - - this.setMot(vec3d.a((double) f2)); - if (!this.isNoGravity() && !flag) { - Vec3D vec3d3 = this.getMot(); - - this.setMot(vec3d3.x, vec3d3.y - 0.05000000074505806D, vec3d3.z); - } - - this.setPosition(this.locX, this.locY, this.locZ); - this.checkBlockCollisions(); - } - } - - protected void i() { - ++this.despawnCounter; - if (this.despawnCounter >= (fromPlayer == PickupStatus.CREATIVE_ONLY ? world.paperConfig.creativeArrowDespawnRate : (fromPlayer == PickupStatus.DISALLOWED ? world.paperConfig.nonPlayerArrowDespawnRate : world.spigotConfig.arrowDespawnRate))) { // Spigot // Paper - this.die(); - } - - } - - protected void a(MovingObjectPosition movingobjectposition) { - org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileHitEvent(this, movingobjectposition); // CraftBukkit - Call event - MovingObjectPosition.EnumMovingObjectType movingobjectposition_enummovingobjecttype = movingobjectposition.getType(); - - if (movingobjectposition_enummovingobjecttype == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - this.a((MovingObjectPositionEntity) movingobjectposition); - } else if (movingobjectposition_enummovingobjecttype == MovingObjectPosition.EnumMovingObjectType.BLOCK) { - MovingObjectPositionBlock movingobjectpositionblock = (MovingObjectPositionBlock) movingobjectposition; - IBlockData iblockdata = this.world.getType(movingobjectpositionblock.getBlockPosition()); - - this.at = iblockdata; - Vec3D vec3d = movingobjectpositionblock.getPos().a(this.locX, this.locY, this.locZ); - - this.setMot(vec3d); - Vec3D vec3d1 = vec3d.d().a(0.05000000074505806D); - - this.locX -= vec3d1.x; - this.locY -= vec3d1.y; - this.locZ -= vec3d1.z; - this.a(this.getSoundHit(), 1.0F, 1.2F / (this.random.nextFloat() * 0.2F + 0.9F)); - this.inGround = true; - this.shake = 7; - this.setCritical(false); - this.setPierceLevel((byte) 0); - this.a(SoundEffects.ENTITY_ARROW_HIT); - this.o(false); - this.w(); - iblockdata.a(this.world, iblockdata, movingobjectpositionblock, this); - } - - } - - private void w() { - if (this.aA != null) { - this.aA.clear(); - } - - if (this.az != null) { - this.az.clear(); - } - - } - - protected void a(MovingObjectPositionEntity movingobjectpositionentity) { - Entity entity = movingobjectpositionentity.getEntity(); - float f = (float) this.getMot().f(); - int i = MathHelper.f(Math.max((double) f * this.damage, 0.0D)); - - if (this.getPierceLevel() > 0) { - if (this.az == null) { - this.az = new IntOpenHashSet(5); - } - - if (this.aA == null) { - this.aA = Lists.newArrayListWithCapacity(5); - } - - if (this.az.size() >= this.getPierceLevel() + 1) { - this.die(); - return; - } - - this.az.add(entity.getId()); - } - - if (this.isCritical()) { - i += this.random.nextInt(i / 2 + 2); - } - - Entity entity1 = this.getShooter(); - DamageSource damagesource; - - if (entity1 == null) { - damagesource = DamageSource.arrow(this, this); - } else { - damagesource = DamageSource.arrow(this, entity1); - if (entity1 instanceof EntityLiving) { - ((EntityLiving) entity1).z(entity); - } - } - - int j = entity.ad(); - - if (this.isBurning() && !(entity instanceof EntityEnderman)) { - // CraftBukkit start - EntityCombustByEntityEvent combustEvent = new EntityCombustByEntityEvent(this.getBukkitEntity(), entity.getBukkitEntity(), 5); - org.bukkit.Bukkit.getPluginManager().callEvent(combustEvent); - if (!combustEvent.isCancelled()) { - entity.setOnFire(combustEvent.getDuration(), false); - } - // CraftBukkit end - } - - if (entity.damageEntity(damagesource, (float) i)) { - if (entity instanceof EntityLiving) { - EntityLiving entityliving = (EntityLiving) entity; - - if (!this.world.isClientSide && this.getPierceLevel() <= 0) { - entityliving.setArrowCount(entityliving.getArrowCount() + 1); - } - - if (this.knockbackStrength > 0) { - Vec3D vec3d = this.getMot().d(1.0D, 0.0D, 1.0D).d().a((double) this.knockbackStrength * 0.6D); - - if (vec3d.g() > 0.0D) { - entityliving.f(vec3d.x, 0.1D, vec3d.z); - } - } - - if (!this.world.isClientSide && entity1 instanceof EntityLiving) { - EnchantmentManager.a(entityliving, entity1); - EnchantmentManager.b((EntityLiving) entity1, (Entity) entityliving); - } - - this.a(entityliving); - if (entity1 != null && entityliving != entity1 && entityliving instanceof EntityHuman && entity1 instanceof EntityPlayer) { - ((EntityPlayer) entity1).playerConnection.sendPacket(new PacketPlayOutGameStateChange(6, 0.0F)); - } - - if (!entity.isAlive() && this.aA != null) { - this.aA.add(entityliving); - } - - if (!this.world.isClientSide && entity1 instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entity1; - - if (this.aA != null && this.r()) { - CriterionTriggers.G.a(entityplayer, this.aA, this.aA.size()); - } else if (!entity.isAlive() && this.r()) { - CriterionTriggers.G.a(entityplayer, Arrays.asList(entity), 0); - } - } - } - - this.a(this.ay, 1.0F, 1.2F / (this.random.nextFloat() * 0.2F + 0.9F)); - if (this.getPierceLevel() <= 0 && !(entity instanceof EntityEnderman)) { - this.die(); - } - } else { - entity.g(j); - this.setMot(this.getMot().a(-0.1D)); - this.yaw += 180.0F; - this.lastYaw += 180.0F; - this.av = 0; - if (!this.world.isClientSide && this.getMot().g() < 1.0E-7D) { - if (this.fromPlayer == EntityArrow.PickupStatus.ALLOWED) { - this.a(this.getItemStack(), 0.1F); - } - - this.die(); - } - } - - } - - protected SoundEffect k() { - return SoundEffects.ENTITY_ARROW_HIT; - } - - protected final SoundEffect getSoundHit() { - return this.ay; - } - - protected void a(EntityLiving entityliving) {} - - @Nullable - protected MovingObjectPositionEntity a(Vec3D vec3d, Vec3D vec3d1) { - return ProjectileHelper.a(this.world, this, vec3d, vec3d1, this.getBoundingBox().a(this.getMot()).g(1.0D), (entity) -> { - return !entity.isSpectator() && entity.isAlive() && entity.isInteractable() && (entity != this.getShooter() || this.av >= 5) && (this.az == null || !this.az.contains(entity.getId())); - }); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("life", (short) this.despawnCounter); - if (this.at != null) { - nbttagcompound.set("inBlockState", GameProfileSerializer.a(this.at)); - } - - nbttagcompound.setByte("shake", (byte) this.shake); - nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); - nbttagcompound.setByte("pickup", (byte) this.fromPlayer.ordinal()); - nbttagcompound.setDouble("damage", this.damage); - nbttagcompound.setBoolean("crit", this.isCritical()); - nbttagcompound.setByte("PierceLevel", this.getPierceLevel()); - if (this.shooter != null) { - nbttagcompound.a("OwnerUUID", this.shooter); - } - - nbttagcompound.setString("SoundEvent", IRegistry.SOUND_EVENT.getKey(this.ay).toString()); - nbttagcompound.setBoolean("ShotFromCrossbow", this.r()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.despawnCounter = nbttagcompound.getShort("life"); - if (nbttagcompound.hasKeyOfType("inBlockState", 10)) { - this.at = GameProfileSerializer.d(nbttagcompound.getCompound("inBlockState")); - } - - 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 = EntityArrow.PickupStatus.a(nbttagcompound.getByte("pickup")); - } else if (nbttagcompound.hasKeyOfType("player", 99)) { - this.fromPlayer = nbttagcompound.getBoolean("player") ? EntityArrow.PickupStatus.ALLOWED : EntityArrow.PickupStatus.DISALLOWED; - } - - this.setCritical(nbttagcompound.getBoolean("crit")); - this.setPierceLevel(nbttagcompound.getByte("PierceLevel")); - if (nbttagcompound.b("OwnerUUID")) { - this.shooter = nbttagcompound.a("OwnerUUID"); - } - - if (nbttagcompound.hasKeyOfType("SoundEvent", 8)) { - this.ay = (SoundEffect) IRegistry.SOUND_EVENT.getOptional(new MinecraftKey(nbttagcompound.getString("SoundEvent"))).orElse(this.k()); - } - - this.o(nbttagcompound.getBoolean("ShotFromCrossbow")); - } - - public void setShooter(@Nullable Entity entity) { - this.shooter = entity == null ? null : entity.getUniqueID(); - this.projectileSource = entity == null ? null : (LivingEntity) entity.getBukkitEntity(); // CraftBukkit - if (entity instanceof EntityHuman) { - this.fromPlayer = ((EntityHuman) entity).abilities.canInstantlyBuild ? EntityArrow.PickupStatus.CREATIVE_ONLY : EntityArrow.PickupStatus.ALLOWED; - } - - } - - @Nullable - public Entity getShooter() { - return this.shooter != null && this.world instanceof WorldServer ? ((WorldServer) this.world).getEntity(this.shooter) : null; - } - - @Override - public void pickup(EntityHuman entityhuman) { - if (!this.world.isClientSide && (this.inGround || this.v()) && this.shake <= 0) { - // CraftBukkit start - ItemStack itemstack = this.getItemStack(); - if (this.fromPlayer == PickupStatus.ALLOWED && !itemstack.isEmpty() && entityhuman.inventory.canHold(itemstack) > 0) { - EntityItem item = new EntityItem(this.world, this.locX, this.locY, this.locZ, itemstack); - PlayerPickupArrowEvent event = new PlayerPickupArrowEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), new org.bukkit.craftbukkit.entity.CraftItem(this.world.getServer(), this, item), (org.bukkit.entity.AbstractArrow) this.getBukkitEntity()); - // event.setCancelled(!entityhuman.canPickUpLoot); TODO - this.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - itemstack = item.getItemStack(); - } - boolean flag = this.fromPlayer == EntityArrow.PickupStatus.ALLOWED || this.fromPlayer == EntityArrow.PickupStatus.CREATIVE_ONLY && entityhuman.abilities.canInstantlyBuild || this.v() && this.getShooter().getUniqueID() == entityhuman.getUniqueID(); - - if (this.fromPlayer == EntityArrow.PickupStatus.ALLOWED && !entityhuman.inventory.pickup(itemstack)) { - // CraftBukkit end - flag = false; - } - - if (flag) { - entityhuman.receive(this, 1); - this.die(); - } - - } - } - - protected abstract ItemStack getItemStack(); - - @Override - protected boolean playStepSound() { - return false; - } - - public void setDamage(double d0) { - this.damage = d0; - } - - public double getDamage() { - return this.damage; - } - - public void setKnockbackStrength(int i) { - this.knockbackStrength = i; - } - - @Override - public boolean bs() { - return false; - } - - @Override - protected float getHeadHeight(EntityPose entitypose, EntitySize entitysize) { - return 0.0F; - } - - public void setCritical(boolean flag) { - this.a(1, flag); - } - - public void setPierceLevel(byte b0) { - this.datawatcher.set(EntityArrow.as, b0); - } - - private void a(int i, boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityArrow.ar); - - if (flag) { - this.datawatcher.set(EntityArrow.ar, (byte) (b0 | i)); - } else { - this.datawatcher.set(EntityArrow.ar, (byte) (b0 & ~i)); - } - - } - - public boolean isCritical() { - byte b0 = (Byte) this.datawatcher.get(EntityArrow.ar); - - return (b0 & 1) != 0; - } - - public boolean r() { - byte b0 = (Byte) this.datawatcher.get(EntityArrow.ar); - - return (b0 & 4) != 0; - } - - public byte getPierceLevel() { - return (Byte) this.datawatcher.get(EntityArrow.as); - } - - public void a(EntityLiving entityliving, float f) { - int i = EnchantmentManager.a(Enchantments.ARROW_DAMAGE, entityliving); - int j = EnchantmentManager.a(Enchantments.ARROW_KNOCKBACK, entityliving); - - this.setDamage((double) (f * 2.0F) + this.random.nextGaussian() * 0.25D + (double) ((float) this.world.getDifficulty().a() * 0.11F)); - if (i > 0) { - this.setDamage(this.getDamage() + (double) i * 0.5D + 0.5D); - } - - if (j > 0) { - this.setKnockbackStrength(j); - } - - if (EnchantmentManager.a(Enchantments.ARROW_FIRE, entityliving) > 0) { - this.setOnFire(100); - } - - } - - protected float u() { - return 0.6F; - } - - public void n(boolean flag) { - this.noclip = flag; - this.a(2, flag); - } - - public boolean v() { - return !this.world.isClientSide ? this.noclip : ((Byte) this.datawatcher.get(EntityArrow.ar) & 2) != 0; - } - - public void o(boolean flag) { - this.a(4, flag); - } - - @Override - public Packet N() { - Entity entity = this.getShooter(); - - return new PacketPlayOutSpawnEntity(this, entity == null ? 0 : entity.getId()); - } - - public static enum PickupStatus { - - DISALLOWED, ALLOWED, CREATIVE_ONLY; - - private PickupStatus() {} - - public static EntityArrow.PickupStatus a(int i) { - if (i < 0 || i > values().length) { - i = 0; - } - - return values()[i]; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityBat.java b/src/main/java/net/minecraft/server/EntityBat.java deleted file mode 100644 index 72474211b..000000000 --- a/src/main/java/net/minecraft/server/EntityBat.java +++ /dev/null @@ -1,230 +0,0 @@ -package net.minecraft.server; - -import java.time.LocalDate; -import java.time.temporal.ChronoField; -import java.util.Random; -import javax.annotation.Nullable; -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class EntityBat extends EntityAmbient { - - private static final DataWatcherObject b = DataWatcher.a(EntityBat.class, DataWatcherRegistry.a); - private static final PathfinderTargetCondition c = (new PathfinderTargetCondition()).a(4.0D).b(); - private BlockPosition d; - - public EntityBat(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.setAsleep(true); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityBat.b, (byte) 0); - } - - @Override - protected float getSoundVolume() { - return 0.1F; - } - - @Override - protected float cV() { - return super.cV() * 0.95F; - } - - @Nullable - @Override - public SoundEffect getSoundAmbient() { - return this.isAsleep() && this.random.nextInt(4) != 0 ? null : SoundEffects.ENTITY_BAT_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_BAT_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_BAT_DEATH; - } - - @Override - public boolean isCollidable() { - return false; - } - - @Override - protected void D(Entity entity) {} - - @Override - protected void collideNearby() {} - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(6.0D); - } - - public boolean isAsleep() { - return ((Byte) this.datawatcher.get(EntityBat.b) & 1) != 0; - } - - public void setAsleep(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityBat.b); - - if (flag) { - this.datawatcher.set(EntityBat.b, (byte) (b0 | 1)); - } else { - this.datawatcher.set(EntityBat.b, (byte) (b0 & -2)); - } - - } - - @Override - public void tick() { - super.tick(); - if (this.isAsleep()) { - this.setMot(Vec3D.a); - this.locY = (double) MathHelper.floor(this.locY) + 1.0D - (double) this.getHeight(); - } else { - this.setMot(this.getMot().d(1.0D, 0.6D, 1.0D)); - } - - } - - @Override - protected void mobTick() { - super.mobTick(); - BlockPosition blockposition = new BlockPosition(this); - BlockPosition blockposition1 = blockposition.up(); - - if (this.isAsleep()) { - if (this.world.getType(blockposition1).isOccluding(this.world, blockposition)) { - if (this.random.nextInt(200) == 0) { - this.aM = (float) this.random.nextInt(360); - } - - if (this.world.a(EntityBat.c, (EntityLiving) this) != null) { - // CraftBukkit Start - Call BatToggleSleepEvent - if (CraftEventFactory.handleBatToggleSleepEvent(this, true)) { - this.setAsleep(false); - this.world.a((EntityHuman) null, 1025, blockposition, 0); - } - // CraftBukkit End - } - } else { - // CraftBukkit Start - Call BatToggleSleepEvent - if (CraftEventFactory.handleBatToggleSleepEvent(this, true)) { - this.setAsleep(false); - this.world.a((EntityHuman) null, 1025, blockposition, 0); - } - // CraftBukkit End - Call BatToggleSleepEvent - } - } else { - if (this.d != null && (!this.world.isEmpty(this.d) || this.d.getY() < 1)) { - this.d = null; - } - - if (this.d == null || this.random.nextInt(30) == 0 || this.d.a((IPosition) this.getPositionVector(), 2.0D)) { - this.d = new BlockPosition(this.locX + (double) this.random.nextInt(7) - (double) this.random.nextInt(7), this.locY + (double) this.random.nextInt(6) - 2.0D, this.locZ + (double) this.random.nextInt(7) - (double) this.random.nextInt(7)); - } - - double d0 = (double) this.d.getX() + 0.5D - this.locX; - double d1 = (double) this.d.getY() + 0.1D - this.locY; - double d2 = (double) this.d.getZ() + 0.5D - this.locZ; - Vec3D vec3d = this.getMot(); - Vec3D vec3d1 = vec3d.add((Math.signum(d0) * 0.5D - vec3d.x) * 0.10000000149011612D, (Math.signum(d1) * 0.699999988079071D - vec3d.y) * 0.10000000149011612D, (Math.signum(d2) * 0.5D - vec3d.z) * 0.10000000149011612D); - - this.setMot(vec3d1); - float f = (float) (MathHelper.d(vec3d1.z, vec3d1.x) * 57.2957763671875D) - 90.0F; - float f1 = MathHelper.g(f - this.yaw); - - this.bd = 0.5F; - this.yaw += f1; - if (this.random.nextInt(100) == 0 && this.world.getType(blockposition1).isOccluding(this.world, blockposition1)) { - // CraftBukkit Start - Call BatToggleSleepEvent - if (CraftEventFactory.handleBatToggleSleepEvent(this, false)) { - this.setAsleep(true); - } - // CraftBukkit End - } - } - - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - public void b(float f, float f1) {} - - @Override - protected void a(double d0, boolean flag, IBlockData iblockdata, BlockPosition blockposition) {} - - @Override - public boolean isIgnoreBlockTrigger() { - return true; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - if (!this.world.isClientSide && this.isAsleep()) { - // CraftBukkit Start - Call BatToggleSleepEvent - if (CraftEventFactory.handleBatToggleSleepEvent(this, true)) { - this.setAsleep(false); - } - // CraftBukkit End - Call BatToggleSleepEvent - } - - return super.damageEntity(damagesource, f); - } - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.datawatcher.set(EntityBat.b, nbttagcompound.getByte("BatFlags")); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setByte("BatFlags", (Byte) this.datawatcher.get(EntityBat.b)); - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - if (blockposition.getY() >= generatoraccess.getSeaLevel()) { - return false; - } else { - int i = generatoraccess.getLightLevel(blockposition); - byte b0 = 4; - - if (dT()) { - b0 = 7; - } else if (random.nextBoolean()) { - return false; - } - - return i > random.nextInt(b0) ? false : a(entitytypes, generatoraccess, enummobspawn, blockposition, random); - } - } - - private static boolean dT() { - LocalDate localdate = LocalDate.now(); - int i = localdate.get(ChronoField.DAY_OF_MONTH); - int j = localdate.get(ChronoField.MONTH_OF_YEAR); - - return j == 10 && i >= 20 || j == 11 && i <= 3; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height / 2.0F; - } -} diff --git a/src/main/java/net/minecraft/server/EntityBoat.java b/src/main/java/net/minecraft/server/EntityBoat.java deleted file mode 100644 index 32b7f7805..000000000 --- a/src/main/java/net/minecraft/server/EntityBoat.java +++ /dev/null @@ -1,959 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import javax.annotation.Nullable; - -// CraftBukkit start -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.event.vehicle.VehicleMoveEvent; -// CraftBukkit end - -public class EntityBoat extends Entity { - - private static final DataWatcherObject b = DataWatcher.a(EntityBoat.class, DataWatcherRegistry.b); - private static final DataWatcherObject c = DataWatcher.a(EntityBoat.class, DataWatcherRegistry.b); - private static final DataWatcherObject d = DataWatcher.a(EntityBoat.class, DataWatcherRegistry.c); - private static final DataWatcherObject e = DataWatcher.a(EntityBoat.class, DataWatcherRegistry.b); - private static final DataWatcherObject f = DataWatcher.a(EntityBoat.class, DataWatcherRegistry.i); - private static final DataWatcherObject g = DataWatcher.a(EntityBoat.class, DataWatcherRegistry.i); - private static final DataWatcherObject ar = DataWatcher.a(EntityBoat.class, DataWatcherRegistry.b); - private final float[] as; - private float at; - private float au; - private float av; - private int aw; - private double ax; - private double ay; - private double az; - private double aA; - private double aB; - private boolean aC; - private boolean aD; - private boolean aE; - private boolean aF; - private double aG; - private float aH; - private EntityBoat.EnumStatus aI; - private EntityBoat.EnumStatus aJ; - private double aK; - private boolean aL; - private boolean aM; - private float aN; - private float aO; - private float aP; - - // CraftBukkit start - // PAIL: Some of these haven't worked since a few updates, and since 1.9 they are less and less applicable. - public double maxSpeed = 0.4D; - public double occupiedDeceleration = 0.2D; - public double unoccupiedDeceleration = -1; - public boolean landBoats = false; - // CraftBukkit end - - public EntityBoat(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.as = new float[2]; - this.i = true; - } - - public EntityBoat(World world, double d0, double d1, double d2) { - this(EntityTypes.BOAT, world); - this.setPosition(d0, d1, d2); - this.setMot(Vec3D.a); - this.lastX = d0; - this.lastY = d1; - this.lastZ = d2; - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - protected void initDatawatcher() { - this.datawatcher.register(EntityBoat.b, 0); - this.datawatcher.register(EntityBoat.c, 1); - this.datawatcher.register(EntityBoat.d, 0.0F); - this.datawatcher.register(EntityBoat.e, EntityBoat.EnumBoatType.OAK.ordinal()); - this.datawatcher.register(EntityBoat.f, false); - this.datawatcher.register(EntityBoat.g, false); - this.datawatcher.register(EntityBoat.ar, 0); - } - - @Nullable - @Override - public AxisAlignedBB j(Entity entity) { - return entity.isCollidable() ? entity.getBoundingBox() : null; - } - - @Nullable - @Override - public AxisAlignedBB aq() { - return this.getBoundingBox(); - } - - @Override - public boolean isCollidable() { - return true; - } - - @Override - public double aP() { - return -0.1D; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (!this.world.isClientSide && !this.dead) { - if (damagesource instanceof EntityDamageSourceIndirect && damagesource.getEntity() != null && this.w(damagesource.getEntity())) { - 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, (double) 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.c(-this.o()); - this.b(10); - this.setDamage(this.getDamage() + f * 10.0F); - this.velocityChanged(); - boolean flag = damagesource.getEntity() instanceof EntityHuman && ((EntityHuman) damagesource.getEntity()).abilities.canInstantlyBuild; - - if (flag || this.getDamage() > 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 (!flag && this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { - this.a((IMaterial) this.f()); - } - - this.die(); - } - - return true; - } - } else { - return true; - } - } - - @Override - public void j(boolean flag) { - if (!this.world.isClientSide) { - this.aL = true; - this.aM = flag; - if (this.A() == 0) { - this.d(60); - } - } - - this.world.addParticle(Particles.SPLASH, this.locX + (double) this.random.nextFloat(), this.locY + 0.7D, this.locZ + (double) this.random.nextFloat(), 0.0D, 0.0D, 0.0D); - if (this.random.nextInt(20) == 0) { - this.world.a(this.locX, this.locY, this.locZ, this.getSoundSplash(), this.getSoundCategory(), 1.0F, 0.8F + 0.4F * this.random.nextFloat(), false); - } - - } - - @Override - public void collide(Entity entity) { - if (entity instanceof EntityBoat) { - if (entity.getBoundingBox().minY < this.getBoundingBox().maxY) { - // CraftBukkit start - VehicleEntityCollisionEvent event = new VehicleEntityCollisionEvent((Vehicle) this.getBukkitEntity(), entity.getBukkitEntity()); - this.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - // CraftBukkit end - super.collide(entity); - } - } else if (entity.getBoundingBox().minY <= this.getBoundingBox().minY) { - // CraftBukkit start - VehicleEntityCollisionEvent event = new VehicleEntityCollisionEvent((Vehicle) this.getBukkitEntity(), entity.getBukkitEntity()); - this.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - // CraftBukkit end - super.collide(entity); - } - - } - - public Item f() { - switch (this.getType()) { - case OAK: - default: - return Items.OAK_BOAT; - case SPRUCE: - return Items.SPRUCE_BOAT; - case BIRCH: - return Items.BIRCH_BOAT; - case JUNGLE: - return Items.JUNGLE_BOAT; - case ACACIA: - return Items.ACACIA_BOAT; - case DARK_OAK: - return Items.DARK_OAK_BOAT; - } - } - - @Override - public boolean isInteractable() { - return !this.dead; - } - - @Override - public EnumDirection getAdjustedDirection() { - return this.getDirection().e(); - } - - private Location lastLocation; // CraftBukkit - @Override - public void tick() { - this.aJ = this.aI; - this.aI = this.s(); - if (this.aI != EntityBoat.EnumStatus.UNDER_WATER && this.aI != EntityBoat.EnumStatus.UNDER_FLOWING_WATER) { - this.au = 0.0F; - } else { - ++this.au; - } - - if (!this.world.isClientSide && this.au >= 60.0F) { - this.ejectPassengers(); - } - - if (this.n() > 0) { - this.b(this.n() - 1); - } - - if (this.getDamage() > 0.0F) { - this.setDamage(this.getDamage() - 1.0F); - } - - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - super.tick(); - this.r(); - if (this.ca()) { - if (this.getPassengers().isEmpty() || !(this.getPassengers().get(0) instanceof EntityHuman)) { - this.a(false, false); - } - - this.w(); - if (this.world.isClientSide) { - this.z(); - this.world.a((Packet) (new PacketPlayInBoatMove(this.a(0), this.a(1)))); - } - - this.move(EnumMoveType.SELF, this.getMot()); - } else { - this.setMot(Vec3D.a); - } - - // CraftBukkit start - org.bukkit.Server server = this.world.getServer(); - org.bukkit.World bworld = this.world.getWorld(); - - 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 (lastLocation != null && !lastLocation.equals(to)) { - VehicleMoveEvent event = new VehicleMoveEvent(vehicle, lastLocation, to); - server.getPluginManager().callEvent(event); - } - lastLocation = vehicle.getLocation(); - // CraftBukkit end - - this.q(); - - for (int i = 0; i <= 1; ++i) { - if (this.a(i)) { - if (!this.isSilent() && (double) (this.as[i] % 6.2831855F) <= 0.7853981852531433D && ((double) this.as[i] + 0.39269909262657166D) % 6.2831854820251465D >= 0.7853981852531433D) { - SoundEffect soundeffect = this.i(); - - if (soundeffect != null) { - Vec3D vec3d = this.f(1.0F); - double d0 = i == 1 ? -vec3d.z : vec3d.z; - double d1 = i == 1 ? vec3d.x : -vec3d.x; - - this.world.playSound((EntityHuman) null, this.locX + d0, this.locY, this.locZ + d1, soundeffect, this.getSoundCategory(), 1.0F, 0.8F + 0.4F * this.random.nextFloat()); - } - } - - this.as[i] = (float) ((double) this.as[i] + 0.39269909262657166D); - } else { - this.as[i] = 0.0F; - } - } - - this.checkBlockCollisions(); - List list = this.world.getEntities(this, this.getBoundingBox().grow(0.20000000298023224D, -0.009999999776482582D, 0.20000000298023224D), IEntitySelector.a(this)); - - if (!list.isEmpty()) { - boolean flag = !this.world.isClientSide && !(this.getRidingPassenger() instanceof EntityHuman); - - for (int j = 0; j < list.size(); ++j) { - Entity entity = (Entity) list.get(j); - - if (!entity.w(this)) { - if (flag && this.getPassengers().size() < 2 && !entity.isPassenger() && entity.getWidth() < this.getWidth() && entity instanceof EntityLiving && !(entity instanceof EntityWaterAnimal) && !(entity instanceof EntityHuman)) { - entity.startRiding(this); - } else { - this.collide(entity); - } - } - } - } - - } - - private void q() { - int i; - - if (this.world.isClientSide) { - i = this.A(); - if (i > 0) { - this.aN += 0.05F; - } else { - this.aN -= 0.1F; - } - - this.aN = MathHelper.a(this.aN, 0.0F, 1.0F); - this.aP = this.aO; - this.aO = 10.0F * (float) Math.sin((double) (0.5F * (float) this.world.getTime())) * this.aN; - } else { - if (!this.aL) { - this.d(0); - } - - i = this.A(); - if (i > 0) { - --i; - this.d(i); - int j = 60 - i - 1; - - if (j > 0 && i == 0) { - this.d(0); - Vec3D vec3d = this.getMot(); - - if (this.aM) { - this.setMot(vec3d.add(0.0D, -0.7D, 0.0D)); - this.ejectPassengers(); - } else { - this.setMot(vec3d.x, this.a(EntityHuman.class) ? 2.7D : 0.6D, vec3d.z); - } - } - - this.aL = false; - } - } - - } - - @Nullable - protected SoundEffect i() { - switch (this.s()) { - case IN_WATER: - case UNDER_WATER: - case UNDER_FLOWING_WATER: - return SoundEffects.ENTITY_BOAT_PADDLE_WATER; - case ON_LAND: - return SoundEffects.ENTITY_BOAT_PADDLE_LAND; - case IN_AIR: - default: - return null; - } - } - - private void r() { - if (this.aw > 0 && !this.ca()) { - double d0 = this.locX + (this.ax - this.locX) / (double) this.aw; - double d1 = this.locY + (this.ay - this.locY) / (double) this.aw; - double d2 = this.locZ + (this.az - this.locZ) / (double) this.aw; - double d3 = MathHelper.g(this.aA - (double) this.yaw); - - this.yaw = (float) ((double) this.yaw + d3 / (double) this.aw); - this.pitch = (float) ((double) this.pitch + (this.aB - (double) this.pitch) / (double) this.aw); - --this.aw; - this.setPosition(d0, d1, d2); - this.setYawPitch(this.yaw, this.pitch); - } - } - - public void a(boolean flag, boolean flag1) { - this.datawatcher.set(EntityBoat.f, flag); - this.datawatcher.set(EntityBoat.g, flag1); - } - - private EntityBoat.EnumStatus s() { - EntityBoat.EnumStatus entityboat_enumstatus = this.v(); - - if (entityboat_enumstatus != null) { - this.aG = this.getBoundingBox().maxY; - return entityboat_enumstatus; - } else if (this.u()) { - return EntityBoat.EnumStatus.IN_WATER; - } else { - float f = this.l(); - - if (f > 0.0F) { - this.aH = f; - return EntityBoat.EnumStatus.ON_LAND; - } else { - return EntityBoat.EnumStatus.IN_AIR; - } - } - } - - public float k() { - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.f(axisalignedbb.maxX); - int k = MathHelper.floor(axisalignedbb.maxY); - int l = MathHelper.f(axisalignedbb.maxY - this.aK); - int i1 = MathHelper.floor(axisalignedbb.minZ); - int j1 = MathHelper.f(axisalignedbb.maxZ); - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - label161: - for (int k1 = k; k1 < l; ++k1) { - float f = 0.0F; - - for (int l1 = i; l1 < j; ++l1) { - for (int i2 = i1; i2 < j1; ++i2) { - blockposition_pooledblockposition.d(l1, k1, i2); - Fluid fluid = this.world.getFluid(blockposition_pooledblockposition); - - if (fluid.a(TagsFluid.WATER)) { - f = Math.max(f, fluid.getHeight(this.world, blockposition_pooledblockposition)); - } - - if (f >= 1.0F) { - continue label161; - } - } - } - - if (f < 1.0F) { - float f1 = (float) blockposition_pooledblockposition.getY() + f; - - return f1; - } - } - - float f2 = (float) (l + 1); - - return f2; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - } - - public float l() { - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - AxisAlignedBB axisalignedbb1 = new AxisAlignedBB(axisalignedbb.minX, axisalignedbb.minY - 0.001D, axisalignedbb.minZ, axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ); - int i = MathHelper.floor(axisalignedbb1.minX) - 1; - int j = MathHelper.f(axisalignedbb1.maxX) + 1; - int k = MathHelper.floor(axisalignedbb1.minY) - 1; - int l = MathHelper.f(axisalignedbb1.maxY) + 1; - int i1 = MathHelper.floor(axisalignedbb1.minZ) - 1; - int j1 = MathHelper.f(axisalignedbb1.maxZ) + 1; - VoxelShape voxelshape = VoxelShapes.a(axisalignedbb1); - float f = 0.0F; - int k1 = 0; - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - for (int l1 = i; l1 < j; ++l1) { - for (int i2 = i1; i2 < j1; ++i2) { - int j2 = (l1 != i && l1 != j - 1 ? 0 : 1) + (i2 != i1 && i2 != j1 - 1 ? 0 : 1); - - if (j2 != 2) { - for (int k2 = k; k2 < l; ++k2) { - if (j2 <= 0 || k2 != k && k2 != l - 1) { - blockposition_pooledblockposition.d(l1, k2, i2); - IBlockData iblockdata = this.world.getType(blockposition_pooledblockposition); - - if (!(iblockdata.getBlock() instanceof BlockWaterLily) && VoxelShapes.c(iblockdata.getCollisionShape(this.world, blockposition_pooledblockposition).a((double) l1, (double) k2, (double) i2), voxelshape, OperatorBoolean.AND)) { - f += iblockdata.getBlock().m(); - ++k1; - } - } - } - } - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - return f / (float) k1; - } - - private boolean u() { - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.f(axisalignedbb.maxX); - int k = MathHelper.floor(axisalignedbb.minY); - int l = MathHelper.f(axisalignedbb.minY + 0.001D); - int i1 = MathHelper.floor(axisalignedbb.minZ); - int j1 = MathHelper.f(axisalignedbb.maxZ); - boolean flag = false; - - this.aG = Double.MIN_VALUE; - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - for (int k1 = i; k1 < j; ++k1) { - for (int l1 = k; l1 < l; ++l1) { - for (int i2 = i1; i2 < j1; ++i2) { - blockposition_pooledblockposition.d(k1, l1, i2); - Fluid fluid = this.world.getFluid(blockposition_pooledblockposition); - - if (fluid.a(TagsFluid.WATER)) { - float f = (float) l1 + fluid.getHeight(this.world, blockposition_pooledblockposition); - - this.aG = Math.max((double) f, this.aG); - flag |= axisalignedbb.minY < (double) f; - } - } - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - return flag; - } - - @Nullable - private EntityBoat.EnumStatus v() { - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - double d0 = axisalignedbb.maxY + 0.001D; - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.f(axisalignedbb.maxX); - int k = MathHelper.floor(axisalignedbb.maxY); - int l = MathHelper.f(d0); - int i1 = MathHelper.floor(axisalignedbb.minZ); - int j1 = MathHelper.f(axisalignedbb.maxZ); - boolean flag = false; - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - for (int k1 = i; k1 < j; ++k1) { - for (int l1 = k; l1 < l; ++l1) { - for (int i2 = i1; i2 < j1; ++i2) { - blockposition_pooledblockposition.d(k1, l1, i2); - Fluid fluid = this.world.getFluid(blockposition_pooledblockposition); - - if (fluid.a(TagsFluid.WATER) && d0 < (double) ((float) blockposition_pooledblockposition.getY() + fluid.getHeight(this.world, blockposition_pooledblockposition))) { - if (!fluid.isSource()) { - EntityBoat.EnumStatus entityboat_enumstatus = EntityBoat.EnumStatus.UNDER_FLOWING_WATER; - - return entityboat_enumstatus; - } - - flag = true; - } - } - } - } - - return flag ? EntityBoat.EnumStatus.UNDER_WATER : null; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - } - - private void w() { - double d0 = -0.03999999910593033D; - double d1 = this.isNoGravity() ? 0.0D : -0.03999999910593033D; - double d2 = 0.0D; - - this.at = 0.05F; - if (this.aJ == EntityBoat.EnumStatus.IN_AIR && this.aI != EntityBoat.EnumStatus.IN_AIR && this.aI != EntityBoat.EnumStatus.ON_LAND) { - this.aG = this.getBoundingBox().minY + (double) this.getHeight(); - this.setPosition(this.locX, (double) (this.k() - this.getHeight()) + 0.101D, this.locZ); - this.setMot(this.getMot().d(1.0D, 0.0D, 1.0D)); - this.aK = 0.0D; - this.aI = EntityBoat.EnumStatus.IN_WATER; - } else { - if (this.aI == EntityBoat.EnumStatus.IN_WATER) { - d2 = (this.aG - this.getBoundingBox().minY) / (double) this.getHeight(); - this.at = 0.9F; - } else if (this.aI == EntityBoat.EnumStatus.UNDER_FLOWING_WATER) { - d1 = -7.0E-4D; - this.at = 0.9F; - } else if (this.aI == EntityBoat.EnumStatus.UNDER_WATER) { - d2 = 0.009999999776482582D; - this.at = 0.45F; - } else if (this.aI == EntityBoat.EnumStatus.IN_AIR) { - this.at = 0.9F; - } else if (this.aI == EntityBoat.EnumStatus.ON_LAND) { - this.at = this.aH; - if (this.getRidingPassenger() instanceof EntityHuman) { - this.aH /= 2.0F; - } - } - - Vec3D vec3d = this.getMot(); - - this.setMot(vec3d.x * (double) this.at, vec3d.y + d1, vec3d.z * (double) this.at); - this.av *= this.at; - if (d2 > 0.0D) { - Vec3D vec3d1 = this.getMot(); - - this.setMot(vec3d1.x, (vec3d1.y + d2 * 0.06153846016296973D) * 0.75D, vec3d1.z); - } - } - - } - - private void z() { - if (this.isVehicle()) { - float f = 0.0F; - - if (this.aC) { - --this.av; - } - - if (this.aD) { - ++this.av; - } - - if (this.aD != this.aC && !this.aE && !this.aF) { - f += 0.005F; - } - - this.yaw += this.av; - if (this.aE) { - f += 0.04F; - } - - if (this.aF) { - f -= 0.005F; - } - - this.setMot(this.getMot().add((double) (MathHelper.sin(-this.yaw * 0.017453292F) * f), 0.0D, (double) (MathHelper.cos(this.yaw * 0.017453292F) * f))); - this.a(this.aD && !this.aC || this.aE, this.aC && !this.aD || this.aE); - } - } - - @Override - public void k(Entity entity) { - if (this.w(entity)) { - float f = 0.0F; - float f1 = (float) ((this.dead ? 0.009999999776482582D : this.aP()) + entity.aO()); - - if (this.getPassengers().size() > 1) { - int i = this.getPassengers().indexOf(entity); - - if (i == 0) { - f = 0.2F; - } else { - f = -0.6F; - } - - if (entity instanceof EntityAnimal) { - f = (float) ((double) f + 0.2D); - } - } - - Vec3D vec3d = (new Vec3D((double) f, 0.0D, 0.0D)).b(-this.yaw * 0.017453292F - 1.5707964F); - - entity.setPosition(this.locX + vec3d.x, this.locY + (double) f1, this.locZ + vec3d.z); - entity.yaw += this.av; - entity.setHeadRotation(entity.getHeadRotation() + this.av); - this.a(entity); - if (entity instanceof EntityAnimal && this.getPassengers().size() > 1) { - int j = entity.getId() % 2 == 0 ? 90 : 270; - - entity.l(((EntityAnimal) entity).aK + (float) j); - entity.setHeadRotation(entity.getHeadRotation() + (float) j); - } - - } - } - - protected void a(Entity entity) { - entity.l(this.yaw); - float f = MathHelper.g(entity.yaw - this.yaw); - float f1 = MathHelper.a(f, -105.0F, 105.0F); - - entity.lastYaw += f1 - f; - entity.yaw += f1 - f; - entity.setHeadRotation(entity.yaw); - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setString("Type", this.getType().a()); - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - if (nbttagcompound.hasKeyOfType("Type", 8)) { - this.setType(EntityBoat.EnumBoatType.a(nbttagcompound.getString("Type"))); - } - - } - - @Override - public boolean b(EntityHuman entityhuman, EnumHand enumhand) { - if (entityhuman.isSneaking()) { - return false; - } else { - if (!this.world.isClientSide && this.au < 60.0F) { - entityhuman.startRiding(this); - } - - return true; - } - } - - @Override - protected void a(double d0, boolean flag, IBlockData iblockdata, BlockPosition blockposition) { - this.aK = this.getMot().y; - if (!this.isPassenger()) { - if (flag) { - if (this.fallDistance > 3.0F) { - if (this.aI != EntityBoat.EnumStatus.ON_LAND) { - this.fallDistance = 0.0F; - return; - } - - this.b(this.fallDistance, 1.0F); - if (!this.world.isClientSide && !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(GameRules.DO_ENTITY_DROPS)) { - int i; - - for (i = 0; i < 3; ++i) { - this.a((IMaterial) this.getType().b()); - } - - for (i = 0; i < 2; ++i) { - this.a((IMaterial) Items.STICK); - } - } - } - } // CraftBukkit end - } - - this.fallDistance = 0.0F; - } else if (!this.world.getFluid((new BlockPosition(this)).down()).a(TagsFluid.WATER) && d0 < 0.0D) { - this.fallDistance = (float) ((double) this.fallDistance - d0); - } - - } - } - - public boolean a(int i) { - return (Boolean) this.datawatcher.get(i == 0 ? EntityBoat.f : EntityBoat.g) && this.getRidingPassenger() != null; - } - - public void setDamage(float f) { - this.datawatcher.set(EntityBoat.d, f); - } - - public float getDamage() { - return (Float) this.datawatcher.get(EntityBoat.d); - } - - public void b(int i) { - this.datawatcher.set(EntityBoat.b, i); - } - - public int n() { - return (Integer) this.datawatcher.get(EntityBoat.b); - } - - private void d(int i) { - this.datawatcher.set(EntityBoat.ar, i); - } - - private int A() { - return (Integer) this.datawatcher.get(EntityBoat.ar); - } - - public void c(int i) { - this.datawatcher.set(EntityBoat.c, i); - } - - public int o() { - return (Integer) this.datawatcher.get(EntityBoat.c); - } - - public void setType(EntityBoat.EnumBoatType entityboat_enumboattype) { - this.datawatcher.set(EntityBoat.e, entityboat_enumboattype.ordinal()); - } - - public EntityBoat.EnumBoatType getType() { - return EntityBoat.EnumBoatType.a((Integer) this.datawatcher.get(EntityBoat.e)); - } - - @Override - protected boolean q(Entity entity) { - return this.getPassengers().size() < 2 && !this.a(TagsFluid.WATER); - } - - @Nullable - @Override - public Entity getRidingPassenger() { - List list = this.getPassengers(); - - return list.isEmpty() ? null : (Entity) list.get(0); - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } - - public static enum EnumBoatType { - - OAK(Blocks.OAK_PLANKS, "oak"), SPRUCE(Blocks.SPRUCE_PLANKS, "spruce"), BIRCH(Blocks.BIRCH_PLANKS, "birch"), JUNGLE(Blocks.JUNGLE_PLANKS, "jungle"), ACACIA(Blocks.ACACIA_PLANKS, "acacia"), DARK_OAK(Blocks.DARK_OAK_PLANKS, "dark_oak"); - - private final String g; - private final Block h; - - private EnumBoatType(Block block, String s) { - this.g = s; - this.h = block; - } - - public String a() { - return this.g; - } - - public Block b() { - return this.h; - } - - public String toString() { - return this.g; - } - - public static EntityBoat.EnumBoatType a(int i) { - EntityBoat.EnumBoatType[] aentityboat_enumboattype = values(); - - if (i < 0 || i >= aentityboat_enumboattype.length) { - i = 0; - } - - return aentityboat_enumboattype[i]; - } - - public static EntityBoat.EnumBoatType a(String s) { - EntityBoat.EnumBoatType[] aentityboat_enumboattype = values(); - - for (int i = 0; i < aentityboat_enumboattype.length; ++i) { - if (aentityboat_enumboattype[i].a().equals(s)) { - return aentityboat_enumboattype[i]; - } - } - - return aentityboat_enumboattype[0]; - } - } - - public static enum EnumStatus { - - IN_WATER, UNDER_WATER, UNDER_FLOWING_WATER, ON_LAND, IN_AIR; - - private EnumStatus() {} - } -} diff --git a/src/main/java/net/minecraft/server/EntityCat.java b/src/main/java/net/minecraft/server/EntityCat.java deleted file mode 100644 index f4660233e..000000000 --- a/src/main/java/net/minecraft/server/EntityCat.java +++ /dev/null @@ -1,572 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntityCat extends EntityTameableAnimal { - - private static final RecipeItemStack bD = RecipeItemStack.a(Items.COD, Items.SALMON); - private static final DataWatcherObject bE = DataWatcher.a(EntityCat.class, DataWatcherRegistry.b); - private static final DataWatcherObject bF = DataWatcher.a(EntityCat.class, DataWatcherRegistry.i); - private static final DataWatcherObject bG = DataWatcher.a(EntityCat.class, DataWatcherRegistry.i); - private static final DataWatcherObject bH = DataWatcher.a(EntityCat.class, DataWatcherRegistry.b); - public static final Map bC = (Map) SystemUtils.a(Maps.newHashMap(), (hashmap) -> { // CraftBukkit - decompile error - hashmap.put(0, new MinecraftKey("textures/entity/cat/tabby.png")); - hashmap.put(1, new MinecraftKey("textures/entity/cat/black.png")); - hashmap.put(2, new MinecraftKey("textures/entity/cat/red.png")); - hashmap.put(3, new MinecraftKey("textures/entity/cat/siamese.png")); - hashmap.put(4, new MinecraftKey("textures/entity/cat/british_shorthair.png")); - hashmap.put(5, new MinecraftKey("textures/entity/cat/calico.png")); - hashmap.put(6, new MinecraftKey("textures/entity/cat/persian.png")); - hashmap.put(7, new MinecraftKey("textures/entity/cat/ragdoll.png")); - hashmap.put(8, new MinecraftKey("textures/entity/cat/white.png")); - hashmap.put(9, new MinecraftKey("textures/entity/cat/jellie.png")); - hashmap.put(10, new MinecraftKey("textures/entity/cat/all_black.png")); - }); - private EntityCat.a bI; - private PathfinderGoalTempt bJ; - private float bK; - private float bL; - private float bM; - private float bN; - private float bO; - private float bP; - - public EntityCat(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public MinecraftKey ee() { - return (MinecraftKey) EntityCat.bC.get(this.getCatType()); - } - - @Override - protected void initPathfinder() { - this.goalSit = new PathfinderGoalSit(this); - this.bJ = new EntityCat.PathfinderGoalTemptChance(this, 0.6D, EntityCat.bD, true); - this.goalSelector.a(1, new PathfinderGoalFloat(this)); - this.goalSelector.a(1, new EntityCat.b(this)); - this.goalSelector.a(2, this.goalSit); - this.goalSelector.a(3, this.bJ); - this.goalSelector.a(5, new PathfinderGoalCatSitOnBed(this, 1.1D, 8)); - this.goalSelector.a(6, new PathfinderGoalFollowOwner(this, 1.0D, 10.0F, 5.0F)); - this.goalSelector.a(7, new PathfinderGoalJumpOnBlock(this, 0.8D)); - this.goalSelector.a(8, new PathfinderGoalLeapAtTarget(this, 0.3F)); - this.goalSelector.a(9, new PathfinderGoalOcelotAttack(this)); - this.goalSelector.a(10, new PathfinderGoalBreed(this, 0.8D)); - this.goalSelector.a(11, new PathfinderGoalRandomStrollLand(this, 0.8D, 1.0000001E-5F)); - this.goalSelector.a(12, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 10.0F)); - this.targetSelector.a(1, new PathfinderGoalRandomTargetNonTamed<>(this, EntityRabbit.class, false, (Predicate) null)); - this.targetSelector.a(1, new PathfinderGoalRandomTargetNonTamed<>(this, EntityTurtle.class, false, EntityTurtle.bz)); - } - - public int getCatType() { - return (Integer) this.datawatcher.get(EntityCat.bE); - } - - public void setCatType(int i) { - if (i < 0 || i >= 11) { - i = this.random.nextInt(10); - } - - this.datawatcher.set(EntityCat.bE, i); - } - - public void u(boolean flag) { - this.datawatcher.set(EntityCat.bF, flag); - } - - public boolean eg() { - return (Boolean) this.datawatcher.get(EntityCat.bF); - } - - public void v(boolean flag) { - this.datawatcher.set(EntityCat.bG, flag); - } - - public boolean eh() { - return (Boolean) this.datawatcher.get(EntityCat.bG); - } - - public EnumColor getCollarColor() { - return EnumColor.fromColorIndex((Integer) this.datawatcher.get(EntityCat.bH)); - } - - public void setCollarColor(EnumColor enumcolor) { - this.datawatcher.set(EntityCat.bH, enumcolor.getColorIndex()); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityCat.bE, 1); - this.datawatcher.register(EntityCat.bF, false); - this.datawatcher.register(EntityCat.bG, false); - this.datawatcher.register(EntityCat.bH, EnumColor.RED.getColorIndex()); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("CatType", this.getCatType()); - nbttagcompound.setByte("CollarColor", (byte) this.getCollarColor().getColorIndex()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setCatType(nbttagcompound.getInt("CatType")); - if (nbttagcompound.hasKeyOfType("CollarColor", 99)) { - this.setCollarColor(EnumColor.fromColorIndex(nbttagcompound.getInt("CollarColor"))); - } - - } - - @Override - public void mobTick() { - if (this.getControllerMove().b()) { - double d0 = this.getControllerMove().c(); - - 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); - } - - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - return this.isTamed() ? (this.isInLove() ? SoundEffects.ENTITY_CAT_PURR : (this.random.nextInt(4) == 0 ? SoundEffects.ENTITY_CAT_PURREOW : SoundEffects.ENTITY_CAT_AMBIENT)) : SoundEffects.ENTITY_CAT_STRAY_AMBIENT; - } - - @Override - public int A() { - return 120; - } - - public void ej() { - this.a(SoundEffects.ENTITY_CAT_HISS, this.getSoundVolume(), this.cV()); - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_CAT_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_CAT_DEATH; - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); - } - - @Override - public void b(float f, float f1) {} - - @Override - protected void a(EntityHuman entityhuman, ItemStack itemstack) { - if (this.i(itemstack)) { - this.a(SoundEffects.ENTITY_CAT_EAT, 1.0F, 1.0F); - } - - super.a(entityhuman, itemstack); - } - - @Override - public boolean C(Entity entity) { - return entity.damageEntity(DamageSource.mobAttack(this), 3.0F); - } - - @Override - public void tick() { - super.tick(); - if (this.bJ != null && this.bJ.h() && !this.isTamed() && this.ticksLived % 100 == 0) { - this.a(SoundEffects.ENTITY_CAT_BEG_FOR_FOOD, 1.0F, 1.0F); - } - - this.ek(); - } - - private void ek() { - if ((this.eg() || this.eh()) && this.ticksLived % 5 == 0) { - this.a(SoundEffects.ENTITY_CAT_PURR, 0.6F + 0.4F * (this.random.nextFloat() - this.random.nextFloat()), 1.0F); - } - - this.el(); - this.em(); - } - - private void el() { - this.bL = this.bK; - this.bN = this.bM; - if (this.eg()) { - this.bK = Math.min(1.0F, this.bK + 0.15F); - this.bM = Math.min(1.0F, this.bM + 0.08F); - } else { - this.bK = Math.max(0.0F, this.bK - 0.22F); - this.bM = Math.max(0.0F, this.bM - 0.13F); - } - - } - - private void em() { - this.bP = this.bO; - if (this.eh()) { - this.bO = Math.min(1.0F, this.bO + 0.1F); - } else { - this.bO = Math.max(0.0F, this.bO - 0.13F); - } - - } - - @Override - public EntityCat createChild(EntityAgeable entityageable) { - EntityCat entitycat = (EntityCat) EntityTypes.CAT.a(this.world); - - if (entityageable instanceof EntityCat) { - if (this.random.nextBoolean()) { - entitycat.setCatType(this.getCatType()); - } else { - entitycat.setCatType(((EntityCat) entityageable).getCatType()); - } - - if (this.isTamed()) { - entitycat.setOwnerUUID(this.getOwnerUUID()); - entitycat.setTamed(true); - if (this.random.nextBoolean()) { - entitycat.setCollarColor(this.getCollarColor()); - } else { - entitycat.setCollarColor(((EntityCat) entityageable).getCollarColor()); - } - } - } - - return entitycat; - } - - @Override - public boolean mate(EntityAnimal entityanimal) { - if (!this.isTamed()) { - return false; - } else if (!(entityanimal instanceof EntityCat)) { - return false; - } else { - EntityCat entitycat = (EntityCat) entityanimal; - - return entitycat.isTamed() && super.mate(entityanimal); - } - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - groupdataentity = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - if (generatoraccess.aa() > 0.9F) { - this.setCatType(this.random.nextInt(11)); - } else { - this.setCatType(this.random.nextInt(10)); - } - - if (WorldGenerator.SWAMP_HUT.b(generatoraccess, new BlockPosition(this))) { - this.setCatType(10); - this.setPersistent(); - } - - return groupdataentity; - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - Item item = itemstack.getItem(); - - if (this.isTamed()) { - if (this.h((EntityLiving) entityhuman)) { - if (item instanceof ItemDye) { - EnumColor enumcolor = ((ItemDye) item).d(); - - if (enumcolor != this.getCollarColor()) { - this.setCollarColor(enumcolor); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - this.setPersistent(); - return true; - } - } else if (this.i(itemstack)) { - if (this.getHealth() < this.getMaxHealth() && item.isFood()) { - this.a(entityhuman, itemstack); - this.heal((float) item.getFoodInfo().getNutrition()); - return true; - } - } else if (!this.world.isClientSide) { - this.goalSit.setSitting(!this.isSitting()); - } - } - } else if (this.i(itemstack)) { - this.a(entityhuman, itemstack); - if (!this.world.isClientSide) { - if (this.random.nextInt(3) == 0 && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityTameEvent(this, entityhuman).isCancelled()) { // CraftBukkit - this.tame(entityhuman); - this.r(true); - this.goalSit.setSitting(true); - this.world.broadcastEntityEffect(this, (byte) 7); - } else { - this.r(false); - this.world.broadcastEntityEffect(this, (byte) 6); - } - } - - this.setPersistent(); - return true; - } - - boolean flag = super.a(entityhuman, enumhand); - - if (flag) { - this.setPersistent(); - } - - return flag; - } - - @Override - public boolean i(ItemStack itemstack) { - return EntityCat.bD.test(itemstack); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * 0.5F; - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return !this.isTamed() && this.ticksLived > 2400; - } - - @Override - protected void dW() { - if (this.bI == null) { - this.bI = new EntityCat.a<>(this, EntityHuman.class, 16.0F, 0.8D, 1.33D); - } - - this.goalSelector.a((PathfinderGoal) this.bI); - if (!this.isTamed()) { - this.goalSelector.a(4, this.bI); - } - - } - - static class b extends PathfinderGoal { - - private final EntityCat a; - private EntityHuman b; - private BlockPosition c; - private int d; - - public b(EntityCat entitycat) { - this.a = entitycat; - } - - @Override - public boolean a() { - if (!this.a.isTamed()) { - return false; - } else if (this.a.isSitting()) { - return false; - } else { - EntityLiving entityliving = this.a.getOwner(); - - if (entityliving instanceof EntityHuman) { - this.b = (EntityHuman) entityliving; - if (!entityliving.isSleeping()) { - return false; - } - - if (this.a.h((Entity) this.b) > 100.0D) { - return false; - } - - BlockPosition blockposition = new BlockPosition(this.b); - IBlockData iblockdata = this.a.world.getType(blockposition); - - if (iblockdata.getBlock().a(TagsBlock.BEDS)) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockBed.FACING); - - this.c = new BlockPosition(blockposition.getX() - enumdirection.getAdjacentX(), blockposition.getY(), blockposition.getZ() - enumdirection.getAdjacentZ()); - return !this.g(); - } - } - - return false; - } - } - - private boolean g() { - List list = this.a.world.a(EntityCat.class, (new AxisAlignedBB(this.c)).g(2.0D)); - Iterator iterator = list.iterator(); - - EntityCat entitycat; - - do { - do { - if (!iterator.hasNext()) { - return false; - } - - entitycat = (EntityCat) iterator.next(); - } while (entitycat == this.a); - } while (!entitycat.eg() && !entitycat.eh()); - - return true; - } - - @Override - public boolean b() { - return this.a.isTamed() && !this.a.isSitting() && this.b != null && this.b.isSleeping() && this.c != null && !this.g(); - } - - @Override - public void c() { - if (this.c != null) { - this.a.getGoalSit().setSitting(false); - this.a.getNavigation().a((double) this.c.getX(), (double) this.c.getY(), (double) this.c.getZ(), 1.100000023841858D); - } - - } - - @Override - public void d() { - this.a.u(false); - float f = this.a.world.j(1.0F); - - if (this.b.dJ() >= 100 && (double) f > 0.77D && (double) f < 0.8D && (double) this.a.world.getRandom().nextFloat() < 0.7D) { - this.h(); - } - - this.d = 0; - this.a.v(false); - this.a.getNavigation().o(); - } - - private void h() { - Random random = this.a.getRandom(); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - blockposition_mutableblockposition.a((Entity) this.a); - this.a.a((double) (blockposition_mutableblockposition.getX() + random.nextInt(11) - 5), (double) (blockposition_mutableblockposition.getY() + random.nextInt(5) - 2), (double) (blockposition_mutableblockposition.getZ() + random.nextInt(11) - 5), false); - blockposition_mutableblockposition.a((Entity) this.a); - LootTable loottable = this.a.world.getMinecraftServer().getLootTableRegistry().getLootTable(LootTables.af); - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder((WorldServer) this.a.world)).set(LootContextParameters.POSITION, blockposition_mutableblockposition).set(LootContextParameters.THIS_ENTITY, this.a).a(random); - List list = loottable.populateLoot(loottableinfo_builder.build(LootContextParameterSets.GIFT)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - - this.a.world.addEntity(new EntityItem(this.a.world, (double) ((float) blockposition_mutableblockposition.getX() - MathHelper.sin(this.a.aK * 0.017453292F)), (double) blockposition_mutableblockposition.getY(), (double) ((float) blockposition_mutableblockposition.getZ() + MathHelper.cos(this.a.aK * 0.017453292F)), itemstack)); - } - - } - - @Override - public void e() { - if (this.b != null && this.c != null) { - this.a.getGoalSit().setSitting(false); - this.a.getNavigation().a((double) this.c.getX(), (double) this.c.getY(), (double) this.c.getZ(), 1.100000023841858D); - if (this.a.h((Entity) this.b) < 2.5D) { - ++this.d; - if (this.d > 16) { - this.a.u(true); - this.a.v(false); - } else { - this.a.a((Entity) this.b, 45.0F, 45.0F); - this.a.v(true); - } - } else { - this.a.u(false); - } - } - - } - } - - static class PathfinderGoalTemptChance extends PathfinderGoalTempt { - - @Nullable - private EntityLiving chosenTarget; // CraftBukkit - private final EntityCat d; - - public PathfinderGoalTemptChance(EntityCat entitycat, double d0, RecipeItemStack recipeitemstack, boolean flag) { - super(entitycat, d0, recipeitemstack, flag); - this.d = entitycat; - } - - @Override - public void e() { - super.e(); - if (this.chosenTarget == null && this.a.getRandom().nextInt(600) == 0) { - this.chosenTarget = this.target; - } else if (this.a.getRandom().nextInt(500) == 0) { - this.chosenTarget = null; - } - - } - - @Override - protected boolean g() { - return this.chosenTarget != null && this.chosenTarget.equals(this.target) ? false : super.g(); - } - - @Override - public boolean a() { - return super.a() && !this.d.isTamed(); - } - } - - static class a extends PathfinderGoalAvoidTarget { - - private final EntityCat i; - - public a(EntityCat entitycat, Class oclass, float f, double d0, double d1) { - // Predicate predicate = IEntitySelector.e; // CraftBukkit - decompile error - - super(entitycat, oclass, f, d0, d1, IEntitySelector.e::test); // CraftBukkit - decompile error - this.i = entitycat; - } - - @Override - public boolean a() { - return !this.i.isTamed() && super.a(); - } - - @Override - public boolean b() { - return !this.i.isTamed() && super.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityCaveSpider.java b/src/main/java/net/minecraft/server/EntityCaveSpider.java deleted file mode 100644 index 89c9306df..000000000 --- a/src/main/java/net/minecraft/server/EntityCaveSpider.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class EntityCaveSpider extends EntitySpider { - - public EntityCaveSpider(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(12.0D); - } - - @Override - public boolean C(Entity entity) { - if (super.C(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(MobEffects.POISON, b0 * 20, 0), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - } - - return true; - } else { - return false; - } - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - return groupdataentity; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 0.45F; - } -} diff --git a/src/main/java/net/minecraft/server/EntityChicken.java b/src/main/java/net/minecraft/server/EntityChicken.java deleted file mode 100644 index f1dfdd4ff..000000000 --- a/src/main/java/net/minecraft/server/EntityChicken.java +++ /dev/null @@ -1,160 +0,0 @@ -package net.minecraft.server; - -public class EntityChicken extends EntityAnimal { - - private static final RecipeItemStack bG = RecipeItemStack.a(Items.WHEAT_SEEDS, Items.MELON_SEEDS, Items.PUMPKIN_SEEDS, Items.BEETROOT_SEEDS); - public float bz; - public float bA; - public float bB; - public float bC; - public float bD = 1.0F; - public int eggLayTime; - public boolean bF; - - public EntityChicken(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.eggLayTime = this.random.nextInt(6000) + 6000; - this.a(PathType.WATER, 0.0F); - } - - @Override - protected void initPathfinder() { - 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, false, EntityChicken.bG)); - this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.1D)); - this.goalSelector.a(5, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); - this.goalSelector.a(7, new PathfinderGoalRandomLookaround(this)); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return this.isBaby() ? entitysize.height * 0.85F : entitysize.height * 0.92F; - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(4.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); - } - - @Override - public void movementTick() { - // CraftBukkit start - if (this.isChickenJockey()) { - this.persistent = !this.isTypeNotPersistent(0); - } - // CraftBukkit end - super.movementTick(); - this.bC = this.bz; - this.bB = this.bA; - this.bA = (float) ((double) this.bA + (double) (this.onGround ? -1 : 4) * 0.3D); - this.bA = MathHelper.a(this.bA, 0.0F, 1.0F); - if (!this.onGround && this.bD < 1.0F) { - this.bD = 1.0F; - } - - this.bD = (float) ((double) this.bD * 0.9D); - Vec3D vec3d = this.getMot(); - - if (!this.onGround && vec3d.y < 0.0D) { - this.setMot(vec3d.d(1.0D, 0.6D, 1.0D)); - } - - this.bz += this.bD * 2.0F; - if (!this.world.isClientSide && this.isAlive() && !this.isBaby() && !this.isChickenJockey() && --this.eggLayTime <= 0) { - this.a(SoundEffects.ENTITY_CHICKEN_EGG, 1.0F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F); - this.forceDrops = true; // CraftBukkit - this.a((IMaterial) Items.EGG); - this.forceDrops = false; // CraftBukkit - this.eggLayTime = this.random.nextInt(6000) + 6000; - } - - } - - @Override - public void b(float f, float f1) {} - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_CHICKEN_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_CHICKEN_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_CHICKEN_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_CHICKEN_STEP, 0.15F, 1.0F); - } - - @Override - public EntityChicken createChild(EntityAgeable entityageable) { - return (EntityChicken) EntityTypes.CHICKEN.a(this.world); - } - - @Override - public boolean i(ItemStack itemstack) { - return EntityChicken.bG.test(itemstack); - } - - @Override - protected int getExpValue(EntityHuman entityhuman) { - return this.isChickenJockey() ? 10 : super.getExpValue(entityhuman); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.bF = nbttagcompound.getBoolean("IsChickenJockey"); - if (nbttagcompound.hasKey("EggLayTime")) { - this.eggLayTime = nbttagcompound.getInt("EggLayTime"); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("IsChickenJockey", this.bF); - nbttagcompound.setInt("EggLayTime", this.eggLayTime); - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return this.isChickenJockey() && !this.isVehicle(); - } - - @Override - public void k(Entity entity) { - super.k(entity); - float f = MathHelper.sin(this.aK * 0.017453292F); - float f1 = MathHelper.cos(this.aK * 0.017453292F); - float f2 = 0.1F; - float f3 = 0.0F; - - entity.setPosition(this.locX + (double) (0.1F * f), this.locY + (double) (this.getHeight() * 0.5F) + entity.aO() + 0.0D, this.locZ - (double) (0.1F * f1)); - if (entity instanceof EntityLiving) { - ((EntityLiving) entity).aK = this.aK; - } - - } - - public boolean isChickenJockey() { - return this.bF; - } - - public void r(boolean flag) { - this.bF = flag; - } -} diff --git a/src/main/java/net/minecraft/server/EntityCow.java b/src/main/java/net/minecraft/server/EntityCow.java deleted file mode 100644 index 2c8bbf20a..000000000 --- a/src/main/java/net/minecraft/server/EntityCow.java +++ /dev/null @@ -1,95 +0,0 @@ -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(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - 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, RecipeItemStack.a(Items.WHEAT), false)); - this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.25D)); - this.goalSelector.a(5, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); - this.goalSelector.a(7, new PathfinderGoalRandomLookaround(this)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.20000000298023224D); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_COW_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_COW_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_COW_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_COW_STEP, 0.15F, 1.0F); - } - - @Override - protected float getSoundVolume() { - return 0.4F; - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() == Items.BUCKET && !entityhuman.abilities.canInstantlyBuild && !this.isBaby()) { - // CraftBukkit start - Got milk? - org.bukkit.event.player.PlayerBucketFillEvent event = CraftEventFactory.callPlayerBucketFillEvent(entityhuman.world, entityhuman, this.getChunkCoordinates(), this.getChunkCoordinates(), null, itemstack, Items.MILK_BUCKET, enumhand); // Paper - add enumHand - - if (event.isCancelled()) { - return false; - } - - ItemStack result = CraftItemStack.asNMSCopy(event.getItemStack()); - entityhuman.a(SoundEffects.ENTITY_COW_MILK, 1.0F, 1.0F); - itemstack.subtract(1); - if (itemstack.isEmpty()) { - entityhuman.a(enumhand, result); - } else if (!entityhuman.inventory.pickup(result)) { - entityhuman.drop(result, false); - } - // CraftBukkit end - - return true; - } else { - return super.a(entityhuman, enumhand); - } - } - - @Override - public EntityCow createChild(EntityAgeable entityageable) { - return (EntityCow) EntityTypes.COW.a(this.world); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return this.isBaby() ? entitysize.height * 0.95F : 1.3F; - } -} diff --git a/src/main/java/net/minecraft/server/EntityCreature.java b/src/main/java/net/minecraft/server/EntityCreature.java deleted file mode 100644 index 7dacaa216..000000000 --- a/src/main/java/net/minecraft/server/EntityCreature.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.event.entity.EntityUnleashEvent; -// CraftBukkit end - -public abstract class EntityCreature extends EntityInsentient { - - public org.bukkit.craftbukkit.entity.CraftCreature getBukkitCreature() { return (org.bukkit.craftbukkit.entity.CraftCreature) super.getBukkitEntity(); } // Paper - - protected EntityCreature(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public float f(BlockPosition blockposition) { - return this.a(blockposition, (IWorldReader) this.world); - } - - public float a(BlockPosition blockposition, IWorldReader iworldreader) { - return 0.0F; - } - - @Override - public boolean a(GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn) { - return this.a(new BlockPosition(this.locX, this.getBoundingBox().minY, this.locZ), (IWorldReader) generatoraccess) >= 0.0F; - } - - public boolean dT() { - return !this.getNavigation().n(); - } - - @Override - protected void dM() { - super.dM(); - Entity entity = this.getLeashHolder(); - - if (entity != null && entity.world == this.world) { - this.a(new BlockPosition(entity), 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; - } - - this.u(f); - if (f > 10.0F) { - this.world.getServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), EntityUnleashEvent.UnleashReason.DISTANCE)); // CraftBukkit - this.unleash(true, true); - this.goalSelector.a(PathfinderGoal.Type.MOVE); - } else 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.setMot(this.getMot().add(Math.copySign(d0 * d0 * 0.4D, d0), Math.copySign(d1 * d1 * 0.4D, d1), Math.copySign(d2 * d2 * 0.4D, d2))); - } else { - this.goalSelector.b(PathfinderGoal.Type.MOVE); - float f1 = 2.0F; - Vec3D vec3d = (new Vec3D(entity.locX - this.locX, entity.locY - this.locY, entity.locZ - this.locZ)).d().a((double) Math.max(f - 2.0F, 0.0F)); - - this.getNavigation().a(this.locX + vec3d.x, this.locY + vec3d.y, this.locZ + vec3d.z, this.dU()); - } - } - - } - - protected double dU() { - return 1.0D; - } - - protected void u(float f) {} -} diff --git a/src/main/java/net/minecraft/server/EntityCreeper.java b/src/main/java/net/minecraft/server/EntityCreeper.java deleted file mode 100644 index bcb727630..000000000 --- a/src/main/java/net/minecraft/server/EntityCreeper.java +++ /dev/null @@ -1,278 +0,0 @@ -package net.minecraft.server; - -import java.util.Collection; -import java.util.Iterator; -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.ExplosionPrimeEvent; -// CraftBukkit end - -public class EntityCreeper extends EntityMonster { - - private static final DataWatcherObject b = DataWatcher.a(EntityCreeper.class, DataWatcherRegistry.b); - private static final DataWatcherObject POWERED = DataWatcher.a(EntityCreeper.class, DataWatcherRegistry.i); - private static final DataWatcherObject d = DataWatcher.a(EntityCreeper.class, DataWatcherRegistry.i); private static final DataWatcherObject isIgnitedDW = d; // Paper OBFHELPER - private int bz; - public int fuseTicks; // Paper - public - public int maxFuseTicks = 30; - public int explosionRadius = 3; - private int bD; - - public EntityCreeper(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - 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(3, new PathfinderGoalAvoidTarget<>(this, EntityCat.class, 6.0F, 1.0D, 1.2D)); - this.goalSelector.a(4, new PathfinderGoalMeleeAttack(this, 1.0D, false)); - this.goalSelector.a(5, new PathfinderGoalRandomStrollLand(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, new Class[0])); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); - } - - @Override - public int bv() { - return this.getGoalTarget() == null ? 3 : 3 + (int) (this.getHealth() - 1.0F); - } - - @Override - public void b(float f, float f1) { - super.b(f, f1); - this.fuseTicks = (int) ((float) this.fuseTicks + f * 1.5F); - if (this.fuseTicks > this.maxFuseTicks - 5) { - this.fuseTicks = this.maxFuseTicks - 5; - } - - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityCreeper.b, -1); - this.datawatcher.register(EntityCreeper.POWERED, false); - this.datawatcher.register(EntityCreeper.d, false); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - if ((Boolean) this.datawatcher.get(EntityCreeper.POWERED)) { - nbttagcompound.setBoolean("powered", true); - } - - nbttagcompound.setShort("Fuse", (short) this.maxFuseTicks); - nbttagcompound.setByte("ExplosionRadius", (byte) this.explosionRadius); - nbttagcompound.setBoolean("ignited", this.isIgnited()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.datawatcher.set(EntityCreeper.POWERED, nbttagcompound.getBoolean("powered")); - 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.ignite(); - } - - } - - @Override - public void tick() { - if (this.isAlive()) { - this.bz = this.fuseTicks; - if (this.isIgnited()) { - this.a(1); - } - - int i = this.dV(); - - if (i > 0 && this.fuseTicks == 0) { - this.a(SoundEffects.ENTITY_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.explode(); - } - } - - super.tick(); - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_CREEPER_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_CREEPER_DEATH; - } - - @Override - protected void dropDeathLoot(DamageSource damagesource, int i, boolean flag) { - super.dropDeathLoot(damagesource, i, flag); - Entity entity = damagesource.getEntity(); - - if (entity != this && entity instanceof EntityCreeper) { - EntityCreeper entitycreeper = (EntityCreeper) entity; - - if (entitycreeper.canCauseHeadDrop()) { - entitycreeper.setCausedHeadDrop(); - this.a((IMaterial) Items.CREEPER_HEAD); - } - } - - } - - @Override - public boolean C(Entity entity) { - return true; - } - - public boolean isPowered() { - return (Boolean) this.datawatcher.get(EntityCreeper.POWERED); - } - - public int dV() { - return (Integer) this.datawatcher.get(EntityCreeper.b); - } - - public void a(int i) { - this.datawatcher.set(EntityCreeper.b, i); - } - - @Override - 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); - } - - public void setPowered(boolean powered) { - this.datawatcher.set(EntityCreeper.POWERED, powered); - } - // CraftBukkit end - - @Override - protected boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() == Items.FLINT_AND_STEEL) { - this.world.playSound(entityhuman, this.locX, this.locY, this.locZ, SoundEffects.ITEM_FLINTANDSTEEL_USE, this.getSoundCategory(), 1.0F, this.random.nextFloat() * 0.4F + 0.8F); - entityhuman.a(enumhand); - if (!this.world.isClientSide) { - this.ignite(); - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(enumhand); - }); - return true; - } - } - - return super.a(entityhuman, enumhand); - } - - public void explode() { - if (!this.world.isClientSide) { - Explosion.Effect explosion_effect = this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) ? Explosion.Effect.DESTROY : Explosion.Effect.NONE; - float f = this.isPowered() ? 2.0F : 1.0F; - - // CraftBukkit start - ExplosionPrimeEvent event = new ExplosionPrimeEvent(this.getBukkitEntity(), this.explosionRadius * f, false); - this.world.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - this.killed = true; - this.world.createExplosion(this, this.locX, this.locY, this.locZ, event.getRadius(), event.getFire(), explosion_effect); - this.die(); - this.createEffectCloud(); - } else { - fuseTicks = 0; - this.datawatcher.set(isIgnitedDW, Boolean.valueOf(false)); // Paper - } - // CraftBukkit end - } - - } - - private void createEffectCloud() { - Collection collection = this.getEffects(); - - if (!collection.isEmpty() && !world.paperConfig.disableCreeperLingeringEffect) { // Paper - EntityAreaEffectCloud entityareaeffectcloud = new EntityAreaEffectCloud(this.world, this.locX, this.locY, this.locZ); - - entityareaeffectcloud.setSource(this); // CraftBukkit - entityareaeffectcloud.setRadius(2.5F); - entityareaeffectcloud.setRadiusOnUse(-0.5F); - entityareaeffectcloud.setWaitTime(10); - entityareaeffectcloud.setDuration(entityareaeffectcloud.getDuration() / 2); - entityareaeffectcloud.setRadiusPerTick(-entityareaeffectcloud.getRadius() / (float) entityareaeffectcloud.getDuration()); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - entityareaeffectcloud.addEffect(new MobEffect(mobeffect)); - } - - this.world.addEntity(entityareaeffectcloud, CreatureSpawnEvent.SpawnReason.EXPLOSION); // CraftBukkit - } - - } - - public boolean isIgnited() { - return (Boolean) this.datawatcher.get(EntityCreeper.d); - } - - public void ignite() { - // Paper start - setIgnited(true); - } - - public void setIgnited(boolean ignited) { - if (isIgnited() != ignited) { - com.destroystokyo.paper.event.entity.CreeperIgniteEvent event = new com.destroystokyo.paper.event.entity.CreeperIgniteEvent((org.bukkit.entity.Creeper) getBukkitEntity(), ignited); - if (event.callEvent()) { - this.datawatcher.set(EntityCreeper.d, event.isIgnited()); - } - } - // Paper end - } - - public boolean canCauseHeadDrop() { - return this.isPowered() && this.bD < 1; - } - - public void setCausedHeadDrop() { - ++this.bD; - } -} diff --git a/src/main/java/net/minecraft/server/EntityDamageSourceIndirect.java b/src/main/java/net/minecraft/server/EntityDamageSourceIndirect.java deleted file mode 100644 index 509fdf135..000000000 --- a/src/main/java/net/minecraft/server/EntityDamageSourceIndirect.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class EntityDamageSourceIndirect extends EntityDamageSource { - - private final Entity owner; - - public EntityDamageSourceIndirect(String s, Entity entity, @Nullable Entity entity1) { - super(s, entity); - this.owner = entity1; - } - - @Nullable - @Override - public Entity j() { - return this.x; - } - - @Nullable - @Override - public Entity getEntity() { - return this.owner; - } - - @Override - public IChatBaseComponent getLocalizedDeathMessage(EntityLiving entityliving) { - IChatBaseComponent ichatbasecomponent = this.owner == null ? this.x.getScoreboardDisplayName() : this.owner.getScoreboardDisplayName(); - ItemStack itemstack = this.owner instanceof EntityLiving ? ((EntityLiving) this.owner).getItemInMainHand() : ItemStack.a; - String s = "death.attack." + this.translationIndex; - String s1 = s + ".item"; - - return !itemstack.isEmpty() && itemstack.hasName() ? new ChatMessage(s1, new Object[]{entityliving.getScoreboardDisplayName(), ichatbasecomponent, itemstack.B()}) : new ChatMessage(s, new Object[]{entityliving.getScoreboardDisplayName(), ichatbasecomponent}); - } - - // CraftBukkit start - public Entity getProximateDamageSource() { - return super.getEntity(); - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/EntityDolphin.java b/src/main/java/net/minecraft/server/EntityDolphin.java deleted file mode 100644 index 063fb7053..000000000 --- a/src/main/java/net/minecraft/server/EntityDolphin.java +++ /dev/null @@ -1,582 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.List; -import java.util.Random; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntityDolphin extends EntityWaterAnimal { - - private static final DataWatcherObject c = DataWatcher.a(EntityDolphin.class, DataWatcherRegistry.l); - private static final DataWatcherObject d = DataWatcher.a(EntityDolphin.class, DataWatcherRegistry.i); - private static final DataWatcherObject bz = DataWatcher.a(EntityDolphin.class, DataWatcherRegistry.b); - private static final PathfinderTargetCondition bA = (new PathfinderTargetCondition()).a(10.0D).b().a().c(); - public static final Predicate b = (entityitem) -> { - return !entityitem.q() && entityitem.isAlive() && entityitem.isInWater(); - }; - - public EntityDolphin(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.moveController = new EntityDolphin.a(this); - this.lookController = new ControllerLookDolphin(this, 10); - this.setCanPickupLoot(true); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.setAirTicks(this.bp()); - this.pitch = 0.0F; - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - @Override - public boolean cm() { - return false; - } - - @Override - protected void a(int i) {} - - public void g(BlockPosition blockposition) { - this.datawatcher.set(EntityDolphin.c, blockposition); - } - - public BlockPosition l() { - return (BlockPosition) this.datawatcher.get(EntityDolphin.c); - } - - public boolean dV() { - return (Boolean) this.datawatcher.get(EntityDolphin.d); - } - - public void r(boolean flag) { - this.datawatcher.set(EntityDolphin.d, flag); - } - - public int dW() { - return (Integer) this.datawatcher.get(EntityDolphin.bz); - } - - public void b(int i) { - this.datawatcher.set(EntityDolphin.bz, i); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityDolphin.c, BlockPosition.ZERO); - this.datawatcher.register(EntityDolphin.d, false); - this.datawatcher.register(EntityDolphin.bz, 2400); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("TreasurePosX", this.l().getX()); - nbttagcompound.setInt("TreasurePosY", this.l().getY()); - nbttagcompound.setInt("TreasurePosZ", this.l().getZ()); - nbttagcompound.setBoolean("GotFish", this.dV()); - nbttagcompound.setInt("Moistness", this.dW()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - int i = nbttagcompound.getInt("TreasurePosX"); - int j = nbttagcompound.getInt("TreasurePosY"); - int k = nbttagcompound.getInt("TreasurePosZ"); - - this.g(new BlockPosition(i, j, k)); - super.a(nbttagcompound); - this.r(nbttagcompound.getBoolean("GotFish")); - this.b(nbttagcompound.getInt("Moistness")); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(0, new PathfinderGoalBreath(this)); - this.goalSelector.a(0, new PathfinderGoalWater(this)); - this.goalSelector.a(1, new EntityDolphin.b(this)); - this.goalSelector.a(2, new EntityDolphin.c(this, 4.0D)); - this.goalSelector.a(4, new PathfinderGoalRandomSwim(this, 1.0D, 10)); - this.goalSelector.a(4, new PathfinderGoalRandomLookaround(this)); - this.goalSelector.a(5, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); - this.goalSelector.a(5, new PathfinderGoalWaterJump(this, 10)); - this.goalSelector.a(6, new PathfinderGoalMeleeAttack(this, 1.2000000476837158D, true)); - this.goalSelector.a(8, new EntityDolphin.d()); - this.goalSelector.a(8, new PathfinderGoalFollowBoat(this)); - this.goalSelector.a(9, new PathfinderGoalAvoidTarget<>(this, EntityGuardian.class, 8.0F, 1.0D, 1.0D)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[]{EntityGuardian.class})).a(new Class[0])); // CraftBukkit - decompile error - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(1.2000000476837158D); - this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(3.0D); - } - - @Override - protected NavigationAbstract b(World world) { - return new NavigationGuardian(this, world); - } - - @Override - public boolean C(Entity entity) { - boolean flag = entity.damageEntity(DamageSource.mobAttack(this), (float) ((int) this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue())); - - if (flag) { - this.a((EntityLiving) this, entity); - this.a(SoundEffects.ENTITY_DOLPHIN_ATTACK, 1.0F, 1.0F); - } - - return flag; - } - - @Override - public int bp() { - return 4800; - } - - @Override - protected int m(int i) { - return this.bp(); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 0.3F; - } - - @Override - public int M() { - return 1; - } - - @Override - public int dA() { - return 1; - } - - @Override - protected boolean n(Entity entity) { - return true; - } - - @Override - public boolean e(ItemStack itemstack) { - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - - return !this.getEquipment(enumitemslot).isEmpty() ? false : enumitemslot == EnumItemSlot.MAINHAND && super.e(itemstack); - } - - @Override - protected void a(EntityItem entityitem) { - if (this.getEquipment(EnumItemSlot.MAINHAND).isEmpty()) { - ItemStack itemstack = entityitem.getItemStack(); - - if (this.g(itemstack)) { - // CraftBukkit start - call EntityPickupItemEvent - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityPickupItemEvent(this, entityitem, 0, false).isCancelled()) { - return; - } - // CraftBukkit end - this.setSlot(EnumItemSlot.MAINHAND, itemstack); - this.dropChanceHand[EnumItemSlot.MAINHAND.b()] = 2.0F; - this.receive(entityitem, itemstack.getCount()); - entityitem.die(); - } - } - - } - - @Override - public void tick() { - super.tick(); - if (!this.isNoAI()) { - if (this.au()) { - this.b(2400); - } else { - this.b(this.dW() - 1); - if (this.dW() <= 0) { - this.damageEntity(DamageSource.DRYOUT, 1.0F); - } - - if (this.onGround) { - this.setMot(this.getMot().add((double) ((this.random.nextFloat() * 2.0F - 1.0F) * 0.2F), 0.5D, (double) ((this.random.nextFloat() * 2.0F - 1.0F) * 0.2F))); - this.yaw = this.random.nextFloat() * 360.0F; - this.onGround = false; - this.impulse = true; - } - } - - if (this.world.isClientSide && this.isInWater() && this.getMot().g() > 0.03D) { - Vec3D vec3d = this.f(0.0F); - float f = MathHelper.cos(this.yaw * 0.017453292F) * 0.3F; - float f1 = MathHelper.sin(this.yaw * 0.017453292F) * 0.3F; - float f2 = 1.2F - this.random.nextFloat() * 0.7F; - - for (int i = 0; i < 2; ++i) { - this.world.addParticle(Particles.DOLPHIN, this.locX - vec3d.x * (double) f2 + (double) f, this.locY - vec3d.y, this.locZ - vec3d.z * (double) f2 + (double) f1, 0.0D, 0.0D, 0.0D); - this.world.addParticle(Particles.DOLPHIN, this.locX - vec3d.x * (double) f2 - (double) f, this.locY - vec3d.y, this.locZ - vec3d.z * (double) f2 - (double) f1, 0.0D, 0.0D, 0.0D); - } - } - - } - } - - @Override - protected boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (!itemstack.isEmpty() && itemstack.getItem().a(TagsItem.FISHES)) { - if (!this.world.isClientSide) { - this.a(SoundEffects.ENTITY_DOLPHIN_EAT, 1.0F, 1.0F); - } - - this.r(true); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - return true; - } else { - return super.a(entityhuman, enumhand); - } - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return blockposition.getY() > 45 && blockposition.getY() < generatoraccess.getSeaLevel() && (generatoraccess.getBiome(blockposition) != Biomes.OCEAN || generatoraccess.getBiome(blockposition) != Biomes.DEEP_OCEAN) && generatoraccess.getFluid(blockposition).a(TagsFluid.WATER); - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_DOLPHIN_HURT; - } - - @Nullable - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_DOLPHIN_DEATH; - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - return this.isInWater() ? SoundEffects.ENTITY_DOLPHIN_AMBIENT_WATER : SoundEffects.ENTITY_DOLPHIN_AMBIENT; - } - - @Override - protected SoundEffect getSoundSplash() { - return SoundEffects.ENTITY_DOLPHIN_SPLASH; - } - - @Override - protected SoundEffect getSoundSwim() { - return SoundEffects.ENTITY_DOLPHIN_SWIM; - } - - protected boolean dX() { - BlockPosition blockposition = this.getNavigation().h(); - - return blockposition != null ? blockposition.a((IPosition) this.getPositionVector(), 12.0D) : false; - } - - @Override - public void e(Vec3D vec3d) { - if (this.df() && this.isInWater()) { - this.a(this.db(), vec3d); - this.move(EnumMoveType.SELF, this.getMot()); - this.setMot(this.getMot().a(0.9D)); - if (this.getGoalTarget() == null) { - this.setMot(this.getMot().add(0.0D, -0.005D, 0.0D)); - } - } else { - super.e(vec3d); - } - - } - - @Override - public boolean a(EntityHuman entityhuman) { - return true; - } - - static class b extends PathfinderGoal { - - private final EntityDolphin a; - private boolean b; - - b(EntityDolphin entitydolphin) { - this.a = entitydolphin; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean C_() { - return false; - } - - @Override - public boolean a() { - return this.a.dV() && this.a.getAirTicks() >= 100; - } - - @Override - public boolean b() { - BlockPosition blockposition = this.a.l(); - - return !(new BlockPosition((double) blockposition.getX(), this.a.locY, (double) blockposition.getZ())).a((IPosition) this.a.getPositionVector(), 4.0D) && !this.b && this.a.getAirTicks() >= 100; - } - - @Override - public void c() { - this.b = false; - this.a.getNavigation().o(); - World world = this.a.world; - BlockPosition blockposition = new BlockPosition(this.a); - String s = (double) world.random.nextFloat() >= 0.5D ? "Ocean_Ruin" : "Shipwreck"; - BlockPosition blockposition1 = world.a(s, blockposition, 50, false); - - if (blockposition1 == null) { - BlockPosition blockposition2 = world.a(s.equals("Ocean_Ruin") ? "Shipwreck" : "Ocean_Ruin", blockposition, 50, false); - - if (blockposition2 == null) { - this.b = true; - return; - } - - this.a.g(blockposition2); - } else { - this.a.g(blockposition1); - } - - world.broadcastEntityEffect(this.a, (byte) 38); - } - - @Override - public void d() { - BlockPosition blockposition = this.a.l(); - - if ((new BlockPosition((double) blockposition.getX(), this.a.locY, (double) blockposition.getZ())).a((IPosition) this.a.getPositionVector(), 4.0D) || this.b) { - this.a.r(false); - } - - } - - @Override - public void e() { - BlockPosition blockposition = this.a.l(); - World world = this.a.world; - - if (this.a.dX() || this.a.getNavigation().n()) { - Vec3D vec3d = RandomPositionGenerator.a((EntityCreature) this.a, 16, 1, new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()), 0.39269909262657166D); - - if (vec3d == null) { - vec3d = RandomPositionGenerator.a(this.a, 8, 4, new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ())); - } - - if (vec3d != null) { - BlockPosition blockposition1 = new BlockPosition(vec3d); - - if (!world.getFluid(blockposition1).a(TagsFluid.WATER) || !world.getType(blockposition1).a((IBlockAccess) world, blockposition1, PathMode.WATER)) { - vec3d = RandomPositionGenerator.a(this.a, 8, 5, new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ())); - } - } - - if (vec3d == null) { - this.b = true; - return; - } - - this.a.getControllerLook().a(vec3d.x, vec3d.y, vec3d.z, (float) (this.a.dA() + 20), (float) this.a.M()); - this.a.getNavigation().a(vec3d.x, vec3d.y, vec3d.z, 1.3D); - if (world.random.nextInt(80) == 0) { - world.broadcastEntityEffect(this.a, (byte) 38); - } - } - - } - } - - static class c extends PathfinderGoal { - - private final EntityDolphin a; - private final double b; - private EntityHuman c; - - c(EntityDolphin entitydolphin, double d0) { - this.a = entitydolphin; - this.b = d0; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - this.c = this.a.world.a(EntityDolphin.bA, (EntityLiving) this.a); - return this.c == null ? false : this.c.isSwimming(); - } - - @Override - public boolean b() { - return this.c != null && this.c.isSwimming() && this.a.h((Entity) this.c) < 256.0D; - } - - @Override - public void c() { - this.c.addEffect(new MobEffect(MobEffects.DOLPHINS_GRACE, 100), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.DOLPHIN); // CraftBukkit - } - - @Override - public void d() { - this.c = null; - this.a.getNavigation().o(); - } - - @Override - public void e() { - this.a.getControllerLook().a(this.c, (float) (this.a.dA() + 20), (float) this.a.M()); - if (this.a.h((Entity) this.c) < 6.25D) { - this.a.getNavigation().o(); - } else { - this.a.getNavigation().a((Entity) this.c, this.b); - } - - if (this.c.isSwimming() && this.c.world.random.nextInt(6) == 0) { - this.c.addEffect(new MobEffect(MobEffects.DOLPHINS_GRACE, 100), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.DOLPHIN); // CraftBukkit - } - - } - } - - class d extends PathfinderGoal { - - private int b; - - private d() {} - - @Override - public boolean a() { - if (this.b > EntityDolphin.this.ticksLived) { - return false; - } else { - List list = EntityDolphin.this.world.a(EntityItem.class, EntityDolphin.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityDolphin.b); - - return !list.isEmpty() || !EntityDolphin.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty(); - } - } - - @Override - public void c() { - List list = EntityDolphin.this.world.a(EntityItem.class, EntityDolphin.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityDolphin.b); - - if (!list.isEmpty()) { - EntityDolphin.this.getNavigation().a((Entity) list.get(0), 1.2000000476837158D); - EntityDolphin.this.a(SoundEffects.ENTITY_DOLPHIN_PLAY, 1.0F, 1.0F); - } - - this.b = 0; - } - - @Override - public void d() { - ItemStack itemstack = EntityDolphin.this.getEquipment(EnumItemSlot.MAINHAND); - - if (!itemstack.isEmpty()) { - this.a(itemstack); - EntityDolphin.this.setSlot(EnumItemSlot.MAINHAND, ItemStack.a); - this.b = EntityDolphin.this.ticksLived + EntityDolphin.this.random.nextInt(100); - } - - } - - @Override - public void e() { - List list = EntityDolphin.this.world.a(EntityItem.class, EntityDolphin.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityDolphin.b); - ItemStack itemstack = EntityDolphin.this.getEquipment(EnumItemSlot.MAINHAND); - - if (!itemstack.isEmpty()) { - this.a(itemstack); - EntityDolphin.this.setSlot(EnumItemSlot.MAINHAND, ItemStack.a); - } else if (!list.isEmpty()) { - EntityDolphin.this.getNavigation().a((Entity) list.get(0), 1.2000000476837158D); - } - - } - - private void a(ItemStack itemstack) { - if (!itemstack.isEmpty()) { - double d0 = EntityDolphin.this.locY - 0.30000001192092896D + (double) EntityDolphin.this.getHeadHeight(); - EntityItem entityitem = new EntityItem(EntityDolphin.this.world, EntityDolphin.this.locX, d0, EntityDolphin.this.locZ, itemstack); - - entityitem.setPickupDelay(40); - entityitem.setThrower(EntityDolphin.this.getUniqueID()); - float f = 0.3F; - float f1 = EntityDolphin.this.random.nextFloat() * 6.2831855F; - float f2 = 0.02F * EntityDolphin.this.random.nextFloat(); - - entityitem.setMot((double) (0.3F * -MathHelper.sin(EntityDolphin.this.yaw * 0.017453292F) * MathHelper.cos(EntityDolphin.this.pitch * 0.017453292F) + MathHelper.cos(f1) * f2), (double) (0.3F * MathHelper.sin(EntityDolphin.this.pitch * 0.017453292F) * 1.5F), (double) (0.3F * MathHelper.cos(EntityDolphin.this.yaw * 0.017453292F) * MathHelper.cos(EntityDolphin.this.pitch * 0.017453292F) + MathHelper.sin(f1) * f2)); - EntityDolphin.this.world.addEntity(entityitem); - } - } - } - - static class a extends ControllerMove { - - private final EntityDolphin i; - - public a(EntityDolphin entitydolphin) { - super(entitydolphin); - this.i = entitydolphin; - } - - @Override - public void a() { - if (this.i.isInWater()) { - this.i.setMot(this.i.getMot().add(0.0D, 0.005D, 0.0D)); - } - - if (this.h == ControllerMove.Operation.MOVE_TO && !this.i.getNavigation().n()) { - double d0 = this.b - this.i.locX; - double d1 = this.c - this.i.locY; - double d2 = this.d - this.i.locZ; - double d3 = d0 * d0 + d1 * d1 + d2 * d2; - - if (d3 < 2.500000277905201E-7D) { - this.a.r(0.0F); - } else { - float f = (float) (MathHelper.d(d2, d0) * 57.2957763671875D) - 90.0F; - - this.i.yaw = this.a(this.i.yaw, f, 10.0F); - this.i.aK = this.i.yaw; - this.i.aM = this.i.yaw; - float f1 = (float) (this.e * this.i.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue()); - - if (this.i.isInWater()) { - this.i.o(f1 * 0.02F); - float f2 = -((float) (MathHelper.d(d1, (double) MathHelper.sqrt(d0 * d0 + d2 * d2)) * 57.2957763671875D)); - - f2 = MathHelper.a(MathHelper.g(f2), -85.0F, 85.0F); - this.i.pitch = this.a(this.i.pitch, f2, 5.0F); - float f3 = MathHelper.cos(this.i.pitch * 0.017453292F); - float f4 = MathHelper.sin(this.i.pitch * 0.017453292F); - - this.i.bd = f3 * f1; - this.i.bc = -f4 * f1; - } else { - this.i.o(f1 * 0.1F); - } - - } - } else { - this.i.o(0.0F); - this.i.t(0.0F); - this.i.s(0.0F); - this.i.r(0.0F); - } - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityDragonFireball.java b/src/main/java/net/minecraft/server/EntityDragonFireball.java deleted file mode 100644 index 547698a2d..000000000 --- a/src/main/java/net/minecraft/server/EntityDragonFireball.java +++ /dev/null @@ -1,72 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; - -public class EntityDragonFireball extends EntityFireball { - - public EntityDragonFireball(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityDragonFireball(World world, EntityLiving entityliving, double d0, double d1, double d2) { - super(EntityTypes.DRAGON_FIREBALL, entityliving, d0, d1, d2, world); - } - - @Override - protected void a(MovingObjectPosition movingobjectposition) { - if (movingobjectposition.getType() != MovingObjectPosition.EnumMovingObjectType.ENTITY || !((MovingObjectPositionEntity) movingobjectposition).getEntity().s(this.shooter)) { - if (!this.world.isClientSide) { - List list = this.world.a(EntityLiving.class, this.getBoundingBox().grow(4.0D, 2.0D, 4.0D)); - EntityAreaEffectCloud entityareaeffectcloud = new EntityAreaEffectCloud(this.world, this.locX, this.locY, this.locZ); - - entityareaeffectcloud.setSource(this.shooter); - entityareaeffectcloud.setParticle(Particles.DRAGON_BREATH); - entityareaeffectcloud.setRadius(3.0F); - entityareaeffectcloud.setDuration(600); - entityareaeffectcloud.setRadiusPerTick((7.0F - entityareaeffectcloud.getRadius()) / (float) entityareaeffectcloud.getDuration()); - entityareaeffectcloud.addEffect(new MobEffect(MobEffects.HARM, 1, 1)); - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityLiving entityliving = (EntityLiving) iterator.next(); - double d0 = this.h(entityliving); - - if (d0 < 16.0D) { - entityareaeffectcloud.setPosition(entityliving.locX, entityliving.locY, entityliving.locZ); - break; - } - } - } - - if (new com.destroystokyo.paper.event.entity.EnderDragonFireballHitEvent((org.bukkit.entity.DragonFireball) this.getBukkitEntity(), list.stream().map(EntityLiving::getBukkitLivingEntity).collect(java.util.stream.Collectors.toList()), (org.bukkit.entity.AreaEffectCloud) entityareaeffectcloud.getBukkitEntity()).callEvent()) { // Paper - this.world.triggerEffect(2006, new BlockPosition(this.locX, this.locY, this.locZ), 0); - this.world.addEntity(entityareaeffectcloud); - } else entityareaeffectcloud.die(); // Paper - this.die(); - } - - } - } - - @Override - public boolean isInteractable() { - return false; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - return false; - } - - @Override - protected ParticleParam i() { - return Particles.DRAGON_BREATH; - } - - @Override - protected boolean K_() { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/EntityDrowned.java b/src/main/java/net/minecraft/server/EntityDrowned.java deleted file mode 100644 index 6f0094e6d..000000000 --- a/src/main/java/net/minecraft/server/EntityDrowned.java +++ /dev/null @@ -1,452 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Random; -import javax.annotation.Nullable; - -public class EntityDrowned extends EntityZombie implements IRangedEntity { - - private boolean bz; - protected final NavigationGuardian b; - protected final Navigation c; - - public EntityDrowned(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.K = 1.0F; - this.moveController = new EntityDrowned.d(this); - this.a(PathType.WATER, 0.0F); - this.b = new NavigationGuardian(this, world); - this.c = new Navigation(this, world); - } - - @Override - protected void l() { - this.goalSelector.a(1, new EntityDrowned.c(this, 1.0D)); - this.goalSelector.a(2, new EntityDrowned.f(this, 1.0D, 40, 10.0F)); - this.goalSelector.a(2, new EntityDrowned.a(this, 1.0D, false)); - this.goalSelector.a(5, new EntityDrowned.b(this, 1.0D)); - this.goalSelector.a(6, new EntityDrowned.e(this, 1.0D, this.world.getSeaLevel())); - this.goalSelector.a(7, new PathfinderGoalRandomStroll(this, 1.0D)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[]{EntityDrowned.class})).a(EntityPigZombie.class)); - this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, 10, true, false, this::h)); - if ( world.spigotConfig.zombieAggressiveTowardsVillager ) this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityVillagerAbstract.class, false)); // Paper - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); - this.targetSelector.a(5, new PathfinderGoalNearestAttackableTarget<>(this, EntityTurtle.class, 10, true, false, EntityTurtle.bz)); - } - - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - groupdataentity = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - if (this.getEquipment(EnumItemSlot.OFFHAND).isEmpty() && this.random.nextFloat() < 0.03F) { - this.setSlot(EnumItemSlot.OFFHAND, new ItemStack(Items.NAUTILUS_SHELL)); - this.dropChanceHand[EnumItemSlot.OFFHAND.b()] = 2.0F; - } - - return groupdataentity; - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - BiomeBase biomebase = generatoraccess.getBiome(blockposition); - boolean flag = generatoraccess.getDifficulty() != EnumDifficulty.PEACEFUL && a(generatoraccess, blockposition, random) && (enummobspawn == EnumMobSpawn.SPAWNER || generatoraccess.getFluid(blockposition).a(TagsFluid.WATER)); - - return biomebase != Biomes.RIVER && biomebase != Biomes.FROZEN_RIVER ? random.nextInt(40) == 0 && a(generatoraccess, blockposition) && flag : random.nextInt(15) == 0 && flag; - } - - private static boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - return blockposition.getY() < generatoraccess.getSeaLevel() - 5; - } - - @Override - protected boolean dV() { - return false; - } - - @Override - protected SoundEffect getSoundAmbient() { - return this.isInWater() ? SoundEffects.ENTITY_DROWNED_AMBIENT_WATER : SoundEffects.ENTITY_DROWNED_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return this.isInWater() ? SoundEffects.ENTITY_DROWNED_HURT_WATER : SoundEffects.ENTITY_DROWNED_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return this.isInWater() ? SoundEffects.ENTITY_DROWNED_DEATH_WATER : SoundEffects.ENTITY_DROWNED_DEATH; - } - - @Override - protected SoundEffect getSoundStep() { - return SoundEffects.ENTITY_DROWNED_STEP; - } - - @Override - protected SoundEffect getSoundSwim() { - return SoundEffects.ENTITY_DROWNED_SWIM; - } - - @Override - protected ItemStack dX() { - return ItemStack.a; - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - if ((double) this.random.nextFloat() > 0.9D) { - int i = this.random.nextInt(16); - - if (i < 10) { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.TRIDENT)); - } else { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.FISHING_ROD)); - } - } - - } - - @Override - protected boolean a(ItemStack itemstack, ItemStack itemstack1, EnumItemSlot enumitemslot) { - return itemstack1.getItem() == Items.NAUTILUS_SHELL ? false : (itemstack1.getItem() == Items.TRIDENT ? (itemstack.getItem() == Items.TRIDENT ? itemstack.getDamage() < itemstack1.getDamage() : false) : (itemstack.getItem() == Items.TRIDENT ? true : super.a(itemstack, itemstack1, enumitemslot))); - } - - @Override - protected boolean dY() { - return false; - } - - @Override - public boolean a(IWorldReader iworldreader) { - return iworldreader.i(this); - } - - public boolean h(@Nullable EntityLiving entityliving) { - return entityliving != null ? !this.world.J() || entityliving.isInWater() : false; - } - - @Override - public boolean bE() { - return !this.isSwimming(); - } - - private boolean ee() { - if (this.bz) { - return true; - } else { - EntityLiving entityliving = this.getGoalTarget(); - - return entityliving != null && entityliving.isInWater(); - } - } - - @Override - public void e(Vec3D vec3d) { - if (this.df() && this.isInWater() && this.ee()) { - this.a(0.01F, vec3d); - this.move(EnumMoveType.SELF, this.getMot()); - this.setMot(this.getMot().a(0.9D)); - } else { - super.e(vec3d); - } - - } - - @Override - public void ax() { - if (!this.world.isClientSide) { - if (this.df() && this.isInWater() && this.ee()) { - this.navigation = this.b; - this.setSwimming(true); - } else { - this.navigation = this.c; - this.setSwimming(false); - } - } - - } - - protected boolean dZ() { - PathEntity pathentity = this.getNavigation().l(); - - if (pathentity != null) { - BlockPosition blockposition = pathentity.k(); - - if (blockposition != null) { - double d0 = this.e((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()); - - if (d0 < 4.0D) { - return true; - } - } - } - - return false; - } - - @Override - public void a(EntityLiving entityliving, float f) { - EntityThrownTrident entitythrowntrident = new EntityThrownTrident(this.world, this, new ItemStack(Items.TRIDENT)); - double d0 = entityliving.locX - this.locX; - double d1 = entityliving.getBoundingBox().minY + (double) (entityliving.getHeight() / 3.0F) - entitythrowntrident.locY; - double d2 = entityliving.locZ - this.locZ; - double d3 = (double) MathHelper.sqrt(d0 * d0 + d2 * d2); - - entitythrowntrident.shoot(d0, d1 + d3 * 0.20000000298023224D, d2, 1.6F, (float) (14 - this.world.getDifficulty().a() * 4)); - this.a(SoundEffects.ENTITY_DROWNED_SHOOT, 1.0F, 1.0F / (this.getRandom().nextFloat() * 0.4F + 0.8F)); - this.world.addEntity(entitythrowntrident); - } - - public void r(boolean flag) { - this.bz = flag; - } - - static class d extends ControllerMove { - - private final EntityDrowned i; - - public d(EntityDrowned entitydrowned) { - super(entitydrowned); - this.i = entitydrowned; - } - - @Override - public void a() { - EntityLiving entityliving = this.i.getGoalTarget(); - - if (this.i.ee() && this.i.isInWater()) { - if (entityliving != null && entityliving.locY > this.i.locY || this.i.bz) { - this.i.setMot(this.i.getMot().add(0.0D, 0.002D, 0.0D)); - } - - if (this.h != ControllerMove.Operation.MOVE_TO || this.i.getNavigation().n()) { - this.i.o(0.0F); - return; - } - - double d0 = this.b - this.i.locX; - double d1 = this.c - this.i.locY; - double d2 = this.d - this.i.locZ; - double d3 = (double) MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); - - d1 /= d3; - float f = (float) (MathHelper.d(d2, d0) * 57.2957763671875D) - 90.0F; - - this.i.yaw = this.a(this.i.yaw, f, 90.0F); - this.i.aK = this.i.yaw; - float f1 = (float) (this.e * this.i.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue()); - float f2 = MathHelper.g(0.125F, this.i.db(), f1); - - this.i.o(f2); - this.i.setMot(this.i.getMot().add((double) f2 * d0 * 0.005D, (double) f2 * d1 * 0.1D, (double) f2 * d2 * 0.005D)); - } else { - if (!this.i.onGround) { - this.i.setMot(this.i.getMot().add(0.0D, -0.008D, 0.0D)); - } - - super.a(); - } - - } - } - - static class a extends PathfinderGoalZombieAttack { - - private final EntityDrowned d; - - public a(EntityDrowned entitydrowned, double d0, boolean flag) { - super((EntityZombie) entitydrowned, d0, flag); - this.d = entitydrowned; - } - - @Override - public boolean a() { - return super.a() && this.d.h(this.d.getGoalTarget()); - } - - @Override - public boolean b() { - return super.b() && this.d.h(this.d.getGoalTarget()); - } - } - - static class c extends PathfinderGoal { - - private final EntityCreature a; - private double b; - private double c; - private double d; - private final double e; - private final World f; - - public c(EntityCreature entitycreature, double d0) { - this.a = entitycreature; - this.e = d0; - this.f = entitycreature.world; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - if (!this.f.J()) { - return false; - } else if (this.a.isInWater()) { - return false; - } else { - Vec3D vec3d = this.g(); - - if (vec3d == null) { - return false; - } else { - this.b = vec3d.x; - this.c = vec3d.y; - this.d = vec3d.z; - return true; - } - } - } - - @Override - public boolean b() { - return !this.a.getNavigation().n(); - } - - @Override - public void c() { - this.a.getNavigation().a(this.b, this.c, this.d, this.e); - } - - @Nullable - private Vec3D g() { - Random random = this.a.getRandom(); - BlockPosition blockposition = new BlockPosition(this.a.locX, this.a.getBoundingBox().minY, this.a.locZ); - - for (int i = 0; i < 10; ++i) { - BlockPosition blockposition1 = blockposition.b(random.nextInt(20) - 10, 2 - random.nextInt(8), random.nextInt(20) - 10); - - if (this.f.getType(blockposition1).getBlock() == Blocks.WATER) { - return new Vec3D((double) blockposition1.getX(), (double) blockposition1.getY(), (double) blockposition1.getZ()); - } - } - - return null; - } - } - - static class b extends PathfinderGoalGotoTarget { - - private final EntityDrowned g; - - public b(EntityDrowned entitydrowned, double d0) { - super(entitydrowned, d0, 8, 2); - this.g = entitydrowned; - } - - @Override - public boolean a() { - return super.a() && !this.g.world.J() && this.g.isInWater() && this.g.locY >= (double) (this.g.world.getSeaLevel() - 3); - } - - @Override - public boolean b() { - return super.b(); - } - - @Override - protected boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.up(); - - return iworldreader.isEmpty(blockposition1) && iworldreader.isEmpty(blockposition1.up()) ? iworldreader.getType(blockposition).a((IBlockAccess) iworldreader, blockposition, (Entity) this.g) : false; - } - - @Override - public void c() { - this.g.r(false); - this.g.navigation = this.g.c; - super.c(); - } - - @Override - public void d() { - super.d(); - } - } - - static class e extends PathfinderGoal { - - private final EntityDrowned a; - private final double b; - private final int c; - private boolean d; - - public e(EntityDrowned entitydrowned, double d0, int i) { - this.a = entitydrowned; - this.b = d0; - this.c = i; - } - - @Override - public boolean a() { - return !this.a.world.J() && this.a.isInWater() && this.a.locY < (double) (this.c - 2); - } - - @Override - public boolean b() { - return this.a() && !this.d; - } - - @Override - public void e() { - if (this.a.locY < (double) (this.c - 1) && (this.a.getNavigation().n() || this.a.dZ())) { - Vec3D vec3d = RandomPositionGenerator.a(this.a, 4, 8, new Vec3D(this.a.locX, (double) (this.c - 1), this.a.locZ)); - - if (vec3d == null) { - this.d = true; - return; - } - - this.a.getNavigation().a(vec3d.x, vec3d.y, vec3d.z, this.b); - } - - } - - @Override - public void c() { - this.a.r(true); - this.d = false; - } - - @Override - public void d() { - this.a.r(false); - } - } - - static class f extends PathfinderGoalArrowAttack { - - private final EntityDrowned a; - - public f(IRangedEntity irangedentity, double d0, int i, float f) { - super(irangedentity, d0, i, f); - this.a = (EntityDrowned) irangedentity; - } - - @Override - public boolean a() { - return super.a() && this.a.getItemInMainHand().getItem() == Items.TRIDENT; - } - - @Override - public void c() { - super.c(); - this.a.q(true); - this.a.c(EnumHand.MAIN_HAND); - } - - @Override - public void d() { - super.d(); - this.a.dp(); - this.a.q(false); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityEgg.java b/src/main/java/net/minecraft/server/EntityEgg.java deleted file mode 100644 index aedf2ce17..000000000 --- a/src/main/java/net/minecraft/server/EntityEgg.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -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 EntityProjectileThrowable { - - public EntityEgg(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityEgg(World world, EntityLiving entityliving) { - super(EntityTypes.EGG, entityliving, world); - } - - public EntityEgg(World world, double d0, double d1, double d2) { - super(EntityTypes.EGG, d0, d1, d2, world); - } - - @Override - protected void a(MovingObjectPosition movingobjectposition) { - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - ((MovingObjectPositionEntity) movingobjectposition).getEntity().damageEntity(DamageSource.projectile(this, this.getShooter()), 0.0F); - } - - if (!this.world.isClientSide) { - boolean hatching = this.random.nextInt(8) == 0; // CraftBukkit - if (true) { - byte b0 = 1; - - if (this.random.nextInt(32) == 0) { - b0 = 4; - } - - // CraftBukkit start - if (!hatching) { - b0 = 0; - } - EntityType hatchingType = EntityType.CHICKEN; - - Entity shooter = this.getShooter(); - if (shooter instanceof EntityPlayer) { - PlayerEggThrowEvent event = new PlayerEggThrowEvent((Player) shooter.getBukkitEntity(), (org.bukkit.entity.Egg) this.getBukkitEntity(), hatching, b0, hatchingType); - this.world.getServer().getPluginManager().callEvent(event); - - b0 = event.getNumHatches(); - hatching = event.isHatching(); - hatchingType = event.getHatchingType(); - } - - if (hatching) { - for (int i = 0; i < b0; ++i) { - 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 - } - - this.world.broadcastEntityEffect(this, (byte) 3); - this.die(); - } - - } - - @Override - protected Item i() { - return Items.EGG; - } -} diff --git a/src/main/java/net/minecraft/server/EntityEnderCrystal.java b/src/main/java/net/minecraft/server/EntityEnderCrystal.java deleted file mode 100644 index 801552fc6..000000000 --- a/src/main/java/net/minecraft/server/EntityEnderCrystal.java +++ /dev/null @@ -1,157 +0,0 @@ -package net.minecraft.server; - -import java.util.Optional; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.ExplosionPrimeEvent; -// CraftBukkit end - -public class EntityEnderCrystal extends Entity { - - private static final DataWatcherObject> c = DataWatcher.a(EntityEnderCrystal.class, DataWatcherRegistry.m); - private static final DataWatcherObject d = DataWatcher.a(EntityEnderCrystal.class, DataWatcherRegistry.i); - public int b; - - public EntityEnderCrystal(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.i = true; - this.b = this.random.nextInt(100000); - } - - public EntityEnderCrystal(World world, double d0, double d1, double d2) { - this(EntityTypes.END_CRYSTAL, world); - this.setPosition(d0, d1, d2); - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - protected void initDatawatcher() { - this.getDataWatcher().register(EntityEnderCrystal.c, Optional.empty()); - this.getDataWatcher().register(EntityEnderCrystal.d, true); - } - - @Override - public void tick() { - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - ++this.b; - if (!this.world.isClientSide) { - BlockPosition blockposition = new BlockPosition(this); - - if (this.world.worldProvider instanceof WorldProviderTheEnd && this.world.getType(blockposition).isAir()) { - // CraftBukkit start - if (!CraftEventFactory.callBlockIgniteEvent(this.world, blockposition, this).isCancelled()) { - this.world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); - } - // CraftBukkit end - } - } - - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - if (this.getBeamTarget() != null) { - nbttagcompound.set("BeamTarget", GameProfileSerializer.a(this.getBeamTarget())); - } - - nbttagcompound.setBoolean("ShowBottom", this.isShowingBottom()); - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - if (nbttagcompound.hasKeyOfType("BeamTarget", 10)) { - this.setBeamTarget(GameProfileSerializer.c(nbttagcompound.getCompound("BeamTarget"))); - } - - if (nbttagcompound.hasKeyOfType("ShowBottom", 1)) { - this.setShowingBottom(nbttagcompound.getBoolean("ShowBottom")); - } - - } - - @Override - public boolean isInteractable() { - return true; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (damagesource.getEntity() instanceof EntityEnderDragon) { - return false; - } else { - if (!this.dead && !this.world.isClientSide) { - // CraftBukkit start - All non-living entities need this - if (CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f)) { - return false; - } - // CraftBukkit end - this.die(); - if (!damagesource.isExplosion()) { - // 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(), Explosion.Effect.DESTROY); - // CraftBukkit end - } - - this.a(damagesource); - } - - return true; - } - } - - @Override - public void killEntity() { - this.a(DamageSource.GENERIC); - super.killEntity(); - } - - private void a(DamageSource damagesource) { - if (this.world.worldProvider instanceof WorldProviderTheEnd) { - WorldProviderTheEnd worldprovidertheend = (WorldProviderTheEnd) this.world.worldProvider; - EnderDragonBattle enderdragonbattle = worldprovidertheend.q(); - - if (enderdragonbattle != null) { - enderdragonbattle.a(this, damagesource); - } - } - - } - - public void setBeamTarget(@Nullable BlockPosition blockposition) { - this.getDataWatcher().set(EntityEnderCrystal.c, Optional.ofNullable(blockposition)); - } - - @Nullable - public BlockPosition getBeamTarget() { - return (BlockPosition) ((Optional) this.getDataWatcher().get(EntityEnderCrystal.c)).orElse((Object) null); - } - - public void setShowingBottom(boolean flag) { - this.getDataWatcher().set(EntityEnderCrystal.d, flag); - } - - public boolean isShowingBottom() { - return (Boolean) this.getDataWatcher().get(EntityEnderCrystal.d); - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntityEnderDragon.java b/src/main/java/net/minecraft/server/EntityEnderDragon.java deleted file mode 100644 index c8c74f2b3..000000000 --- a/src/main/java/net/minecraft/server/EntityEnderDragon.java +++ /dev/null @@ -1,951 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -// CraftBukkit start -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.entity.EntityRegainHealthEvent; -// CraftBukkit end -import com.destroystokyo.paper.event.block.TNTPrimeEvent; // Paper - TNTPrimeEvent - -// PAIL: Fixme -public class EntityEnderDragon extends EntityInsentient implements IMonster { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final DataWatcherObject PHASE = DataWatcher.a(EntityEnderDragon.class, DataWatcherRegistry.b); - private static final PathfinderTargetCondition bO = (new PathfinderTargetCondition()).a(64.0D); - public final double[][] c = new double[64][3]; - public int d = -1; - public final EntityComplexPart[] children; - public final EntityComplexPart bA = new EntityComplexPart(this, "head", 1.0F, 1.0F); - public final EntityComplexPart bB = new EntityComplexPart(this, "neck", 3.0F, 3.0F); - public final EntityComplexPart bC = new EntityComplexPart(this, "body", 5.0F, 3.0F); - public final EntityComplexPart bD = new EntityComplexPart(this, "tail", 2.0F, 2.0F); - public final EntityComplexPart bE = new EntityComplexPart(this, "tail", 2.0F, 2.0F); - public final EntityComplexPart bF = new EntityComplexPart(this, "tail", 2.0F, 2.0F); - public final EntityComplexPart bG = new EntityComplexPart(this, "wing", 4.0F, 2.0F); - public final EntityComplexPart bH = new EntityComplexPart(this, "wing", 4.0F, 2.0F); - public float bI; - public float bJ; - public boolean bK; - public int bL; - public EntityEnderCrystal currentEnderCrystal; - private final EnderDragonBattle bP; - private final DragonControllerManager bQ; - private int bR = 100; - private int bS; - private final PathPoint[] bT = new PathPoint[24]; - private final int[] bU = new int[24]; - private final Path bV = new Path(); - private Explosion explosionSource = new Explosion(null, this, Double.NaN, Double.NaN, Double.NaN, Float.NaN, true, Explosion.Effect.DESTROY); // CraftBukkit - reusable source for CraftTNTPrimed.getSource() - - public EntityEnderDragon(EntityTypes entitytypes, World world) { - super(EntityTypes.ENDER_DRAGON, world); - this.children = new EntityComplexPart[]{this.bA, this.bB, this.bC, this.bD, this.bE, this.bF, this.bG, this.bH}; - this.setHealth(this.getMaxHealth()); - this.noclip = true; - this.af = true; - if (!world.isClientSide && world.worldProvider instanceof WorldProviderTheEnd) { - this.bP = ((WorldProviderTheEnd) world.worldProvider).q(); - } else { - this.bP = null; - } - - this.bQ = new DragonControllerManager(this); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(200.0D); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.getDataWatcher().register(EntityEnderDragon.PHASE, DragonControllerPhase.HOVER.b()); - } - - public double[] a(int i, float f) { - if (this.getHealth() <= 0.0F) { - f = 0.0F; - } - - f = 1.0F - f; - int j = this.d - i & 63; - int k = this.d - i - 1 & 63; - double[] adouble = new double[3]; - double d0 = this.c[j][0]; - double d1 = MathHelper.g(this.c[k][0] - d0); - - adouble[0] = d0 + d1 * (double) f; - d0 = this.c[j][1]; - d1 = this.c[k][1] - d0; - adouble[1] = d0 + d1 * (double) f; - adouble[2] = MathHelper.d((double) f, this.c[j][2], this.c[k][2]); - return adouble; - } - - @Override - public void movementTick() { - float f; - float f1; - - if (this.world.isClientSide) { - this.setHealth(this.getHealth()); - if (!this.isSilent()) { - f = MathHelper.cos(this.bJ * 6.2831855F); - f1 = MathHelper.cos(this.bI * 6.2831855F); - if (f1 <= -0.3F && f >= -0.3F) { - this.world.a(this.locX, this.locY, this.locZ, SoundEffects.ENTITY_ENDER_DRAGON_FLAP, this.getSoundCategory(), 5.0F, 0.8F + this.random.nextFloat() * 0.3F, false); - } - - if (!this.bQ.a().a() && --this.bR < 0) { - this.world.a(this.locX, this.locY, this.locZ, SoundEffects.ENTITY_ENDER_DRAGON_GROWL, this.getSoundCategory(), 2.5F, 0.8F + this.random.nextFloat() * 0.3F, false); - this.bR = 200 + this.random.nextInt(200); - } - } - } - - this.bI = this.bJ; - if (this.getHealth() <= 0.0F) { - f = (this.random.nextFloat() - 0.5F) * 8.0F; - f1 = (this.random.nextFloat() - 0.5F) * 4.0F; - float f2 = (this.random.nextFloat() - 0.5F) * 8.0F; - - this.world.addParticle(Particles.EXPLOSION, this.locX + (double) f, this.locY + 2.0D + (double) f1, this.locZ + (double) f2, 0.0D, 0.0D, 0.0D); - } else { - this.dW(); - Vec3D vec3d = this.getMot(); - - f1 = 0.2F / (MathHelper.sqrt(b(vec3d)) * 10.0F + 1.0F); - f1 *= (float) Math.pow(2.0D, vec3d.y); - if (this.bQ.a().a()) { - this.bJ += 0.1F; - } else if (this.bK) { - this.bJ += f1 * 0.5F; - } else { - this.bJ += f1; - } - - this.yaw = MathHelper.g(this.yaw); - if (this.isNoAI()) { - this.bJ = 0.5F; - } else { - if (this.d < 0) { - for (int i = 0; i < this.c.length; ++i) { - this.c[i][0] = (double) this.yaw; - this.c[i][1] = this.locY; - } - } - - if (++this.d == this.c.length) { - this.d = 0; - } - - this.c[this.d][0] = (double) this.yaw; - this.c[this.d][1] = this.locY; - double d0; - double d1; - double d2; - float f3; - - if (this.world.isClientSide) { - if (this.bf > 0) { - double d3 = this.locX + (this.bg - this.locX) / (double) this.bf; - - d0 = this.locY + (this.bh - this.locY) / (double) this.bf; - d1 = this.locZ + (this.bi - this.locZ) / (double) this.bf; - d2 = MathHelper.g(this.bj - (double) this.yaw); - this.yaw = (float) ((double) this.yaw + d2 / (double) this.bf); - this.pitch = (float) ((double) this.pitch + (this.bk - (double) this.pitch) / (double) this.bf); - --this.bf; - this.setPosition(d3, d0, d1); - this.setYawPitch(this.yaw, this.pitch); - } - - this.bQ.a().b(); - } else { - IDragonController idragoncontroller = this.bQ.a(); - - idragoncontroller.c(); - if (this.bQ.a() != idragoncontroller) { - idragoncontroller = this.bQ.a(); - idragoncontroller.c(); - } - - Vec3D vec3d1 = idragoncontroller.g(); - - if (vec3d1 != null && idragoncontroller.getControllerPhase() != DragonControllerPhase.HOVER) { // CraftBukkit - Don't move when hovering - d0 = vec3d1.x - this.locX; - d1 = vec3d1.y - this.locY; - d2 = vec3d1.z - this.locZ; - double d4 = d0 * d0 + d1 * d1 + d2 * d2; - - f3 = idragoncontroller.f(); - double d5 = (double) MathHelper.sqrt(d0 * d0 + d2 * d2); - - if (d5 > 0.0D) { - d1 = MathHelper.a(d1 / d5, (double) (-f3), (double) f3); - } - - this.setMot(this.getMot().add(0.0D, d1 * 0.01D, 0.0D)); - this.yaw = MathHelper.g(this.yaw); - double d6 = MathHelper.a(MathHelper.g(180.0D - MathHelper.d(d0, d2) * 57.2957763671875D - (double) this.yaw), -50.0D, 50.0D); - Vec3D vec3d2 = vec3d1.a(this.locX, this.locY, this.locZ).d(); - Vec3D vec3d3 = (new Vec3D((double) MathHelper.sin(this.yaw * 0.017453292F), this.getMot().y, (double) (-MathHelper.cos(this.yaw * 0.017453292F)))).d(); - float f4 = Math.max(((float) vec3d3.b(vec3d2) + 0.5F) / 1.5F, 0.0F); - - this.be *= 0.8F; - this.be = (float) ((double) this.be + d6 * (double) idragoncontroller.h()); - this.yaw += this.be * 0.1F; - float f5 = (float) (2.0D / (d4 + 1.0D)); - float f6 = 0.06F; - - this.a(0.06F * (f4 * f5 + (1.0F - f5)), new Vec3D(0.0D, 0.0D, -1.0D)); - if (this.bK) { - this.move(EnumMoveType.SELF, this.getMot().a(0.800000011920929D)); - } else { - this.move(EnumMoveType.SELF, this.getMot()); - } - - Vec3D vec3d4 = this.getMot().d(); - double d7 = 0.8D + 0.15D * (vec3d4.b(vec3d3) + 1.0D) / 2.0D; - - this.setMot(this.getMot().d(d7, 0.9100000262260437D, d7)); - } - } - - this.aK = this.yaw; - Vec3D[] avec3d = new Vec3D[this.children.length]; - - for (int j = 0; j < this.children.length; ++j) { - avec3d[j] = new Vec3D(this.children[j].locX, this.children[j].locY, this.children[j].locZ); - } - - float f7 = (float) (this.a(5, 1.0F)[1] - this.a(10, 1.0F)[1]) * 10.0F * 0.017453292F; - float f8 = MathHelper.cos(f7); - float f9 = MathHelper.sin(f7); - float f10 = this.yaw * 0.017453292F; - float f11 = MathHelper.sin(f10); - float f12 = MathHelper.cos(f10); - - this.bC.tick(); - this.bC.setPositionRotation(this.locX + (double) (f11 * 0.5F), this.locY, this.locZ - (double) (f12 * 0.5F), 0.0F, 0.0F); - this.bG.tick(); - this.bG.setPositionRotation(this.locX + (double) (f12 * 4.5F), this.locY + 2.0D, this.locZ + (double) (f11 * 4.5F), 0.0F, 0.0F); - this.bH.tick(); - this.bH.setPositionRotation(this.locX - (double) (f12 * 4.5F), this.locY + 2.0D, this.locZ - (double) (f11 * 4.5F), 0.0F, 0.0F); - if (!this.world.isClientSide && this.hurtTicks == 0) { - this.a(this.world.getEntities(this, this.bG.getBoundingBox().grow(4.0D, 2.0D, 4.0D).d(0.0D, -2.0D, 0.0D), IEntitySelector.e)); - this.a(this.world.getEntities(this, this.bH.getBoundingBox().grow(4.0D, 2.0D, 4.0D).d(0.0D, -2.0D, 0.0D), IEntitySelector.e)); - this.b(this.world.getEntities(this, this.bA.getBoundingBox().g(1.0D), IEntitySelector.e)); - this.b(this.world.getEntities(this, this.bB.getBoundingBox().g(1.0D), IEntitySelector.e)); - } - - double[] adouble = this.a(5, 1.0F); - float f13 = MathHelper.sin(this.yaw * 0.017453292F - this.be * 0.01F); - float f14 = MathHelper.cos(this.yaw * 0.017453292F - this.be * 0.01F); - - this.bA.tick(); - this.bB.tick(); - f3 = this.v(1.0F); - this.bA.setPositionRotation(this.locX + (double) (f13 * 6.5F * f8), this.locY + (double) f3 + (double) (f9 * 6.5F), this.locZ - (double) (f14 * 6.5F * f8), 0.0F, 0.0F); - this.bB.setPositionRotation(this.locX + (double) (f13 * 5.5F * f8), this.locY + (double) f3 + (double) (f9 * 5.5F), this.locZ - (double) (f14 * 5.5F * f8), 0.0F, 0.0F); - - int k; - - for (k = 0; k < 3; ++k) { - EntityComplexPart entitycomplexpart = null; - - if (k == 0) { - entitycomplexpart = this.bD; - } - - if (k == 1) { - entitycomplexpart = this.bE; - } - - if (k == 2) { - entitycomplexpart = this.bF; - } - - double[] adouble1 = this.a(12 + k * 2, 1.0F); - float f15 = this.yaw * 0.017453292F + this.d(adouble1[0] - adouble[0]) * 0.017453292F; - float f16 = MathHelper.sin(f15); - float f17 = MathHelper.cos(f15); - float f18 = 1.5F; - float f19 = (float) (k + 1) * 2.0F; - - entitycomplexpart.tick(); - entitycomplexpart.setPositionRotation(this.locX - (double) ((f11 * 1.5F + f16 * f19) * f8), this.locY + (adouble1[1] - adouble[1]) - (double) ((f19 + 1.5F) * f9) + 1.5D, this.locZ + (double) ((f12 * 1.5F + f17 * f19) * f8), 0.0F, 0.0F); - } - - if (!this.world.isClientSide) { - this.bK = this.b(this.bA.getBoundingBox()) | this.b(this.bB.getBoundingBox()) | this.b(this.bC.getBoundingBox()); - if (this.bP != null) { - this.bP.b(this); - } - } - - for (k = 0; k < this.children.length; ++k) { - this.children[k].lastX = avec3d[k].x; - this.children[k].lastY = avec3d[k].y; - this.children[k].lastZ = avec3d[k].z; - } - - } - } - } - - private float v(float f) { - double d0; - - if (this.bQ.a().a()) { - d0 = -1.0D; - } else { - double[] adouble = this.a(5, 1.0F); - double[] adouble1 = this.a(0, 1.0F); - - d0 = adouble[1] - adouble1[1]; - } - - return (float) d0; - } - - private void dW() { - if (this.currentEnderCrystal != null) { - if (this.currentEnderCrystal.dead) { - this.currentEnderCrystal = null; - } else if (this.ticksLived % 10 == 0 && this.getHealth() < this.getMaxHealth()) { - // CraftBukkit start - EntityRegainHealthEvent event = new EntityRegainHealthEvent(this.getBukkitEntity(), 1.0F, EntityRegainHealthEvent.RegainReason.ENDER_CRYSTAL); - this.world.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - this.setHealth((float) (this.getHealth() + event.getAmount())); - } - // CraftBukkit end - } - } - - if (this.random.nextInt(10) == 0) { - List list = this.world.a(EntityEnderCrystal.class, this.getBoundingBox().g(32.0D)); - EntityEnderCrystal entityendercrystal = null; - double d0 = Double.MAX_VALUE; - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityEnderCrystal entityendercrystal1 = (EntityEnderCrystal) iterator.next(); - double d1 = entityendercrystal1.h(this); - - if (d1 < d0) { - d0 = d1; - entityendercrystal = entityendercrystal1; - } - } - - this.currentEnderCrystal = entityendercrystal; - } - - } - - private void a(List list) { - double d0 = (this.bC.getBoundingBox().minX + this.bC.getBoundingBox().maxX) / 2.0D; - double d1 = (this.bC.getBoundingBox().minZ + this.bC.getBoundingBox().maxZ) / 2.0D; - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (entity instanceof EntityLiving) { - double d2 = entity.locX - d0; - double d3 = entity.locZ - d1; - double d4 = d2 * d2 + d3 * d3; - - entity.f(d2 / d4 * 4.0D, 0.20000000298023224D, d3 / d4 * 4.0D); - if (!this.bQ.a().a() && ((EntityLiving) entity).ct() < entity.ticksLived - 2) { - entity.damageEntity(DamageSource.mobAttack(this), 5.0F); - this.a((EntityLiving) this, entity); - } - } - } - - } - - private void b(List list) { - for (int i = 0; i < list.size(); ++i) { - Entity entity = (Entity) list.get(i); - - if (entity instanceof EntityLiving) { - entity.damageEntity(DamageSource.mobAttack(this), 10.0F); - this.a((EntityLiving) this, entity); - } - } - - } - - private float d(double d0) { - return (float) MathHelper.g(d0); - } - - private boolean b(AxisAlignedBB axisalignedbb) { - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.floor(axisalignedbb.minY); - int k = MathHelper.floor(axisalignedbb.minZ); - int l = MathHelper.floor(axisalignedbb.maxX); - int i1 = MathHelper.floor(axisalignedbb.maxY); - int j1 = MathHelper.floor(axisalignedbb.maxZ); - boolean flag = false; - boolean flag1 = false; - // CraftBukkit start - Create a list to hold all the destroyed blocks - List destroyedBlocks = new java.util.ArrayList(); - // CraftBukkit end - - for (int k1 = i; k1 <= l; ++k1) { - for (int l1 = j; l1 <= i1; ++l1) { - for (int i2 = k; i2 <= j1; ++i2) { - BlockPosition blockposition = new BlockPosition(k1, l1, i2); - IBlockData iblockdata = this.world.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (!iblockdata.isAir() && iblockdata.getMaterial() != Material.FIRE) { - if (this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) && !TagsBlock.DRAGON_IMMUNE.isTagged(block)) { - // CraftBukkit start - Add blocks to list rather than destroying them - // flag1 = this.world.a(blockposition, false) || flag1; - flag1 = true; - destroyedBlocks.add(CraftBlock.at(world, blockposition)); - // CraftBukkit end - } else { - flag = true; - } - } - } - } - } - - // CraftBukkit start - Set off an EntityExplodeEvent for the dragon exploding all these blocks - // SPIGOT-4882: don't fire event if nothing hit - if (!flag1) { - return flag; - } - - org.bukkit.entity.Entity bukkitEntity = this.getBukkitEntity(); - EntityExplodeEvent event = new EntityExplodeEvent(bukkitEntity, bukkitEntity.getLocation(), destroyedBlocks, 0F); - bukkitEntity.getServer().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.a(new BlockPosition(block.getX(), block.getY(), block.getZ()), false); - } - } else { - for (org.bukkit.block.Block block : event.blockList()) { - org.bukkit.Material blockId = block.getType(); - if (blockId == org.bukkit.Material.AIR) { - continue; - } - - CraftBlock craftBlock = ((CraftBlock) block); - BlockPosition blockposition = craftBlock.getPosition(); - - Block nmsBlock = craftBlock.getNMS().getBlock(); - if (nmsBlock.a(explosionSource)) { - TileEntity tileentity = nmsBlock.isTileEntity() ? this.world.getTileEntity(blockposition) : null; - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder((WorldServer) this.world)).a(this.world.random).set(LootContextParameters.POSITION, blockposition).set(LootContextParameters.TOOL, ItemStack.a).set(LootContextParameters.EXPLOSION_RADIUS, 1.0F / event.getYield()).setOptional(LootContextParameters.BLOCK_ENTITY, tileentity); - - Block.b(craftBlock.getNMS(), loottableinfo_builder); - } - // Paper start - TNTPrimeEvent - org.bukkit.block.Block tntBlock = world.getWorld().getBlockAt(blockposition.x, blockposition.y, blockposition.z); - if(!new TNTPrimeEvent(tntBlock, TNTPrimeEvent.PrimeReason.EXPLOSION, explosionSource.getSource().getBukkitEntity()).callEvent()) - continue; - // Paper end - nmsBlock.wasExploded(world, blockposition, explosionSource); - - this.world.a(blockposition, false); - } - } - // CraftBukkit end - - if (flag1) { - BlockPosition blockposition1 = new BlockPosition(i + this.random.nextInt(l - i + 1), j + this.random.nextInt(i1 - j + 1), k + this.random.nextInt(j1 - k + 1)); - - this.world.triggerEffect(2008, blockposition1, 0); - } - - return flag; - } - - public boolean a(EntityComplexPart entitycomplexpart, DamageSource damagesource, float f) { - f = this.bQ.a().a(damagesource, f); - if (entitycomplexpart != this.bA) { - f = f / 4.0F + Math.min(f, 1.0F); - } - - if (f < 0.01F) { - return false; - } else { - if (damagesource.getEntity() instanceof EntityHuman || damagesource.isExplosion()) { - float f1 = this.getHealth(); - - this.dealDamage(damagesource, f); - if (this.getHealth() <= 0.0F && !this.bQ.a().a()) { - this.setHealth(1.0F); - this.bQ.setControllerPhase(DragonControllerPhase.DYING); - } - - if (this.bQ.a().a()) { - this.bS = (int) ((float) this.bS + (f1 - this.getHealth())); - if ((float) this.bS > 0.25F * this.getMaxHealth()) { - this.bS = 0; - this.bQ.setControllerPhase(DragonControllerPhase.TAKEOFF); - } - } - } - - return true; - } - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (damagesource instanceof EntityDamageSource && ((EntityDamageSource) damagesource).y()) { - this.a(this.bC, damagesource, f); - } - - return false; - } - - protected boolean dealDamage(DamageSource damagesource, float f) { - return super.damageEntity(damagesource, f); - } - - @Override - public void killEntity() { - this.die(); - if (this.bP != null) { - this.bP.b(this); - this.bP.a(this); - } - - } - - @Override - protected void co() { - if (this.bP != null) { - this.bP.b(this); - } - - ++this.bL; - if (this.bL >= 180 && this.bL <= 200) { - float f = (this.random.nextFloat() - 0.5F) * 8.0F; - float f1 = (this.random.nextFloat() - 0.5F) * 4.0F; - float f2 = (this.random.nextFloat() - 0.5F) * 8.0F; - - this.world.addParticle(Particles.EXPLOSION_EMITTER, this.locX + (double) f, this.locY + 2.0D + (double) f1, this.locZ + (double) f2, 0.0D, 0.0D, 0.0D); - } - - boolean flag = this.world.getGameRules().getBoolean(GameRules.DO_MOB_LOOT); - short short0 = 500; - - if (this.bP != null && !this.bP.d()) { - short0 = 12000; - } - - if (!this.world.isClientSide) { - if (this.bL > 150 && this.bL % 5 == 0 && flag) { - this.a(MathHelper.d((float) short0 * 0.08F)); - } - - if (this.bL == 1) { - // CraftBukkit start - Use relative location for far away sounds - // this.world.b(1028, new BlockPosition(this), 0); - // Paper start - int viewDistance = ((WorldServer) this.world).spigotConfig.viewDistance * 16; // Paper - updated to use worlds actual view distance incase we have to uncomment this due to removal of player view distance API - for (EntityPlayer player : ((WorldServer)world).getPlayers()) { - //final int viewDistance = player.getViewDistance(); // TODO apply view distance api patch - // Paper end - 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(1028, new BlockPosition((int) relativeX, (int) this.locY, (int) relativeZ), 0, true)); - } else { - player.playerConnection.sendPacket(new PacketPlayOutWorldEvent(1028, new BlockPosition((int) this.locX, (int) this.locY, (int) this.locZ), 0, true)); - } - } - // CraftBukkit end - } - } - - this.move(EnumMoveType.SELF, new Vec3D(0.0D, 0.10000000149011612D, 0.0D)); - this.yaw += 20.0F; - this.aK = this.yaw; - if (this.bL == 200 && !this.world.isClientSide) { - if (flag) { - this.a(MathHelper.d((float) short0 * 0.2F)); - } - - if (this.bP != null) { - this.bP.a(this); - } - - this.die(); - } - - } - - private void a(int i) { - while (i > 0) { - int j = EntityExperienceOrb.getOrbValue(i); - - i -= j; - this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY, this.locZ, j, org.bukkit.entity.ExperienceOrb.SpawnReason.ENTITY_DEATH, this.killer, this)); // Paper - } - - } - - public int l() { - if (this.bT[0] == null) { - for (int i = 0; i < 24; ++i) { - int j = 5; - int k; - int l; - - if (i < 12) { - k = MathHelper.d(60.0F * MathHelper.cos(2.0F * (-3.1415927F + 0.2617994F * (float) i))); - l = MathHelper.d(60.0F * MathHelper.sin(2.0F * (-3.1415927F + 0.2617994F * (float) i))); - } else { - int i1; - - if (i < 20) { - i1 = i - 12; - k = MathHelper.d(40.0F * MathHelper.cos(2.0F * (-3.1415927F + 0.3926991F * (float) i1))); - l = MathHelper.d(40.0F * MathHelper.sin(2.0F * (-3.1415927F + 0.3926991F * (float) i1))); - j += 10; - } else { - i1 = i - 20; - k = MathHelper.d(20.0F * MathHelper.cos(2.0F * (-3.1415927F + 0.7853982F * (float) i1))); - l = MathHelper.d(20.0F * MathHelper.sin(2.0F * (-3.1415927F + 0.7853982F * (float) i1))); - } - } - - int j1 = Math.max(this.world.getSeaLevel() + 10, this.world.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, new BlockPosition(k, 0, l)).getY() + j); - - this.bT[i] = new PathPoint(k, j1, l); - } - - this.bU[0] = 6146; - this.bU[1] = 8197; - this.bU[2] = 8202; - this.bU[3] = 16404; - this.bU[4] = 32808; - this.bU[5] = 32848; - this.bU[6] = 65696; - this.bU[7] = 131392; - this.bU[8] = 131712; - this.bU[9] = 263424; - this.bU[10] = 526848; - this.bU[11] = 525313; - this.bU[12] = 1581057; - this.bU[13] = 3166214; - this.bU[14] = 2138120; - this.bU[15] = 6373424; - this.bU[16] = 4358208; - this.bU[17] = 12910976; - this.bU[18] = 9044480; - this.bU[19] = 9706496; - this.bU[20] = 15216640; - this.bU[21] = 13688832; - this.bU[22] = 11763712; - this.bU[23] = 8257536; - } - - return this.l(this.locX, this.locY, this.locZ); - } - - public int l(double d0, double d1, double d2) { - float f = 10000.0F; - int i = 0; - PathPoint pathpoint = new PathPoint(MathHelper.floor(d0), MathHelper.floor(d1), MathHelper.floor(d2)); - byte b0 = 0; - - if (this.bP == null || this.bP.c() == 0) { - b0 = 12; - } - - for (int j = b0; j < 24; ++j) { - if (this.bT[j] != null) { - float f1 = this.bT[j].b(pathpoint); - - if (f1 < f) { - f = f1; - i = j; - } - } - } - - return i; - } - - @Nullable - public PathEntity a(int i, int j, @Nullable PathPoint pathpoint) { - PathPoint pathpoint1; - - for (int k = 0; k < 24; ++k) { - pathpoint1 = this.bT[k]; - pathpoint1.i = false; - pathpoint1.g = 0.0F; - pathpoint1.e = 0.0F; - pathpoint1.f = 0.0F; - pathpoint1.h = null; - pathpoint1.d = -1; - } - - PathPoint pathpoint2 = this.bT[i]; - - pathpoint1 = this.bT[j]; - pathpoint2.e = 0.0F; - pathpoint2.f = pathpoint2.a(pathpoint1); - pathpoint2.g = pathpoint2.f; - this.bV.a(); - this.bV.a(pathpoint2); - PathPoint pathpoint3 = pathpoint2; - byte b0 = 0; - - if (this.bP == null || this.bP.c() == 0) { - b0 = 12; - } - - label70: - while (!this.bV.e()) { - PathPoint pathpoint4 = this.bV.c(); - - if (pathpoint4.equals(pathpoint1)) { - if (pathpoint != null) { - pathpoint.h = pathpoint1; - pathpoint1 = pathpoint; - } - - return this.a(pathpoint2, pathpoint1); - } - - if (pathpoint4.a(pathpoint1) < pathpoint3.a(pathpoint1)) { - pathpoint3 = pathpoint4; - } - - pathpoint4.i = true; - int l = 0; - int i1 = 0; - - while (true) { - if (i1 < 24) { - if (this.bT[i1] != pathpoint4) { - ++i1; - continue; - } - - l = i1; - } - - i1 = b0; - - while (true) { - if (i1 >= 24) { - continue label70; - } - - if ((this.bU[l] & 1 << i1) > 0) { - PathPoint pathpoint5 = this.bT[i1]; - - if (!pathpoint5.i) { - float f = pathpoint4.e + pathpoint4.a(pathpoint5); - - if (!pathpoint5.c() || f < pathpoint5.e) { - pathpoint5.h = pathpoint4; - pathpoint5.e = f; - pathpoint5.f = pathpoint5.a(pathpoint1); - if (pathpoint5.c()) { - this.bV.a(pathpoint5, pathpoint5.e + pathpoint5.f); - } else { - pathpoint5.g = pathpoint5.e + pathpoint5.f; - this.bV.a(pathpoint5); - } - } - } - } - - ++i1; - } - } - } - - if (pathpoint3 == pathpoint2) { - return null; - } else { - EntityEnderDragon.LOGGER.debug("Failed to find path from {} to {}", i, j); - if (pathpoint != null) { - pathpoint.h = pathpoint3; - pathpoint3 = pathpoint; - } - - return this.a(pathpoint2, pathpoint3); - } - } - - private PathEntity a(PathPoint pathpoint, PathPoint pathpoint1) { - List list = Lists.newArrayList(); - PathPoint pathpoint2 = pathpoint1; - - list.add(0, pathpoint1); - - while (pathpoint2.h != null) { - pathpoint2 = pathpoint2.h; - list.add(0, pathpoint2); - } - - return new PathEntity(list, new BlockPosition(pathpoint1.a, pathpoint1.b, pathpoint1.c), true); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("DragonPhase", this.bQ.a().getControllerPhase().b()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKey("DragonPhase")) { - this.bQ.setControllerPhase(DragonControllerPhase.getById(nbttagcompound.getInt("DragonPhase"))); - } - - } - - @Override - protected void checkDespawn() {} - - public EntityComplexPart[] dT() { - return this.children; - } - - @Override - public boolean isInteractable() { - return false; - } - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.HOSTILE; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_ENDER_DRAGON_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_ENDER_DRAGON_HURT; - } - - @Override - protected float getSoundVolume() { - return 5.0F; - } - - public Vec3D u(float f) { - IDragonController idragoncontroller = this.bQ.a(); - DragonControllerPhase dragoncontrollerphase = idragoncontroller.getControllerPhase(); - float f1; - Vec3D vec3d; - - if (dragoncontrollerphase != DragonControllerPhase.LANDING && dragoncontrollerphase != DragonControllerPhase.TAKEOFF) { - if (idragoncontroller.a()) { - float f2 = this.pitch; - - f1 = 1.5F; - this.pitch = -45.0F; - vec3d = this.f(f); - this.pitch = f2; - } else { - vec3d = this.f(f); - } - } else { - BlockPosition blockposition = this.world.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, WorldGenEndTrophy.a); - - f1 = Math.max(MathHelper.sqrt(blockposition.a(this.getPositionVector(), true)) / 4.0F, 1.0F); - float f3 = 6.0F / f1; - float f4 = this.pitch; - float f5 = 1.5F; - - this.pitch = -f3 * 1.5F * 5.0F; - vec3d = this.f(f); - this.pitch = f4; - } - - return vec3d; - } - - public void a(EntityEnderCrystal entityendercrystal, BlockPosition blockposition, DamageSource damagesource) { - EntityHuman entityhuman; - - if (damagesource.getEntity() instanceof EntityHuman) { - entityhuman = (EntityHuman) damagesource.getEntity(); - } else { - entityhuman = this.world.a(EntityEnderDragon.bO, (double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()); - } - - if (entityendercrystal == this.currentEnderCrystal) { - this.a(this.bA, DamageSource.b(entityhuman), 10.0F); - } - - this.bQ.a().a(entityendercrystal, blockposition, damagesource, entityhuman); - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityEnderDragon.PHASE.equals(datawatcherobject) && this.world.isClientSide) { - this.bQ.setControllerPhase(DragonControllerPhase.getById((Integer) this.getDataWatcher().get(EntityEnderDragon.PHASE))); - } - - super.a(datawatcherobject); - } - - public DragonControllerManager getDragonControllerManager() { - return this.bQ; - } - - @Nullable - public EnderDragonBattle getEnderDragonBattle() { - return this.bP; - } - - @Override - public boolean addEffect(MobEffect mobeffect) { - return false; - } - - @Override - protected boolean n(Entity entity) { - return false; - } - - @Override - public boolean canPortal() { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/EntityEnderPearl.java b/src/main/java/net/minecraft/server/EntityEnderPearl.java deleted file mode 100644 index c553a92a0..000000000 --- a/src/main/java/net/minecraft/server/EntityEnderPearl.java +++ /dev/null @@ -1,135 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -// CraftBukkit end - -public class EntityEnderPearl extends EntityProjectileThrowable { - - private EntityLiving e; - - public EntityEnderPearl(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityEnderPearl(World world, EntityLiving entityliving) { - super(EntityTypes.ENDER_PEARL, entityliving, world); - this.e = entityliving; - } - - @Override - protected Item i() { - return Items.ENDER_PEARL; - } - - @Override - protected void a(MovingObjectPosition movingobjectposition) { - EntityLiving entityliving = this.getShooter(); - - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - Entity entity = ((MovingObjectPositionEntity) movingobjectposition).getEntity(); - - if (entity == this.e) { - return; - } - - entity.damageEntity(DamageSource.projectile(this, entityliving), 0.0F); - } - - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { - BlockPosition blockposition = ((MovingObjectPositionBlock) movingobjectposition).getBlockPosition(); - TileEntity tileentity = this.world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityEndGateway) { - TileEntityEndGateway tileentityendgateway = (TileEntityEndGateway) tileentity; - - if (entityliving != null) { - if (entityliving instanceof EntityPlayer) { - CriterionTriggers.d.a((EntityPlayer) entityliving, this.world.getType(blockposition)); - } - - tileentityendgateway.a((Entity) entityliving); - this.die(); - return; - } - - tileentityendgateway.a((Entity) this); - return; - } - } - - for (int i = 0; i < 32; ++i) { - this.world.addParticle(Particles.PORTAL, this.locX, this.locY + this.random.nextDouble() * 2.0D, this.locZ, this.random.nextGaussian(), 0.0D, this.random.nextGaussian()); - } - - if (!this.world.isClientSide) { - if (entityliving instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entityliving; - - if (entityplayer.playerConnection.a().isConnected() && entityplayer.world == this.world && !entityplayer.isSleeping()) { - // CraftBukkit start - Fire PlayerTeleportEvent - org.bukkit.craftbukkit.entity.CraftPlayer player = entityplayer.getBukkitEntity(); - org.bukkit.Location location = getBukkitEntity().getLocation(); - location.setPitch(player.getLocation().getPitch()); - location.setYaw(player.getLocation().getYaw()); - - PlayerTeleportEvent teleEvent = new PlayerTeleportEvent(player, player.getLocation(), location, PlayerTeleportEvent.TeleportCause.ENDER_PEARL); - Bukkit.getPluginManager().callEvent(teleEvent); - - if (!teleEvent.isCancelled() && !entityplayer.playerConnection.isDisconnected()) { - if (this.random.nextFloat() < 0.05F && this.world.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING)) { - EntityEndermite entityendermite = (EntityEndermite) EntityTypes.ENDERMITE.a(this.world); - - entityendermite.setPlayerSpawned(true); - entityendermite.setPositionRotation(entityliving.locX, entityliving.locY, entityliving.locZ, entityliving.yaw, entityliving.pitch); - this.world.addEntity(entityendermite, CreatureSpawnEvent.SpawnReason.ENDER_PEARL); - } - - if (entityliving.isPassenger()) { - entityliving.stopRiding(); - } - - entityplayer.playerConnection.teleport(teleEvent.getTo()); - entityliving.fallDistance = 0.0F; - CraftEventFactory.entityDamage = this; - entityliving.damageEntity(DamageSource.FALL, 5.0F); - CraftEventFactory.entityDamage = null; - } - // CraftBukkit end - } - } else if (entityliving != null) { - entityliving.enderTeleportTo(this.locX, this.locY, this.locZ); - entityliving.fallDistance = 0.0F; - } - - this.die(); - } - - } - - @Override - public void tick() { - EntityLiving entityliving = this.getShooter(); - - if (entityliving != null && entityliving instanceof EntityHuman && !entityliving.isAlive()) { - this.die(); - } else { - super.tick(); - } - - } - - @Nullable - @Override - public Entity a(DimensionManager dimensionmanager) { - if (this.shooter.dimension != dimensionmanager) { - this.shooter = null; - } - - return super.a(dimensionmanager); - } -} diff --git a/src/main/java/net/minecraft/server/EntityEnderman.java b/src/main/java/net/minecraft/server/EntityEnderman.java deleted file mode 100644 index a94ed1ae0..000000000 --- a/src/main/java/net/minecraft/server/EntityEnderman.java +++ /dev/null @@ -1,496 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Optional; -import com.destroystokyo.paper.event.entity.EndermanEscapeEvent; // Paper -import java.util.Random; -import java.util.UUID; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntityEnderman extends EntityMonster { - - private static final UUID b = UUID.fromString("020E0DFB-87AE-4653-9556-831010E291A0"); - private static final AttributeModifier c = (new AttributeModifier(EntityEnderman.b, "Attacking speed boost", 0.15000000596046448D, AttributeModifier.Operation.ADDITION)).a(false); - private static final DataWatcherObject> d = DataWatcher.a(EntityEnderman.class, DataWatcherRegistry.h); - private static final DataWatcherObject bz = DataWatcher.a(EntityEnderman.class, DataWatcherRegistry.i); - private static final Predicate bA = (entityliving) -> { - return entityliving instanceof EntityEndermite && ((EntityEndermite) entityliving).isPlayerSpawned(); - }; - private int bB; - private int bC; - - public EntityEnderman(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.K = 1.0F; - this.a(PathType.WATER, -1.0F); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(1, new EntityEnderman.a(this)); - this.goalSelector.a(2, new PathfinderGoalMeleeAttack(this, 1.0D, false)); - this.goalSelector.a(7, new PathfinderGoalRandomStrollLand(this, 1.0D, 0.0F)); - this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); - this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); - this.goalSelector.a(10, new EntityEnderman.PathfinderGoalEndermanPlaceBlock(this)); - this.goalSelector.a(11, new EntityEnderman.PathfinderGoalEndermanPickupBlock(this)); - this.targetSelector.a(1, new EntityEnderman.PathfinderGoalPlayerWhoLookedAtTarget(this)); - this.targetSelector.a(2, new PathfinderGoalHurtByTarget(this, new Class[0])); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityEndermite.class, 10, true, false, EntityEnderman.bA)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).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); - } - - @Override - public void setGoalTarget(@Nullable EntityLiving entityliving) { - // CraftBukkit start - fire event - setGoalTarget(entityliving, org.bukkit.event.entity.EntityTargetEvent.TargetReason.UNKNOWN, true); - } - - // Paper start - private boolean tryEscape(EndermanEscapeEvent.Reason reason) { - return new EndermanEscapeEvent((org.bukkit.craftbukkit.entity.CraftEnderman) this.getBukkitEntity(), reason).callEvent(); - } - // Paper end - - @Override - public boolean setGoalTarget(EntityLiving entityliving, org.bukkit.event.entity.EntityTargetEvent.TargetReason reason, boolean fireEvent) { - if (!super.setGoalTarget(entityliving, reason, fireEvent)) { - return false; - } - entityliving = getGoalTarget(); - // CraftBukkit end - AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); - - if (entityliving == null) { - this.bC = 0; - this.datawatcher.set(EntityEnderman.bz, false); - attributeinstance.removeModifier(EntityEnderman.c); - } else { - this.bC = this.ticksLived; - this.datawatcher.set(EntityEnderman.bz, true); - if (!attributeinstance.a(EntityEnderman.c)) { - attributeinstance.addModifier(EntityEnderman.c); - } - } - return true; - - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityEnderman.d, Optional.empty()); - this.datawatcher.register(EntityEnderman.bz, false); - } - - public void l() { - if (this.ticksLived >= this.bB + 400) { - this.bB = this.ticksLived; - if (!this.isSilent()) { - this.world.a(this.locX, this.locY + (double) this.getHeadHeight(), this.locZ, SoundEffects.ENTITY_ENDERMAN_STARE, this.getSoundCategory(), 2.5F, 1.0F, false); - } - } - - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityEnderman.bz.equals(datawatcherobject) && this.dX() && this.world.isClientSide) { - this.l(); - } - - super.a(datawatcherobject); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - IBlockData iblockdata = this.getCarried(); - - if (iblockdata != null) { - nbttagcompound.set("carriedBlockState", GameProfileSerializer.a(iblockdata)); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - IBlockData iblockdata = null; - - if (nbttagcompound.hasKeyOfType("carriedBlockState", 10)) { - iblockdata = GameProfileSerializer.d(nbttagcompound.getCompound("carriedBlockState")); - if (iblockdata.isAir()) { - iblockdata = null; - } - } - - this.setCarried(iblockdata); - } - - // Paper start - OBFHELPER - ok not really, but verify this on updates - private boolean f(EntityHuman entityhuman) { - boolean shouldAttack = f_real(entityhuman); - com.destroystokyo.paper.event.entity.EndermanAttackPlayerEvent event = new com.destroystokyo.paper.event.entity.EndermanAttackPlayerEvent((org.bukkit.entity.Enderman) getBukkitEntity(), (org.bukkit.entity.Player) entityhuman.getBukkitEntity()); - event.setCancelled(!shouldAttack); - return event.callEvent(); - } - private boolean f_real(EntityHuman entityhuman) { - // Paper end - ItemStack itemstack = (ItemStack) entityhuman.inventory.armor.get(3); - - if (itemstack.getItem() == Blocks.CARVED_PUMPKIN.getItem()) { - return false; - } else { - Vec3D vec3d = entityhuman.f(1.0F).d(); - Vec3D vec3d1 = new Vec3D(this.locX - entityhuman.locX, this.getBoundingBox().minY + (double) this.getHeadHeight() - (entityhuman.locY + (double) entityhuman.getHeadHeight()), this.locZ - entityhuman.locZ); - double d0 = vec3d1.f(); - - vec3d1 = vec3d1.d(); - double d1 = vec3d.b(vec3d1); - - return d1 > 1.0D - 0.025D / d0 ? entityhuman.hasLineOfSight(this) : false; - } - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 2.55F; - } - - @Override - public void movementTick() { - if (this.world.isClientSide) { - for (int i = 0; i < 2; ++i) { - this.world.addParticle(Particles.PORTAL, this.locX + (this.random.nextDouble() - 0.5D) * (double) this.getWidth(), this.locY + this.random.nextDouble() * (double) this.getHeight() - 0.25D, this.locZ + (this.random.nextDouble() - 0.5D) * (double) this.getWidth(), (this.random.nextDouble() - 0.5D) * 2.0D, -this.random.nextDouble(), (this.random.nextDouble() - 0.5D) * 2.0D); - } - } - - this.jumping = false; - super.movementTick(); - } - - @Override - protected void mobTick() { - if (this.au()) { - this.damageEntity(DamageSource.DROWN, 1.0F); - } - - if (this.world.J() && this.ticksLived >= this.bC + 600) { - float f = this.aF(); - - if (f > 0.5F && this.world.f(new BlockPosition(this)) && this.random.nextFloat() * 30.0F < (f - 0.4F) * 2.0F && this.tryEscape(EndermanEscapeEvent.Reason.RUNAWAY)) { // Paper - this.setGoalTarget((EntityLiving) null); - this.dV(); - } - } - - super.mobTick(); - } - - public final boolean teleportRandomly() { return this.dV(); } // Paper - OBFHELPER - protected boolean dV() { - double d0 = this.locX + (this.random.nextDouble() - 0.5D) * 64.0D; - double d1 = this.locY + (double) (this.random.nextInt(64) - 32); - double d2 = this.locZ + (this.random.nextDouble() - 0.5D) * 64.0D; - - return this.l(d0, d1, d2); - } - - private boolean a(Entity entity) { - Vec3D vec3d = new Vec3D(this.locX - entity.locX, this.getBoundingBox().minY + (double) (this.getHeight() / 2.0F) - entity.locY + (double) entity.getHeadHeight(), this.locZ - entity.locZ); - - vec3d = vec3d.d(); - double d0 = 16.0D; - double d1 = this.locX + (this.random.nextDouble() - 0.5D) * 8.0D - vec3d.x * 16.0D; - double d2 = this.locY + (double) (this.random.nextInt(16) - 8) - vec3d.y * 16.0D; - double d3 = this.locZ + (this.random.nextDouble() - 0.5D) * 8.0D - vec3d.z * 16.0D; - - return this.l(d1, d2, d3); - } - - private boolean l(double d0, double d1, double d2) { - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(d0, d1, d2); - - while (blockposition_mutableblockposition.getY() > 0 && !this.world.getType(blockposition_mutableblockposition).getMaterial().isSolid()) { - blockposition_mutableblockposition.c(EnumDirection.DOWN); - } - - if (!this.world.getType(blockposition_mutableblockposition).getMaterial().isSolid()) { - return false; - } else { - boolean flag = this.a(d0, d1, d2, true); - - if (flag) { - this.world.playSound((EntityHuman) null, this.lastX, this.lastY, this.lastZ, SoundEffects.ENTITY_ENDERMAN_TELEPORT, this.getSoundCategory(), 1.0F, 1.0F); - this.a(SoundEffects.ENTITY_ENDERMAN_TELEPORT, 1.0F, 1.0F); - } - - return flag; - } - } - - @Override - protected SoundEffect getSoundAmbient() { - return this.dX() ? SoundEffects.ENTITY_ENDERMAN_SCREAM : SoundEffects.ENTITY_ENDERMAN_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_ENDERMAN_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_ENDERMAN_DEATH; - } - - @Override - protected void dropDeathLoot(DamageSource damagesource, int i, boolean flag) { - super.dropDeathLoot(damagesource, i, flag); - IBlockData iblockdata = this.getCarried(); - - if (iblockdata != null) { - this.a((IMaterial) iblockdata.getBlock()); - } - - } - - public void setCarried(@Nullable IBlockData iblockdata) { - this.datawatcher.set(EntityEnderman.d, Optional.ofNullable(iblockdata)); - } - - @Nullable - public IBlockData getCarried() { - return (IBlockData) ((Optional) this.datawatcher.get(EntityEnderman.d)).orElse((Object) null); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (!(damagesource instanceof EntityDamageSourceIndirect) && damagesource != DamageSource.FIREWORKS) { - boolean flag = super.damageEntity(damagesource, f); - - if (damagesource.ignoresArmor() && this.random.nextInt(10) != 0 && this.tryEscape(damagesource == DamageSource.DROWN ? EndermanEscapeEvent.Reason.DROWN : EndermanEscapeEvent.Reason.CRITICAL_HIT)) { // Paper - this.dV(); - } - - return flag; - } else { - if (this.tryEscape(EndermanEscapeEvent.Reason.INDIRECT)) { // Paper start - for (int i = 0; i < 64; ++i) { - if (this.dV()) { - return true; - } - } - } // Paper end - - return false; - } - } - - public boolean dX() { - return (Boolean) this.datawatcher.get(EntityEnderman.bz); - } - - static class PathfinderGoalEndermanPickupBlock extends PathfinderGoal { - - private final EntityEnderman enderman; - - public PathfinderGoalEndermanPickupBlock(EntityEnderman entityenderman) { - this.enderman = entityenderman; - } - - @Override - public boolean a() { - return this.enderman.getCarried() != null ? false : (!this.enderman.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) ? false : this.enderman.getRandom().nextInt(20) == 0); - } - - @Override - public void e() { - Random random = this.enderman.getRandom(); - 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); - BlockPosition blockposition = new BlockPosition(i, j, k); - IBlockData iblockdata = world.getTypeIfLoaded(blockposition); // Paper - if (iblockdata == null) return; // Paper - Block block = iblockdata.getBlock(); - Vec3D vec3d = new Vec3D((double) MathHelper.floor(this.enderman.locX) + 0.5D, (double) j + 0.5D, (double) MathHelper.floor(this.enderman.locZ) + 0.5D); - Vec3D vec3d1 = new Vec3D((double) i + 0.5D, (double) j + 0.5D, (double) k + 0.5D); - MovingObjectPositionBlock movingobjectpositionblock = world.rayTrace(new RayTrace(vec3d, vec3d1, RayTrace.BlockCollisionOption.COLLIDER, RayTrace.FluidCollisionOption.NONE, this.enderman)); - boolean flag = movingobjectpositionblock.getType() != MovingObjectPosition.EnumMovingObjectType.MISS && movingobjectpositionblock.getBlockPosition().equals(blockposition); - - if (block.a(TagsBlock.ENDERMAN_HOLDABLE) && flag) { - // CraftBukkit start - Pickup event - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.enderman, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { - //this.enderman.setCarried(iblockdata); // Paper - moved down - world.a(blockposition, false); - this.enderman.setCarried(Block.getValidBlockForPosition(iblockdata, this.enderman.world, blockposition)); // Paper - Fix MC-124320 - } - // CraftBukkit end - } - - } - } - - static class PathfinderGoalEndermanPlaceBlock extends PathfinderGoal { - - private EntityEnderman getEnderman() { return this.a; } // Paper - OBFHELPER - private final EntityEnderman a; - - public PathfinderGoalEndermanPlaceBlock(EntityEnderman entityenderman) { - this.a = entityenderman; - } - - @Override - public boolean a() { - return this.a.getCarried() == null ? false : (!this.a.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) ? false : this.a.getRandom().nextInt(2000) == 0); - } - - @Override - public void e() { - Random random = this.a.getRandom(); - 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); - IBlockData iblockdata = world.getTypeIfLoaded(blockposition); // Paper - if (iblockdata == null) return; // Paper - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata1 = world.getType(blockposition1); - IBlockData iblockdata2 = Block.getValidBlockForPosition(getEnderman().getCarried(), getEnderman().world, blockposition); // Paper - Fix MC-124320 - - if (iblockdata2 != null && this.a(world, blockposition, iblockdata2, iblockdata, iblockdata1, blockposition1)) { - // CraftBukkit start - Place event - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.a, blockposition, iblockdata2).isCancelled()) { - world.setTypeAndData(blockposition, iblockdata2, 3); - this.a.setCarried((IBlockData) null); - } - // CraftBukkit end - } - - } - - private boolean a(IWorldReader iworldreader, BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1, IBlockData iblockdata2, BlockPosition blockposition1) { - return iblockdata1.isAir() && !iblockdata2.isAir() && iblockdata2.o(iworldreader, blockposition1) && iblockdata.canPlace(iworldreader, blockposition); - } - } - - static class a extends PathfinderGoal { - - private final EntityEnderman a; - - public a(EntityEnderman entityenderman) { - this.a = entityenderman; - this.a(EnumSet.of(PathfinderGoal.Type.JUMP, PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - EntityLiving entityliving = this.a.getGoalTarget(); - - if (!(entityliving instanceof EntityHuman)) { - return false; - } else { - double d0 = entityliving.h((Entity) this.a); - - return d0 > 256.0D ? false : this.a.f((EntityHuman) entityliving); - } - } - - @Override - public void c() { - this.a.getNavigation().o(); - } - } - - static class PathfinderGoalPlayerWhoLookedAtTarget extends PathfinderGoalNearestAttackableTarget { - - private final EntityEnderman i; public final EntityEnderman getEnderman() { return this.i; } // Paper - OBFHELPER - private EntityHuman j; - private int k; - private int l; - private final PathfinderTargetCondition m; - private final PathfinderTargetCondition n = (new PathfinderTargetCondition()).c(); - - public PathfinderGoalPlayerWhoLookedAtTarget(EntityEnderman entityenderman) { - super(entityenderman, EntityHuman.class, false); - this.i = entityenderman; - this.m = (new PathfinderTargetCondition()).a(this.k()).a((entityliving) -> { - return entityenderman.f((EntityHuman) entityliving); - }); - } - - @Override - public boolean a() { - this.j = this.i.world.a(this.m, (EntityLiving) this.i); - return this.j != null; - } - - @Override - public void c() { - this.k = 5; - this.l = 0; - } - - @Override - public void d() { - this.j = null; - super.d(); - } - - @Override - public boolean b() { - if (this.j != null) { - if (!this.i.f(this.j)) { - return false; - } else { - this.i.a((Entity) this.j, 10.0F, 10.0F); - return true; - } - } else { - return this.c != null && this.n.a(this.i, this.c) ? true : super.b(); - } - } - - @Override - public void e() { - if (this.j != null) { - if (--this.k <= 0) { - this.c = this.j; - this.j = null; - super.c(); - } - } else { - if (this.c != null && !this.i.isPassenger()) { - if (this.i.f((EntityHuman) this.c)) { - if (this.c.h((Entity) this.i) < 16.0D && this.getEnderman().tryEscape(EndermanEscapeEvent.Reason.STARE)) { - this.i.dV(); - } - - this.l = 0; - } else if (this.c.h((Entity) this.i) > 256.0D && this.l++ >= 30 && this.i.a((Entity) this.c)) { - this.l = 0; - } - } - - super.e(); - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityEvokerFangs.java b/src/main/java/net/minecraft/server/EntityEvokerFangs.java deleted file mode 100644 index 853002e6e..000000000 --- a/src/main/java/net/minecraft/server/EntityEvokerFangs.java +++ /dev/null @@ -1,135 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.UUID; -import javax.annotation.Nullable; - -public class EntityEvokerFangs extends Entity { - - private int b; - private boolean c; - private int d; - private boolean e; - private EntityLiving f; - private UUID g; - - public EntityEvokerFangs(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.d = 22; - } - - public EntityEvokerFangs(World world, double d0, double d1, double d2, float f, int i, EntityLiving entityliving) { - this(EntityTypes.EVOKER_FANGS, world); - this.b = i; - this.a(entityliving); - this.yaw = f * 57.295776F; - this.setPosition(d0, d1, d2); - } - - @Override - protected void initDatawatcher() {} - - public void a(@Nullable EntityLiving entityliving) { - this.f = entityliving; - this.g = entityliving == null ? null : entityliving.getUniqueID(); - } - - @Nullable - public EntityLiving getOwner() { - if (this.f == null && this.g != null && this.world instanceof WorldServer) { - Entity entity = ((WorldServer) this.world).getEntity(this.g); - - if (entity instanceof EntityLiving) { - this.f = (EntityLiving) entity; - } - } - - return this.f; - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - this.b = nbttagcompound.getInt("Warmup"); - if (nbttagcompound.b("OwnerUUID")) { - this.g = nbttagcompound.a("OwnerUUID"); - } - - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setInt("Warmup", this.b); - if (this.g != null) { - nbttagcompound.a("OwnerUUID", this.g); - } - - } - - @Override - public void tick() { - super.tick(); - if (this.world.isClientSide) { - if (this.e) { - --this.d; - if (this.d == 14) { - for (int i = 0; i < 12; ++i) { - double d0 = this.locX + (this.random.nextDouble() * 2.0D - 1.0D) * (double) this.getWidth() * 0.5D; - double d1 = this.locY + 0.05D + this.random.nextDouble(); - double d2 = this.locZ + (this.random.nextDouble() * 2.0D - 1.0D) * (double) this.getWidth() * 0.5D; - double d3 = (this.random.nextDouble() * 2.0D - 1.0D) * 0.3D; - double d4 = 0.3D + this.random.nextDouble() * 0.3D; - double d5 = (this.random.nextDouble() * 2.0D - 1.0D) * 0.3D; - - this.world.addParticle(Particles.CRIT, d0, d1 + 1.0D, d2, d3, d4, d5); - } - } - } - } else if (--this.b < 0) { - if (this.b == -8) { - List list = this.world.a(EntityLiving.class, this.getBoundingBox().grow(0.2D, 0.0D, 0.2D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityLiving entityliving = (EntityLiving) iterator.next(); - - this.c(entityliving); - } - } - - if (!this.c) { - this.world.broadcastEntityEffect(this, (byte) 4); - this.c = true; - } - - if (--this.d < 0) { - this.die(); - } - } - - } - - private void c(EntityLiving entityliving) { - EntityLiving entityliving1 = this.getOwner(); - - if (entityliving.isAlive() && !entityliving.isInvulnerable() && entityliving != entityliving1) { - if (entityliving1 == null) { - org.bukkit.craftbukkit.event.CraftEventFactory.entityDamage = this; // CraftBukkit - entityliving.damageEntity(DamageSource.MAGIC, 6.0F); - org.bukkit.craftbukkit.event.CraftEventFactory.entityDamage = null; // CraftBukkit - } else { - if (entityliving1.r(entityliving)) { - return; - } - - entityliving.damageEntity(DamageSource.c(this, entityliving1), 6.0F); - } - - } - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntityExperienceOrb.java b/src/main/java/net/minecraft/server/EntityExperienceOrb.java deleted file mode 100644 index d8f23ff02..000000000 --- a/src/main/java/net/minecraft/server/EntityExperienceOrb.java +++ /dev/null @@ -1,302 +0,0 @@ -package net.minecraft.server; - -import java.util.Map.Entry; -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.event.entity.EntityTargetEvent; -// CraftBukkit end - -public class EntityExperienceOrb extends Entity { - - public int b; - public int c; - public int d; - private int e; - public int value; - private EntityHuman targetPlayer; - private int targetTime; - // Paper start - public java.util.UUID sourceEntityId; - public java.util.UUID triggerEntityId; - public org.bukkit.entity.ExperienceOrb.SpawnReason spawnReason = org.bukkit.entity.ExperienceOrb.SpawnReason.UNKNOWN; - - private void loadPaperNBT(NBTTagCompound nbttagcompound) { - if (!nbttagcompound.hasKeyOfType("Paper.ExpData", 10)) { // 10 = compound - return; - } - NBTTagCompound comp = nbttagcompound.getCompound("Paper.ExpData"); - if (comp.hasUUID("source")) { - this.sourceEntityId = comp.getUUID("source"); - } - if (comp.hasUUID("trigger")) { - this.triggerEntityId = comp.getUUID("trigger"); - } - if (comp.hasKey("reason")) { - String reason = comp.getString("reason"); - try { - this.spawnReason = org.bukkit.entity.ExperienceOrb.SpawnReason.valueOf(reason); - } catch (Exception e) { - this.world.getServer().getLogger().warning("Invalid spawnReason set for experience orb: " + e.getMessage() + " - " + reason); - } - } - } - private void savePaperNBT(NBTTagCompound nbttagcompound) { - NBTTagCompound comp = new NBTTagCompound(); - if (this.sourceEntityId != null) { - comp.setUUID("source", this.sourceEntityId); - } - if (this.triggerEntityId != null) { - comp.setUUID("trigger", triggerEntityId); - } - if (this.spawnReason != null && this.spawnReason != org.bukkit.entity.ExperienceOrb.SpawnReason.UNKNOWN) { - comp.setString("reason", this.spawnReason.name()); - } - nbttagcompound.set("Paper.ExpData", comp); - } - - public EntityExperienceOrb(World world, double d0, double d1, double d2, int i) { - this(world, d0, d1, d2, i, null, null); - } - - public EntityExperienceOrb(World world, double d0, double d1, double d2, int i, org.bukkit.entity.ExperienceOrb.SpawnReason reason, Entity triggerId) { - this(world, d0, d1, d2, i, reason, triggerId, null); - } - - public EntityExperienceOrb(World world, double d0, double d1, double d2, int i, org.bukkit.entity.ExperienceOrb.SpawnReason reason, Entity triggerId, Entity sourceId) { - this(EntityTypes.EXPERIENCE_ORB, world); - this.sourceEntityId = sourceId != null ? sourceId.getUniqueID() : null; - this.triggerEntityId = triggerId != null ? triggerId.getUniqueID() : null; - this.spawnReason = reason != null ? reason : org.bukkit.entity.ExperienceOrb.SpawnReason.UNKNOWN; - // Paper end - this.setPosition(d0, d1, d2); - this.yaw = (float) (this.random.nextDouble() * 360.0D); - this.setMot((this.random.nextDouble() * 0.20000000298023224D - 0.10000000149011612D) * 2.0D, this.random.nextDouble() * 0.2D * 2.0D, (this.random.nextDouble() * 0.20000000298023224D - 0.10000000149011612D) * 2.0D); - this.value = i; - } - - public EntityExperienceOrb(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.e = 5; - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - protected void initDatawatcher() {} - - @Override - public void tick() { - super.tick(); - EntityHuman prevTarget = this.targetPlayer;// CraftBukkit - store old target - if (this.d > 0) { - --this.d; - } - - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - if (this.a(TagsFluid.WATER)) { - this.k(); - } else if (!this.isNoGravity()) { - this.setMot(this.getMot().add(0.0D, -0.03D, 0.0D)); - } - - if (this.world.getFluid(new BlockPosition(this)).a(TagsFluid.LAVA)) { - this.setMot((double) ((this.random.nextFloat() - this.random.nextFloat()) * 0.2F), 0.20000000298023224D, (double) ((this.random.nextFloat() - this.random.nextFloat()) * 0.2F)); - this.a(SoundEffects.ENTITY_GENERIC_BURN, 0.4F, 2.0F + this.random.nextFloat() * 0.4F); - } - - if (!this.world.c(this.getBoundingBox())) { - this.i(this.locX, (this.getBoundingBox().minY + this.getBoundingBox().maxY) / 2.0D, this.locZ); - } - - double d0 = 8.0D; - - if (this.targetTime < this.b - 20 + this.getId() % 100) { - if (this.targetPlayer == null || this.targetPlayer.h((Entity) this) > 64.0D) { - this.targetPlayer = this.world.findNearbyPlayer(this, 8.0D); - } - - this.targetTime = this.b; - } - - if (this.targetPlayer != null && this.targetPlayer.isSpectator()) { - this.targetPlayer = null; - } - - // CraftBukkit start - boolean cancelled = false; - if (this.targetPlayer != prevTarget) { - EntityTargetLivingEntityEvent event = CraftEventFactory.callEntityTargetLivingEvent(this, targetPlayer, (targetPlayer != null) ? EntityTargetEvent.TargetReason.CLOSEST_PLAYER : EntityTargetEvent.TargetReason.FORGOT_TARGET); - EntityLiving target = (event.getTarget() == null) ? null : ((org.bukkit.craftbukkit.entity.CraftLivingEntity) event.getTarget()).getHandle(); - cancelled = event.isCancelled(); - - if (cancelled) { - targetPlayer = prevTarget; - } else { - targetPlayer = (target instanceof EntityHuman) ? (EntityHuman) target : null; - } - } - - if (this.targetPlayer != null && !cancelled) { - // CraftBukkit end - Vec3D vec3d = new Vec3D(this.targetPlayer.locX - this.locX, this.targetPlayer.locY + (double) this.targetPlayer.getHeadHeight() / 2.0D - this.locY, this.targetPlayer.locZ - this.locZ); - double d1 = vec3d.g(); - - if (d1 < 64.0D) { - double d2 = 1.0D - Math.sqrt(d1) / 8.0D; - - this.setMot(this.getMot().e(vec3d.d().a(d2 * d2 * 0.1D))); - } - } - - this.move(EnumMoveType.SELF, this.getMot()); - float f = 0.98F; - - if (this.onGround) { - f = this.world.getType(new BlockPosition(this.locX, this.getBoundingBox().minY - 1.0D, this.locZ)).getBlock().m() * 0.98F; - } - - this.setMot(this.getMot().d((double) f, 0.98D, (double) f)); - if (this.onGround) { - this.setMot(this.getMot().d(1.0D, -0.9D, 1.0D)); - } - - ++this.b; - ++this.c; - if (this.c >= 6000) { - this.die(); - } - - } - - private void k() { - Vec3D vec3d = this.getMot(); - - this.setMot(vec3d.x * 0.9900000095367432D, Math.min(vec3d.y + 5.000000237487257E-4D, 0.05999999865889549D), vec3d.z * 0.9900000095367432D); - } - - @Override - protected void az() {} - - @Override - protected void burn(float i) { // CraftBukkit - int -> float - this.damageEntity(DamageSource.FIRE, (float) i); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - this.velocityChanged(); - this.e = (int) ((float) this.e - f); - if (this.e <= 0) { - this.die(); - } - - return false; - } - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("Health", (short) this.e); - nbttagcompound.setShort("Age", (short) this.c); - nbttagcompound.setInt("Value", this.value); // Paper - save as Integer - this.savePaperNBT(nbttagcompound); // Paper - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.e = nbttagcompound.getShort("Health"); - this.c = nbttagcompound.getShort("Age"); - this.value = nbttagcompound.getInt("Value"); // Paper - load as Integer - this.loadPaperNBT(nbttagcompound); // Paper - } - - @Override - public void pickup(EntityHuman entityhuman) { - if (!this.world.isClientSide) { - if (this.d == 0 && entityhuman.bF == 0 && new com.destroystokyo.paper.event.player.PlayerPickupExperienceEvent(((EntityPlayer) entityhuman).getBukkitEntity(), (org.bukkit.entity.ExperienceOrb) this.getBukkitEntity()).callEvent()) { // Paper - entityhuman.bF = 2; - entityhuman.receive(this, 1); - Entry entry = EnchantmentManager.b(Enchantments.MENDING, (EntityLiving) entityhuman); - - if (entry != null) { - ItemStack itemstack = (ItemStack) entry.getValue(); - - if (!itemstack.isEmpty() && itemstack.f()) { - int i = Math.min(this.c(this.value), itemstack.getDamage()); - - // CraftBukkit start - org.bukkit.event.player.PlayerItemMendEvent event = CraftEventFactory.callPlayerItemMendEvent(entityhuman, this, itemstack, i); - i = event.getRepairAmount(); - if (!event.isCancelled()) { - this.value -= this.b(i); - itemstack.setDamage(itemstack.getDamage() - i); - } - // CraftBukkit end - } - } - - if (this.value > 0) { - entityhuman.giveExp(CraftEventFactory.callPlayerExpChangeEvent(entityhuman, this).getAmount()); // CraftBukkit - this.value -> event.getAmount() // Paper - supply experience orb object - } - - this.die(); - } - - } - } - - public int durToXp(int i) { return b(i); } // Paper OBFHELPER - private int b(int i) { - return i / 2; - } - - public int xpToDur(int i) { return c(i); } // Paper OBFHELPER - private int c(int i) { - return i * 2; - } - - public int f() { - return this.value; - } - - 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))))))))); - } - - @Override - public boolean bs() { - return false; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntityExperienceOrb(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntityFallingBlock.java b/src/main/java/net/minecraft/server/EntityFallingBlock.java deleted file mode 100644 index 0a6d2b9b3..000000000 --- a/src/main/java/net/minecraft/server/EntityFallingBlock.java +++ /dev/null @@ -1,299 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class EntityFallingBlock extends Entity { - - private IBlockData block; - public int ticksLived; - public boolean dropItem; - private boolean g; - public boolean hurtEntities; - private int fallHurtMax; - private float fallHurtAmount; - public NBTTagCompound tileEntityData; - protected static final DataWatcherObject e = DataWatcher.a(EntityFallingBlock.class, DataWatcherRegistry.l); - - public EntityFallingBlock(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.block = Blocks.SAND.getBlockData(); - this.dropItem = true; - this.fallHurtMax = 40; - this.fallHurtAmount = 2.0F; - } - - public EntityFallingBlock(World world, double d0, double d1, double d2, IBlockData iblockdata) { - this(EntityTypes.FALLING_BLOCK, world); - this.block = iblockdata; - this.i = true; - this.setPosition(d0, d1 + (double) ((1.0F - this.getHeight()) / 2.0F), d2); - this.setMot(Vec3D.a); - this.lastX = d0; - this.lastY = d1; - this.lastZ = d2; - this.a(new BlockPosition(this)); - } - - @Override - public boolean bs() { - return false; - } - - public void a(BlockPosition blockposition) { - this.datawatcher.set(EntityFallingBlock.e, blockposition); - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - protected void initDatawatcher() { - this.datawatcher.register(EntityFallingBlock.e, BlockPosition.ZERO); - } - - @Override - public boolean isInteractable() { - return !this.dead; - } - - @Override - public void tick() { - if (this.block.isAir()) { - this.die(); - } else { - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - Block block = this.block.getBlock(); - BlockPosition blockposition; - - if (this.ticksLived++ == 0) { - blockposition = new BlockPosition(this); - if (this.world.getType(blockposition).getBlock() == block && !CraftEventFactory.callEntityChangeBlockEvent(this, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { - this.world.a(blockposition, false); - } else if (!this.world.isClientSide) { - this.die(); - return; - } - } - - if (!this.isNoGravity()) { - this.setMot(this.getMot().add(0.0D, -0.04D, 0.0D)); - } - - this.move(EnumMoveType.SELF, this.getMot()); - - // Paper start - Configurable EntityFallingBlock height nerf - if (this.world.paperConfig.fallingBlockHeightNerf != 0 && this.locY > this.world.paperConfig.fallingBlockHeightNerf) { - if (this.dropItem && this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { - this.a(block); - } - - this.die(); - } - // Paper end - if (!this.world.isClientSide) { - blockposition = new BlockPosition(this); - boolean flag = this.block.getBlock() instanceof BlockConcretePowder; - boolean flag1 = flag && this.world.getFluid(blockposition).a(TagsFluid.WATER); - double d0 = this.getMot().g(); - - if (flag && d0 > 1.0D) { - MovingObjectPositionBlock movingobjectpositionblock = this.world.rayTrace(new RayTrace(new Vec3D(this.lastX, this.lastY, this.lastZ), new Vec3D(this.locX, this.locY, this.locZ), RayTrace.BlockCollisionOption.COLLIDER, RayTrace.FluidCollisionOption.SOURCE_ONLY, this)); - - if (movingobjectpositionblock.getType() != MovingObjectPosition.EnumMovingObjectType.MISS && this.world.getFluid(movingobjectpositionblock.getBlockPosition()).a(TagsFluid.WATER)) { - blockposition = movingobjectpositionblock.getBlockPosition(); - flag1 = true; - } - } - - if (!this.onGround && !flag1) { - if (!this.world.isClientSide && (this.ticksLived > 100 && (blockposition.getY() < 1 || blockposition.getY() > 256) || this.ticksLived > 600)) { - if (this.dropItem && this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { - this.a((IMaterial) block); - } - - this.die(); - } - } else { - IBlockData iblockdata = this.world.getType(blockposition); - - this.setMot(this.getMot().d(0.7D, -0.5D, 0.7D)); - if (iblockdata.getBlock() != Blocks.MOVING_PISTON) { - this.die(); - if (!this.g) { - boolean flag2 = iblockdata.a((BlockActionContext) (new BlockActionContextDirectional(this.world, blockposition, EnumDirection.DOWN, ItemStack.a, EnumDirection.UP))); - boolean flag3 = this.block.canPlace(this.world, blockposition); - - if (flag2 && flag3) { - if (this.block.b((IBlockState) BlockProperties.C) && this.world.getFluid(blockposition).getType() == FluidTypes.WATER) { - this.block = (IBlockData) this.block.set(BlockProperties.C, true); - } - - // CraftBukkit start - if (CraftEventFactory.callEntityChangeBlockEvent(this, blockposition, this.block).isCancelled()) { - return; - } - // CraftBukkit end - if (this.world.setTypeAndData(blockposition, this.block, 3)) { - if (block instanceof BlockFalling) { - ((BlockFalling) block).a(this.world, blockposition, this.block, iblockdata); - } - - if (this.tileEntityData != null && block instanceof ITileEntity) { - TileEntity tileentity = this.world.getTileEntity(blockposition); - - if (tileentity != null) { - NBTTagCompound nbttagcompound = tileentity.save(new NBTTagCompound()); - Iterator iterator = this.tileEntityData.getKeys().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - NBTBase nbtbase = this.tileEntityData.get(s); - - if (!"x".equals(s) && !"y".equals(s) && !"z".equals(s)) { - nbttagcompound.set(s, nbtbase.clone()); - } - } - - tileentity.load(nbttagcompound); - tileentity.update(); - } - } - } else if (this.dropItem && this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { - this.a((IMaterial) block); - } - } else if (this.dropItem && this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { - this.a((IMaterial) block); - } - } else if (block instanceof BlockFalling) { - ((BlockFalling) block).a(this.world, blockposition); - } - } - } - } - - this.setMot(this.getMot().a(0.98D)); - } - } - - @Override - public void b(float f, float f1) { - if (this.hurtEntities) { - int i = MathHelper.f(f - 1.0F); - - if (i > 0) { - List list = Lists.newArrayList(this.world.getEntities(this, this.getBoundingBox())); - boolean flag = this.block.a(TagsBlock.ANVIL); - DamageSource damagesource = flag ? DamageSource.ANVIL : DamageSource.FALLING_BLOCK; - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - CraftEventFactory.entityDamage = this; // CraftBukkit - entity.damageEntity(damagesource, (float) Math.min(MathHelper.d((float) i * this.fallHurtAmount), this.fallHurtMax)); - CraftEventFactory.entityDamage = null; // CraftBukkit - } - - if (flag && (double) this.random.nextFloat() < 0.05000000074505806D + (double) i * 0.05D) { - IBlockData iblockdata = BlockAnvil.a_(this.block); - - if (iblockdata == null) { - this.g = true; - } else { - this.block = iblockdata; - } - } - } - } - - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - nbttagcompound.set("BlockState", GameProfileSerializer.a(this.block)); - nbttagcompound.setInt("Time", 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); - } - - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - this.block = GameProfileSerializer.d(nbttagcompound.getCompound("BlockState")); - - // Paper start - Block FallingBlocks with Command Blocks - // Check mappings on update - dc = "repeating_command_block" - dd = "chain_command_block" - final Block b = this.block.getBlock(); - if (this.world.paperConfig.filterNBTFromSpawnEgg && (b == Blocks.COMMAND_BLOCK || b == Blocks.REPEATING_COMMAND_BLOCK || b == Blocks.CHAIN_COMMAND_BLOCK)) { - this.block = Blocks.STONE.getBlockData(); - } - // Paper end - - this.ticksLived = nbttagcompound.getInt("Time"); - if (nbttagcompound.hasKeyOfType("HurtEntities", 99)) { - this.hurtEntities = nbttagcompound.getBoolean("HurtEntities"); - this.fallHurtAmount = nbttagcompound.getFloat("FallHurtAmount"); - this.fallHurtMax = nbttagcompound.getInt("FallHurtMax"); - } else if (this.block.a(TagsBlock.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 (this.block.isAir()) { - this.block = Blocks.SAND.getBlockData(); - } - - // Paper start - Try and load origin location from the old NBT tags for backwards compatibility - if (nbttagcompound.hasKey("SourceLoc_x")) { - int srcX = nbttagcompound.getInt("SourceLoc_x"); - int srcY = nbttagcompound.getInt("SourceLoc_y"); - int srcZ = nbttagcompound.getInt("SourceLoc_z"); - origin = new org.bukkit.Location(world.getWorld(), srcX, srcY, srcZ); - } - // Paper end - } - - public void a(boolean flag) { - this.hurtEntities = flag; - } - - @Override - public void appendEntityCrashDetails(CrashReportSystemDetails crashreportsystemdetails) { - super.appendEntityCrashDetails(crashreportsystemdetails); - crashreportsystemdetails.a("Immitating BlockState", (Object) this.block.toString()); - } - - public IBlockData getBlock() { - return this.block; - } - - @Override - public boolean bT() { - return true; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this, Block.getCombinedId(this.getBlock())); - } -} diff --git a/src/main/java/net/minecraft/server/EntityFireball.java b/src/main/java/net/minecraft/server/EntityFireball.java deleted file mode 100644 index 14c439493..000000000 --- a/src/main/java/net/minecraft/server/EntityFireball.java +++ /dev/null @@ -1,210 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public abstract class EntityFireball extends Entity { - - public EntityLiving shooter; - private int f; - private int g; - public double dirX; - public double dirY; - public double dirZ; - public float bukkitYield = 1; // CraftBukkit - public boolean isIncendiary = true; // CraftBukkit - - protected EntityFireball(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityFireball(EntityTypes entitytypes, double d0, double d1, double d2, double d3, double d4, double d5, World world) { - this(entitytypes, world); - this.setPositionRotation(d0, d1, d2, this.yaw, this.pitch); - this.setPosition(d0, d1, d2); - double d6 = (double) 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(EntityTypes entitytypes, EntityLiving entityliving, double d0, double d1, double d2, World world) { - this(entitytypes, world); - this.shooter = entityliving; - this.projectileSource = (org.bukkit.entity.LivingEntity) entityliving.getBukkitEntity(); // CraftBukkit - this.setPositionRotation(entityliving.locX, entityliving.locY, entityliving.locZ, entityliving.yaw, entityliving.pitch); - this.setPosition(this.locX, this.locY, this.locZ); - this.setMot(Vec3D.a); - // CraftBukkit start - Added setDirection method - this.setDirection(d0, d1, d2); - } - - public void setDirection(double d0, double d1, double d2) { - // CraftBukkit end - d0 += this.random.nextGaussian() * 0.4D; - d1 += this.random.nextGaussian() * 0.4D; - d2 += this.random.nextGaussian() * 0.4D; - double d3 = (double) 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; - } - - @Override - protected void initDatawatcher() {} - - @Override - public void tick() { - if (!this.world.isClientSide && (this.shooter != null && this.shooter.dead || !this.world.isLoaded(new BlockPosition(this)))) { - this.die(); - } else { - super.tick(); - if (this.K_()) { - this.setOnFire(1); - } - - ++this.g; - MovingObjectPosition movingobjectposition = ProjectileHelper.a(this, true, this.g >= 25, this.shooter, RayTrace.BlockCollisionOption.COLLIDER); - - // Paper start - Call ProjectileCollideEvent - if (movingobjectposition instanceof MovingObjectPositionEntity) { - com.destroystokyo.paper.event.entity.ProjectileCollideEvent event = CraftEventFactory.callProjectileCollideEvent(this, (MovingObjectPositionEntity)movingobjectposition); - if (event.isCancelled()) { - movingobjectposition = null; - } - } - // Paper end - - if (movingobjectposition != null && movingobjectposition.getType() != MovingObjectPosition.EnumMovingObjectType.MISS) { // Paper - add null check in case cancelled - this.a(movingobjectposition); - - // CraftBukkit start - Fire ProjectileHitEvent - if (this.dead) { - CraftEventFactory.callProjectileHitEvent(this, movingobjectposition); - } - // CraftBukkit end - } - - Vec3D vec3d = this.getMot(); - - this.locX += vec3d.x; - this.locY += vec3d.y; - this.locZ += vec3d.z; - ProjectileHelper.a(this, 0.2F); - float f = this.k(); - - if (this.isInWater()) { - for (int i = 0; i < 4; ++i) { - float f1 = 0.25F; - - this.world.addParticle(Particles.BUBBLE, this.locX - vec3d.x * 0.25D, this.locY - vec3d.y * 0.25D, this.locZ - vec3d.z * 0.25D, vec3d.x, vec3d.y, vec3d.z); - } - - f = 0.8F; - } - - this.setMot(vec3d.add(this.dirX, this.dirY, this.dirZ).a((double) f)); - this.world.addParticle(this.i(), this.locX, this.locY + 0.5D, this.locZ, 0.0D, 0.0D, 0.0D); - this.setPosition(this.locX, this.locY, this.locZ); - } - } - - protected boolean K_() { - return true; - } - - protected ParticleParam i() { - return Particles.SMOKE; - } - - protected float k() { - return 0.95F; - } - - protected abstract void a(MovingObjectPosition movingobjectposition); - - @Override - public void b(NBTTagCompound nbttagcompound) { - Vec3D vec3d = this.getMot(); - - nbttagcompound.set("direction", this.a(new double[]{vec3d.x, vec3d.y, vec3d.z})); - nbttagcompound.set("power", this.a(new double[]{this.dirX, this.dirY, this.dirZ})); - nbttagcompound.setInt("life", this.f); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - NBTTagList nbttaglist; - - if (nbttagcompound.hasKeyOfType("power", 9)) { - nbttaglist = nbttagcompound.getList("power", 6); - if (nbttaglist.size() == 3) { - this.dirX = nbttaglist.h(0); - this.dirY = nbttaglist.h(1); - this.dirZ = nbttaglist.h(2); - } - } - - this.f = nbttagcompound.getInt("life"); - if (nbttagcompound.hasKeyOfType("direction", 9) && nbttagcompound.getList("direction", 6).size() == 3) { - nbttaglist = nbttagcompound.getList("direction", 6); - this.setMot(nbttaglist.h(0), nbttaglist.h(1), nbttaglist.h(2)); - } else { - this.die(); - } - - } - - @Override - public boolean isInteractable() { - return true; - } - - @Override - public float aS() { - return 1.0F; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - this.velocityChanged(); - if (damagesource.getEntity() != null) { - // CraftBukkit start - if (CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f)) { - return false; - } - // CraftBukkit end - Vec3D vec3d = damagesource.getEntity().getLookDirection(); - - this.setMot(vec3d); - this.dirX = vec3d.x * 0.1D; - this.dirY = vec3d.y * 0.1D; - this.dirZ = vec3d.z * 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; - } - } - } - - @Override - public float aF() { - return 1.0F; - } - - @Override - public Packet N() { - int i = this.shooter == null ? 0 : this.shooter.getId(); - - return new PacketPlayOutSpawnEntity(this.getId(), this.getUniqueID(), this.locX, this.locY, this.locZ, this.pitch, this.yaw, this.getEntityType(), i, new Vec3D(this.dirX, this.dirY, this.dirZ)); - } -} diff --git a/src/main/java/net/minecraft/server/EntityFireworks.java b/src/main/java/net/minecraft/server/EntityFireworks.java deleted file mode 100644 index dbbb96ac5..000000000 --- a/src/main/java/net/minecraft/server/EntityFireworks.java +++ /dev/null @@ -1,329 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.OptionalInt; -import java.util.UUID; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class EntityFireworks extends Entity implements IProjectile { - - public static final DataWatcherObject FIREWORK_ITEM = DataWatcher.a(EntityFireworks.class, DataWatcherRegistry.g); - private static final DataWatcherObject c = DataWatcher.a(EntityFireworks.class, DataWatcherRegistry.r); - public static final DataWatcherObject d = DataWatcher.a(EntityFireworks.class, DataWatcherRegistry.i); // PAIL - private int ticksFlown; - public int expectedLifespan; - private EntityLiving ridingEntity; public final EntityLiving getBoostedEntity() { return this.ridingEntity; } // Paper - OBFHELPER - public UUID spawningEntity; // Paper - - public EntityFireworks(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - // Spigot Start - copied from tick - @Override - public void inactiveTick() { - this.ticksFlown += 1; - - if (!this.world.isClientSide && this.ticksFlown > this.expectedLifespan) { - // CraftBukkit start - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callFireworkExplodeEvent(this).isCancelled()) { - this.explode(); - } - // CraftBukkit end - } - super.inactiveTick(); - } - // Spigot End - - @Override - protected void initDatawatcher() { - this.datawatcher.register(EntityFireworks.FIREWORK_ITEM, ItemStack.a); - this.datawatcher.register(EntityFireworks.c, OptionalInt.empty()); - this.datawatcher.register(EntityFireworks.d, false); - } - - public EntityFireworks(World world, double d0, double d1, double d2, ItemStack itemstack) { - super(EntityTypes.FIREWORK_ROCKET, world); - this.ticksFlown = 0; - this.setPosition(d0, d1, d2); - int i = 1; - - if (!itemstack.isEmpty() && itemstack.hasTag()) { - this.datawatcher.set(EntityFireworks.FIREWORK_ITEM, itemstack.cloneItemStack()); - i += itemstack.a("Fireworks").getByte("Flight"); - } - - this.setMot(this.random.nextGaussian() * 0.001D, 0.05D, this.random.nextGaussian() * 0.001D); - this.expectedLifespan = 10 * i + this.random.nextInt(6) + this.random.nextInt(7); - } - - public EntityFireworks(World world, ItemStack itemstack, EntityLiving entityliving) { - this(world, entityliving.locX, entityliving.locY, entityliving.locZ, itemstack); - this.datawatcher.set(EntityFireworks.c, OptionalInt.of(entityliving.getId())); - this.ridingEntity = entityliving; - } - - public EntityFireworks(World world, ItemStack itemstack, double d0, double d1, double d2, boolean flag) { - this(world, d0, d1, d2, itemstack); - this.datawatcher.set(EntityFireworks.d, flag); - } - - @Override - public void tick() { - this.H = this.locX; - this.I = this.locY; - this.J = this.locZ; - super.tick(); - Vec3D vec3d; - - if (this.n()) { - if (this.ridingEntity == null) { - ((OptionalInt) this.datawatcher.get(EntityFireworks.c)).ifPresent((i) -> { - Entity entity = this.world.getEntity(i); - - if (entity instanceof EntityLiving) { - this.ridingEntity = (EntityLiving) entity; - } - - }); - } - - if (this.ridingEntity != null) { - if (this.ridingEntity.isGliding()) { - vec3d = this.ridingEntity.getLookDirection(); - double d0 = 1.5D; - double d1 = 0.1D; - Vec3D vec3d1 = this.ridingEntity.getMot(); - - this.ridingEntity.setMot(vec3d1.add(vec3d.x * 0.1D + (vec3d.x * 1.5D - vec3d1.x) * 0.5D, vec3d.y * 0.1D + (vec3d.y * 1.5D - vec3d1.y) * 0.5D, vec3d.z * 0.1D + (vec3d.z * 1.5D - vec3d1.z) * 0.5D)); - } - - this.setPosition(this.ridingEntity.locX, this.ridingEntity.locY, this.ridingEntity.locZ); - this.setMot(this.ridingEntity.getMot()); - } - } else { - if (!this.i()) { - this.setMot(this.getMot().d(1.15D, 1.0D, 1.15D).add(0.0D, 0.04D, 0.0D)); - } - - this.move(EnumMoveType.SELF, this.getMot()); - } - - vec3d = this.getMot(); - MovingObjectPosition movingobjectposition = ProjectileHelper.a(this, this.getBoundingBox().a(vec3d).g(1.0D), (entity) -> { - return !entity.isSpectator() && entity.isAlive() && entity.isInteractable(); - }, RayTrace.BlockCollisionOption.COLLIDER, true); - - if (!this.noclip) { - this.a(movingobjectposition); - this.impulse = true; - } - - float f = MathHelper.sqrt(b(vec3d)); - - this.yaw = (float) (MathHelper.d(vec3d.x, vec3d.z) * 57.2957763671875D); - - for (this.pitch = (float) (MathHelper.d(vec3d.y, (double) f) * 57.2957763671875D); 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 = MathHelper.g(0.2F, this.lastPitch, this.pitch); - this.yaw = MathHelper.g(0.2F, this.lastYaw, this.yaw); - if (this.ticksFlown == 0 && !this.isSilent()) { - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_FIREWORK_ROCKET_LAUNCH, SoundCategory.AMBIENT, 3.0F, 1.0F); - } - - ++this.ticksFlown; - if (this.world.isClientSide && this.ticksFlown % 2 < 2) { - this.world.addParticle(Particles.FIREWORK, this.locX, this.locY - 0.3D, this.locZ, this.random.nextGaussian() * 0.05D, -this.getMot().y * 0.5D, this.random.nextGaussian() * 0.05D); - } - - if (!this.world.isClientSide && this.ticksFlown > this.expectedLifespan) { - // CraftBukkit start - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callFireworkExplodeEvent(this).isCancelled()) { - this.explode(); - } - // CraftBukkit end - } - - } - - private void explode() { - this.world.broadcastEntityEffect(this, (byte) 17); - this.m(); - this.die(); - } - - protected void a(MovingObjectPosition movingobjectposition) { - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY && !this.world.isClientSide) { - // CraftBukkit start - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callFireworkExplodeEvent(this).isCancelled()) { - this.explode(); - } - // CraftBukkit end - } else if (this.z) { - BlockPosition blockposition; - - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { - blockposition = new BlockPosition(((MovingObjectPositionBlock) movingobjectposition).getBlockPosition()); - } else { - blockposition = new BlockPosition(this); - } - - this.world.getType(blockposition).a(this.world, blockposition, (Entity) this); - if (this.l()) { - // CraftBukkit start - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callFireworkExplodeEvent(this).isCancelled()) { - this.explode(); - } - // CraftBukkit end - } - } - - } - - private boolean l() { - ItemStack itemstack = (ItemStack) this.datawatcher.get(EntityFireworks.FIREWORK_ITEM); - NBTTagCompound nbttagcompound = itemstack.isEmpty() ? null : itemstack.b("Fireworks"); - NBTTagList nbttaglist = nbttagcompound != null ? nbttagcompound.getList("Explosions", 10) : null; - - return nbttaglist != null && !nbttaglist.isEmpty(); - } - - private void m() { - float f = 0.0F; - ItemStack itemstack = (ItemStack) this.datawatcher.get(EntityFireworks.FIREWORK_ITEM); - NBTTagCompound nbttagcompound = itemstack.isEmpty() ? null : itemstack.b("Fireworks"); - NBTTagList nbttaglist = nbttagcompound != null ? nbttagcompound.getList("Explosions", 10) : null; - - if (nbttaglist != null && !nbttaglist.isEmpty()) { - f = 5.0F + (float) (nbttaglist.size() * 2); - } - - if (f > 0.0F) { - if (this.ridingEntity != null) { - CraftEventFactory.entityDamage = this; // CraftBukkit - this.ridingEntity.damageEntity(DamageSource.FIREWORKS, 5.0F + (float) (nbttaglist.size() * 2)); - CraftEventFactory.entityDamage = null; // CraftBukkit - } - - double d0 = 5.0D; - Vec3D vec3d = new Vec3D(this.locX, this.locY, this.locZ); - List list = this.world.a(EntityLiving.class, this.getBoundingBox().g(5.0D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityLiving entityliving = (EntityLiving) iterator.next(); - - if (entityliving != this.ridingEntity && this.h(entityliving) <= 25.0D) { - boolean flag = false; - - for (int i = 0; i < 2; ++i) { - Vec3D vec3d1 = new Vec3D(entityliving.locX, entityliving.locY + (double) entityliving.getHeight() * 0.5D * (double) i, entityliving.locZ); - MovingObjectPositionBlock movingobjectpositionblock = this.world.rayTrace(new RayTrace(vec3d, vec3d1, RayTrace.BlockCollisionOption.COLLIDER, RayTrace.FluidCollisionOption.NONE, this)); - - if (movingobjectpositionblock.getType() == MovingObjectPosition.EnumMovingObjectType.MISS) { - flag = true; - break; - } - } - - if (flag) { - float f1 = f * (float) Math.sqrt((5.0D - (double) this.g(entityliving)) / 5.0D); - - CraftEventFactory.entityDamage = this; // CraftBukkit - entityliving.damageEntity(DamageSource.FIREWORKS, f1); - CraftEventFactory.entityDamage = null; // CraftBukkit - } - } - } - } - - } - - private boolean n() { - return ((OptionalInt) this.datawatcher.get(EntityFireworks.c)).isPresent(); - } - - public boolean i() { - return (Boolean) this.datawatcher.get(EntityFireworks.d); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setInt("Life", this.ticksFlown); - nbttagcompound.setInt("LifeTime", this.expectedLifespan); - ItemStack itemstack = (ItemStack) this.datawatcher.get(EntityFireworks.FIREWORK_ITEM); - - if (!itemstack.isEmpty()) { - nbttagcompound.set("FireworksItem", itemstack.save(new NBTTagCompound())); - } - - nbttagcompound.setBoolean("ShotAtAngle", (Boolean) this.datawatcher.get(EntityFireworks.d)); - // Paper start - if (this.spawningEntity != null) { - nbttagcompound.setUUID("SpawningEntity", this.spawningEntity); - } - // Paper end - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.ticksFlown = nbttagcompound.getInt("Life"); - this.expectedLifespan = nbttagcompound.getInt("LifeTime"); - ItemStack itemstack = ItemStack.a(nbttagcompound.getCompound("FireworksItem")); - - if (!itemstack.isEmpty()) { - this.datawatcher.set(EntityFireworks.FIREWORK_ITEM, itemstack); - } - - if (nbttagcompound.hasKey("ShotAtAngle")) { - this.datawatcher.set(EntityFireworks.d, nbttagcompound.getBoolean("ShotAtAngle")); - } - // Paper start - if (nbttagcompound.hasUUID("SpawningEntity")) { - this.spawningEntity = nbttagcompound.getUUID("SpawningEntity"); - } - // Paper end - } - - @Override - public boolean bs() { - return false; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } - - @Override - public void shoot(double d0, double d1, double d2, float f, float f1) { - float f2 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); - - d0 /= (double) f2; - d1 /= (double) f2; - d2 /= (double) f2; - d0 += this.random.nextGaussian() * 0.007499999832361937D * (double) f1; - d1 += this.random.nextGaussian() * 0.007499999832361937D * (double) f1; - d2 += this.random.nextGaussian() * 0.007499999832361937D * (double) f1; - d0 *= (double) f; - d1 *= (double) f; - d2 *= (double) f; - this.setMot(d0, d1, d2); - } -} diff --git a/src/main/java/net/minecraft/server/EntityFish.java b/src/main/java/net/minecraft/server/EntityFish.java deleted file mode 100644 index 90479feb4..000000000 --- a/src/main/java/net/minecraft/server/EntityFish.java +++ /dev/null @@ -1,213 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import java.util.function.Predicate; - -public abstract class EntityFish extends EntityWaterAnimal { - - private static final DataWatcherObject FROM_BUCKET = DataWatcher.a(EntityFish.class, DataWatcherRegistry.i); - - public EntityFish(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.moveController = new EntityFish.a(this); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * 0.65F; - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(3.0D); - } - - @Override - public boolean I() { - return this.isFromBucket(); - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return generatoraccess.getType(blockposition).getBlock() == Blocks.WATER && generatoraccess.getType(blockposition.up()).getBlock() == Blocks.WATER; - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return true; // CraftBukkit - } - - @Override - public int dC() { - return 8; - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityFish.FROM_BUCKET, false); - } - - public boolean isFromBucket() { - return (Boolean) this.datawatcher.get(EntityFish.FROM_BUCKET); - } - - public void setFromBucket(boolean flag) { - this.datawatcher.set(EntityFish.FROM_BUCKET, flag); - this.persistent = this.isPersistent(); // CraftBukkit - SPIGOT-4106 update persistence - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("FromBucket", this.isFromBucket()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setFromBucket(nbttagcompound.getBoolean("FromBucket")); - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(0, new PathfinderGoalPanic(this, 1.25D)); - PathfinderGoalSelector pathfindergoalselector = this.goalSelector; - Predicate predicate = IEntitySelector.f; - - predicate.getClass(); - pathfindergoalselector.a(2, new PathfinderGoalAvoidTarget<>(this, EntityHuman.class, 8.0F, 1.6D, 1.4D, predicate::test)); - this.goalSelector.a(4, new EntityFish.b(this)); - } - - @Override - protected NavigationAbstract b(World world) { - return new NavigationGuardian(this, world); - } - - @Override - public void e(Vec3D vec3d) { - if (this.df() && this.isInWater()) { - this.a(0.01F, vec3d); - this.move(EnumMoveType.SELF, this.getMot()); - this.setMot(this.getMot().a(0.9D)); - if (this.getGoalTarget() == null) { - this.setMot(this.getMot().add(0.0D, -0.005D, 0.0D)); - } - } else { - super.e(vec3d); - } - - } - - @Override - public void movementTick() { - if (!this.isInWater() && this.onGround && this.y) { - this.setMot(this.getMot().add((double) ((this.random.nextFloat() * 2.0F - 1.0F) * 0.05F), 0.4000000059604645D, (double) ((this.random.nextFloat() * 2.0F - 1.0F) * 0.05F))); - this.onGround = false; - this.impulse = true; - this.a(this.getSoundFlop(), this.getSoundVolume(), this.cV()); - } - - super.movementTick(); - } - - @Override - protected boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() == Items.WATER_BUCKET && this.isAlive()) { - this.a(SoundEffects.ITEM_BUCKET_FILL_FISH, 1.0F, 1.0F); - itemstack.subtract(1); - ItemStack itemstack1 = this.l(); - - this.i(itemstack1); - if (!this.world.isClientSide) { - CriterionTriggers.j.a((EntityPlayer) entityhuman, itemstack1); - } - - if (itemstack.isEmpty()) { - entityhuman.a(enumhand, itemstack1); - } else if (!entityhuman.inventory.pickup(itemstack1)) { - entityhuman.drop(itemstack1, false); - } - - this.die(); - return true; - } else { - return super.a(entityhuman, enumhand); - } - } - - protected void i(ItemStack itemstack) { - if (this.hasCustomName()) { - itemstack.a(this.getCustomName()); - } - - } - - protected abstract ItemStack l(); - - protected boolean dV() { - return true; - } - - protected abstract SoundEffect getSoundFlop(); - - @Override - protected SoundEffect getSoundSwim() { - return SoundEffects.ENTITY_FISH_SWIM; - } - - static class a extends ControllerMove { - - private final EntityFish i; - - a(EntityFish entityfish) { - super(entityfish); - this.i = entityfish; - } - - @Override - public void a() { - if (this.i.a(TagsFluid.WATER)) { - this.i.setMot(this.i.getMot().add(0.0D, 0.005D, 0.0D)); - } - - if (this.h == ControllerMove.Operation.MOVE_TO && !this.i.getNavigation().n()) { - double d0 = this.b - this.i.locX; - double d1 = this.c - this.i.locY; - double d2 = this.d - this.i.locZ; - double d3 = (double) MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); - - d1 /= d3; - float f = (float) (MathHelper.d(d2, d0) * 57.2957763671875D) - 90.0F; - - this.i.yaw = this.a(this.i.yaw, f, 90.0F); - this.i.aK = this.i.yaw; - float f1 = (float) (this.e * this.i.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue()); - - this.i.o(MathHelper.g(0.125F, this.i.db(), f1)); - this.i.setMot(this.i.getMot().add(0.0D, (double) this.i.db() * d1 * 0.1D, 0.0D)); - } else { - this.i.o(0.0F); - } - } - } - - static class b extends PathfinderGoalRandomSwim { - - private final EntityFish h; - - public b(EntityFish entityfish) { - super(entityfish, 1.0D, 40); - this.h = entityfish; - } - - @Override - public boolean a() { - return this.h.dV() && super.a(); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityFishingHook.java b/src/main/java/net/minecraft/server/EntityFishingHook.java deleted file mode 100644 index 2a351701b..000000000 --- a/src/main/java/net/minecraft/server/EntityFishingHook.java +++ /dev/null @@ -1,491 +0,0 @@ -package net.minecraft.server; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.entity.Player; -import org.bukkit.entity.FishHook; -import org.bukkit.event.player.PlayerFishEvent; -// CraftBukkit end - -public class EntityFishingHook extends Entity { - - private static final DataWatcherObject c = DataWatcher.a(EntityFishingHook.class, DataWatcherRegistry.b); - private boolean isInGround; - private int e; - public EntityHuman owner; - private int g; - private int ar; - private int as; - private int at; - private float au; - public Entity hooked; - private EntityFishingHook.HookState av; - private final int aw; - private final int ax; - - private EntityFishingHook(World world, EntityHuman entityhuman, int i, int j) { - super(EntityTypes.FISHING_BOBBER, world); - this.av = EntityFishingHook.HookState.FLYING; - this.af = true; - this.owner = entityhuman; - this.owner.hookedFish = this; - this.aw = Math.max(0, i); - this.ax = Math.max(0, j); - } - - public EntityFishingHook(EntityHuman entityhuman, World world, int i, int j) { - this(world, entityhuman, i, j); - float f = this.owner.pitch; - float f1 = this.owner.yaw; - 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); - double d0 = this.owner.locX - (double) f3 * 0.3D; - double d1 = this.owner.locY + (double) this.owner.getHeadHeight(); - double d2 = this.owner.locZ - (double) f2 * 0.3D; - - this.setPositionRotation(d0, d1, d2, f1, f); - Vec3D vec3d = new Vec3D((double) (-f3), (double) MathHelper.a(-(f5 / f4), -5.0F, 5.0F), (double) (-f2)); - double d3 = vec3d.f(); - - vec3d = vec3d.d(0.6D / d3 + 0.5D + this.random.nextGaussian() * 0.0045D, 0.6D / d3 + 0.5D + this.random.nextGaussian() * 0.0045D, 0.6D / d3 + 0.5D + this.random.nextGaussian() * 0.0045D); - this.setMot(vec3d); - this.yaw = (float) (MathHelper.d(vec3d.x, vec3d.z) * 57.2957763671875D); - this.pitch = (float) (MathHelper.d(vec3d.y, (double) MathHelper.sqrt(b(vec3d))) * 57.2957763671875D); - this.lastYaw = this.yaw; - this.lastPitch = this.pitch; - } - - @Override - protected void initDatawatcher() { - this.getDataWatcher().register(EntityFishingHook.c, 0); - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityFishingHook.c.equals(datawatcherobject)) { - int i = (Integer) this.getDataWatcher().get(EntityFishingHook.c); - - this.hooked = i > 0 ? this.world.getEntity(i - 1) : null; - } - - super.a(datawatcherobject); - } - - @Override - public void tick() { - super.tick(); - if (this.owner == null) { - this.die(); - } else if (this.world.isClientSide || !this.k()) { - if (this.isInGround) { - ++this.e; - if (this.e >= 1200) { - this.die(); - return; - } - } - - float f = 0.0F; - BlockPosition blockposition = new BlockPosition(this); - Fluid fluid = this.world.getFluid(blockposition); - - if (fluid.a(TagsFluid.WATER)) { - f = fluid.getHeight(this.world, blockposition); - } - - if (this.av == EntityFishingHook.HookState.FLYING) { - if (this.hooked != null) { - this.setMot(Vec3D.a); - this.av = EntityFishingHook.HookState.HOOKED_IN_ENTITY; - return; - } - - if (f > 0.0F) { - this.setMot(this.getMot().d(0.3D, 0.2D, 0.3D)); - this.av = EntityFishingHook.HookState.BOBBING; - return; - } - - if (!this.world.isClientSide) { - this.m(); - } - - if (!this.isInGround && !this.onGround && !this.positionChanged) { - ++this.g; - } else { - this.g = 0; - this.setMot(Vec3D.a); - } - } else { - if (this.av == EntityFishingHook.HookState.HOOKED_IN_ENTITY) { - if (this.hooked != null) { - if (this.hooked.dead) { - this.hooked = null; - this.av = EntityFishingHook.HookState.FLYING; - } else { - this.locX = this.hooked.locX; - this.locY = this.hooked.getBoundingBox().minY + (double) this.hooked.getHeight() * 0.8D; - this.locZ = this.hooked.locZ; - this.setPosition(this.locX, this.locY, this.locZ); - } - } - - return; - } - - if (this.av == EntityFishingHook.HookState.BOBBING) { - Vec3D vec3d = this.getMot(); - double d0 = this.locY + vec3d.y - (double) blockposition.getY() - (double) f; - - if (Math.abs(d0) < 0.01D) { - d0 += Math.signum(d0) * 0.1D; - } - - this.setMot(vec3d.x * 0.9D, vec3d.y - d0 * (double) this.random.nextFloat() * 0.2D, vec3d.z * 0.9D); - if (!this.world.isClientSide && f > 0.0F) { - this.a(blockposition); - } - } - } - - if (!fluid.a(TagsFluid.WATER)) { - this.setMot(this.getMot().add(0.0D, -0.03D, 0.0D)); - } - - this.move(EnumMoveType.SELF, this.getMot()); - this.l(); - double d1 = 0.92D; - - this.setMot(this.getMot().a(0.92D)); - this.setPosition(this.locX, this.locY, this.locZ); - - // Paper start - These shouldn't be going through portals - if (this.inPortal()) { - this.die(); - } - // Paper end - } - } - - private boolean k() { - ItemStack itemstack = this.owner.getItemInMainHand(); - ItemStack itemstack1 = this.owner.getItemInOffHand(); - boolean flag = itemstack.getItem() == Items.FISHING_ROD; - boolean flag1 = itemstack1.getItem() == Items.FISHING_ROD; - - if (!this.owner.dead && this.owner.isAlive() && (flag || flag1) && this.h(this.owner) <= 1024.0D) { - return false; - } else { - this.die(); - return true; - } - } - - private void l() { - Vec3D vec3d = this.getMot(); - float f = MathHelper.sqrt(b(vec3d)); - - this.yaw = (float) (MathHelper.d(vec3d.x, vec3d.z) * 57.2957763671875D); - - for (this.pitch = (float) (MathHelper.d(vec3d.y, (double) f) * 57.2957763671875D); 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 = MathHelper.g(0.2F, this.lastPitch, this.pitch); - this.yaw = MathHelper.g(0.2F, this.lastYaw, this.yaw); - } - - private void m() { - MovingObjectPosition movingobjectposition = ProjectileHelper.a(this, this.getBoundingBox().a(this.getMot()).g(1.0D), (entity) -> { - return !entity.isSpectator() && (entity.isInteractable() || entity instanceof EntityItem) && (entity != this.owner || this.g >= 5); - }, RayTrace.BlockCollisionOption.COLLIDER, true); - - // Paper start - Call ProjectileCollideEvent - if (movingobjectposition instanceof MovingObjectPositionEntity) { - com.destroystokyo.paper.event.entity.ProjectileCollideEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileCollideEvent(this, (MovingObjectPositionEntity)movingobjectposition); - if (event.isCancelled()) { - movingobjectposition = null; - } - } - // Paper end - - if (movingobjectposition != null && movingobjectposition.getType() != MovingObjectPosition.EnumMovingObjectType.MISS) { // Paper - add null check in case cancelled - org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileHitEvent(this, movingobjectposition); // Craftbukkit - Call event - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - this.hooked = ((MovingObjectPositionEntity) movingobjectposition).getEntity(); - this.n(); - } else { - this.isInGround = true; - } - } - - } - - private void n() { - this.getDataWatcher().set(EntityFishingHook.c, this.hooked.getId() + 1); - } - - private void a(BlockPosition blockposition) { - WorldServer worldserver = (WorldServer) this.world; - int i = 1; - BlockPosition blockposition1 = blockposition.up(); - - if (this.random.nextFloat() < 0.25F && this.world.isRainingAt(blockposition1)) { - ++i; - } - - if (this.random.nextFloat() < 0.5F && !this.world.f(blockposition1)) { - --i; - } - - if (this.ar > 0) { - --this.ar; - if (this.ar <= 0) { - this.as = 0; - this.at = 0; - // CraftBukkit start - PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), null, (FishHook) this.getBukkitEntity(), PlayerFishEvent.State.FAILED_ATTEMPT); - this.world.getServer().getPluginManager().callEvent(playerFishEvent); - // CraftBukkit end - } else { - this.setMot(this.getMot().add(0.0D, -0.2D * (double) this.random.nextFloat() * (double) this.random.nextFloat(), 0.0D)); - } - } else { - float f; - float f1; - float f2; - double d0; - double d1; - double d2; - Block block; - - if (this.at > 0) { - this.at -= i; - if (this.at > 0) { - this.au = (float) ((double) this.au + this.random.nextGaussian() * 4.0D); - f = this.au * 0.017453292F; - f1 = MathHelper.sin(f); - f2 = MathHelper.cos(f); - d0 = this.locX + (double) (f1 * (float) this.at * 0.1F); - d1 = (double) ((float) MathHelper.floor(this.getBoundingBox().minY) + 1.0F); - d2 = this.locZ + (double) (f2 * (float) this.at * 0.1F); - block = worldserver.getType(new BlockPosition(d0, d1 - 1.0D, d2)).getBlock(); - if (block == Blocks.WATER) { - if (this.random.nextFloat() < 0.15F) { - worldserver.a(Particles.BUBBLE, d0, d1 - 0.10000000149011612D, d2, 1, (double) f1, 0.1D, (double) f2, 0.0D); - } - - float f3 = f1 * 0.04F; - float f4 = f2 * 0.04F; - - worldserver.a(Particles.FISHING, d0, d1, d2, 0, (double) f4, 0.01D, (double) (-f3), 1.0D); - worldserver.a(Particles.FISHING, d0, d1, d2, 0, (double) (-f4), 0.01D, (double) f3, 1.0D); - } - } else { - // CraftBukkit start - PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), null, (FishHook) this.getBukkitEntity(), PlayerFishEvent.State.BITE); - this.world.getServer().getPluginManager().callEvent(playerFishEvent); - if (playerFishEvent.isCancelled()) { - return; - } - // CraftBukkit end - Vec3D vec3d = this.getMot(); - - this.setMot(vec3d.x, (double) (-0.4F * MathHelper.a(this.random, 0.6F, 1.0F)), vec3d.z); - this.a(SoundEffects.ENTITY_FISHING_BOBBER_SPLASH, 0.25F, 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.4F); - double d3 = this.getBoundingBox().minY + 0.5D; - - worldserver.a(Particles.BUBBLE, this.locX, d3, this.locZ, (int) (1.0F + this.getWidth() * 20.0F), (double) this.getWidth(), 0.0D, (double) this.getWidth(), 0.20000000298023224D); - worldserver.a(Particles.FISHING, this.locX, d3, this.locZ, (int) (1.0F + this.getWidth() * 20.0F), (double) this.getWidth(), 0.0D, (double) this.getWidth(), 0.20000000298023224D); - this.ar = MathHelper.nextInt(this.random, 20, 40); - } - } else if (this.as > 0) { - this.as -= i; - f = 0.15F; - if (this.as < 20) { - f = (float) ((double) f + (double) (20 - this.as) * 0.05D); - } else if (this.as < 40) { - f = (float) ((double) f + (double) (40 - this.as) * 0.02D); - } else if (this.as < 60) { - f = (float) ((double) f + (double) (60 - this.as) * 0.01D); - } - - if (this.random.nextFloat() < f) { - f1 = MathHelper.a(this.random, 0.0F, 360.0F) * 0.017453292F; - f2 = MathHelper.a(this.random, 25.0F, 60.0F); - d0 = this.locX + (double) (MathHelper.sin(f1) * f2 * 0.1F); - d1 = (double) ((float) MathHelper.floor(this.getBoundingBox().minY) + 1.0F); - d2 = this.locZ + (double) (MathHelper.cos(f1) * f2 * 0.1F); - block = worldserver.getType(new BlockPosition(d0, d1 - 1.0D, d2)).getBlock(); - if (block == Blocks.WATER) { - worldserver.a(Particles.SPLASH, d0, d1, d2, 2 + this.random.nextInt(2), 0.10000000149011612D, 0.0D, 0.10000000149011612D, 0.0D); - } - } - - if (this.as <= 0) { - this.au = MathHelper.a(this.random, 0.0F, 360.0F); - this.at = MathHelper.nextInt(this.random, 20, 80); - } - } else { - this.as = MathHelper.nextInt(this.random, world.paperConfig.fishingMinTicks, world.paperConfig.fishingMaxTicks); // Paper - this.as -= this.ax * 20 * 5; - this.as = Math.max(0, this.as); // Paper - Don't allow negative values - } - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) {} - - @Override - public void a(NBTTagCompound nbttagcompound) {} - - public int b(ItemStack itemstack) { - if (!this.world.isClientSide && this.owner != null) { - int i = 0; - - if (this.hooked != null) { - // CraftBukkit start - PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), this.hooked.getBukkitEntity(), (FishHook) this.getBukkitEntity(), PlayerFishEvent.State.CAUGHT_ENTITY); - this.world.getServer().getPluginManager().callEvent(playerFishEvent); - - if (playerFishEvent.isCancelled()) { - return 0; - } - // CraftBukkit end - this.reel(); - CriterionTriggers.D.a((EntityPlayer) this.owner, itemstack, this, Collections.emptyList()); - this.world.broadcastEntityEffect(this, (byte) 31); - i = this.hooked instanceof EntityItem ? 3 : 5; - } else if (this.ar > 0) { - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder((WorldServer) this.world)).set(LootContextParameters.POSITION, new BlockPosition(this)).set(LootContextParameters.TOOL, itemstack).a(this.random).a((float) this.aw + this.owner.eb()); - LootTable loottable = this.world.getMinecraftServer().getLootTableRegistry().getLootTable(LootTables.ab); - List list = loottable.populateLoot(loottableinfo_builder.build(LootContextParameterSets.FISHING)); - - CriterionTriggers.D.a((EntityPlayer) this.owner, itemstack, this, list); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack1 = (ItemStack) iterator.next(); - EntityItem entityitem = new EntityItem(this.world, this.locX, this.locY, this.locZ, itemstack1); - // CraftBukkit start - PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), entityitem.getBukkitEntity(), (FishHook) this.getBukkitEntity(), PlayerFishEvent.State.CAUGHT_FISH); - playerFishEvent.setExpToDrop(this.random.nextInt(6) + 1); - 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 = 0.1D; - - entityitem.setMot(d0 * 0.1D, d1 * 0.1D + Math.sqrt(Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2)) * 0.08D, d2 * 0.1D); - this.world.addEntity(entityitem); - // CraftBukkit start - this.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(), org.bukkit.entity.ExperienceOrb.SpawnReason.FISHING, this.owner, this)); // Paper - } - // CraftBukkit end - if (itemstack1.getItem().a(TagsItem.FISHES)) { - this.owner.a(StatisticList.FISH_CAUGHT, 1); - } - } - - i = 1; - } - - if (this.isInGround) { - // CraftBukkit start - PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), null, (FishHook) this.getBukkitEntity(), PlayerFishEvent.State.IN_GROUND); - this.world.getServer().getPluginManager().callEvent(playerFishEvent); - - if (playerFishEvent.isCancelled()) { - return 0; - } - // CraftBukkit end - i = 2; - } - // CraftBukkit start - if (i == 0) { - PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), null, (FishHook) this.getBukkitEntity(), PlayerFishEvent.State.REEL_IN); - this.world.getServer().getPluginManager().callEvent(playerFishEvent); - if (playerFishEvent.isCancelled()) { - return 0; - } - } - // CraftBukkit end - - this.die(); - return i; - } else { - return 0; - } - } - - protected void reel() { - if (this.owner != null) { - Vec3D vec3d = (new Vec3D(this.owner.locX - this.locX, this.owner.locY - this.locY, this.owner.locZ - this.locZ)).a(0.1D); - - this.hooked.setMot(this.hooked.getMot().e(vec3d)); - } - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - public void die() { - super.die(); - if (this.owner != null) { - this.owner.hookedFish = null; - } - - } - - @Nullable - public EntityHuman i() { - return this.owner; - } - - @Override - public boolean canPortal() { - return false; - } - - @Override - public Packet N() { - EntityHuman entityhuman = this.i(); - - return new PacketPlayOutSpawnEntity(this, entityhuman == null ? this.getId() : entityhuman.getId()); - } - - static enum HookState { - - FLYING, HOOKED_IN_ENTITY, BOBBING; - - private HookState() {} - } -} diff --git a/src/main/java/net/minecraft/server/EntityFox.java b/src/main/java/net/minecraft/server/EntityFox.java deleted file mode 100644 index ca38ccf76..000000000 --- a/src/main/java/net/minecraft/server/EntityFox.java +++ /dev/null @@ -1,1474 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Arrays; -import java.util.Comparator; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -public class EntityFox extends EntityAnimal { - - private static final DataWatcherObject bz = DataWatcher.a(EntityFox.class, DataWatcherRegistry.b); - private static final DataWatcherObject bA = DataWatcher.a(EntityFox.class, DataWatcherRegistry.a); - private static final DataWatcherObject> bB = DataWatcher.a(EntityFox.class, DataWatcherRegistry.o); - private static final DataWatcherObject> bC = DataWatcher.a(EntityFox.class, DataWatcherRegistry.o); - private static final Predicate bD = (entityitem) -> { - return !entityitem.q() && entityitem.isAlive(); - }; - private static final Predicate bE = (entity) -> { - if (!(entity instanceof EntityLiving)) { - return false; - } else { - EntityLiving entityliving = (EntityLiving) entity; - - return entityliving.cu() != null && entityliving.cv() < entityliving.ticksLived + 600; - } - }; - private static final Predicate bF = (entity) -> { - return entity instanceof EntityChicken || entity instanceof EntityRabbit; - }; - private static final Predicate bG = (entity) -> { - return !entity.isSneaking() && IEntitySelector.e.test(entity); - }; - private PathfinderGoal bH; - private PathfinderGoal bI; - private PathfinderGoal bJ; - private float bK; - private float bL; - private float bM; - private float bN; - private int bO; - - public EntityFox(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.lookController = new EntityFox.k(); - this.moveController = new EntityFox.m(); - this.a(PathType.DANGER_OTHER, 0.0F); - this.a(PathType.DAMAGE_OTHER, 0.0F); - this.setCanPickupLoot(true); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityFox.bB, Optional.empty()); - this.datawatcher.register(EntityFox.bC, Optional.empty()); - this.datawatcher.register(EntityFox.bz, 0); - this.datawatcher.register(EntityFox.bA, (byte) 0); - } - - @Override - protected void initPathfinder() { - this.bH = new PathfinderGoalNearestAttackableTarget<>(this, EntityAnimal.class, 10, false, false, (entityliving) -> { - return entityliving instanceof EntityChicken || entityliving instanceof EntityRabbit; - }); - this.bI = new PathfinderGoalNearestAttackableTarget<>(this, EntityTurtle.class, 10, false, false, EntityTurtle.bz); - this.bJ = new PathfinderGoalNearestAttackableTarget<>(this, EntityFish.class, 20, false, false, (entityliving) -> { - return entityliving instanceof EntityFishSchool; - }); - this.goalSelector.a(0, new EntityFox.g()); - this.goalSelector.a(1, new EntityFox.b()); - this.goalSelector.a(2, new EntityFox.n(2.2D)); - this.goalSelector.a(3, new PathfinderGoalAvoidTarget<>(this, EntityHuman.class, 16.0F, 1.6D, 1.4D, (entityliving) -> { - return EntityFox.bG.test(entityliving) && !this.c(entityliving.getUniqueID()) && !this.el(); - })); - this.goalSelector.a(3, new PathfinderGoalAvoidTarget<>(this, EntityWolf.class, 8.0F, 1.6D, 1.4D, (entityliving) -> { - return !((EntityWolf) entityliving).isTamed() && !this.el(); - })); - this.goalSelector.a(4, new EntityFox.u()); - this.goalSelector.a(5, new EntityFox.o()); - this.goalSelector.a(5, new EntityFox.e(1.0D)); - this.goalSelector.a(5, new EntityFox.s(1.25D)); - this.goalSelector.a(6, new EntityFox.l(1.2000000476837158D, true)); - this.goalSelector.a(6, new EntityFox.t()); - this.goalSelector.a(7, new EntityFox.h(this, 1.25D)); - this.goalSelector.a(8, new EntityFox.q(32, 200)); - this.goalSelector.a(9, new EntityFox.f(1.2000000476837158D, 12, 2)); - this.goalSelector.a(9, new PathfinderGoalLeapAtTarget(this, 0.4F)); - this.goalSelector.a(10, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.goalSelector.a(10, new EntityFox.p()); - this.goalSelector.a(11, new EntityFox.j(this, EntityHuman.class, 24.0F)); - this.goalSelector.a(12, new EntityFox.r()); - this.targetSelector.a(3, new EntityFox.a(EntityLiving.class, false, false, (entityliving) -> { - return EntityFox.bE.test(entityliving) && !this.c(entityliving.getUniqueID()); - })); - } - - @Override - public SoundEffect d(ItemStack itemstack) { - return SoundEffects.ENTITY_FOX_EAT; - } - - @Override - public void movementTick() { - if (!this.world.isClientSide && this.isAlive() && this.df()) { - ++this.bO; - ItemStack itemstack = this.getEquipment(EnumItemSlot.MAINHAND); - - if (this.j(itemstack)) { - if (this.bO > 600) { - ItemStack itemstack1 = itemstack.a(this.world, (EntityLiving) this); - - if (!itemstack1.isEmpty()) { - this.setSlot(EnumItemSlot.MAINHAND, itemstack1); - } - - this.bO = 0; - } else if (this.bO > 560 && this.random.nextFloat() < 0.1F) { - this.a(this.d(itemstack), 1.0F, 1.0F); - this.world.broadcastEntityEffect(this, (byte) 45); - } - } - - EntityLiving entityliving = this.getGoalTarget(); - - if (entityliving == null || !entityliving.isAlive()) { - this.setCrouching(false); - this.u(false); - } - } - - if (this.isSleeping() || this.isFrozen()) { - this.jumping = false; - this.bb = 0.0F; - this.bd = 0.0F; - this.be = 0.0F; - } - - super.movementTick(); - if (this.el() && this.random.nextFloat() < 0.05F) { - this.a(SoundEffects.ENTITY_FOX_AGGRO, 1.0F, 1.0F); - } - - } - - @Override - protected boolean isFrozen() { - return this.getHealth() <= 0.0F; - } - - private boolean j(ItemStack itemstack) { - return itemstack.getItem().isFood() && this.getGoalTarget() == null && this.onGround && !this.isSleeping(); - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - if (this.random.nextFloat() < 0.2F) { - float f = this.random.nextFloat(); - ItemStack itemstack; - - if (f < 0.05F) { - itemstack = new ItemStack(Items.EMERALD); - } else if (f < 0.2F) { - itemstack = new ItemStack(Items.EGG); - } else if (f < 0.4F) { - itemstack = this.random.nextBoolean() ? new ItemStack(Items.RABBIT_FOOT) : new ItemStack(Items.RABBIT_HIDE); - } else if (f < 0.6F) { - itemstack = new ItemStack(Items.WHEAT); - } else if (f < 0.8F) { - itemstack = new ItemStack(Items.LEATHER); - } else { - itemstack = new ItemStack(Items.FEATHER); - } - - this.setSlot(EnumItemSlot.MAINHAND, itemstack); - } - - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(32.0D); - this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(2.0D); - } - - @Override - public EntityFox createChild(EntityAgeable entityageable) { - EntityFox entityfox = (EntityFox) EntityTypes.FOX.a(this.world); - - entityfox.setFoxType(this.random.nextBoolean() ? this.getFoxType() : ((EntityFox) entityageable).getFoxType()); - return entityfox; - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - BiomeBase biomebase = generatoraccess.getBiome(new BlockPosition(this)); - EntityFox.Type entityfox_type = EntityFox.Type.a(biomebase); - boolean flag = false; - - if (groupdataentity instanceof EntityFox.i) { - entityfox_type = ((EntityFox.i) groupdataentity).a; - if (((EntityFox.i) groupdataentity).b >= 2) { - flag = true; - } else { - ++((EntityFox.i) groupdataentity).b; - } - } else { - groupdataentity = new EntityFox.i(entityfox_type); - ++((EntityFox.i) groupdataentity).b; - } - - this.setFoxType(entityfox_type); - if (flag) { - this.setAgeRaw(-24000); - } - - this.initializePathFinderGoals(); - this.a(difficultydamagescaler); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, (GroupDataEntity) groupdataentity, nbttagcompound); - } - - private void initializePathFinderGoals() { - if (this.getFoxType() == EntityFox.Type.RED) { - this.targetSelector.a(4, this.bH); - this.targetSelector.a(4, this.bI); - this.targetSelector.a(6, this.bJ); - } else { - this.targetSelector.a(4, this.bJ); - this.targetSelector.a(6, this.bH); - this.targetSelector.a(6, this.bI); - } - - } - - @Override - protected void a(EntityHuman entityhuman, ItemStack itemstack) { - if (this.i(itemstack)) { - this.a(this.d(itemstack), 1.0F, 1.0F); - } - - super.a(entityhuman, itemstack); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return this.isBaby() ? entitysize.height * 0.85F : 0.4F; - } - - public EntityFox.Type getFoxType() { - return EntityFox.Type.a((Integer) this.datawatcher.get(EntityFox.bz)); - } - - public void setFoxType(EntityFox.Type entityfox_type) { - this.datawatcher.set(EntityFox.bz, entityfox_type.c()); - } - - private List ek() { - List list = Lists.newArrayList(); - - list.add(((Optional) this.datawatcher.get(EntityFox.bB)).orElse(null)); // CraftBukkit - decompile error - list.add(((Optional) this.datawatcher.get(EntityFox.bC)).orElse(null)); // CraftBukkit - decompile error - return list; - } - - private void b(@Nullable UUID uuid) { - if (((Optional) this.datawatcher.get(EntityFox.bB)).isPresent()) { - this.datawatcher.set(EntityFox.bC, Optional.ofNullable(uuid)); - } else { - this.datawatcher.set(EntityFox.bB, Optional.ofNullable(uuid)); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - List list = this.ek(); - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - UUID uuid = (UUID) iterator.next(); - - if (uuid != null) { - nbttaglist.add(GameProfileSerializer.a(uuid)); - } - } - - nbttagcompound.set("TrustedUUIDs", nbttaglist); - nbttagcompound.setBoolean("Sleeping", this.isSleeping()); - nbttagcompound.setString("Type", this.getFoxType().a()); - nbttagcompound.setBoolean("Sitting", this.isSitting()); - nbttagcompound.setBoolean("Crouching", this.isCrouching()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - NBTTagList nbttaglist = nbttagcompound.getList("TrustedUUIDs", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - this.b(GameProfileSerializer.b(nbttaglist.getCompound(i))); - } - - this.setSleeping(nbttagcompound.getBoolean("Sleeping")); - this.setFoxType(EntityFox.Type.a(nbttagcompound.getString("Type"))); - this.setSitting(nbttagcompound.getBoolean("Sitting")); - this.setCrouching(nbttagcompound.getBoolean("Crouching")); - this.initializePathFinderGoals(); - } - - public boolean isSitting() { - return this.s(1); - } - - public void setSitting(boolean flag) { - this.d(1, flag); - } - - public boolean dX() { - return this.s(64); - } - - private void v(boolean flag) { - this.d(64, flag); - } - - private boolean el() { - return this.s(128); - } - - private void w(boolean flag) { - this.d(128, flag); - } - - @Override - public boolean isSleeping() { - return this.s(32); - } - - public void setSleeping(boolean flag) { - this.d(32, flag); - } - - private void d(int i, boolean flag) { - if (flag) { - this.datawatcher.set(EntityFox.bA, (byte) ((Byte) this.datawatcher.get(EntityFox.bA) | i)); - } else { - this.datawatcher.set(EntityFox.bA, (byte) ((Byte) this.datawatcher.get(EntityFox.bA) & ~i)); - } - - } - - private boolean s(int i) { - return ((Byte) this.datawatcher.get(EntityFox.bA) & i) != 0; - } - - @Override - public boolean e(ItemStack itemstack) { - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - - return !this.getEquipment(enumitemslot).isEmpty() ? false : enumitemslot == EnumItemSlot.MAINHAND && super.e(itemstack); - } - - @Override - protected boolean g(ItemStack itemstack) { - Item item = itemstack.getItem(); - ItemStack itemstack1 = this.getEquipment(EnumItemSlot.MAINHAND); - - return itemstack1.isEmpty() || this.bO > 0 && item.isFood() && !itemstack1.getItem().isFood(); - } - - private void k(ItemStack itemstack) { - if (!itemstack.isEmpty() && !this.world.isClientSide) { - EntityItem entityitem = new EntityItem(this.world, this.locX + this.getLookDirection().x, this.locY + 1.0D, this.locZ + this.getLookDirection().z, itemstack); - - entityitem.setPickupDelay(40); - entityitem.setThrower(this.getUniqueID()); - this.a(SoundEffects.ENTITY_FOX_SPIT, 1.0F, 1.0F); - this.world.addEntity(entityitem); - } - } - - private void l(ItemStack itemstack) { - EntityItem entityitem = new EntityItem(this.world, this.locX, this.locY, this.locZ, itemstack); - - this.world.addEntity(entityitem); - } - - @Override - protected void a(EntityItem entityitem) { - ItemStack itemstack = entityitem.getItemStack(); - - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callEntityPickupItemEvent(this, entityitem, itemstack.getCount() - 1, !this.g(itemstack)).isCancelled()) { // CraftBukkit - call EntityPickupItemEvent - int i = itemstack.getCount(); - - if (i > 1) { - this.l(itemstack.cloneAndSubtract(i - 1)); - } - - this.k(this.getEquipment(EnumItemSlot.MAINHAND)); - this.setSlot(EnumItemSlot.MAINHAND, itemstack.cloneAndSubtract(1)); - this.dropChanceHand[EnumItemSlot.MAINHAND.b()] = 2.0F; - this.receive(entityitem, itemstack.getCount()); - entityitem.die(); - this.bO = 0; - } - - } - - @Override - public void tick() { - super.tick(); - if (this.df()) { - boolean flag = this.isInWater(); - - if (flag || this.getGoalTarget() != null || this.world.U()) { - this.em(); - } - - if (flag || this.isSleeping()) { - this.setSitting(false); - } - - if (this.dX() && this.world.random.nextFloat() < 0.2F) { - BlockPosition blockposition = new BlockPosition(this.locX, this.locY, this.locZ); - IBlockData iblockdata = this.world.getType(blockposition); - - this.world.triggerEffect(2001, blockposition, Block.getCombinedId(iblockdata)); - } - } - - this.bL = this.bK; - if (this.eg()) { - this.bK += (1.0F - this.bK) * 0.4F; - } else { - this.bK += (0.0F - this.bK) * 0.4F; - } - - this.bN = this.bM; - if (this.isCrouching()) { - this.bM += 0.2F; - if (this.bM > 3.0F) { - this.bM = 3.0F; - } - } else { - this.bM = 0.0F; - } - - } - - @Override - public boolean i(ItemStack itemstack) { - return itemstack.getItem() == Items.SWEET_BERRIES; - } - - @Override - protected void a(EntityHuman entityhuman, EntityAgeable entityageable) { - ((EntityFox) entityageable).b(entityhuman.getUniqueID()); - } - - public boolean dY() { - return this.s(16); - } - - public void s(boolean flag) { - this.d(16, flag); - } - - public boolean ee() { - return this.bM == 3.0F; - } - - public void setCrouching(boolean flag) { - this.d(4, flag); - } - - public boolean isCrouching() { - return this.s(4); - } - - public void u(boolean flag) { - this.d(8, flag); - } - - public boolean eg() { - return this.s(8); - } - - @Override - public void setGoalTarget(@Nullable EntityLiving entityliving) { - if (this.el() && entityliving == null) { - this.w(false); - } - - super.setGoalTarget(entityliving); - } - - @Override - public void b(float f, float f1) { - int i = MathHelper.f((f - 5.0F) * f1); - - if (i > 0) { - this.damageEntity(DamageSource.FALL, (float) i); - if (this.isVehicle()) { - Iterator iterator = this.getAllPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - entity.damageEntity(DamageSource.FALL, (float) i); - } - } - - IBlockData iblockdata = this.world.getType(new BlockPosition(this.locX, this.locY - 0.2D - (double) this.lastYaw, this.locZ)); - - if (!iblockdata.isAir() && !this.isSilent()) { - SoundEffectType soundeffecttype = iblockdata.r(); - - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, soundeffecttype.d(), this.getSoundCategory(), soundeffecttype.a() * 0.5F, soundeffecttype.b() * 0.75F); - } - - } - } - - private void em() { - this.setSleeping(false); - } - - private void en() { - this.u(false); - this.setCrouching(false); - this.setSitting(false); - this.setSleeping(false); - this.w(false); - this.v(false); - } - - private boolean eo() { - return !this.isSleeping() && !this.isSitting() && !this.dX(); - } - - @Override - public void B() { - SoundEffect soundeffect = this.getSoundAmbient(); - - if (soundeffect == SoundEffects.ENTITY_FOX_SCREECH) { - this.a(soundeffect, 2.0F, this.cV()); - } else { - super.B(); - } - - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - if (this.isSleeping()) { - return SoundEffects.ENTITY_FOX_SLEEP; - } else { - if (!this.world.J() && this.random.nextFloat() < 0.1F) { - List list = this.world.a(EntityHuman.class, this.getBoundingBox().grow(16.0D, 16.0D, 16.0D), IEntitySelector.f); - - if (list.isEmpty()) { - return SoundEffects.ENTITY_FOX_SCREECH; - } - } - - return SoundEffects.ENTITY_FOX_AMBIENT; - } - } - - @Nullable - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_FOX_HURT; - } - - @Nullable - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_FOX_DEATH; - } - - private boolean c(UUID uuid) { - return this.ek().contains(uuid); - } - - @Override - protected org.bukkit.event.entity.EntityDeathEvent d(DamageSource damagesource) { // Paper - ItemStack itemstack = this.getEquipment(EnumItemSlot.MAINHAND).cloneItemStack(); // Paper - - // Paper start - Cancellable death event - org.bukkit.event.entity.EntityDeathEvent deathEvent = super.d(damagesource); - - // Below is code to drop - - if (deathEvent == null || deathEvent.isCancelled()) { - return deathEvent; - } - // Paper end - - if (!itemstack.isEmpty()) { - this.a(itemstack); - this.setSlot(EnumItemSlot.MAINHAND, ItemStack.a); - } - - return deathEvent; // Paper - } - - public static boolean a(EntityFox entityfox, EntityLiving entityliving) { - double d0 = entityliving.locZ - entityfox.locZ; - double d1 = entityliving.locX - entityfox.locX; - double d2 = d0 / d1; - boolean flag = true; - - for (int i = 0; i < 6; ++i) { - double d3 = d2 == 0.0D ? 0.0D : d0 * (double) ((float) i / 6.0F); - double d4 = d2 == 0.0D ? d1 * (double) ((float) i / 6.0F) : d3 / d2; - - for (int j = 1; j < 4; ++j) { - if (!entityfox.world.getType(new BlockPosition(entityfox.locX + d4, entityfox.locY + (double) j, entityfox.locZ + d3)).getMaterial().isReplaceable()) { - return false; - } - } - } - - return true; - } - - class j extends PathfinderGoalLookAtPlayer { - - public j(EntityInsentient entityinsentient, Class oclass, float f) { - super(entityinsentient, oclass, f); - } - - @Override - public boolean a() { - return super.a() && !EntityFox.this.dX() && !EntityFox.this.eg(); - } - - @Override - public boolean b() { - return super.b() && !EntityFox.this.dX() && !EntityFox.this.eg(); - } - } - - class h extends PathfinderGoalFollowParent { - - private final EntityFox b; - - public h(EntityFox entityfox, double d0) { - super(entityfox, d0); - this.b = entityfox; - } - - @Override - public boolean a() { - return !this.b.el() && super.a(); - } - - @Override - public boolean b() { - return !this.b.el() && super.b(); - } - - @Override - public void c() { - this.b.en(); - super.c(); - } - } - - public class k extends ControllerLook { - - public k() { - super(EntityFox.this); - } - - @Override - public void a() { - if (!EntityFox.this.isSleeping()) { - super.a(); - } - - } - - @Override - protected boolean b() { - return !EntityFox.this.dY() && !EntityFox.this.isCrouching() && !EntityFox.this.eg() & !EntityFox.this.dX(); - } - } - - public class o extends PathfinderGoalWaterJumpAbstract { - - public o() {} - - @Override - public boolean a() { - if (!EntityFox.this.ee()) { - return false; - } else { - EntityLiving entityliving = EntityFox.this.getGoalTarget(); - - if (entityliving != null && entityliving.isAlive()) { - if (entityliving.getAdjustedDirection() != entityliving.getDirection()) { - return false; - } else { - boolean flag = EntityFox.a((EntityFox) EntityFox.this, entityliving); - - if (!flag) { - EntityFox.this.getNavigation().a((Entity) entityliving, 0); - EntityFox.this.setCrouching(false); - EntityFox.this.u(false); - } - - return flag; - } - } else { - return false; - } - } - } - - @Override - public boolean b() { - EntityLiving entityliving = EntityFox.this.getGoalTarget(); - - if (entityliving != null && entityliving.isAlive()) { - double d0 = EntityFox.this.getMot().y; - - return (d0 * d0 >= 0.05000000074505806D || Math.abs(EntityFox.this.pitch) >= 15.0F || !EntityFox.this.onGround) && !EntityFox.this.dX(); - } else { - return false; - } - } - - @Override - public boolean C_() { - return false; - } - - @Override - public void c() { - EntityFox.this.setJumping(true); - EntityFox.this.s(true); - EntityFox.this.u(false); - EntityLiving entityliving = EntityFox.this.getGoalTarget(); - - EntityFox.this.getControllerLook().a(entityliving, 60.0F, 30.0F); - Vec3D vec3d = (new Vec3D(entityliving.locX - EntityFox.this.locX, entityliving.locY - EntityFox.this.locY, entityliving.locZ - EntityFox.this.locZ)).d(); - - EntityFox.this.setMot(EntityFox.this.getMot().add(vec3d.x * 0.8D, 0.9D, vec3d.z * 0.8D)); - EntityFox.this.getNavigation().o(); - } - - @Override - public void d() { - EntityFox.this.setCrouching(false); - EntityFox.this.bM = 0.0F; - EntityFox.this.bN = 0.0F; - EntityFox.this.u(false); - EntityFox.this.s(false); - } - - @Override - public void e() { - EntityLiving entityliving = EntityFox.this.getGoalTarget(); - - if (entityliving != null) { - EntityFox.this.getControllerLook().a(entityliving, 60.0F, 30.0F); - } - - if (!EntityFox.this.dX()) { - Vec3D vec3d = EntityFox.this.getMot(); - - if (vec3d.y * vec3d.y < 0.029999999329447746D && EntityFox.this.pitch != 0.0F) { - EntityFox.this.pitch = this.a(EntityFox.this.pitch, 0.0F, 0.2F); - } else { - double d0 = Math.sqrt(Entity.b(vec3d)); - double d1 = Math.signum(-vec3d.y) * Math.acos(d0 / vec3d.f()) * 57.2957763671875D; - - EntityFox.this.pitch = (float) d1; - } - } - - if (entityliving != null && EntityFox.this.g((Entity) entityliving) <= 2.0F) { - EntityFox.this.C(entityliving); - } else if (EntityFox.this.pitch > 0.0F && EntityFox.this.onGround && (float) EntityFox.this.getMot().y != 0.0F && EntityFox.this.world.getType(new BlockPosition(EntityFox.this)).getBlock() == Blocks.SNOW) { - EntityFox.this.pitch = 60.0F; - EntityFox.this.setGoalTarget((EntityLiving) null); - EntityFox.this.v(true); - } - - } - } - - class g extends PathfinderGoalFloat { - - public g() { - super(EntityFox.this); - } - - @Override - public void c() { - super.c(); - EntityFox.this.en(); - } - - @Override - public boolean a() { - return EntityFox.this.isInWater() && EntityFox.this.cf() > 0.25D || EntityFox.this.aD(); - } - } - - class q extends PathfinderGoalNearestVillage { - - public q(int i, int j) { - super(EntityFox.this, j); - } - - @Override - public void c() { - EntityFox.this.en(); - super.c(); - } - - @Override - public boolean a() { - return super.a() && this.g(); - } - - @Override - public boolean b() { - return super.b() && this.g(); - } - - private boolean g() { - return !EntityFox.this.isSleeping() && !EntityFox.this.isSitting() && !EntityFox.this.el() && EntityFox.this.getGoalTarget() == null; - } - } - - class n extends PathfinderGoalPanic { - - public n(double d0) { - super(EntityFox.this, d0); - } - - @Override - public boolean a() { - return !EntityFox.this.el() && super.a(); - } - } - - class b extends PathfinderGoal { - - int a; - - public b() { - this.a(EnumSet.of(PathfinderGoal.Type.LOOK, PathfinderGoal.Type.JUMP, PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - return EntityFox.this.dX(); - } - - @Override - public boolean b() { - return this.a() && this.a > 0; - } - - @Override - public void c() { - this.a = 40; - } - - @Override - public void d() { - EntityFox.this.v(false); - } - - @Override - public void e() { - --this.a; - } - } - - public static class i implements GroupDataEntity { - - public final EntityFox.Type a; - public int b; - - public i(EntityFox.Type entityfox_type) { - this.a = entityfox_type; - } - } - - public class f extends PathfinderGoalGotoTarget { - - protected int g; - - public f(double d0, int i, int j) { - super(EntityFox.this, d0, i, j); - } - - @Override - public double h() { - return 2.0D; - } - - @Override - public boolean j() { - return this.d % 100 == 0; - } - - @Override - protected boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - IBlockData iblockdata = iworldreader.getType(blockposition); - - return iblockdata.getBlock() == Blocks.SWEET_BERRY_BUSH && (Integer) iblockdata.get(BlockSweetBerryBush.a) >= 2; - } - - @Override - public void e() { - if (this.k()) { - if (this.g >= 40) { - this.m(); - } else { - ++this.g; - } - } else if (!this.k() && EntityFox.this.random.nextFloat() < 0.05F) { - EntityFox.this.a(SoundEffects.ENTITY_FOX_SNIFF, 1.0F, 1.0F); - } - - super.e(); - } - - protected void m() { - if (EntityFox.this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - IBlockData iblockdata = EntityFox.this.world.getType(this.e); - - if (iblockdata.getBlock() == Blocks.SWEET_BERRY_BUSH) { - int i = (Integer) iblockdata.get(BlockSweetBerryBush.a); - - iblockdata.set(BlockSweetBerryBush.a, 1); - // CraftBukkit start - call EntityChangeBlockEvent - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(EntityFox.this, this.e, iblockdata.set(BlockSweetBerryBush.a, 1)).isCancelled()) { - return; - } - // CraftBukkit end - int j = 1 + EntityFox.this.world.random.nextInt(2) + (i == 3 ? 1 : 0); - ItemStack itemstack = EntityFox.this.getEquipment(EnumItemSlot.MAINHAND); - - if (itemstack.isEmpty()) { - EntityFox.this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.SWEET_BERRIES)); - --j; - } - - if (j > 0) { - Block.a(EntityFox.this.world, this.e, new ItemStack(Items.SWEET_BERRIES, j)); - } - - EntityFox.this.a(SoundEffects.ITEM_SWEET_BERRIES_PICK_FROM_BUSH, 1.0F, 1.0F); - EntityFox.this.world.setTypeAndData(this.e, (IBlockData) iblockdata.set(BlockSweetBerryBush.a, 1), 2); - } - } - } - - @Override - public boolean a() { - return !EntityFox.this.isSleeping() && super.a(); - } - - @Override - public void c() { - this.g = 0; - EntityFox.this.setSitting(false); - super.c(); - } - } - - class r extends EntityFox.d { - - private double c; - private double d; - private int e; - private int f; - - public r() { - super(); // CraftBukkit - decompile error - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - return EntityFox.this.getLastDamager() == null && EntityFox.this.getRandom().nextFloat() < 0.02F && !EntityFox.this.isSleeping() && EntityFox.this.getGoalTarget() == null && EntityFox.this.getNavigation().n() && !this.h() && !EntityFox.this.dY() && !EntityFox.this.isCrouching(); - } - - @Override - public boolean b() { - return this.f > 0; - } - - @Override - public void c() { - this.j(); - this.f = 2 + EntityFox.this.getRandom().nextInt(3); - EntityFox.this.setSitting(true); - EntityFox.this.getNavigation().o(); - } - - @Override - public void d() { - EntityFox.this.setSitting(false); - } - - @Override - public void e() { - --this.e; - if (this.e <= 0) { - --this.f; - this.j(); - } - - EntityFox.this.getControllerLook().a(EntityFox.this.locX + this.c, EntityFox.this.locY + (double) EntityFox.this.getHeadHeight(), EntityFox.this.locZ + this.d, (float) EntityFox.this.dA(), (float) EntityFox.this.M()); - } - - private void j() { - double d0 = 6.283185307179586D * EntityFox.this.getRandom().nextDouble(); - - this.c = Math.cos(d0); - this.d = Math.sin(d0); - this.e = 80 + EntityFox.this.getRandom().nextInt(20); - } - } - - class t extends EntityFox.d { - - private int c; - - public t() { - super(); // CraftBukkit - decompile error - this.c = EntityFox.this.random.nextInt(140); - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK, PathfinderGoal.Type.JUMP)); - } - - @Override - public boolean a() { - return EntityFox.this.bb == 0.0F && EntityFox.this.bc == 0.0F && EntityFox.this.bd == 0.0F ? this.j() || EntityFox.this.isSleeping() : false; - } - - @Override - public boolean b() { - return this.j(); - } - - private boolean j() { - if (this.c > 0) { - --this.c; - return false; - } else { - return EntityFox.this.world.J() && this.g() && !this.h(); - } - } - - @Override - public void d() { - this.c = EntityFox.this.random.nextInt(140); - EntityFox.this.en(); - } - - @Override - public void c() { - EntityFox.this.setSitting(false); - EntityFox.this.setCrouching(false); - EntityFox.this.u(false); - EntityFox.this.setJumping(false); - EntityFox.this.setSleeping(true); - EntityFox.this.getNavigation().o(); - EntityFox.this.getControllerMove().a(EntityFox.this.locX, EntityFox.this.locY, EntityFox.this.locZ, 0.0D); - } - } - - abstract class d extends PathfinderGoal { - - private final PathfinderTargetCondition b; - - private d() { - this.b = (new PathfinderTargetCondition()).a(12.0D).c().a(EntityFox.this.new c()); - } - - protected boolean g() { - BlockPosition blockposition = new BlockPosition(EntityFox.this); - - return !EntityFox.this.world.f(blockposition) && EntityFox.this.f(blockposition) >= 0.0F; - } - - protected boolean h() { - return !EntityFox.this.world.a(EntityLiving.class, this.b, EntityFox.this, EntityFox.this.getBoundingBox().grow(12.0D, 6.0D, 12.0D)).isEmpty(); - } - } - - public class c implements Predicate { - - public c() {} - - public boolean test(EntityLiving entityliving) { - return entityliving instanceof EntityFox ? false : (!(entityliving instanceof EntityChicken) && !(entityliving instanceof EntityRabbit) && !(entityliving instanceof EntityMonster) ? (entityliving instanceof EntityTameableAnimal ? !((EntityTameableAnimal) entityliving).isTamed() : (entityliving instanceof EntityHuman && (entityliving.isSpectator() || ((EntityHuman) entityliving).isCreative()) ? false : (EntityFox.this.c(entityliving.getUniqueID()) ? false : !entityliving.isSleeping() && !entityliving.isSneaking()))) : true); - } - } - - class s extends PathfinderGoalFleeSun { - - private int c = 100; - - public s(double d0) { - super(EntityFox.this, d0); - } - - @Override - public boolean a() { - if (!EntityFox.this.isSleeping() && this.a.getGoalTarget() == null) { - if (EntityFox.this.world.U()) { - return true; - } else if (this.c > 0) { - --this.c; - return false; - } else { - this.c = 100; - BlockPosition blockposition = new BlockPosition(this.a); - - return EntityFox.this.world.J() && EntityFox.this.world.f(blockposition) && !((WorldServer) EntityFox.this.world).b_(blockposition) && this.g(); - } - } else { - return false; - } - } - - @Override - public void c() { - EntityFox.this.en(); - super.c(); - } - } - - class a extends PathfinderGoalNearestAttackableTarget { - - @Nullable - private EntityLiving j; - private EntityLiving k; - private int l; - - public a(Class oclass, boolean flag, boolean flag1, Predicate predicate) { // CraftBukkit - decompile error - super(EntityFox.this, oclass, 10, flag, flag1, predicate); - } - - @Override - public boolean a() { - if (this.b > 0 && this.e.getRandom().nextInt(this.b) != 0) { - return false; - } else { - Iterator iterator = EntityFox.this.ek().iterator(); - - while (iterator.hasNext()) { - UUID uuid = (UUID) iterator.next(); - - if (uuid != null && EntityFox.this.world instanceof WorldServer) { - Entity entity = ((WorldServer) EntityFox.this.world).getEntity(uuid); - - if (entity instanceof EntityLiving) { - EntityLiving entityliving = (EntityLiving) entity; - - this.k = entityliving; - this.j = entityliving.getLastDamager(); - int i = entityliving.ct(); - - return i != this.l && this.a(this.j, this.d); - } - } - } - - return false; - } - } - - @Override - public void c() { - EntityFox.this.setGoalTarget(this.j, org.bukkit.event.entity.EntityTargetEvent.TargetReason.TARGET_ATTACKED_OWNER, true); // CraftBukkit - this.c = this.j; - if (this.k != null) { - this.l = this.k.ct(); - } - - EntityFox.this.a(SoundEffects.ENTITY_FOX_AGGRO, 1.0F, 1.0F); - EntityFox.this.w(true); - EntityFox.this.em(); - super.c(); - } - } - - class e extends PathfinderGoalBreed { - - public e(double d0) { - super(EntityFox.this, d0); - } - - @Override - public void c() { - ((EntityFox) this.animal).en(); - ((EntityFox) this.partner).en(); - super.c(); - } - - @Override - protected void g() { - EntityFox entityfox = (EntityFox) this.animal.createChild(this.partner); - - if (entityfox != null) { - EntityPlayer entityplayer = this.animal.getBreedCause(); - EntityPlayer entityplayer1 = this.partner.getBreedCause(); - EntityPlayer entityplayer2 = entityplayer; - - if (entityplayer != null) { - entityfox.b(entityplayer.getUniqueID()); - } else { - entityplayer2 = entityplayer1; - } - - if (entityplayer1 != null && entityplayer != entityplayer1) { - entityfox.b(entityplayer1.getUniqueID()); - } - // CraftBukkit start - call EntityBreedEvent - int experience = this.animal.getRandom().nextInt(7) + 1; - org.bukkit.event.entity.EntityBreedEvent entityBreedEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityBreedEvent(entityfox, animal, partner, entityplayer, this.animal.breedItem, experience); - if (entityBreedEvent.isCancelled()) { - return; - } - experience = entityBreedEvent.getExperience(); - // CraftBukkit end - - if (entityplayer2 != null) { - entityplayer2.a(StatisticList.ANIMALS_BRED); - CriterionTriggers.o.a(entityplayer2, this.animal, this.partner, entityfox); - } - - boolean flag = true; - - this.animal.setAgeRaw(6000); - this.partner.setAgeRaw(6000); - this.animal.resetLove(); - this.partner.resetLove(); - entityfox.setAgeRaw(-24000); - entityfox.setPositionRotation(this.animal.locX, this.animal.locY, this.animal.locZ, 0.0F, 0.0F); - this.b.addEntity(entityfox, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.BREEDING); // CraftBukkit - added SpawnReason - this.b.broadcastEntityEffect(this.animal, (byte) 18); - if (this.b.getGameRules().getBoolean(GameRules.DO_MOB_LOOT)) { - // CraftBukkit start - use event experience - if (experience > 0) { - this.b.addEntity(new EntityExperienceOrb(this.b, this.animal.locX, this.animal.locY, this.animal.locZ, experience)); - } - // CraftBukkit end - } - - } - } - } - - class l extends PathfinderGoalMeleeAttack { - - public l(double d0, boolean flag) { - super(EntityFox.this, d0, flag); - } - - @Override - protected void a(EntityLiving entityliving, double d0) { - double d1 = this.a(entityliving); - - if (d0 <= d1 && this.b <= 0) { - this.b = 20; - this.a.C(entityliving); - EntityFox.this.a(SoundEffects.ENTITY_FOX_BITE, 1.0F, 1.0F); - } - - } - - @Override - public void c() { - EntityFox.this.u(false); - super.c(); - } - - @Override - public boolean a() { - return !EntityFox.this.isSitting() && !EntityFox.this.isSleeping() && !EntityFox.this.isCrouching() && !EntityFox.this.dX() && super.a(); - } - } - - class u extends PathfinderGoal { - - public u() { - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - if (EntityFox.this.isSleeping()) { - return false; - } else { - EntityLiving entityliving = EntityFox.this.getGoalTarget(); - - return entityliving != null && entityliving.isAlive() && EntityFox.bF.test(entityliving) && EntityFox.this.h((Entity) entityliving) > 36.0D && !EntityFox.this.isCrouching() && !EntityFox.this.eg() && !EntityFox.this.jumping; - } - } - - @Override - public void c() { - EntityFox.this.setSitting(false); - EntityFox.this.v(false); - } - - @Override - public void d() { - EntityLiving entityliving = EntityFox.this.getGoalTarget(); - - if (entityliving != null && EntityFox.a((EntityFox) EntityFox.this, entityliving)) { - EntityFox.this.u(true); - EntityFox.this.setCrouching(true); - EntityFox.this.getNavigation().o(); - EntityFox.this.getControllerLook().a(entityliving, (float) EntityFox.this.dA(), (float) EntityFox.this.M()); - } else { - EntityFox.this.u(false); - EntityFox.this.setCrouching(false); - } - - } - - @Override - public void e() { - EntityLiving entityliving = EntityFox.this.getGoalTarget(); - - EntityFox.this.getControllerLook().a(entityliving, (float) EntityFox.this.dA(), (float) EntityFox.this.M()); - if (EntityFox.this.h((Entity) entityliving) <= 36.0D) { - EntityFox.this.u(true); - EntityFox.this.setCrouching(true); - EntityFox.this.getNavigation().o(); - } else { - EntityFox.this.getNavigation().a((Entity) entityliving, 1.5D); - } - - } - } - - class m extends ControllerMove { - - public m() { - super(EntityFox.this); - } - - @Override - public void a() { - if (EntityFox.this.eo()) { - super.a(); - } - - } - } - - class p extends PathfinderGoal { - - public p() { - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - if (!EntityFox.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty()) { - return false; - } else if (EntityFox.this.getGoalTarget() == null && EntityFox.this.getLastDamager() == null) { - if (!EntityFox.this.eo()) { - return false; - } else if (EntityFox.this.getRandom().nextInt(10) != 0) { - return false; - } else { - List list = EntityFox.this.world.a(EntityItem.class, EntityFox.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityFox.bD); - - return !list.isEmpty() && EntityFox.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty(); - } - } else { - return false; - } - } - - @Override - public void e() { - List list = EntityFox.this.world.a(EntityItem.class, EntityFox.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityFox.bD); - ItemStack itemstack = EntityFox.this.getEquipment(EnumItemSlot.MAINHAND); - - if (itemstack.isEmpty() && !list.isEmpty()) { - EntityFox.this.getNavigation().a((Entity) list.get(0), 1.2000000476837158D); - } - - } - - @Override - public void c() { - List list = EntityFox.this.world.a(EntityItem.class, EntityFox.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityFox.bD); - - if (!list.isEmpty()) { - EntityFox.this.getNavigation().a((Entity) list.get(0), 1.2000000476837158D); - } - - } - } - - public static enum Type { - - RED(0, "red", new BiomeBase[]{Biomes.TAIGA, Biomes.TAIGA_HILLS, Biomes.TAIGA_MOUNTAINS, Biomes.GIANT_TREE_TAIGA, Biomes.GIANT_SPRUCE_TAIGA, Biomes.GIANT_TREE_TAIGA_HILLS, Biomes.GIANT_SPRUCE_TAIGA_HILLS}), SNOW(1, "snow", new BiomeBase[]{Biomes.SNOWY_TAIGA, Biomes.SNOWY_TAIGA_HILLS, Biomes.SNOWY_TAIGA_MOUNTAINS}); - - private static final EntityFox.Type[] c = (EntityFox.Type[]) Arrays.stream(values()).sorted(Comparator.comparingInt(EntityFox.Type::c)).toArray((i) -> { - return new EntityFox.Type[i]; - }); - private static final Map d = (Map) Arrays.stream(values()).collect(Collectors.toMap(EntityFox.Type::a, (entityfox_type) -> { - return entityfox_type; - })); - private final int e; - private final String f; - private final List g; - - private Type(int i, String s, BiomeBase... abiomebase) { - this.e = i; - this.f = s; - this.g = Arrays.asList(abiomebase); - } - - public String a() { - return this.f; - } - - public List b() { - return this.g; - } - - public int c() { - return this.e; - } - - public static EntityFox.Type a(String s) { - return (EntityFox.Type) EntityFox.Type.d.getOrDefault(s, EntityFox.Type.RED); - } - - public static EntityFox.Type a(int i) { - if (i < 0 || i > EntityFox.Type.c.length) { - i = 0; - } - - return EntityFox.Type.c[i]; - } - - public static EntityFox.Type a(BiomeBase biomebase) { - return EntityFox.Type.SNOW.b().contains(biomebase) ? EntityFox.Type.SNOW : EntityFox.Type.RED; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityGhast.java b/src/main/java/net/minecraft/server/EntityGhast.java deleted file mode 100644 index f25c828df..000000000 --- a/src/main/java/net/minecraft/server/EntityGhast.java +++ /dev/null @@ -1,306 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Random; - -public class EntityGhast extends EntityFlying implements IMonster { - - private static final DataWatcherObject b = DataWatcher.a(EntityGhast.class, DataWatcherRegistry.i); - private int c = 1; - - public EntityGhast(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.f = 5; - this.moveController = new EntityGhast.ControllerGhast(this); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(5, new EntityGhast.PathfinderGoalGhastIdleMove(this)); - this.goalSelector.a(7, new EntityGhast.PathfinderGoalGhastMoveTowardsTarget(this)); - this.goalSelector.a(7, new EntityGhast.PathfinderGoalGhastAttackTarget(this)); - this.targetSelector.a(1, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, 10, true, false, (entityliving) -> { - return Math.abs(entityliving.locY - this.locY) <= 4.0D; - })); - } - - public void r(boolean flag) { - this.datawatcher.set(EntityGhast.b, flag); - } - - public int getPower() { - return this.c; - } - - @Override - public void tick() { - super.tick(); - if (!this.world.isClientSide && this.world.getDifficulty() == EnumDifficulty.PEACEFUL) { - this.die(); - } - - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (damagesource.j() instanceof EntityLargeFireball && damagesource.getEntity() instanceof EntityHuman) { - super.damageEntity(damagesource, 1000.0F); - return true; - } else { - return super.damageEntity(damagesource, f); - } - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityGhast.b, false); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(100.0D); - } - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.HOSTILE; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_GHAST_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_GHAST_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_GHAST_DEATH; - } - - @Override - protected float getSoundVolume() { - return 10.0F; - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return generatoraccess.getDifficulty() != EnumDifficulty.PEACEFUL && random.nextInt(20) == 0 && a(entitytypes, generatoraccess, enummobspawn, blockposition, random); - } - - @Override - public int dC() { - return 1; - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("ExplosionPower", this.c); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("ExplosionPower", 99)) { - this.c = nbttagcompound.getInt("ExplosionPower"); - } - - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 2.6F; - } - - static class PathfinderGoalGhastAttackTarget extends PathfinderGoal { - - private final EntityGhast ghast; - public int a; - - public PathfinderGoalGhastAttackTarget(EntityGhast entityghast) { - this.ghast = entityghast; - } - - @Override - public boolean a() { - return this.ghast.getGoalTarget() != null; - } - - @Override - public void c() { - this.a = 0; - } - - @Override - public void d() { - this.ghast.r(false); - } - - @Override - public void e() { - EntityLiving entityliving = this.ghast.getGoalTarget(); - double d0 = 64.0D; - - if (entityliving.h((Entity) this.ghast) < 4096.0D && this.ghast.hasLineOfSight(entityliving)) { - World world = this.ghast.world; - - ++this.a; - if (this.a == 10) { - world.a((EntityHuman) null, 1015, new BlockPosition(this.ghast), 0); - } - - if (this.a == 20) { - double d1 = 4.0D; - Vec3D vec3d = this.ghast.f(1.0F); - double d2 = entityliving.locX - (this.ghast.locX + vec3d.x * 4.0D); - double d3 = entityliving.getBoundingBox().minY + (double) (entityliving.getHeight() / 2.0F) - (0.5D + this.ghast.locY + (double) (this.ghast.getHeight() / 2.0F)); - double d4 = entityliving.locZ - (this.ghast.locZ + vec3d.z * 4.0D); - - world.a((EntityHuman) null, 1016, new BlockPosition(this.ghast), 0); - EntityLargeFireball entitylargefireball = new EntityLargeFireball(world, this.ghast, d2, d3, d4); - - // CraftBukkit - set bukkitYield when setting explosionpower - entitylargefireball.bukkitYield = entitylargefireball.yield = this.ghast.getPower(); - entitylargefireball.locX = this.ghast.locX + vec3d.x * 4.0D; - entitylargefireball.locY = this.ghast.locY + (double) (this.ghast.getHeight() / 2.0F) + 0.5D; - entitylargefireball.locZ = this.ghast.locZ + vec3d.z * 4.0D; - world.addEntity(entitylargefireball); - this.a = -40; - } - } else if (this.a > 0) { - --this.a; - } - - this.ghast.r(this.a > 10); - } - } - - static class PathfinderGoalGhastMoveTowardsTarget extends PathfinderGoal { - - private final EntityGhast a; - - public PathfinderGoalGhastMoveTowardsTarget(EntityGhast entityghast) { - this.a = entityghast; - this.a(EnumSet.of(PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - return true; - } - - @Override - public void e() { - if (this.a.getGoalTarget() == null) { - Vec3D vec3d = this.a.getMot(); - - this.a.yaw = -((float) MathHelper.d(vec3d.x, vec3d.z)) * 57.295776F; - this.a.aK = this.a.yaw; - } else { - EntityLiving entityliving = this.a.getGoalTarget(); - double d0 = 64.0D; - - if (entityliving.h((Entity) this.a) < 4096.0D) { - double d1 = entityliving.locX - this.a.locX; - double d2 = entityliving.locZ - this.a.locZ; - - this.a.yaw = -((float) MathHelper.d(d1, d2)) * 57.295776F; - this.a.aK = this.a.yaw; - } - } - - } - } - - static class PathfinderGoalGhastIdleMove extends PathfinderGoal { - - private final EntityGhast a; - - public PathfinderGoalGhastIdleMove(EntityGhast entityghast) { - this.a = entityghast; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - ControllerMove controllermove = this.a.getControllerMove(); - - if (!controllermove.b()) { - 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; - } - } - - @Override - public boolean b() { - return false; - } - - @Override - public void c() { - Random random = this.a.getRandom(); - 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 i; - private int j; - - public ControllerGhast(EntityGhast entityghast) { - super(entityghast); - this.i = entityghast; - } - - @Override - public void a() { - if (this.h == ControllerMove.Operation.MOVE_TO) { - if (this.j-- <= 0) { - this.j += this.i.getRandom().nextInt(5) + 2; - Vec3D vec3d = new Vec3D(this.b - this.i.locX, this.c - this.i.locY, this.d - this.i.locZ); - double d0 = vec3d.f(); - - vec3d = vec3d.d(); - if (this.a(vec3d, MathHelper.f(d0))) { - this.i.setMot(this.i.getMot().e(vec3d.a(0.1D))); - } else { - this.h = ControllerMove.Operation.WAIT; - } - } - - } - } - - private boolean a(Vec3D vec3d, int i) { - AxisAlignedBB axisalignedbb = this.i.getBoundingBox(); - - for (int j = 1; j < i; ++j) { - axisalignedbb = axisalignedbb.b(vec3d); - if (!this.i.world.getCubes(this.i, axisalignedbb)) { - return false; - } - } - - return true; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityGuardianElder.java b/src/main/java/net/minecraft/server/EntityGuardianElder.java deleted file mode 100644 index 7248d46cf..000000000 --- a/src/main/java/net/minecraft/server/EntityGuardianElder.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; - -public class EntityGuardianElder extends EntityGuardian { - - public static final float b = EntityTypes.ELDER_GUARDIAN.i() / EntityTypes.GUARDIAN.i(); - - public EntityGuardianElder(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.setPersistent(); - if (this.goalRandomStroll != null) { - this.goalRandomStroll.setTimeBetweenMovement(400); - } - - } - - @Override - public void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(8.0D); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(80.0D); - } - - @Override - public int l() { - return 60; - } - - @Override - protected SoundEffect getSoundAmbient() { - return this.av() ? SoundEffects.ENTITY_ELDER_GUARDIAN_AMBIENT : SoundEffects.ENTITY_ELDER_GUARDIAN_AMBIENT_LAND; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return this.av() ? SoundEffects.ENTITY_ELDER_GUARDIAN_HURT : SoundEffects.ENTITY_ELDER_GUARDIAN_HURT_LAND; - } - - @Override - protected SoundEffect getSoundDeath() { - return this.av() ? SoundEffects.ENTITY_ELDER_GUARDIAN_DEATH : SoundEffects.ENTITY_ELDER_GUARDIAN_DEATH_LAND; - } - - @Override - protected SoundEffect getSoundFlop() { - return SoundEffects.ENTITY_ELDER_GUARDIAN_FLOP; - } - - @Override - protected void mobTick() { - super.mobTick(); - boolean flag = true; - - if ((this.ticksLived + this.getId()) % 1200 == 0) { - MobEffectList mobeffectlist = MobEffects.SLOWER_DIG; - List list = ((WorldServer) this.world).a((entityplayer) -> { - return this.h((Entity) entityplayer) < 2500.0D && entityplayer.playerInteractManager.c(); - }); - boolean flag1 = true; - boolean flag2 = true; - boolean flag3 = true; - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - 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, 6000, 2), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - } - } - - if (!this.dL()) { - this.a(new BlockPosition(this), 16); - } - - } -} diff --git a/src/main/java/net/minecraft/server/EntityHanging.java b/src/main/java/net/minecraft/server/EntityHanging.java deleted file mode 100644 index 2b4a849f4..000000000 --- a/src/main/java/net/minecraft/server/EntityHanging.java +++ /dev/null @@ -1,320 +0,0 @@ -package net.minecraft.server; - -import java.util.function.Predicate; -import javax.annotation.Nullable; -import org.apache.commons.lang3.Validate; - -// CraftBukkit start -import org.bukkit.entity.Hanging; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.hanging.HangingBreakEvent; -// CraftBukkit end - -public abstract class EntityHanging extends Entity { - - protected static final Predicate b = (entity) -> { - return entity instanceof EntityHanging; - }; - private int e; { this.e = this.getId() % this.world.spigotConfig.hangingTickFrequency; } // Paper - public BlockPosition blockPosition; - protected EnumDirection direction; - - protected EntityHanging(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.direction = EnumDirection.SOUTH; - } - - protected EntityHanging(EntityTypes entitytypes, World world, BlockPosition blockposition) { - this(entitytypes, world); - this.blockPosition = blockposition; - } - - @Override - protected void initDatawatcher() {} - - public void setDirection(EnumDirection enumdirection) { - Validate.notNull(enumdirection); - Validate.isTrue(enumdirection.k().c()); - this.direction = enumdirection; - this.yaw = (float) (this.direction.get2DRotationValue() * 90); - this.lastYaw = this.yaw; - this.updateBoundingBox(); - } - - protected void updateBoundingBox() { - if (this.direction != null) { - // CraftBukkit start code moved in to calculateBoundingBox - this.a(calculateBoundingBox(this, this.blockPosition, this.direction, this.getHangingWidth(), this.getHangingHeight())); - // CraftBukkit end - } - } - - // CraftBukkit start - break out BB calc into own method - public static AxisAlignedBB calculateBoundingBox(@Nullable Entity entity, BlockPosition blockPosition, EnumDirection direction, int width, int height) { - { - double d0 = (double) blockPosition.getX() + 0.5D; - double d1 = (double) blockPosition.getY() + 0.5D; - double d2 = (double) blockPosition.getZ() + 0.5D; - double d3 = 0.46875D; - double d4 = a(width); - double d5 = a(height); - - d0 -= (double) direction.getAdjacentX() * 0.46875D; - d2 -= (double) direction.getAdjacentZ() * 0.46875D; - d1 += d5; - EnumDirection enumdirection = direction.f(); - - d0 += d4 * (double) enumdirection.getAdjacentX(); - d2 += d4 * (double) enumdirection.getAdjacentZ(); - if (entity != null) { - entity.locX = d0; - entity.locY = d1; - entity.locZ = d2; - } - double d6 = (double) width; - double d7 = (double) height; - double d8 = (double) 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); - } - } - // CraftBukkit end - - private static double a(int i) { // CraftBukkit - static - return i % 32 == 0 ? 0.5D : 0.0D; - } - - @Override - public void tick() { - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - if (this.e++ == this.world.spigotConfig.hangingTickFrequency && !this.world.isClientSide) { // Spigot - this.e = 0; - if (!this.dead && !this.survives()) { - // CraftBukkit start - fire break events - Material material = this.world.getType(new BlockPosition(this)).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); - - if (dead || event.isCancelled()) { - return; - } - // CraftBukkit end - this.die(); - this.a((Entity) null); - } - } - - } - - public boolean survives() { - if (!this.world.getCubes(this)) { - return false; - } else { - int i = Math.max(1, this.getHangingWidth() / 16); - int j = Math.max(1, this.getHangingHeight() / 16); - BlockPosition blockposition = this.blockPosition.shift(this.direction.opposite()); - EnumDirection enumdirection = this.direction.f(); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - for (int k = 0; k < i; ++k) { - for (int l = 0; l < j; ++l) { - int i1 = (i - 1) / -2; - int j1 = (j - 1) / -2; - - blockposition_mutableblockposition.g(blockposition).c(enumdirection, k + i1).c(EnumDirection.UP, l + j1); - IBlockData iblockdata = this.world.getType(blockposition_mutableblockposition); - - if (!iblockdata.getMaterial().isBuildable() && !BlockDiodeAbstract.isDiode(iblockdata)) { - return false; - } - } - } - - return this.world.getEntities(this, this.getBoundingBox(), EntityHanging.b).isEmpty(); - } - } - - @Override - public boolean isInteractable() { - return true; - } - - @Override - public boolean t(Entity entity) { - return entity instanceof EntityHuman ? this.damageEntity(DamageSource.playerAttack((EntityHuman) entity), 0.0F) : false; - } - - @Override - public EnumDirection getDirection() { - return this.direction; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - if (!this.dead && !this.world.isClientSide) { - // CraftBukkit start - fire break events - HangingBreakEvent event = new HangingBreakEvent((Hanging) this.getBukkitEntity(), HangingBreakEvent.RemoveCause.DEFAULT); - if (damagesource.getEntity() != null) { - event = new HangingBreakByEntityEvent((Hanging) this.getBukkitEntity(), damagesource.getEntity() == null ? null : damagesource.getEntity().getBukkitEntity(), damagesource.isExplosion() ? HangingBreakEvent.RemoveCause.EXPLOSION : HangingBreakEvent.RemoveCause.ENTITY); - } else if (damagesource.isExplosion()) { - event = new HangingBreakEvent((Hanging) this.getBukkitEntity(), HangingBreakEvent.RemoveCause.EXPLOSION); - } - - this.world.getServer().getPluginManager().callEvent(event); - - if (this.dead || event.isCancelled()) { - return true; - } - // CraftBukkit end - - this.die(); - this.velocityChanged(); - this.a(damagesource.getEntity()); - } - - return true; - } - } - - @Override - public void move(EnumMoveType enummovetype, Vec3D vec3d) { - if (!this.world.isClientSide && !this.dead && vec3d.g() > 0.0D) { - if (this.dead) return; // CraftBukkit - - // 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 (this.dead || event.isCancelled()) { - return; - } - // CraftBukkit end - - this.die(); - this.a((Entity) null); - } - - } - - @Override - public void f(double d0, double d1, double d2) { - if (false && !this.world.isClientSide && !this.dead && d0 * d0 + d1 * d1 + d2 * d2 > 0.0D) { // CraftBukkit - not needed - this.die(); - this.a((Entity) null); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setByte("Facing", (byte) this.direction.get2DRotationValue()); - BlockPosition blockposition = this.getBlockPosition(); - - nbttagcompound.setInt("TileX", blockposition.getX()); - nbttagcompound.setInt("TileY", blockposition.getY()); - nbttagcompound.setInt("TileZ", blockposition.getZ()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.blockPosition = new BlockPosition(nbttagcompound.getInt("TileX"), nbttagcompound.getInt("TileY"), nbttagcompound.getInt("TileZ")); - this.direction = EnumDirection.fromType2(nbttagcompound.getByte("Facing")); - } - - public abstract int getHangingWidth(); - - public abstract int getHangingHeight(); - - public abstract void a(@Nullable Entity entity); - - public abstract void playPlaceSound(); - - @Override - public EntityItem a(ItemStack itemstack, float f) { - EntityItem entityitem = new EntityItem(this.world, this.locX + (double) ((float) this.direction.getAdjacentX() * 0.15F), this.locY + (double) f, this.locZ + (double) ((float) this.direction.getAdjacentZ() * 0.15F), itemstack); - - entityitem.defaultPickupDelay(); - this.world.addEntity(entityitem); - return entityitem; - } - - @Override - protected boolean aJ() { - return false; - } - - @Override - public void setPosition(double d0, double d1, double d2) { - this.blockPosition = new BlockPosition(d0, d1, d2); - this.updateBoundingBox(); - this.impulse = true; - } - - public BlockPosition getBlockPosition() { - return this.blockPosition; - } - - @Override - public float a(EnumBlockRotation enumblockrotation) { - if (this.direction.k() != EnumDirection.EnumAxis.Y) { - switch (enumblockrotation) { - case CLOCKWISE_180: - this.direction = this.direction.opposite(); - break; - case COUNTERCLOCKWISE_90: - this.direction = this.direction.f(); - break; - case CLOCKWISE_90: - this.direction = this.direction.e(); - } - } - - float f = MathHelper.g(this.yaw); - - switch (enumblockrotation) { - case CLOCKWISE_180: - return f + 180.0F; - case COUNTERCLOCKWISE_90: - return f + 90.0F; - case CLOCKWISE_90: - return f + 270.0F; - default: - return f; - } - } - - @Override - public float a(EnumBlockMirror enumblockmirror) { - return this.a(enumblockmirror.a(this.direction)); - } - - @Override - public void onLightningStrike(EntityLightning entitylightning) {} - - @Override - public void updateSize() {} -} diff --git a/src/main/java/net/minecraft/server/EntityHorseAbstract.java b/src/main/java/net/minecraft/server/EntityHorseAbstract.java deleted file mode 100644 index 8aa60e95f..000000000 --- a/src/main/java/net/minecraft/server/EntityHorseAbstract.java +++ /dev/null @@ -1,925 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Optional; -import java.util.UUID; -import java.util.function.Predicate; -import javax.annotation.Nullable; -import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; // CraftBukkit - -public abstract class EntityHorseAbstract extends EntityAnimal implements IInventoryListener, IJumpable { - - private static final Predicate bI = (entityliving) -> { - return entityliving instanceof EntityHorseAbstract && ((EntityHorseAbstract) entityliving).hasReproduced(); - }; - private static final PathfinderTargetCondition bJ = (new PathfinderTargetCondition()).a(16.0D).a().b().c().a(EntityHorseAbstract.bI); - public static final IAttribute attributeJumpStrength = (new AttributeRanged((IAttribute) null, "horse.jumpStrength", 0.7D, 0.0D, 2.0D)).a("Jump Strength").a(true); - private static final DataWatcherObject bK = DataWatcher.a(EntityHorseAbstract.class, DataWatcherRegistry.a); - private static final DataWatcherObject> bL = DataWatcher.a(EntityHorseAbstract.class, DataWatcherRegistry.o); - private int bM; - private int bN; - private int bO; - public int bA; - public int bB; - protected boolean bC; - public InventorySubcontainer inventoryChest; - protected int bE; - protected float jumpPower; - private boolean canSlide; - private float bQ; - private float bR; - private float bS; - private float bT; - private float bU; - private float bV; - protected boolean bG = true; - protected int bH; - public int maxDomestication = 100; // CraftBukkit - store max domestication value - - protected EntityHorseAbstract(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.K = 1.0F; - this.loadChest(); - } - - @Override - protected void initPathfinder() { - 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, EntityHorseAbstract.class)); - this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.0D)); - this.goalSelector.a(6, new PathfinderGoalRandomStrollLand(this, 0.7D)); - this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); - this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); - this.ee(); - } - - protected void ee() { - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityHorseAbstract.bK, (byte) 0); - this.datawatcher.register(EntityHorseAbstract.bL, Optional.empty()); - } - - protected boolean s(int i) { - return ((Byte) this.datawatcher.get(EntityHorseAbstract.bK) & i) != 0; - } - - protected void d(int i, boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityHorseAbstract.bK); - - if (flag) { - this.datawatcher.set(EntityHorseAbstract.bK, (byte) (b0 | i)); - } else { - this.datawatcher.set(EntityHorseAbstract.bK, (byte) (b0 & ~i)); - } - - } - - public boolean isTamed() { - return this.s(2); - } - - @Nullable - public UUID getOwnerUUID() { - return (UUID) ((Optional) this.datawatcher.get(EntityHorseAbstract.bL)).orElse((Object) null); - } - - public void setOwnerUUID(@Nullable UUID uuid) { - this.datawatcher.set(EntityHorseAbstract.bL, Optional.ofNullable(uuid)); - } - - public boolean eh() { - return this.bC; - } - - public void setTamed(boolean flag) { - this.d(2, flag); - } - - public void t(boolean flag) { - this.bC = flag; - } - - @Override - public boolean a(EntityHuman entityhuman) { - return world.paperConfig.allowLeashingUndeadHorse ? super.a(entityhuman) : super.a(entityhuman) && this.getMonsterType() != EnumMonsterType.UNDEAD; // Paper - } - - @Override - protected void u(float f) { - if (f > 6.0F && this.ei()) { - this.w(false); - } - - } - - public boolean ei() { - return this.s(16); - } - - public boolean ej() { - return this.s(32); - } - - public boolean hasReproduced() { - return this.s(8); - } - - public void u(boolean flag) { - this.d(8, flag); - } - - public void v(boolean flag) { - this.d(4, flag); - } - - public int getTemper() { - return this.bE; - } - - public void setTemper(int i) { - this.bE = i; - } - - public int u(int i) { - int j = MathHelper.clamp(this.getTemper() + i, 0, this.getMaxDomestication()); - - this.setTemper(j); - return j; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - Entity entity = damagesource.getEntity(); - - return this.isVehicle() && entity != null && this.y(entity) ? false : super.damageEntity(damagesource, f); - } - - @Override - public boolean isCollidable() { - return !this.isVehicle(); - } - - private void dV() { - this.dZ(); - if (!this.isSilent()) { - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_HORSE_EAT, this.getSoundCategory(), 1.0F, 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.2F); - } - - } - - @Override - public void b(float f, float f1) { - if (f > 1.0F) { - this.a(SoundEffects.ENTITY_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.isVehicle()) { - Iterator iterator = this.getAllPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - entity.damageEntity(DamageSource.FALL, (float) i); - } - } - - IBlockData iblockdata = this.world.getType(new BlockPosition(this.locX, this.locY - 0.2D - (double) this.lastYaw, this.locZ)); - - if (!iblockdata.isAir() && !this.isSilent()) { - SoundEffectType soundeffecttype = iblockdata.r(); - - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, soundeffecttype.d(), this.getSoundCategory(), soundeffecttype.a() * 0.5F, soundeffecttype.b() * 0.75F); - } - - } - } - - protected int getChestSlots() { - return 2; - } - - public void loadChest() { - InventorySubcontainer inventorysubcontainer = this.inventoryChest; - - this.inventoryChest = new InventorySubcontainer(this.getChestSlots(), (org.bukkit.entity.AbstractHorse) this.getBukkitEntity()); // CraftBukkit - if (inventorysubcontainer != null) { - inventorysubcontainer.b((IInventoryListener) this); - int i = Math.min(inventorysubcontainer.getSize(), this.inventoryChest.getSize()); - - for (int j = 0; j < i; ++j) { - ItemStack itemstack = inventorysubcontainer.getItem(j); - - if (!itemstack.isEmpty()) { - this.inventoryChest.setItem(j, itemstack.cloneItemStack()); - } - } - } - - this.inventoryChest.a((IInventoryListener) this); - this.en(); - } - - protected void en() { - if (!this.world.isClientSide) { - this.v(!this.inventoryChest.getItem(0).isEmpty() && this.ep()); - } - } - - @Override - public void a(IInventory iinventory) { - boolean flag = this.eq(); - - this.en(); - if (this.ticksLived > 20 && !flag && this.eq()) { - this.a(SoundEffects.ENTITY_HORSE_SADDLE, 0.5F, 1.0F); - } - - } - - public double getJumpStrength() { - return this.getAttributeInstance(EntityHorseAbstract.attributeJumpStrength).getValue(); - } - - @Nullable - @Override - protected SoundEffect getSoundDeath() { - return null; - } - - @Nullable - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - if (this.random.nextInt(3) == 0) { - this.eB(); - } - - return null; - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - if (this.random.nextInt(10) == 0 && !this.isFrozen()) { - this.eB(); - } - - return null; - } - - public boolean ep() { - return true; - } - - public boolean eq() { - return this.s(4); - } - - @Nullable - protected SoundEffect getSoundAngry() { - this.eB(); - return null; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - if (!iblockdata.getMaterial().isLiquid()) { - IBlockData iblockdata1 = this.world.getType(blockposition.up()); - SoundEffectType soundeffecttype = iblockdata.r(); - - if (iblockdata1.getBlock() == Blocks.SNOW) { - soundeffecttype = iblockdata1.r(); - } - - if (this.isVehicle() && this.bG) { - ++this.bH; - if (this.bH > 5 && this.bH % 3 == 0) { - this.a(soundeffecttype); - } else if (this.bH <= 5) { - this.a(SoundEffects.ENTITY_HORSE_STEP_WOOD, soundeffecttype.a() * 0.15F, soundeffecttype.b()); - } - } else if (soundeffecttype == SoundEffectType.a) { - this.a(SoundEffects.ENTITY_HORSE_STEP_WOOD, soundeffecttype.a() * 0.15F, soundeffecttype.b()); - } else { - this.a(SoundEffects.ENTITY_HORSE_STEP, soundeffecttype.a() * 0.15F, soundeffecttype.b()); - } - - } - } - - protected void a(SoundEffectType soundeffecttype) { - this.a(SoundEffects.ENTITY_HORSE_GALLOP, soundeffecttype.a() * 0.15F, soundeffecttype.b()); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeMap().b(EntityHorseAbstract.attributeJumpStrength); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(53.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.22499999403953552D); - } - - @Override - public int dC() { - return 6; - } - - public int getMaxDomestication() { - return this.maxDomestication; // CraftBukkit - return stored max domestication instead of 100 - } - - @Override - protected float getSoundVolume() { - return 0.8F; - } - - @Override - public int A() { - return 400; - } - - public void e(EntityHuman entityhuman) { - if (!this.world.isClientSide && (!this.isVehicle() || this.w(entityhuman)) && this.isTamed()) { - entityhuman.openHorseInventory(this, this.inventoryChest); - } - - } - - protected boolean b(EntityHuman entityhuman, ItemStack itemstack) { - boolean flag = false; - float f = 0.0F; - short short0 = 0; - byte b0 = 0; - Item item = itemstack.getItem(); - - if (item == Items.WHEAT) { - f = 2.0F; - short0 = 20; - b0 = 3; - } else if (item == Items.SUGAR) { - f = 1.0F; - short0 = 30; - b0 = 3; - } else if (item == Blocks.HAY_BLOCK.getItem()) { - f = 20.0F; - short0 = 180; - } else if (item == Items.APPLE) { - f = 3.0F; - short0 = 60; - b0 = 3; - } else if (item == Items.GOLDEN_CARROT) { - f = 4.0F; - short0 = 60; - b0 = 5; - if (this.isTamed() && this.getAge() == 0 && !this.isInLove()) { - flag = true; - this.f(entityhuman); - } - } else if (item == Items.GOLDEN_APPLE || item == Items.ENCHANTED_GOLDEN_APPLE) { - f = 10.0F; - short0 = 240; - b0 = 10; - if (this.isTamed() && this.getAge() == 0 && !this.isInLove()) { - flag = true; - this.f(entityhuman); - } - } - - if (this.getHealth() < this.getMaxHealth() && f > 0.0F) { - this.heal(f, RegainReason.EATING); // CraftBukkit - flag = true; - } - - if (this.isBaby() && short0 > 0) { - this.world.addParticle(Particles.HAPPY_VILLAGER, this.locX + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), this.locY + 0.5D + (double) (this.random.nextFloat() * this.getHeight()), this.locZ + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), 0.0D, 0.0D, 0.0D); - if (!this.world.isClientSide) { - this.setAge(short0); - } - - flag = true; - } - - if (b0 > 0 && (flag || !this.isTamed()) && this.getTemper() < this.getMaxDomestication()) { - flag = true; - if (!this.world.isClientSide) { - this.u(b0); - } - } - - if (flag) { - this.dV(); - } - - return flag; - } - - protected void g(EntityHuman entityhuman) { - this.w(false); - this.setStanding(false); - if (!this.world.isClientSide) { - entityhuman.yaw = this.yaw; - entityhuman.pitch = this.pitch; - entityhuman.startRiding(this); - } - - } - - @Override - protected boolean isFrozen() { - return super.isFrozen() && this.isVehicle() && this.eq() || this.ei() || this.ej(); - } - - @Override - public boolean i(ItemStack itemstack) { - return false; - } - - private void dY() { - this.bA = 1; - } - - @Override - protected void cF() { - super.cF(); - if (this.inventoryChest != null) { - for (int i = 0; i < this.inventoryChest.getSize(); ++i) { - ItemStack itemstack = this.inventoryChest.getItem(i); - - if (!itemstack.isEmpty()) { - this.a(itemstack); - } - } - - } - } - - @Override - public void movementTick() { - if (this.random.nextInt(200) == 0) { - this.dY(); - } - - super.movementTick(); - if (!this.world.isClientSide && this.isAlive()) { - if (this.random.nextInt(900) == 0 && this.deathTicks == 0) { - this.heal(1.0F, RegainReason.REGEN); // CraftBukkit - } - - if (this.et()) { - if (!this.ei() && !this.isVehicle() && this.random.nextInt(300) == 0 && this.world.getType((new BlockPosition(this)).down()).getBlock() == Blocks.GRASS_BLOCK) { - this.w(true); - } - - if (this.ei() && ++this.bM > 50) { - this.bM = 0; - this.w(false); - } - } - - this.es(); - } - } - - protected void es() { - if (this.hasReproduced() && this.isBaby() && !this.ei()) { - EntityLiving entityliving = this.world.a(EntityHorseAbstract.class, EntityHorseAbstract.bJ, this, this.locX, this.locY, this.locZ, this.getBoundingBox().g(16.0D)); - - if (entityliving != null && this.h((Entity) entityliving) > 4.0D) { - this.navigation.a((Entity) entityliving, 0); - } - } - - } - - public boolean et() { - return true; - } - - @Override - public void tick() { - super.tick(); - if (this.bN > 0 && ++this.bN > 30) { - this.bN = 0; - this.d(64, false); - } - - if ((this.ca() || this.df()) && this.bO > 0 && ++this.bO > 20) { - this.bO = 0; - this.setStanding(false); - } - - if (this.bA > 0 && ++this.bA > 8) { - this.bA = 0; - } - - if (this.bB > 0) { - ++this.bB; - if (this.bB > 300) { - this.bB = 0; - } - } - - this.bR = this.bQ; - if (this.ei()) { - this.bQ += (1.0F - this.bQ) * 0.4F + 0.05F; - if (this.bQ > 1.0F) { - this.bQ = 1.0F; - } - } else { - this.bQ += (0.0F - this.bQ) * 0.4F - 0.05F; - if (this.bQ < 0.0F) { - this.bQ = 0.0F; - } - } - - this.bT = this.bS; - if (this.ej()) { - this.bQ = 0.0F; - this.bR = this.bQ; - this.bS += (1.0F - this.bS) * 0.4F + 0.05F; - if (this.bS > 1.0F) { - this.bS = 1.0F; - } - } else { - this.canSlide = false; - this.bS += (0.8F * this.bS * this.bS * this.bS - this.bS) * 0.6F - 0.05F; - if (this.bS < 0.0F) { - this.bS = 0.0F; - } - } - - this.bV = this.bU; - if (this.s(64)) { - this.bU += (1.0F - this.bU) * 0.7F + 0.05F; - if (this.bU > 1.0F) { - this.bU = 1.0F; - } - } else { - this.bU += (0.0F - this.bU) * 0.7F - 0.05F; - if (this.bU < 0.0F) { - this.bU = 0.0F; - } - } - - } - - private void dZ() { - if (!this.world.isClientSide) { - this.bN = 1; - this.d(64, true); - } - - } - - public void w(boolean flag) { - this.d(16, flag); - } - - public void setStanding(boolean flag) { - if (flag) { - this.w(false); - } - - this.d(32, flag); - } - - private void eB() { - if (this.ca() || this.df()) { - this.bO = 1; - this.setStanding(true); - } - - } - - public void eu() { - this.eB(); - SoundEffect soundeffect = this.getSoundAngry(); - - if (soundeffect != null) { - this.a(soundeffect, this.getSoundVolume(), this.cV()); - } - - } - - public boolean h(EntityHuman entityhuman) { - this.setOwnerUUID(entityhuman.getUniqueID()); - this.setTamed(true); - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.x.a((EntityPlayer) entityhuman, (EntityAnimal) this); - } - - this.world.broadcastEntityEffect(this, (byte) 7); - return true; - } - - @Override - public void e(Vec3D vec3d) { - if (this.isAlive()) { - if (this.isVehicle() && this.dD() && this.eq()) { - EntityLiving entityliving = (EntityLiving) this.getRidingPassenger(); - - this.yaw = entityliving.yaw; - this.lastYaw = this.yaw; - this.pitch = entityliving.pitch * 0.5F; - this.setYawPitch(this.yaw, this.pitch); - this.aK = this.yaw; - this.aM = this.aK; - float f = entityliving.bb * 0.5F; - float f1 = entityliving.bd; - - if (f1 <= 0.0F) { - f1 *= 0.25F; - this.bH = 0; - } - - if (this.onGround && this.jumpPower == 0.0F && this.ej() && !this.canSlide) { - f = 0.0F; - f1 = 0.0F; - } - - double d0; - double d1; - - if (this.jumpPower > 0.0F && !this.eh() && this.onGround) { - d0 = this.getJumpStrength() * (double) this.jumpPower; - if (this.hasEffect(MobEffects.JUMP)) { - d1 = d0 + (double) ((float) (this.getEffect(MobEffects.JUMP).getAmplifier() + 1) * 0.1F); - } else { - d1 = d0; - } - - Vec3D vec3d1 = this.getMot(); - - this.setMot(vec3d1.x, d1, vec3d1.z); - this.t(true); - this.impulse = true; - if (f1 > 0.0F) { - float f2 = MathHelper.sin(this.yaw * 0.017453292F); - float f3 = MathHelper.cos(this.yaw * 0.017453292F); - - this.setMot(this.getMot().add((double) (-0.4F * f2 * this.jumpPower), 0.0D, (double) (0.4F * f3 * this.jumpPower))); - this.ev(); - } - - this.jumpPower = 0.0F; - } - - this.aO = this.db() * 0.1F; - if (this.ca()) { - this.o((float) this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue()); - super.e(new Vec3D((double) f, vec3d.y, (double) f1)); - } else if (entityliving instanceof EntityHuman) { - this.setMot(Vec3D.a); - } - - if (this.onGround) { - this.jumpPower = 0.0F; - this.t(false); - } - - this.aE = this.aF; - d0 = this.locX - this.lastX; - d1 = this.locZ - this.lastZ; - float f4 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0F; - - if (f4 > 1.0F) { - f4 = 1.0F; - } - - this.aF += (f4 - this.aF) * 0.4F; - this.aG += this.aF; - } else { - this.aO = 0.02F; - super.e(vec3d); - } - } - } - - protected void ev() { - this.a(SoundEffects.ENTITY_HORSE_JUMP, 0.4F, 1.0F); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("EatingHaystack", this.ei()); - nbttagcompound.setBoolean("Bred", this.hasReproduced()); - nbttagcompound.setInt("Temper", this.getTemper()); - nbttagcompound.setBoolean("Tame", this.isTamed()); - if (this.getOwnerUUID() != null) { - nbttagcompound.setString("OwnerUUID", this.getOwnerUUID().toString()); - } - nbttagcompound.setInt("Bukkit.MaxDomestication", this.maxDomestication); // CraftBukkit - - if (!this.inventoryChest.getItem(0).isEmpty()) { - nbttagcompound.set("SaddleItem", this.inventoryChest.getItem(0).save(new NBTTagCompound())); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.w(nbttagcompound.getBoolean("EatingHaystack")); - this.u(nbttagcompound.getBoolean("Bred")); - this.setTemper(nbttagcompound.getInt("Temper")); - this.setTamed(nbttagcompound.getBoolean("Tame")); - String s; - - if (nbttagcompound.hasKeyOfType("OwnerUUID", 8)) { - s = nbttagcompound.getString("OwnerUUID"); - } else { - String s1 = nbttagcompound.getString("Owner"); - - s = NameReferencingFileConverter.a(this.getMinecraftServer(), s1); - } - - if (!s.isEmpty()) { - this.setOwnerUUID(UUID.fromString(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.getBaseValue() * 0.25D); - } - - if (nbttagcompound.hasKeyOfType("SaddleItem", 10)) { - ItemStack itemstack = ItemStack.a(nbttagcompound.getCompound("SaddleItem")); - - if (itemstack.getItem() == Items.SADDLE) { - this.inventoryChest.setItem(0, itemstack); - } - } - - this.en(); - } - - @Override - public boolean mate(EntityAnimal entityanimal) { - return false; - } - - protected boolean ew() { - return !this.isVehicle() && !this.isPassenger() && this.isTamed() && !this.isBaby() && this.getHealth() >= this.getMaxHealth() && this.isInLove(); - } - - @Nullable - @Override - public EntityAgeable createChild(EntityAgeable entityageable) { - return null; - } - - protected void a(EntityAgeable entityageable, EntityHorseAbstract entityhorseabstract) { - double d0 = this.getAttributeInstance(GenericAttributes.MAX_HEALTH).getBaseValue() + entityageable.getAttributeInstance(GenericAttributes.MAX_HEALTH).getBaseValue() + (double) this.ex(); - - entityhorseabstract.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(d0 / 3.0D); - double d1 = this.getAttributeInstance(EntityHorseAbstract.attributeJumpStrength).getBaseValue() + entityageable.getAttributeInstance(EntityHorseAbstract.attributeJumpStrength).getBaseValue() + this.ey(); - - entityhorseabstract.getAttributeInstance(EntityHorseAbstract.attributeJumpStrength).setValue(d1 / 3.0D); - double d2 = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getBaseValue() + entityageable.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getBaseValue() + this.ez(); - - entityhorseabstract.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(d2 / 3.0D); - } - - @Override - public boolean dD() { - return this.getRidingPassenger() instanceof EntityLiving; - } - - @Override - public boolean F_() { - return this.eq(); - } - - @Override - public void b(int i) { - // CraftBukkit start - 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()) { - return; - } - // CraftBukkit end - this.canSlide = true; - this.eB(); - } - - @Override - public void c() {} - - @Override - public void k(Entity entity) { - super.k(entity); - if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - - this.aK = entityinsentient.aK; - } - - if (this.bT > 0.0F) { - float f = MathHelper.sin(this.aK * 0.017453292F); - float f1 = MathHelper.cos(this.aK * 0.017453292F); - float f2 = 0.7F * this.bT; - float f3 = 0.15F * this.bT; - - entity.setPosition(this.locX + (double) (f2 * f), this.locY + this.aP() + entity.aO() + (double) f3, this.locZ - (double) (f2 * f1)); - if (entity instanceof EntityLiving) { - ((EntityLiving) entity).aK = this.aK; - } - } - - } - - protected float ex() { - return 15.0F + (float) this.random.nextInt(8) + (float) this.random.nextInt(9); - } - - protected double ey() { - return 0.4000000059604645D + this.random.nextDouble() * 0.2D + this.random.nextDouble() * 0.2D + this.random.nextDouble() * 0.2D; - } - - protected double ez() { - return (0.44999998807907104D + this.random.nextDouble() * 0.3D + this.random.nextDouble() * 0.3D + this.random.nextDouble() * 0.3D) * 0.25D; - } - - @Override - public boolean isClimbing() { - return false; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * 0.95F; - } - - public boolean eA() { - return false; - } - - public boolean j(ItemStack itemstack) { - return false; - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - int j = i - 400; - - if (j >= 0 && j < 2 && j < this.inventoryChest.getSize()) { - if (j == 0 && itemstack.getItem() != Items.SADDLE) { - return false; - } else if (j == 1 && (!this.eA() || !this.j(itemstack))) { - return false; - } else { - this.inventoryChest.setItem(j, itemstack); - this.en(); - 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; - } - } - } - - @Nullable - @Override - public Entity getRidingPassenger() { - return this.getPassengers().isEmpty() ? null : (Entity) this.getPassengers().get(0); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - groupdataentity = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - if (this.random.nextInt(5) == 0) { - this.setAgeRaw(-24000); - } - - return groupdataentity; - } -} diff --git a/src/main/java/net/minecraft/server/EntityHorseChestedAbstract.java b/src/main/java/net/minecraft/server/EntityHorseChestedAbstract.java deleted file mode 100644 index 2a988366c..000000000 --- a/src/main/java/net/minecraft/server/EntityHorseChestedAbstract.java +++ /dev/null @@ -1,205 +0,0 @@ -package net.minecraft.server; - -public abstract class EntityHorseChestedAbstract extends EntityHorseAbstract { - - private static final DataWatcherObject bI = DataWatcher.a(EntityHorseChestedAbstract.class, DataWatcherRegistry.i); - - protected EntityHorseChestedAbstract(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.bG = false; - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityHorseChestedAbstract.bI, false); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue((double) this.ex()); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.17499999701976776D); - this.getAttributeInstance(EntityHorseChestedAbstract.attributeJumpStrength).setValue(0.5D); - } - - public boolean isCarryingChest() { - return (Boolean) this.datawatcher.get(EntityHorseChestedAbstract.bI); - } - - public void setCarryingChest(boolean flag) { - this.datawatcher.set(EntityHorseChestedAbstract.bI, flag); - } - - @Override - protected int getChestSlots() { - return this.isCarryingChest() ? 17 : super.getChestSlots(); - } - - @Override - public double aP() { - return super.aP() - 0.25D; - } - - @Override - protected SoundEffect getSoundAngry() { - super.getSoundAngry(); - return SoundEffects.ENTITY_DONKEY_ANGRY; - } - - @Override - protected void cF() { - super.cF(); - if (this.isCarryingChest()) { - if (!this.world.isClientSide) { - this.a((IMaterial) Blocks.CHEST); - } - - //this.setCarryingChest(false); // Paper - moved to post death logic - } - - } - - // Paper start - protected void postDeathDropItems(org.bukkit.event.entity.EntityDeathEvent event) { - if (this.isCarryingChest() && (event == null || !event.isCancelled())) { - this.setCarryingChest(false); - } - } - // Paper end - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("ChestedHorse", this.isCarryingChest()); - if (this.isCarryingChest()) { - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 2; i < this.inventoryChest.getSize(); ++i) { - ItemStack itemstack = this.inventoryChest.getItem(i); - - if (!itemstack.isEmpty()) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - nbttagcompound1.setByte("Slot", (byte) i); - itemstack.save(nbttagcompound1); - nbttaglist.add(nbttagcompound1); - } - } - - nbttagcompound.set("Items", nbttaglist); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setCarryingChest(nbttagcompound.getBoolean("ChestedHorse")); - if (this.isCarryingChest()) { - NBTTagList nbttaglist = nbttagcompound.getList("Items", 10); - - this.loadChest(); - - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompound(i); - int j = nbttagcompound1.getByte("Slot") & 255; - - if (j >= 2 && j < this.inventoryChest.getSize()) { - this.inventoryChest.setItem(j, ItemStack.a(nbttagcompound1)); - } - } - } - - this.en(); - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - if (i == 499) { - if (this.isCarryingChest() && itemstack.isEmpty()) { - this.setCarryingChest(false); - this.loadChest(); - return true; - } - - if (!this.isCarryingChest() && itemstack.getItem() == Blocks.CHEST.getItem()) { - this.setCarryingChest(true); - this.loadChest(); - return true; - } - } - - return super.a_(i, itemstack); - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() instanceof ItemMonsterEgg) { - return super.a(entityhuman, enumhand); - } else { - if (!this.isBaby()) { - if (this.isTamed() && entityhuman.isSneaking()) { - this.e(entityhuman); - return true; - } - - if (this.isVehicle()) { - return super.a(entityhuman, enumhand); - } - } - - if (!itemstack.isEmpty()) { - boolean flag = this.b(entityhuman, itemstack); - - if (!flag) { - if (!this.isTamed() || itemstack.getItem() == Items.NAME_TAG) { - if (itemstack.a(entityhuman, (EntityLiving) this, enumhand)) { - return true; - } - - this.eu(); - return true; - } - - if (!this.isCarryingChest() && itemstack.getItem() == Blocks.CHEST.getItem()) { - this.setCarryingChest(true); - this.dY(); - flag = true; - this.loadChest(); - } - - if (!this.isBaby() && !this.eq() && itemstack.getItem() == Items.SADDLE) { - this.e(entityhuman); - return true; - } - } - - if (flag) { - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - return true; - } - } - - if (this.isBaby()) { - return super.a(entityhuman, enumhand); - } else { - this.g(entityhuman); - return true; - } - } - } - - protected void dY() { - this.a(SoundEffects.ENTITY_DONKEY_CHEST, 1.0F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F); - } - - public int dZ() { - return 5; - } -} diff --git a/src/main/java/net/minecraft/server/EntityHorseSkeleton.java b/src/main/java/net/minecraft/server/EntityHorseSkeleton.java deleted file mode 100644 index 0aa77914c..000000000 --- a/src/main/java/net/minecraft/server/EntityHorseSkeleton.java +++ /dev/null @@ -1,182 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class EntityHorseSkeleton extends EntityHorseAbstract { - - private final PathfinderGoalHorseTrap bI = new PathfinderGoalHorseTrap(this); - private boolean bJ; - private int bK;public int getTrapTime() { return this.bK; } // Paper - OBFHELPER - - public EntityHorseSkeleton(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(15.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.20000000298023224D); - this.getAttributeInstance(EntityHorseSkeleton.attributeJumpStrength).setValue(this.ey()); - } - - @Override - protected void ee() {} - - @Override - protected SoundEffect getSoundAmbient() { - super.getSoundAmbient(); - return this.a(TagsFluid.WATER) ? SoundEffects.ENTITY_SKELETON_HORSE_AMBIENT_WATER : SoundEffects.ENTITY_SKELETON_HORSE_AMBIENT; - } - - @Override - protected SoundEffect getSoundDeath() { - super.getSoundDeath(); - return SoundEffects.ENTITY_SKELETON_HORSE_DEATH; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - super.getSoundHurt(damagesource); - return SoundEffects.ENTITY_SKELETON_HORSE_HURT; - } - - @Override - protected SoundEffect getSoundSwim() { - if (this.onGround) { - if (!this.isVehicle()) { - return SoundEffects.ENTITY_SKELETON_HORSE_STEP_WATER; - } - - ++this.bH; - if (this.bH > 5 && this.bH % 3 == 0) { - return SoundEffects.ENTITY_SKELETON_HORSE_GALLOP_WATER; - } - - if (this.bH <= 5) { - return SoundEffects.ENTITY_SKELETON_HORSE_STEP_WATER; - } - } - - return SoundEffects.ENTITY_SKELETON_HORSE_SWIM; - } - - @Override - protected void d(float f) { - if (this.onGround) { - super.d(0.3F); - } else { - super.d(Math.min(0.1F, f * 25.0F)); - } - - } - - @Override - protected void ev() { - if (this.isInWater()) { - this.a(SoundEffects.ENTITY_SKELETON_HORSE_JUMP_WATER, 0.4F, 1.0F); - } else { - super.ev(); - } - - } - - @Override - public EnumMonsterType getMonsterType() { - return EnumMonsterType.UNDEAD; - } - - @Override - public double aP() { - return super.aP() - 0.1875D; - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.dV() && this.bK++ >= 18000) { - this.die(); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("SkeletonTrap", this.dV()); - nbttagcompound.setInt("SkeletonTrapTime", this.bK); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.r(nbttagcompound.getBoolean("SkeletonTrap")); - this.bK = nbttagcompound.getInt("SkeletonTrapTime"); - } - - @Override - public boolean bf() { - return true; - } - - @Override - protected float da() { - return 0.96F; - } - - public boolean isTrap() { return this.dV(); } // Paper - OBFHELPER - public boolean dV() { - return this.bJ; - } - - public void setTrap(boolean trap) { this.r(trap); } // Paper - OBFHELPER - public void r(boolean flag) { - if (flag != this.bJ) { - this.bJ = flag; - if (flag) { - this.goalSelector.a(1, this.bI); - } else { - this.goalSelector.a((PathfinderGoal) this.bI); - } - - } - } - - @Nullable - @Override - public EntityAgeable createChild(EntityAgeable entityageable) { - return (EntityAgeable) EntityTypes.SKELETON_HORSE.a(this.world); - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() instanceof ItemMonsterEgg) { - return super.a(entityhuman, enumhand); - } else if (!this.isTamed()) { - return false; - } else if (this.isBaby()) { - return super.a(entityhuman, enumhand); - } else if (entityhuman.isSneaking()) { - this.e(entityhuman); - return true; - } else if (this.isVehicle()) { - return super.a(entityhuman, enumhand); - } else { - if (!itemstack.isEmpty()) { - if (itemstack.getItem() == Items.SADDLE && !this.eq()) { - this.e(entityhuman); - return true; - } - - if (itemstack.a(entityhuman, (EntityLiving) this, enumhand)) { - return true; - } - } - - this.g(entityhuman); - return true; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityHuman.java b/src/main/java/net/minecraft/server/EntityHuman.java deleted file mode 100644 index cd73cde8d..000000000 --- a/src/main/java/net/minecraft/server/EntityHuman.java +++ /dev/null @@ -1,2136 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.mojang.authlib.GameProfile; -import com.mojang.datafixers.util.Either; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.OptionalInt; -import java.util.UUID; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.craftbukkit.util.CraftVector; -import org.bukkit.entity.Item; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.player.PlayerBedLeaveEvent; -import org.bukkit.event.player.PlayerDropItemEvent; -import org.bukkit.event.player.PlayerVelocityEvent; -import org.bukkit.util.Vector; -// CraftBukkit end - -public abstract class EntityHuman extends EntityLiving { - - public static final EntitySize bs = EntitySize.b(0.6F, 1.8F); - // CraftBukkit - decompile error - private static final Map b = ImmutableMap.builder().put(EntityPose.STANDING, EntityHuman.bs).put(EntityPose.SLEEPING, EntityHuman.as).put(EntityPose.FALL_FLYING, EntitySize.b(0.6F, 0.6F)).put(EntityPose.SWIMMING, EntitySize.b(0.6F, 0.6F)).put(EntityPose.SPIN_ATTACK, EntitySize.b(0.6F, 0.6F)).put(EntityPose.SNEAKING, EntitySize.b(0.6F, 1.5F)).put(EntityPose.DYING, EntitySize.c(0.2F, 0.2F)).build(); - private static final DataWatcherObject c = DataWatcher.a(EntityHuman.class, DataWatcherRegistry.c); - private static final DataWatcherObject d = DataWatcher.a(EntityHuman.class, DataWatcherRegistry.b); - protected static final DataWatcherObject bt = DataWatcher.a(EntityHuman.class, DataWatcherRegistry.a); - protected static final DataWatcherObject bu = DataWatcher.a(EntityHuman.class, DataWatcherRegistry.a); - protected static final DataWatcherObject bv = DataWatcher.a(EntityHuman.class, DataWatcherRegistry.p); - protected static final DataWatcherObject bw = DataWatcher.a(EntityHuman.class, DataWatcherRegistry.p); - private long e; - public final PlayerInventory inventory = new PlayerInventory(this); - protected InventoryEnderChest enderChest = new InventoryEnderChest(this); // CraftBukkit - add "this" to constructor - public final ContainerPlayer defaultContainer; - public Container activeContainer; - protected FoodMetaData foodData = new FoodMetaData(this); // CraftBukkit - add "this" to constructor - protected int bC; - public float bD; - public float bE; - public int bF; - public double bG; - public double bH; - public double bI; - public double bJ; - public double bK; - public double bL; - public int sleepTicks; - protected boolean bM; - private BlockPosition g; - private boolean bU; - public final PlayerAbilities abilities = new PlayerAbilities(); - public int expLevel; - public int expTotal; - public float exp; - protected int bR; - protected final float bS = 0.02F; - private int bV; - private GameProfile bW; public final void setProfile(final GameProfile profile) { this.bW = profile; } // Paper - OBFHELPER - private ItemStack bY; - private final ItemCooldown bZ; - @Nullable - public EntityFishingHook hookedFish; - // Paper start - public boolean affectsSpawning = true; - // Paper end - - // CraftBukkit start - public boolean fauxSleeping; - public String spawnWorld = ""; - public int oldLevel = -1; - - @Override - public CraftHumanEntity getBukkitEntity() { - return (CraftHumanEntity) super.getBukkitEntity(); - } - // CraftBukkit end - - public EntityHuman(World world, GameProfile gameprofile) { - super(EntityTypes.PLAYER, world); - this.bY = ItemStack.a; - this.bZ = this.g(); - this.a(a(gameprofile)); - this.bW = gameprofile; - this.defaultContainer = new ContainerPlayer(this.inventory, !world.isClientSide, this); - this.activeContainer = this.defaultContainer; - BlockPosition blockposition = world.getSpawn(); - - this.setPositionRotation((double) blockposition.getX() + 0.5D, (double) (blockposition.getY() + 1), (double) blockposition.getZ() + 0.5D, 0.0F, 0.0F); - this.aX = 180.0F; - } - - public boolean a(World world, BlockPosition blockposition, EnumGamemode enumgamemode) { - if (!enumgamemode.d()) { - return false; - } else if (enumgamemode == EnumGamemode.SPECTATOR) { - return true; - } else if (this.dQ()) { - return false; - } else { - ItemStack itemstack = this.getItemInMainHand(); - - return itemstack.isEmpty() || !itemstack.a(world.t(), new ShapeDetectorBlock(world, blockposition, false)); - } - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(1.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.10000000149011612D); - this.getAttributeMap().b(GenericAttributes.ATTACK_SPEED); - this.getAttributeMap().b(GenericAttributes.LUCK); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityHuman.c, 0.0F); - this.datawatcher.register(EntityHuman.d, 0); - this.datawatcher.register(EntityHuman.bt, (byte) 0); - this.datawatcher.register(EntityHuman.bu, (byte) 1); - this.datawatcher.register(EntityHuman.bv, new NBTTagCompound()); - this.datawatcher.register(EntityHuman.bw, new NBTTagCompound()); - } - - @Override - public void tick() { - this.noclip = this.isSpectator(); - if (this.isSpectator()) { - this.onGround = false; - } - - if (this.bF > 0) { - --this.bF; - } - - if (this.isSleeping()) { - ++this.sleepTicks; - if (this.sleepTicks > 100) { - this.sleepTicks = 100; - } - - if (!this.world.isClientSide && this.world.J()) { - this.wakeup(false, true, true); - } - } else if (this.sleepTicks > 0) { - ++this.sleepTicks; - if (this.sleepTicks >= 110) { - this.sleepTicks = 0; - } - } - - this.dA(); - super.tick(); - if (!this.world.isClientSide && this.activeContainer != null && !this.activeContainer.canUse(this)) { - this.closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.CANT_USE); // Paper - this.activeContainer = this.defaultContainer; - } - - if (this.isBurning() && this.abilities.isInvulnerable) { - this.extinguish(); - } - - this.n(); - if (!this.world.isClientSide) { - this.foodData.a(this); - this.a(StatisticList.PLAY_ONE_MINUTE); - if (this.isAlive()) { - this.a(StatisticList.TIME_SINCE_DEATH); - } - - if (this.isSneaking()) { - this.a(StatisticList.SNEAK_TIME); - } - - if (!this.isSleeping()) { - this.a(StatisticList.TIME_SINCE_REST); - } - } - - int i = 29999999; - double d0 = MathHelper.a(this.locX, -2.9999999E7D, 2.9999999E7D); - double d1 = MathHelper.a(this.locZ, -2.9999999E7D, 2.9999999E7D); - - if (d0 != this.locX || d1 != this.locZ) { - this.setPosition(d0, this.locY, d1); - } - - ++this.aD; - ItemStack itemstack = this.getItemInMainHand(); - - if (!ItemStack.matches(this.bY, itemstack)) { - if (!ItemStack.d(this.bY, itemstack)) { - this.dZ(); - } - - this.bY = itemstack.isEmpty() ? ItemStack.a : itemstack.cloneItemStack(); - } - - this.l(); - this.bZ.a(); - this.dB(); - } - - protected boolean dA() { - this.bM = this.a(TagsFluid.WATER, true); - return this.bM; - } - - private void l() { - ItemStack itemstack = this.getEquipment(EnumItemSlot.HEAD); - - if (itemstack.getItem() == Items.TURTLE_HELMET && !this.a(TagsFluid.WATER)) { - this.addEffect(new MobEffect(MobEffects.WATER_BREATHING, 200, 0, false, false, true), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.TURTLE_HELMET); // CraftBukkit - } - - } - - protected ItemCooldown g() { - return new ItemCooldown(); - } - - private void n() { - this.bG = this.bJ; - this.bH = this.bK; - this.bI = this.bL; - double d0 = this.locX - this.bJ; - double d1 = this.locY - this.bK; - double d2 = this.locZ - this.bL; - double d3 = 10.0D; - - if (d0 > 10.0D) { - this.bJ = this.locX; - this.bG = this.bJ; - } - - if (d2 > 10.0D) { - this.bL = this.locZ; - this.bI = this.bL; - } - - if (d1 > 10.0D) { - this.bK = this.locY; - this.bH = this.bK; - } - - if (d0 < -10.0D) { - this.bJ = this.locX; - this.bG = this.bJ; - } - - if (d2 < -10.0D) { - this.bL = this.locZ; - this.bI = this.bL; - } - - if (d1 < -10.0D) { - this.bK = this.locY; - this.bH = this.bK; - } - - this.bJ += d0 * 0.25D; - this.bL += d2 * 0.25D; - this.bK += d1 * 0.25D; - } - - protected void dB() { - if (this.c(EntityPose.SWIMMING)) { - EntityPose entitypose; - - if (this.isGliding()) { - entitypose = EntityPose.FALL_FLYING; - } else if (this.isSleeping()) { - entitypose = EntityPose.SLEEPING; - } else if (this.isSwimming()) { - entitypose = EntityPose.SWIMMING; - } else if (this.isRiptiding()) { - entitypose = EntityPose.SPIN_ATTACK; - } else if (this.isSneaking() && !this.abilities.isFlying) { - entitypose = EntityPose.SNEAKING; - } else { - entitypose = EntityPose.STANDING; - } - - EntityPose entitypose1; - - if (!this.isSpectator() && !this.isPassenger() && !this.c(entitypose)) { - if (this.c(EntityPose.SNEAKING)) { - entitypose1 = EntityPose.SNEAKING; - } else { - entitypose1 = EntityPose.SWIMMING; - } - } else { - entitypose1 = entitypose; - } - - this.setPose(entitypose1); - } - } - - @Override - public int ab() { - return this.abilities.isInvulnerable ? 1 : 80; - } - - @Override - protected SoundEffect getSoundSwim() { - return SoundEffects.ENTITY_PLAYER_SWIM; - } - - @Override - protected SoundEffect getSoundSplash() { - return SoundEffects.ENTITY_PLAYER_SPLASH; - } - - @Override - protected SoundEffect getSoundSplashHighSpeed() { - return SoundEffects.ENTITY_PLAYER_SPLASH_HIGH_SPEED; - } - - @Override - public int aX() { - return 10; - } - - @Override - public void a(SoundEffect soundeffect, float f, float f1) { - this.world.playSound(this, this.locX, this.locY, this.locZ, soundeffect, this.getSoundCategory(), f, f1); - } - - public void a(SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) {} - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.PLAYERS; - } - - @Override - public int getMaxFireTicks() { - return 20; - } - - // Paper start - unused code, but to keep signatures aligned - public void closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason reason) { - closeInventory(); - this.activeContainer = this.defaultContainer; - } - // Paper end - - public void closeInventory() { - this.activeContainer = this.defaultContainer; - } - - @Override - public void passengerTick() { - if (!this.world.isClientSide && this.isSneaking() && this.isPassenger()) { - this.stopRiding(); - 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.passengerTick(); - this.bD = this.bE; - this.bE = 0.0F; - this.m(this.locX - d0, this.locY - d1, this.locZ - d2); - if (this.getVehicle() instanceof EntityPig) { - this.pitch = f1; - this.yaw = f; - this.aK = ((EntityPig) this.getVehicle()).aK; - } - - } - } - - @Override - protected void doTick() { - super.doTick(); - this.cO(); - this.aM = this.yaw; - } - - @Override - public void movementTick() { - if (this.bC > 0) { - --this.bC; - } - - if (this.world.getDifficulty() == EnumDifficulty.PEACEFUL && this.world.getGameRules().getBoolean(GameRules.NATURAL_REGENERATION)) { - 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.j(); - this.bD = this.bE; - super.movementTick(); - AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); - - if (!this.world.isClientSide) { - attributeinstance.setValue((double) this.abilities.b()); - } - - this.aO = 0.02F; - if (this.isSprinting()) { - this.aO = (float) ((double) this.aO + 0.005999999865889549D); - } - - this.o((float) attributeinstance.getValue()); - float f; - - if (this.onGround && this.getHealth() > 0.0F && !this.isSwimming()) { - f = Math.min(0.1F, MathHelper.sqrt(b(this.getMot()))); - } else { - f = 0.0F; - } - - this.bE += (f - this.bE) * 0.4F; - if (this.getHealth() > 0.0F && !this.isSpectator()) { - AxisAlignedBB axisalignedbb; - - if (this.isPassenger() && !this.getVehicle().dead) { - axisalignedbb = this.getBoundingBox().b(this.getVehicle().getBoundingBox()).grow(1.0D, 0.0D, 1.0D); - } else { - axisalignedbb = this.getBoundingBox().grow(1.0D, 0.5D, 1.0D); - } - - List list = this.world.getEntities(this, axisalignedbb); - - for (int i = 0; i < list.size(); ++i) { - Entity entity = (Entity) list.get(i); - - if (!entity.dead) { - this.c(entity); - } - } - } - - this.j(this.getShoulderEntityLeft()); - this.j(this.getShoulderEntityRight()); - if (!this.world.isClientSide && (this.fallDistance > 0.5F || this.isInWater() || this.isPassenger()) || this.abilities.isFlying || this.isSleeping()) { - if (!this.world.paperConfig.parrotsHangOnBetter) this.releaseShoulderEntities(); // Paper - Hang on! - } - - } - - private void j(@Nullable NBTTagCompound nbttagcompound) { - if (nbttagcompound != null && !nbttagcompound.hasKey("Silent") || !nbttagcompound.getBoolean("Silent")) { - String s = nbttagcompound.getString("id"); - - EntityTypes.a(s).filter((entitytypes) -> { - return entitytypes == EntityTypes.PARROT; - }).ifPresent((entitytypes) -> { - EntityParrot.a(this.world, (Entity) this); - }); - } - - } - - private void c(Entity entity) { - entity.pickup(this); - } - - public int getScore() { - return (Integer) this.datawatcher.get(EntityHuman.d); - } - - public void setScore(int i) { - this.datawatcher.set(EntityHuman.d, i); - } - - public void addScore(int i) { - int j = this.getScore(); - - this.datawatcher.set(EntityHuman.d, j + i); - } - - @Override - public void die(DamageSource damagesource) { - super.die(damagesource); - this.setPosition(this.locX, this.locY, this.locZ); - if (!this.isSpectator()) { - this.d(damagesource); - } - - if (damagesource != null) { - this.setMot((double) (-MathHelper.cos((this.az + this.yaw) * 0.017453292F) * 0.1F), 0.10000000149011612D, (double) (-MathHelper.sin((this.az + this.yaw) * 0.017453292F) * 0.1F)); - } else { - this.setMot(0.0D, 0.1D, 0.0D); - } - - this.a(StatisticList.DEATHS); - this.a(StatisticList.CUSTOM.b(StatisticList.TIME_SINCE_DEATH)); - this.a(StatisticList.CUSTOM.b(StatisticList.TIME_SINCE_REST)); - this.extinguish(); - this.setFlag(0, false); - } - - @Override - protected void cF() { - super.cF(); - if (!this.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY)) { - this.removeCursedItems(); - this.inventory.dropContents(); - } - - } - - protected void removeCursedItems() { - for (int i = 0; i < this.inventory.getSize(); ++i) { - ItemStack itemstack = this.inventory.getItem(i); - - if (!itemstack.isEmpty() && EnchantmentManager.shouldNotDrop(itemstack)) { - this.inventory.splitWithoutUpdate(i); - } - } - - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return damagesource == DamageSource.BURN ? SoundEffects.ENTITY_PLAYER_HURT_ON_FIRE : (damagesource == DamageSource.DROWN ? SoundEffects.ENTITY_PLAYER_HURT_DROWN : (damagesource == DamageSource.SWEET_BERRY_BUSH ? SoundEffects.ENTITY_PLAYER_HURT_SWEET_BERRY_BUSH : SoundEffects.ENTITY_PLAYER_HURT)); - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_PLAYER_DEATH; - } - - @Nullable - public EntityItem n(boolean flag) { - // Called only when dropped by Q or CTRL-Q - return this.a(this.inventory.splitStack(this.inventory.itemInHandIndex, flag && !this.inventory.getItemInHand().isEmpty() ? this.inventory.getItemInHand().getCount() : 1), false, true); - } - - @Nullable - public EntityItem drop(ItemStack itemstack, boolean flag) { - return this.a(itemstack, false, flag); - } - - @Nullable - public EntityItem a(ItemStack itemstack, boolean flag, boolean flag1) { - if (itemstack.isEmpty()) { - return null; - } else { - double d0 = this.locY - 0.30000001192092896D + (double) this.getHeadHeight(); - EntityItem entityitem = new EntityItem(this.world, this.locX, d0, this.locZ, itemstack); - - entityitem.setPickupDelay(40); - if (flag1) { - entityitem.setThrower(this.getUniqueID()); - } - - float f; - float f1; - - if (flag) { - f = this.random.nextFloat() * 0.5F; - f1 = this.random.nextFloat() * 6.2831855F; - this.setMot((double) (-MathHelper.sin(f1) * f), 0.20000000298023224D, (double) (MathHelper.cos(f1) * f)); - } else { - f = 0.3F; - f1 = MathHelper.sin(this.pitch * 0.017453292F); - float f2 = MathHelper.cos(this.pitch * 0.017453292F); - float f3 = MathHelper.sin(this.yaw * 0.017453292F); - float f4 = MathHelper.cos(this.yaw * 0.017453292F); - float f5 = this.random.nextFloat() * 6.2831855F; - float f6 = 0.02F * this.random.nextFloat(); - - entityitem.setMot((double) (-f3 * f2 * 0.3F) + Math.cos((double) f5) * (double) f6, (double) (-f1 * 0.3F + 0.1F + (this.random.nextFloat() - this.random.nextFloat()) * 0.1F), (double) (f4 * f2 * 0.3F) + Math.sin((double) f5) * (double) f6); - } - - // CraftBukkit start - fire PlayerDropItemEvent - Player player = (Player) this.getBukkitEntity(); - Item drop = (Item) entityitem.getBukkitEntity(); - - PlayerDropItemEvent event = new PlayerDropItemEvent(player, drop); - this.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - org.bukkit.inventory.ItemStack cur = player.getInventory().getItemInHand(); - if (flag1 && (cur == null || cur.getAmount() == 0)) { - // The complete stack was dropped - player.getInventory().setItemInHand(drop.getItemStack()); - } else if (flag1 && cur.isSimilar(drop.getItemStack()) && cur.getAmount() < cur.getMaxStackSize() && drop.getItemStack().getAmount() == 1) { - // Only one item is dropped - cur.setAmount(cur.getAmount() + 1); - player.getInventory().setItemInHand(cur); - } else { - // Fallback - player.getInventory().addItem(drop.getItemStack()); - } - return null; - } - // CraftBukkit end - // Paper start - remove player from map on drop - if (itemstack.getItem() == Items.FILLED_MAP) { - WorldMap worldmap = ItemWorldMap.getSavedMap(itemstack, this.world); - worldmap.updateSeenPlayers(this, itemstack); - } - // Paper end - - return entityitem; - } - } - - public float b(IBlockData iblockdata) { - float f = this.inventory.a(iblockdata); - - if (f > 1.0F) { - int i = EnchantmentManager.getDigSpeedEnchantmentLevel(this); - ItemStack itemstack = this.getItemInMainHand(); - - if (i > 0 && !itemstack.isEmpty()) { - f += (float) (i * i + 1); - } - } - - if (MobEffectUtil.a(this)) { - f *= 1.0F + (float) (MobEffectUtil.b(this) + 1) * 0.2F; - } - - if (this.hasEffect(MobEffects.SLOWER_DIG)) { - float f1; - - switch (this.getEffect(MobEffects.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(TagsFluid.WATER) && !EnchantmentManager.h((EntityLiving) this)) { - f /= 5.0F; - } - - if (!this.onGround) { - f /= 5.0F; - } - - return f; - } - - public boolean hasBlock(IBlockData iblockdata) { - return iblockdata.getMaterial().isAlwaysDestroyable() || this.inventory.b(iblockdata); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.a(a(this.bW)); - NBTTagList nbttaglist = nbttagcompound.getList("Inventory", 10); - - this.inventory.b(nbttaglist); - this.inventory.itemInHandIndex = nbttagcompound.getInt("SelectedItemSlot"); - this.sleepTicks = nbttagcompound.getShort("SleepTimer"); - this.exp = nbttagcompound.getFloat("XpP"); - this.expLevel = nbttagcompound.getInt("XpLevel"); - this.expTotal = nbttagcompound.getInt("XpTotal"); - this.bR = nbttagcompound.getInt("XpSeed"); - if (this.bR == 0) { - this.bR = this.random.nextInt(); - } - - this.setScore(nbttagcompound.getInt("Score")); - - // CraftBukkit start - this.spawnWorld = nbttagcompound.getString("SpawnWorld"); - if ("".equals(spawnWorld)) { - this.spawnWorld = this.world.getServer().getWorlds().get(0).getName(); - } - // CraftBukkit end - - if (nbttagcompound.hasKeyOfType("SpawnX", 99) && nbttagcompound.hasKeyOfType("SpawnY", 99) && nbttagcompound.hasKeyOfType("SpawnZ", 99)) { - this.g = new BlockPosition(nbttagcompound.getInt("SpawnX"), nbttagcompound.getInt("SpawnY"), nbttagcompound.getInt("SpawnZ")); - this.bU = nbttagcompound.getBoolean("SpawnForced"); - } - - this.foodData.a(nbttagcompound); - this.abilities.b(nbttagcompound); - if (nbttagcompound.hasKeyOfType("EnderItems", 9)) { - this.enderChest.a(nbttagcompound.getList("EnderItems", 10)); - } - - if (nbttagcompound.hasKeyOfType("ShoulderEntityLeft", 10)) { - this.setShoulderEntityLeft(nbttagcompound.getCompound("ShoulderEntityLeft")); - } - - if (nbttagcompound.hasKeyOfType("ShoulderEntityRight", 10)) { - this.setShoulderEntityRight(nbttagcompound.getCompound("ShoulderEntityRight")); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("DataVersion", SharedConstants.a().getWorldVersion()); - nbttagcompound.set("Inventory", this.inventory.a(new NBTTagList())); - nbttagcompound.setInt("SelectedItemSlot", this.inventory.itemInHandIndex); - 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.bR); - nbttagcompound.setInt("Score", this.getScore()); - if (this.g != null) { - nbttagcompound.setInt("SpawnX", this.g.getX()); - nbttagcompound.setInt("SpawnY", this.g.getY()); - nbttagcompound.setInt("SpawnZ", this.g.getZ()); - nbttagcompound.setBoolean("SpawnForced", this.bU); - } - - this.foodData.b(nbttagcompound); - this.abilities.a(nbttagcompound); - nbttagcompound.set("EnderItems", this.enderChest.f()); - if (!this.getShoulderEntityLeft().isEmpty()) { - nbttagcompound.set("ShoulderEntityLeft", this.getShoulderEntityLeft()); - } - - if (!this.getShoulderEntityRight().isEmpty()) { - nbttagcompound.set("ShoulderEntityRight", this.getShoulderEntityRight()); - } - nbttagcompound.setString("SpawnWorld", spawnWorld); // CraftBukkit - fixes bed spawns for multiworld worlds - - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (this.abilities.isInvulnerable && !damagesource.ignoresInvulnerability()) { - this.forceExplosionKnockback = true; // SPIGOT-5258 - Make invulnerable players get knockback from explosions - return false; - } else { - this.ticksFarFromPlayer = 0; - if (this.getHealth() <= 0.0F) { - return false; - } else { - // this.releaseShoulderEntities(); // CraftBukkit - moved down - if (damagesource.s()) { - if (this.world.getDifficulty() == EnumDifficulty.PEACEFUL) { - return false; // CraftBukkit - f = 0.0f -> return false - } - - if (this.world.getDifficulty() == EnumDifficulty.EASY) { - f = Math.min(f / 2.0F + 1.0F, f); - } - - if (this.world.getDifficulty() == EnumDifficulty.HARD) { - f = f * 3.0F / 2.0F; - } - } - - // CraftBukkit start - Don't filter out 0 damage - boolean damaged = super.damageEntity(damagesource, f); - if (damaged) { - this.releaseShoulderEntities(); - } - return damaged; - // CraftBukkit end - } - } - } - - @Override - protected void shieldBlock(EntityLiving entityliving) { - super.shieldBlock(entityliving); - if (entityliving.getItemInMainHand().getItem() instanceof ItemAxe) { - this.o(true); - } - - } - - 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()); - if (team == null || team.allowFriendlyFire()) { - return true; - } - } 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 - } - - @Override - protected void damageArmor(float f) { - this.inventory.a(f); - } - - @Override - protected void damageShield(float f) { - if (f >= 3.0F && this.activeItem.getItem() == Items.SHIELD) { - int i = 1 + MathHelper.d(f); - EnumHand enumhand = this.getRaisedHand(); - - this.activeItem.damage(i, this, (entityhuman) -> { - entityhuman.d(enumhand); - }); - if (this.activeItem.isEmpty()) { - if (enumhand == EnumHand.MAIN_HAND) { - this.setSlot(EnumItemSlot.MAINHAND, ItemStack.a); - } else { - this.setSlot(EnumItemSlot.OFFHAND, ItemStack.a); - } - - this.activeItem = ItemStack.a; - this.a(SoundEffects.ITEM_SHIELD_BREAK, 0.8F, 0.8F + this.world.random.nextFloat() * 0.4F); - } - } - - } - - // CraftBukkit start - @Override - protected boolean damageEntity0(DamageSource damagesource, float f) { // void -> boolean - if (true) { - return super.damageEntity0(damagesource, f); - } - // CraftBukkit end - if (!this.isInvulnerable(damagesource)) { - f = this.applyArmorModifier(damagesource, f); - f = this.applyMagicModifier(damagesource, f); - float f1 = f; - - f = Math.max(f - this.getAbsorptionHearts(), 0.0F); - this.setAbsorptionHearts(this.getAbsorptionHearts() - (f1 - f)); - float f2 = f1 - f; - - if (f2 > 0.0F && f2 < 3.4028235E37F) { - this.a(StatisticList.DAMAGE_ABSORBED, Math.round(f2 * 10.0F)); - } - - if (f != 0.0F) { - this.applyExhaustion(damagesource.getExhaustionCost()); - float f3 = this.getHealth(); - - this.setHealth(this.getHealth() - f); - this.getCombatTracker().trackDamage(damagesource, f3, f); - if (f < 3.4028235E37F) { - this.a(StatisticList.DAMAGE_TAKEN, Math.round(f * 10.0F)); - } - - } - } - return false; // CraftBukkit - } - - public void openSign(TileEntitySign tileentitysign) {} - - public void a(CommandBlockListenerAbstract commandblocklistenerabstract) {} - - public void a(TileEntityCommand tileentitycommand) {} - - public void a(TileEntityStructure tileentitystructure) {} - - public void a(TileEntityJigsaw tileentityjigsaw) {} - - public void openHorseInventory(EntityHorseAbstract entityhorseabstract, IInventory iinventory) {} - - public OptionalInt openContainer(@Nullable ITileInventory itileinventory) { - return OptionalInt.empty(); - } - - public void openTrade(int i, MerchantRecipeList merchantrecipelist, int j, int k, boolean flag, boolean flag1) {} - - public void openBook(ItemStack itemstack, EnumHand enumhand) {} - - public EnumInteractionResult a(Entity entity, EnumHand enumhand) { - if (this.isSpectator()) { - if (entity instanceof ITileInventory) { - this.openContainer((ITileInventory) entity); - } - - return EnumInteractionResult.PASS; - } else { - ItemStack itemstack = this.b(enumhand); - ItemStack itemstack1 = itemstack.isEmpty() ? ItemStack.a : itemstack.cloneItemStack(); - - if (entity.b(this, enumhand)) { - if (this.abilities.canInstantlyBuild && itemstack == this.b(enumhand) && itemstack.getCount() < itemstack1.getCount()) { - itemstack.setCount(itemstack1.getCount()); - } - - return EnumInteractionResult.SUCCESS; - } else { - if (!itemstack.isEmpty() && entity instanceof EntityLiving) { - if (this.abilities.canInstantlyBuild) { - itemstack = itemstack1; - } - - if (itemstack.a(this, (EntityLiving) entity, enumhand)) { - if (itemstack.isEmpty() && !this.abilities.canInstantlyBuild) { - this.a(enumhand, ItemStack.a); - } - - return EnumInteractionResult.SUCCESS; - } - } - - return EnumInteractionResult.PASS; - } - } - } - - @Override - public double aO() { - return -0.35D; - } - - // Paper start - @Override public void stopRiding() { stopRiding(false); } - @Override public void stopRiding(boolean suppressCancellation) { - // Paper end - super.stopRiding(suppressCancellation); // Paper - suppress - this.j = 0; - } - - @Override - protected boolean isFrozen() { - return super.isFrozen() || this.isSleeping(); - } - - // Paper start - send SoundEffect to everyone who can see fromEntity - private static void sendSoundEffect(EntityHuman fromEntity, double x, double y, double z, SoundEffect soundEffect, SoundCategory soundCategory, float volume, float pitch) { - fromEntity.world.sendSoundEffect(fromEntity, x, y, z, soundEffect, soundCategory, volume, pitch); // This will not send the effect to the entity himself - if (fromEntity instanceof EntityPlayer) { - ((EntityPlayer) fromEntity).playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(soundEffect, soundCategory, x, y, z, volume, pitch)); - } - } - // Paper end - - public void attack(Entity entity) { - if (entity.bs()) { - if (!entity.t(this)) { - float f = (float) this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue(); - float f1; - - if (entity instanceof EntityLiving) { - f1 = EnchantmentManager.a(this.getItemInMainHand(), ((EntityLiving) entity).getMonsterType()); - } else { - f1 = EnchantmentManager.a(this.getItemInMainHand(), EnumMonsterType.UNDEFINED); - } - - float f2 = this.s(0.5F); - - f *= 0.2F + f2 * f2 * 0.8F; - f1 *= f2; - this.dZ(); - if (f > 0.0F || f1 > 0.0F) { - boolean flag = f2 > 0.9F; - boolean flag1 = false; - byte b0 = 0; - int i = b0 + EnchantmentManager.b((EntityLiving) this); - - if (this.isSprinting() && flag) { - sendSoundEffect(this, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PLAYER_ATTACK_KNOCKBACK, this.getSoundCategory(), 1.0F, 1.0F); // Paper - send while respecting visibility - ++i; - flag1 = true; - } - - boolean flag2 = flag && this.fallDistance > 0.0F && !this.onGround && !this.isClimbing() && !this.isInWater() && !this.hasEffect(MobEffects.BLINDNESS) && !this.isPassenger() && entity instanceof EntityLiving; - - flag2 = flag2 && !world.paperConfig.disablePlayerCrits; // Paper - flag2 = flag2 && !this.isSprinting(); - if (flag2) { - f *= 1.5F; - } - - f += f1; - boolean flag3 = false; - double d0 = (double) (this.E - this.D); - - if (flag && !flag2 && !flag1 && this.onGround && d0 < (double) this.db()) { - ItemStack itemstack = this.b(EnumHand.MAIN_HAND); - - if (itemstack.getItem() instanceof ItemSword) { - flag3 = true; - } - } - - float f3 = 0.0F; - boolean flag4 = false; - int j = EnchantmentManager.getFireAspectEnchantmentLevel(this); - - if (entity instanceof EntityLiving) { - f3 = ((EntityLiving) entity).getHealth(); - if (j > 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()) { - flag4 = true; - entity.setOnFire(combustEvent.getDuration(), false); - } - // CraftBukkit end - } - } - - Vec3D vec3d = entity.getMot(); - boolean flag5 = entity.damageEntity(DamageSource.playerAttack(this), f); - - if (flag5) { - if (i > 0) { - if (entity instanceof EntityLiving) { - ((EntityLiving) entity).a(this, (float) i * 0.5F, (double) MathHelper.sin(this.yaw * 0.017453292F), (double) (-MathHelper.cos(this.yaw * 0.017453292F))); - } else { - entity.f((double) (-MathHelper.sin(this.yaw * 0.017453292F) * (float) i * 0.5F), 0.1D, (double) (MathHelper.cos(this.yaw * 0.017453292F) * (float) i * 0.5F)); - } - - this.setMot(this.getMot().d(0.6D, 1.0D, 0.6D)); - // Paper start - Configuration option to disable automatic sprint interruption - if (!world.paperConfig.disableSprintInterruptionOnAttack) { - this.setSprinting(false); - } - // Paper end - } - - if (flag3) { - float f4 = 1.0F + EnchantmentManager.a((EntityLiving) this) * f; - List list = this.world.a(EntityLiving.class, entity.getBoundingBox().grow(1.0D, 0.25D, 1.0D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityLiving entityliving = (EntityLiving) iterator.next(); - - if (entityliving != this && entityliving != entity && !this.r(entityliving) && (!(entityliving instanceof EntityArmorStand) || !((EntityArmorStand) entityliving).isMarker()) && this.h((Entity) entityliving) < 9.0D) { - // CraftBukkit start - Only apply knockback if the damage hits - if (entityliving.damageEntity(DamageSource.playerAttack(this).sweep(), f4)) { - entityliving.a(this, 0.4F, (double) MathHelper.sin(this.yaw * 0.017453292F), (double) (-MathHelper.cos(this.yaw * 0.017453292F))); - } - // CraftBukkit end - } - } - - sendSoundEffect(this, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PLAYER_ATTACK_SWEEP, this.getSoundCategory(), 1.0F, 1.0F); // Paper - send while respecting visibility - this.dE(); - } - - if (entity instanceof EntityPlayer && entity.velocityChanged) { - // CraftBukkit start - Add Velocity Event - boolean cancelled = false; - Player player = (Player) entity.getBukkitEntity(); - org.bukkit.util.Vector velocity = CraftVector.toBukkit(vec3d); - - PlayerVelocityEvent event = new PlayerVelocityEvent(player, velocity.clone()); - world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - cancelled = true; - } else if (!velocity.equals(event.getVelocity())) { - player.setVelocity(event.getVelocity()); - } - - if (!cancelled) { - ((EntityPlayer) entity).playerConnection.sendPacket(new PacketPlayOutEntityVelocity(entity)); - entity.velocityChanged = false; - entity.setMot(vec3d); - } - // CraftBukkit end - } - - if (flag2) { - sendSoundEffect(this, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PLAYER_ATTACK_CRIT, this.getSoundCategory(), 1.0F, 1.0F); // Paper - send while respecting visibility - this.a(entity); - } - - if (!flag2 && !flag3) { - if (flag) { - sendSoundEffect(this, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PLAYER_ATTACK_STRONG, this.getSoundCategory(), 1.0F, 1.0F); // Paper - send while respecting visibility - } else { - sendSoundEffect(this, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PLAYER_ATTACK_WEAK, this.getSoundCategory(), 1.0F, 1.0F); // Paper - send while respecting visibility - } - } - - if (f1 > 0.0F) { - this.b(entity); - } - - this.z(entity); - if (entity instanceof EntityLiving) { - EnchantmentManager.a((EntityLiving) entity, (Entity) this); - } - - EnchantmentManager.b((EntityLiving) this, entity); - ItemStack itemstack1 = this.getItemInMainHand(); - Object object = entity; - - if (entity instanceof EntityComplexPart) { - object = ((EntityComplexPart) entity).owner; - } - - if (!this.world.isClientSide && !itemstack1.isEmpty() && object instanceof EntityLiving) { - itemstack1.a((EntityLiving) object, this); - if (itemstack1.isEmpty()) { - this.a(EnumHand.MAIN_HAND, ItemStack.a); - } - } - - if (entity instanceof EntityLiving) { - float f5 = f3 - ((EntityLiving) entity).getHealth(); - - this.a(StatisticList.DAMAGE_DEALT, Math.round(f5 * 10.0F)); - 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(), false); - } - // CraftBukkit end - } - - if (this.world instanceof WorldServer && f5 > 2.0F) { - int k = (int) ((double) f5 * 0.5D); - - ((WorldServer) this.world).a(Particles.DAMAGE_INDICATOR, entity.locX, entity.locY + (double) (entity.getHeight() * 0.5F), entity.locZ, k, 0.1D, 0.0D, 0.1D, 0.2D); - } - } - - this.applyExhaustion(world.spigotConfig.combatExhaustion); // Spigot - Change to use configurable value - } else { - sendSoundEffect(this, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PLAYER_ATTACK_NODAMAGE, this.getSoundCategory(), 1.0F, 1.0F); // Paper - send while respecting visibility - if (flag4) { - entity.extinguish(); - } - // CraftBukkit start - resync on cancelled event - if (this instanceof EntityPlayer) { - ((EntityPlayer) this).getBukkitEntity().updateInventory(); - } - // CraftBukkit end - } - } - - } - } - } - - @Override - protected void f(EntityLiving entityliving) { - this.attack(entityliving); - } - - public void o(boolean flag) { - float f = 0.25F + (float) EnchantmentManager.getDigSpeedEnchantmentLevel(this) * 0.05F; - - if (flag) { - f += 0.75F; - } - - if (this.random.nextFloat() < f) { - this.getCooldownTracker().setCooldown(Items.SHIELD, 100); - this.dp(); - this.world.broadcastEntityEffect(this, (byte) 30); - } - - } - - public void a(Entity entity) {} - - public void b(Entity entity) {} - - public void dE() { - double d0 = (double) (-MathHelper.sin(this.yaw * 0.017453292F)); - double d1 = (double) MathHelper.cos(this.yaw * 0.017453292F); - - if (this.world instanceof WorldServer) { - ((WorldServer) this.world).a(Particles.SWEEP_ATTACK, this.locX + d0, this.locY + (double) this.getHeight() * 0.5D, this.locZ + d1, 0, d0, 0.0D, d1, 0.0D); - } - - } - - @Override - public void die() { - super.die(); - this.defaultContainer.b(this); - if (this.activeContainer != null) { - this.activeContainer.b(this); - } - - } - - public boolean dG() { - return false; - } - - public GameProfile getProfile() { - return this.bW; - } - - // CraftBukkit start - moved bed result checks from below into separate method - private Either getBedResult(BlockPosition blockposition, EnumDirection enumdirection) { - if (!this.world.isClientSide) { - if (this.isSleeping() || !this.isAlive()) { - return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM); - } - - // CraftBukkit - moved world and biome check from BlockBed interact handling here - if (!world.worldProvider.canRespawn() || world.getBiome(blockposition) == Biomes.NETHER || !this.world.worldProvider.isOverworld()) { - return Either.left(EntityHuman.EnumBedResult.NOT_POSSIBLE_HERE); - } - - if (this.world.J()) { - return Either.left(EntityHuman.EnumBedResult.NOT_POSSIBLE_NOW); - } - - if (!this.a(blockposition, enumdirection)) { - return Either.left(EntityHuman.EnumBedResult.TOO_FAR_AWAY); - } - - if (this.b(blockposition, enumdirection)) { - return Either.left(EntityHuman.EnumBedResult.OBSTRUCTED); - } - - if (!this.isCreative()) { - double d0 = 8.0D; - double d1 = 5.0D; - List list = this.world.a(EntityMonster.class, new AxisAlignedBB((double) blockposition.getX() - 8.0D, (double) blockposition.getY() - 5.0D, (double) blockposition.getZ() - 8.0D, (double) blockposition.getX() + 8.0D, (double) blockposition.getY() + 5.0D, (double) blockposition.getZ() + 8.0D), (entitymonster) -> { - return entitymonster.e(this); - }); - - if (!list.isEmpty()) { - return Either.left(EntityHuman.EnumBedResult.NOT_SAFE); - } - } - } - return Either.right(Unit.INSTANCE); - } - - public Either sleep(BlockPosition blockposition) { - // CraftBukkit start - moved checks into separate method above, add force - return this.sleep(blockposition, false); - } - - public Either sleep(BlockPosition blockposition, boolean force) { - EnumDirection enumdirection = (EnumDirection) this.world.getType(blockposition).get(BlockFacingHorizontal.FACING); - Either bedResult = this.getBedResult(blockposition, enumdirection); - - if (bedResult.left().orElse(null) == EntityHuman.EnumBedResult.OTHER_PROBLEM) { - return bedResult; // return immediately if the result is not bypassable by plugins - } - - if (force) { - bedResult = Either.right(Unit.INSTANCE); - } - - if (this.getBukkitEntity() instanceof Player) { - bedResult = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerBedEnterEvent(this, blockposition, bedResult); - - if (bedResult.left().isPresent()) { - return bedResult; - } - } - // CraftBukkit end - - this.e(blockposition); - this.sleepTicks = 0; - if (this.world instanceof WorldServer) { - ((WorldServer) this.world).everyoneSleeping(); - } - - return Either.right(Unit.INSTANCE); - } - - @Override - public void e(BlockPosition blockposition) { - this.a(StatisticList.CUSTOM.b(StatisticList.TIME_SINCE_REST)); - super.e(blockposition); - } - - private boolean a(BlockPosition blockposition, EnumDirection enumdirection) { - if (Math.abs(this.locX - (double) blockposition.getX()) <= 3.0D && Math.abs(this.locY - (double) blockposition.getY()) <= 2.0D && Math.abs(this.locZ - (double) blockposition.getZ()) <= 3.0D) { - return true; - } else { - BlockPosition blockposition1 = blockposition.shift(enumdirection.opposite()); - - return Math.abs(this.locX - (double) blockposition1.getX()) <= 3.0D && Math.abs(this.locY - (double) blockposition1.getY()) <= 2.0D && Math.abs(this.locZ - (double) blockposition1.getZ()) <= 3.0D; - } - } - - private boolean b(BlockPosition blockposition, EnumDirection enumdirection) { - BlockPosition blockposition1 = blockposition.up(); - - return !this.f(blockposition1) || !this.f(blockposition1.shift(enumdirection.opposite())); - } - - public void wakeup(boolean flag, boolean flag1, boolean flag2) { - Optional optional = this.getBedPosition(); - - super.dy(); - if (this.world instanceof WorldServer && flag1) { - ((WorldServer) this.world).everyoneSleeping(); - } - - // CraftBukkit start - fire PlayerBedLeaveEvent - if (this.getBukkitEntity() instanceof Player) { - Player player = (Player) this.getBukkitEntity(); - - org.bukkit.block.Block bed; - BlockPosition blockposition = optional.orElse(null); - 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, flag2); - this.world.getServer().getPluginManager().callEvent(event); - flag2 = event.shouldSetSpawnLocation(); - } - // CraftBukkit end - - this.sleepTicks = flag ? 0 : 100; - if (flag2) { - optional.ifPresent((blockposition) -> { - this.setRespawnPosition(blockposition, false); - }); - } - - } - - @Override - public void dy() { - this.wakeup(true, true, false); - } - - public static Optional getBed(IWorldReader iworldreader, BlockPosition blockposition, boolean flag) { - Block block = iworldreader.getType(blockposition).getBlock(); - - if (!(block instanceof BlockBed)) { - if (!flag) { - return Optional.empty(); - } else { - boolean flag1 = block.S_(); - boolean flag2 = iworldreader.getType(blockposition.up()).getBlock().S_(); - - return flag1 && flag2 ? Optional.of(new Vec3D((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D)) : Optional.empty(); - } - } else { - return BlockBed.a(EntityTypes.PLAYER, iworldreader, blockposition, 0); - } - } - - public boolean isDeeplySleeping() { - return this.isSleeping() && this.sleepTicks >= 100; - } - - public int dJ() { - return this.sleepTicks; - } - - public void a(IChatBaseComponent ichatbasecomponent, boolean flag) {} - - public BlockPosition getBed() { - return this.g; - } - - public boolean isRespawnForced() { - return this.bU; - } - - public void setRespawnPosition(BlockPosition blockposition, boolean flag) { - if (blockposition != null) { - this.g = blockposition; - this.bU = flag; - this.spawnWorld = this.world.worldData.getName(); // CraftBukkit - } else { - this.g = null; - this.bU = false; - this.spawnWorld = ""; // CraftBukkit - } - - } - - public void a(MinecraftKey minecraftkey) { - this.b(StatisticList.CUSTOM.b(minecraftkey)); - } - - public void a(MinecraftKey minecraftkey, int i) { - this.a(StatisticList.CUSTOM.b(minecraftkey), i); - } - - public void b(Statistic statistic) { - this.a(statistic, 1); - } - - public void a(Statistic statistic, int i) {} - - public void a(Statistic statistic) {} - - public int discoverRecipes(Collection> collection) { - return 0; - } - - public void a(MinecraftKey[] aminecraftkey) {} - - public int undiscoverRecipes(Collection> collection) { - return 0; - } - - @Override - public void jump() { - super.jump(); - this.a(StatisticList.JUMP); - if (this.isSprinting()) { - this.applyExhaustion(world.spigotConfig.jumpSprintExhaustion); // Spigot - Change to use configurable value - } else { - this.applyExhaustion(world.spigotConfig.jumpWalkExhaustion); // Spigot - Change to use configurable value - } - - } - - @Override - public void e(Vec3D vec3d) { - double d0 = this.locX; - double d1 = this.locY; - double d2 = this.locZ; - double d3; - - if (this.isSwimming() && !this.isPassenger()) { - d3 = this.getLookDirection().y; - double d4 = d3 < -0.2D ? 0.085D : 0.06D; - - if (d3 <= 0.0D || this.jumping || !this.world.getType(new BlockPosition(this.locX, this.locY + 1.0D - 0.1D, this.locZ)).p().isEmpty()) { - Vec3D vec3d1 = this.getMot(); - - this.setMot(vec3d1.add(0.0D, (d3 - vec3d1.y) * d4, 0.0D)); - } - } - - if (this.abilities.isFlying && !this.isPassenger()) { - d3 = this.getMot().y; - float f = this.aO; - - this.aO = this.abilities.a() * (float) (this.isSprinting() ? 2 : 1); - super.e(vec3d); - Vec3D vec3d2 = this.getMot(); - - this.setMot(vec3d2.x, d3 * 0.6D, vec3d2.z); - this.aO = f; - this.fallDistance = 0.0F; - // CraftBukkit start - if (getFlag(7) && !org.bukkit.craftbukkit.event.CraftEventFactory.callToggleGlideEvent(this, false).isCancelled()) { - this.setFlag(7, false); - } - // CraftBukkit end - } else { - super.e(vec3d); - } - - this.checkMovement(this.locX - d0, this.locY - d1, this.locZ - d2); - } - - @Override - public void ax() { - if (this.abilities.isFlying) { - this.setSwimming(false); - } else { - super.ax(); - } - - } - - protected boolean f(BlockPosition blockposition) { - return !this.world.getType(blockposition).m(this.world, blockposition); - } - - @Override - public float db() { - return (float) this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue(); - } - - public void checkMovement(double d0, double d1, double d2) { - if (!this.isPassenger()) { - int i; - - if (this.isSwimming()) { - i = Math.round(MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F); - if (i > 0) { - this.a(StatisticList.SWIM_ONE_CM, i); - this.applyExhaustion(0.01F * (float) i * 0.01F); - } - } else if (this.a(TagsFluid.WATER, true)) { - i = Math.round(MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F); - if (i > 0) { - this.a(StatisticList.WALK_UNDER_WATER_ONE_CM, i); - this.applyExhaustion(world.spigotConfig.swimMultiplier * (float) i * 0.01F); // Spigot - } - } else if (this.isInWater()) { - i = Math.round(MathHelper.sqrt(d0 * d0 + d2 * d2) * 100.0F); - if (i > 0) { - this.a(StatisticList.WALK_ON_WATER_ONE_CM, i); - this.applyExhaustion(world.spigotConfig.swimMultiplier * (float) i * 0.01F); // Spigot - } - } else if (this.isClimbing()) { - if (d1 > 0.0D) { - this.a(StatisticList.CLIMB_ONE_CM, (int) Math.round(d1 * 100.0D)); - } - } else if (this.onGround) { - i = Math.round(MathHelper.sqrt(d0 * d0 + d2 * d2) * 100.0F); - if (i > 0) { - if (this.isSprinting()) { - this.a(StatisticList.SPRINT_ONE_CM, i); - this.applyExhaustion(world.spigotConfig.sprintMultiplier * (float) i * 0.01F); // Spigot - } else if (this.isSneaking()) { - this.a(StatisticList.CROUCH_ONE_CM, i); - this.applyExhaustion(world.spigotConfig.otherMultiplier * (float) i * 0.01F); // Spigot - } else { - this.a(StatisticList.WALK_ONE_CM, i); - this.applyExhaustion(world.spigotConfig.otherMultiplier * (float) i * 0.01F); // Spigot - } - } - } else if (this.isGliding()) { - i = Math.round(MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F); - this.a(StatisticList.AVIATE_ONE_CM, i); - } else { - i = Math.round(MathHelper.sqrt(d0 * d0 + d2 * d2) * 100.0F); - if (i > 25) { - this.a(StatisticList.FLY_ONE_CM, i); - } - } - - } - } - - private void m(double d0, double d1, double d2) { - if (this.isPassenger()) { - int i = Math.round(MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F); - - if (i > 0) { - if (this.getVehicle() instanceof EntityMinecartAbstract) { - this.a(StatisticList.MINECART_ONE_CM, i); - } else if (this.getVehicle() instanceof EntityBoat) { - this.a(StatisticList.BOAT_ONE_CM, i); - } else if (this.getVehicle() instanceof EntityPig) { - this.a(StatisticList.PIG_ONE_CM, i); - } else if (this.getVehicle() instanceof EntityHorseAbstract) { - this.a(StatisticList.HORSE_ONE_CM, i); - } - } - } - - } - - @Override - public void b(float f, float f1) { - if (!this.abilities.canFly) { - if (f >= 2.0F) { - this.a(StatisticList.FALL_ONE_CM, (int) Math.round((double) f * 100.0D)); - } - - super.b(f, f1); - } - } - - @Override - protected void az() { - if (!this.isSpectator()) { - super.az(); - } - - } - - @Override - protected SoundEffect getSoundFall(int i) { - return i > 4 ? SoundEffects.ENTITY_PLAYER_BIG_FALL : SoundEffects.ENTITY_PLAYER_SMALL_FALL; - } - - @Override - public void b(EntityLiving entityliving) { - this.b(StatisticList.ENTITY_KILLED.b(entityliving.getEntityType())); - } - - @Override - public void a(IBlockData iblockdata, Vec3D vec3d) { - if (!this.abilities.isFlying) { - super.a(iblockdata, vec3d); - } - - } - - public void giveExp(int i) { - this.addScore(i); - this.exp += (float) i / (float) this.getExpToLevel(); - this.expTotal = MathHelper.clamp(this.expTotal + i, 0, Integer.MAX_VALUE); - - while (this.exp < 0.0F) { - float f = this.exp * (float) this.getExpToLevel(); - - if (this.expLevel > 0) { - this.levelDown(-1); - this.exp = 1.0F + f / (float) this.getExpToLevel(); - } else { - this.levelDown(-1); - this.exp = 0.0F; - } - } - - while (this.exp >= 1.0F) { - this.exp = (this.exp - 1.0F) * (float) this.getExpToLevel(); - this.levelDown(1); - this.exp /= (float) this.getExpToLevel(); - } - - } - - public int dM() { - return this.bR; - } - - public void enchantDone(ItemStack itemstack, int i) { - this.expLevel -= i; - if (this.expLevel < 0) { - this.expLevel = 0; - this.exp = 0.0F; - this.expTotal = 0; - } - - this.bR = this.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.bV < (float) this.ticksLived - 100.0F) { - float f = this.expLevel > 30 ? 1.0F : (float) this.expLevel / 30.0F; - - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PLAYER_LEVELUP, this.getSoundCategory(), f * 0.75F, 1.0F); - this.bV = this.ticksLived; - } - - } - - public int getExpToLevel() { - 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) { - if (!this.world.isClientSide) { - this.foodData.a(f); - } - - } - } - - public FoodMetaData getFoodData() { - return this.foodData; - } - - public boolean p(boolean flag) { - return !this.abilities.isInvulnerable && (flag || this.foodData.c()); - } - - public boolean dP() { - return this.getHealth() > 0.0F && this.getHealth() < this.getMaxHealth(); - } - - public boolean dQ() { - return this.abilities.mayBuild; - } - - public boolean a(BlockPosition blockposition, EnumDirection enumdirection, ItemStack itemstack) { - if (this.abilities.mayBuild) { - return true; - } else { - BlockPosition blockposition1 = blockposition.shift(enumdirection.opposite()); - ShapeDetectorBlock shapedetectorblock = new ShapeDetectorBlock(this.world, blockposition1, false); - - return itemstack.b(this.world.t(), shapedetectorblock); - } - } - - @Override - protected int getExpValue(EntityHuman entityhuman) { - if (!this.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY) && !this.isSpectator()) { - int i = this.expLevel * 7; - - return i > 100 ? 100 : i; - } else { - return 0; - } - } - - @Override - protected boolean alwaysGivesExp() { - return true; - } - - @Override - protected boolean playStepSound() { - return !this.abilities.isFlying; - } - - public void updateAbilities() {} - - public void a(EnumGamemode enumgamemode) {} - - @Override - public IChatBaseComponent getDisplayName() { - return new ChatComponentText(this.bW.getName()); - } - - public InventoryEnderChest getEnderChest() { - return this.enderChest; - } - - @Override - public ItemStack getEquipment(EnumItemSlot enumitemslot) { - return enumitemslot == EnumItemSlot.MAINHAND ? this.inventory.getItemInHand() : (enumitemslot == EnumItemSlot.OFFHAND ? (ItemStack) this.inventory.extraSlots.get(0) : (enumitemslot.a() == EnumItemSlot.Function.ARMOR ? (ItemStack) this.inventory.armor.get(enumitemslot.b()) : ItemStack.a)); - } - - @Override - public void setSlot(EnumItemSlot enumitemslot, ItemStack itemstack) { - if (enumitemslot == EnumItemSlot.MAINHAND) { - this.b(itemstack); - this.inventory.items.set(this.inventory.itemInHandIndex, itemstack); - } else if (enumitemslot == EnumItemSlot.OFFHAND) { - this.b(itemstack); - this.inventory.extraSlots.set(0, itemstack); - } else if (enumitemslot.a() == EnumItemSlot.Function.ARMOR) { - this.b(itemstack); - this.inventory.armor.set(enumitemslot.b(), itemstack); - } - - } - - public boolean g(ItemStack itemstack) { - this.b(itemstack); - return this.inventory.pickup(itemstack); - } - - @Override - public Iterable aZ() { - return Lists.newArrayList(new ItemStack[]{this.getItemInMainHand(), this.getItemInOffHand()}); - } - - @Override - public Iterable getArmorItems() { - return this.inventory.armor; - } - - public boolean g(NBTTagCompound nbttagcompound) { - if (!this.isPassenger() && this.onGround && !this.isInWater()) { - if (this.getShoulderEntityLeft().isEmpty()) { - this.setShoulderEntityLeft(nbttagcompound); - this.e = this.world.getTime(); - return true; - } else if (this.getShoulderEntityRight().isEmpty()) { - this.setShoulderEntityRight(nbttagcompound); - this.e = this.world.getTime(); - return true; - } else { - return false; - } - } else { - return false; - } - } - - protected void releaseShoulderEntities() { - if (this.e + 20L < this.world.getTime()) { - // CraftBukkit start - if (this.spawnEntityFromShoulder(this.getShoulderEntityLeft())) { - this.setShoulderEntityLeft(new NBTTagCompound()); - } - if (this.spawnEntityFromShoulder(this.getShoulderEntityRight())) { - this.setShoulderEntityRight(new NBTTagCompound()); - } - // CraftBukkit end - } - - } - - // Paper start - public Entity releaseLeftShoulderEntity() { - Entity entity = this.spawnEntityFromShoulder0(this.getShoulderEntityLeft()); - if (entity != null) { - this.setShoulderEntityLeft(new NBTTagCompound()); - } - return entity; - } - - public Entity releaseRightShoulderEntity() { - Entity entity = this.spawnEntityFromShoulder0(this.getShoulderEntityRight()); - if (entity != null) { - this.setShoulderEntityRight(new NBTTagCompound()); - } - return entity; - } - // Paper - maintain old signature - private boolean spawnEntityFromShoulder(NBTTagCompound nbttagcompound) { // CraftBukkit void->boolean - return spawnEntityFromShoulder0(nbttagcompound) != null; - } - - // Paper - return entity - private Entity spawnEntityFromShoulder0(@Nullable NBTTagCompound nbttagcompound) { - if (!this.world.isClientSide && nbttagcompound != null && !nbttagcompound.isEmpty()) { - return EntityTypes.a(nbttagcompound, this.world).map((entity) -> { // CraftBukkit - if (entity instanceof EntityTameableAnimal) { - ((EntityTameableAnimal) entity).setOwnerUUID(this.uniqueID); - } - - entity.setPosition(this.locX, this.locY + 0.699999988079071D, this.locZ); - boolean addedToWorld = ((WorldServer) this.world).addEntitySerialized(entity, CreatureSpawnEvent.SpawnReason.SHOULDER_ENTITY); // CraftBukkit - return addedToWorld ? entity : null; - }).orElse(null); // CraftBukkit // Paper - false -> null - } - - return null; // Paper - return null - } - // Paper end - - @Override - public abstract boolean isSpectator(); - - @Override - public boolean isSwimming() { - return !this.abilities.isFlying && !this.isSpectator() && super.isSwimming(); - } - - public abstract boolean isCreative(); - - @Override - public boolean bE() { - return !this.abilities.isFlying; - } - - public Scoreboard getScoreboard() { - return this.world.getScoreboard(); - } - - @Override - public IChatBaseComponent getScoreboardDisplayName() { - IChatBaseComponent ichatbasecomponent = ScoreboardTeam.a(this.getScoreboardTeam(), this.getDisplayName()); - - return this.c(ichatbasecomponent); - } - - public IChatBaseComponent dU() { - return (new ChatComponentText("")).addSibling(this.getDisplayName()).a(" (").a(this.bW.getId().toString()).a(")"); - } - - private IChatBaseComponent c(IChatBaseComponent ichatbasecomponent) { - String s = this.getProfile().getName(); - - return ichatbasecomponent.a((chatmodifier) -> { - chatmodifier.setChatClickable(new ChatClickable(ChatClickable.EnumClickAction.SUGGEST_COMMAND, "/tell " + s + " ")).setChatHoverable(this.bK()).setInsertion(s); - }); - } - - @Override - public String getName() { - return this.getProfile().getName(); - } - - @Override - public float b(EntityPose entitypose, EntitySize entitysize) { - switch (entitypose) { - case SWIMMING: - case FALL_FLYING: - case SPIN_ATTACK: - return 0.4F; - case SNEAKING: - return 1.27F; - default: - return 1.62F; - } - } - - @Override - public void setAbsorptionHearts(float f) { - if (f < 0.0F) { - f = 0.0F; - } - - this.getDataWatcher().set(EntityHuman.c, f); - } - - @Override - public float getAbsorptionHearts() { - return (Float) this.getDataWatcher().get(EntityHuman.c); - } - - public static UUID a(GameProfile gameprofile) { - UUID uuid = gameprofile.getId(); - - if (uuid == null) { - uuid = getOfflineUUID(gameprofile.getName()); - } - - return uuid; - } - - public static UUID getOfflineUUID(String s) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + s).getBytes(StandardCharsets.UTF_8)); - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - if (i >= 0 && i < this.inventory.items.size()) { - this.inventory.setItem(i, itemstack); - return true; - } else { - EnumItemSlot enumitemslot; - - if (i == 100 + EnumItemSlot.HEAD.b()) { - enumitemslot = EnumItemSlot.HEAD; - } else if (i == 100 + EnumItemSlot.CHEST.b()) { - enumitemslot = EnumItemSlot.CHEST; - } else if (i == 100 + EnumItemSlot.LEGS.b()) { - enumitemslot = EnumItemSlot.LEGS; - } else if (i == 100 + EnumItemSlot.FEET.b()) { - enumitemslot = EnumItemSlot.FEET; - } else { - enumitemslot = null; - } - - if (i == 98) { - this.setSlot(EnumItemSlot.MAINHAND, itemstack); - return true; - } else if (i == 99) { - this.setSlot(EnumItemSlot.OFFHAND, itemstack); - return true; - } else if (enumitemslot == null) { - int j = i - 200; - - if (j >= 0 && j < this.enderChest.getSize()) { - this.enderChest.setItem(j, itemstack); - return true; - } else { - return false; - } - } else { - if (!itemstack.isEmpty()) { - if (!(itemstack.getItem() instanceof ItemArmor) && !(itemstack.getItem() instanceof ItemElytra)) { - if (enumitemslot != EnumItemSlot.HEAD) { - return false; - } - } else if (EntityInsentient.h(itemstack) != enumitemslot) { - return false; - } - } - - this.inventory.setItem(enumitemslot.b() + this.inventory.items.size(), itemstack); - return true; - } - } - } - - @Override - public EnumMainHand getMainHand() { - return (Byte) this.datawatcher.get(EntityHuman.bu) == 0 ? EnumMainHand.LEFT : EnumMainHand.RIGHT; - } - - public void a(EnumMainHand enummainhand) { - this.datawatcher.set(EntityHuman.bu, (byte) (enummainhand == EnumMainHand.LEFT ? 0 : 1)); - } - - public NBTTagCompound getShoulderEntityLeft() { - return (NBTTagCompound) this.datawatcher.get(EntityHuman.bv); - } - - public void setShoulderEntityLeft(NBTTagCompound nbttagcompound) { - this.datawatcher.set(EntityHuman.bv, nbttagcompound); - } - - public NBTTagCompound getShoulderEntityRight() { - return (NBTTagCompound) this.datawatcher.get(EntityHuman.bw); - } - - public void setShoulderEntityRight(NBTTagCompound nbttagcompound) { - this.datawatcher.set(EntityHuman.bw, nbttagcompound); - } - - public float getCooldownPeriod() { return this.dY(); } // Paper - OBFHELPER - public float dY() { - return (float) (1.0D / this.getAttributeInstance(GenericAttributes.ATTACK_SPEED).getValue() * 20.0D); - } - - public float getCooledAttackStrength(float adjustTicks) { return s(adjustTicks); } // Paper - OBFHELPER - public float s(float f) { - return MathHelper.a(((float) this.aD + f) / this.dY(), 0.0F, 1.0F); - } - - public void resetCooldown() { this.dZ(); } // Paper - OBFHELPER - public void dZ() { - this.aD = 0; - } - - public ItemCooldown getCooldownTracker() { - return this.bZ; - } - - public float eb() { - return (float) this.getAttributeInstance(GenericAttributes.LUCK).getValue(); - } - - public boolean isCreativeAndOp() { - return this.abilities.canInstantlyBuild && this.y() >= 2; - } - - @Override - public boolean e(ItemStack itemstack) { - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - - return this.getEquipment(enumitemslot).isEmpty(); - } - - @Override - public EntitySize a(EntityPose entitypose) { - return (EntitySize) EntityHuman.b.getOrDefault(entitypose, EntityHuman.bs); - } - - // Paper start - protected boolean tryReadyArrow(ItemStack bow, ItemStack itemstack) { - return !(this instanceof EntityPlayer) || - new com.destroystokyo.paper.event.player.PlayerReadyArrowEvent( - ((EntityPlayer) this).getBukkitEntity(), - org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(bow), - org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack) - ).callEvent(); - // Paper end - } - - @Override - public ItemStack f(ItemStack itemstack) { - if (!(itemstack.getItem() instanceof ItemProjectileWeapon)) { - return ItemStack.a; - } else { - Predicate predicate = ((ItemProjectileWeapon) itemstack.getItem()).d(); - ItemStack itemstack1 = ItemProjectileWeapon.a((EntityLiving) this, predicate); - - if (!itemstack1.isEmpty()) { - return itemstack1; - } else { - predicate = ((ItemProjectileWeapon) itemstack.getItem()).b(); - - for (int i = 0; i < this.inventory.getSize(); ++i) { - ItemStack itemstack2 = this.inventory.getItem(i); - - if (predicate.test(itemstack2) && tryReadyArrow(itemstack, itemstack2)) { // Paper - return itemstack2; - } - } - - return this.abilities.canInstantlyBuild ? new ItemStack(Items.ARROW) : ItemStack.a; - } - } - } - - @Override - public ItemStack a(World world, ItemStack itemstack) { - this.getFoodData().a(itemstack.getItem(), itemstack); - this.b(StatisticList.ITEM_USED.b(itemstack.getItem())); - world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PLAYER_BURP, SoundCategory.PLAYERS, 0.5F, world.random.nextFloat() * 0.1F + 0.9F); - if (this instanceof EntityPlayer) { - CriterionTriggers.z.a((EntityPlayer) this, itemstack); - } - - return super.a(world, itemstack); - } - - public static enum EnumBedResult { - - NOT_POSSIBLE_HERE, NOT_POSSIBLE_NOW(new ChatMessage("block.minecraft.bed.no_sleep", new Object[0])), TOO_FAR_AWAY(new ChatMessage("block.minecraft.bed.too_far_away", new Object[0])), OBSTRUCTED(new ChatMessage("block.minecraft.bed.obstructed", new Object[0])), OTHER_PROBLEM, NOT_SAFE(new ChatMessage("block.minecraft.bed.not_safe", new Object[0])); - - @Nullable - private final IChatBaseComponent g; - - private EnumBedResult() { - this.g = null; - } - - private EnumBedResult(IChatBaseComponent ichatbasecomponent) { - this.g = ichatbasecomponent; - } - - @Nullable - public IChatBaseComponent a() { - return this.g; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityIllagerIllusioner.java b/src/main/java/net/minecraft/server/EntityIllagerIllusioner.java deleted file mode 100644 index cc37b5ff1..000000000 --- a/src/main/java/net/minecraft/server/EntityIllagerIllusioner.java +++ /dev/null @@ -1,237 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class EntityIllagerIllusioner extends EntityIllagerWizard implements IRangedEntity { - - private int bz; - private final Vec3D[][] bA; - - public EntityIllagerIllusioner(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.f = 5; - this.bA = new Vec3D[2][4]; - - for (int i = 0; i < 4; ++i) { - this.bA[0][i] = new Vec3D(0.0D, 0.0D, 0.0D); - this.bA[1][i] = new Vec3D(0.0D, 0.0D, 0.0D); - } - - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(1, new EntityIllagerWizard.b()); - this.goalSelector.a(4, new EntityIllagerIllusioner.b()); - this.goalSelector.a(5, new EntityIllagerIllusioner.a()); - this.goalSelector.a(6, new PathfinderGoalBowShoot<>(this, 0.5D, 20, 15.0F)); - this.goalSelector.a(8, new PathfinderGoalRandomStroll(this, 0.6D)); - this.goalSelector.a(9, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 3.0F, 1.0F)); - this.goalSelector.a(10, new PathfinderGoalLookAtPlayer(this, EntityInsentient.class, 8.0F)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[]{EntityRaider.class})).a(new Class[0])); // CraftBukkit - decompile error - this.targetSelector.a(2, (new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)).a(300)); - this.targetSelector.a(3, (new PathfinderGoalNearestAttackableTarget<>(this, EntityVillagerAbstract.class, false)).a(300)); - this.targetSelector.a(3, (new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, false)).a(300)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.5D); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(18.0D); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(32.0D); - } - - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.BOW)); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.world.isClientSide && this.isInvisible()) { - --this.bz; - if (this.bz < 0) { - this.bz = 0; - } - - if (this.hurtTicks != 1 && this.ticksLived % 1200 != 0) { - if (this.hurtTicks == this.hurtDuration - 1) { - this.bz = 3; - - for (int i = 0; i < 4; ++i) { - this.bA[0][i] = this.bA[1][i]; - this.bA[1][i] = new Vec3D(0.0D, 0.0D, 0.0D); - } - } - } else { - this.bz = 3; - float f = -6.0F; - boolean flag = true; - - int j; - - for (j = 0; j < 4; ++j) { - this.bA[0][j] = this.bA[1][j]; - this.bA[1][j] = new Vec3D((double) (-6.0F + (float) this.random.nextInt(13)) * 0.5D, (double) Math.max(0, this.random.nextInt(6) - 4), (double) (-6.0F + (float) this.random.nextInt(13)) * 0.5D); - } - - for (j = 0; j < 16; ++j) { - this.world.addParticle(Particles.CLOUD, this.locX + (this.random.nextDouble() - 0.5D) * (double) this.getWidth(), this.locY + this.random.nextDouble() * (double) this.getHeight(), this.locZ + (this.random.nextDouble() - 0.5D) * (double) this.getWidth(), 0.0D, 0.0D, 0.0D); - } - - this.world.a(this.locX, this.locY, this.locZ, SoundEffects.ENTITY_ILLUSIONER_MIRROR_MOVE, this.getSoundCategory(), 1.0F, 1.0F, false); - } - } - - } - - @Override - public SoundEffect dV() { - return SoundEffects.ENTITY_ILLUSIONER_AMBIENT; - } - - @Override - public boolean r(Entity entity) { - return super.r(entity) ? true : (entity instanceof EntityLiving && ((EntityLiving) entity).getMonsterType() == EnumMonsterType.ILLAGER ? this.getScoreboardTeam() == null && entity.getScoreboardTeam() == null : false); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_ILLUSIONER_AMBIENT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_ILLUSIONER_DEATH; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_ILLUSIONER_HURT; - } - - @Override - protected SoundEffect getSoundCastSpell() { - return SoundEffects.ENTITY_ILLUSIONER_CAST_SPELL; - } - - @Override - public void a(int i, boolean flag) {} - - @Override - public void a(EntityLiving entityliving, float f) { - ItemStack itemstack = this.f(this.b(ProjectileHelper.a(this, Items.BOW))); - EntityArrow entityarrow = ProjectileHelper.a(this, itemstack, f); - double d0 = entityliving.locX - this.locX; - double d1 = entityliving.getBoundingBox().minY + (double) (entityliving.getHeight() / 3.0F) - entityarrow.locY; - double d2 = entityliving.locZ - this.locZ; - double d3 = (double) MathHelper.sqrt(d0 * d0 + d2 * d2); - - entityarrow.shoot(d0, d1 + d3 * 0.20000000298023224D, d2, 1.6F, (float) (14 - this.world.getDifficulty().a() * 4)); - // Paper start - org.bukkit.event.entity.EntityShootBowEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityShootBowEvent(this, this.getItemInMainHand(), this.getItemInOffHand(), entityarrow,0.8F); - if (event.isCancelled()) { - event.getProjectile().remove(); - return; - } - - if (event.getProjectile() == entityarrow.getBukkitEntity()) { - this.world.addEntity(entityarrow); - } - this.a(SoundEffects.ENTITY_SKELETON_SHOOT, 1.0F, 1.0F / (this.getRandom().nextFloat() * 0.4F + 0.8F)); - // Paper end - } - - class a extends EntityIllagerWizard.c { - - private int e; - - private a() { - super(); - } - - @Override - public boolean a() { - return !super.a() ? false : (EntityIllagerIllusioner.this.getGoalTarget() == null ? false : (EntityIllagerIllusioner.this.getGoalTarget().getId() == this.e ? false : EntityIllagerIllusioner.this.world.getDamageScaler(new BlockPosition(EntityIllagerIllusioner.this)).a((float) EnumDifficulty.NORMAL.ordinal()))); - } - - @Override - public void c() { - super.c(); - this.e = EntityIllagerIllusioner.this.getGoalTarget().getId(); - } - - @Override - protected int g() { - return 20; - } - - @Override - protected int h() { - return 180; - } - - @Override - protected void j() { - EntityIllagerIllusioner.this.getGoalTarget().addEffect(new MobEffect(MobEffects.BLINDNESS, 400), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - - @Override - protected SoundEffect k() { - return SoundEffects.ENTITY_ILLUSIONER_PREPARE_BLINDNESS; - } - - @Override - protected EntityIllagerWizard.Spell l() { - return EntityIllagerWizard.Spell.BLINDNESS; - } - } - - class b extends EntityIllagerWizard.c { - - private b() { - super(); - } - - @Override - public boolean a() { - return !super.a() ? false : !EntityIllagerIllusioner.this.hasEffect(MobEffects.INVISIBILITY); - } - - @Override - protected int g() { - return 20; - } - - @Override - protected int h() { - return 340; - } - - @Override - protected void j() { - EntityIllagerIllusioner.this.addEffect(new MobEffect(MobEffects.INVISIBILITY, 1200), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ILLUSION); // CraftBukkit - } - - @Nullable - @Override - protected SoundEffect k() { - return SoundEffects.ENTITY_ILLUSIONER_PREPARE_MIRROR; - } - - @Override - protected EntityIllagerWizard.Spell l() { - return EntityIllagerWizard.Spell.DISAPPEAR; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityInsentient.java b/src/main/java/net/minecraft/server/EntityInsentient.java deleted file mode 100644 index d00e99cdb..000000000 --- a/src/main/java/net/minecraft/server/EntityInsentient.java +++ /dev/null @@ -1,1359 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.UUID; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.craftbukkit.entity.CraftLivingEntity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.entity.EntityPickupItemEvent; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.event.entity.EntityTargetEvent; -import org.bukkit.event.entity.EntityUnleashEvent; -import org.bukkit.event.entity.EntityUnleashEvent.UnleashReason; -// CraftBukkit end - -public abstract class EntityInsentient extends EntityLiving { - - private static final DataWatcherObject b = DataWatcher.a(EntityInsentient.class, DataWatcherRegistry.a); - public int e; - protected int f; - protected ControllerLook lookController; - protected ControllerMove moveController; - protected ControllerJump bt; - private final EntityAIBodyControl c; - protected NavigationAbstract navigation; - public PathfinderGoalSelector goalSelector; - @Nullable public PathfinderGoalFloat goalFloat; // Paper - public PathfinderGoalSelector targetSelector; - private EntityLiving goalTarget; - private final EntitySenses bz; - private final NonNullList bA; - public final float[] dropChanceHand; - private final NonNullList bB; - public final float[] dropChanceArmor; - // private boolean canPickUpLoot; // CraftBukkit - moved up to EntityLiving - public boolean persistent; - private final Map bE; - public MinecraftKey lootTableKey; - public long lootTableSeed; - @Nullable - private Entity leashHolder; - private int bI; - @Nullable - private NBTTagCompound bJ; - private BlockPosition bK; - private float bL; - - protected EntityInsentient(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.bA = NonNullList.a(2, ItemStack.a); - this.dropChanceHand = new float[2]; - this.bB = NonNullList.a(4, ItemStack.a); - this.dropChanceArmor = new float[4]; - this.bE = Maps.newEnumMap(PathType.class); - this.bK = BlockPosition.ZERO; - this.bL = -1.0F; - this.goalSelector = new PathfinderGoalSelector(world != null && world.getMethodProfiler() != null ? world.getMethodProfiler() : null); - this.targetSelector = new PathfinderGoalSelector(world != null && world.getMethodProfiler() != null ? world.getMethodProfiler() : null); - this.lookController = new ControllerLook(this); - this.moveController = new ControllerMove(this); - this.bt = new ControllerJump(this); - this.c = this.o(); - this.navigation = this.b(world); - this.bz = new EntitySenses(this); - Arrays.fill(this.dropChanceArmor, 0.085F); - Arrays.fill(this.dropChanceHand, 0.085F); - if (world != null && !world.isClientSide) { - this.initPathfinder(); - } - - // CraftBukkit start - default persistance to type's persistance value - this.persistent = !isTypeNotPersistent(0); - // CraftBukkit end - } - - protected void initPathfinder() {} - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeMap().b(GenericAttributes.FOLLOW_RANGE).setValue(16.0D); - this.getAttributeMap().b(GenericAttributes.ATTACK_KNOCKBACK); - } - - protected NavigationAbstract b(World world) { - return new Navigation(this, world); - } - - public float a(PathType pathtype) { - Float ofloat = (Float) this.bE.get(pathtype); - - return ofloat == null ? pathtype.a() : ofloat; - } - - public void a(PathType pathtype, float f) { - this.bE.put(pathtype, f); - } - - protected EntityAIBodyControl o() { - return new EntityAIBodyControl(this); - } - - public ControllerLook getControllerLook() { - return this.lookController; - } - - public ControllerMove getControllerMove() { - if (this.isPassenger() && this.getVehicle() instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) this.getVehicle(); - - return entityinsentient.getControllerMove(); - } else { - return this.moveController; - } - } - - public ControllerJump getControllerJump() { - return this.bt; - } - - public NavigationAbstract getNavigation() { - if (this.isPassenger() && this.getVehicle() instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) this.getVehicle(); - - return entityinsentient.getNavigation(); - } else { - return this.navigation; - } - } - - public EntitySenses getEntitySenses() { - return this.bz; - } - - @Nullable - public EntityLiving getGoalTarget() { - return this.goalTarget; - } - - public org.bukkit.craftbukkit.entity.CraftMob getBukkitMob() { return (org.bukkit.craftbukkit.entity.CraftMob) super.getBukkitEntity(); } // Paper - public void setGoalTarget(@Nullable EntityLiving entityliving) { - // CraftBukkit start - fire event - setGoalTarget(entityliving, EntityTargetEvent.TargetReason.UNKNOWN, true); - } - - public boolean setGoalTarget(EntityLiving entityliving, EntityTargetEvent.TargetReason reason, boolean fireEvent) { - if (getGoalTarget() == entityliving) return false; - 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 false; - } - - if (event.getTarget() != null) { - entityliving = ((CraftLivingEntity) event.getTarget()).getHandle(); - } else { - entityliving = null; - } - } - this.goalTarget = entityliving; - return true; - // CraftBukkit end - } - - @Override - public boolean a(EntityTypes entitytypes) { - return entitytypes != EntityTypes.GHAST; - } - - public void blockEaten() {} - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityInsentient.b, (byte) 0); - } - - public int A() { - return 80; - } - - public void B() { - SoundEffect soundeffect = this.getSoundAmbient(); - - if (soundeffect != null) { - this.a(soundeffect, this.getSoundVolume(), this.cV()); - } - - } - - @Override - public void entityBaseTick() { - super.entityBaseTick(); - this.world.getMethodProfiler().enter("mobBaseTick"); - if (this.isAlive() && this.random.nextInt(1000) < this.e++) { - this.l(); - this.B(); - } - - this.world.getMethodProfiler().exit(); - } - - @Override - protected void c(DamageSource damagesource) { - this.l(); - super.c(damagesource); - } - - private void l() { - this.e = -this.A(); - } - - @Override - protected int getExpValue(EntityHuman entityhuman) { - if (this.f > 0) { - int i = this.f; - - int j; - - for (j = 0; j < this.bB.size(); ++j) { - if (!((ItemStack) this.bB.get(j)).isEmpty() && this.dropChanceArmor[j] <= 1.0F) { - i += 1 + this.random.nextInt(3); - } - } - - for (j = 0; j < this.bA.size(); ++j) { - if (!((ItemStack) this.bA.get(j)).isEmpty() && this.dropChanceHand[j] <= 1.0F) { - i += 1 + this.random.nextInt(3); - } - } - - return i; - } else { - return this.f; - } - } - - public void doSpawnEffect() { - if (this.world.isClientSide) { - for (int i = 0; i < 20; ++i) { - double d0 = this.random.nextGaussian() * 0.02D; - double d1 = this.random.nextGaussian() * 0.02D; - double d2 = this.random.nextGaussian() * 0.02D; - double d3 = 10.0D; - - this.world.addParticle(Particles.POOF, this.locX + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth() - d0 * 10.0D, this.locY + (double) (this.random.nextFloat() * this.getHeight()) - d1 * 10.0D, this.locZ + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth() - d2 * 10.0D, d0, d1, d2); - } - } else { - this.world.broadcastEntityEffect(this, (byte) 20); - } - - } - - @Override - public void tick() { - super.tick(); - if (!this.world.isClientSide) { - this.dM(); - if (this.ticksLived % 5 == 0) { - this.F(); - } - } - - } - - protected void F() { - boolean flag = !(this.getRidingPassenger() instanceof EntityInsentient); - boolean flag1 = !(this.getVehicle() instanceof EntityBoat); - - this.goalSelector.a(PathfinderGoal.Type.MOVE, flag); - this.goalSelector.a(PathfinderGoal.Type.JUMP, flag && flag1); - this.goalSelector.a(PathfinderGoal.Type.LOOK, flag); - } - - @Override - protected float e(float f, float f1) { - this.c.a(); - return f1; - } - - @Nullable - protected SoundEffect getSoundAmbient() { - return null; - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("CanPickUpLoot", this.canPickupLoot()); - nbttagcompound.setBoolean("PersistenceRequired", this.persistent); - NBTTagList nbttaglist = new NBTTagList(); - - NBTTagCompound nbttagcompound1; - - for (Iterator iterator = this.bB.iterator(); iterator.hasNext(); nbttaglist.add(nbttagcompound1)) { - ItemStack itemstack = (ItemStack) iterator.next(); - - nbttagcompound1 = new NBTTagCompound(); - if (!itemstack.isEmpty()) { - itemstack.save(nbttagcompound1); - } - } - - nbttagcompound.set("ArmorItems", nbttaglist); - NBTTagList nbttaglist1 = new NBTTagList(); - - NBTTagCompound nbttagcompound2; - - for (Iterator iterator1 = this.bA.iterator(); iterator1.hasNext(); nbttaglist1.add(nbttagcompound2)) { - ItemStack itemstack1 = (ItemStack) iterator1.next(); - - nbttagcompound2 = new NBTTagCompound(); - if (!itemstack1.isEmpty()) { - itemstack1.save(nbttagcompound2); - } - } - - nbttagcompound.set("HandItems", nbttaglist1); - NBTTagList nbttaglist2 = new NBTTagList(); - float[] afloat = this.dropChanceArmor; - int i = afloat.length; - - int j; - - for (j = 0; j < i; ++j) { - float f = afloat[j]; - - nbttaglist2.add(new NBTTagFloat(f)); - } - - nbttagcompound.set("ArmorDropChances", nbttaglist2); - NBTTagList nbttaglist3 = new NBTTagList(); - float[] afloat1 = this.dropChanceHand; - - j = afloat1.length; - - for (int k = 0; k < j; ++k) { - float f1 = afloat1[k]; - - nbttaglist3.add(new NBTTagFloat(f1)); - } - - nbttagcompound.set("HandDropChances", nbttaglist3); - if (this.leashHolder != null) { - nbttagcompound2 = new NBTTagCompound(); - if (this.leashHolder instanceof EntityLiving) { - UUID uuid = this.leashHolder.getUniqueID(); - - nbttagcompound2.a("UUID", uuid); - } else if (this.leashHolder instanceof EntityHanging) { - BlockPosition blockposition = ((EntityHanging) this.leashHolder).getBlockPosition(); - - nbttagcompound2.setInt("X", blockposition.getX()); - nbttagcompound2.setInt("Y", blockposition.getY()); - nbttagcompound2.setInt("Z", blockposition.getZ()); - } - - nbttagcompound.set("Leash", nbttagcompound2); - } - - nbttagcompound.setBoolean("LeftHanded", this.isLeftHanded()); - if (this.lootTableKey != null) { - nbttagcompound.setString("DeathLootTable", this.lootTableKey.toString()); - if (this.lootTableSeed != 0L) { - nbttagcompound.setLong("DeathLootTableSeed", this.lootTableSeed); - } - } - - if (this.isNoAI()) { - nbttagcompound.setBoolean("NoAI", this.isNoAI()); - } - - } - - @Override - 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.setCanPickupLoot(data); - } - } - - boolean data = nbttagcompound.getBoolean("PersistenceRequired"); - if (isLevelAtLeast(nbttagcompound, 1) || data) { - this.persistent = data; - } - // CraftBukkit end - NBTTagList nbttaglist; - int i; - - if (nbttagcompound.hasKeyOfType("ArmorItems", 9)) { - nbttaglist = nbttagcompound.getList("ArmorItems", 10); - - for (i = 0; i < this.bB.size(); ++i) { - this.bB.set(i, ItemStack.a(nbttaglist.getCompound(i))); - } - } - - if (nbttagcompound.hasKeyOfType("HandItems", 9)) { - nbttaglist = nbttagcompound.getList("HandItems", 10); - - for (i = 0; i < this.bA.size(); ++i) { - this.bA.set(i, ItemStack.a(nbttaglist.getCompound(i))); - } - } - - if (nbttagcompound.hasKeyOfType("ArmorDropChances", 9)) { - nbttaglist = nbttagcompound.getList("ArmorDropChances", 5); - - for (i = 0; i < nbttaglist.size(); ++i) { - this.dropChanceArmor[i] = nbttaglist.i(i); - } - } - - if (nbttagcompound.hasKeyOfType("HandDropChances", 9)) { - nbttaglist = nbttagcompound.getList("HandDropChances", 5); - - for (i = 0; i < nbttaglist.size(); ++i) { - this.dropChanceHand[i] = nbttaglist.i(i); - } - } - - if (nbttagcompound.hasKeyOfType("Leash", 10)) { - this.bJ = nbttagcompound.getCompound("Leash"); - } - - this.p(nbttagcompound.getBoolean("LeftHanded")); - if (nbttagcompound.hasKeyOfType("DeathLootTable", 8)) { - this.lootTableKey = new MinecraftKey(nbttagcompound.getString("DeathLootTable")); - this.lootTableSeed = nbttagcompound.getLong("DeathLootTableSeed"); - } - - this.setNoAI(nbttagcompound.getBoolean("NoAI")); - } - - @Override - protected void a(DamageSource damagesource, boolean flag) { - super.a(damagesource, flag); - this.lootTableKey = null; - } - // CraftBukkit - start - public MinecraftKey getLootTable() { - return getDefaultLootTable(); - } - // CraftBukkit - end - - @Override - protected LootTableInfo.Builder a(boolean flag, DamageSource damagesource) { - return super.a(flag, damagesource).a(this.lootTableSeed, this.random); - } - - @Override - public final MinecraftKey cG() { - return this.lootTableKey == null ? this.getDefaultLootTable() : this.lootTableKey; - } - - protected MinecraftKey getDefaultLootTable() { - return super.cG(); - } - - public void r(float f) { - this.bd = f; - } - - public void s(float f) { - this.bc = f; - } - - public void t(float f) { - this.bb = f; - } - - @Override - public void o(float f) { - super.o(f); - this.r(f); - } - - @Override - public void movementTick() { - super.movementTick(); - this.world.getMethodProfiler().enter("looting"); - if (!this.world.isClientSide && this.canPickupLoot() && this.isAlive() && !this.killed && this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - List list = this.world.a(EntityItem.class, this.getBoundingBox().grow(1.0D, 0.0D, 1.0D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityItem entityitem = (EntityItem) iterator.next(); - - if (!entityitem.dead && !entityitem.getItemStack().isEmpty() && !entityitem.q()) { - // Paper Start - if (!entityitem.canMobPickup) { - continue; - } - // Paper End - this.a(entityitem); - } - } - } - - this.world.getMethodProfiler().exit(); - } - - protected void a(EntityItem entityitem) { - ItemStack itemstack = entityitem.getItemStack(); - EnumItemSlot enumitemslot = h(itemstack); - ItemStack itemstack1 = this.getEquipment(enumitemslot); - boolean flag = this.a(itemstack, itemstack1, enumitemslot); - - // CraftBukkit start - boolean canPickup = flag && this.g(itemstack); - canPickup = !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityPickupItemEvent(this, entityitem, 0, !canPickup).isCancelled(); - if (canPickup) { - // CraftBukkit end - double d0 = (double) this.d(enumitemslot); - - if (!itemstack1.isEmpty() && (double) (this.random.nextFloat() - 0.1F) < d0) { - this.forceDrops = true; // CraftBukkit - this.a(itemstack1); - this.forceDrops = false; // CraftBukkit - } - - this.setSlot(enumitemslot, itemstack); - switch (enumitemslot.a()) { - case HAND: - this.dropChanceHand[enumitemslot.b()] = 2.0F; - break; - case ARMOR: - this.dropChanceArmor[enumitemslot.b()] = 2.0F; - } - - this.persistent = true; - this.receive(entityitem, itemstack.getCount()); - entityitem.die(); - } - - } - - protected boolean a(ItemStack itemstack, ItemStack itemstack1, EnumItemSlot enumitemslot) { - boolean flag = true; - - if (!itemstack1.isEmpty()) { - if (enumitemslot.a() == EnumItemSlot.Function.HAND) { - if (itemstack.getItem() instanceof ItemSword && !(itemstack1.getItem() instanceof ItemSword)) { - flag = true; - } else if (itemstack.getItem() instanceof ItemSword && itemstack1.getItem() instanceof ItemSword) { - ItemSword itemsword = (ItemSword) itemstack.getItem(); - ItemSword itemsword1 = (ItemSword) itemstack1.getItem(); - - if (itemsword.d() == itemsword1.d()) { - flag = itemstack.getDamage() < itemstack1.getDamage() || itemstack.hasTag() && !itemstack1.hasTag(); - } else { - flag = itemsword.d() > itemsword1.d(); - } - } 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)) { - flag = true; - } else if (itemstack.getItem() instanceof ItemArmor && itemstack1.getItem() instanceof ItemArmor && !EnchantmentManager.d(itemstack1)) { - ItemArmor itemarmor = (ItemArmor) itemstack.getItem(); - ItemArmor itemarmor1 = (ItemArmor) itemstack1.getItem(); - - if (itemarmor.e() == itemarmor1.e()) { - flag = itemstack.getDamage() < itemstack1.getDamage() || itemstack.hasTag() && !itemstack1.hasTag(); - } else { - flag = itemarmor.e() > itemarmor1.e(); - } - } else { - flag = false; - } - } - - return flag; - } - - protected boolean g(ItemStack itemstack) { - return true; - } - - public boolean isTypeNotPersistent(double d0) { - return true; - } - - public boolean I() { - return false; - } - - protected void checkDespawn() { - if (!this.isPersistent() && !this.I()) { - EntityHuman entityhuman = this.world.findNearbyPlayer(this, -1.0D); - - if (entityhuman != null && entityhuman.affectsSpawning) { // Paper - Affects Spawning API - double d0 = entityhuman.h(this); - - if (d0 > world.paperConfig.hardDespawnDistance) { // CraftBukkit - remove isTypeNotPersistent() check // Paper - custom despawn distances - this.die(); - } - - if (this.ticksFarFromPlayer > 600 && this.random.nextInt(800) == 0 && d0 > world.paperConfig.softDespawnDistance) { // CraftBukkit - remove isTypeNotPersistent() check // Paper - custom despawn distances - this.die(); - } else if (d0 < 1024.0D) { - this.ticksFarFromPlayer = 0; - } - } - - } else { - this.ticksFarFromPlayer = 0; - } - } - - @Override - protected final void doTick() { - ++this.ticksFarFromPlayer; - this.world.getMethodProfiler().enter("checkDespawn"); - this.checkDespawn(); - this.world.getMethodProfiler().exit(); - // Spigot Start - if ( this.fromMobSpawner ) - { - // Paper start - Allow nerfed mobs to jump and float - if (goalFloat != null) { - if (goalFloat.validConditions()) goalFloat.update(); - this.getControllerJump().jumpIfSet(); - } - // Paper end - return; - } - // Spigot End - this.world.getMethodProfiler().enter("sensing"); - this.bz.a(); - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("targetSelector"); - this.targetSelector.doTick(); - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("goalSelector"); - this.goalSelector.doTick(); - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("navigation"); - this.navigation.c(); - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("mob tick"); - this.mobTick(); - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("controls"); - this.world.getMethodProfiler().enter("move"); - this.moveController.a(); - this.world.getMethodProfiler().exitEnter("look"); - this.lookController.a(); - this.world.getMethodProfiler().exitEnter("jump"); - this.bt.b(); - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().exit(); - this.K(); - } - - protected void K() { - PacketDebug.a(this.world, this, this.goalSelector); - } - - protected void mobTick() {} - - public int M() { - return 40; - } - - public int dA() { - return 75; - } - - public int dB() { - return 10; - } - - 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.getBoundingBox().minY + entity.getBoundingBox().maxY) / 2.0D - (this.locY + (double) this.getHeadHeight()); - } - - double d3 = (double) MathHelper.sqrt(d0 * d0 + d1 * d1); - float f2 = (float) (MathHelper.d(d1, d0) * 57.2957763671875D) - 90.0F; - float f3 = (float) (-(MathHelper.d(d2, d3) * 57.2957763671875D)); - - this.pitch = this.a(this.pitch, f3, f1); - this.yaw = this.a(this.yaw, f2, f); - } - - 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 static boolean a(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - BlockPosition blockposition1 = blockposition.down(); - - return enummobspawn == EnumMobSpawn.SPAWNER || generatoraccess.getType(blockposition1).a((IBlockAccess) generatoraccess, blockposition1, entitytypes); - } - - public boolean a(GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn) { - return true; - } - - public boolean a(IWorldReader iworldreader) { - return !iworldreader.containsLiquid(this.getBoundingBox()) && iworldreader.i(this); - } - - public int dC() { - return 4; - } - - public boolean c(int i) { - return false; - } - - @Override - public int bv() { - 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; - } - } - - @Override - public Iterable aZ() { - return this.bA; - } - - @Override - public Iterable getArmorItems() { - return this.bB; - } - - @Override - public ItemStack getEquipment(EnumItemSlot enumitemslot) { - switch (enumitemslot.a()) { - case HAND: - return (ItemStack) this.bA.get(enumitemslot.b()); - case ARMOR: - return (ItemStack) this.bB.get(enumitemslot.b()); - default: - return ItemStack.a; - } - } - - @Override - public void setSlot(EnumItemSlot enumitemslot, ItemStack itemstack) { - switch (enumitemslot.a()) { - case HAND: - this.bA.set(enumitemslot.b(), itemstack); - break; - case ARMOR: - this.bB.set(enumitemslot.b(), itemstack); - } - - } - - @Override - protected void dropDeathLoot(DamageSource damagesource, int i, boolean flag) { - super.dropDeathLoot(damagesource, i, flag); - EnumItemSlot[] aenumitemslot = EnumItemSlot.values(); - int j = aenumitemslot.length; - - for (int k = 0; k < j; ++k) { - EnumItemSlot enumitemslot = aenumitemslot[k]; - ItemStack itemstack = this.getEquipment(enumitemslot); - float f = this.d(enumitemslot); - boolean flag1 = f > 1.0F; - - if (!itemstack.isEmpty() && !EnchantmentManager.shouldNotDrop(itemstack) && (flag || flag1) && this.random.nextFloat() - (float) i * 0.01F < f) { - if (!flag1 && itemstack.e()) { - itemstack.setDamage(itemstack.h() - this.random.nextInt(1 + this.random.nextInt(Math.max(itemstack.h() - 3, 1)))); - } - - this.a(itemstack); - } - } - - } - - protected float d(EnumItemSlot enumitemslot) { - float f; - - switch (enumitemslot.a()) { - case HAND: - f = this.dropChanceHand[enumitemslot.b()]; - break; - case ARMOR: - f = this.dropChanceArmor[enumitemslot.b()]; - break; - default: - f = 0.0F; - } - - return f; - } - - protected void a(DifficultyDamageScaler difficultydamagescaler) { - if (this.random.nextFloat() < 0.15F * difficultydamagescaler.d()) { - int i = this.random.nextInt(2); - float f = this.world.getDifficulty() == EnumDifficulty.HARD ? 0.1F : 0.25F; - - if (this.random.nextFloat() < 0.095F) { - ++i; - } - - if (this.random.nextFloat() < 0.095F) { - ++i; - } - - if (this.random.nextFloat() < 0.095F) { - ++i; - } - - boolean flag = true; - EnumItemSlot[] aenumitemslot = EnumItemSlot.values(); - int j = aenumitemslot.length; - - for (int k = 0; k < j; ++k) { - EnumItemSlot enumitemslot = aenumitemslot[k]; - - if (enumitemslot.a() == EnumItemSlot.Function.ARMOR) { - ItemStack itemstack = this.getEquipment(enumitemslot); - - if (!flag && this.random.nextFloat() < f) { - break; - } - - flag = false; - if (itemstack.isEmpty()) { - Item item = a(enumitemslot, i); - - if (item != null) { - this.setSlot(enumitemslot, new ItemStack(item)); - } - } - } - } - } - - } - - public static EnumItemSlot h(ItemStack itemstack) { - Item item = itemstack.getItem(); - - return item != Blocks.CARVED_PUMPKIN.getItem() && (!(item instanceof ItemBlock) || !(((ItemBlock) item).getBlock() instanceof BlockSkullAbstract)) ? (item instanceof ItemArmor ? ((ItemArmor) item).b() : (item == Items.ELYTRA ? EnumItemSlot.CHEST : (item == Items.SHIELD ? EnumItemSlot.OFFHAND : EnumItemSlot.MAINHAND))) : EnumItemSlot.HEAD; - } - - @Nullable - public static Item a(EnumItemSlot enumitemslot, int i) { - switch (enumitemslot) { - case HEAD: - if (i == 0) { - return Items.LEATHER_HELMET; - } else if (i == 1) { - return Items.GOLDEN_HELMET; - } else if (i == 2) { - return Items.CHAINMAIL_HELMET; - } else if (i == 3) { - return Items.IRON_HELMET; - } else if (i == 4) { - return Items.DIAMOND_HELMET; - } - case CHEST: - if (i == 0) { - return Items.LEATHER_CHESTPLATE; - } else if (i == 1) { - return Items.GOLDEN_CHESTPLATE; - } else if (i == 2) { - return Items.CHAINMAIL_CHESTPLATE; - } else if (i == 3) { - return Items.IRON_CHESTPLATE; - } else if (i == 4) { - return Items.DIAMOND_CHESTPLATE; - } - case LEGS: - if (i == 0) { - return Items.LEATHER_LEGGINGS; - } else if (i == 1) { - return Items.GOLDEN_LEGGINGS; - } else if (i == 2) { - return Items.CHAINMAIL_LEGGINGS; - } else if (i == 3) { - return Items.IRON_LEGGINGS; - } else if (i == 4) { - return Items.DIAMOND_LEGGINGS; - } - case FEET: - if (i == 0) { - return Items.LEATHER_BOOTS; - } else if (i == 1) { - return Items.GOLDEN_BOOTS; - } else if (i == 2) { - return Items.CHAINMAIL_BOOTS; - } else if (i == 3) { - return Items.IRON_BOOTS; - } else if (i == 4) { - return Items.DIAMOND_BOOTS; - } - default: - return null; - } - } - - protected void b(DifficultyDamageScaler difficultydamagescaler) { - float f = difficultydamagescaler.d(); - - if (!this.getItemInMainHand().isEmpty() && this.random.nextFloat() < 0.25F * f) { - this.setSlot(EnumItemSlot.MAINHAND, EnchantmentManager.a(this.random, this.getItemInMainHand(), (int) (5.0F + f * (float) this.random.nextInt(18)), false)); - } - - EnumItemSlot[] aenumitemslot = EnumItemSlot.values(); - int i = aenumitemslot.length; - - for (int j = 0; j < i; ++j) { - EnumItemSlot enumitemslot = aenumitemslot[j]; - - if (enumitemslot.a() == EnumItemSlot.Function.ARMOR) { - ItemStack itemstack = this.getEquipment(enumitemslot); - - if (!itemstack.isEmpty() && this.random.nextFloat() < 0.5F * f) { - this.setSlot(enumitemslot, EnchantmentManager.a(this.random, itemstack, (int) (5.0F + f * (float) this.random.nextInt(18)), false)); - } - } - } - - } - - @Nullable - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).addModifier(new AttributeModifier("Random spawn bonus", this.random.nextGaussian() * 0.05D, AttributeModifier.Operation.MULTIPLY_BASE)); - if (this.random.nextFloat() < 0.05F) { - this.p(true); - } else { - this.p(false); - } - - return groupdataentity; - } - - public boolean dD() { - return false; - } - - public void setPersistent() { - this.persistent = true; - } - - public void a(EnumItemSlot enumitemslot, float f) { - switch (enumitemslot.a()) { - case HAND: - this.dropChanceHand[enumitemslot.b()] = f; - break; - case ARMOR: - this.dropChanceArmor[enumitemslot.b()] = f; - } - - } - - public boolean canPickupLoot() { - return this.canPickUpLoot; - } - - public void setCanPickupLoot(boolean flag) { - this.canPickUpLoot = flag; - } - - @Override - public boolean e(ItemStack itemstack) { - EnumItemSlot enumitemslot = h(itemstack); - - return this.getEquipment(enumitemslot).isEmpty() && this.canPickupLoot(); - } - - public boolean isPersistent() { - return this.persistent; - } - - @Override - public final boolean b(EntityHuman entityhuman, EnumHand enumhand) { - if (!this.isAlive()) { - return false; - } else if (this.getLeashHolder() == entityhuman) { - // CraftBukkit start - fire PlayerUnleashEntityEvent - if (CraftEventFactory.callPlayerUnleashEntityEvent(this, entityhuman).isCancelled()) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutAttachEntity(this, this.getLeashHolder())); - return false; - } - // CraftBukkit end - this.unleash(true, !entityhuman.abilities.canInstantlyBuild); - return true; - } else { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() == Items.LEAD && this.a(entityhuman)) { - // CraftBukkit start - fire PlayerLeashEntityEvent - if (CraftEventFactory.callPlayerLeashEntityEvent(this, entityhuman, entityhuman).isCancelled()) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutAttachEntity(this, this.getLeashHolder())); - return false; - } - // CraftBukkit end - this.setLeashHolder(entityhuman, true); - itemstack.subtract(1); - return true; - } else { - return this.a(entityhuman, enumhand) ? true : super.b(entityhuman, enumhand); - } - } - } - - protected boolean a(EntityHuman entityhuman, EnumHand enumhand) { - return false; - } - - public boolean dH() { - return this.a(new BlockPosition(this)); - } - - public boolean a(BlockPosition blockposition) { - return this.bL == -1.0F ? true : this.bK.m(blockposition) < (double) (this.bL * this.bL); - } - - public void a(BlockPosition blockposition, int i) { - this.bK = blockposition; - this.bL = (float) i; - } - - public BlockPosition dI() { - return this.bK; - } - - public float dJ() { - return this.bL; - } - - public boolean dL() { - return this.bL != -1.0F; - } - - protected void dM() { - if (this.bJ != null) { - this.dT(); - } - - if (this.leashHolder != null) { - if (!this.isAlive() || !this.leashHolder.isAlive()) { - this.world.getServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), (!this.isAlive()) ? UnleashReason.PLAYER_UNLEASH : UnleashReason.HOLDER_GONE)); // CraftBukkit - this.unleash(true, true); - } - - } - } - - public void unleash(boolean flag, boolean flag1) { - if (this.leashHolder != null) { - this.attachedToPlayer = false; - if (!(this.leashHolder instanceof EntityHuman)) { - this.leashHolder.attachedToPlayer = false; - } - - this.leashHolder = null; - if (!this.world.isClientSide && flag1) { - this.forceDrops = true; // CraftBukkit - this.a((IMaterial) Items.LEAD); - this.forceDrops = false; // CraftBukkit - } - - if (!this.world.isClientSide && flag && this.world instanceof WorldServer) { - ((WorldServer) this.world).getChunkProvider().broadcast(this, new PacketPlayOutAttachEntity(this, (Entity) null)); - } - } - - } - - public boolean a(EntityHuman entityhuman) { - return !this.isLeashed() && !(this instanceof IMonster); - } - - public boolean isLeashed() { - return this.leashHolder != null; - } - - @Nullable - public Entity getLeashHolder() { - if (this.leashHolder == null && this.bI != 0 && this.world.isClientSide) { - this.leashHolder = this.world.getEntity(this.bI); - } - - return this.leashHolder; - } - - public void setLeashHolder(Entity entity, boolean flag) { - this.leashHolder = entity; - this.attachedToPlayer = true; - if (!(this.leashHolder instanceof EntityHuman)) { - this.leashHolder.attachedToPlayer = true; - } - - if (!this.world.isClientSide && flag && this.world instanceof WorldServer) { - ((WorldServer) this.world).getChunkProvider().broadcast(this, new PacketPlayOutAttachEntity(this, this.leashHolder)); - } - - if (this.isPassenger()) { - this.stopRiding(); - } - - } - - @Override - public boolean a(Entity entity, boolean flag) { - boolean flag1 = super.a(entity, flag); - - if (flag1 && this.isLeashed()) { - this.unleash(true, true); - } - - return flag1; - } - - private void dT() { - if (this.bJ != null && this.world instanceof WorldServer) { - if (this.bJ.b("UUID")) { - UUID uuid = this.bJ.a("UUID"); - Entity entity = ((WorldServer) this.world).getEntity(uuid); - - if (entity != null) { - this.setLeashHolder(entity, true); - } - } else if (this.bJ.hasKeyOfType("X", 99) && this.bJ.hasKeyOfType("Y", 99) && this.bJ.hasKeyOfType("Z", 99)) { - BlockPosition blockposition = new BlockPosition(this.bJ.getInt("X"), this.bJ.getInt("Y"), this.bJ.getInt("Z")); - - this.setLeashHolder(EntityLeash.a(this.world, blockposition), true); - } else { - this.world.getServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), UnleashReason.UNKNOWN)); // CraftBukkit - this.unleash(false, true); - } - - this.bJ = null; - } - - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - EnumItemSlot enumitemslot; - - if (i == 98) { - enumitemslot = EnumItemSlot.MAINHAND; - } else if (i == 99) { - enumitemslot = EnumItemSlot.OFFHAND; - } else if (i == 100 + EnumItemSlot.HEAD.b()) { - enumitemslot = EnumItemSlot.HEAD; - } else if (i == 100 + EnumItemSlot.CHEST.b()) { - enumitemslot = EnumItemSlot.CHEST; - } else if (i == 100 + EnumItemSlot.LEGS.b()) { - enumitemslot = EnumItemSlot.LEGS; - } else { - if (i != 100 + EnumItemSlot.FEET.b()) { - return false; - } - - enumitemslot = EnumItemSlot.FEET; - } - - if (!itemstack.isEmpty() && !b(enumitemslot, itemstack) && enumitemslot != EnumItemSlot.HEAD) { - return false; - } else { - this.setSlot(enumitemslot, itemstack); - return true; - } - } - - @Override - public boolean ca() { - return this.dD() && super.ca(); - } - - public static boolean b(EnumItemSlot enumitemslot, ItemStack itemstack) { - EnumItemSlot enumitemslot1 = h(itemstack); - - return enumitemslot1 == enumitemslot || enumitemslot1 == EnumItemSlot.MAINHAND && enumitemslot == EnumItemSlot.OFFHAND || enumitemslot1 == EnumItemSlot.OFFHAND && enumitemslot == EnumItemSlot.MAINHAND; - } - - @Override - public boolean df() { - return super.df() && !this.isNoAI(); - } - - public void setNoAI(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityInsentient.b); - - this.datawatcher.set(EntityInsentient.b, flag ? (byte) (b0 | 1) : (byte) (b0 & -2)); - } - - public void p(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityInsentient.b); - - this.datawatcher.set(EntityInsentient.b, flag ? (byte) (b0 | 2) : (byte) (b0 & -3)); - } - - public boolean isArmsRaisedZombie() { return (this.datawatcher.get(EntityInsentient.b) & 4) != 0; } // Paper - OBFHELPER - public void setArmsRaisedZombie(boolean flag) { this.q(flag); } // Paper - OBFHELPER - public void q(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityInsentient.b); - - this.datawatcher.set(EntityInsentient.b, flag ? (byte) (b0 | 4) : (byte) (b0 & -5)); - } - - public boolean isNoAI() { - return ((Byte) this.datawatcher.get(EntityInsentient.b) & 1) != 0; - } - - public boolean isLeftHanded() { - return ((Byte) this.datawatcher.get(EntityInsentient.b) & 2) != 0; - } - - public boolean dR() { - return ((Byte) this.datawatcher.get(EntityInsentient.b) & 4) != 0; - } - - @Override - public EnumMainHand getMainHand() { - return this.isLeftHanded() ? EnumMainHand.LEFT : EnumMainHand.RIGHT; - } - - @Override - public boolean c(EntityLiving entityliving) { - return entityliving.getEntityType() == EntityTypes.PLAYER && ((EntityHuman) entityliving).abilities.isInvulnerable ? false : super.c(entityliving); - } - - @Override - public boolean C(Entity entity) { - float f = (float) this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue(); - float f1 = (float) this.getAttributeInstance(GenericAttributes.ATTACK_KNOCKBACK).getValue(); - - if (entity instanceof EntityLiving) { - f += EnchantmentManager.a(this.getItemInMainHand(), ((EntityLiving) entity).getMonsterType()); - f1 += (float) EnchantmentManager.b((EntityLiving) this); - } - - int i = EnchantmentManager.getFireAspectEnchantmentLevel(this); - - if (i > 0) { - // CraftBukkit start - Call a combust event when somebody hits with a fire enchanted item - EntityCombustByEntityEvent combustEvent = new EntityCombustByEntityEvent(this.getBukkitEntity(), entity.getBukkitEntity(), i * 4); - org.bukkit.Bukkit.getPluginManager().callEvent(combustEvent); - - if (!combustEvent.isCancelled()) { - entity.setOnFire(combustEvent.getDuration(), false); - } - // CraftBukkit end - } - - boolean flag = entity.damageEntity(DamageSource.mobAttack(this), f); - - if (flag) { - if (f1 > 0.0F && entity instanceof EntityLiving) { - ((EntityLiving) entity).a(this, f1 * 0.5F, (double) MathHelper.sin(this.yaw * 0.017453292F), (double) (-MathHelper.cos(this.yaw * 0.017453292F))); - this.setMot(this.getMot().d(0.6D, 1.0D, 0.6D)); - } - - if (entity instanceof EntityHuman) { - EntityHuman entityhuman = (EntityHuman) entity; - ItemStack itemstack = this.getItemInMainHand(); - ItemStack itemstack1 = entityhuman.isHandRaised() ? entityhuman.dl() : ItemStack.a; - - if (!itemstack.isEmpty() && !itemstack1.isEmpty() && itemstack.getItem() instanceof ItemAxe && itemstack1.getItem() == Items.SHIELD) { - float f2 = 0.25F + (float) EnchantmentManager.getDigSpeedEnchantmentLevel(this) * 0.05F; - - if (this.random.nextFloat() < f2) { - entityhuman.getCooldownTracker().setCooldown(Items.SHIELD, 100); - this.world.broadcastEntityEffect(entityhuman, (byte) 30); - } - } - } - - this.a((EntityLiving) this, entity); - } - - return flag; - } - - public boolean isInDaylight() { return this.dS(); } // Paper - OBFHELPER - protected boolean dS() { - if (this.world.J() && !this.world.isClientSide) { - float f = this.aF(); - BlockPosition blockposition = this.getVehicle() instanceof EntityBoat ? (new BlockPosition(this.locX, (double) Math.round(this.locY), this.locZ)).up() : new BlockPosition(this.locX, (double) Math.round(this.locY), this.locZ); - - if (f > 0.5F && this.random.nextFloat() * 30.0F < (f - 0.4F) * 2.0F && this.world.f(blockposition)) { - return true; - } - } - - return false; - } - - @Override - protected void c(Tag tag) { - if (this.getNavigation().r()) { - super.c(tag); - } else { - this.setMot(this.getMot().add(0.0D, 0.3D, 0.0D)); - } - - } - - public boolean a(Item item) { - return this.getItemInMainHand().getItem() == item || this.getItemInOffHand().getItem() == item; - } -} diff --git a/src/main/java/net/minecraft/server/EntityIronGolem.java b/src/main/java/net/minecraft/server/EntityIronGolem.java deleted file mode 100644 index 8e463111b..000000000 --- a/src/main/java/net/minecraft/server/EntityIronGolem.java +++ /dev/null @@ -1,184 +0,0 @@ -package net.minecraft.server; - -public class EntityIronGolem extends EntityGolem { - - protected static final DataWatcherObject b = DataWatcher.a(EntityIronGolem.class, DataWatcherRegistry.a); - private int c; - private int d; - - public EntityIronGolem(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.K = 1.0F; - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(1, new PathfinderGoalMeleeAttack(this, 1.0D, true)); - this.goalSelector.a(2, new PathfinderGoalMoveTowardsTarget(this, 0.9D, 32.0F)); - this.goalSelector.a(2, new PathfinderGoalStrollVillage(this, 0.6D)); - this.goalSelector.a(3, new PathfinderGoalMoveThroughVillage(this, 0.6D, false, 4, () -> { - return false; - })); - this.goalSelector.a(5, new PathfinderGoalOfferFlower(this)); - this.goalSelector.a(6, new PathfinderGoalRandomStrollLand(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, new Class[0])); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityInsentient.class, 5, false, false, (entityliving) -> { - return entityliving instanceof IMonster && !(entityliving instanceof EntityCreeper); - })); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityIronGolem.b, (byte) 0); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(100.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); - this.getAttributeInstance(GenericAttributes.KNOCKBACK_RESISTANCE).setValue(1.0D); - } - - @Override - protected int l(int i) { - return i; - } - - @Override - protected void D(Entity entity) { - if (entity instanceof IMonster && !(entity instanceof EntityCreeper) && this.getRandom().nextInt(20) == 0) { - this.setGoalTarget((EntityLiving) entity, org.bukkit.event.entity.EntityTargetLivingEntityEvent.TargetReason.COLLISION, true); // CraftBukkit - set reason - } - - super.D(entity); - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.c > 0) { - --this.c; - } - - if (this.d > 0) { - --this.d; - } - - if (b(this.getMot()) > 2.500000277905201E-7D && this.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(new BlockPosition(i, j, k)); - - if (!iblockdata.isAir()) { - this.world.addParticle(new ParticleParamBlock(Particles.BLOCK, iblockdata), this.locX + ((double) this.random.nextFloat() - 0.5D) * (double) this.getWidth(), this.getBoundingBox().minY + 0.1D, this.locZ + ((double) this.random.nextFloat() - 0.5D) * (double) this.getWidth(), 4.0D * ((double) this.random.nextFloat() - 0.5D), 0.5D, ((double) this.random.nextFloat() - 0.5D) * 4.0D); - } - } - - } - - @Override - public boolean a(EntityTypes entitytypes) { - return this.isPlayerCreated() && entitytypes == EntityTypes.PLAYER ? false : (entitytypes == EntityTypes.CREEPER ? false : super.a(entitytypes)); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("PlayerCreated", this.isPlayerCreated()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setPlayerCreated(nbttagcompound.getBoolean("PlayerCreated")); - } - - @Override - public boolean C(Entity entity) { - this.c = 10; - this.world.broadcastEntityEffect(this, (byte) 4); - boolean flag = entity.damageEntity(DamageSource.mobAttack(this), (float) (7 + this.random.nextInt(15))); - - if (flag) { - entity.setMot(entity.getMot().add(0.0D, 0.4000000059604645D, 0.0D)); - this.a((EntityLiving) this, entity); - } - - this.a(SoundEffects.ENTITY_IRON_GOLEM_ATTACK, 1.0F, 1.0F); - return flag; - } - - public void r(boolean flag) { - if (flag) { - this.d = 400; - this.world.broadcastEntityEffect(this, (byte) 11); - } else { - this.d = 0; - this.world.broadcastEntityEffect(this, (byte) 34); - } - - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_IRON_GOLEM_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_IRON_GOLEM_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_IRON_GOLEM_STEP, 1.0F, 1.0F); - } - - public boolean isPlayerCreated() { - return ((Byte) this.datawatcher.get(EntityIronGolem.b) & 1) != 0; - } - - public void setPlayerCreated(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityIronGolem.b); - - if (flag) { - this.datawatcher.set(EntityIronGolem.b, (byte) (b0 | 1)); - } else { - this.datawatcher.set(EntityIronGolem.b, (byte) (b0 & -2)); - } - - } - - @Override - public void die(DamageSource damagesource) { - super.die(damagesource); - } - - @Override - public boolean a(IWorldReader iworldreader) { - BlockPosition blockposition = new BlockPosition(this); - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata = iworldreader.getType(blockposition1); - - if (!iblockdata.a((IBlockAccess) iworldreader, blockposition1, (Entity) this)) { - return false; - } else { - for (int i = 1; i < 3; ++i) { - BlockPosition blockposition2 = blockposition.up(i); - IBlockData iblockdata1 = iworldreader.getType(blockposition2); - - if (!SpawnerCreature.a((IBlockAccess) iworldreader, blockposition2, iblockdata1, iblockdata1.p())) { - return false; - } - } - - return SpawnerCreature.a((IBlockAccess) iworldreader, blockposition, iworldreader.getType(blockposition), FluidTypes.EMPTY.i()) && iworldreader.i(this); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityItem.java b/src/main/java/net/minecraft/server/EntityItem.java deleted file mode 100644 index df26cef6a..000000000 --- a/src/main/java/net/minecraft/server/EntityItem.java +++ /dev/null @@ -1,492 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.UUID; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Material; // Paper -import org.bukkit.event.entity.EntityPickupItemEvent; -import org.bukkit.event.player.PlayerPickupItemEvent; -// CraftBukkit end -import org.bukkit.event.player.PlayerAttemptPickupItemEvent; // Paper - -public class EntityItem extends Entity { - - private static final DataWatcherObject ITEM = DataWatcher.a(EntityItem.class, DataWatcherRegistry.g); - public int age; - public int pickupDelay; - private int f; - private UUID thrower; - private UUID owner; - public final float b; - private int lastTick = MinecraftServer.currentTick - 1; // CraftBukkit - public boolean canMobPickup = true; // Paper - - public EntityItem(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.f = 5; - this.b = (float) (Math.random() * 3.141592653589793D * 2.0D); - } - - public EntityItem(World world, double d0, double d1, double d2) { - this(EntityTypes.ITEM, world); - this.setPosition(d0, d1, d2); - this.yaw = this.random.nextFloat() * 360.0F; - this.setMot(this.random.nextDouble() * 0.2D - 0.1D, 0.2D, this.random.nextDouble() * 0.2D - 0.1D); - } - - public EntityItem(World world, double d0, double d1, double d2, ItemStack itemstack) { - this(world, d0, d1, d2); - this.setItemStack(itemstack); - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - protected void initDatawatcher() { - this.getDataWatcher().register(EntityItem.ITEM, ItemStack.a); - } - - @Override - public void tick() { - if (this.getItemStack().isEmpty()) { - this.die(); - } else { - super.tick(); - // CraftBukkit start - Use wall time for pickup and despawn timers - int elapsedTicks = MinecraftServer.currentTick - this.lastTick; - if (this.pickupDelay != 32767) this.pickupDelay -= elapsedTicks; - this.pickupDelay = Math.max(0, this.pickupDelay); // Paper - don't go below 0 - 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; - Vec3D vec3d = this.getMot(); - - if (this.a(TagsFluid.WATER)) { - this.v(); - } else if (!this.isNoGravity()) { - this.setMot(this.getMot().add(0.0D, -0.04D, 0.0D)); - } - - if (this.world.isClientSide) { - this.noclip = false; - } else { - this.noclip = !this.world.getCubes(this); - if (this.noclip) { - this.i(this.locX, (this.getBoundingBox().minY + this.getBoundingBox().maxY) / 2.0D, this.locZ); - } - } - - if (!this.onGround || b(this.getMot()) > 9.999999747378752E-6D || (this.ticksLived + this.getId()) % 4 == 0) { - this.move(EnumMoveType.SELF, this.getMot()); - float f = 0.98F; - - if (this.onGround) { - f = this.world.getType(new BlockPosition(this.locX, this.getBoundingBox().minY - 1.0D, this.locZ)).getBlock().m() * 0.98F; - } - - this.setMot(this.getMot().d((double) f, 0.98D, (double) f)); - if (this.onGround) { - this.setMot(this.getMot().d(1.0D, -0.5D, 1.0D)); - } - } - - boolean flag = MathHelper.floor(this.lastX) != MathHelper.floor(this.locX) || MathHelper.floor(this.lastY) != MathHelper.floor(this.locY) || MathHelper.floor(this.lastZ) != MathHelper.floor(this.locZ); - int i = flag ? 2 : 40; - - if (this.ticksLived % i == 0) { - if (this.world.getFluid(new BlockPosition(this)).a(TagsFluid.LAVA)) { - this.setMot((double) ((this.random.nextFloat() - this.random.nextFloat()) * 0.2F), 0.20000000298023224D, (double) ((this.random.nextFloat() - this.random.nextFloat()) * 0.2F)); - this.a(SoundEffects.ENTITY_GENERIC_BURN, 0.4F, 2.0F + this.random.nextFloat() * 0.4F); - } - - if (!this.world.isClientSide && this.z()) { - this.mergeNearby(); - } - } - - /* Craftbukkit start - moved up - if (this.age != -32768) { - ++this.age; - } - // Craftbukkit end */ - - this.impulse |= this.ay(); - if (!this.world.isClientSide) { - double d0 = this.getMot().d(vec3d).g(); - - if (d0 > 0.01D) { - this.impulse = true; - } - } - - if (!this.world.isClientSide && this.age >= this.getDespawnRate()) { // Spigot // Paper - // CraftBukkit start - fire ItemDespawnEvent - if (org.bukkit.craftbukkit.event.CraftEventFactory.callItemDespawnEvent(this).isCancelled()) { - this.age = 0; - return; - } - // CraftBukkit end - this.die(); - } - - } - } - - // Spigot start - copied from above - @Override - public void inactiveTick() { - // CraftBukkit start - Use wall time for pickup and despawn timers - int elapsedTicks = MinecraftServer.currentTick - this.lastTick; - if (this.pickupDelay != 32767) this.pickupDelay -= elapsedTicks; - this.pickupDelay = Math.max(0, this.pickupDelay); // Paper - don't go below 0 - if (this.age != -32768) this.age += elapsedTicks; - this.lastTick = MinecraftServer.currentTick; - // CraftBukkit end - - if (!this.world.isClientSide && this.age >= this.getDespawnRate()) { // Spigot // Paper - // 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 v() { - Vec3D vec3d = this.getMot(); - - this.setMot(vec3d.x * 0.9900000095367432D, vec3d.y + (double) (vec3d.y < 0.05999999865889549D ? 5.0E-4F : 0.0F), vec3d.z * 0.9900000095367432D); - } - - private void mergeNearby() { - // Paper start - avoid item merge if stack size above max stack size - ItemStack stack = getItemStack(); - if (stack.getCount() >= stack.getMaxStackSize()) return; - // Paper end - // Spigot start - double radius = world.spigotConfig.itemMerge; - List list = this.world.a(EntityItem.class, this.getBoundingBox().grow(radius, radius, radius), (entityitem) -> { - // Spigot end - return entityitem != this && entityitem.z(); - }); - - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityItem entityitem = (EntityItem) iterator.next(); - - if (!this.z()) { - return; - } - - this.a(entityitem); - } - } - - } - - private boolean z() { - ItemStack itemstack = this.getItemStack(); - - return this.isAlive() && this.pickupDelay != 32767 && this.age != -32768 && this.age < 6000 && itemstack.getCount() < itemstack.getMaxStackSize(); - } - - private void a(EntityItem entityitem) { - ItemStack itemstack = this.getItemStack(); - ItemStack itemstack1 = entityitem.getItemStack(); - - if (itemstack1.getItem() == itemstack.getItem()) { - if (itemstack1.getCount() + itemstack.getCount() <= itemstack1.getMaxStackSize()) { - if (!(itemstack1.hasTag() ^ itemstack.hasTag())) { - if (!itemstack1.hasTag() || itemstack1.getTag().equals(itemstack.getTag())) { - if (true || itemstack1.getCount() < itemstack.getCount()) { // Spigot - a(this, itemstack, entityitem, itemstack1); - } else { - a(entityitem, itemstack1, this, itemstack); - } - - } - } - } - } - } - - private static void a(EntityItem entityitem, ItemStack itemstack, EntityItem entityitem1, ItemStack itemstack1) { - if (org.bukkit.craftbukkit.event.CraftEventFactory.callItemMergeEvent(entityitem1, entityitem).isCancelled()) return; // CraftBukkit - int i = Math.min(itemstack.getMaxStackSize() - itemstack.getCount(), itemstack1.getCount()); - ItemStack itemstack2 = itemstack.cloneItemStack(); - - itemstack2.add(i); - entityitem.setItemStack(itemstack2); - itemstack1.subtract(i); - if (!itemstack1.isEmpty()) entityitem1.setItemStack(itemstack1); // CraftBukkit - don't set empty stacks - entityitem.pickupDelay = Math.max(entityitem.pickupDelay, entityitem1.pickupDelay); - entityitem.age = Math.min(entityitem.age, entityitem1.age); - if (itemstack1.isEmpty()) { - entityitem1.die(); - } - - } - - public void f() { - this.age = 4800; - } - - @Override - protected void burn(float i) { // CraftBukkit - int -> float - this.damageEntity(DamageSource.FIRE, (float) i); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (!this.getItemStack().isEmpty() && 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.velocityChanged(); - this.f = (int) ((float) this.f - f); - if (this.f <= 0) { - this.die(); - } - - return false; - } - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("Health", (short) this.f); - nbttagcompound.setShort("Age", (short) this.age); - nbttagcompound.setShort("PickupDelay", (short) this.pickupDelay); - if (this.getThrower() != null) { - nbttagcompound.set("Thrower", GameProfileSerializer.a(this.getThrower())); - } - - if (this.getOwner() != null) { - nbttagcompound.set("Owner", GameProfileSerializer.a(this.getOwner())); - } - - if (!this.getItemStack().isEmpty()) { - nbttagcompound.set("Item", this.getItemStack().save(new NBTTagCompound())); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.f = nbttagcompound.getShort("Health"); - this.age = nbttagcompound.getShort("Age"); - if (nbttagcompound.hasKey("PickupDelay")) { - this.pickupDelay = nbttagcompound.getShort("PickupDelay"); - } - - if (nbttagcompound.hasKeyOfType("Owner", 10)) { - this.owner = GameProfileSerializer.b(nbttagcompound.getCompound("Owner")); - } - - if (nbttagcompound.hasKeyOfType("Thrower", 10)) { - this.thrower = GameProfileSerializer.b(nbttagcompound.getCompound("Thrower")); - } - - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Item"); - - this.setItemStack(ItemStack.a(nbttagcompound1)); - if (this.getItemStack().isEmpty()) { - this.die(); - } - - } - - @Override - public void pickup(EntityHuman entityhuman) { - if (!this.world.isClientSide) { - ItemStack itemstack = this.getItemStack(); - Item item = itemstack.getItem(); - int i = itemstack.getCount(); - - // CraftBukkit start - fire PlayerPickupItemEvent - int canHold = entityhuman.inventory.canHold(itemstack); - int remaining = i - canHold; - boolean flyAtPlayer = false; // Paper - - // Paper start - if (this.pickupDelay <= 0) { - PlayerAttemptPickupItemEvent attemptEvent = new PlayerAttemptPickupItemEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), (org.bukkit.entity.Item) this.getBukkitEntity(), remaining); - this.world.getServer().getPluginManager().callEvent(attemptEvent); - - flyAtPlayer = attemptEvent.getFlyAtPlayer(); - if (attemptEvent.isCancelled()) { - if (flyAtPlayer) { - entityhuman.receive(this, i); - } - - return; - } - } - // Paper end - - if (this.pickupDelay <= 0 && canHold > 0) { - itemstack.setCount(canHold); - // Call legacy event - PlayerPickupItemEvent playerEvent = new PlayerPickupItemEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), (org.bukkit.entity.Item) this.getBukkitEntity(), remaining); - playerEvent.setCancelled(!entityhuman.canPickUpLoot); - this.world.getServer().getPluginManager().callEvent(playerEvent); - flyAtPlayer = playerEvent.getFlyAtPlayer(); // Paper - if (playerEvent.isCancelled()) { - itemstack.setCount(i); // SPIGOT-5294 - restore count - // Paper Start - if (flyAtPlayer) { - entityhuman.receive(this, i); - } - // Paper End - return; - } - - // Call newer event afterwards - EntityPickupItemEvent entityEvent = new EntityPickupItemEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), (org.bukkit.entity.Item) this.getBukkitEntity(), remaining); - entityEvent.setCancelled(!entityhuman.canPickUpLoot); - this.world.getServer().getPluginManager().callEvent(entityEvent); - if (entityEvent.isCancelled()) { - itemstack.setCount(i); // SPIGOT-5294 - restore count - return; - } - - itemstack.setCount(canHold + remaining); // = i - - // Possibly < 0; fix here so we do not have to modify code below - this.pickupDelay = 0; - } else if (this.pickupDelay == 0) { - // ensure that the code below isn't triggered if canHold says we can't pick the items up - this.pickupDelay = -1; - } - // CraftBukkit end - - if (this.pickupDelay == 0 && (this.owner == null || 6000 - this.age <= 200 || this.owner.equals(entityhuman.getUniqueID())) && entityhuman.inventory.pickup(itemstack)) { - // Paper Start - if (flyAtPlayer) { - entityhuman.receive(this, i); - } - // Paper End - if (itemstack.isEmpty()) { - this.die(); - itemstack.setCount(i); - } - - entityhuman.a(StatisticList.ITEM_PICKED_UP.b(item), i); - } - - } - } - - @Override - public IChatBaseComponent getDisplayName() { - IChatBaseComponent ichatbasecomponent = this.getCustomName(); - - return (IChatBaseComponent) (ichatbasecomponent != null ? ichatbasecomponent : new ChatMessage(this.getItemStack().j(), new Object[0])); - } - - @Override - public boolean bs() { - return false; - } - - @Nullable - @Override - public Entity a(DimensionManager dimensionmanager) { - Entity entity = super.a(dimensionmanager); - - if (!this.world.isClientSide && entity instanceof EntityItem) { - ((EntityItem) entity).mergeNearby(); - } - - return entity; - } - - public ItemStack getItemStack() { - return (ItemStack) this.getDataWatcher().get(EntityItem.ITEM); - } - - public void setItemStack(ItemStack itemstack) { - com.google.common.base.Preconditions.checkArgument(!itemstack.isEmpty(), "Cannot drop air"); // CraftBukkit - this.getDataWatcher().set(EntityItem.ITEM, itemstack); - this.getDataWatcher().markDirty(EntityItem.ITEM); // CraftBukkit - SPIGOT-4591, must mark dirty - } - - @Nullable - public UUID getOwner() { - return this.owner; - } - - public void setOwner(@Nullable UUID uuid) { - this.owner = uuid; - } - - @Nullable - public UUID getThrower() { - return this.thrower; - } - - public void setThrower(@Nullable UUID uuid) { - this.thrower = uuid; - } - - public void defaultPickupDelay() { - this.pickupDelay = 10; - } - - public void o() { - this.pickupDelay = 0; - } - - public void p() { - this.pickupDelay = 32767; - } - - public void setPickupDelay(int i) { - this.pickupDelay = i; - } - - public boolean q() { - return this.pickupDelay > 0; - } - - public void s() { - this.age = -6000; - } - - public void u() { - this.p(); - this.age = this.getDespawnRate() - 1; // Spigot // Paper - } - - // Paper start - public int getDespawnRate(){ - Material material = this.getItemStack().getBukkitStack().getType(); - return world.paperConfig.altItemDespawnRateMap.getOrDefault(material, world.spigotConfig.itemDespawnRate); - } - // Paper end - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntityItemFrame.java b/src/main/java/net/minecraft/server/EntityItemFrame.java deleted file mode 100644 index b078435c6..000000000 --- a/src/main/java/net/minecraft/server/EntityItemFrame.java +++ /dev/null @@ -1,346 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -import org.apache.commons.lang3.Validate; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class EntityItemFrame extends EntityHanging { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final DataWatcherObject ITEM = DataWatcher.a(EntityItemFrame.class, DataWatcherRegistry.g); - private static final DataWatcherObject g = DataWatcher.a(EntityItemFrame.class, DataWatcherRegistry.b); - private float ar = 1.0F; - - public EntityItemFrame(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityItemFrame(World world, BlockPosition blockposition, EnumDirection enumdirection) { - super(EntityTypes.ITEM_FRAME, world, blockposition); - this.setDirection(enumdirection); - } - - @Override - protected float getHeadHeight(EntityPose entitypose, EntitySize entitysize) { - return 0.0F; - } - - @Override - protected void initDatawatcher() { - this.getDataWatcher().register(EntityItemFrame.ITEM, ItemStack.a); - this.getDataWatcher().register(EntityItemFrame.g, 0); - } - - @Override - public void setDirection(EnumDirection enumdirection) { - Validate.notNull(enumdirection); - this.direction = enumdirection; - if (enumdirection.k().c()) { - this.pitch = 0.0F; - this.yaw = (float) (this.direction.get2DRotationValue() * 90); - } else { - this.pitch = (float) (-90 * enumdirection.c().a()); - this.yaw = 0.0F; - } - - this.lastPitch = this.pitch; - this.lastYaw = this.yaw; - this.updateBoundingBox(); - } - - @Override - protected void updateBoundingBox() { - if (this.direction != null) { - // CraftBukkit start code moved in to calculateBoundingBox - this.a(calculateBoundingBox(this, this.blockPosition, this.direction, this.getHangingWidth(), this.getHangingHeight())); - // CraftBukkit end - } - } - - // CraftBukkit start - break out BB calc into own method - public static AxisAlignedBB calculateBoundingBox(@Nullable Entity entity, BlockPosition blockPosition, EnumDirection direction, int width, int height) { - { - double d0 = 0.46875D; - - double locX = (double) blockPosition.getX() + 0.5D - (double) direction.getAdjacentX() * 0.46875D; - double locY = (double) blockPosition.getY() + 0.5D - (double) direction.getAdjacentY() * 0.46875D; - double locZ = (double) blockPosition.getZ() + 0.5D - (double) direction.getAdjacentZ() * 0.46875D; - if (entity != null) { - entity.locX = locX; - entity.locY = locY; - entity.locZ = locZ; - } - double d1 = (double) width; - double d2 = (double) height; - double d3 = (double) width; - EnumDirection.EnumAxis enumdirection_enumaxis = direction.k(); - - switch (enumdirection_enumaxis) { - case X: - d1 = 1.0D; - break; - case Y: - d2 = 1.0D; - break; - case Z: - d3 = 1.0D; - } - - d1 /= 32.0D; - d2 /= 32.0D; - d3 /= 32.0D; - return new AxisAlignedBB(locX - d1, locY - d2, locZ - d3, locX + d1, locY + d2, locZ + d3); - } - } - // CraftBukkit end - - @Override - public boolean survives() { - if (!this.world.getCubes(this)) { - return false; - } else { - IBlockData iblockdata = this.world.getType(this.blockPosition.shift(this.direction.opposite())); - - return !iblockdata.getMaterial().isBuildable() && (!this.direction.k().c() || !BlockDiodeAbstract.isDiode(iblockdata)) ? false : this.world.getEntities(this, this.getBoundingBox(), EntityItemFrame.b).isEmpty(); - } - } - - @Override - public float aS() { - return 0.0F; - } - - @Override - public void killEntity() { - this.c(this.getItem()); - super.killEntity(); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (!damagesource.isExplosion() && !this.getItem().isEmpty()) { - if (!this.world.isClientSide) { - // CraftBukkit start - fire EntityDamageEvent - if (org.bukkit.craftbukkit.event.CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f, false) || this.dead) { - return true; - } - // CraftBukkit end - this.b(damagesource.getEntity(), false); - this.a(SoundEffects.ENTITY_ITEM_FRAME_REMOVE_ITEM, 1.0F, 1.0F); - } - - return true; - } else { - return super.damageEntity(damagesource, f); - } - } - - @Override - public int getHangingWidth() { - return 12; - } - - @Override - public int getHangingHeight() { - return 12; - } - - @Override - public void a(@Nullable Entity entity) { - this.a(SoundEffects.ENTITY_ITEM_FRAME_BREAK, 1.0F, 1.0F); - this.b(entity, true); - } - - @Override - public void playPlaceSound() { - this.a(SoundEffects.ENTITY_ITEM_FRAME_PLACE, 1.0F, 1.0F); - } - - private void b(@Nullable Entity entity, boolean flag) { - if (!this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { - if (entity == null) { - this.c(this.getItem()); - } - - } else { - ItemStack itemstack = this.getItem(); - - this.setItem(ItemStack.a); - if (entity instanceof EntityHuman) { - EntityHuman entityhuman = (EntityHuman) entity; - - if (entityhuman.abilities.canInstantlyBuild) { - this.c(itemstack); - return; - } - } - - if (flag) { - this.a((IMaterial) Items.ITEM_FRAME); - } - - if (!itemstack.isEmpty()) { - itemstack = itemstack.cloneItemStack(); - this.c(itemstack); - if (this.random.nextFloat() < this.ar) { - this.a(itemstack); - } - } - - } - } - - private void c(ItemStack itemstack) { - if (itemstack.getItem() == Items.FILLED_MAP) { - WorldMap worldmap = ItemWorldMap.getSavedMap(itemstack, this.world); - - worldmap.a(this.blockPosition, this.getId()); - worldmap.a(true); - } - - itemstack.a((EntityItemFrame) null); - } - - public ItemStack getItem() { - return (ItemStack) this.getDataWatcher().get(EntityItemFrame.ITEM); - } - - public void setItem(ItemStack itemstack) { - this.setItem(itemstack, true); - } - - public void setItem(ItemStack itemstack, boolean flag) { - // CraftBukkit start - this.setItem(itemstack, flag, true); - } - - public void setItem(ItemStack itemstack, boolean flag, boolean playSound) { - // CraftBukkit end - if (!itemstack.isEmpty()) { - itemstack = itemstack.cloneItemStack(); - itemstack.setCount(1); - itemstack.a(this); - } - - this.getDataWatcher().set(EntityItemFrame.ITEM, itemstack); - if (!itemstack.isEmpty() && flag && playSound) { // CraftBukkit // Paper - only play sound when update flag is set - this.a(SoundEffects.ENTITY_ITEM_FRAME_ADD_ITEM, 1.0F, 1.0F); - } - - if (flag && this.blockPosition != null) { - this.world.updateAdjacentComparators(this.blockPosition, Blocks.AIR); - } - - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - if (i == 0) { - this.setItem(itemstack); - return true; - } else { - return false; - } - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (datawatcherobject.equals(EntityItemFrame.ITEM)) { - ItemStack itemstack = this.getItem(); - - if (!itemstack.isEmpty() && itemstack.z() != this) { - itemstack.a(this); - } - } - - } - - public int getRotation() { - return (Integer) this.getDataWatcher().get(EntityItemFrame.g); - } - - public void setRotation(int i) { - this.setRotation(i, true); - } - - private void setRotation(int i, boolean flag) { - this.getDataWatcher().set(EntityItemFrame.g, i % 8); - if (flag && this.blockPosition != null) { - this.world.updateAdjacentComparators(this.blockPosition, Blocks.AIR); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - if (!this.getItem().isEmpty()) { - nbttagcompound.set("Item", this.getItem().save(new NBTTagCompound())); - nbttagcompound.setByte("ItemRotation", (byte) this.getRotation()); - nbttagcompound.setFloat("ItemDropChance", this.ar); - } - - nbttagcompound.setByte("Facing", (byte) this.direction.a()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Item"); - - if (nbttagcompound1 != null && !nbttagcompound1.isEmpty()) { - ItemStack itemstack = ItemStack.a(nbttagcompound1); - - if (itemstack.isEmpty()) { - EntityItemFrame.LOGGER.warn("Unable to load item from: {}", nbttagcompound1); - } - - ItemStack itemstack1 = this.getItem(); - - if (!itemstack1.isEmpty() && !ItemStack.matches(itemstack, itemstack1)) { - this.c(itemstack1); - } - - this.setItem(itemstack, false); - this.setRotation(nbttagcompound.getByte("ItemRotation"), false); - if (nbttagcompound.hasKeyOfType("ItemDropChance", 99)) { - this.ar = nbttagcompound.getFloat("ItemDropChance"); - } - } - - this.setDirection(EnumDirection.fromType1(nbttagcompound.getByte("Facing"))); - } - - @Override - public boolean b(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (!this.world.isClientSide) { - if (this.getItem().isEmpty()) { - if (!itemstack.isEmpty()) { - this.setItem(itemstack); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - } - } else { - this.a(SoundEffects.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1.0F, 1.0F); - this.setRotation(this.getRotation() + 1); - } - } - - return true; - } - - public int q() { - return this.getItem().isEmpty() ? 0 : this.getRotation() % 8 + 1; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this, this.getEntityType(), this.direction.a(), this.getBlockPosition()); - } -} diff --git a/src/main/java/net/minecraft/server/EntityLargeFireball.java b/src/main/java/net/minecraft/server/EntityLargeFireball.java deleted file mode 100644 index d90860eb6..000000000 --- a/src/main/java/net/minecraft/server/EntityLargeFireball.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.event.entity.ExplosionPrimeEvent; // CraftBukkit - -public class EntityLargeFireball extends EntityFireballFireball { - - public int yield = 1; - - public EntityLargeFireball(EntityTypes entitytypes, World world) { - super(entitytypes, world); - isIncendiary = this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING); // CraftBukkit - } - - public EntityLargeFireball(World world, EntityLiving entityliving, double d0, double d1, double d2) { - super(EntityTypes.FIREBALL, entityliving, d0, d1, d2, world); - isIncendiary = this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING); // CraftBukkit - } - - @Override - protected void a(MovingObjectPosition movingobjectposition) { - if (!this.world.isClientSide) { - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - Entity entity = ((MovingObjectPositionEntity) movingobjectposition).getEntity(); - - entity.damageEntity(DamageSource.fireball(this, this.shooter), 6.0F); - this.a(this.shooter, entity); - } - - boolean flag = this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING); - - // CraftBukkit start - fire ExplosionPrimeEvent - ExplosionPrimeEvent event = new ExplosionPrimeEvent((org.bukkit.entity.Explosive) this.getBukkitEntity()); - 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 ? Explosion.Effect.DESTROY : Explosion.Effect.NONE); - } - // CraftBukkit end - this.die(); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("ExplosionPower", this.yield); - } - - @Override - 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/src/main/java/net/minecraft/server/EntityLeash.java b/src/main/java/net/minecraft/server/EntityLeash.java deleted file mode 100644 index 230f5a1b9..000000000 --- a/src/main/java/net/minecraft/server/EntityLeash.java +++ /dev/null @@ -1,164 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.craftbukkit.event.CraftEventFactory; - -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -public class EntityLeash extends EntityHanging { - - public EntityLeash(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityLeash(World world, BlockPosition blockposition) { - super(EntityTypes.LEASH_KNOT, world, blockposition); - this.setPosition((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D); - float f = 0.125F; - float f1 = 0.1875F; - float f2 = 0.25F; - - 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)); - this.attachedToPlayer = true; - } - - @Override - public void setPosition(double d0, double d1, double d2) { - super.setPosition((double) MathHelper.floor(d0) + 0.5D, (double) MathHelper.floor(d1) + 0.5D, (double) MathHelper.floor(d2) + 0.5D); - } - - @Override - protected void updateBoundingBox() { - this.locX = (double) this.blockPosition.getX() + 0.5D; - this.locY = (double) this.blockPosition.getY() + 0.5D; - this.locZ = (double) this.blockPosition.getZ() + 0.5D; - if (valid) ((WorldServer) world).chunkCheck(this); // CraftBukkit - } - - @Override - public void setDirection(EnumDirection enumdirection) {} - - @Override - public int getHangingWidth() { - return 9; - } - - @Override - public int getHangingHeight() { - return 9; - } - - @Override - protected float getHeadHeight(EntityPose entitypose, EntitySize entitysize) { - return -0.0625F; - } - - @Override - public void a(@Nullable Entity entity) { - this.a(SoundEffects.ENTITY_LEASH_KNOT_BREAK, 1.0F, 1.0F); - } - - @Override - public void b(NBTTagCompound nbttagcompound) {} - - @Override - public void a(NBTTagCompound nbttagcompound) {} - - @Override - public boolean b(EntityHuman entityhuman, EnumHand enumhand) { - if (this.world.isClientSide) { - return true; - } else { - boolean flag = false; - double d0 = 7.0D; - List list = this.world.a(EntityInsentient.class, new AxisAlignedBB(this.locX - 7.0D, this.locY - 7.0D, this.locZ - 7.0D, this.locX + 7.0D, this.locY + 7.0D, this.locZ + 7.0D)); - Iterator iterator = list.iterator(); - - EntityInsentient entityinsentient; - - while (iterator.hasNext()) { - entityinsentient = (EntityInsentient) iterator.next(); - if (entityinsentient.getLeashHolder() == entityhuman) { - // CraftBukkit start - if (CraftEventFactory.callPlayerLeashEntityEvent(entityinsentient, this, entityhuman).isCancelled()) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutAttachEntity(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 - if (true || entityhuman.abilities.canInstantlyBuild) { // CraftBukkit - Process for non-creative as well - iterator = list.iterator(); - - while (iterator.hasNext()) { - entityinsentient = (EntityInsentient) iterator.next(); - if (entityinsentient.isLeashed() && 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; - } - } - - @Override - public boolean survives() { - return this.world.getType(this.blockPosition).getBlock().a(TagsBlock.FENCES); - } - - public static EntityLeash a(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()) { - EntityLeash entityleash1 = new EntityLeash(world, blockposition); - - world.addEntity(entityleash1); - entityleash1.playPlaceSound(); - return entityleash1; - } - - entityleash = (EntityLeash) iterator.next(); - } while (!entityleash.getBlockPosition().equals(blockposition)); - - return entityleash; - } - - @Override - public void playPlaceSound() { - this.a(SoundEffects.ENTITY_LEASH_KNOT_PLACE, 1.0F, 1.0F); - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this, this.getEntityType(), 0, this.getBlockPosition()); - } -} diff --git a/src/main/java/net/minecraft/server/EntityLightning.java b/src/main/java/net/minecraft/server/EntityLightning.java deleted file mode 100644 index 27bf271bb..000000000 --- a/src/main/java/net/minecraft/server/EntityLightning.java +++ /dev/null @@ -1,166 +0,0 @@ -package net.minecraft.server; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class EntityLightning extends Entity { - - private int lifeTicks; - public long b; - private int d; - private final boolean e; - @Nullable - private EntityPlayer f; - public boolean isEffect; // CraftBukkit - public boolean isSilent = false; // Spigot - - public EntityLightning(World world, double d0, double d1, double d2, boolean flag) { - super(EntityTypes.LIGHTNING_BOLT, world); - this.isEffect = flag; // CraftBukkit - this.af = true; - this.setPositionRotation(d0, d1, d2, 0.0F, 0.0F); - this.lifeTicks = 2; - this.b = this.random.nextLong(); - this.d = this.random.nextInt(3) + 1; - this.e = flag; - EnumDifficulty enumdifficulty = world.getDifficulty(); - - if (enumdifficulty == EnumDifficulty.NORMAL || enumdifficulty == EnumDifficulty.HARD) { - this.a(4); - } - - } - - // 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 - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.WEATHER; - } - - public void d(@Nullable EntityPlayer entityplayer) { - this.f = entityplayer; - } - - @Override - public void tick() { - super.tick(); - if (!isSilent && this.lifeTicks == 2) { // Spigot - // CraftBukkit start - Use relative location for far away sounds - // this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_LIGHTNING_BOLT_THUNDER, SoundCategory.WEATHER, 10000.0F, 0.8F + this.random.nextFloat() * 0.2F); - float pitch = 0.8F + this.random.nextFloat() * 0.2F; - int viewDistance = ((WorldServer) this.world).getServer().getViewDistance() * 16; - for (EntityPlayer player : (List) (List) this.world.getPlayers()) { - double deltaX = this.locX - player.locX; - double deltaZ = this.locZ - player.locZ; - double distanceSquared = deltaX * deltaX + deltaZ * deltaZ; - // Paper start - Limit lightning strike effect distance - if (distanceSquared <= this.world.paperConfig.sqrMaxLightningImpactSoundDistance) { - player.playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(SoundEffects.ENTITY_LIGHTNING_BOLT_IMPACT, - SoundCategory.WEATHER, this.locX, this.locY, this.locZ, 2.0f, 0.5F + this.random.nextFloat() * 0.2F)); - } - - if (world.paperConfig.sqrMaxThunderDistance != -1 && distanceSquared >= world.paperConfig.sqrMaxThunderDistance) { - continue; - } - - // Paper end - 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 PacketPlayOutNamedSoundEffect(SoundEffects.ENTITY_LIGHTNING_BOLT_THUNDER, SoundCategory.WEATHER, relativeX, this.locY, relativeZ, 10000.0F, pitch)); - } else { - player.playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(SoundEffects.ENTITY_LIGHTNING_BOLT_THUNDER, SoundCategory.WEATHER, this.locX, this.locY, this.locZ, 10000.0F, pitch)); - } - } - // CraftBukkit end - //this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_LIGHTNING_BOLT_IMPACT, SoundCategory.WEATHER, 2.0F, 0.5F + this.random.nextFloat() * 0.2F); // Paper - Limit lightning strike effect distance (the packet is now sent from inside the loop) - } - - --this.lifeTicks; - if (this.lifeTicks < 0) { - if (this.d == 0) { - this.die(); - } else if (this.lifeTicks < -this.random.nextInt(10)) { - --this.d; - this.lifeTicks = 1; - this.b = this.random.nextLong(); - this.a(0); - } - } - - if (this.lifeTicks >= 0 && !this.isEffect) { // CraftBukkit - add !this.isEffect - if (this.world.isClientSide) { - this.world.c(2); - } else if (!this.e) { - double d0 = 3.0D; - List list = this.world.getEntities(this, new AxisAlignedBB(this.locX - 3.0D, this.locY - 3.0D, this.locZ - 3.0D, this.locX + 3.0D, this.locY + 6.0D + 3.0D, this.locZ + 3.0D), Entity::isAlive); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - entity.onLightningStrike(this); - } - - if (this.f != null) { - CriterionTriggers.E.a(this.f, (Collection) list); - } - } - } - - } - - private void a(int i) { - if (!this.e && !this.world.isClientSide && this.world.getGameRules().getBoolean(GameRules.DO_FIRE_TICK)) { - IBlockData iblockdata = Blocks.FIRE.getBlockData(); - BlockPosition blockposition = new BlockPosition(this); - - if (this.world.getType(blockposition).isAir() && iblockdata.canPlace(this.world, blockposition)) { - // CraftBukkit start - add "!isEffect" - if (!isEffect && !CraftEventFactory.callBlockIgniteEvent(world, blockposition, this).isCancelled()) { - this.world.setTypeUpdate(blockposition, iblockdata); - } - // CraftBukkit end - } - - for (int j = 0; j < i; ++j) { - BlockPosition blockposition1 = blockposition.b(this.random.nextInt(3) - 1, this.random.nextInt(3) - 1, this.random.nextInt(3) - 1); - - if (this.world.getType(blockposition1).isAir() && iblockdata.canPlace(this.world, blockposition1)) { - // CraftBukkit start - add "!isEffect" - if (!isEffect && !CraftEventFactory.callBlockIgniteEvent(world, blockposition1, this).isCancelled()) { - this.world.setTypeUpdate(blockposition1, iblockdata); - } - // CraftBukkit end - } - } - - } - } - - @Override - protected void initDatawatcher() {} - - @Override - protected void a(NBTTagCompound nbttagcompound) {} - - @Override - protected void b(NBTTagCompound nbttagcompound) {} - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntityWeather(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntityLiving.java b/src/main/java/net/minecraft/server/EntityLiving.java deleted file mode 100644 index f675ad2f5..000000000 --- a/src/main/java/net/minecraft/server/EntityLiving.java +++ /dev/null @@ -1,3277 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.event.player.PlayerArmorChangeEvent; -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Maps; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.types.DynamicOps; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.UUID; -import javax.annotation.Nullable; -import org.apache.commons.lang3.tuple.Pair; - -// CraftBukkit start -import java.util.ArrayList; -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import org.bukkit.Location; -import org.bukkit.craftbukkit.attribute.CraftAttributeMap; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; -import org.bukkit.event.entity.EntityPotionEffectEvent; -import org.bukkit.event.entity.EntityRegainHealthEvent; -import org.bukkit.event.entity.EntityResurrectEvent; -import org.bukkit.event.entity.EntityTeleportEvent; -import org.bukkit.event.player.PlayerItemConsumeEvent; -// CraftBukkit end - -import co.aikar.timings.MinecraftTimings; // Paper - -public abstract class EntityLiving extends Entity { - - private static final UUID b = UUID.fromString("662A6B8D-DA3E-4C1C-8813-96EA6097278D"); - private static final AttributeModifier c = (new AttributeModifier(EntityLiving.b, "Sprinting speed boost", 0.30000001192092896D, AttributeModifier.Operation.MULTIPLY_TOTAL)).a(false); - protected static final DataWatcherObject ar = DataWatcher.a(EntityLiving.class, DataWatcherRegistry.a); - public static final DataWatcherObject HEALTH = DataWatcher.a(EntityLiving.class, DataWatcherRegistry.c); - private static final DataWatcherObject e = DataWatcher.a(EntityLiving.class, DataWatcherRegistry.b); - private static final DataWatcherObject f = DataWatcher.a(EntityLiving.class, DataWatcherRegistry.i); - private static final DataWatcherObject g = DataWatcher.a(EntityLiving.class, DataWatcherRegistry.b); - private static final DataWatcherObject> bs = DataWatcher.a(EntityLiving.class, DataWatcherRegistry.m); - protected static final EntitySize as = EntitySize.c(0.2F, 0.2F); - private AttributeMapBase attributeMap; - public CombatTracker combatTracker = new CombatTracker(this); - public final Map effects = Maps.newHashMap(); - private final NonNullList bw; - private final NonNullList bx; - public boolean at; - public EnumHand au; - public int av; - public int aw; - public int hurtTicks; - public int hurtDuration; - public float az; - public int deathTicks; - public float aB; - public float aC; - protected int aD; - public float aE; - public float aF; - public float aG; - public int maxNoDamageTicks; - public final float aI; - public final float aJ; - public float aK; - public float aL; - public float aM; - public float aN; - public float aO; - public EntityHuman killer; - public int lastDamageByPlayerTime; // Paper - protected -> public - protected boolean killed; - protected int ticksFarFromPlayer; - protected float aT; - protected float aU; - protected float aV; - protected float aW; - protected float aX; - protected int aY; protected int getKillCount() { return this.aY; } // Paper - OBFHELPER - public float lastDamage; - protected boolean jumping; - public float bb; - public float bc; - public float bd; - public float be; - protected int bf; - protected double bg; - protected double bh; - protected double bi; - protected double bj; - protected double bk; - protected double bl; - protected int bm; - public boolean updateEffects; - @Nullable - public EntityLiving lastDamager; - public int hurtTimestamp; - private EntityLiving bB; - private int bC; - private float bD; - private int jumpTicks; - private float bF; - public ItemStack activeItem; // Paper - public - protected int bo; - protected int bp; - private BlockPosition bG; - private DamageSource bH; - private long bI; - protected int bq; - private float bJ; - private float bK; - protected BehaviorController br; - // CraftBukkit start - public int expToDrop; - public int maxAirTicks = 300; - boolean forceDrops; - ArrayList drops = new ArrayList(); - public org.bukkit.craftbukkit.attribute.CraftAttributeMap craftAttributes; - public boolean collides = true; - public boolean canPickUpLoot; - public org.bukkit.craftbukkit.entity.CraftLivingEntity getBukkitLivingEntity() { return (org.bukkit.craftbukkit.entity.CraftLivingEntity) super.getBukkitEntity(); } // Paper - public boolean silentDeath = false; // Paper - mark entity as dying silently for cancellable death event - - @Override - public float getBukkitYaw() { - return getHeadRotation(); - } - // CraftBukkit end - // Spigot start - public void inactiveTick() - { - super.inactiveTick(); - ++this.ticksFarFromPlayer; // Above all the floats - } - // Spigot end - - protected EntityLiving(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.bw = NonNullList.a(2, ItemStack.a); - this.bx = NonNullList.a(4, ItemStack.a); - this.maxNoDamageTicks = 20; - this.aO = 0.02F; - this.updateEffects = true; - this.activeItem = ItemStack.a; - this.initAttributes(); - // CraftBukkit - setHealth(getMaxHealth()) inlined and simplified to skip the instanceof check for EntityPlayer, as getBukkitEntity() is not initialized in constructor - this.datawatcher.set(EntityLiving.HEALTH, (float) this.getAttributeInstance(GenericAttributes.MAX_HEALTH).getValue()); - this.i = true; - this.aJ = (float) ((Math.random() + 1.0D) * 0.009999999776482582D); - this.setPosition(this.locX, this.locY, this.locZ); - this.aI = (float) Math.random() * 12398.0F; - this.yaw = (float) (Math.random() * 6.2831854820251465D); - this.aM = this.yaw; - this.K = 0.6F; - this.br = this.a(new Dynamic(DynamicOpsNBT.a, new NBTTagCompound())); - } - - public BehaviorController getBehaviorController() { - return this.br; - } - - protected BehaviorController a(Dynamic dynamic) { - return new BehaviorController<>(ImmutableList.of(), ImmutableList.of(), dynamic); - } - - @Override - public void killEntity() { - this.damageEntity(DamageSource.OUT_OF_WORLD, Float.MAX_VALUE); - } - - public boolean a(EntityTypes entitytypes) { - return true; - } - - @Override - protected void initDatawatcher() { - this.datawatcher.register(EntityLiving.ar, (byte) 0); - this.datawatcher.register(EntityLiving.e, 0); - this.datawatcher.register(EntityLiving.f, false); - this.datawatcher.register(EntityLiving.g, 0); - this.datawatcher.register(EntityLiving.HEALTH, 1.0F); - this.datawatcher.register(EntityLiving.bs, Optional.empty()); - } - - protected void initAttributes() { - this.getAttributeMap().b(GenericAttributes.MAX_HEALTH); - this.getAttributeMap().b(GenericAttributes.KNOCKBACK_RESISTANCE); - this.getAttributeMap().b(GenericAttributes.MOVEMENT_SPEED); - this.getAttributeMap().b(GenericAttributes.ARMOR); - this.getAttributeMap().b(GenericAttributes.ARMOR_TOUGHNESS); - } - - @Override - protected void a(double d0, boolean flag, IBlockData iblockdata, BlockPosition blockposition) { - if (!this.isInWater()) { - this.ay(); - } - - if (!this.world.isClientSide && this.fallDistance > 3.0F && flag) { - float f = (float) MathHelper.f(this.fallDistance - 3.0F); - - if (!iblockdata.isAir()) { - double d1 = Math.min((double) (0.2F + f / 15.0F), 2.5D); - int i = (int) (150.0D * d1); - - // CraftBukkit start - visiblity api - if (this instanceof EntityPlayer) { - ((WorldServer) this.world).sendParticles((EntityPlayer) this, new ParticleParamBlock(Particles.BLOCK, iblockdata), this.locX, this.locY, this.locZ, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D, false); - } else { - ((WorldServer) this.world).a(new ParticleParamBlock(Particles.BLOCK, iblockdata), this.locX, this.locY, this.locZ, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D); - } - // CraftBukkit end - } - } - - super.a(d0, flag, iblockdata, blockposition); - } - - public boolean canBreatheUnderwater() { return this.cm(); } // Paper - OBFHELPER - public boolean cm() { - return this.getMonsterType() == EnumMonsterType.UNDEAD; - } - - @Override - public void entityBaseTick() { - this.aB = this.aC; - if (this.justCreated) { - this.getBedPosition().ifPresent(this::a); - } - - super.entityBaseTick(); - this.world.getMethodProfiler().enter("livingEntityBaseTick"); - boolean flag = this instanceof EntityHuman; - - if (this.isAlive()) { - if (this.inBlock()) { - this.damageEntity(DamageSource.STUCK, 1.0F); - } else if (flag && !this.world.getWorldBorder().a(this.getBoundingBox())) { - double d0 = this.world.getWorldBorder().a((Entity) this) + this.world.getWorldBorder().getDamageBuffer(); - - if (d0 < 0.0D) { - double d1 = this.world.getWorldBorder().getDamageAmount(); - - if (d1 > 0.0D) { - this.damageEntity(DamageSource.STUCK, (float) Math.max(1, MathHelper.floor(-d0 * d1))); - } - } - } - } - - if (this.isFireProof() || this.world.isClientSide) { - this.extinguish(); - } - - boolean flag1 = flag && ((EntityHuman) this).abilities.isInvulnerable; - - if (this.isAlive()) { - if (this.a(TagsFluid.WATER) && this.world.getType(new BlockPosition(this.locX, this.locY + (double) this.getHeadHeight(), this.locZ)).getBlock() != Blocks.BUBBLE_COLUMN) { - if (!this.canBreatheUnderwater() && !MobEffectUtil.c(this) && !flag1) { // Paper - use OBFHELPER so it can be overridden - this.setAirTicks(this.l(this.getAirTicks())); - if (this.getAirTicks() == -20) { - this.setAirTicks(0); - Vec3D vec3d = this.getMot(); - - for (int i = 0; i < 8; ++i) { - float f = this.random.nextFloat() - this.random.nextFloat(); - float f1 = this.random.nextFloat() - this.random.nextFloat(); - float f2 = this.random.nextFloat() - this.random.nextFloat(); - - this.world.addParticle(Particles.BUBBLE, this.locX + (double) f, this.locY + (double) f1, this.locZ + (double) f2, vec3d.x, vec3d.y, vec3d.z); - } - - this.damageEntity(DamageSource.DROWN, 2.0F); - } - } - - if (!this.world.isClientSide && this.isPassenger() && this.getVehicle() != null && !this.getVehicle().bf()) { - this.stopRiding(); - } - } else if (this.getAirTicks() < this.bp()) { - this.setAirTicks(this.m(this.getAirTicks())); - } - - if (!this.world.isClientSide) { - BlockPosition blockposition = new BlockPosition(this); - - if (!Objects.equal(this.bG, blockposition)) { - this.bG = blockposition; - this.b(blockposition); - } - } - } - - if (this.isAlive() && this.au()) { - this.extinguish(); - } - - if (this.hurtTicks > 0) { - --this.hurtTicks; - } - - if (this.noDamageTicks > 0 && !(this instanceof EntityPlayer)) { - --this.noDamageTicks; - } - - if (this.getHealth() <= 0.0F) { - this.co(); - } - - if (this.lastDamageByPlayerTime > 0) { - --this.lastDamageByPlayerTime; - } else { - this.killer = null; - } - - if (this.bB != null && !this.bB.isAlive()) { - this.bB = null; - } - - if (this.lastDamager != null) { - if (!this.lastDamager.isAlive()) { - this.setLastDamager((EntityLiving) null); - } else if (this.ticksLived - this.hurtTimestamp > 100) { - this.setLastDamager((EntityLiving) null); - } - } - - this.tickPotionEffects(); - this.aW = this.aV; - this.aL = this.aK; - this.aN = this.aM; - this.lastYaw = this.yaw; - this.lastPitch = this.pitch; - this.world.getMethodProfiler().exit(); - } - - // CraftBukkit start - public int getExpReward() { - int exp = this.getExpValue(this.killer); - - if (!this.world.isClientSide && (this.lastDamageByPlayerTime > 0 || this.alwaysGivesExp()) && this.isDropExperience() && this.world.getGameRules().getBoolean(GameRules.DO_MOB_LOOT)) { - return exp; - } else { - return 0; - } - } - // CraftBukkit end - - protected void b(BlockPosition blockposition) { - int i = EnchantmentManager.a(Enchantments.FROST_WALKER, this); - - if (i > 0) { - EnchantmentFrostWalker.a(this, this.world, blockposition, i); - } - - } - - public boolean isBaby() { - return false; - } - - public float cn() { - return this.isBaby() ? 0.5F : 1.0F; - } - - @Override - public boolean bf() { - return false; - } - - protected void co() { - ++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; - EntityLiving attacker = killer != null ? killer : lastDamager; // Paper - this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY, this.locZ, j, this instanceof EntityPlayer ? org.bukkit.entity.ExperienceOrb.SpawnReason.PLAYER_DEATH : org.bukkit.entity.ExperienceOrb.SpawnReason.ENTITY_DEATH, attacker, this)); // Paper - } - this.expToDrop = 0; - // CraftBukkit end - - this.die(); - - for (i = 0; i < 20; ++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(Particles.POOF, this.locX + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), this.locY + (double) (this.random.nextFloat() * this.getHeight()), this.locZ + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), d0, d1, d2); - } - } - - } - - protected boolean isDropExperience() { - return !this.isBaby(); - } - - protected int l(int i) { - int j = EnchantmentManager.getOxygenEnchantmentLevel(this); - - return j > 0 && this.random.nextInt(j + 1) > 0 ? i : i - 1; - } - - protected int m(int i) { - return Math.min(i + 4, this.bp()); - } - - protected int getExpValue(EntityHuman entityhuman) { - return 0; - } - - protected boolean alwaysGivesExp() { - return false; - } - - public Random getRandom() { - return this.random; - } - - @Nullable - public EntityLiving getLastDamager() { - return this.lastDamager; - } - - public int ct() { - return this.hurtTimestamp; - } - - public void setLastDamager(@Nullable EntityLiving entityliving) { - this.lastDamager = entityliving; - this.hurtTimestamp = this.ticksLived; - } - - @Nullable - public EntityLiving cu() { - return this.bB; - } - - public int cv() { - return this.bC; - } - - public void z(Entity entity) { - if (entity instanceof EntityLiving) { - this.bB = (EntityLiving) entity; - } else { - this.bB = null; - } - - this.bC = this.ticksLived; - } - - public int cw() { - return this.ticksFarFromPlayer; - } - - public void n(int i) { - this.ticksFarFromPlayer = i; - } - - protected void b(ItemStack itemstack) { - if (!itemstack.isEmpty()) { - SoundEffect soundeffect = SoundEffects.ITEM_ARMOR_EQUIP_GENERIC; - Item item = itemstack.getItem(); - - if (item instanceof ItemArmor) { - soundeffect = ((ItemArmor) item).d().b(); - } else if (item == Items.ELYTRA) { - soundeffect = SoundEffects.ITEM_ARMOR_EQUIP_ELYTRA; - } - - this.a(soundeffect, 1.0F, 1.0F); - } - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setFloat("Health", this.getHealth()); - nbttagcompound.setShort("HurtTime", (short) this.hurtTicks); - nbttagcompound.setInt("HurtByTimestamp", this.hurtTimestamp); - nbttagcompound.setShort("DeathTime", (short) this.deathTicks); - nbttagcompound.setFloat("AbsorptionAmount", this.getAbsorptionHearts()); - EnumItemSlot[] aenumitemslot = EnumItemSlot.values(); - int i = aenumitemslot.length; - - EnumItemSlot enumitemslot; - int j; - ItemStack itemstack; - - for (j = 0; j < i; ++j) { - enumitemslot = aenumitemslot[j]; - itemstack = this.getEquipment(enumitemslot); - if (!itemstack.isEmpty()) { - this.getAttributeMap().a(itemstack.a(enumitemslot)); - } - } - - nbttagcompound.set("Attributes", GenericAttributes.a(this.getAttributeMap())); - aenumitemslot = EnumItemSlot.values(); - i = aenumitemslot.length; - - for (j = 0; j < i; ++j) { - enumitemslot = aenumitemslot[j]; - itemstack = this.getEquipment(enumitemslot); - if (!itemstack.isEmpty()) { - this.getAttributeMap().b(itemstack.a(enumitemslot)); - } - } - - if (!this.effects.isEmpty()) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.effects.values().iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - nbttaglist.add(mobeffect.a(new NBTTagCompound())); - } - - nbttagcompound.set("ActiveEffects", nbttaglist); - } - - nbttagcompound.setBoolean("FallFlying", this.isGliding()); - this.getBedPosition().ifPresent((blockposition) -> { - nbttagcompound.setInt("SleepingX", blockposition.getX()); - nbttagcompound.setInt("SleepingY", blockposition.getY()); - nbttagcompound.setInt("SleepingZ", blockposition.getZ()); - }); - nbttagcompound.set("Brain", (NBTBase) this.br.a((DynamicOps) DynamicOpsNBT.a)); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - // Paper start - jvm keeps optimizing the setter - float absorptionAmount = nbttagcompound.getFloat("AbsorptionAmount"); - if (Float.isNaN(absorptionAmount)) { - absorptionAmount = 0; - } - this.setAbsorptionHearts(absorptionAmount); - // Paper end - if (nbttagcompound.hasKeyOfType("Attributes", 9) && this.world != null && !this.world.isClientSide) { - 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.getCompound(i); - MobEffect mobeffect = MobEffect.b(nbttagcompound1); - - if (mobeffect != null) { - this.effects.put(mobeffect.getMobEffect(), mobeffect); - } - } - } - - // CraftBukkit start - if (nbttagcompound.hasKey("Bukkit.MaxHealth")) { - NBTBase nbtbase = nbttagcompound.get("Bukkit.MaxHealth"); - if (nbtbase.getTypeId() == 5) { - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(((NBTTagFloat) nbtbase).asDouble()); - } else if (nbtbase.getTypeId() == 3) { - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(((NBTTagInt) nbtbase).asDouble()); - } - } - // CraftBukkit end - - if (nbttagcompound.hasKeyOfType("Health", 99)) { - this.setHealth(nbttagcompound.getFloat("Health")); - } - - this.hurtTicks = nbttagcompound.getShort("HurtTime"); - this.deathTicks = nbttagcompound.getShort("DeathTime"); - this.hurtTimestamp = nbttagcompound.getInt("HurtByTimestamp"); - if (nbttagcompound.hasKeyOfType("Team", 8)) { - String s = nbttagcompound.getString("Team"); - ScoreboardTeam scoreboardteam = this.world.getScoreboard().getTeam(s); - if (!world.paperConfig.nonPlayerEntitiesOnScoreboards && !(this instanceof EntityHuman)) { scoreboardteam = null; } // Paper - boolean flag = scoreboardteam != null && this.world.getScoreboard().addPlayerToTeam(this.getUniqueIDString(), scoreboardteam); - - if (!flag) { - EntityLiving.LOGGER.warn("Unable to add mob to team \"{}\" (that team probably doesn't exist)", s); - } - } - - if (nbttagcompound.getBoolean("FallFlying")) { - this.setFlag(7, true); - } - - if (nbttagcompound.hasKeyOfType("SleepingX", 99) && nbttagcompound.hasKeyOfType("SleepingY", 99) && nbttagcompound.hasKeyOfType("SleepingZ", 99)) { - BlockPosition blockposition = new BlockPosition(nbttagcompound.getInt("SleepingX"), nbttagcompound.getInt("SleepingY"), nbttagcompound.getInt("SleepingZ")); - - this.d(blockposition); - this.datawatcher.set(EntityLiving.POSE, EntityPose.SLEEPING); - if (!this.justCreated) { - this.a(blockposition); - } - } - - if (nbttagcompound.hasKeyOfType("Brain", 10)) { - this.br = this.a(new Dynamic(DynamicOpsNBT.a, nbttagcompound.get("Brain"))); - } - - } - - // CraftBukkit start - private boolean isTickingEffects = false; - private List effectsToProcess = Lists.newArrayList(); - - private static class ProcessableEffect { - - private MobEffectList type; - private MobEffect effect; - private final EntityPotionEffectEvent.Cause cause; - - private ProcessableEffect(MobEffect effect, EntityPotionEffectEvent.Cause cause) { - this.effect = effect; - this.cause = cause; - } - - private ProcessableEffect(MobEffectList type, EntityPotionEffectEvent.Cause cause) { - this.type = type; - this.cause = cause; - } - } - // CraftBukkit end - - protected void tickPotionEffects() { - Iterator iterator = this.effects.keySet().iterator(); - - isTickingEffects = true; // CraftBukkit - try { - while (iterator.hasNext()) { - MobEffectList mobeffectlist = (MobEffectList) iterator.next(); - MobEffect mobeffect = (MobEffect) this.effects.get(mobeffectlist); - - if (!mobeffect.tick(this)) { - if (!this.world.isClientSide) { - // CraftBukkit start - EntityPotionEffectEvent event = CraftEventFactory.callEntityPotionEffectChangeEvent(this, mobeffect, null, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.EXPIRATION); - if (event.isCancelled()) { - continue; - } - // CraftBukkit end - iterator.remove(); - this.b(mobeffect); - } - } else if (mobeffect.getDuration() % 600 == 0) { - this.a(mobeffect, false); - } - } - } catch (ConcurrentModificationException concurrentmodificationexception) { - ; - } - // CraftBukkit start - isTickingEffects = false; - for (ProcessableEffect e : effectsToProcess) { - if (e.effect != null) { - addEffect(e.effect, e.cause); - } else { - removeEffect(e.type, e.cause); - } - } - effectsToProcess.clear(); - // CraftBukkit end - - if (this.updateEffects) { - if (!this.world.isClientSide) { - this.C(); - } - - this.updateEffects = false; - } - - int i = (Integer) this.datawatcher.get(EntityLiving.e); - boolean flag = (Boolean) this.datawatcher.get(EntityLiving.f); - - if (i > 0) { - boolean flag1; - - if (this.isInvisible()) { - flag1 = this.random.nextInt(15) == 0; - } else { - flag1 = this.random.nextBoolean(); - } - - if (flag) { - flag1 &= this.random.nextInt(5) == 0; - } - - if (flag1 && i > 0) { - double d0 = (double) (i >> 16 & 255) / 255.0D; - double d1 = (double) (i >> 8 & 255) / 255.0D; - double d2 = (double) (i >> 0 & 255) / 255.0D; - - this.world.addParticle(flag ? Particles.AMBIENT_ENTITY_EFFECT : Particles.ENTITY_EFFECT, this.locX + (this.random.nextDouble() - 0.5D) * (double) this.getWidth(), this.locY + this.random.nextDouble() * (double) this.getHeight(), this.locZ + (this.random.nextDouble() - 0.5D) * (double) this.getWidth(), d0, d1, d2); - } - } - - } - - protected void C() { - if (this.effects.isEmpty()) { - this.cy(); - this.setInvisible(false); - } else { - Collection collection = this.effects.values(); - - this.datawatcher.set(EntityLiving.f, c(collection)); - this.datawatcher.set(EntityLiving.e, PotionUtil.a(collection)); - this.setInvisible(this.hasEffect(MobEffects.INVISIBILITY)); - } - - } - - public double A(@Nullable Entity entity) { - double d0 = 1.0D; - - if (this.isSneaking()) { - d0 *= 0.8D; - } - - if (this.isInvisible()) { - float f = this.cT(); - - if (f < 0.1F) { - f = 0.1F; - } - - d0 *= 0.7D * (double) f; - } - - if (entity != null) { - ItemStack itemstack = this.getEquipment(EnumItemSlot.HEAD); - Item item = itemstack.getItem(); - EntityTypes entitytypes = entity.getEntityType(); - - if (entitytypes == EntityTypes.SKELETON && item == Items.SKELETON_SKULL || entitytypes == EntityTypes.ZOMBIE && item == Items.ZOMBIE_HEAD || entitytypes == EntityTypes.CREEPER && item == Items.CREEPER_HEAD) { - d0 *= 0.5D; - } - } - - return d0; - } - - public boolean c(EntityLiving entityliving) { - return true; - } - - public boolean a(EntityLiving entityliving, PathfinderTargetCondition pathfindertargetcondition) { - return pathfindertargetcondition.a(this, entityliving); - } - - public static boolean c(Collection collection) { - Iterator iterator = collection.iterator(); - - MobEffect mobeffect; - - do { - if (!iterator.hasNext()) { - return true; - } - - mobeffect = (MobEffect) iterator.next(); - } while (mobeffect.isAmbient()); - - return false; - } - - protected void cy() { - this.datawatcher.set(EntityLiving.f, false); - this.datawatcher.set(EntityLiving.e, 0); - } - - // CraftBukkit start - public boolean removeAllEffects() { - return removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.UNKNOWN); - } - - public boolean removeAllEffects(EntityPotionEffectEvent.Cause cause) { - // CraftBukkit end - if (this.world.isClientSide) { - return false; - } else { - Iterator iterator = this.effects.values().iterator(); - - boolean flag; - - for (flag = false; iterator.hasNext(); flag = true) { - // CraftBukkit start - MobEffect effect = (MobEffect) iterator.next(); - EntityPotionEffectEvent event = CraftEventFactory.callEntityPotionEffectChangeEvent(this, effect, null, cause, EntityPotionEffectEvent.Action.CLEARED); - if (event.isCancelled()) { - continue; - } - this.b(effect); - // CraftBukkit end - iterator.remove(); - } - - return flag; - } - } - - public Collection getEffects() { - return this.effects.values(); - } - - public Map cB() { - return this.effects; - } - - public boolean hasEffect(MobEffectList mobeffectlist) { - return this.effects.containsKey(mobeffectlist); - } - - @Nullable - public MobEffect getEffect(MobEffectList mobeffectlist) { - return (MobEffect) this.effects.get(mobeffectlist); - } - - // CraftBukkit start - public boolean addEffect(MobEffect mobeffect) { - return addEffect(mobeffect, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.UNKNOWN); - } - - public boolean addEffect(MobEffect mobeffect, EntityPotionEffectEvent.Cause cause) { - org.spigotmc.AsyncCatcher.catchOp("effect add"); // Spigot - if (isTickingEffects) { - effectsToProcess.add(new ProcessableEffect(mobeffect, cause)); - return true; - } - // CraftBukkit end - - if (!this.d(mobeffect)) { - return false; - } else { - MobEffect mobeffect1 = (MobEffect) this.effects.get(mobeffect.getMobEffect()); - - // CraftBukkit start - boolean override = false; - if (mobeffect1 != null) { - override = new MobEffect(mobeffect1).a(mobeffect); - } - - EntityPotionEffectEvent event = CraftEventFactory.callEntityPotionEffectChangeEvent(this, mobeffect1, mobeffect, cause, override); - if (event.isCancelled()) { - return false; - } - // CraftBukkit end - - if (mobeffect1 == null) { - this.effects.put(mobeffect.getMobEffect(), mobeffect); - this.a(mobeffect); - return true; - // CraftBukkit start - } else if (event.isOverride()) { - mobeffect1.a(mobeffect); - this.a(mobeffect1, true); - // CraftBukkit end - return true; - } else { - return false; - } - } - } - - public boolean d(MobEffect mobeffect) { - if (this.getMonsterType() == EnumMonsterType.UNDEAD) { - MobEffectList mobeffectlist = mobeffect.getMobEffect(); - - if (mobeffectlist == MobEffects.REGENERATION || mobeffectlist == MobEffects.POISON) { - return false; - } - } - - return true; - } - - public boolean cC() { - return this.getMonsterType() == EnumMonsterType.UNDEAD; - } - - // CraftBukkit start - @Nullable - public MobEffect c(@Nullable MobEffectList mobeffectlist) { - return c(mobeffectlist, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.UNKNOWN); - } - - @Nullable - public MobEffect c(@Nullable MobEffectList mobeffectlist, EntityPotionEffectEvent.Cause cause) { - if (isTickingEffects) { - effectsToProcess.add(new ProcessableEffect(mobeffectlist, cause)); - return null; - } - - MobEffect effect = this.effects.get(mobeffectlist); - if (effect == null) { - return null; - } - - EntityPotionEffectEvent event = CraftEventFactory.callEntityPotionEffectChangeEvent(this, effect, null, cause); - if (event.isCancelled()) { - return null; - } - - return (MobEffect) this.effects.remove(mobeffectlist); - } - - public boolean removeEffect(MobEffectList mobeffectlist) { - return removeEffect(mobeffectlist, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.UNKNOWN); - } - - public boolean removeEffect(MobEffectList mobeffectlist, EntityPotionEffectEvent.Cause cause) { - MobEffect mobeffect = this.c(mobeffectlist, cause); - // CraftBukkit end - - if (mobeffect != null) { - this.b(mobeffect); - return true; - } else { - return false; - } - } - - protected void a(MobEffect mobeffect) { - this.updateEffects = true; - if (!this.world.isClientSide) { - mobeffect.getMobEffect().b(this, this.getAttributeMap(), mobeffect.getAmplifier()); - } - - } - - protected void a(MobEffect mobeffect, boolean flag) { - this.updateEffects = true; - if (flag && !this.world.isClientSide) { - MobEffectList mobeffectlist = mobeffect.getMobEffect(); - - mobeffectlist.a(this, this.getAttributeMap(), mobeffect.getAmplifier()); - mobeffectlist.b(this, this.getAttributeMap(), mobeffect.getAmplifier()); - } - - } - - protected void b(MobEffect mobeffect) { - this.updateEffects = true; - if (!this.world.isClientSide) { - mobeffect.getMobEffect().a(this, 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) { - // Paper start - Forward - heal(f, regainReason, false); - } - - public void heal(float f, EntityRegainHealthEvent.RegainReason regainReason, boolean isFastRegen) { - // Paper end - float f1 = this.getHealth(); - - if (f1 > 0.0F) { - EntityRegainHealthEvent event = new EntityRegainHealthEvent(this.getBukkitEntity(), f, regainReason, isFastRegen); // Paper - // Suppress during worldgen - if (this.valid) { - this.world.getServer().getPluginManager().callEvent(event); - } - - if (!event.isCancelled()) { - this.setHealth((float) (this.getHealth() + event.getAmount())); - } - // CraftBukkit end - } - - } - - public float getHealth() { - // CraftBukkit start - Use unscaled health - if (this instanceof EntityPlayer) { - return (float) ((EntityPlayer) this).getBukkitEntity().getHealth(); - } - // CraftBukkit end - return (Float) this.datawatcher.get(EntityLiving.HEALTH); - } - - public void setHealth(float f) { - // Paper start - if (Float.isNaN(f)) { f = getMaxHealth(); if (this.valid) { - System.err.println("[NAN-HEALTH] " + getName() + " had NaN health set"); - } } // Paper end - // CraftBukkit start - Handle scaled health - if (this instanceof EntityPlayer) { - org.bukkit.craftbukkit.entity.CraftPlayer player = ((EntityPlayer) this).getBukkitEntity(); - // Squeeze - if (f < 0.0F) { - player.setRealHealth(0.0D); - } else if (f > player.getMaxHealth()) { - player.setRealHealth(player.getMaxHealth()); - } else { - player.setRealHealth(f); - } - - player.updateScaledHealth(false); - return; - } - // CraftBukkit end - this.datawatcher.set(EntityLiving.HEALTH, MathHelper.a(f, 0.0F, this.getMaxHealth())); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (this.world.isClientSide) { - return false; - } else if (this.dead || this.killed || this.getHealth() <= 0.0F) { // CraftBukkit - Don't allow entities that got set to dead/killed elsewhere to get damaged and die - return false; - } else if (damagesource.p() && this.hasEffect(MobEffects.FIRE_RESISTANCE)) { - return false; - } else { - if (this.isSleeping() && !this.world.isClientSide) { - this.dy(); - } - - this.ticksFarFromPlayer = 0; - float f1 = f; - - // CraftBukkit - Moved into damageEntity0(DamageSource, float) - if (false && (damagesource == DamageSource.ANVIL || damagesource == DamageSource.FALLING_BLOCK) && !this.getEquipment(EnumItemSlot.HEAD).isEmpty()) { - this.getEquipment(EnumItemSlot.HEAD).damage((int) (f * 4.0F + this.random.nextFloat() * f * 2.0F), this, (entityliving) -> { - entityliving.c(EnumItemSlot.HEAD); - }); - f *= 0.75F; - } - - boolean flag = f > 0.0F && this.applyBlockingModifier(damagesource); // Copied from below - float f2 = 0.0F; - - // CraftBukkit - Moved into damageEntity0(DamageSource, float) - if (false && f > 0.0F && this.applyBlockingModifier(damagesource)) { - this.damageShield(f); - f2 = f; - f = 0.0F; - if (!damagesource.b()) { - Entity entity = damagesource.j(); - - if (entity instanceof EntityLiving) { - this.shieldBlock((EntityLiving) entity); - } - } - - flag = true; - } - - this.aF = 1.5F; - boolean flag1 = true; - - if ((float) this.noDamageTicks > 10.0F) { - if (f <= this.lastDamage) { - this.forceExplosionKnockback = true; // CraftBukkit - SPIGOT-949 - for vanilla consistency, cooldown does not prevent explosion knockback - return false; - } - - // CraftBukkit start - if (!this.damageEntity0(damagesource, f - this.lastDamage)) { - return false; - } - // CraftBukkit end - this.lastDamage = f; - flag1 = false; - } else { - // CraftBukkit start - if (!this.damageEntity0(damagesource, f)) { - return false; - } - this.lastDamage = f; - this.noDamageTicks = 20; - // this.damageEntity0(damagesource, f); - // CraftBukkit end - this.hurtDuration = 10; - this.hurtTicks = this.hurtDuration; - } - - // CraftBukkit start - if (this instanceof EntityAnimal) { - ((EntityAnimal) this).resetLove(); - if (this instanceof EntityTameableAnimal) { - ((EntityTameableAnimal) this).getGoalSit().setSitting(false); - } - } - // CraftBukkit end - - this.az = 0.0F; - Entity entity1 = damagesource.getEntity(); - - if (entity1 != null) { - if (entity1 instanceof EntityLiving) { - this.setLastDamager((EntityLiving) entity1); - } - - if (entity1 instanceof EntityHuman) { - this.lastDamageByPlayerTime = 100; - this.killer = (EntityHuman) entity1; - } else if (entity1 instanceof EntityWolf) { - EntityWolf entitywolf = (EntityWolf) entity1; - - if (entitywolf.isTamed()) { - this.lastDamageByPlayerTime = 100; - EntityLiving entityliving = entitywolf.getOwner(); - - if (entityliving != null && entityliving.getEntityType() == EntityTypes.PLAYER) { - this.killer = (EntityHuman) entityliving; - } else { - this.killer = null; - } - } - } - } - - boolean knockbackCancelled = world.paperConfig.disableExplosionKnockback && damagesource.isExplosion() && this instanceof EntityHuman; // Paper - Disable explosion knockback - if (flag1) { - if (flag) { - this.world.broadcastEntityEffect(this, (byte) 29); - } else if (damagesource instanceof EntityDamageSource && ((EntityDamageSource) damagesource).y()) { - this.world.broadcastEntityEffect(this, (byte) 33); - } else { - byte b0; - - if (damagesource == DamageSource.DROWN) { - b0 = 36; - } else if (damagesource.p()) { - b0 = 37; - } else if (damagesource == DamageSource.SWEET_BERRY_BUSH) { - b0 = 44; - } else { - b0 = 2; - } - - if (!knockbackCancelled) // Paper - Disable explosion knockback - this.world.broadcastEntityEffect(this, b0); - } - - if (damagesource != DamageSource.DROWN && (!flag || f > 0.0F)) { - this.velocityChanged(); - } - - if (entity1 != null) { - double d0 = entity1.locX - this.locX; - - double d1; - - for (d1 = entity1.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.az = (float) (MathHelper.d(d1, d0) * 57.2957763671875D - (double) this.yaw); - this.a(entity1, 0.4F, d0, d1); - } else { - this.az = (float) ((int) (Math.random() * 2.0D) * 180); - } - } - - if (knockbackCancelled) this.world.broadcastEntityEffect(this, (byte) 2); // Paper - Disable explosion knockback - - if (this.getHealth() <= 0.0F) { - if (!this.f(damagesource)) { - // Paper start - moved into CraftEventFactory event caller for cancellable death event - //SoundEffect soundeffect = this.getSoundDeath(); - - //if (flag1 && soundeffect != null) { - // this.a(soundeffect, this.getSoundVolume(), this.cV()); - //} - this.silentDeath = !flag1; // mark entity as dying silently - // Paper end - - this.die(damagesource); - this.silentDeath = false; // Paper - cancellable death event - reset to default - } - } else if (flag1) { - this.c(damagesource); - } - - boolean flag2 = !flag || f > 0.0F; - - if (flag2) { - this.bH = damagesource; - this.bI = this.world.getTime(); - } - - if (this instanceof EntityPlayer) { - CriterionTriggers.h.a((EntityPlayer) this, damagesource, f1, f, flag); - if (f2 > 0.0F && f2 < 3.4028235E37F) { - ((EntityPlayer) this).a(StatisticList.DAMAGE_BLOCKED_BY_SHIELD, Math.round(f2 * 10.0F)); - } - } - - if (entity1 instanceof EntityPlayer) { - CriterionTriggers.g.a((EntityPlayer) entity1, this, damagesource, f1, f, flag); - } - - return flag2; - } - } - - protected void shieldBlock(EntityLiving entityliving) { - entityliving.e(this); - } - - protected void e(EntityLiving entityliving) { - entityliving.a(this, 0.5F, entityliving.locX - this.locX, entityliving.locZ - this.locZ); - } - - private boolean f(DamageSource damagesource) { - if (damagesource.ignoresInvulnerability()) { - return false; - } else { - ItemStack itemstack = null; - EnumHand[] aenumhand = EnumHand.values(); - int i = aenumhand.length; - - // CraftBukkit start - ItemStack itemstack1 = ItemStack.a; - for (int j = 0; j < i; ++j) { - EnumHand enumhand = aenumhand[j]; - itemstack1 = this.b(enumhand); - - if (itemstack1.getItem() == Items.TOTEM_OF_UNDYING) { - itemstack = itemstack1.cloneItemStack(); - // itemstack1.subtract(1); // CraftBukkit - break; - } - } - - EntityResurrectEvent event = new EntityResurrectEvent((LivingEntity) this.getBukkitEntity()); - event.setCancelled(itemstack == null); - this.world.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - if (!itemstack1.isEmpty()) { - itemstack1.subtract(1); - } - if (itemstack != null && this instanceof EntityPlayer) { - // CraftBukkit end - EntityPlayer entityplayer = (EntityPlayer) this; - - entityplayer.b(StatisticList.ITEM_USED.b(Items.TOTEM_OF_UNDYING)); - CriterionTriggers.B.a(entityplayer, itemstack); - } - - this.setHealth(1.0F); - // CraftBukkit start - this.removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.TOTEM); - this.addEffect(new MobEffect(MobEffects.REGENERATION, 900, 1), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.TOTEM); - this.addEffect(new MobEffect(MobEffects.ABSORBTION, 100, 1), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.TOTEM); - // CraftBukkit end - this.world.broadcastEntityEffect(this, (byte) 35); - } - - return !event.isCancelled(); - } - } - - @Nullable - public DamageSource cE() { - if (this.world.getTime() - this.bI > 40L) { - this.bH = null; - } - - return this.bH; - } - - protected void c(DamageSource damagesource) { - SoundEffect soundeffect = this.getSoundHurt(damagesource); - - if (soundeffect != null) { - this.a(soundeffect, this.getSoundVolume(), this.cV()); - } - - } - - private boolean applyBlockingModifier(DamageSource damagesource) { - Entity entity = damagesource.j(); - boolean flag = false; - - if (entity instanceof EntityArrow) { - EntityArrow entityarrow = (EntityArrow) entity; - - if (entityarrow.getPierceLevel() > 0) { - flag = true; - } - } - - if (!damagesource.ignoresArmor() && this.isBlocking() && !flag) { - Vec3D vec3d = damagesource.w(); - - if (vec3d != null) { - Vec3D vec3d1 = this.f(1.0F); - Vec3D vec3d2 = vec3d.a(new Vec3D(this.locX, this.locY, this.locZ)).d(); - - vec3d2 = new Vec3D(vec3d2.x, 0.0D, vec3d2.z); - if (vec3d2.b(vec3d1) < 0.0D) { - return true; - } - } - } - - return false; - } - - public void die(DamageSource damagesource) { - if (!this.killed) { - Entity entity = damagesource.getEntity(); - EntityLiving entityliving = this.getKillingEntity(); - - /* // Paper - move down to make death event cancellable - if (this.aY >= 0 && entityliving != null) { - entityliving.a(this, this.aY, damagesource); - } - - if (entity != null) { - entity.b(this); - } - - if (this.isSleeping()) { - this.dy(); - } - */ // Paper - - this.killed = true; - //this.getCombatTracker().g(); - if (!this.world.isClientSide) { - org.bukkit.event.entity.EntityDeathEvent deathEvent = this.d(damagesource); - if (deathEvent == null || !deathEvent.isCancelled()) { - if (this.getKillCount() >= 0 && entityliving != null) { - entityliving.runKillTrigger(this, this.getKillCount(), damagesource); - } - if (entity != null) { - entity.onKill(this); - } - if (this.isSleeping()) { - this.dy(); - } - this.getCombatTracker().reset(); - } else { - this.killed = false; - this.setHealth((float) deathEvent.getReviveHealth()); - } - // Paper end - - boolean flag = false; - - if (this.killed && entityliving instanceof EntityWither) { - if (this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - BlockPosition blockposition = new BlockPosition(this.locX, this.locY, this.locZ); - IBlockData iblockdata = Blocks.WITHER_ROSE.getBlockData(); - - if (this.world.getType(blockposition).isAir() && iblockdata.canPlace(this.world, blockposition)) { - this.world.setTypeAndData(blockposition, iblockdata, 3); - flag = true; - } - } - - if (!flag) { - EntityItem entityitem = new EntityItem(this.world, this.locX, this.locY, this.locZ, new ItemStack(Items.bg)); - - this.world.addEntity(entityitem); - } - } - } - - if (this.killed) { // Paper - this.world.broadcastEntityEffect(this, (byte) 3); - this.setPose(EntityPose.DYING); - } // Paper - } - } - - protected org.bukkit.event.entity.EntityDeathEvent processDeath(DamageSource damagesource) { return d(damagesource); } // Paper - OBFHELPER - protected org.bukkit.event.entity.EntityDeathEvent d(DamageSource damagesource) { // Paper - Entity entity = damagesource.getEntity(); - int i; - - if (entity instanceof EntityHuman) { - i = EnchantmentManager.g((EntityLiving) entity); - } else { - i = 0; - } - - boolean flag = this.lastDamageByPlayerTime > 0; - - this.cF(); // CraftBukkit - from below // PAIL - org.bukkit.event.entity.EntityDeathEvent deathEvent; // Paper - if (this.isDropExperience() && this.world.getGameRules().getBoolean(GameRules.DO_MOB_LOOT)) { - this.a(damagesource, flag); - this.dropDeathLoot(damagesource, i, flag); - // CraftBukkit start - Call death event - deathEvent = CraftEventFactory.callEntityDeathEvent(this, this.drops); // Paper - } else { - deathEvent = CraftEventFactory.callEntityDeathEvent(this); // Paper - // CraftBukkit end - } - this.postDeathDropItems(deathEvent); // Paper - this.drops = new ArrayList<>(); // Paper - - return deathEvent; // Paper - } - - protected void cF() {} - protected void postDeathDropItems(org.bukkit.event.entity.EntityDeathEvent event) {} // Paper - method for post death logic that cannot be ran before the event is potentially cancelled - - protected void dropDeathLoot(DamageSource damagesource, int i, boolean flag) {} - - public MinecraftKey cG() { - return this.getEntityType().h(); - } - - protected void a(DamageSource damagesource, boolean flag) { - MinecraftKey minecraftkey = this.cG(); - LootTable loottable = this.world.getMinecraftServer().getLootTableRegistry().getLootTable(minecraftkey); - LootTableInfo.Builder loottableinfo_builder = this.a(flag, damagesource); - - loottable.populateLoot(loottableinfo_builder.build(LootContextParameterSets.ENTITY), this::a); - } - - protected LootTableInfo.Builder a(boolean flag, DamageSource damagesource) { - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder((WorldServer) this.world)).a(this.random).set(LootContextParameters.THIS_ENTITY, this).set(LootContextParameters.POSITION, new BlockPosition(this)).set(LootContextParameters.DAMAGE_SOURCE, damagesource).setOptional(LootContextParameters.KILLER_ENTITY, damagesource.getEntity()).setOptional(LootContextParameters.DIRECT_KILLER_ENTITY, damagesource.j()); - - if (flag && this.killer != null) { - loottableinfo_builder = loottableinfo_builder.set(LootContextParameters.LAST_DAMAGE_PLAYER, this.killer).a(this.killer.eb()); - } - - return loottableinfo_builder; - } - - public void a(Entity entity, float f, double d0, double d1) { - if (this.random.nextDouble() >= this.getAttributeInstance(GenericAttributes.KNOCKBACK_RESISTANCE).getValue()) { - this.impulse = true; - Vec3D vec3d = this.getMot(); - Vec3D vec3d1 = (new Vec3D(d0, 0.0D, d1)).d().a((double) f); - - this.setMot(vec3d.x / 2.0D - vec3d1.x, this.onGround ? Math.min(0.4D, vec3d.y / 2.0D + (double) f) : vec3d.y, vec3d.z / 2.0D - vec3d1.z); - - // Paper start - call EntityKnockbackByEntityEvent - Vec3D currentMot = this.getMot(); - org.bukkit.util.Vector delta = new org.bukkit.util.Vector(currentMot.x - vec3d.x, currentMot.y - vec3d.y, currentMot.z - vec3d.z); - // Restore old velocity to be able to access it in the event - this.setMot(vec3d); - if (entity == null || new com.destroystokyo.paper.event.entity.EntityKnockbackByEntityEvent((LivingEntity) getBukkitEntity(), entity.getBukkitEntity(), f, delta).callEvent()) { - this.setMot(vec3d.x + delta.getX(), vec3d.y + delta.getY(), vec3d.z + delta.getZ()); - } - // Paper end - } - } - - @Nullable - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_GENERIC_HURT; - } - - public final SoundEffect getDeathSoundEffect() { return this.getSoundDeath(); } // Paper - OBFHELPER - @Nullable - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_GENERIC_DEATH; - } - - protected SoundEffect getSoundFall(int i) { - return i > 4 ? SoundEffects.ENTITY_GENERIC_BIG_FALL : SoundEffects.ENTITY_GENERIC_SMALL_FALL; - } - - protected SoundEffect c(ItemStack itemstack) { - return SoundEffects.ENTITY_GENERIC_DRINK; - } - - public SoundEffect d(ItemStack itemstack) { - return SoundEffects.ENTITY_GENERIC_EAT; - } - - public boolean isClimbing() { - if (this.isSpectator()) { - return false; - } else { - IBlockData iblockdata = this.cI(); - Block block = iblockdata.getBlock(); - - return block != Blocks.LADDER && block != Blocks.VINE && block != Blocks.SCAFFOLDING ? block instanceof BlockTrapdoor && this.b(new BlockPosition(this), iblockdata) : true; - } - } - - public IBlockData cI() { - return this.world.getType(new BlockPosition(this)); - } - - private boolean b(BlockPosition blockposition, IBlockData iblockdata) { - if ((Boolean) iblockdata.get(BlockTrapdoor.OPEN)) { - IBlockData iblockdata1 = this.world.getType(blockposition.down()); - - if (iblockdata1.getBlock() == Blocks.LADDER && iblockdata1.get(BlockLadder.FACING) == iblockdata.get(BlockTrapdoor.FACING)) { - return true; - } - } - - return false; - } - - @Override - public boolean isAlive() { - return !this.dead && this.getHealth() > 0.0F; - } - - @Override - public void b(float f, float f1) { - super.b(f, f1); - MobEffect mobeffect = this.getEffect(MobEffects.JUMP); - float f2 = mobeffect == null ? 0.0F : (float) (mobeffect.getAmplifier() + 1); - int i = MathHelper.f((f - 3.0F - f2) * f1); - - if (i > 0) { - // CraftBukkit start - if (!this.damageEntity(DamageSource.FALL, (float) i)) { - return; - } - // CraftBukkit end - this.a(this.getSoundFall(i), 1.0F, 1.0F); - // this.damageEntity(DamageSource.FALL, (float) i); // CraftBukkit - moved up - int j = MathHelper.floor(this.locX); - int k = MathHelper.floor(this.locY - 0.20000000298023224D); - int l = MathHelper.floor(this.locZ); - IBlockData iblockdata = this.world.getType(new BlockPosition(j, k, l)); - - if (!iblockdata.isAir()) { - SoundEffectType soundeffecttype = iblockdata.r(); - - this.a(soundeffecttype.g(), soundeffecttype.a() * 0.5F, soundeffecttype.b() * 0.75F); - } - } - - } - - public int getArmorStrength() { - AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.ARMOR); - - return MathHelper.floor(attributeinstance.getValue()); - } - - protected void damageArmor(float f) {} - - protected void damageShield(float f) {} - - protected float applyArmorModifier(DamageSource damagesource, float f) { - if (!damagesource.ignoresArmor()) { - // this.damageArmor(f); // CraftBukkit - Moved into damageEntity0(DamageSource, float) - f = CombatMath.a(f, (float) this.getArmorStrength(), (float) this.getAttributeInstance(GenericAttributes.ARMOR_TOUGHNESS).getValue()); - } - - return f; - } - - protected float applyMagicModifier(DamageSource damagesource, float f) { - if (damagesource.isStarvation()) { - return f; - } else { - int i; - - // CraftBukkit - Moved to damageEntity0(DamageSource, float) - if (false && this.hasEffect(MobEffects.RESISTANCE) && damagesource != DamageSource.OUT_OF_WORLD) { - i = (this.getEffect(MobEffects.RESISTANCE).getAmplifier() + 1) * 5; - int j = 25 - i; - float f1 = f * (float) j; - float f2 = f; - - f = Math.max(f1 / 25.0F, 0.0F); - float f3 = f2 - f; - - if (f3 > 0.0F && f3 < 3.4028235E37F) { - if (this instanceof EntityPlayer) { - ((EntityPlayer) this).a(StatisticList.DAMAGE_RESISTED, Math.round(f3 * 10.0F)); - } else if (damagesource.getEntity() instanceof EntityPlayer) { - ((EntityPlayer) damagesource.getEntity()).a(StatisticList.DAMAGE_DEALT_RESISTED, Math.round(f3 * 10.0F)); - } - } - } - - if (f <= 0.0F) { - return 0.0F; - } else { - i = EnchantmentManager.a(this.getArmorItems(), damagesource); - if (i > 0) { - f = CombatMath.a(f, (float) i); - } - - return f; - } - } - } - - // CraftBukkit start - protected boolean damageEntity0(final DamageSource damagesource, float f) { // void -> boolean, add final - if (!this.isInvulnerable(damagesource)) { - final boolean human = this instanceof EntityHuman; - float originalDamage = f; - Function hardHat = new Function() { - @Override - public Double apply(Double f) { - if ((damagesource == DamageSource.ANVIL || damagesource == DamageSource.FALLING_BLOCK) && !EntityLiving.this.getEquipment(EnumItemSlot.HEAD).isEmpty()) { - return -(f - (f * 0.75F)); - - } - return -0.0; - } - }; - float hardHatModifier = hardHat.apply((double) f).floatValue(); - f += hardHatModifier; - - Function blocking = new Function() { - @Override - public Double apply(Double f) { - return -((EntityLiving.this.applyBlockingModifier(damagesource)) ? f : 0.0); - } - }; - float blockingModifier = blocking.apply((double) f).floatValue(); - f += blockingModifier; - - Function armor = new Function() { - @Override - public Double apply(Double f) { - return -(f - EntityLiving.this.applyArmorModifier(damagesource, f.floatValue())); - } - }; - float armorModifier = armor.apply((double) f).floatValue(); - f += armorModifier; - - Function resistance = new Function() { - @Override - public Double apply(Double f) { - if (!damagesource.isStarvation() && EntityLiving.this.hasEffect(MobEffects.RESISTANCE) && damagesource != DamageSource.OUT_OF_WORLD) { - int i = (EntityLiving.this.getEffect(MobEffects.RESISTANCE).getAmplifier() + 1) * 5; - int j = 25 - i; - float f1 = f.floatValue() * (float) j; - return -(f - (f1 / 25.0F)); - } - return -0.0; - } - }; - float resistanceModifier = resistance.apply((double) f).floatValue(); - f += resistanceModifier; - - Function magic = new Function() { - @Override - public Double apply(Double f) { - return -(f - EntityLiving.this.applyMagicModifier(damagesource, f.floatValue())); - } - }; - float magicModifier = magic.apply((double) f).floatValue(); - f += magicModifier; - - Function absorption = new Function() { - @Override - public Double apply(Double f) { - return -(Math.max(f - Math.max(f - EntityLiving.this.getAbsorptionHearts(), 0.0F), 0.0F)); - } - }; - 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); - if (event.isCancelled()) { - return false; - } - - f = (float) event.getFinalDamage(); - - // Resistance - if (event.getDamage(DamageModifier.RESISTANCE) < 0) { - float f3 = (float) -event.getDamage(DamageModifier.RESISTANCE); - if (f3 > 0.0F && f3 < 3.4028235E37F) { - if (this instanceof EntityPlayer) { - ((EntityPlayer) this).a(StatisticList.DAMAGE_RESISTED, Math.round(f3 * 10.0F)); - } else if (damagesource.getEntity() instanceof EntityPlayer) { - ((EntityPlayer) damagesource.getEntity()).a(StatisticList.DAMAGE_DEALT_RESISTED, Math.round(f3 * 10.0F)); - } - } - } - - // Apply damage to helmet - if ((damagesource == DamageSource.ANVIL || damagesource == DamageSource.FALLING_BLOCK) && this.getEquipment(EnumItemSlot.HEAD) != null) { - this.getEquipment(EnumItemSlot.HEAD).damage((int) (event.getDamage() * 4.0F + this.random.nextFloat() * event.getDamage() * 2.0F), this, (entityliving) -> { - entityliving.c(EnumItemSlot.HEAD); - }); - } - - // Apply damage to armor - if (!damagesource.ignoresArmor()) { - float armorDamage = (float) (event.getDamage() + event.getDamage(DamageModifier.BLOCKING) + event.getDamage(DamageModifier.HARD_HAT)); - this.damageArmor(armorDamage); - } - - // Apply blocking code // PAIL: steal from above - if (event.getDamage(DamageModifier.BLOCKING) < 0) { - this.world.broadcastEntityEffect(this, (byte) 29); // SPIGOT-4635 - shield damage sound - this.damageShield((float) -event.getDamage(DamageModifier.BLOCKING)); - Entity entity = damagesource.j(); - - if (entity instanceof EntityLiving) { - this.shieldBlock((EntityLiving) entity); - } - } - - absorptionModifier = (float) -event.getDamage(DamageModifier.ABSORPTION); - this.setAbsorptionHearts(Math.max(this.getAbsorptionHearts() - absorptionModifier, 0.0F)); - float f2 = absorptionModifier; - - if (f2 > 0.0F && f2 < 3.4028235E37F && this instanceof EntityHuman) { - ((EntityHuman) this).a(StatisticList.DAMAGE_ABSORBED, Math.round(f2 * 10.0F)); - } - if (f2 > 0.0F && f2 < 3.4028235E37F && damagesource.getEntity() instanceof EntityPlayer) { - ((EntityPlayer) damagesource.getEntity()).a(StatisticList.DAMAGE_DEALT_ABSORBED, Math.round(f2 * 10.0F)); - } - - if (f > 0 || !human) { - if (human) { - // PAIL: Be sure to drag all this code from the EntityHuman subclass each update. - ((EntityHuman) this).applyExhaustion(damagesource.getExhaustionCost()); - if (f < 3.4028235E37F) { - ((EntityHuman) this).a(StatisticList.DAMAGE_TAKEN, Math.round(f * 10.0F)); - } - } - // CraftBukkit end - float f3 = this.getHealth(); - - this.setHealth(f3 - f); - this.getCombatTracker().trackDamage(damagesource, f3, f); - // CraftBukkit start - if (!human) { - this.setAbsorptionHearts(this.getAbsorptionHearts() - f); - } - - return true; - } else { - // Duplicate triggers if blocking - if (event.getDamage(DamageModifier.BLOCKING) < 0) { - if (this instanceof EntityPlayer) { - CriterionTriggers.h.a((EntityPlayer) this, damagesource, f, originalDamage, true); - f2 = (float) -event.getDamage(DamageModifier.BLOCKING); - if (f2 > 0.0F && f2 < 3.4028235E37F) { - ((EntityPlayer) this).a(StatisticList.DAMAGE_BLOCKED_BY_SHIELD, Math.round(originalDamage * 10.0F)); - } - } - - if (damagesource.getEntity() instanceof EntityPlayer) { - CriterionTriggers.g.a((EntityPlayer) damagesource.getEntity(), this, damagesource, f, originalDamage, true); - } - - return false; - } else { - return originalDamage > 0; - } - // CraftBukkit end - } - } - return false; // CraftBukkit - } - - public CombatTracker getCombatTracker() { - return this.combatTracker; - } - - @Nullable - public EntityLiving getKillingEntity() { - return (EntityLiving) (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.MAX_HEALTH).getValue(); - } - - public final int getArrowCount() { - return (Integer) this.datawatcher.get(EntityLiving.g); - } - - public final void setArrowCount(int i) { - this.datawatcher.set(EntityLiving.g, i); - } - - private int l() { - return MobEffectUtil.a(this) ? 6 - (1 + MobEffectUtil.b(this)) : (this.hasEffect(MobEffects.SLOWER_DIG) ? 6 + (1 + this.getEffect(MobEffects.SLOWER_DIG).getAmplifier()) * 2 : 6); - } - - public void a(EnumHand enumhand) { - if (!this.at || this.av >= this.l() / 2 || this.av < 0) { - this.av = -1; - this.at = true; - this.au = enumhand; - if (this.world instanceof WorldServer) { - ((WorldServer) this.world).getChunkProvider().broadcast(this, new PacketPlayOutAnimation(this, enumhand == EnumHand.MAIN_HAND ? 0 : 3)); - } - } - - } - - @Override - protected void af() { - this.damageEntity(DamageSource.OUT_OF_WORLD, 4.0F); - } - - protected void cO() { - int i = this.l(); - - if (this.at) { - ++this.av; - if (this.av >= i) { - this.av = 0; - this.at = false; - } - } else { - this.av = 0; - } - - this.aC = (float) this.av / (float) i; - } - - public AttributeInstance getAttributeInstance(IAttribute iattribute) { - return this.getAttributeMap().a(iattribute); - } - - public AttributeMapBase getAttributeMap() { - if (this.attributeMap == null) { - this.attributeMap = new AttributeMapServer(); - this.craftAttributes = new CraftAttributeMap(attributeMap); // CraftBukkit - } - - return this.attributeMap; - } - - public EnumMonsterType getMonsterType() { - return EnumMonsterType.UNDEFINED; - } - - public ItemStack getItemInMainHand() { - return this.getEquipment(EnumItemSlot.MAINHAND); - } - - public ItemStack getItemInOffHand() { - return this.getEquipment(EnumItemSlot.OFFHAND); - } - - public ItemStack b(EnumHand enumhand) { - if (enumhand == EnumHand.MAIN_HAND) { - return this.getEquipment(EnumItemSlot.MAINHAND); - } else if (enumhand == EnumHand.OFF_HAND) { - return this.getEquipment(EnumItemSlot.OFFHAND); - } else { - throw new IllegalArgumentException("Invalid hand " + enumhand); - } - } - - public void a(EnumHand enumhand, ItemStack itemstack) { - if (enumhand == EnumHand.MAIN_HAND) { - this.setSlot(EnumItemSlot.MAINHAND, itemstack); - } else { - if (enumhand != EnumHand.OFF_HAND) { - throw new IllegalArgumentException("Invalid hand " + enumhand); - } - - this.setSlot(EnumItemSlot.OFFHAND, itemstack); - } - - } - - public boolean a(EnumItemSlot enumitemslot) { - return !this.getEquipment(enumitemslot).isEmpty(); - } - - @Override - public abstract Iterable getArmorItems(); - - public abstract ItemStack getEquipment(EnumItemSlot enumitemslot); - - public abstract void setSlot(EnumItemSlot enumitemslot, ItemStack itemstack); - - public float cT() { - Iterable iterable = this.getArmorItems(); - int i = 0; - int j = 0; - - for (Iterator iterator = iterable.iterator(); iterator.hasNext(); ++i) { - ItemStack itemstack = (ItemStack) iterator.next(); - - if (!itemstack.isEmpty()) { - ++j; - } - } - - return i > 0 ? (float) j / (float) i : 0.0F; - } - - @Override - public void setSprinting(boolean flag) { - super.setSprinting(flag); - AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); - - if (attributeinstance.a(EntityLiving.b) != null) { - attributeinstance.removeModifier(EntityLiving.c); - } - - if (flag) { - attributeinstance.addModifier(EntityLiving.c); - } - - } - - public final float getDeathSoundVolume() { return this.getSoundVolume(); } // Paper - OBFHELPER - protected float getSoundVolume() { - return 1.0F; - } - - public float getSoundPitch() { return cV();} // Paper - OBFHELPER - protected float cV() { - return this.isBaby() ? (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.5F : (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F; - } - - protected boolean isFrozen() { - return this.getHealth() <= 0.0F; - } - - @Override - public void collide(Entity entity) { - if (!this.isSleeping()) { - super.collide(entity); - } - - } - - public void B(Entity entity) { - double d0; - - if (!(entity instanceof EntityBoat) && !(entity instanceof EntityHorseAbstract)) { - double d1 = entity.locX; - double d2 = entity.getBoundingBox().minY + (double) entity.getHeight(); - - d0 = entity.locZ; - EnumDirection enumdirection = entity.getAdjustedDirection(); - - if (enumdirection != null) { - EnumDirection enumdirection1 = enumdirection.e(); - int[][] aint = new int[][]{{0, 1}, {0, -1}, {-1, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 0}, {1, 0}, {0, 1}}; - double d3 = Math.floor(this.locX) + 0.5D; - double d4 = Math.floor(this.locZ) + 0.5D; - double d5 = this.getBoundingBox().maxX - this.getBoundingBox().minX; - double d6 = this.getBoundingBox().maxZ - this.getBoundingBox().minZ; - AxisAlignedBB axisalignedbb = new AxisAlignedBB(d3 - d5 / 2.0D, entity.getBoundingBox().minY, d4 - d6 / 2.0D, d3 + d5 / 2.0D, Math.floor(entity.getBoundingBox().minY) + (double) this.getHeight(), d4 + d6 / 2.0D); - int[][] aint1 = aint; - int i = aint.length; - - for (int j = 0; j < i; ++j) { - int[] aint2 = aint1[j]; - double d7 = (double) (enumdirection.getAdjacentX() * aint2[0] + enumdirection1.getAdjacentX() * aint2[1]); - double d8 = (double) (enumdirection.getAdjacentZ() * aint2[0] + enumdirection1.getAdjacentZ() * aint2[1]); - double d9 = d3 + d7; - double d10 = d4 + d8; - AxisAlignedBB axisalignedbb1 = axisalignedbb.d(d7, 0.0D, d8); - BlockPosition blockposition; - - if (this.world.getCubes(this, axisalignedbb1)) { - blockposition = new BlockPosition(d9, this.locY, d10); - if (this.world.getType(blockposition).a((IBlockAccess) this.world, blockposition, (Entity) this)) { - this.enderTeleportTo(d9, this.locY + 1.0D, d10); - return; - } - - BlockPosition blockposition1 = new BlockPosition(d9, this.locY - 1.0D, d10); - - if (this.world.getType(blockposition1).a((IBlockAccess) this.world, blockposition1, (Entity) this) || this.world.getFluid(blockposition1).a(TagsFluid.WATER)) { - d1 = d9; - d2 = this.locY + 1.0D; - d0 = d10; - } - } else { - blockposition = new BlockPosition(d9, this.locY + 1.0D, d10); - if (this.world.getCubes(this, axisalignedbb1.d(0.0D, 1.0D, 0.0D)) && this.world.getType(blockposition).a((IBlockAccess) this.world, blockposition, (Entity) this)) { - d1 = d9; - d2 = this.locY + 2.0D; - d0 = d10; - } - } - } - } - - this.enderTeleportTo(d1, d2, d0); - } else { - double d11 = (double) (this.getWidth() / 2.0F + entity.getWidth() / 2.0F) + 0.4D; - float f; - - if (entity instanceof EntityBoat) { - f = 0.0F; - } else { - f = 1.5707964F * (float) (this.getMainHand() == EnumMainHand.RIGHT ? -1 : 1); - } - - float f1 = -MathHelper.sin(-this.yaw * 0.017453292F - 3.1415927F + f); - float f2 = -MathHelper.cos(-this.yaw * 0.017453292F - 3.1415927F + f); - - d0 = Math.abs(f1) > Math.abs(f2) ? d11 / (double) Math.abs(f1) : d11 / (double) Math.abs(f2); - double d12 = this.locX + (double) f1 * d0; - double d13 = this.locZ + (double) f2 * d0; - - this.setPosition(d12, entity.locY + (double) entity.getHeight() + 0.001D, d13); - if (!this.world.getCubes(this, this.getBoundingBox().b(entity.getBoundingBox()))) { - this.setPosition(d12, entity.locY + (double) entity.getHeight() + 1.001D, d13); - if (!this.world.getCubes(this, this.getBoundingBox().b(entity.getBoundingBox()))) { - this.setPosition(entity.locX, entity.locY + (double) this.getHeight() + 0.001D, entity.locZ); - } - } - } - } - - protected float cX() { - return 0.42F; - } - - protected void jump() { - float f; - - if (this.hasEffect(MobEffects.JUMP)) { - f = this.cX() + 0.1F * (float) (this.getEffect(MobEffects.JUMP).getAmplifier() + 1); - } else { - f = this.cX(); - } - - Vec3D vec3d = this.getMot(); - - this.setMot(vec3d.x, (double) f, vec3d.z); - if (this.isSprinting()) { - float f1 = this.yaw * 0.017453292F; - - this.setMot(this.getMot().add((double) (-MathHelper.sin(f1) * 0.2F), 0.0D, (double) (MathHelper.cos(f1) * 0.2F))); - } - - this.impulse = true; - } - - protected void c(Tag tag) { - this.setMot(this.getMot().add(0.0D, 0.03999999910593033D, 0.0D)); - } - - protected float da() { - return 0.8F; - } - - public void e(Vec3D vec3d) { - double d0; - float f; - - if (this.df() || this.ca()) { - d0 = 0.08D; - boolean flag = this.getMot().y <= 0.0D; - - if (flag && this.hasEffect(MobEffects.SLOW_FALLING)) { - d0 = 0.01D; - this.fallDistance = 0.0F; - } - - double d1; - float f1; - double d2; - - if (this.isInWater() && (!(this instanceof EntityHuman) || !((EntityHuman) this).abilities.isFlying)) { - d1 = this.locY; - f1 = this.isSprinting() ? 0.9F : this.da(); - f = 0.02F; - float f2 = (float) EnchantmentManager.e(this); - - if (f2 > 3.0F) { - f2 = 3.0F; - } - - if (!this.onGround) { - f2 *= 0.5F; - } - - if (f2 > 0.0F) { - f1 += (0.54600006F - f1) * f2 / 3.0F; - f += (this.db() - f) * f2 / 3.0F; - } - - if (this.hasEffect(MobEffects.DOLPHINS_GRACE)) { - f1 = 0.96F; - } - - this.a(f, vec3d); - this.move(EnumMoveType.SELF, this.getMot()); - Vec3D vec3d1 = this.getMot(); - - if (this.positionChanged && this.isClimbing()) { - vec3d1 = new Vec3D(vec3d1.x, 0.2D, vec3d1.z); - } - - this.setMot(vec3d1.d((double) f1, 0.800000011920929D, (double) f1)); - Vec3D vec3d2; - - if (!this.isNoGravity() && !this.isSprinting()) { - vec3d2 = this.getMot(); - if (flag && Math.abs(vec3d2.y - 0.005D) >= 0.003D && Math.abs(vec3d2.y - d0 / 16.0D) < 0.003D) { - d2 = -0.003D; - } else { - d2 = vec3d2.y - d0 / 16.0D; - } - - this.setMot(vec3d2.x, d2, vec3d2.z); - } - - vec3d2 = this.getMot(); - if (this.positionChanged && this.d(vec3d2.x, vec3d2.y + 0.6000000238418579D - this.locY + d1, vec3d2.z)) { - this.setMot(vec3d2.x, 0.30000001192092896D, vec3d2.z); - } - } else if (this.aD() && (!(this instanceof EntityHuman) || !((EntityHuman) this).abilities.isFlying)) { - d1 = this.locY; - this.a(0.02F, vec3d); - this.move(EnumMoveType.SELF, this.getMot()); - this.setMot(this.getMot().a(0.5D)); - if (!this.isNoGravity()) { - this.setMot(this.getMot().add(0.0D, -d0 / 4.0D, 0.0D)); - } - - Vec3D vec3d3 = this.getMot(); - - if (this.positionChanged && this.d(vec3d3.x, vec3d3.y + 0.6000000238418579D - this.locY + d1, vec3d3.z)) { - this.setMot(vec3d3.x, 0.30000001192092896D, vec3d3.z); - } - } else if (this.isGliding()) { - Vec3D vec3d4 = this.getMot(); - - if (vec3d4.y > -0.5D) { - this.fallDistance = 1.0F; - } - - Vec3D vec3d5 = this.getLookDirection(); - - f1 = this.pitch * 0.017453292F; - double d3 = Math.sqrt(vec3d5.x * vec3d5.x + vec3d5.z * vec3d5.z); - double d4 = Math.sqrt(b(vec3d4)); - - d2 = vec3d5.f(); - float f3 = MathHelper.cos(f1); - - f3 = (float) ((double) f3 * (double) f3 * Math.min(1.0D, d2 / 0.4D)); - vec3d4 = this.getMot().add(0.0D, d0 * (-1.0D + (double) f3 * 0.75D), 0.0D); - double d5; - - if (vec3d4.y < 0.0D && d3 > 0.0D) { - d5 = vec3d4.y * -0.1D * (double) f3; - vec3d4 = vec3d4.add(vec3d5.x * d5 / d3, d5, vec3d5.z * d5 / d3); - } - - if (f1 < 0.0F && d3 > 0.0D) { - d5 = d4 * (double) (-MathHelper.sin(f1)) * 0.04D; - vec3d4 = vec3d4.add(-vec3d5.x * d5 / d3, d5 * 3.2D, -vec3d5.z * d5 / d3); - } - - if (d3 > 0.0D) { - vec3d4 = vec3d4.add((vec3d5.x / d3 * d4 - vec3d4.x) * 0.1D, 0.0D, (vec3d5.z / d3 * d4 - vec3d4.z) * 0.1D); - } - - this.setMot(vec3d4.d(0.9900000095367432D, 0.9800000190734863D, 0.9900000095367432D)); - this.move(EnumMoveType.SELF, this.getMot()); - if (this.positionChanged && !this.world.isClientSide) { - d5 = Math.sqrt(b(this.getMot())); - double d6 = d4 - d5; - float f4 = (float) (d6 * 10.0D - 3.0D); - - if (f4 > 0.0F) { - this.a(this.getSoundFall((int) f4), 1.0F, 1.0F); - this.damageEntity(DamageSource.FLY_INTO_WALL, f4); - } - } - - if (this.onGround && !this.world.isClientSide) { - if (getFlag(7) && !CraftEventFactory.callToggleGlideEvent(this, false).isCancelled()) // CraftBukkit - this.setFlag(7, false); - } - } else { - BlockPosition blockposition = new BlockPosition(this.locX, this.getBoundingBox().minY - 1.0D, this.locZ); - float f5 = this.world.getType(blockposition).getBlock().m(); - - f1 = this.onGround ? f5 * 0.91F : 0.91F; - this.a(this.r(f5), vec3d); - this.setMot(this.f(this.getMot())); - this.move(EnumMoveType.SELF, this.getMot()); - Vec3D vec3d6 = this.getMot(); - - if ((this.positionChanged || this.jumping) && this.isClimbing()) { - vec3d6 = new Vec3D(vec3d6.x, 0.2D, vec3d6.z); - } - - double d7 = vec3d6.y; - - if (this.hasEffect(MobEffects.LEVITATION)) { - d7 += (0.05D * (double) (this.getEffect(MobEffects.LEVITATION).getAmplifier() + 1) - vec3d6.y) * 0.2D; - this.fallDistance = 0.0F; - } else if (this.world.isClientSide && !this.world.isLoaded(blockposition)) { - if (this.locY > 0.0D) { - d7 = -0.1D; - } else { - d7 = 0.0D; - } - } else if (!this.isNoGravity()) { - d7 -= d0; - } - - this.setMot(vec3d6.x * (double) f1, d7 * 0.9800000190734863D, vec3d6.z * (double) f1); - } - } - - this.aE = this.aF; - d0 = this.locX - this.lastX; - double d8 = this.locZ - this.lastZ; - double d9 = this instanceof EntityBird ? this.locY - this.lastY : 0.0D; - - f = MathHelper.sqrt(d0 * d0 + d9 * d9 + d8 * d8) * 4.0F; - if (f > 1.0F) { - f = 1.0F; - } - - this.aF += (f - this.aF) * 0.4F; - this.aG += this.aF; - } - - private Vec3D f(Vec3D vec3d) { - if (this.isClimbing()) { - this.fallDistance = 0.0F; - float f = 0.15F; - double d0 = MathHelper.a(vec3d.x, -0.15000000596046448D, 0.15000000596046448D); - double d1 = MathHelper.a(vec3d.z, -0.15000000596046448D, 0.15000000596046448D); - double d2 = Math.max(vec3d.y, -0.15000000596046448D); - - if (d2 < 0.0D && this.cI().getBlock() != Blocks.SCAFFOLDING && this.isSneaking() && this instanceof EntityHuman) { - d2 = 0.0D; - } - - vec3d = new Vec3D(d0, d2, d1); - } - - return vec3d; - } - - private float r(float f) { - return this.onGround ? this.db() * (0.21600002F / (f * f * f)) : this.aO; - } - - public float db() { - return this.bD; - } - - public void o(float f) { - this.bD = f; - } - - public boolean C(Entity entity) { - this.z(entity); - return false; - } - - @Override - public void tick() { - super.tick(); - this.o(); - this.p(); - if (!this.world.isClientSide) { - int i = this.getArrowCount(); - - if (i > 0) { - if (this.aw <= 0) { - this.aw = 20 * (30 - i); - } - - --this.aw; - if (this.aw <= 0) { - this.setArrowCount(i - 1); - } - } - - updateEntityEquipment(); // Paper - split into own method - - if (this.ticksLived % 20 == 0) { - this.getCombatTracker().g(); - } - - if (!this.glowing) { - boolean flag = this.hasEffect(MobEffects.GLOWING); - - if (this.getFlag(6) != flag) { - this.setFlag(6, flag); - } - } - - if (this.isSleeping() && !this.r()) { - this.dy(); - } - } - - this.movementTick(); - double d0 = this.locX - this.lastX; - double d1 = this.locZ - this.lastZ; - float f = (float) (d0 * d0 + d1 * d1); - float f1 = this.aK; - float f2 = 0.0F; - - this.aT = this.aU; - float f3 = 0.0F; - - if (f > 0.0025000002F) { - f3 = 1.0F; - f2 = (float) Math.sqrt((double) f) * 3.0F; - float f4 = (float) MathHelper.d(d1, d0) * 57.295776F - 90.0F; - float f5 = MathHelper.e(MathHelper.g(this.yaw) - f4); - - if (95.0F < f5 && f5 < 265.0F) { - f1 = f4 - 180.0F; - } else { - f1 = f4; - } - } - - if (this.aC > 0.0F) { - f1 = this.yaw; - } - - if (!this.onGround) { - f3 = 0.0F; - } - - this.aU += (f3 - this.aU) * 0.3F; - this.world.getMethodProfiler().enter("headTurn"); - f2 = this.e(f1, f2); - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("rangeChecks"); - - while (this.yaw - this.lastYaw < -180.0F) { - this.lastYaw -= 360.0F; - } - - while (this.yaw - this.lastYaw >= 180.0F) { - this.lastYaw += 360.0F; - } - - while (this.aK - this.aL < -180.0F) { - this.aL -= 360.0F; - } - - while (this.aK - this.aL >= 180.0F) { - this.aL += 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.aM - this.aN < -180.0F) { - this.aN -= 360.0F; - } - - while (this.aM - this.aN >= 180.0F) { - this.aN += 360.0F; - } - - this.world.getMethodProfiler().exit(); - this.aV += f2; - if (this.isGliding()) { - ++this.bp; - } else { - this.bp = 0; - } - - if (this.isSleeping()) { - this.pitch = 0.0F; - } - } - - // Paper start - split into own method from above - public void updateEntityEquipment() { - EnumItemSlot[] aenumitemslot = EnumItemSlot.values(); - int j = aenumitemslot.length; - - for (int k = 0; k < j; ++k) { - EnumItemSlot enumitemslot = aenumitemslot[k]; - ItemStack itemstack; - - switch (enumitemslot.a()) { - case HAND: - itemstack = (ItemStack) this.bw.get(enumitemslot.b()); - break; - case ARMOR: - itemstack = (ItemStack) this.bx.get(enumitemslot.b()); - break; - default: - continue; - } - - ItemStack itemstack1 = this.getEquipment(enumitemslot); - - if (!ItemStack.matches(itemstack1, itemstack)) { - // Paper start - PlayerArmorChangeEvent - if (this instanceof EntityPlayer && enumitemslot.getType() == EnumItemSlot.Function.ARMOR) { - final org.bukkit.inventory.ItemStack oldItem = CraftItemStack.asBukkitCopy(itemstack); - final org.bukkit.inventory.ItemStack newItem = CraftItemStack.asBukkitCopy(itemstack1); - new PlayerArmorChangeEvent((Player) this.getBukkitEntity(), PlayerArmorChangeEvent.SlotType.valueOf(enumitemslot.name()), oldItem, newItem).callEvent(); - } - // Paper end - ((WorldServer) this.world).getChunkProvider().broadcast(this, new PacketPlayOutEntityEquipment(this.getId(), enumitemslot, itemstack1)); - if (!itemstack.isEmpty()) { - this.getAttributeMap().a(itemstack.a(enumitemslot)); - } - - if (!itemstack1.isEmpty()) { - this.getAttributeMap().b(itemstack1.a(enumitemslot)); - } - - switch (enumitemslot.a()) { - case HAND: - this.bw.set(enumitemslot.b(), itemstack1.isEmpty() ? ItemStack.a : itemstack1.cloneItemStack()); - break; - case ARMOR: - this.bx.set(enumitemslot.b(), itemstack1.isEmpty() ? ItemStack.a : itemstack1.cloneItemStack()); - } - } - } - } - // Paper end - - protected float e(float f, float f1) { - float f2 = MathHelper.g(f - this.aK); - - this.aK += f2 * 0.3F; - float f3 = MathHelper.g(this.yaw - this.aK); - boolean flag = f3 < -90.0F || f3 >= 90.0F; - - if (f3 < -75.0F) { - f3 = -75.0F; - } - - if (f3 >= 75.0F) { - f3 = 75.0F; - } - - this.aK = this.yaw - f3; - if (f3 * f3 > 2500.0F) { - this.aK += f3 * 0.2F; - } - - if (flag) { - f1 *= -1.0F; - } - - return f1; - } - - public void movementTick() { - if (this.jumpTicks > 0) { - --this.jumpTicks; - } - - if (this.bf > 0 && !this.ca()) { - double d0 = this.locX + (this.bg - this.locX) / (double) this.bf; - double d1 = this.locY + (this.bh - this.locY) / (double) this.bf; - double d2 = this.locZ + (this.bi - this.locZ) / (double) this.bf; - double d3 = MathHelper.g(this.bj - (double) this.yaw); - - this.yaw = (float) ((double) this.yaw + d3 / (double) this.bf); - this.pitch = (float) ((double) this.pitch + (this.bk - (double) this.pitch) / (double) this.bf); - --this.bf; - this.setPosition(d0, d1, d2); - this.setYawPitch(this.yaw, this.pitch); - } else if (!this.df()) { - this.setMot(this.getMot().a(0.98D)); - } - - if (this.bm > 0) { - this.aM = (float) ((double) this.aM + MathHelper.g(this.bl - (double) this.aM) / (double) this.bm); - --this.bm; - } - - Vec3D vec3d = this.getMot(); - double d4 = vec3d.x; - double d5 = vec3d.y; - double d6 = vec3d.z; - - if (Math.abs(vec3d.x) < 0.003D) { - d4 = 0.0D; - } - - if (Math.abs(vec3d.y) < 0.003D) { - d5 = 0.0D; - } - - if (Math.abs(vec3d.z) < 0.003D) { - d6 = 0.0D; - } - - this.setMot(d4, d5, d6); - this.world.getMethodProfiler().enter("ai"); - if (this.isFrozen()) { - this.jumping = false; - this.bb = 0.0F; - this.bd = 0.0F; - this.be = 0.0F; - } else if (this.df()) { - this.world.getMethodProfiler().enter("newAi"); - this.doTick(); - this.world.getMethodProfiler().exit(); - } - - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("jump"); - if (this.jumping) { - if (this.Q > 0.0D && (!this.onGround || this.Q > 0.4D)) { - this.c(TagsFluid.WATER); - } else if (this.aD()) { - this.c(TagsFluid.LAVA); - } else if ((this.onGround || this.Q > 0.0D && this.Q <= 0.4D) && this.jumpTicks == 0) { - this.jump(); - this.jumpTicks = 10; - } - } else { - this.jumpTicks = 0; - } - - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("travel"); - this.bb *= 0.98F; - this.bd *= 0.98F; - this.be *= 0.9F; - this.n(); - AxisAlignedBB axisalignedbb = this.getBoundingBox(); - - this.e(new Vec3D((double) this.bb, (double) this.bc, (double) this.bd)); - this.world.getMethodProfiler().exit(); - this.world.getMethodProfiler().enter("push"); - if (this.bq > 0) { - --this.bq; - this.a(axisalignedbb, this.getBoundingBox()); - } - - this.collideNearby(); - this.world.getMethodProfiler().exit(); - } - - private void n() { - boolean flag = this.getFlag(7); - - if (flag && !this.onGround && !this.isPassenger()) { - ItemStack itemstack = this.getEquipment(EnumItemSlot.CHEST); - - if (itemstack.getItem() == Items.ELYTRA && ItemElytra.e(itemstack)) { - flag = true; - if (!this.world.isClientSide && (this.bp + 1) % 20 == 0) { - itemstack.damage(1, this, (entityliving) -> { - entityliving.c(EnumItemSlot.CHEST); - }); - } - } else { - flag = false; - } - } else { - flag = false; - } - - if (!this.world.isClientSide) { - if (flag != this.getFlag(7) && !CraftEventFactory.callToggleGlideEvent(this, flag).isCancelled()) // CraftBukkit - this.setFlag(7, flag); - } - - } - - protected void doTick() {} - - protected void collideNearby() { - List list = this.world.getEntities(this, this.getBoundingBox(), IEntitySelector.a(this)); - - if (!list.isEmpty()) { - int i = this.world.getGameRules().getInt(GameRules.MAX_ENTITY_CRAMMING); - int j; - - if (i > 0 && list.size() > i - 1 && this.random.nextInt(4) == 0) { - j = 0; - - for (int k = 0; k < list.size(); ++k) { - if (!((Entity) list.get(k)).isPassenger()) { - ++j; - } - } - - if (j > i - 1) { - this.damageEntity(DamageSource.CRAMMING, 6.0F); - } - } - - numCollisions = Math.max(0, numCollisions - world.paperConfig.maxCollisionsPerEntity); // Paper - for (j = 0; j < list.size() && numCollisions < world.paperConfig.maxCollisionsPerEntity; ++j) { // Paper - Entity entity = (Entity) list.get(j); - entity.numCollisions++; // Paper - numCollisions++; // Paper - - this.D(entity); - } - } - - } - - protected void a(AxisAlignedBB axisalignedbb, AxisAlignedBB axisalignedbb1) { - AxisAlignedBB axisalignedbb2 = axisalignedbb.b(axisalignedbb1); - List list = this.world.getEntities(this, axisalignedbb2); - - if (!list.isEmpty()) { - for (int i = 0; i < list.size(); ++i) { - Entity entity = (Entity) list.get(i); - - if (entity instanceof EntityLiving) { - this.f((EntityLiving) entity); - this.bq = 0; - this.setMot(this.getMot().a(-0.2D)); - break; - } - } - } else if (this.positionChanged) { - this.bq = 0; - } - - if (!this.world.isClientSide && this.bq <= 0) { - this.c(4, false); - } - - } - - protected void D(Entity entity) { - entity.collide(this); - } - - protected void f(EntityLiving entityliving) {} - - public void q(int i) { - this.bq = i; - if (!this.world.isClientSide) { - this.c(4, true); - } - - } - - public boolean isRiptiding() { - return ((Byte) this.datawatcher.get(EntityLiving.ar) & 4) != 0; - } - - // Paper start - @Override public void stopRiding() { stopRiding(false); } - @Override public void stopRiding(boolean suppressCancellation) { - // Paper end - Entity entity = this.getVehicle(); - - super.stopRiding(suppressCancellation); // Paper - suppress - if (entity != null && entity != this.getVehicle() && !this.world.isClientSide) { - this.B(entity); - } - - } - - @Override - public void passengerTick() { - super.passengerTick(); - this.aT = this.aU; - this.aU = 0.0F; - this.fallDistance = 0.0F; - } - - public void setJumping(boolean flag) { - this.jumping = flag; - } - - public void receive(Entity entity, int i) { - if (!entity.dead && !this.world.isClientSide && (entity instanceof EntityItem || entity instanceof EntityArrow || entity instanceof EntityExperienceOrb)) { - ((WorldServer) this.world).getChunkProvider().broadcast(entity, new PacketPlayOutCollect(entity.getId(), this.getId(), i)); - } - - } - - public boolean hasLineOfSight(Entity entity) { - Vec3D vec3d = new Vec3D(this.locX, this.locY + (double) this.getHeadHeight(), this.locZ); - Vec3D vec3d1 = new Vec3D(entity.locX, entity.locY + (double) entity.getHeadHeight(), entity.locZ); - - return this.world.rayTrace(new RayTrace(vec3d, vec3d1, RayTrace.BlockCollisionOption.COLLIDER, RayTrace.FluidCollisionOption.NONE, this)).getType() == MovingObjectPosition.EnumMovingObjectType.MISS; - } - - @Override - public float h(float f) { - return f == 1.0F ? this.aM : MathHelper.g(f, this.aN, this.aM); - } - - public boolean df() { - return !this.world.isClientSide; - } - - @Override - public boolean isInteractable() { - return !this.dead && this.collides; // CraftBukkit - } - - @Override - public boolean isCollidable() { - return this.isAlive() && !this.isClimbing() && this.collides; // CraftBukkit - } - - @Override - protected void velocityChanged() { - this.velocityChanged = this.random.nextDouble() >= this.getAttributeInstance(GenericAttributes.KNOCKBACK_RESISTANCE).getValue(); - } - - @Override - public float getHeadRotation() { - return this.aM; - } - - @Override - public void setHeadRotation(float f) { - this.aM = f; - } - - @Override - public void l(float f) { - this.aK = f; - } - - public float getAbsorptionHearts() { - return this.bF; - } - - public void setAbsorptionHearts(float f) { - if (f < 0.0F || Float.isNaN(f)) { // Paper - f = 0.0F; - } - - this.bF = f; - } - - public void enterCombat() {} - - public void exitCombat() {} - - protected void dh() { - this.updateEffects = true; - } - - public abstract EnumMainHand getMainHand(); - - public boolean isHandRaised() { - return ((Byte) this.datawatcher.get(EntityLiving.ar) & 1) > 0; - } - - public EnumHand getRaisedHand() { - return ((Byte) this.datawatcher.get(EntityLiving.ar) & 2) > 0 ? EnumHand.OFF_HAND : EnumHand.MAIN_HAND; - } - - private void o() { - if (this.isHandRaised()) { - if (ItemStack.d(this.b(this.getRaisedHand()), this.activeItem)) { - this.activeItem.b(this.world, this, this.dm()); - if (this.dm() <= 25 && this.dm() % 4 == 0) { - this.b(this.activeItem, 5); - } - - if (--this.bo == 0 && !this.world.isClientSide && !this.activeItem.m()) { - this.q(); - } - } else { - this.dp(); - } - } - - } - - private void p() { - this.bK = this.bJ; - if (this.bk()) { - this.bJ = Math.min(1.0F, this.bJ + 0.09F); - } else { - this.bJ = Math.max(0.0F, this.bJ - 0.09F); - } - - } - - protected void c(int i, boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityLiving.ar); - int j; - - if (flag) { - j = b0 | i; - } else { - j = b0 & ~i; - } - - this.datawatcher.set(EntityLiving.ar, (byte) j); - } - - // Paper start -- OBFHELPER and forwarder to method with forceUpdate parameter - public void c(EnumHand enumhand) { this.updateActiveItem(enumhand, false); } - public void updateActiveItem(EnumHand enumhand, boolean forceUpdate) { - // Paper end - ItemStack itemstack = this.b(enumhand); - - if (!itemstack.isEmpty() && !this.isHandRaised() || forceUpdate) { // Paper use override flag - this.activeItem = itemstack; - this.bo = itemstack.k(); - if (!this.world.isClientSide) { - this.c(1, true); - this.c(2, enumhand == EnumHand.OFF_HAND); - } - - } - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - super.a(datawatcherobject); - if (EntityLiving.bs.equals(datawatcherobject)) { - if (this.world.isClientSide) { - this.getBedPosition().ifPresent(this::a); - } - } else if (EntityLiving.ar.equals(datawatcherobject) && this.world.isClientSide) { - if (this.isHandRaised() && this.activeItem.isEmpty()) { - this.activeItem = this.b(this.getRaisedHand()); - if (!this.activeItem.isEmpty()) { - this.bo = this.activeItem.k(); - } - } else if (!this.isHandRaised() && !this.activeItem.isEmpty()) { - this.activeItem = ItemStack.a; - this.bo = 0; - } - } - - } - - @Override - public void a(ArgumentAnchor.Anchor argumentanchor_anchor, Vec3D vec3d) { - super.a(argumentanchor_anchor, vec3d); - this.aN = this.aM; - this.aK = this.aM; - this.aL = this.aK; - } - - protected void b(ItemStack itemstack, int i) { - if (!itemstack.isEmpty() && this.isHandRaised()) { - if (itemstack.l() == EnumAnimation.DRINK) { - this.a(this.c(itemstack), 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); - } - - if (itemstack.l() == EnumAnimation.EAT) { - this.a(itemstack, i); - this.a(this.d(itemstack), 0.5F + 0.5F * (float) this.random.nextInt(2), (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F); - } - - } - } - - private void a(ItemStack itemstack, int i) { - for (int j = 0; j < i; ++j) { - Vec3D vec3d = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); - - vec3d = vec3d.a(-this.pitch * 0.017453292F); - vec3d = vec3d.b(-this.yaw * 0.017453292F); - double d0 = (double) (-this.random.nextFloat()) * 0.6D - 0.3D; - Vec3D vec3d1 = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); - - vec3d1 = vec3d1.a(-this.pitch * 0.017453292F); - vec3d1 = vec3d1.b(-this.yaw * 0.017453292F); - vec3d1 = vec3d1.add(this.locX, this.locY + (double) this.getHeadHeight(), this.locZ); - this.world.addParticle(new ParticleParamItem(Particles.ITEM, itemstack), vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z); - } - - } - - protected void q() { - if (!this.activeItem.isEmpty() && this.isHandRaised()) { - this.updateActiveItem(this.getRaisedHand(), true); // Paper - PlayerItemConsumeEvent event = null; // Paper - this.b(this.activeItem, 16); - // CraftBukkit start - fire PlayerItemConsumeEvent - ItemStack itemstack; - if (this instanceof EntityPlayer) { - org.bukkit.inventory.ItemStack craftItem = CraftItemStack.asBukkitCopy(this.activeItem); - event = new PlayerItemConsumeEvent((Player) this.getBukkitEntity(), craftItem); // Paper - world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - // Update client - ((EntityPlayer) this).getBukkitEntity().updateInventory(); - ((EntityPlayer) this).getBukkitEntity().updateScaledHealth(); - return; - } - - itemstack = (craftItem.equals(event.getItem())) ? this.activeItem.a(this.world, this) : CraftItemStack.asNMSCopy(event.getItem()).a(world, this); - } else { - itemstack = this.activeItem.a(this.world, this); - } - - // Paper start - save the default replacement item and change it if necessary - final ItemStack defaultReplacement = itemstack; - if (event != null && event.getReplacement() != null) { - itemstack = CraftItemStack.asNMSCopy(event.getReplacement()); - } - // Paper end - this.a(this.getRaisedHand(), itemstack); - // CraftBukkit end - this.dp(); - // Paper start - if (this instanceof EntityPlayer) { - ((EntityPlayer) this).getBukkitEntity().updateInventory(); - } - // Paper end - } - - } - - public ItemStack dl() { - return this.activeItem; - } - - public int getItemUseRemainingTime() { return this.dm(); } // Paper - OBFHELPER - public int dm() { - return this.bo; - } - - public int getHandRaisedTime() { return this.dn(); } // Paper - OBFHELPER - public int dn() { - return this.isHandRaised() ? this.activeItem.k() - this.dm() : 0; - } - - public void clearActiveItem() { - if (!this.activeItem.isEmpty()) { - this.activeItem.a(this.world, this, this.dm()); - if (this.activeItem.m()) { - this.o(); - } - } - - this.dp(); - } - - public void dp() { - if (!this.world.isClientSide) { - this.c(1, false); - } - - this.activeItem = ItemStack.a; - this.bo = 0; - } - - public boolean isBlocking() { - if (this.isHandRaised() && !this.activeItem.isEmpty()) { - Item item = this.activeItem.getItem(); - - return item.e_(this.activeItem) != EnumAnimation.BLOCK ? false : item.f_(this.activeItem) - this.bo >= getShieldBlockingDelay(); // Paper - shieldBlockingDelay - } else { - return false; - } - } - - public boolean isGliding() { - return this.getFlag(7); - } - - @Override - public boolean bk() { - return super.bk() || !this.isGliding() && this.getPose() == EntityPose.FALL_FLYING; - } - - public boolean a(double d0, double d1, double d2, boolean flag) { - double d3 = this.locX; - double d4 = this.locY; - double d5 = this.locZ; - - this.locX = d0; - this.locY = d1; - this.locZ = d2; - boolean flag1 = false; - BlockPosition blockposition = new BlockPosition(this); - World world = this.world; - - if (world.isLoaded(blockposition)) { - boolean flag2 = false; - - while (!flag2 && blockposition.getY() > 0) { - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata = world.getType(blockposition1); - - if (iblockdata.getMaterial().isSolid()) { - flag2 = true; - } else { - --this.locY; - blockposition = blockposition1; - } - } - - if (flag2) { - // CraftBukkit start - Teleport event - // this.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()) { - Location to = teleport.getTo(); - this.enderTeleportTo(to.getX(), to.getY(), to.getZ()); - if (world.getCubes(this) && !world.containsLiquid(this.getBoundingBox())) { - flag1 = true; - } - } - // CraftBukkit end - } - } - - if (!flag1) { - this.enderTeleportTo(d3, d4, d5); - return false; - } else { - if (flag) { - world.broadcastEntityEffect(this, (byte) 46); - } - - if (this instanceof EntityCreature) { - ((EntityCreature) this).getNavigation().o(); - } - - return true; - } - } - - public boolean dt() { - return true; - } - - public boolean du() { - return true; - } - - public boolean e(ItemStack itemstack) { - return false; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntityLiving(this); - } - - @Override - public EntitySize a(EntityPose entitypose) { - return entitypose == EntityPose.SLEEPING ? EntityLiving.as : super.a(entitypose).a(this.cn()); - } - - public Optional getBedPosition() { - return (Optional) this.datawatcher.get(EntityLiving.bs); - } - - public void d(BlockPosition blockposition) { - this.datawatcher.set(EntityLiving.bs, Optional.of(blockposition)); - } - - public void dw() { - this.datawatcher.set(EntityLiving.bs, Optional.empty()); - } - - public boolean isSleeping() { - return this.getBedPosition().isPresent(); - } - - public void e(BlockPosition blockposition) { - if (this.isPassenger()) { - this.stopRiding(); - } - - IBlockData iblockdata = this.world.getType(blockposition); - - if (iblockdata.getBlock() instanceof BlockBed) { - this.world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockBed.OCCUPIED, true), 3); - } - - this.setPose(EntityPose.SLEEPING); - this.a(blockposition); - this.d(blockposition); - this.setMot(Vec3D.a); - this.impulse = true; - } - - private void a(BlockPosition blockposition) { - this.setPosition((double) blockposition.getX() + 0.5D, (double) ((float) blockposition.getY() + 0.6875F), (double) blockposition.getZ() + 0.5D); - } - - private boolean r() { - return (Boolean) this.getBedPosition().map((blockposition) -> { - return this.world.getType(blockposition).getBlock() instanceof BlockBed; - }).orElse(false); - } - - public void dy() { - Optional optional = this.getBedPosition(); // CraftBukkit - decompile error - World world = this.world; - - this.world.getClass(); - optional.filter(world::isLoaded).ifPresent((blockposition) -> { - IBlockData iblockdata = this.world.getType(blockposition); - - if (iblockdata.getBlock() instanceof BlockBed) { - this.world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockBed.OCCUPIED, false), 3); - Vec3D vec3d = (Vec3D) BlockBed.a(this.getEntityType(), (IWorldReader) this.world, blockposition, 0).orElseGet(() -> { - BlockPosition blockposition1 = blockposition.up(); - - return new Vec3D((double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 0.1D, (double) blockposition1.getZ() + 0.5D); - }); - - this.setPosition(vec3d.x, vec3d.y, vec3d.z); - } - - }); - this.setPose(EntityPose.STANDING); - this.dw(); - } - - @Override - public boolean inBlock() { - return !this.isSleeping() && super.inBlock(); - } - - @Override - protected final float getHeadHeight(EntityPose entitypose, EntitySize entitysize) { - return entitypose == EntityPose.SLEEPING ? 0.2F : this.b(entitypose, entitysize); - } - - protected float b(EntityPose entitypose, EntitySize entitysize) { - return super.getHeadHeight(entitypose, entitysize); - } - - public ItemStack f(ItemStack itemstack) { - return ItemStack.a; - } - - public ItemStack a(World world, ItemStack itemstack) { - if (itemstack.E()) { - world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, this.d(itemstack), SoundCategory.NEUTRAL, 1.0F, 1.0F + (world.random.nextFloat() - world.random.nextFloat()) * 0.4F); - this.a(itemstack, world, this); - itemstack.subtract(1); - } - - return itemstack; - } - - private void a(ItemStack itemstack, World world, EntityLiving entityliving) { - Item item = itemstack.getItem(); - - if (item.isFood()) { - List> list = item.getFoodInfo().f(); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Pair pair = (Pair) iterator.next(); - - if (!world.isClientSide && pair.getLeft() != null && world.random.nextFloat() < (Float) pair.getRight()) { - entityliving.addEffect(new MobEffect((MobEffect) pair.getLeft()), EntityPotionEffectEvent.Cause.FOOD); // CraftBukkit - } - } - } - - } - - private static byte d(EnumItemSlot enumitemslot) { - switch (enumitemslot) { - case MAINHAND: - return 47; - case OFFHAND: - return 48; - case HEAD: - return 49; - case CHEST: - return 50; - case FEET: - return 52; - case LEGS: - return 51; - default: - return 47; - } - } - - public void c(EnumItemSlot enumitemslot) { - this.world.broadcastEntityEffect(this, d(enumitemslot)); - } - - public void d(EnumHand enumhand) { - this.c(enumhand == EnumHand.MAIN_HAND ? EnumItemSlot.MAINHAND : EnumItemSlot.OFFHAND); - } - // Paper start - public MovingObjectPosition getRayTrace(int maxDistance) { - return getRayTrace(maxDistance, RayTrace.FluidCollisionOption.NONE); - } - - public MovingObjectPosition getRayTrace(int maxDistance, RayTrace.FluidCollisionOption fluidCollisionOption) { - if (maxDistance < 1 || maxDistance > 120) { - throw new IllegalArgumentException("maxDistance must be between 1-120"); - } - - Vec3D start = new Vec3D(locX, locY + getHeadHeight(), locZ); - org.bukkit.util.Vector dir = getBukkitEntity().getLocation().getDirection().multiply(maxDistance); - Vec3D end = new Vec3D(start.x + dir.getX(), start.y + dir.getY(), start.z + dir.getZ()); - RayTrace raytrace = new RayTrace(start, end, RayTrace.BlockCollisionOption.OUTLINE, fluidCollisionOption, this); - - return world.rayTrace(raytrace); - } - - public MovingObjectPositionEntity getTargetEntity(int maxDistance) { - if (maxDistance < 1 || maxDistance > 120) { - throw new IllegalArgumentException("maxDistance must be between 1-120"); - } - - Vec3D start = this.getEyePosition(1.0F); - Vec3D direction = this.getLookDirection(); - Vec3D end = start.add(direction.x * maxDistance, direction.y * maxDistance, direction.z * maxDistance); - - List entityList = world.getEntities(this, getBoundingBox().expand(direction.x * maxDistance, direction.y * maxDistance, direction.z * maxDistance).grow(1.0D, 1.0D, 1.0D), IEntitySelector.notSpectator().and(Entity::isInteractable)); - - double distance = 0.0D; - MovingObjectPositionEntity result = null; - - for (Entity entity : entityList) { - AxisAlignedBB aabb = entity.getBoundingBox().grow((double) entity.getCollisionBorderSize()); - Optional rayTraceResult = aabb.calculateIntercept(start, end); - - if (rayTraceResult.isPresent()) { - Vec3D rayTrace = rayTraceResult.get(); - double distanceTo = start.distanceSquared(rayTrace); - if (distanceTo < distance || distance == 0.0D) { - result = new MovingObjectPositionEntity(entity, rayTrace); - distance = distanceTo; - } - } - } - - return result; - } - - public int shieldBlockingDelay = world.paperConfig.shieldBlockingDelay; - - public int getShieldBlockingDelay() { - return shieldBlockingDelay; - } - - public void setShieldBlockingDelay(int shieldBlockingDelay) { - this.shieldBlockingDelay = shieldBlockingDelay; - } - // Paper end -} diff --git a/src/main/java/net/minecraft/server/EntityLlamaSpit.java b/src/main/java/net/minecraft/server/EntityLlamaSpit.java deleted file mode 100644 index 6c4ebd643..000000000 --- a/src/main/java/net/minecraft/server/EntityLlamaSpit.java +++ /dev/null @@ -1,151 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.UUID; - -public class EntityLlamaSpit extends Entity implements IProjectile { - - public EntityLiving shooter; // CraftBukkit - type - private NBTTagCompound c; - - public EntityLlamaSpit(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityLlamaSpit(World world, EntityLlama entityllama) { - this(EntityTypes.LLAMA_SPIT, world); - this.shooter = entityllama; - this.setPosition(entityllama.locX - (double) (entityllama.getWidth() + 1.0F) * 0.5D * (double) MathHelper.sin(entityllama.aK * 0.017453292F), entityllama.locY + (double) entityllama.getHeadHeight() - 0.10000000149011612D, entityllama.locZ + (double) (entityllama.getWidth() + 1.0F) * 0.5D * (double) MathHelper.cos(entityllama.aK * 0.017453292F)); - } - - @Override - public void tick() { - super.tick(); - if (this.c != null) { - this.f(); - } - - Vec3D vec3d = this.getMot(); - MovingObjectPosition movingobjectposition = ProjectileHelper.a(this, this.getBoundingBox().a(vec3d).g(1.0D), (entity) -> { - return !entity.isSpectator() && entity != this.shooter; - }, RayTrace.BlockCollisionOption.OUTLINE, true); - - if (movingobjectposition != null) { - this.a(movingobjectposition); - } - - this.locX += vec3d.x; - this.locY += vec3d.y; - this.locZ += vec3d.z; - float f = MathHelper.sqrt(b(vec3d)); - - this.yaw = (float) (MathHelper.d(vec3d.x, vec3d.z) * 57.2957763671875D); - - for (this.pitch = (float) (MathHelper.d(vec3d.y, (double) f) * 57.2957763671875D); 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 = MathHelper.g(0.2F, this.lastPitch, this.pitch); - this.yaw = MathHelper.g(0.2F, this.lastYaw, this.yaw); - float f1 = 0.99F; - float f2 = 0.06F; - - if (!this.world.a(this.getBoundingBox(), Material.AIR)) { - this.die(); - } else if (this.av()) { - this.die(); - } else { - this.setMot(vec3d.a(0.9900000095367432D)); - if (!this.isNoGravity()) { - this.setMot(this.getMot().add(0.0D, -0.05999999865889549D, 0.0D)); - } - - this.setPosition(this.locX, this.locY, this.locZ); - } - } - - @Override - public void shoot(double d0, double d1, double d2, float f, float f1) { - Vec3D vec3d = (new Vec3D(d0, d1, d2)).d().add(this.random.nextGaussian() * 0.007499999832361937D * (double) f1, this.random.nextGaussian() * 0.007499999832361937D * (double) f1, this.random.nextGaussian() * 0.007499999832361937D * (double) f1).a((double) f); - - this.setMot(vec3d); - float f2 = MathHelper.sqrt(b(vec3d)); - - this.yaw = (float) (MathHelper.d(vec3d.x, d2) * 57.2957763671875D); - this.pitch = (float) (MathHelper.d(vec3d.y, (double) f2) * 57.2957763671875D); - this.lastYaw = this.yaw; - this.lastPitch = this.pitch; - } - - public void a(MovingObjectPosition movingobjectposition) { - org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileHitEvent(this, movingobjectposition); // Craftbukkit - Call event - MovingObjectPosition.EnumMovingObjectType movingobjectposition_enummovingobjecttype = movingobjectposition.getType(); - - if (movingobjectposition_enummovingobjecttype == MovingObjectPosition.EnumMovingObjectType.ENTITY && this.shooter != null) { - ((MovingObjectPositionEntity) movingobjectposition).getEntity().damageEntity(DamageSource.a(this, (EntityLiving) this.shooter).c(), 1.0F); - } else if (movingobjectposition_enummovingobjecttype == MovingObjectPosition.EnumMovingObjectType.BLOCK && !this.world.isClientSide) { - this.die(); - } - - } - - @Override - protected void initDatawatcher() {} - - @Override - protected void a(NBTTagCompound nbttagcompound) { - if (nbttagcompound.hasKeyOfType("Owner", 10)) { - this.c = nbttagcompound.getCompound("Owner"); - } - - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - if (this.shooter != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - UUID uuid = this.shooter.getUniqueID(); - - nbttagcompound1.a("OwnerUUID", uuid); - nbttagcompound.set("Owner", nbttagcompound1); - } - - } - - private void f() { - if (this.c != null && this.c.b("OwnerUUID")) { - UUID uuid = this.c.a("OwnerUUID"); - List list = this.world.a(EntityLlama.class, this.getBoundingBox().g(15.0D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityLlama entityllama = (EntityLlama) iterator.next(); - - if (entityllama.getUniqueID().equals(uuid)) { - this.shooter = entityllama; - break; - } - } - } - - this.c = null; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntityLlamaTrader.java b/src/main/java/net/minecraft/server/EntityLlamaTrader.java deleted file mode 100644 index b60a167f8..000000000 --- a/src/main/java/net/minecraft/server/EntityLlamaTrader.java +++ /dev/null @@ -1,138 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import javax.annotation.Nullable; - -public class EntityLlamaTrader extends EntityLlama { - - private int bI = 47999; - - public EntityLlamaTrader(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected EntityLlama eF() { - return (EntityLlama) EntityTypes.TRADER_LLAMA.a(this.world); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("DespawnDelay", this.bI); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("DespawnDelay", 99)) { - this.bI = nbttagcompound.getInt("DespawnDelay"); - } - - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(1, new PathfinderGoalPanic(this, 2.0D)); - this.targetSelector.a(1, new EntityLlamaTrader.a(this)); - } - - @Override - protected void g(EntityHuman entityhuman) { - Entity entity = this.getLeashHolder(); - - if (!(entity instanceof EntityVillagerTrader)) { - super.g(entityhuman); - } - } - - @Override - public void movementTick() { - super.movementTick(); - if (!this.world.isClientSide) { - this.eK(); - } - - } - - private void eK() { - if (this.eL()) { - this.bI = this.eM() ? ((EntityVillagerTrader) this.getLeashHolder()).ef() - 1 : this.bI - 1; - if (this.bI <= 0) { - this.unleash(true, false); - this.die(); - } - - } - } - - private boolean eL() { - return !this.isTamed() && !this.eN() && !this.hasSinglePlayerPassenger(); - } - - private boolean eM() { - return this.getLeashHolder() instanceof EntityVillagerTrader; - } - - private boolean eN() { - return this.isLeashed() && !this.eM(); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - GroupDataEntity groupdataentity1 = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - - if (enummobspawn == EnumMobSpawn.EVENT) { - this.setAgeRaw(0); - } - - return groupdataentity1; - } - - public class a extends PathfinderGoalTarget { - - private final EntityLlama b; - private EntityLiving c; - private int d; - - public a(EntityLlama entityllama) { - super(entityllama, false); - this.b = entityllama; - this.a(EnumSet.of(PathfinderGoal.Type.TARGET)); - } - - @Override - public boolean a() { - if (!this.b.isLeashed()) { - return false; - } else { - Entity entity = this.b.getLeashHolder(); - - if (!(entity instanceof EntityVillagerTrader)) { - return false; - } else { - EntityVillagerTrader entityvillagertrader = (EntityVillagerTrader) entity; - - this.c = entityvillagertrader.getLastDamager(); - int i = entityvillagertrader.ct(); - - return i != this.d && this.a(this.c, PathfinderTargetCondition.a); - } - } - } - - @Override - public void c() { - this.e.setGoalTarget(this.c, org.bukkit.event.entity.EntityTargetEvent.TargetReason.TARGET_ATTACKED_OWNER, true); // CraftBukkit - Entity entity = this.b.getLeashHolder(); - - if (entity instanceof EntityVillagerTrader) { - this.d = ((EntityVillagerTrader) entity).ct(); - } - - super.c(); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityMinecartAbstract.java b/src/main/java/net/minecraft/server/EntityMinecartAbstract.java deleted file mode 100644 index 6df2930e2..000000000 --- a/src/main/java/net/minecraft/server/EntityMinecartAbstract.java +++ /dev/null @@ -1,780 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -// CraftBukkit start -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; -// CraftBukkit end - -public abstract class EntityMinecartAbstract extends Entity { - - private static final DataWatcherObject b = DataWatcher.a(EntityMinecartAbstract.class, DataWatcherRegistry.b); - private static final DataWatcherObject c = DataWatcher.a(EntityMinecartAbstract.class, DataWatcherRegistry.b); - private static final DataWatcherObject d = DataWatcher.a(EntityMinecartAbstract.class, DataWatcherRegistry.c); - private static final DataWatcherObject e = DataWatcher.a(EntityMinecartAbstract.class, DataWatcherRegistry.b); - private static final DataWatcherObject f = DataWatcher.a(EntityMinecartAbstract.class, DataWatcherRegistry.b); - private static final DataWatcherObject g = DataWatcher.a(EntityMinecartAbstract.class, DataWatcherRegistry.i); - private boolean ar; - private static final int[][][] as = new int[][][]{{{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}}}; - private int at; - private double au; - private double av; - private double aw; - private double ax; - private double ay; - - // 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.949999988079071D; // Paper - restore vanilla precision - private double flyingY = 0.949999988079071D; // Paper - restore vanilla precision - private double flyingZ = 0.949999988079071D; // Paper - restore vanilla precision - public double maxSpeed = 0.4D; - // CraftBukkit end - - protected EntityMinecartAbstract(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.i = true; - } - - protected EntityMinecartAbstract(EntityTypes entitytypes, World world, double d0, double d1, double d2) { - this(entitytypes, world); - this.setPosition(d0, d1, d2); - this.setMot(Vec3D.a); - this.lastX = d0; - this.lastY = d1; - this.lastZ = d2; - } - - public static EntityMinecartAbstract a(World world, double d0, double d1, double d2, EntityMinecartAbstract.EnumMinecartType entityminecartabstract_enumminecarttype) { - return (EntityMinecartAbstract) (entityminecartabstract_enumminecarttype == EntityMinecartAbstract.EnumMinecartType.CHEST ? new EntityMinecartChest(world, d0, d1, d2) : (entityminecartabstract_enumminecarttype == EntityMinecartAbstract.EnumMinecartType.FURNACE ? new EntityMinecartFurnace(world, d0, d1, d2) : (entityminecartabstract_enumminecarttype == EntityMinecartAbstract.EnumMinecartType.TNT ? new EntityMinecartTNT(world, d0, d1, d2) : (entityminecartabstract_enumminecarttype == EntityMinecartAbstract.EnumMinecartType.SPAWNER ? new EntityMinecartMobSpawner(world, d0, d1, d2) : (entityminecartabstract_enumminecarttype == EntityMinecartAbstract.EnumMinecartType.HOPPER ? new EntityMinecartHopper(world, d0, d1, d2) : (entityminecartabstract_enumminecarttype == EntityMinecartAbstract.EnumMinecartType.COMMAND_BLOCK ? new EntityMinecartCommandBlock(world, d0, d1, d2) : new EntityMinecartRideable(world, d0, d1, d2))))))); - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - protected void initDatawatcher() { - this.datawatcher.register(EntityMinecartAbstract.b, 0); - this.datawatcher.register(EntityMinecartAbstract.c, 1); - this.datawatcher.register(EntityMinecartAbstract.d, 0.0F); - this.datawatcher.register(EntityMinecartAbstract.e, Block.getCombinedId(Blocks.AIR.getBlockData())); - this.datawatcher.register(EntityMinecartAbstract.f, 6); - this.datawatcher.register(EntityMinecartAbstract.g, false); - } - - @Nullable - @Override - public AxisAlignedBB j(Entity entity) { - return entity.isCollidable() ? entity.getBoundingBox() : null; - } - - @Override - public boolean isCollidable() { - return true; - } - - @Override - public double aP() { - return 0.0D; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (!this.world.isClientSide && !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.d(-this.n()); - this.c(10); - this.velocityChanged(); - 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 - this.ejectPassengers(); - 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(GameRules.DO_ENTITY_DROPS)) { - ItemStack itemstack = new ItemStack(Items.MINECART); - - if (this.hasCustomName()) { - itemstack.a(this.getCustomName()); - } - - this.a(itemstack); - } - - } - - @Override - public boolean isInteractable() { - return !this.dead; - } - - @Override - public EnumDirection getAdjustedDirection() { - return this.ar ? this.getDirection().opposite().e() : this.getDirection().e(); - } - - @Override - public void tick() { - // 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.c(this.getType() - 1); - } - - if (this.getDamage() > 0.0F) { - this.setDamage(this.getDamage() - 1.0F); - } - - // Paper start - Configurable nether ceiling damage - // Extracted to own function - /* - if (this.locY < -64.0D) { - this.af(); - } - */ - this.performVoidDamage(); - // Paper end - - // this.doPortalTick(); // CraftBukkit - handled in postTick - if (this.world.isClientSide) { - if (this.at > 0) { - double d0 = this.locX + (this.au - this.locX) / (double) this.at; - double d1 = this.locY + (this.av - this.locY) / (double) this.at; - double d2 = this.locZ + (this.aw - this.locZ) / (double) this.at; - double d3 = MathHelper.g(this.ax - (double) this.yaw); - - this.yaw = (float) ((double) this.yaw + d3 / (double) this.at); - this.pitch = (float) ((double) this.pitch + (this.ay - (double) this.pitch) / (double) this.at); - --this.at; - this.setPosition(d0, d1, d2); - this.setYawPitch(this.yaw, this.pitch); - } else { - this.setPosition(this.locX, this.locY, this.locZ); - this.setYawPitch(this.yaw, this.pitch); - } - - } else { - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - if (!this.isNoGravity()) { - this.setMot(this.getMot().add(0.0D, -0.04D, 0.0D)); - } - - int i = MathHelper.floor(this.locX); - int j = MathHelper.floor(this.locY); - int k = MathHelper.floor(this.locZ); - - if (this.world.getType(new BlockPosition(i, j - 1, k)).a(TagsBlock.RAILS)) { - --j; - } - - BlockPosition blockposition = new BlockPosition(i, j, k); - IBlockData iblockdata = this.world.getType(blockposition); - - if (iblockdata.a(TagsBlock.RAILS)) { - this.b(blockposition, iblockdata); - if (iblockdata.getBlock() == Blocks.ACTIVATOR_RAIL) { - this.a(i, j, k, (Boolean) iblockdata.get(BlockPoweredRail.POWERED)); - } - } else { - this.i(); - } - - 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.d(d5, d4) * 180.0D / 3.141592653589793D); - if (this.ar) { - this.yaw += 180.0F; - } - } - - double d6 = (double) MathHelper.g(this.yaw - this.lastYaw); - - if (d6 < -170.0D || d6 >= 170.0D) { - this.yaw += 180.0F; - this.ar = !this.ar; - } - - 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 - if (this.getMinecartType() == EntityMinecartAbstract.EnumMinecartType.RIDEABLE && b(this.getMot()) > 0.01D) { - List list = this.world.getEntities(this, this.getBoundingBox().grow(0.20000000298023224D, 0.0D, 0.20000000298023224D), IEntitySelector.a(this)); - - if (!list.isEmpty()) { - for (int l = 0; l < list.size(); ++l) { - Entity entity = (Entity) list.get(l); - - if (!(entity instanceof EntityHuman) && !(entity instanceof EntityIronGolem) && !(entity instanceof EntityMinecartAbstract) && !this.isVehicle() && !entity.isPassenger()) { - // CraftBukkit start - VehicleEntityCollisionEvent collisionEvent = new VehicleEntityCollisionEvent(vehicle, entity.getBukkitEntity()); - this.world.getServer().getPluginManager().callEvent(collisionEvent); - - if (collisionEvent.isCancelled()) { - continue; - } - // CraftBukkit end - entity.startRiding(this); - } else { - // CraftBukkit start - VehicleEntityCollisionEvent collisionEvent = new VehicleEntityCollisionEvent(vehicle, entity.getBukkitEntity()); - this.world.getServer().getPluginManager().callEvent(collisionEvent); - - if (collisionEvent.isCancelled()) { - continue; - } - // CraftBukkit end - entity.collide(this); - } - } - } - } else { - Iterator iterator = this.world.getEntities(this, this.getBoundingBox().grow(0.20000000298023224D, 0.0D, 0.20000000298023224D)).iterator(); - - while (iterator.hasNext()) { - Entity entity1 = (Entity) iterator.next(); - - if (!this.w(entity1) && entity1.isCollidable() && entity1 instanceof EntityMinecartAbstract) { - // CraftBukkit start - VehicleEntityCollisionEvent collisionEvent = new VehicleEntityCollisionEvent(vehicle, entity1.getBukkitEntity()); - this.world.getServer().getPluginManager().callEvent(collisionEvent); - - if (collisionEvent.isCancelled()) { - continue; - } - // CraftBukkit end - entity1.collide(this); - } - } - } - - this.ay(); - } - } - - protected double getMaxSpeed() { - return this.maxSpeed; // CraftBukkit - } - - public void a(int i, int j, int k, boolean flag) {} - - protected void i() { - double d0 = this.getMaxSpeed(); - Vec3D vec3d = this.getMot(); - - this.setMot(MathHelper.a(vec3d.x, -d0, d0), vec3d.y, MathHelper.a(vec3d.z, -d0, d0)); - if (this.onGround) { - // CraftBukkit start - replace magic numbers with our variables - this.setMot(new Vec3D(this.getMot().x * this.derailedX, this.getMot().y * this.derailedY, this.getMot().z * this.derailedZ)); - // CraftBukkit end - } - - this.move(EnumMoveType.SELF, this.getMot()); - if (!this.onGround) { - // CraftBukkit start - replace magic numbers with our variables - this.setMot(new Vec3D(this.getMot().x * this.flyingX, this.getMot().y * this.flyingY, this.getMot().z * this.flyingZ)); - // CraftBukkit end - } - - } - - protected void b(BlockPosition blockposition, IBlockData iblockdata) { - this.fallDistance = 0.0F; - Vec3D vec3d = this.l(this.locX, this.locY, this.locZ); - - this.locY = (double) blockposition.getY(); - boolean flag = false; - boolean flag1 = false; - BlockMinecartTrackAbstract blockminecarttrackabstract = (BlockMinecartTrackAbstract) iblockdata.getBlock(); - - if (blockminecarttrackabstract == Blocks.POWERED_RAIL) { - flag = (Boolean) iblockdata.get(BlockPoweredRail.POWERED); - flag1 = !flag; - } - - double d0 = 0.0078125D; - Vec3D vec3d1 = this.getMot(); - BlockPropertyTrackPosition blockpropertytrackposition = (BlockPropertyTrackPosition) iblockdata.get(blockminecarttrackabstract.e()); - - switch (blockpropertytrackposition) { - case ASCENDING_EAST: - this.setMot(vec3d1.add(-0.0078125D, 0.0D, 0.0D)); - ++this.locY; - break; - case ASCENDING_WEST: - this.setMot(vec3d1.add(0.0078125D, 0.0D, 0.0D)); - ++this.locY; - break; - case ASCENDING_NORTH: - this.setMot(vec3d1.add(0.0D, 0.0D, 0.0078125D)); - ++this.locY; - break; - case ASCENDING_SOUTH: - this.setMot(vec3d1.add(0.0D, 0.0D, -0.0078125D)); - ++this.locY; - } - - vec3d1 = this.getMot(); - int[][] aint = EntityMinecartAbstract.as[blockpropertytrackposition.a()]; - double d1 = (double) (aint[1][0] - aint[0][0]); - double d2 = (double) (aint[1][2] - aint[0][2]); - double d3 = Math.sqrt(d1 * d1 + d2 * d2); - double d4 = vec3d1.x * d1 + vec3d1.z * d2; - - if (d4 < 0.0D) { - d1 = -d1; - d2 = -d2; - } - - double d5 = Math.min(2.0D, Math.sqrt(b(vec3d1))); - - vec3d1 = new Vec3D(d5 * d1 / d3, vec3d1.y, d5 * d2 / d3); - this.setMot(vec3d1); - Entity entity = this.getPassengers().isEmpty() ? null : (Entity) this.getPassengers().get(0); - - if (entity instanceof EntityHuman) { - Vec3D vec3d2 = entity.getMot(); - double d6 = b(vec3d2); - double d7 = b(this.getMot()); - - if (d6 > 1.0E-4D && d7 < 0.01D) { - this.setMot(this.getMot().add(vec3d2.x * 0.1D, 0.0D, vec3d2.z * 0.1D)); - flag1 = false; - } - } - - double d8; - - if (flag1) { - d8 = Math.sqrt(b(this.getMot())); - if (d8 < 0.03D) { - this.setMot(Vec3D.a); - } else { - this.setMot(this.getMot().d(0.5D, 0.0D, 0.5D)); - } - } - - d8 = (double) blockposition.getX() + 0.5D + (double) aint[0][0] * 0.5D; - double d9 = (double) blockposition.getZ() + 0.5D + (double) aint[0][2] * 0.5D; - double d10 = (double) blockposition.getX() + 0.5D + (double) aint[1][0] * 0.5D; - double d11 = (double) blockposition.getZ() + 0.5D + (double) aint[1][2] * 0.5D; - - d1 = d10 - d8; - d2 = d11 - d9; - double d12; - double d13; - double d14; - - if (d1 == 0.0D) { - this.locX = (double) blockposition.getX() + 0.5D; - d12 = this.locZ - (double) blockposition.getZ(); - } else if (d2 == 0.0D) { - this.locZ = (double) blockposition.getZ() + 0.5D; - d12 = this.locX - (double) blockposition.getX(); - } else { - d13 = this.locX - d8; - d14 = this.locZ - d9; - d12 = (d13 * d1 + d14 * d2) * 2.0D; - } - - this.locX = d8 + d1 * d12; - this.locZ = d9 + d2 * d12; - this.setPosition(this.locX, this.locY, this.locZ); - d13 = this.isVehicle() ? 0.75D : 1.0D; - d14 = this.getMaxSpeed(); - vec3d1 = this.getMot(); - this.move(EnumMoveType.SELF, new Vec3D(MathHelper.a(d13 * vec3d1.x, -d14, d14), 0.0D, MathHelper.a(d13 * vec3d1.z, -d14, d14))); - if (aint[0][1] != 0 && MathHelper.floor(this.locX) - blockposition.getX() == aint[0][0] && MathHelper.floor(this.locZ) - blockposition.getZ() == 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) - blockposition.getX() == aint[1][0] && MathHelper.floor(this.locZ) - blockposition.getZ() == aint[1][2]) { - this.setPosition(this.locX, this.locY + (double) aint[1][1], this.locZ); - } - - this.decelerate(); - Vec3D vec3d3 = this.l(this.locX, this.locY, this.locZ); - Vec3D vec3d4; - double d15; - - if (vec3d3 != null && vec3d != null) { - double d16 = (vec3d.y - vec3d3.y) * 0.05D; - - vec3d4 = this.getMot(); - d15 = Math.sqrt(b(vec3d4)); - if (d15 > 0.0D) { - this.setMot(vec3d4.d((d15 + d16) / d15, 1.0D, (d15 + d16) / d15)); - } - - this.setPosition(this.locX, vec3d3.y, this.locZ); - } - - int i = MathHelper.floor(this.locX); - int j = MathHelper.floor(this.locZ); - - if (i != blockposition.getX() || j != blockposition.getZ()) { - vec3d4 = this.getMot(); - d15 = Math.sqrt(b(vec3d4)); - this.setMot(d15 * (double) (i - blockposition.getX()), vec3d4.y, d15 * (double) (j - blockposition.getZ())); - } - - if (flag) { - vec3d4 = this.getMot(); - d15 = Math.sqrt(b(vec3d4)); - if (d15 > 0.01D) { - double d17 = 0.06D; - - this.setMot(vec3d4.add(vec3d4.x / d15 * 0.06D, 0.0D, vec3d4.z / d15 * 0.06D)); - } else { - Vec3D vec3d5 = this.getMot(); - double d18 = vec3d5.x; - double d19 = vec3d5.z; - - if (blockpropertytrackposition == BlockPropertyTrackPosition.EAST_WEST) { - if (this.a(blockposition.west())) { - d18 = 0.02D; - } else if (this.a(blockposition.east())) { - d18 = -0.02D; - } - } else { - if (blockpropertytrackposition != BlockPropertyTrackPosition.NORTH_SOUTH) { - return; - } - - if (this.a(blockposition.north())) { - d19 = 0.02D; - } else if (this.a(blockposition.south())) { - d19 = -0.02D; - } - } - - this.setMot(d18, vec3d5.y, d19); - } - } - - } - - private boolean a(BlockPosition blockposition) { - return this.world.getType(blockposition).isOccluding(this.world, blockposition); - } - - protected void decelerate() { - double d0 = this.isVehicle() || !this.slowWhenEmpty ? 0.997D : 0.96D; // CraftBukkit - add !this.slowWhenEmpty - - this.setMot(this.getMot().d(d0, 0.0D, d0)); - } - - @Nullable - public Vec3D l(double d0, double d1, double d2) { - int i = MathHelper.floor(d0); - int j = MathHelper.floor(d1); - int k = MathHelper.floor(d2); - - if (this.world.getType(new BlockPosition(i, j - 1, k)).a(TagsBlock.RAILS)) { - --j; - } - - IBlockData iblockdata = this.world.getType(new BlockPosition(i, j, k)); - - if (iblockdata.a(TagsBlock.RAILS)) { - BlockPropertyTrackPosition blockpropertytrackposition = (BlockPropertyTrackPosition) iblockdata.get(((BlockMinecartTrackAbstract) iblockdata.getBlock()).e()); - int[][] aint = EntityMinecartAbstract.as[blockpropertytrackposition.a()]; - double d3 = (double) i + 0.5D + (double) aint[0][0] * 0.5D; - double d4 = (double) j + 0.0625D + (double) aint[0][1] * 0.5D; - double d5 = (double) k + 0.5D + (double) aint[0][2] * 0.5D; - double d6 = (double) i + 0.5D + (double) aint[1][0] * 0.5D; - double d7 = (double) j + 0.0625D + (double) aint[1][1] * 0.5D; - double d8 = (double) k + 0.5D + (double) aint[1][2] * 0.5D; - double d9 = d6 - d3; - double d10 = (d7 - d4) * 2.0D; - double d11 = d8 - d5; - double d12; - - if (d9 == 0.0D) { - d12 = d2 - (double) k; - } else if (d11 == 0.0D) { - d12 = d0 - (double) i; - } else { - double d13 = d0 - d3; - double d14 = d2 - d5; - - d12 = (d13 * d9 + d14 * d11) * 2.0D; - } - - d0 = d3 + d9 * d12; - d1 = d4 + d10 * d12; - d2 = d5 + d11 * d12; - if (d10 < 0.0D) { - ++d1; - } - - if (d10 > 0.0D) { - d1 += 0.5D; - } - - return new Vec3D(d0, d1, d2); - } else { - return null; - } - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - if (nbttagcompound.getBoolean("CustomDisplayTile")) { - this.setDisplayBlock(GameProfileSerializer.d(nbttagcompound.getCompound("DisplayState"))); - this.setDisplayBlockOffset(nbttagcompound.getInt("DisplayOffset")); - } - - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - if (this.u()) { - nbttagcompound.setBoolean("CustomDisplayTile", true); - nbttagcompound.set("DisplayState", GameProfileSerializer.a(this.getDisplayBlock())); - nbttagcompound.setInt("DisplayOffset", this.getDisplayBlockOffset()); - } - - } - - @Override - public void collide(Entity entity) { - if (!this.world.isClientSide) { - if (!entity.noclip && !this.noclip) { - if (!this.w(entity)) { - // CraftBukkit start - VehicleEntityCollisionEvent collisionEvent = new VehicleEntityCollisionEvent((Vehicle) this.getBukkitEntity(), entity.getBukkitEntity()); - this.world.getServer().getPluginManager().callEvent(collisionEvent); - - if (collisionEvent.isCancelled()) { - return; - } - // CraftBukkit end - double d0 = entity.locX - this.locX; - double d1 = entity.locZ - this.locZ; - double d2 = d0 * d0 + d1 * d1; - - if (d2 >= 9.999999747378752E-5D) { - d2 = (double) 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 *= (double) (1.0F - this.M); - d1 *= (double) (1.0F - this.M); - 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)).d(); - Vec3D vec3d1 = (new Vec3D((double) MathHelper.cos(this.yaw * 0.017453292F), 0.0D, (double) MathHelper.sin(this.yaw * 0.017453292F))).d(); - double d6 = Math.abs(vec3d.b(vec3d1)); - - if (d6 < 0.800000011920929D) { - return; - } - - Vec3D vec3d2 = this.getMot(); - Vec3D vec3d3 = entity.getMot(); - - if (((EntityMinecartAbstract) entity).getMinecartType() == EntityMinecartAbstract.EnumMinecartType.FURNACE && this.getMinecartType() != EntityMinecartAbstract.EnumMinecartType.FURNACE) { - this.setMot(vec3d2.d(0.2D, 1.0D, 0.2D)); - this.f(vec3d3.x - d0, 0.0D, vec3d3.z - d1); - entity.setMot(vec3d3.d(0.95D, 1.0D, 0.95D)); - } else if (((EntityMinecartAbstract) entity).getMinecartType() != EntityMinecartAbstract.EnumMinecartType.FURNACE && this.getMinecartType() == EntityMinecartAbstract.EnumMinecartType.FURNACE) { - entity.setMot(vec3d3.d(0.2D, 1.0D, 0.2D)); - entity.f(vec3d2.x + d0, 0.0D, vec3d2.z + d1); - this.setMot(vec3d2.d(0.95D, 1.0D, 0.95D)); - } else { - double d7 = (vec3d3.x + vec3d2.x) / 2.0D; - double d8 = (vec3d3.z + vec3d2.z) / 2.0D; - - this.setMot(vec3d2.d(0.2D, 1.0D, 0.2D)); - this.f(d7 - d0, 0.0D, d8 - d1); - entity.setMot(vec3d3.d(0.2D, 1.0D, 0.2D)); - entity.f(d7 + d0, 0.0D, d8 + d1); - } - } else { - this.f(-d0, 0.0D, -d1); - entity.f(d0 / 4.0D, 0.0D, d1 / 4.0D); - } - } - - } - } - } - } - - public void setDamage(float f) { - this.datawatcher.set(EntityMinecartAbstract.d, f); - } - - public float getDamage() { - return (Float) this.datawatcher.get(EntityMinecartAbstract.d); - } - - public void c(int i) { - this.datawatcher.set(EntityMinecartAbstract.b, i); - } - - public int getType() { - return (Integer) this.datawatcher.get(EntityMinecartAbstract.b); - } - - public void d(int i) { - this.datawatcher.set(EntityMinecartAbstract.c, i); - } - - public int n() { - return (Integer) this.datawatcher.get(EntityMinecartAbstract.c); - } - - public abstract EntityMinecartAbstract.EnumMinecartType getMinecartType(); - - public IBlockData getDisplayBlock() { - return !this.u() ? this.q() : Block.getByCombinedId((Integer) this.getDataWatcher().get(EntityMinecartAbstract.e)); - } - - public IBlockData q() { - return Blocks.AIR.getBlockData(); - } - - public int getDisplayBlockOffset() { - return !this.u() ? this.s() : (Integer) this.getDataWatcher().get(EntityMinecartAbstract.f); - } - - public int s() { - return 6; - } - - public void setDisplayBlock(IBlockData iblockdata) { - this.getDataWatcher().set(EntityMinecartAbstract.e, Block.getCombinedId(iblockdata)); - this.a(true); - } - - public void setDisplayBlockOffset(int i) { - this.getDataWatcher().set(EntityMinecartAbstract.f, i); - this.a(true); - } - - public boolean u() { - return (Boolean) this.getDataWatcher().get(EntityMinecartAbstract.g); - } - - public void a(boolean flag) { - this.getDataWatcher().set(EntityMinecartAbstract.g, flag); - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } - - public static enum EnumMinecartType { - - RIDEABLE, CHEST, FURNACE, TNT, SPAWNER, HOPPER, COMMAND_BLOCK; - - private 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/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java b/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java deleted file mode 100644 index 9ef7eadeb..000000000 --- a/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java +++ /dev/null @@ -1,115 +0,0 @@ -package net.minecraft.server; - -public class EntityMinecartCommandBlock extends EntityMinecartAbstract { - - public static final DataWatcherObject COMMAND = DataWatcher.a(EntityMinecartCommandBlock.class, DataWatcherRegistry.d); - private static final DataWatcherObject c = DataWatcher.a(EntityMinecartCommandBlock.class, DataWatcherRegistry.e); - private final CommandBlockListenerAbstract d = new EntityMinecartCommandBlock.a(); - private int e; - - public EntityMinecartCommandBlock(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityMinecartCommandBlock(World world, double d0, double d1, double d2) { - super(EntityTypes.COMMAND_BLOCK_MINECART, world, d0, d1, d2); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.getDataWatcher().register(EntityMinecartCommandBlock.COMMAND, ""); - this.getDataWatcher().register(EntityMinecartCommandBlock.c, new ChatComponentText("")); - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.d.b(nbttagcompound); - this.getDataWatcher().set(EntityMinecartCommandBlock.COMMAND, this.getCommandBlock().getCommand()); - this.getDataWatcher().set(EntityMinecartCommandBlock.c, this.getCommandBlock().j()); - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - this.d.a(nbttagcompound); - } - - @Override - public EntityMinecartAbstract.EnumMinecartType getMinecartType() { - return EntityMinecartAbstract.EnumMinecartType.COMMAND_BLOCK; - } - - @Override - public IBlockData q() { - return Blocks.COMMAND_BLOCK.getBlockData(); - } - - public CommandBlockListenerAbstract getCommandBlock() { - return this.d; - } - - @Override - public void a(int i, int j, int k, boolean flag) { - if (flag && this.ticksLived - this.e >= 4) { - this.getCommandBlock().a(this.world); - this.e = this.ticksLived; - } - - } - - @Override - public boolean b(EntityHuman entityhuman, EnumHand enumhand) { - this.d.a(entityhuman); - return true; - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - super.a(datawatcherobject); - if (EntityMinecartCommandBlock.c.equals(datawatcherobject)) { - try { - this.d.c((IChatBaseComponent) this.getDataWatcher().get(EntityMinecartCommandBlock.c)); - } catch (Throwable throwable) { - ; - } - } else if (EntityMinecartCommandBlock.COMMAND.equals(datawatcherobject)) { - this.d.setCommand((String) this.getDataWatcher().get(EntityMinecartCommandBlock.COMMAND)); - } - - } - - @Override - public boolean bT() { - return true; - } - - public class a extends CommandBlockListenerAbstract { - - public a() {} - - @Override - public WorldServer d() { - return (WorldServer) EntityMinecartCommandBlock.this.world; - } - - @Override - public void e() { - EntityMinecartCommandBlock.this.getDataWatcher().set(EntityMinecartCommandBlock.COMMAND, this.getCommand()); - EntityMinecartCommandBlock.this.getDataWatcher().set(EntityMinecartCommandBlock.c, this.j()); - } - - @Override - public CommandListenerWrapper getWrapper() { - return new CommandListenerWrapper(this, new Vec3D(EntityMinecartCommandBlock.this.locX, EntityMinecartCommandBlock.this.locY, EntityMinecartCommandBlock.this.locZ), EntityMinecartCommandBlock.this.aU(), this.d(), 2, this.getName().getString(), EntityMinecartCommandBlock.this.getScoreboardDisplayName(), this.d().getMinecraftServer(), EntityMinecartCommandBlock.this); - } - - // CraftBukkit start - @Override - public org.bukkit.command.CommandSender getBukkitSender(CommandListenerWrapper wrapper) { - return (org.bukkit.craftbukkit.entity.CraftMinecartCommand) EntityMinecartCommandBlock.this.getBukkitEntity(); - } - // CraftBukkit end - } -} diff --git a/src/main/java/net/minecraft/server/EntityMinecartContainer.java b/src/main/java/net/minecraft/server/EntityMinecartContainer.java deleted file mode 100644 index 8e6e7ed60..000000000 --- a/src/main/java/net/minecraft/server/EntityMinecartContainer.java +++ /dev/null @@ -1,257 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import javax.annotation.Nullable; -// CraftBukkit start -import java.util.List; -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.InventoryHolder; -// CraftBukkit end - -public abstract class EntityMinecartContainer extends EntityMinecartAbstract implements IInventory, ITileInventory { - - private NonNullList items; - private boolean c; - @Nullable - public MinecraftKey lootTable; public MinecraftKey getLootTableKey() { return this.lootTable; } public void setLootTable(final MinecraftKey key) { this.lootTable = key; } // Paper - OBFHELPER - public long lootTableSeed; - - // CraftBukkit start - { this.lootableData = new com.destroystokyo.paper.loottable.PaperLootableInventoryData(new com.destroystokyo.paper.loottable.PaperMinecartLootableInventory(this)); } // Paper - public List transaction = new java.util.ArrayList(); - private int maxStack = MAX_STACK; - - public List 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; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - - @Override - public Location getLocation() { - return getBukkitEntity().getLocation(); - } - // CraftBukkit end - - protected EntityMinecartContainer(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.items = NonNullList.a(this.getSize(), ItemStack.a); // CraftBukkit - SPIGOT-3513 - this.c = true; - } - - protected EntityMinecartContainer(EntityTypes entitytypes, double d0, double d1, double d2, World world) { - super(entitytypes, world, d0, d1, d2); - this.items = NonNullList.a(this.getSize(), ItemStack.a); // CraftBukkit - SPIGOT-3513 - this.c = true; - } - - @Override - public void a(DamageSource damagesource) { - super.a(damagesource); - if (this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { - InventoryUtils.dropEntity(this.world, this, this); - } - - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public ItemStack getItem(int i) { - this.d((EntityHuman) null); - return (ItemStack) this.items.get(i); - } - - @Override - public ItemStack splitStack(int i, int j) { - this.d((EntityHuman) null); - return ContainerUtil.a(this.items, i, j); - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - this.d((EntityHuman) null); - ItemStack itemstack = (ItemStack) this.items.get(i); - - if (itemstack.isEmpty()) { - return ItemStack.a; - } else { - this.items.set(i, ItemStack.a); - return itemstack; - } - } - - @Override - public void setItem(int i, ItemStack itemstack) { - this.d((EntityHuman) null); - this.items.set(i, itemstack); - if (!itemstack.isEmpty() && itemstack.getCount() > this.getMaxStackSize()) { - itemstack.setCount(this.getMaxStackSize()); - } - - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - if (i >= 0 && i < this.getSize()) { - this.setItem(i, itemstack); - return true; - } else { - return false; - } - } - - @Override - public void update() {} - - @Override - public boolean a(EntityHuman entityhuman) { - return this.dead ? false : entityhuman.h((Entity) this) <= 64.0D; - } - - @Nullable - @Override - public Entity a(DimensionManager dimensionmanager) { - this.c = false; - return super.a(dimensionmanager); - } - - @Override - public void die() { - if (!this.world.isClientSide && this.c) { - InventoryUtils.dropEntity(this.world, this, this); - } - - super.die(); - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - this.lootableData.saveNbt(nbttagcompound); // Paper - if (this.lootTable != null) { - nbttagcompound.setString("LootTable", this.lootTable.toString()); - if (this.lootTableSeed != 0L) { - nbttagcompound.setLong("LootTableSeed", this.lootTableSeed); - } - } if (true) { // Paper - Always save the items, Table may stick around - ContainerUtil.a(nbttagcompound, this.items); - } - - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.lootableData.loadNbt(nbttagcompound); // Paper - this.items = NonNullList.a(this.getSize(), ItemStack.a); - if (nbttagcompound.hasKeyOfType("LootTable", 8)) { - this.lootTable = new MinecraftKey(nbttagcompound.getString("LootTable")); - this.lootTableSeed = nbttagcompound.getLong("LootTableSeed"); - } if (true) { // Paper - always load the items, table may still remain - ContainerUtil.b(nbttagcompound, this.items); - } - - } - - @Override - public boolean b(EntityHuman entityhuman, EnumHand enumhand) { - entityhuman.openContainer(this); - return true; - } - - @Override - protected void decelerate() { - float f = 0.98F; - - if (this.lootTable == null) { - int i = 15 - Container.b((IInventory) this); - - f += (float) i * 0.001F; - } - - this.setMot(this.getMot().d((double) f, 0.0D, (double) f)); - } - - public void d(@Nullable EntityHuman entityhuman) { - if (this.lootableData.shouldReplenish(entityhuman) && this.world.getMinecraftServer() != null) { // Paper - LootTable loottable = this.world.getMinecraftServer().getLootTableRegistry().getLootTable(this.lootTable); - - this.lootableData.processRefill(entityhuman); // Paper - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder((WorldServer) this.world)).set(LootContextParameters.POSITION, new BlockPosition(this)).a(this.lootTableSeed); - - if (entityhuman != null) { - loottableinfo_builder.a(entityhuman.eb()).set(LootContextParameters.THIS_ENTITY, entityhuman); - } - - loottable.fillInventory(this, loottableinfo_builder.build(LootContextParameterSets.CHEST)); - } - - } - - @Override - public void clear() { - this.d((EntityHuman) null); - this.items.clear(); - } - - public void setLootTable(MinecraftKey minecraftkey, long i) { - this.lootTable = minecraftkey; - this.lootTableSeed = i; - } - - @Nullable - @Override - public Container createMenu(int i, PlayerInventory playerinventory, EntityHuman entityhuman) { - if (this.lootTable != null && entityhuman.isSpectator()) { - return null; - } else { - this.d(playerinventory.player); - return this.a(i, playerinventory); - } - } - - protected abstract Container a(int i, PlayerInventory playerinventory); -} diff --git a/src/main/java/net/minecraft/server/EntityMonster.java b/src/main/java/net/minecraft/server/EntityMonster.java deleted file mode 100644 index e0609e7e9..000000000 --- a/src/main/java/net/minecraft/server/EntityMonster.java +++ /dev/null @@ -1,123 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import java.util.function.Predicate; - -public abstract class EntityMonster extends EntityCreature implements IMonster { - - public org.bukkit.craftbukkit.entity.CraftMonster getBukkitMonster() { return (org.bukkit.craftbukkit.entity.CraftMonster) super.getBukkitEntity(); } // Paper - protected EntityMonster(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.f = 5; - } - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.HOSTILE; - } - - @Override - public void movementTick() { - this.cO(); - this.eb(); - super.movementTick(); - } - - protected void eb() { - float f = this.aF(); - - if (f > 0.5F) { - this.ticksFarFromPlayer += 2; - } - - } - - @Override - public void tick() { - super.tick(); - if (!this.world.isClientSide && this.world.getDifficulty() == EnumDifficulty.PEACEFUL) { - this.die(); - } - - } - - @Override - protected SoundEffect getSoundSwim() { - return SoundEffects.ENTITY_HOSTILE_SWIM; - } - - @Override - protected SoundEffect getSoundSplash() { - return SoundEffects.ENTITY_HOSTILE_SPLASH; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - return this.isInvulnerable(damagesource) ? false : super.damageEntity(damagesource, f); - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_HOSTILE_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_HOSTILE_DEATH; - } - - @Override - protected SoundEffect getSoundFall(int i) { - return i > 4 ? SoundEffects.ENTITY_HOSTILE_BIG_FALL : SoundEffects.ENTITY_HOSTILE_SMALL_FALL; - } - - @Override - public float a(BlockPosition blockposition, IWorldReader iworldreader) { - return 0.5F - iworldreader.v(blockposition); - } - - public static boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition, Random random) { - if (generatoraccess.getBrightness(EnumSkyBlock.SKY, blockposition) > random.nextInt(32)) { - return false; - } else { - int i = generatoraccess.getMinecraftWorld().U() ? generatoraccess.d(blockposition, 10) : generatoraccess.getLightLevel(blockposition); - - return i <= random.nextInt(8); - } - } - - public static boolean c(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return generatoraccess.getDifficulty() != EnumDifficulty.PEACEFUL && a(generatoraccess, blockposition, random) && a(entitytypes, generatoraccess, enummobspawn, blockposition, random); - } - - public static boolean d(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return generatoraccess.getDifficulty() != EnumDifficulty.PEACEFUL && a(entitytypes, generatoraccess, enummobspawn, blockposition, random); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE); - } - - @Override - protected boolean isDropExperience() { - return true; - } - - public boolean e(EntityHuman entityhuman) { - return true; - } - - @Override - public ItemStack f(ItemStack itemstack) { - if (itemstack.getItem() instanceof ItemProjectileWeapon) { - Predicate predicate = ((ItemProjectileWeapon) itemstack.getItem()).d(); - ItemStack itemstack1 = ItemProjectileWeapon.a((EntityLiving) this, predicate); - - return itemstack1.isEmpty() ? new ItemStack(Items.ARROW) : itemstack1; - } else { - return ItemStack.a; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityMushroomCow.java b/src/main/java/net/minecraft/server/EntityMushroomCow.java deleted file mode 100644 index 1363069ff..000000000 --- a/src/main/java/net/minecraft/server/EntityMushroomCow.java +++ /dev/null @@ -1,246 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import java.util.UUID; -import org.apache.commons.lang3.tuple.Pair; -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityTransformEvent; -import org.bukkit.event.player.PlayerShearEntityEvent; -// CraftBukkit end - -public class EntityMushroomCow extends EntityCow { - - private static final DataWatcherObject bz = DataWatcher.a(EntityMushroomCow.class, DataWatcherRegistry.d); - private MobEffectList bA; - private int bB; - private UUID bC; - - public EntityMushroomCow(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - public float a(BlockPosition blockposition, IWorldReader iworldreader) { - return iworldreader.getType(blockposition.down()).getBlock() == Blocks.MYCELIUM ? 10.0F : iworldreader.v(blockposition) - 0.5F; - } - - public static boolean c(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return generatoraccess.getType(blockposition.down()).getBlock() == Blocks.MYCELIUM && generatoraccess.getLightLevel(blockposition, 0) > 8; - } - - @Override - public void onLightningStrike(EntityLightning entitylightning) { - UUID uuid = entitylightning.getUniqueID(); - - if (!uuid.equals(this.bC)) { - this.setVariant(this.getVariant() == EntityMushroomCow.Type.RED ? EntityMushroomCow.Type.BROWN : EntityMushroomCow.Type.RED); - this.bC = uuid; - this.a(SoundEffects.ENTITY_MOOSHROOM_CONVERT, 2.0F, 1.0F); - } - - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityMushroomCow.bz, EntityMushroomCow.Type.RED.c); - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() == Items.BOWL && this.getAge() >= 0 && !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - boolean flag = false; - ItemStack itemstack1; - - if (this.bA != null) { - flag = true; - itemstack1 = new ItemStack(Items.SUSPICIOUS_STEW); - ItemSuspiciousStew.a(itemstack1, this.bA, this.bB); - this.bA = null; - this.bB = 0; - } else { - itemstack1 = new ItemStack(Items.MUSHROOM_STEW); - } - - if (itemstack.isEmpty()) { - entityhuman.a(enumhand, itemstack1); - } else if (!entityhuman.inventory.pickup(itemstack1)) { - entityhuman.drop(itemstack1, false); - } - - SoundEffect soundeffect; - - if (flag) { - soundeffect = SoundEffects.ENTITY_MOOSHROOM_SUSPICIOUS_MILK; - } else { - soundeffect = SoundEffects.ENTITY_MOOSHROOM_MILK; - } - - this.a(soundeffect, 1.0F, 1.0F); - return true; - } else { - int i; - - if (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.world.addParticle(Particles.EXPLOSION, this.locX, this.locY + (double) (this.getHeight() / 2.0F), this.locZ, 0.0D, 0.0D, 0.0D); - if (!this.world.isClientSide) { - // this.die(); // CraftBukkit - moved down - EntityCow entitycow = (EntityCow) EntityTypes.COW.a(this.world); - - entitycow.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, this.pitch); - entitycow.setHealth(this.getHealth()); - entitycow.aK = this.aK; - if (this.hasCustomName()) { - entitycow.setCustomName(this.getCustomName()); - } - - // CraftBukkit start - if (CraftEventFactory.callEntityTransformEvent(this, entitycow, EntityTransformEvent.TransformReason.SHEARED).isCancelled()) { - return false; - } - if (!new com.destroystokyo.paper.event.entity.EntityTransformedEvent(this.getBukkitEntity(), entitycow.getBukkitEntity(), com.destroystokyo.paper.event.entity.EntityTransformedEvent.TransformedReason.SHEARED).callEvent()) return false; // Paper - this.world.addEntity(entitycow, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SHEARED); - - this.die(); // CraftBukkit - from above - // CraftBukkit end - - for (i = 0; i < 5; ++i) { - this.world.addEntity(new EntityItem(this.world, this.locX, this.locY + (double) this.getHeight(), this.locZ, new ItemStack(this.getVariant().d.getBlock()))); - } - - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(enumhand); - }); - this.a(SoundEffects.ENTITY_MOOSHROOM_SHEAR, 1.0F, 1.0F); - } - - return true; - } else { - if (this.getVariant() == EntityMushroomCow.Type.BROWN && itemstack.getItem().a(TagsItem.SMALL_FLOWERS)) { - if (this.bA != null) { - for (int j = 0; j < 2; ++j) { - this.world.addParticle(Particles.SMOKE, this.locX + (double) (this.random.nextFloat() / 2.0F), this.locY + (double) (this.getHeight() / 2.0F), this.locZ + (double) (this.random.nextFloat() / 2.0F), 0.0D, (double) (this.random.nextFloat() / 5.0F), 0.0D); - } - } else { - Pair pair = this.j(itemstack); - - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - for (i = 0; i < 4; ++i) { - this.world.addParticle(Particles.EFFECT, this.locX + (double) (this.random.nextFloat() / 2.0F), this.locY + (double) (this.getHeight() / 2.0F), this.locZ + (double) (this.random.nextFloat() / 2.0F), 0.0D, (double) (this.random.nextFloat() / 5.0F), 0.0D); - } - - this.bA = (MobEffectList) pair.getLeft(); - this.bB = (Integer) pair.getRight(); - this.a(SoundEffects.ENTITY_MOOSHROOM_EAT, 2.0F, 1.0F); - } - } - - return super.a(entityhuman, enumhand); - } - } - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setString("Type", this.getVariant().c); - if (this.bA != null) { - nbttagcompound.setByte("EffectId", (byte) MobEffectList.getId(this.bA)); - nbttagcompound.setInt("EffectDuration", this.bB); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setVariant(EntityMushroomCow.Type.b(nbttagcompound.getString("Type"))); - if (nbttagcompound.hasKeyOfType("EffectId", 1)) { - this.bA = MobEffectList.fromId(nbttagcompound.getByte("EffectId")); - } - - if (nbttagcompound.hasKeyOfType("EffectDuration", 3)) { - this.bB = nbttagcompound.getInt("EffectDuration"); - } - - } - - private Pair j(ItemStack itemstack) { - BlockFlowers blockflowers = (BlockFlowers) ((ItemBlock) itemstack.getItem()).getBlock(); - - return Pair.of(blockflowers.d(), blockflowers.e()); - } - - public void setVariant(EntityMushroomCow.Type entitymushroomcow_type) { - this.datawatcher.set(EntityMushroomCow.bz, entitymushroomcow_type.c); - } - - public EntityMushroomCow.Type getVariant() { - return EntityMushroomCow.Type.b((String) this.datawatcher.get(EntityMushroomCow.bz)); - } - - @Override - public EntityMushroomCow createChild(EntityAgeable entityageable) { - EntityMushroomCow entitymushroomcow = (EntityMushroomCow) EntityTypes.MOOSHROOM.a(this.world); - - entitymushroomcow.setVariant(this.a((EntityMushroomCow) entityageable)); - return entitymushroomcow; - } - - private EntityMushroomCow.Type a(EntityMushroomCow entitymushroomcow) { - EntityMushroomCow.Type entitymushroomcow_type = this.getVariant(); - EntityMushroomCow.Type entitymushroomcow_type1 = entitymushroomcow.getVariant(); - EntityMushroomCow.Type entitymushroomcow_type2; - - if (entitymushroomcow_type == entitymushroomcow_type1 && this.random.nextInt(1024) == 0) { - entitymushroomcow_type2 = entitymushroomcow_type == EntityMushroomCow.Type.BROWN ? EntityMushroomCow.Type.RED : EntityMushroomCow.Type.BROWN; - } else { - entitymushroomcow_type2 = this.random.nextBoolean() ? entitymushroomcow_type : entitymushroomcow_type1; - } - - return entitymushroomcow_type2; - } - - public static enum Type { - - RED("red", Blocks.RED_MUSHROOM.getBlockData()), BROWN("brown", Blocks.BROWN_MUSHROOM.getBlockData()); - - private final String c; - private final IBlockData d; - - private Type(String s, IBlockData iblockdata) { - this.c = s; - this.d = iblockdata; - } - - private static EntityMushroomCow.Type b(String s) { - EntityMushroomCow.Type[] aentitymushroomcow_type = values(); - int i = aentitymushroomcow_type.length; - - for (int j = 0; j < i; ++j) { - EntityMushroomCow.Type entitymushroomcow_type = aentitymushroomcow_type[j]; - - if (entitymushroomcow_type.c.equals(s)) { - return entitymushroomcow_type; - } - } - - return EntityMushroomCow.Type.RED; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityOcelot.java b/src/main/java/net/minecraft/server/EntityOcelot.java deleted file mode 100644 index edc5f696c..000000000 --- a/src/main/java/net/minecraft/server/EntityOcelot.java +++ /dev/null @@ -1,274 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntityOcelot extends EntityAnimal { - - private static final RecipeItemStack bz = RecipeItemStack.a(Items.COD, Items.SALMON); - private static final DataWatcherObject bA = DataWatcher.a(EntityOcelot.class, DataWatcherRegistry.i); - private EntityOcelot.a bB; - private EntityOcelot.b bC; - public boolean spawnBonus = true; // Spigot - - public EntityOcelot(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.dV(); - } - - private boolean isTrusting() { - return (Boolean) this.datawatcher.get(EntityOcelot.bA); - } - - private void setTrusting(boolean flag) { - this.datawatcher.set(EntityOcelot.bA, flag); - this.dV(); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("Trusting", this.isTrusting()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setTrusting(nbttagcompound.getBoolean("Trusting")); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityOcelot.bA, false); - } - - @Override - protected void initPathfinder() { - this.bC = new EntityOcelot.b(this, 0.6D, EntityOcelot.bz, true); - this.goalSelector.a(1, new PathfinderGoalFloat(this)); - this.goalSelector.a(3, this.bC); - 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 PathfinderGoalRandomStrollLand(this, 0.8D, 1.0000001E-5F)); - this.goalSelector.a(11, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 10.0F)); - this.targetSelector.a(1, new PathfinderGoalNearestAttackableTarget<>(this, EntityChicken.class, false)); - this.targetSelector.a(1, new PathfinderGoalNearestAttackableTarget<>(this, EntityTurtle.class, 10, false, false, EntityTurtle.bz)); - } - - @Override - public void mobTick() { - if (this.getControllerMove().b()) { - double d0 = this.getControllerMove().c(); - - 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); - } - - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return !this.isTrusting() && !this.hasCustomName() && !this.isLeashed() /*&& this.ticksLived > 2400*/; // CraftBukkit // Paper - honor name and leash - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); - } - - @Override - public void b(float f, float f1) {} - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_OCELOT_AMBIENT; - } - - @Override - public int A() { - return 900; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_OCELOT_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_OCELOT_DEATH; - } - - @Override - public boolean C(Entity entity) { - return entity.damageEntity(DamageSource.mobAttack(this), 3.0F); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - return this.isInvulnerable(damagesource) ? false : super.damageEntity(damagesource, f); - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if ((this.bC == null || this.bC.h()) && !this.isTrusting() && this.i(itemstack) && entityhuman.h((Entity) this) < 9.0D) { - this.a(entityhuman, itemstack); - if (!this.world.isClientSide) { - // CraftBukkit - added event call and isCancelled check - if (this.random.nextInt(3) == 0 && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityTameEvent(this, entityhuman).isCancelled()) { - this.setTrusting(true); - this.s(true); - this.world.broadcastEntityEffect(this, (byte) 41); - } else { - this.s(false); - this.world.broadcastEntityEffect(this, (byte) 40); - } - } - - return true; - } else { - return super.a(entityhuman, enumhand); - } - } - - private void s(boolean flag) { - ParticleType particletype = Particles.HEART; - - if (!flag) { - particletype = Particles.SMOKE; - } - - 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(particletype, this.locX + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), this.locY + 0.5D + (double) (this.random.nextFloat() * this.getHeight()), this.locZ + (double) (this.random.nextFloat() * this.getWidth() * 2.0F) - (double) this.getWidth(), d0, d1, d2); - } - - } - - protected void dV() { - if (this.bB == null) { - this.bB = new EntityOcelot.a<>(this, EntityHuman.class, 16.0F, 0.8D, 1.33D); - } - - this.goalSelector.a((PathfinderGoal) this.bB); - if (!this.isTrusting()) { - this.goalSelector.a(4, this.bB); - } - - } - - @Override - public EntityOcelot createChild(EntityAgeable entityageable) { - return (EntityOcelot) EntityTypes.OCELOT.a(this.world); - } - - @Override - public boolean i(ItemStack itemstack) { - return EntityOcelot.bz.test(itemstack); - } - - public static boolean c(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return random.nextInt(3) != 0; - } - - @Override - public boolean a(IWorldReader iworldreader) { - if (iworldreader.i(this) && !iworldreader.containsLiquid(this.getBoundingBox())) { - BlockPosition blockposition = new BlockPosition(this.locX, this.getBoundingBox().minY, this.locZ); - - if (blockposition.getY() < iworldreader.getSeaLevel()) { - return false; - } - - IBlockData iblockdata = iworldreader.getType(blockposition.down()); - Block block = iblockdata.getBlock(); - - if (block == Blocks.GRASS_BLOCK || iblockdata.a(TagsBlock.LEAVES)) { - return true; - } - } - - return false; - } - - protected void dW() { - for (int i = 0; i < 2; ++i) { - EntityOcelot entityocelot = (EntityOcelot) EntityTypes.OCELOT.a(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 - } - - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - groupdataentity = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - if (spawnBonus && generatoraccess.getRandom().nextInt(7) == 0) { // Spigot - this.dW(); - } - - return groupdataentity; - } - - static class b extends PathfinderGoalTempt { - - private final EntityOcelot c; - - public b(EntityOcelot entityocelot, double d0, RecipeItemStack recipeitemstack, boolean flag) { - super(entityocelot, d0, recipeitemstack, flag); - this.c = entityocelot; - } - - @Override - protected boolean g() { - return super.g() && !this.c.isTrusting(); - } - } - - static class a extends PathfinderGoalAvoidTarget { - - private final EntityOcelot i; - - public a(EntityOcelot entityocelot, Class oclass, float f, double d0, double d1) { - // Predicate predicate = IEntitySelector.e; // CraftBukkit - decompile error - - super(entityocelot, oclass, f, d0, d1, IEntitySelector.e::test); // CraftBukkit - decompile error - this.i = entityocelot; - } - - @Override - public boolean a() { - return !this.i.isTrusting() && super.a(); - } - - @Override - public boolean b() { - return !this.i.isTrusting() && super.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityPainting.java b/src/main/java/net/minecraft/server/EntityPainting.java deleted file mode 100644 index fe2beede2..000000000 --- a/src/main/java/net/minecraft/server/EntityPainting.java +++ /dev/null @@ -1,110 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -public class EntityPainting extends EntityHanging { - - public Paintings art; - - public EntityPainting(EntityTypes entitytypes, World world) { - super(entitytypes, world); - // CraftBukkit start - generate a non-null painting - List list = Lists.newArrayList(Paintings.a); - this.art = (Paintings) list.get(this.random.nextInt(list.size())); - // CraftBukkit end - } - - public EntityPainting(World world, BlockPosition blockposition, EnumDirection enumdirection) { - super(EntityTypes.PAINTING, world, blockposition); - List list = Lists.newArrayList(); - int i = 0; - Iterator iterator = IRegistry.MOTIVE.iterator(); - - Paintings paintings; - - while (iterator.hasNext()) { - paintings = (Paintings) iterator.next(); - this.art = paintings; - this.setDirection(enumdirection); - if (this.survives()) { - list.add(paintings); - int j = paintings.getWidth() * paintings.getHeight(); - - if (j > i) { - i = j; - } - } - } - - if (!list.isEmpty()) { - iterator = list.iterator(); - - while (iterator.hasNext()) { - paintings = (Paintings) iterator.next(); - if (paintings.getWidth() * paintings.getHeight() < i) { - iterator.remove(); - } - } - - this.art = (Paintings) list.get(this.random.nextInt(list.size())); - } - - this.setDirection(enumdirection); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setString("Motive", IRegistry.MOTIVE.getKey(this.art).toString()); - super.b(nbttagcompound); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.art = (Paintings) IRegistry.MOTIVE.get(MinecraftKey.a(nbttagcompound.getString("Motive"))); - super.a(nbttagcompound); - } - - @Override - public int getHangingWidth() { - return this.art == null ? 1 : this.art.getWidth(); - } - - @Override - public int getHangingHeight() { - return this.art == null ? 1 : this.art.getHeight(); - } - - @Override - public void a(@Nullable Entity entity) { - if (this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { - this.a(SoundEffects.ENTITY_PAINTING_BREAK, 1.0F, 1.0F); - if (entity instanceof EntityHuman) { - EntityHuman entityhuman = (EntityHuman) entity; - - if (entityhuman.abilities.canInstantlyBuild) { - return; - } - } - - this.a((IMaterial) Items.PAINTING); - } - } - - @Override - public void playPlaceSound() { - this.a(SoundEffects.ENTITY_PAINTING_PLACE, 1.0F, 1.0F); - } - - @Override - public void setPositionRotation(double d0, double d1, double d2, float f, float f1) { - this.setPosition(d0, d1, d2); - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntityPainting(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntityPanda.java b/src/main/java/net/minecraft/server/EntityPanda.java deleted file mode 100644 index 479ef6b92..000000000 --- a/src/main/java/net/minecraft/server/EntityPanda.java +++ /dev/null @@ -1,1039 +0,0 @@ -package net.minecraft.server; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -import org.bukkit.event.entity.EntityTargetEvent; // CraftBukkit - -public class EntityPanda extends EntityAnimal { - - private static final DataWatcherObject bA = DataWatcher.a(EntityPanda.class, DataWatcherRegistry.b); - private static final DataWatcherObject bB = DataWatcher.a(EntityPanda.class, DataWatcherRegistry.b); - private static final DataWatcherObject bC = DataWatcher.a(EntityPanda.class, DataWatcherRegistry.b); - private static final DataWatcherObject bD = DataWatcher.a(EntityPanda.class, DataWatcherRegistry.a); - private static final DataWatcherObject bE = DataWatcher.a(EntityPanda.class, DataWatcherRegistry.a); - private static final DataWatcherObject bF = DataWatcher.a(EntityPanda.class, DataWatcherRegistry.a); - private boolean bG; - private boolean bH; - public int bz; - private Vec3D bI; - private float bJ; - private float bK; - private float bL; - private float bM; - private float bN; - private float bO; - private static final Predicate PICKUP_PREDICATE = (entityitem) -> { - Item item = entityitem.getItemStack().getItem(); - - return (item == Blocks.BAMBOO.getItem() || item == Blocks.CAKE.getItem()) && entityitem.isAlive() && !entityitem.q(); - }; - - public EntityPanda(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.moveController = new EntityPanda.i(this); - if (!this.isBaby()) { - this.setCanPickupLoot(true); - } - - } - - @Override - public boolean e(ItemStack itemstack) { - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - - return !this.getEquipment(enumitemslot).isEmpty() ? false : enumitemslot == EnumItemSlot.MAINHAND && super.e(itemstack); - } - - public int dV() { - return (Integer) this.datawatcher.get(EntityPanda.bA); - } - - public void s(int i) { - this.datawatcher.set(EntityPanda.bA, i); - } - - public boolean dW() { - return this.v(2); - } - - public boolean dX() { - return this.v(8); - } - - public void r(boolean flag) { - this.d(8, flag); - } - - public boolean dY() { - return this.v(16); - } - - public void s(boolean flag) { - this.d(16, flag); - } - - public boolean dZ() { - return (Integer) this.datawatcher.get(EntityPanda.bC) > 0; - } - - public void t(boolean flag) { - this.datawatcher.set(EntityPanda.bC, flag ? 1 : 0); - } - - private int es() { - return (Integer) this.datawatcher.get(EntityPanda.bC); - } - - private void u(int i) { - this.datawatcher.set(EntityPanda.bC, i); - } - - public void u(boolean flag) { - this.d(2, flag); - if (!flag) { - this.t(0); - } - - } - - public int ee() { - return (Integer) this.datawatcher.get(EntityPanda.bB); - } - - public void t(int i) { - this.datawatcher.set(EntityPanda.bB, i); - } - - public EntityPanda.Gene getMainGene() { - return EntityPanda.Gene.a((Byte) this.datawatcher.get(EntityPanda.bD)); - } - - public void setMainGene(EntityPanda.Gene entitypanda_gene) { - if (entitypanda_gene.a() > 6) { - entitypanda_gene = EntityPanda.Gene.a(this.random); - } - - this.datawatcher.set(EntityPanda.bD, (byte) entitypanda_gene.a()); - } - - public EntityPanda.Gene getHiddenGene() { - return EntityPanda.Gene.a((Byte) this.datawatcher.get(EntityPanda.bE)); - } - - public void setHiddenGene(EntityPanda.Gene entitypanda_gene) { - if (entitypanda_gene.a() > 6) { - entitypanda_gene = EntityPanda.Gene.a(this.random); - } - - this.datawatcher.set(EntityPanda.bE, (byte) entitypanda_gene.a()); - } - - public boolean eh() { - return this.v(4); - } - - public void v(boolean flag) { - this.d(4, flag); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityPanda.bA, 0); - this.datawatcher.register(EntityPanda.bB, 0); - this.datawatcher.register(EntityPanda.bD, (byte) 0); - this.datawatcher.register(EntityPanda.bE, (byte) 0); - this.datawatcher.register(EntityPanda.bF, (byte) 0); - this.datawatcher.register(EntityPanda.bC, 0); - } - - private boolean v(int i) { - return ((Byte) this.datawatcher.get(EntityPanda.bF) & i) != 0; - } - - private void d(int i, boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityPanda.bF); - - if (flag) { - this.datawatcher.set(EntityPanda.bF, (byte) (b0 | i)); - } else { - this.datawatcher.set(EntityPanda.bF, (byte) (b0 & ~i)); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setString("MainGene", this.getMainGene().b()); - nbttagcompound.setString("HiddenGene", this.getHiddenGene().b()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setMainGene(EntityPanda.Gene.a(nbttagcompound.getString("MainGene"))); - this.setHiddenGene(EntityPanda.Gene.a(nbttagcompound.getString("HiddenGene"))); - } - - @Nullable - @Override - public EntityAgeable createChild(EntityAgeable entityageable) { - EntityPanda entitypanda = (EntityPanda) EntityTypes.PANDA.a(this.world); - - if (entityageable instanceof EntityPanda) { - entitypanda.a(this, (EntityPanda) entityageable); - } - - entitypanda.ep(); - return entitypanda; - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(2, new EntityPanda.j(this, 2.0D)); - this.goalSelector.a(2, new EntityPanda.d(this, 1.0D)); - this.goalSelector.a(3, new EntityPanda.b(this, 1.2000000476837158D, true)); - this.goalSelector.a(4, new PathfinderGoalTempt(this, 1.0D, RecipeItemStack.a(Blocks.BAMBOO.getItem()), false)); - this.goalSelector.a(6, new EntityPanda.c<>(this, EntityHuman.class, 8.0F, 2.0D, 2.0D)); - this.goalSelector.a(6, new EntityPanda.c<>(this, EntityMonster.class, 4.0F, 2.0D, 2.0D)); - this.goalSelector.a(7, new EntityPanda.l()); - this.goalSelector.a(8, new EntityPanda.g(this)); - this.goalSelector.a(8, new EntityPanda.m(this)); - this.goalSelector.a(9, new EntityPanda.h(this, EntityHuman.class, 6.0F)); - this.goalSelector.a(10, new PathfinderGoalRandomLookaround(this)); - this.goalSelector.a(12, new EntityPanda.k(this)); - this.goalSelector.a(13, new PathfinderGoalFollowParent(this, 1.25D)); - this.goalSelector.a(14, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.targetSelector.a(1, (new EntityPanda.f(this, new Class[0])).a(new Class[0])); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.15000000596046448D); - this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(6.0D); - } - - public EntityPanda.Gene ei() { - return EntityPanda.Gene.b(this.getMainGene(), this.getHiddenGene()); - } - - public boolean ej() { - return this.ei() == EntityPanda.Gene.LAZY; - } - - public boolean ek() { - return this.ei() == EntityPanda.Gene.WORRIED; - } - - public boolean el() { - return this.ei() == EntityPanda.Gene.PLAYFUL; - } - - public boolean en() { - return this.ei() == EntityPanda.Gene.WEAK; - } - - @Override - public boolean dR() { - return this.ei() == EntityPanda.Gene.AGGRESSIVE; - } - - @Override - public boolean a(EntityHuman entityhuman) { - return false; - } - - @Override - public boolean C(Entity entity) { - this.a(SoundEffects.ENTITY_PANDA_BITE, 1.0F, 1.0F); - if (!this.dR()) { - this.bH = true; - } - - return super.C(entity); - } - - @Override - public void tick() { - super.tick(); - if (this.ek()) { - if (this.world.U() && !this.isInWater()) { - this.r(true); - this.t(false); - } else if (!this.dZ()) { - this.r(false); - } - } - - if (this.getGoalTarget() == null) { - this.bG = false; - this.bH = false; - } - - if (this.dV() > 0) { - if (this.getGoalTarget() != null) { - this.a((Entity) this.getGoalTarget(), 90.0F, 90.0F); - } - - if (this.dV() == 29 || this.dV() == 14) { - this.a(SoundEffects.ENTITY_PANDA_CANT_BREED, 1.0F, 1.0F); - } - - this.s(this.dV() - 1); - } - - if (this.dW()) { - this.t(this.ee() + 1); - if (this.ee() > 20) { - this.u(false); - this.ez(); - } else if (this.ee() == 1) { - this.a(SoundEffects.ENTITY_PANDA_PRE_SNEEZE, 1.0F, 1.0F); - } - } - - if (this.eh()) { - this.ey(); - } else { - this.bz = 0; - } - - if (this.dX()) { - this.pitch = 0.0F; - } - - this.ev(); - this.et(); - this.ew(); - this.ex(); - } - - public boolean eo() { - return this.ek() && this.world.U(); - } - - private void et() { - if (!this.dZ() && this.dX() && !this.eo() && !this.getEquipment(EnumItemSlot.MAINHAND).isEmpty() && this.random.nextInt(80) == 1) { - this.t(true); - } else if (this.getEquipment(EnumItemSlot.MAINHAND).isEmpty() || !this.dX()) { - this.t(false); - } - - if (this.dZ()) { - this.eu(); - if (!this.world.isClientSide && this.es() > 80 && this.random.nextInt(20) == 1) { - if (this.es() > 100 && this.j(this.getEquipment(EnumItemSlot.MAINHAND))) { - if (!this.world.isClientSide) { - this.setSlot(EnumItemSlot.MAINHAND, ItemStack.a); - } - - this.r(false); - } - - this.t(false); - return; - } - - this.u(this.es() + 1); - } - - } - - private void eu() { - if (this.es() % 5 == 0) { - this.a(SoundEffects.ENTITY_PANDA_EAT, 0.5F + 0.5F * (float) this.random.nextInt(2), (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F); - - for (int i = 0; i < 6; ++i) { - Vec3D vec3d = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, ((double) this.random.nextFloat() - 0.5D) * 0.1D); - - vec3d = vec3d.a(-this.pitch * 0.017453292F); - vec3d = vec3d.b(-this.yaw * 0.017453292F); - double d0 = (double) (-this.random.nextFloat()) * 0.6D - 0.3D; - Vec3D vec3d1 = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.8D, d0, 1.0D + ((double) this.random.nextFloat() - 0.5D) * 0.4D); - - vec3d1 = vec3d1.b(-this.aK * 0.017453292F); - vec3d1 = vec3d1.add(this.locX, this.locY + (double) this.getHeadHeight() + 1.0D, this.locZ); - this.world.addParticle(new ParticleParamItem(Particles.ITEM, this.getEquipment(EnumItemSlot.MAINHAND)), vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z); - } - } - - } - - private void ev() { - this.bK = this.bJ; - if (this.dX()) { - this.bJ = Math.min(1.0F, this.bJ + 0.15F); - } else { - this.bJ = Math.max(0.0F, this.bJ - 0.19F); - } - - } - - private void ew() { - this.bM = this.bL; - if (this.dY()) { - this.bL = Math.min(1.0F, this.bL + 0.15F); - } else { - this.bL = Math.max(0.0F, this.bL - 0.19F); - } - - } - - private void ex() { - this.bO = this.bN; - if (this.eh()) { - this.bN = Math.min(1.0F, this.bN + 0.15F); - } else { - this.bN = Math.max(0.0F, this.bN - 0.19F); - } - - } - - private void ey() { - ++this.bz; - if (this.bz > 32) { - this.v(false); - } else { - if (!this.world.isClientSide) { - Vec3D vec3d = this.getMot(); - - if (this.bz == 1) { - float f = this.yaw * 0.017453292F; - float f1 = this.isBaby() ? 0.1F : 0.2F; - - this.bI = new Vec3D(vec3d.x + (double) (-MathHelper.sin(f) * f1), 0.0D, vec3d.z + (double) (MathHelper.cos(f) * f1)); - this.setMot(this.bI.add(0.0D, 0.27D, 0.0D)); - } else if ((float) this.bz != 7.0F && (float) this.bz != 15.0F && (float) this.bz != 23.0F) { - this.setMot(this.bI.x, vec3d.y, this.bI.z); - } else { - this.setMot(0.0D, this.onGround ? 0.27D : vec3d.y, 0.0D); - } - } - - } - } - - private void ez() { - Vec3D vec3d = this.getMot(); - - this.world.addParticle(Particles.SNEEZE, this.locX - (double) (this.getWidth() + 1.0F) * 0.5D * (double) MathHelper.sin(this.aK * 0.017453292F), this.locY + (double) this.getHeadHeight() - 0.10000000149011612D, this.locZ + (double) (this.getWidth() + 1.0F) * 0.5D * (double) MathHelper.cos(this.aK * 0.017453292F), vec3d.x, 0.0D, vec3d.z); - this.a(SoundEffects.ENTITY_PANDA_SNEEZE, 1.0F, 1.0F); - List list = this.world.a(EntityPanda.class, this.getBoundingBox().g(10.0D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityPanda entitypanda = (EntityPanda) iterator.next(); - - if (!entitypanda.isBaby() && entitypanda.onGround && !entitypanda.isInWater() && entitypanda.eq()) { - entitypanda.jump(); - } - } - - if (!this.world.e() && this.random.nextInt(700) == 0 && this.world.getGameRules().getBoolean(GameRules.DO_MOB_LOOT)) { - this.a((IMaterial) Items.SLIME_BALL); - } - - } - - @Override - protected void a(EntityItem entityitem) { - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callEntityPickupItemEvent(this, entityitem, 0, !(this.getEquipment(EnumItemSlot.MAINHAND).isEmpty() && EntityPanda.PICKUP_PREDICATE.test(entityitem))).isCancelled()) { // CraftBukkit - ItemStack itemstack = entityitem.getItemStack(); - - this.setSlot(EnumItemSlot.MAINHAND, itemstack); - this.dropChanceHand[EnumItemSlot.MAINHAND.b()] = 2.0F; - this.receive(entityitem, itemstack.getCount()); - entityitem.die(); - } - - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - this.r(false); - return super.damageEntity(damagesource, f); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - Object object = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - - this.setMainGene(EntityPanda.Gene.a(this.random)); - this.setHiddenGene(EntityPanda.Gene.a(this.random)); - this.ep(); - if (object instanceof EntityPanda.e) { - if (this.random.nextInt(5) == 0) { - this.setAgeRaw(-24000); - } - } else { - object = new EntityPanda.e(); - } - - return (GroupDataEntity) object; - } - - public void a(EntityPanda entitypanda, @Nullable EntityPanda entitypanda1) { - if (entitypanda1 == null) { - if (this.random.nextBoolean()) { - this.setMainGene(entitypanda.eA()); - this.setHiddenGene(EntityPanda.Gene.a(this.random)); - } else { - this.setMainGene(EntityPanda.Gene.a(this.random)); - this.setHiddenGene(entitypanda.eA()); - } - } else if (this.random.nextBoolean()) { - this.setMainGene(entitypanda.eA()); - this.setHiddenGene(entitypanda1.eA()); - } else { - this.setMainGene(entitypanda1.eA()); - this.setHiddenGene(entitypanda.eA()); - } - - if (this.random.nextInt(32) == 0) { - this.setMainGene(EntityPanda.Gene.a(this.random)); - } - - if (this.random.nextInt(32) == 0) { - this.setHiddenGene(EntityPanda.Gene.a(this.random)); - } - - } - - private EntityPanda.Gene eA() { - return this.random.nextBoolean() ? this.getMainGene() : this.getHiddenGene(); - } - - public void ep() { - if (this.en()) { - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - } - - if (this.ej()) { - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.07000000029802322D); - } - - } - - private void eB() { - if (!this.isInWater()) { - this.r(0.0F); - this.getNavigation().o(); - this.r(true); - } - - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() instanceof ItemMonsterEgg) { - return super.a(entityhuman, enumhand); - } else if (this.eo()) { - return false; - } else if (this.dY()) { - this.s(false); - return true; - } else if (this.i(itemstack)) { - if (this.getGoalTarget() != null) { - this.bG = true; - } - - if (this.isBaby()) { - this.a(entityhuman, itemstack); - this.setAge((int) ((float) (-this.getAge() / 20) * 0.1F), true); - } else if (!this.world.isClientSide && this.getAge() == 0 && this.ea()) { - this.a(entityhuman, itemstack); - this.f(entityhuman); - } else { - if (this.world.isClientSide || this.dX() || this.isInWater()) { - return false; - } - - this.eB(); - this.t(true); - ItemStack itemstack1 = this.getEquipment(EnumItemSlot.MAINHAND); - - if (!itemstack1.isEmpty() && !entityhuman.abilities.canInstantlyBuild) { - this.a(itemstack1); - } - - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(itemstack.getItem(), 1)); - this.a(entityhuman, itemstack); - } - - return true; - } else { - return false; - } - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - return this.dR() ? SoundEffects.ENTITY_PANDA_AGGRESSIVE_AMBIENT : (this.ek() ? SoundEffects.ENTITY_PANDA_WORRIED_AMBIENT : SoundEffects.ENTITY_PANDA_AMBIENT); - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_PANDA_STEP, 0.15F, 1.0F); - } - - @Override - public boolean i(ItemStack itemstack) { - return itemstack.getItem() == Blocks.BAMBOO.getItem(); - } - - private boolean j(ItemStack itemstack) { - return this.i(itemstack) || itemstack.getItem() == Blocks.CAKE.getItem(); - } - - @Nullable - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_PANDA_DEATH; - } - - @Nullable - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_PANDA_HURT; - } - - public boolean eq() { - return !this.dY() && !this.eo() && !this.dZ() && !this.eh() && !this.dX(); - } - - static class j extends PathfinderGoalPanic { - - private final EntityPanda f; - - public j(EntityPanda entitypanda, double d0) { - super(entitypanda, d0); - this.f = entitypanda; - } - - @Override - public boolean a() { - if (!this.f.isBurning()) { - return false; - } else { - BlockPosition blockposition = this.a(this.a.world, this.a, 5, 4); - - if (blockposition != null) { - this.c = (double) blockposition.getX(); - this.d = (double) blockposition.getY(); - this.e = (double) blockposition.getZ(); - return true; - } else { - return this.g(); - } - } - } - - @Override - public boolean b() { - if (this.f.dX()) { - this.f.getNavigation().o(); - return false; - } else { - return super.b(); - } - } - } - - static class f extends PathfinderGoalHurtByTarget { - - private final EntityPanda a; - - public f(EntityPanda entitypanda, Class... aclass) { - super(entitypanda, aclass); - this.a = entitypanda; - } - - @Override - public boolean b() { - if (!this.a.bG && !this.a.bH) { - return super.b(); - } else { - this.a.setGoalTarget((EntityLiving) null); - return false; - } - } - - @Override - protected void a(EntityInsentient entityinsentient, EntityLiving entityliving) { - if (entityinsentient instanceof EntityPanda && ((EntityPanda) entityinsentient).dR()) { - entityinsentient.setGoalTarget(entityliving, EntityTargetEvent.TargetReason.TARGET_ATTACKED_ENTITY, true); // CraftBukkit - } - - } - } - - static class g extends PathfinderGoal { - - private final EntityPanda a; - private int b; - - public g(EntityPanda entitypanda) { - this.a = entitypanda; - } - - @Override - public boolean a() { - return this.b < this.a.ticksLived && this.a.ej() && this.a.eq() && this.a.random.nextInt(400) == 1; - } - - @Override - public boolean b() { - return !this.a.isInWater() && (this.a.ej() || this.a.random.nextInt(600) != 1) ? this.a.random.nextInt(2000) != 1 : false; - } - - @Override - public void c() { - this.a.s(true); - this.b = 0; - } - - @Override - public void d() { - this.a.s(false); - this.b = this.a.ticksLived + 200; - } - } - - class l extends PathfinderGoal { - - private int b; - - public l() { - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - if (this.b <= EntityPanda.this.ticksLived && !EntityPanda.this.isBaby() && !EntityPanda.this.isInWater() && EntityPanda.this.eq() && EntityPanda.this.dV() <= 0) { - List list = EntityPanda.this.world.a(EntityItem.class, EntityPanda.this.getBoundingBox().grow(6.0D, 6.0D, 6.0D), EntityPanda.PICKUP_PREDICATE); - - return !list.isEmpty() || !EntityPanda.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty(); - } else { - return false; - } - } - - @Override - public boolean b() { - return !EntityPanda.this.isInWater() && (EntityPanda.this.ej() || EntityPanda.this.random.nextInt(600) != 1) ? EntityPanda.this.random.nextInt(2000) != 1 : false; - } - - @Override - public void e() { - if (!EntityPanda.this.dX() && !EntityPanda.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty()) { - EntityPanda.this.eB(); - } - - } - - @Override - public void c() { - List list = EntityPanda.this.world.a(EntityItem.class, EntityPanda.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityPanda.PICKUP_PREDICATE); - - if (!list.isEmpty() && EntityPanda.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty()) { - EntityPanda.this.getNavigation().a((Entity) list.get(0), 1.2000000476837158D); - } else if (!EntityPanda.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty()) { - EntityPanda.this.eB(); - } - - this.b = 0; - } - - @Override - public void d() { - ItemStack itemstack = EntityPanda.this.getEquipment(EnumItemSlot.MAINHAND); - - if (!itemstack.isEmpty()) { - EntityPanda.this.a(itemstack); - EntityPanda.this.setSlot(EnumItemSlot.MAINHAND, ItemStack.a); - int i = EntityPanda.this.ej() ? EntityPanda.this.random.nextInt(50) + 10 : EntityPanda.this.random.nextInt(150) + 10; - - this.b = EntityPanda.this.ticksLived + i * 20; - } - - EntityPanda.this.r(false); - } - } - - static class c extends PathfinderGoalAvoidTarget { - - private final EntityPanda i; - - public c(EntityPanda entitypanda, Class oclass, float f, double d0, double d1) { - // Predicate predicate = IEntitySelector.f; // CraftBukkit - decompile error - - super(entitypanda, oclass, f, d0, d1, IEntitySelector.f::test); // CraftBukkit - decompile error - this.i = entitypanda; - } - - @Override - public boolean a() { - return this.i.ek() && this.i.eq() && super.a(); - } - } - - static class d extends PathfinderGoalBreed { - - private static final PathfinderTargetCondition d = (new PathfinderTargetCondition()).a(8.0D).b().a(); - private final EntityPanda e; - private int f; - - public d(EntityPanda entitypanda, double d0) { - super(entitypanda, d0); - this.e = entitypanda; - } - - @Override - public boolean a() { - if (super.a() && this.e.dV() == 0) { - if (!this.h()) { - if (this.f <= this.e.ticksLived) { - this.e.s(32); - this.f = this.e.ticksLived + 600; - if (this.e.df()) { - EntityHuman entityhuman = this.b.a(d, (EntityLiving) this.e); // CraftBukkit - decompile error - - this.e.setGoalTarget(entityhuman, EntityTargetEvent.TargetReason.CLOSEST_PLAYER, true); // CraftBukkit - } - } - - return false; - } else { - return true; - } - } else { - return false; - } - } - - private boolean h() { - BlockPosition blockposition = new BlockPosition(this.e); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 8; ++j) { - for (int k = 0; k <= j; k = k > 0 ? -k : 1 - k) { - for (int l = k < j && k > -j ? j : 0; l <= j; l = l > 0 ? -l : 1 - l) { - blockposition_mutableblockposition.g(blockposition).e(k, i, l); - if (this.b.getType(blockposition_mutableblockposition).getBlock() == Blocks.BAMBOO) { - return true; - } - } - } - } - } - - return false; - } - } - - static class m extends PathfinderGoal { - - private final EntityPanda a; - - public m(EntityPanda entitypanda) { - this.a = entitypanda; - } - - @Override - public boolean a() { - return this.a.isBaby() && this.a.eq() ? (this.a.en() && this.a.random.nextInt(500) == 1 ? true : this.a.random.nextInt(6000) == 1) : false; - } - - @Override - public boolean b() { - return false; - } - - @Override - public void c() { - this.a.u(true); - } - } - - static class k extends PathfinderGoal { - - private final EntityPanda a; - - public k(EntityPanda entitypanda) { - this.a = entitypanda; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK, PathfinderGoal.Type.JUMP)); - } - - @Override - public boolean a() { - if ((this.a.isBaby() || this.a.el()) && this.a.onGround) { - if (!this.a.eq()) { - return false; - } else { - float f = this.a.yaw * 0.017453292F; - int i = 0; - int j = 0; - float f1 = -MathHelper.sin(f); - float f2 = MathHelper.cos(f); - - if ((double) Math.abs(f1) > 0.5D) { - i = (int) ((float) i + f1 / Math.abs(f1)); - } - - if ((double) Math.abs(f2) > 0.5D) { - j = (int) ((float) j + f2 / Math.abs(f2)); - } - - return this.a.world.getType((new BlockPosition(this.a)).b(i, -1, j)).isAir() ? true : (this.a.el() && this.a.random.nextInt(60) == 1 ? true : this.a.random.nextInt(500) == 1); - } - } else { - return false; - } - } - - @Override - public boolean b() { - return false; - } - - @Override - public void c() { - this.a.v(true); - } - - @Override - public boolean C_() { - return false; - } - } - - static class h extends PathfinderGoalLookAtPlayer { - - private final EntityPanda f; - - public h(EntityPanda entitypanda, Class oclass, float f) { - super(entitypanda, oclass, f); - this.f = entitypanda; - } - - @Override - public boolean a() { - return this.f.eq() && super.a(); - } - } - - static class b extends PathfinderGoalMeleeAttack { - - private final EntityPanda d; - - public b(EntityPanda entitypanda, double d0, boolean flag) { - super(entitypanda, d0, flag); - this.d = entitypanda; - } - - @Override - public boolean a() { - return this.d.eq() && super.a(); - } - } - - static class e implements GroupDataEntity { - - private e() {} - } - - static class i extends ControllerMove { - - private final EntityPanda i; - - public i(EntityPanda entitypanda) { - super(entitypanda); - this.i = entitypanda; - } - - @Override - public void a() { - if (this.i.eq()) { - super.a(); - } - } - } - - public static enum Gene { - - NORMAL(0, "normal", false), LAZY(1, "lazy", false), WORRIED(2, "worried", false), PLAYFUL(3, "playful", false), BROWN(4, "brown", true), WEAK(5, "weak", true), AGGRESSIVE(6, "aggressive", false); - - private static final EntityPanda.Gene[] h = (EntityPanda.Gene[]) Arrays.stream(values()).sorted(Comparator.comparingInt(EntityPanda.Gene::a)).toArray((i) -> { - return new EntityPanda.Gene[i]; - }); - private final int i; - private final String j; - private final boolean k; - - private Gene(int i, String s, boolean flag) { - this.i = i; - this.j = s; - this.k = flag; - } - - public int a() { - return this.i; - } - - public String b() { - return this.j; - } - - public boolean isRecessive() { - return this.k; - } - - private static EntityPanda.Gene b(EntityPanda.Gene entitypanda_gene, EntityPanda.Gene entitypanda_gene1) { - return entitypanda_gene.isRecessive() ? (entitypanda_gene == entitypanda_gene1 ? entitypanda_gene : EntityPanda.Gene.NORMAL) : entitypanda_gene; - } - - public static EntityPanda.Gene a(int i) { - if (i < 0 || i >= EntityPanda.Gene.h.length) { - i = 0; - } - - return EntityPanda.Gene.h[i]; - } - - public static EntityPanda.Gene a(String s) { - EntityPanda.Gene[] aentitypanda_gene = values(); - int i = aentitypanda_gene.length; - - for (int j = 0; j < i; ++j) { - EntityPanda.Gene entitypanda_gene = aentitypanda_gene[j]; - - if (entitypanda_gene.j.equals(s)) { - return entitypanda_gene; - } - } - - return EntityPanda.Gene.NORMAL; - } - - public static EntityPanda.Gene a(Random random) { - int i = random.nextInt(16); - - return i == 0 ? EntityPanda.Gene.LAZY : (i == 1 ? EntityPanda.Gene.WORRIED : (i == 2 ? EntityPanda.Gene.PLAYFUL : (i == 4 ? EntityPanda.Gene.AGGRESSIVE : (i < 9 ? EntityPanda.Gene.WEAK : (i < 11 ? EntityPanda.Gene.BROWN : EntityPanda.Gene.NORMAL))))); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityParrot.java b/src/main/java/net/minecraft/server/EntityParrot.java deleted file mode 100644 index a7cdb5e7a..000000000 --- a/src/main/java/net/minecraft/server/EntityParrot.java +++ /dev/null @@ -1,369 +0,0 @@ -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.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntityParrot extends EntityPerchable implements EntityBird { - - private static final DataWatcherObject bH = DataWatcher.a(EntityParrot.class, DataWatcherRegistry.b); - private static final Predicate bI = new Predicate() { - public boolean test(@Nullable EntityInsentient entityinsentient) { - return entityinsentient != null && EntityParrot.bL.containsKey(entityinsentient.getEntityType()); - } - }; - private static final Item bJ = Items.COOKIE; - private static final Set bK = Sets.newHashSet(new Item[]{Items.WHEAT_SEEDS, Items.MELON_SEEDS, Items.PUMPKIN_SEEDS, Items.BEETROOT_SEEDS}); - private static final Map, SoundEffect> bL = (Map) SystemUtils.a(Maps.newHashMap(), (hashmap) -> { // CraftBukkit - decompile error - hashmap.put(EntityTypes.BLAZE, SoundEffects.ENTITY_PARROT_IMITATE_BLAZE); - hashmap.put(EntityTypes.CAVE_SPIDER, SoundEffects.ENTITY_PARROT_IMITATE_SPIDER); - hashmap.put(EntityTypes.CREEPER, SoundEffects.ENTITY_PARROT_IMITATE_CREEPER); - hashmap.put(EntityTypes.DROWNED, SoundEffects.ENTITY_PARROT_IMITATE_DROWNED); - hashmap.put(EntityTypes.ELDER_GUARDIAN, SoundEffects.ENTITY_PARROT_IMITATE_ELDER_GUARDIAN); - hashmap.put(EntityTypes.ENDER_DRAGON, SoundEffects.ENTITY_PARROT_IMITATE_ENDER_DRAGON); - hashmap.put(EntityTypes.ENDERMAN, SoundEffects.ENTITY_PARROT_IMITATE_ENDERMAN); - hashmap.put(EntityTypes.ENDERMITE, SoundEffects.ENTITY_PARROT_IMITATE_ENDERMITE); - hashmap.put(EntityTypes.EVOKER, SoundEffects.ENTITY_PARROT_IMITATE_EVOKER); - hashmap.put(EntityTypes.GHAST, SoundEffects.ENTITY_PARROT_IMITATE_GHAST); - hashmap.put(EntityTypes.GUARDIAN, SoundEffects.ENTITY_PARROT_IMITATE_GUARDIAN); - hashmap.put(EntityTypes.HUSK, SoundEffects.ENTITY_PARROT_IMITATE_HUSK); - hashmap.put(EntityTypes.ILLUSIONER, SoundEffects.ENTITY_PARROT_IMITATE_ILLUSIONER); - hashmap.put(EntityTypes.MAGMA_CUBE, SoundEffects.ENTITY_PARROT_IMITATE_MAGMA_CUBE); - hashmap.put(EntityTypes.ZOMBIE_PIGMAN, SoundEffects.ENTITY_PARROT_IMITATE_ZOMBIE_PIGMAN); - hashmap.put(EntityTypes.PANDA, SoundEffects.ENTITY_PARROT_IMITATE_PANDA); - hashmap.put(EntityTypes.PHANTOM, SoundEffects.ENTITY_PARROT_IMITATE_PHANTOM); - hashmap.put(EntityTypes.PILLAGER, SoundEffects.ENTITY_PARROT_IMITATE_PILLAGER); - hashmap.put(EntityTypes.POLAR_BEAR, SoundEffects.ENTITY_PARROT_IMITATE_POLAR_BEAR); - hashmap.put(EntityTypes.RAVAGER, SoundEffects.ENTITY_PARROT_IMITATE_RAVAGER); - hashmap.put(EntityTypes.SHULKER, SoundEffects.ENTITY_PARROT_IMITATE_SHULKER); - hashmap.put(EntityTypes.SILVERFISH, SoundEffects.ENTITY_PARROT_IMITATE_SILVERFISH); - hashmap.put(EntityTypes.SKELETON, SoundEffects.ENTITY_PARROT_IMITATE_SKELETON); - hashmap.put(EntityTypes.SLIME, SoundEffects.ENTITY_PARROT_IMITATE_SLIME); - hashmap.put(EntityTypes.SPIDER, SoundEffects.ENTITY_PARROT_IMITATE_SPIDER); - hashmap.put(EntityTypes.STRAY, SoundEffects.ENTITY_PARROT_IMITATE_STRAY); - hashmap.put(EntityTypes.VEX, SoundEffects.ENTITY_PARROT_IMITATE_VEX); - hashmap.put(EntityTypes.VINDICATOR, SoundEffects.ENTITY_PARROT_IMITATE_VINDICATOR); - hashmap.put(EntityTypes.WITCH, SoundEffects.ENTITY_PARROT_IMITATE_WITCH); - hashmap.put(EntityTypes.WITHER, SoundEffects.ENTITY_PARROT_IMITATE_WITHER); - hashmap.put(EntityTypes.WITHER_SKELETON, SoundEffects.ENTITY_PARROT_IMITATE_WITHER_SKELETON); - hashmap.put(EntityTypes.WOLF, SoundEffects.ENTITY_PARROT_IMITATE_WOLF); - hashmap.put(EntityTypes.ZOMBIE, SoundEffects.ENTITY_PARROT_IMITATE_ZOMBIE); - hashmap.put(EntityTypes.ZOMBIE_VILLAGER, SoundEffects.ENTITY_PARROT_IMITATE_ZOMBIE_VILLAGER); - }); - public float bC; - public float bD; - public float bE; - public float bF; - public float bG = 1.0F; - private boolean bM; - private BlockPosition bN; - - public EntityParrot(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.moveController = new ControllerMoveFlying(this); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.setVariant(this.random.nextInt(5)); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - @Override - protected void initPathfinder() { - this.goalSit = new PathfinderGoalSit(this); - this.goalSelector.a(0, new PathfinderGoalPanic(this, 1.25D)); - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(1, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); - this.goalSelector.a(2, this.goalSit); - this.goalSelector.a(2, new PathfinderGoalFollowOwnerParrot(this, 1.0D, 5.0F, 1.0F)); - this.goalSelector.a(2, new PathfinderGoalRandomFly(this, 1.0D)); - this.goalSelector.a(3, new PathfinderGoalPerch(this)); - this.goalSelector.a(3, new PathfinderGoalFollowEntity(this, 1.0D, 3.0F, 7.0F)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeMap().b(GenericAttributes.FLYING_SPEED); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(6.0D); - this.getAttributeInstance(GenericAttributes.FLYING_SPEED).setValue(0.4000000059604645D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.20000000298023224D); - } - - @Override - protected NavigationAbstract b(World world) { - NavigationFlying navigationflying = new NavigationFlying(this, world); - - navigationflying.a(false); - navigationflying.d(true); - navigationflying.b(true); - return navigationflying; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * 0.6F; - } - - @Override - public void movementTick() { - b(this.world, (Entity) this); - if (this.bN == null || !this.bN.a((IPosition) this.getPositionVector(), 3.46D) || this.world.getType(this.bN).getBlock() != Blocks.JUKEBOX) { - this.bM = false; - this.bN = null; - } - - super.movementTick(); - this.ei(); - } - - private void ei() { - this.bF = this.bC; - this.bE = this.bD; - this.bD = (float) ((double) this.bD + (double) (!this.onGround && !this.isPassenger() ? 4 : -1) * 0.3D); - this.bD = MathHelper.a(this.bD, 0.0F, 1.0F); - if (!this.onGround && this.bG < 1.0F) { - this.bG = 1.0F; - } - - this.bG = (float) ((double) this.bG * 0.9D); - Vec3D vec3d = this.getMot(); - - if (!this.onGround && vec3d.y < 0.0D) { - this.setMot(vec3d.d(1.0D, 0.6D, 1.0D)); - } - - this.bC += this.bG * 2.0F; - } - - private static boolean b(World world, Entity entity) { - if (entity.isAlive() && !entity.isSilent() && world.random.nextInt(50) == 0) { - List list = world.a(EntityInsentient.class, entity.getBoundingBox().g(20.0D), EntityParrot.bI); - - if (!list.isEmpty()) { - EntityInsentient entityinsentient = (EntityInsentient) list.get(world.random.nextInt(list.size())); - - if (!entityinsentient.isSilent()) { - SoundEffect soundeffect = b(entityinsentient.getEntityType()); - - world.playSound((EntityHuman) null, entity.locX, entity.locY, entity.locZ, soundeffect, entity.getSoundCategory(), 0.7F, b(world.random)); - return true; - } - } - - return false; - } else { - return false; - } - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (!this.isTamed() && EntityParrot.bK.contains(itemstack.getItem())) { - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - if (!this.isSilent()) { - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PARROT_EAT, this.getSoundCategory(), 1.0F, 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.2F); - } - - if (!this.world.isClientSide) { - if (this.random.nextInt(10) == 0 && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityTameEvent(this, entityhuman).isCancelled()) { // CraftBukkit - this.tame(entityhuman); - this.r(true); - this.world.broadcastEntityEffect(this, (byte) 7); - } else { - this.r(false); - this.world.broadcastEntityEffect(this, (byte) 6); - } - } - - return true; - } else if (itemstack.getItem() == EntityParrot.bJ) { - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - this.addEffect(new MobEffect(MobEffects.POISON, 900), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.FOOD); // CraftBukkit - if (entityhuman.isCreative() || !this.isInvulnerable()) { - this.damageEntity(DamageSource.playerAttack(entityhuman), Float.MAX_VALUE); - } - - return true; - } else { - if (!this.world.isClientSide && !this.E_() && this.isTamed() && this.h((EntityLiving) entityhuman)) { - this.goalSit.setSitting(!this.isSitting()); - } - - return super.a(entityhuman, enumhand); - } - } - - @Override - public boolean i(ItemStack itemstack) { - return false; - } - - public static boolean c(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - Block block = generatoraccess.getType(blockposition.down()).getBlock(); - - return (block.a(TagsBlock.LEAVES) || block == Blocks.GRASS_BLOCK || block instanceof BlockLogAbstract || block == Blocks.AIR) && generatoraccess.getLightLevel(blockposition, 0) > 8; - } - - @Override - public void b(float f, float f1) {} - - @Override - protected void a(double d0, boolean flag, IBlockData iblockdata, BlockPosition blockposition) {} - - @Override - public boolean mate(EntityAnimal entityanimal) { - return false; - } - - @Nullable - @Override - public EntityAgeable createChild(EntityAgeable entityageable) { - return null; - } - - public static void a(World world, Entity entity) { - if (!entity.isSilent() && !b(world, entity) && world.random.nextInt(200) == 0) { - world.playSound((EntityHuman) null, entity.locX, entity.locY, entity.locZ, a(world.random), entity.getSoundCategory(), 1.0F, b(world.random)); - } - - } - - @Override - public boolean C(Entity entity) { - return entity.damageEntity(DamageSource.mobAttack(this), 3.0F); - } - - @Nullable - @Override - public SoundEffect getSoundAmbient() { - return a(this.random); - } - - private static SoundEffect a(Random random) { - if (random.nextInt(1000) == 0) { - List> list = Lists.newArrayList(EntityParrot.bL.keySet()); - - return b((EntityTypes) list.get(random.nextInt(list.size()))); - } else { - return SoundEffects.ENTITY_PARROT_AMBIENT; - } - } - - public static SoundEffect b(EntityTypes entitytypes) { - return (SoundEffect) EntityParrot.bL.getOrDefault(entitytypes, SoundEffects.ENTITY_PARROT_AMBIENT); - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_PARROT_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_PARROT_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_PARROT_STEP, 0.15F, 1.0F); - } - - @Override - protected float e(float f) { - this.a(SoundEffects.ENTITY_PARROT_FLY, 0.15F, 1.0F); - return f + this.bD / 2.0F; - } - - @Override - protected boolean am() { - return true; - } - - @Override - protected float cV() { - return b(this.random); - } - - private static float b(Random random) { - return (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F; - } - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.NEUTRAL; - } - - @Override - public boolean isCollidable() { - return true; - } - - @Override - protected void D(Entity entity) { - if (!(entity instanceof EntityHuman)) { - super.D(entity); - } - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - if (this.goalSit != null) { - // CraftBukkit - moved into EntityLiving.d(DamageSource, float) - // this.goalSit.setSitting(false); - } - - return super.damageEntity(damagesource, f); - } - } - - public int getVariant() { - return MathHelper.clamp((Integer) this.datawatcher.get(EntityParrot.bH), 0, 4); - } - - public void setVariant(int i) { - this.datawatcher.set(EntityParrot.bH, i); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityParrot.bH, 0); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("Variant", this.getVariant()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setVariant(nbttagcompound.getInt("Variant")); - } - - public boolean E_() { - return !this.onGround; - } -} diff --git a/src/main/java/net/minecraft/server/EntityPhantom.java b/src/main/java/net/minecraft/server/EntityPhantom.java deleted file mode 100644 index e5d032d02..000000000 --- a/src/main/java/net/minecraft/server/EntityPhantom.java +++ /dev/null @@ -1,529 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -public class EntityPhantom extends EntityFlying implements IMonster { - - private static final DataWatcherObject b = DataWatcher.a(EntityPhantom.class, DataWatcherRegistry.b); - private Vec3D c; - private BlockPosition d; - private EntityPhantom.AttackPhase bz; - - public EntityPhantom(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.c = Vec3D.a; - this.d = BlockPosition.ZERO; - this.bz = EntityPhantom.AttackPhase.CIRCLE; - this.f = 5; - this.moveController = new EntityPhantom.g(this); - this.lookController = new EntityPhantom.f(this); - } - - @Override - protected EntityAIBodyControl o() { - return new EntityPhantom.d(this); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(1, new EntityPhantom.c()); - this.goalSelector.a(2, new EntityPhantom.i()); - this.goalSelector.a(3, new EntityPhantom.e()); - this.targetSelector.a(1, new EntityPhantom.b()); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityPhantom.b, 0); - } - - public void setSize(int i) { - this.datawatcher.set(EntityPhantom.b, MathHelper.clamp(i, 0, 64)); - } - - private void dU() { - this.updateSize(); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue((double) (6 + this.getSize())); - } - - public int getSize() { - return (Integer) this.datawatcher.get(EntityPhantom.b); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * 0.35F; - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityPhantom.b.equals(datawatcherobject)) { - this.dU(); - } - - super.a(datawatcherobject); - } - - @Override - public void tick() { - super.tick(); - if (this.world.isClientSide) { - float f = MathHelper.cos((float) (this.getId() * 3 + this.ticksLived) * 0.13F + 3.1415927F); - float f1 = MathHelper.cos((float) (this.getId() * 3 + this.ticksLived + 1) * 0.13F + 3.1415927F); - - if (f > 0.0F && f1 <= 0.0F) { - this.world.a(this.locX, this.locY, this.locZ, SoundEffects.ENTITY_PHANTOM_FLAP, this.getSoundCategory(), 0.95F + this.random.nextFloat() * 0.05F, 0.95F + this.random.nextFloat() * 0.05F, false); - } - - int i = this.getSize(); - float f2 = MathHelper.cos(this.yaw * 0.017453292F) * (1.3F + 0.21F * (float) i); - float f3 = MathHelper.sin(this.yaw * 0.017453292F) * (1.3F + 0.21F * (float) i); - float f4 = (0.3F + f * 0.45F) * ((float) i * 0.2F + 1.0F); - - this.world.addParticle(Particles.MYCELIUM, this.locX + (double) f2, this.locY + (double) f4, this.locZ + (double) f3, 0.0D, 0.0D, 0.0D); - this.world.addParticle(Particles.MYCELIUM, this.locX - (double) f2, this.locY + (double) f4, this.locZ - (double) f3, 0.0D, 0.0D, 0.0D); - } - - if (!this.world.isClientSide && this.world.getDifficulty() == EnumDifficulty.PEACEFUL) { - this.die(); - } - - } - - @Override - public void movementTick() { - if (this.isAlive() && this.dS()) { - this.setOnFire(8); - } - - super.movementTick(); - } - - @Override - protected void mobTick() { - super.mobTick(); - } - - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.d = (new BlockPosition(this)).up(5); - this.setSize(0); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKey("AX")) { - this.d = new BlockPosition(nbttagcompound.getInt("AX"), nbttagcompound.getInt("AY"), nbttagcompound.getInt("AZ")); - } - - this.setSize(nbttagcompound.getInt("Size")); - // Paper start - if (nbttagcompound.hasUUID("Paper.SpawningEntity")) { - this.spawningEntity = nbttagcompound.getUUID("Paper.SpawningEntity"); - } - // Paper end - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("AX", this.d.getX()); - nbttagcompound.setInt("AY", this.d.getY()); - nbttagcompound.setInt("AZ", this.d.getZ()); - nbttagcompound.setInt("Size", this.getSize()); - // Paper start - if (this.spawningEntity != null) { - nbttagcompound.setUUID("Paper.SpawningEntity", this.spawningEntity); - } - // Paper end - } - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.HOSTILE; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_PHANTOM_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_PHANTOM_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_PHANTOM_DEATH; - } - - @Override - public EnumMonsterType getMonsterType() { - return EnumMonsterType.UNDEAD; - } - - @Override - protected float getSoundVolume() { - return 1.0F; - } - - @Override - public boolean a(EntityTypes entitytypes) { - return true; - } - - @Override - public EntitySize a(EntityPose entitypose) { - int i = this.getSize(); - EntitySize entitysize = super.a(entitypose); - float f = (entitysize.width + 0.2F * (float) i) / entitysize.width; - - return entitysize.a(f); - } - - // Paper start - java.util.UUID spawningEntity; - - public java.util.UUID getSpawningEntity() { - return spawningEntity; - } - // Paper end - - class b extends PathfinderGoal { - - private final PathfinderTargetCondition b; - private int c; - - private b() { - this.b = (new PathfinderTargetCondition()).a(64.0D); - this.c = 20; - } - - @Override - public boolean a() { - if (this.c > 0) { - --this.c; - return false; - } else { - this.c = 60; - List list = EntityPhantom.this.world.a(this.b, (EntityLiving) EntityPhantom.this, EntityPhantom.this.getBoundingBox().grow(16.0D, 64.0D, 16.0D)); - - if (!list.isEmpty()) { - list.sort((entityhuman, entityhuman1) -> { - return entityhuman.locY > entityhuman1.locY ? -1 : 1; - }); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman = (EntityHuman) iterator.next(); - - if (EntityPhantom.this.a((EntityLiving) entityhuman, PathfinderTargetCondition.a)) { - EntityPhantom.this.setGoalTarget(entityhuman, org.bukkit.event.entity.EntityTargetEvent.TargetReason.CLOSEST_PLAYER, true); // CraftBukkit - reason - return true; - } - } - } - - return false; - } - } - - @Override - public boolean b() { - EntityLiving entityliving = EntityPhantom.this.getGoalTarget(); - - return entityliving != null ? EntityPhantom.this.a(entityliving, PathfinderTargetCondition.a) : false; - } - } - - class c extends PathfinderGoal { - - private int b; - - private c() {} - - @Override - public boolean a() { - EntityLiving entityliving = EntityPhantom.this.getGoalTarget(); - - return entityliving != null ? EntityPhantom.this.a(EntityPhantom.this.getGoalTarget(), PathfinderTargetCondition.a) : false; - } - - @Override - public void c() { - this.b = 10; - EntityPhantom.this.bz = EntityPhantom.AttackPhase.CIRCLE; - this.g(); - } - - @Override - public void d() { - EntityPhantom.this.d = EntityPhantom.this.world.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, EntityPhantom.this.d).up(10 + EntityPhantom.this.random.nextInt(20)); - } - - @Override - public void e() { - if (EntityPhantom.this.bz == EntityPhantom.AttackPhase.CIRCLE) { - --this.b; - if (this.b <= 0) { - EntityPhantom.this.bz = EntityPhantom.AttackPhase.SWOOP; - this.g(); - this.b = (8 + EntityPhantom.this.random.nextInt(4)) * 20; - EntityPhantom.this.a(SoundEffects.ENTITY_PHANTOM_SWOOP, 10.0F, 0.95F + EntityPhantom.this.random.nextFloat() * 0.1F); - } - } - - } - - private void g() { - EntityPhantom.this.d = (new BlockPosition(EntityPhantom.this.getGoalTarget())).up(20 + EntityPhantom.this.random.nextInt(20)); - if (EntityPhantom.this.d.getY() < EntityPhantom.this.world.getSeaLevel()) { - EntityPhantom.this.d = new BlockPosition(EntityPhantom.this.d.getX(), EntityPhantom.this.world.getSeaLevel() + 1, EntityPhantom.this.d.getZ()); - } - - } - } - - class i extends EntityPhantom.h { - - private i() { - super(); - } - - @Override - public boolean a() { - return EntityPhantom.this.getGoalTarget() != null && EntityPhantom.this.bz == EntityPhantom.AttackPhase.SWOOP; - } - - @Override - public boolean b() { - EntityLiving entityliving = EntityPhantom.this.getGoalTarget(); - - if (entityliving == null) { - return false; - } else if (!entityliving.isAlive()) { - return false; - } else if (entityliving instanceof EntityHuman && (((EntityHuman) entityliving).isSpectator() || ((EntityHuman) entityliving).isCreative())) { - return false; - } else if (!this.a()) { - return false; - } else { - if (EntityPhantom.this.ticksLived % 20 == 0) { - List list = EntityPhantom.this.world.a(EntityCat.class, EntityPhantom.this.getBoundingBox().g(16.0D), IEntitySelector.a); - - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityCat entitycat = (EntityCat) iterator.next(); - - entitycat.ej(); - } - - return false; - } - } - - return true; - } - } - - @Override - public void c() {} - - @Override - public void d() { - EntityPhantom.this.setGoalTarget((EntityLiving) null); - EntityPhantom.this.bz = EntityPhantom.AttackPhase.CIRCLE; - } - - @Override - public void e() { - EntityLiving entityliving = EntityPhantom.this.getGoalTarget(); - - EntityPhantom.this.c = new Vec3D(entityliving.locX, entityliving.locY + (double) entityliving.getHeight() * 0.5D, entityliving.locZ); - if (EntityPhantom.this.getBoundingBox().g(0.20000000298023224D).c(entityliving.getBoundingBox())) { - EntityPhantom.this.C(entityliving); - EntityPhantom.this.bz = EntityPhantom.AttackPhase.CIRCLE; - EntityPhantom.this.world.triggerEffect(1039, new BlockPosition(EntityPhantom.this), 0); - } else if (EntityPhantom.this.positionChanged || EntityPhantom.this.hurtTicks > 0) { - EntityPhantom.this.bz = EntityPhantom.AttackPhase.CIRCLE; - } - - } - } - - class e extends EntityPhantom.h { - - private float c; - private float d; - private float e; - private float f; - - private e() { - super(); - } - - @Override - public boolean a() { - return EntityPhantom.this.getGoalTarget() == null || EntityPhantom.this.bz == EntityPhantom.AttackPhase.CIRCLE; - } - - @Override - public void c() { - this.d = 5.0F + EntityPhantom.this.random.nextFloat() * 10.0F; - this.e = -4.0F + EntityPhantom.this.random.nextFloat() * 9.0F; - this.f = EntityPhantom.this.random.nextBoolean() ? 1.0F : -1.0F; - this.h(); - } - - @Override - public void e() { - if (EntityPhantom.this.random.nextInt(350) == 0) { - this.e = -4.0F + EntityPhantom.this.random.nextFloat() * 9.0F; - } - - if (EntityPhantom.this.random.nextInt(250) == 0) { - ++this.d; - if (this.d > 15.0F) { - this.d = 5.0F; - this.f = -this.f; - } - } - - if (EntityPhantom.this.random.nextInt(450) == 0) { - this.c = EntityPhantom.this.random.nextFloat() * 2.0F * 3.1415927F; - this.h(); - } - - if (this.g()) { - this.h(); - } - - if (EntityPhantom.this.c.y < EntityPhantom.this.locY && !EntityPhantom.this.world.isEmpty((new BlockPosition(EntityPhantom.this)).down(1))) { - this.e = Math.max(1.0F, this.e); - this.h(); - } - - if (EntityPhantom.this.c.y > EntityPhantom.this.locY && !EntityPhantom.this.world.isEmpty((new BlockPosition(EntityPhantom.this)).up(1))) { - this.e = Math.min(-1.0F, this.e); - this.h(); - } - - } - - private void h() { - if (BlockPosition.ZERO.equals(EntityPhantom.this.d)) { - EntityPhantom.this.d = new BlockPosition(EntityPhantom.this); - } - - this.c += this.f * 15.0F * 0.017453292F; - EntityPhantom.this.c = (new Vec3D(EntityPhantom.this.d)).add((double) (this.d * MathHelper.cos(this.c)), (double) (-4.0F + this.e), (double) (this.d * MathHelper.sin(this.c))); - } - } - - abstract class h extends PathfinderGoal { - - public h() { - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - protected boolean g() { - return EntityPhantom.this.c.c(EntityPhantom.this.locX, EntityPhantom.this.locY, EntityPhantom.this.locZ) < 4.0D; - } - } - - class f extends ControllerLook { - - public f(EntityInsentient entityinsentient) { - super(entityinsentient); - } - - @Override - public void a() {} - } - - class d extends EntityAIBodyControl { - - public d(EntityInsentient entityinsentient) { - super(entityinsentient); - } - - @Override - public void a() { - EntityPhantom.this.aM = EntityPhantom.this.aK; - EntityPhantom.this.aK = EntityPhantom.this.yaw; - } - } - - class g extends ControllerMove { - - private float j = 0.1F; - - public g(EntityInsentient entityinsentient) { - super(entityinsentient); - } - - @Override - public void a() { - if (EntityPhantom.this.positionChanged) { - EntityPhantom.this.yaw += 180.0F; - this.j = 0.1F; - } - - float f = (float) (EntityPhantom.this.c.x - EntityPhantom.this.locX); - float f1 = (float) (EntityPhantom.this.c.y - EntityPhantom.this.locY); - float f2 = (float) (EntityPhantom.this.c.z - EntityPhantom.this.locZ); - double d0 = (double) MathHelper.c(f * f + f2 * f2); - double d1 = 1.0D - (double) MathHelper.e(f1 * 0.7F) / d0; - - f = (float) ((double) f * d1); - f2 = (float) ((double) f2 * d1); - d0 = (double) MathHelper.c(f * f + f2 * f2); - double d2 = (double) MathHelper.c(f * f + f2 * f2 + f1 * f1); - float f3 = EntityPhantom.this.yaw; - float f4 = (float) MathHelper.d((double) f2, (double) f); - float f5 = MathHelper.g(EntityPhantom.this.yaw + 90.0F); - float f6 = MathHelper.g(f4 * 57.295776F); - - EntityPhantom.this.yaw = MathHelper.d(f5, f6, 4.0F) - 90.0F; - EntityPhantom.this.aK = EntityPhantom.this.yaw; - if (MathHelper.d(f3, EntityPhantom.this.yaw) < 3.0F) { - this.j = MathHelper.c(this.j, 1.8F, 0.005F * (1.8F / this.j)); - } else { - this.j = MathHelper.c(this.j, 0.2F, 0.025F); - } - - float f7 = (float) (-(MathHelper.d((double) (-f1), d0) * 57.2957763671875D)); - - EntityPhantom.this.pitch = f7; - float f8 = EntityPhantom.this.yaw + 90.0F; - double d3 = (double) (this.j * MathHelper.cos(f8 * 0.017453292F)) * Math.abs((double) f / d2); - double d4 = (double) (this.j * MathHelper.sin(f8 * 0.017453292F)) * Math.abs((double) f2 / d2); - double d5 = (double) (this.j * MathHelper.sin(f7 * 0.017453292F)) * Math.abs((double) f1 / d2); - Vec3D vec3d = EntityPhantom.this.getMot(); - - EntityPhantom.this.setMot(vec3d.e((new Vec3D(d3, d5, d4)).d(vec3d).a(0.2D))); - } - } - - static enum AttackPhase { - - CIRCLE, SWOOP; - - private AttackPhase() {} - } -} diff --git a/src/main/java/net/minecraft/server/EntityPig.java b/src/main/java/net/minecraft/server/EntityPig.java deleted file mode 100644 index 7136e274a..000000000 --- a/src/main/java/net/minecraft/server/EntityPig.java +++ /dev/null @@ -1,257 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -// CraftBukkit end - -public class EntityPig extends EntityAnimal { - - private static final DataWatcherObject bz = DataWatcher.a(EntityPig.class, DataWatcherRegistry.i); - private static final DataWatcherObject bA = DataWatcher.a(EntityPig.class, DataWatcherRegistry.b); - private static final RecipeItemStack bB = RecipeItemStack.a(Items.CARROT, Items.POTATO, Items.BEETROOT); - private boolean bC; - private int bD; - private int bE; - - public EntityPig(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(1, new PathfinderGoalPanic(this, 1.25D)); - this.goalSelector.a(3, new PathfinderGoalBreed(this, 1.0D)); - this.goalSelector.a(4, new PathfinderGoalTempt(this, 1.2D, RecipeItemStack.a(Items.CARROT_ON_A_STICK), false)); - this.goalSelector.a(4, new PathfinderGoalTempt(this, 1.2D, false, EntityPig.bB)); - this.goalSelector.a(5, new PathfinderGoalFollowParent(this, 1.1D)); - this.goalSelector.a(6, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); - this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); - } - - @Nullable - @Override - public Entity getRidingPassenger() { - return this.getPassengers().isEmpty() ? null : (Entity) this.getPassengers().get(0); - } - - @Override - public boolean dD() { - Entity entity = this.getRidingPassenger(); - - if (!(entity instanceof EntityHuman)) { - return false; - } else { - EntityHuman entityhuman = (EntityHuman) entity; - - return entityhuman.getItemInMainHand().getItem() == Items.CARROT_ON_A_STICK || entityhuman.getItemInOffHand().getItem() == Items.CARROT_ON_A_STICK; - } - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityPig.bA.equals(datawatcherobject) && this.world.isClientSide) { - this.bC = true; - this.bD = 0; - this.bE = (Integer) this.datawatcher.get(EntityPig.bA); - } - - super.a(datawatcherobject); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityPig.bz, false); - this.datawatcher.register(EntityPig.bA, 0); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("Saddle", this.hasSaddle()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setSaddle(nbttagcompound.getBoolean("Saddle")); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_PIG_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_PIG_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_PIG_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_PIG_STEP, 0.15F, 1.0F); - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - if (!super.a(entityhuman, enumhand)) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() == Items.NAME_TAG) { - itemstack.a(entityhuman, (EntityLiving) this, enumhand); - return true; - } else if (this.hasSaddle() && !this.isVehicle()) { - if (!this.world.isClientSide) { - entityhuman.startRiding(this); - } - - return true; - } else if (itemstack.getItem() == Items.SADDLE) { - itemstack.a(entityhuman, (EntityLiving) this, enumhand); - return true; - } else { - return false; - } - } else { - return true; - } - } - - @Override - protected void cF() { - super.cF(); - if (this.hasSaddle()) { - this.a((IMaterial) Items.SADDLE); - } - - } - - public boolean hasSaddle() { - return (Boolean) this.datawatcher.get(EntityPig.bz); - } - - public void setSaddle(boolean flag) { - if (flag) { - this.datawatcher.set(EntityPig.bz, true); - } else { - this.datawatcher.set(EntityPig.bz, false); - } - - } - - @Override - public void onLightningStrike(EntityLightning entitylightning) { - EntityPigZombie entitypigzombie = (EntityPigZombie) EntityTypes.ZOMBIE_PIGMAN.a(this.world); - - entitypigzombie.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.GOLDEN_SWORD)); - entitypigzombie.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, this.pitch); - entitypigzombie.setNoAI(this.isNoAI()); - if (this.hasCustomName()) { - entitypigzombie.setCustomName(this.getCustomName()); - entitypigzombie.setCustomNameVisible(this.getCustomNameVisible()); - } - - // Paper start - if (CraftEventFactory.callEntityZapEvent(this, entitylightning, entitypigzombie).isCancelled()) { - return; - } - // Paper end - - // CraftBukkit start - if (CraftEventFactory.callPigZapEvent(this, entitylightning, entitypigzombie).isCancelled()) { - return; - } - // CraftBukkit - added a reason for spawning this creature - this.world.addEntity(entitypigzombie, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.LIGHTNING); - // CraftBukkit end - this.die(); - } - - @Override - public void e(Vec3D vec3d) { - if (this.isAlive()) { - Entity entity = this.getPassengers().isEmpty() ? null : (Entity) this.getPassengers().get(0); - - if (this.isVehicle() && this.dD()) { - this.yaw = entity.yaw; - this.lastYaw = this.yaw; - this.pitch = entity.pitch * 0.5F; - this.setYawPitch(this.yaw, this.pitch); - this.aK = this.yaw; - this.aM = this.yaw; - this.K = 1.0F; - this.aO = this.db() * 0.1F; - if (this.bC && this.bD++ > this.bE) { - this.bC = false; - } - - if (this.ca()) { - float f = (float) this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue() * 0.225F; - - if (this.bC) { - f += f * 1.15F * MathHelper.sin((float) this.bD / (float) this.bE * 3.1415927F); - } - - this.o(f); - super.e(new Vec3D(0.0D, 0.0D, 1.0D)); - } else { - this.setMot(Vec3D.a); - } - - this.aE = this.aF; - double d0 = this.locX - this.lastX; - double d1 = this.locZ - this.lastZ; - float f1 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0F; - - if (f1 > 1.0F) { - f1 = 1.0F; - } - - this.aF += (f1 - this.aF) * 0.4F; - this.aG += this.aF; - } else { - this.K = 0.5F; - this.aO = 0.02F; - super.e(vec3d); - } - } - } - - public boolean dW() { - if (this.bC) { - return false; - } else { - this.bC = true; - this.bD = 0; - this.bE = this.getRandom().nextInt(841) + 140; - this.getDataWatcher().set(EntityPig.bA, this.bE); - return true; - } - } - - @Override - public EntityPig createChild(EntityAgeable entityageable) { - return (EntityPig) EntityTypes.PIG.a(this.world); - } - - @Override - public boolean i(ItemStack itemstack) { - return EntityPig.bB.test(itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/EntityPigZombie.java b/src/main/java/net/minecraft/server/EntityPigZombie.java deleted file mode 100644 index 4f260f814..000000000 --- a/src/main/java/net/minecraft/server/EntityPigZombie.java +++ /dev/null @@ -1,236 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import java.util.UUID; -import javax.annotation.Nullable; - -public class EntityPigZombie extends EntityZombie { - - private static final UUID b = UUID.fromString("49455A49-7EC5-45BA-B886-3B90B23A1718"); - private static final AttributeModifier c = (new AttributeModifier(EntityPigZombie.b, "Attacking speed boost", 0.05D, AttributeModifier.Operation.ADDITION)).a(false); - public int angerLevel; - private int soundDelay; - private UUID hurtBy; - - public EntityPigZombie(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.a(PathType.LAVA, 8.0F); - } - - @Override - public void setLastDamager(@Nullable EntityLiving entityliving) { - super.setLastDamager(entityliving); - if (entityliving != null) { - this.hurtBy = entityliving.getUniqueID(); - } - - } - - @Override - protected void l() { - this.goalSelector.a(2, new PathfinderGoalZombieAttack(this, 1.0D, false)); - this.goalSelector.a(7, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.targetSelector.a(1, new EntityPigZombie.PathfinderGoalAngerOther(this)); - this.targetSelector.a(2, new EntityPigZombie.PathfinderGoalAnger(this)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(EntityPigZombie.d).setValue(0.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.23000000417232513D); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(5.0D); - } - - @Override - protected boolean dY() { - return false; - } - - @Override - protected void mobTick() { - AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); - EntityLiving entityliving = this.getLastDamager(); - - if (this.ef()) { - if (!this.isBaby() && !attributeinstance.a(EntityPigZombie.c)) { - attributeinstance.addModifier(EntityPigZombie.c); - } - - --this.angerLevel; - EntityLiving entityliving1 = entityliving != null ? entityliving : this.getGoalTarget(); - - if (!this.ef() && entityliving1 != null) { - if (!this.hasLineOfSight(entityliving1)) { - this.setLastDamager((EntityLiving) null); - this.setGoalTarget((EntityLiving) null); - } else { - this.angerLevel = this.ee(); - } - } - } else if (attributeinstance.a(EntityPigZombie.c)) { - attributeinstance.removeModifier(EntityPigZombie.c); - } - - if (this.soundDelay > 0 && --this.soundDelay == 0) { - this.a(SoundEffects.ENTITY_ZOMBIE_PIGMAN_ANGRY, this.getSoundVolume() * 2.0F, ((this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F) * 1.8F); - } - - if (this.ef() && this.hurtBy != null && entityliving == null) { - EntityHuman entityhuman = this.world.b(this.hurtBy); - - this.setLastDamager(entityhuman); - this.killer = entityhuman; - this.lastDamageByPlayerTime = this.ct(); - } - - super.mobTick(); - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return generatoraccess.getDifficulty() != EnumDifficulty.PEACEFUL; - } - - @Override - public boolean a(IWorldReader iworldreader) { - return iworldreader.i(this) && !iworldreader.containsLiquid(this.getBoundingBox()); - } - - @Override - 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", ""); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.angerLevel = nbttagcompound.getShort("Anger"); - String s = nbttagcompound.getString("HurtBy"); - - if (!s.isEmpty()) { - this.hurtBy = UUID.fromString(s); - EntityHuman entityhuman = this.world.b(this.hurtBy); - - this.setLastDamager(entityhuman); - if (entityhuman != null) { - this.killer = entityhuman; - this.lastDamageByPlayerTime = this.ct(); - } - } - - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - Entity entity = damagesource.getEntity(); - - // CraftBukkit start - boolean result = super.damageEntity(damagesource, f); - - if (result && entity instanceof EntityHuman && !((EntityHuman) entity).isCreative() && this.hasLineOfSight(entity)) { - this.a(entity); - } - - return result; - // CraftBukkit end - } - } - - private boolean a(Entity entity) { - // CraftBukkit start - org.bukkit.event.entity.PigZombieAngerEvent event = new org.bukkit.event.entity.PigZombieAngerEvent((org.bukkit.entity.PigZombie) this.getBukkitEntity(), (entity == null) ? null : entity.getBukkitEntity(), this.ee()); - this.world.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return false; - } - this.angerLevel = event.getNewAnger(); - // CraftBukkit end - this.soundDelay = this.random.nextInt(40); - if (entity instanceof EntityLiving) { - this.setLastDamager((EntityLiving) entity); - } - - return true; - } - - private int ee() { - return 400 + this.random.nextInt(400); - } - - private boolean ef() { - return this.angerLevel > 0; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_ZOMBIE_PIGMAN_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_ZOMBIE_PIGMAN_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_ZOMBIE_PIGMAN_DEATH; - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - return false; - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.GOLDEN_SWORD)); - } - - @Override - protected ItemStack dX() { - return ItemStack.a; - } - - @Override - public boolean e(EntityHuman entityhuman) { - return this.ef(); - } - - static class PathfinderGoalAnger extends PathfinderGoalNearestAttackableTarget { - - public PathfinderGoalAnger(EntityPigZombie entitypigzombie) { - super(entitypigzombie, EntityHuman.class, true); - } - - @Override - public boolean a() { - return ((EntityPigZombie) this.e).ef() && super.a(); - } - } - - static class PathfinderGoalAngerOther extends PathfinderGoalHurtByTarget { - - public PathfinderGoalAngerOther(EntityPigZombie entitypigzombie) { - super(entitypigzombie); - this.a(new Class[]{EntityZombie.class}); - } - - @Override - protected void a(EntityInsentient entityinsentient, EntityLiving entityliving) { - if (entityinsentient instanceof EntityPigZombie && this.e.hasLineOfSight(entityliving) && ((EntityPigZombie) entityinsentient).a((Entity) entityliving)) { - entityinsentient.setGoalTarget(entityliving, org.bukkit.event.entity.EntityTargetEvent.TargetReason.TARGET_ATTACKED_NEARBY_ENTITY, true); // CraftBukkit - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityPillager.java b/src/main/java/net/minecraft/server/EntityPillager.java deleted file mode 100644 index 79a330650..000000000 --- a/src/main/java/net/minecraft/server/EntityPillager.java +++ /dev/null @@ -1,263 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.Map; -import javax.annotation.Nullable; - -public class EntityPillager extends EntityIllagerAbstract implements ICrossbow, IRangedEntity { - - private static final DataWatcherObject b = DataWatcher.a(EntityPillager.class, DataWatcherRegistry.i); - private final InventorySubcontainer inventory = new InventorySubcontainer(5); - - public EntityPillager(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(2, new EntityRaider.a(this, 10.0F)); - this.goalSelector.a(3, new PathfinderGoalCrossbowAttack<>(this, 1.0D, 8.0F)); - this.goalSelector.a(8, new PathfinderGoalRandomStroll(this, 0.6D)); - this.goalSelector.a(9, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 15.0F, 1.0F)); - this.goalSelector.a(10, new PathfinderGoalLookAtPlayer(this, EntityInsentient.class, 15.0F)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[]{EntityRaider.class})).a(new Class[0])); // CraftBukkit - decompile error - this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityVillagerAbstract.class, false)); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.3499999940395355D); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(24.0D); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(5.0D); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(32.0D); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityPillager.b, false); - } - - @Override - public void a(boolean flag) { - this.datawatcher.set(EntityPillager.b, flag); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.inventory.getSize(); ++i) { - ItemStack itemstack = this.inventory.getItem(i); - - if (!itemstack.isEmpty()) { - nbttaglist.add(itemstack.save(new NBTTagCompound())); - } - } - - nbttagcompound.set("Inventory", nbttaglist); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - NBTTagList nbttaglist = nbttagcompound.getList("Inventory", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - ItemStack itemstack = ItemStack.a(nbttaglist.getCompound(i)); - - if (!itemstack.isEmpty()) { - this.inventory.a(itemstack); - } - } - - this.setCanPickupLoot(true); - } - - @Override - public float a(BlockPosition blockposition, IWorldReader iworldreader) { - Block block = iworldreader.getType(blockposition.down()).getBlock(); - - return block != Blocks.GRASS_BLOCK && block != Blocks.SAND ? 0.5F - iworldreader.v(blockposition) : 10.0F; - } - - @Override - public int dC() { - return 1; - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.a(difficultydamagescaler); - this.b(difficultydamagescaler); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - ItemStack itemstack = new ItemStack(Items.CROSSBOW); - - if (this.random.nextInt(300) == 0) { - Map map = Maps.newHashMap(); - - map.put(Enchantments.PIERCING, 1); - EnchantmentManager.a((Map) map, itemstack); - } - - this.setSlot(EnumItemSlot.MAINHAND, itemstack); - } - - @Override - public boolean r(Entity entity) { - return super.r(entity) ? true : (entity instanceof EntityLiving && ((EntityLiving) entity).getMonsterType() == EnumMonsterType.ILLAGER ? this.getScoreboardTeam() == null && entity.getScoreboardTeam() == null : false); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_PILLAGER_AMBIENT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_PILLAGER_DEATH; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_PILLAGER_HURT; - } - - @Override - public void a(EntityLiving entityliving, float f) { - EnumHand enumhand = ProjectileHelper.a(this, Items.CROSSBOW); - ItemStack itemstack = this.b(enumhand); - - if (this.a(Items.CROSSBOW)) { - ItemCrossbow.a(this.world, this, enumhand, itemstack, 1.6F, (float) (14 - this.world.getDifficulty().a() * 4)); - } - - this.ticksFarFromPlayer = 0; - } - - @Override - public void a(EntityLiving entityliving, ItemStack itemstack, IProjectile iprojectile, float f) { - Entity entity = (Entity) iprojectile; - double d0 = entityliving.locX - this.locX; - double d1 = entityliving.locZ - this.locZ; - double d2 = (double) MathHelper.sqrt(d0 * d0 + d1 * d1); - double d3 = entityliving.getBoundingBox().minY + (double) (entityliving.getHeight() / 3.0F) - entity.locY + d2 * 0.20000000298023224D; - Vector3fa vector3fa = this.a(new Vec3D(d0, d3, d1), f); - - iprojectile.shoot((double) vector3fa.a(), (double) vector3fa.b(), (double) vector3fa.c(), 1.6F, (float) (14 - this.world.getDifficulty().a() * 4)); - this.a(SoundEffects.ITEM_CROSSBOW_SHOOT, 1.0F, 1.0F / (this.getRandom().nextFloat() * 0.4F + 0.8F)); - } - - private Vector3fa a(Vec3D vec3d, float f) { - Vec3D vec3d1 = vec3d.d(); - Vec3D vec3d2 = vec3d1.c(new Vec3D(0.0D, 1.0D, 0.0D)); - - if (vec3d2.g() <= 1.0E-7D) { - vec3d2 = vec3d1.c(this.i(1.0F)); - } - - Quaternion quaternion = new Quaternion(new Vector3fa(vec3d2), 90.0F, true); - Vector3fa vector3fa = new Vector3fa(vec3d1); - - vector3fa.a(quaternion); - Quaternion quaternion1 = new Quaternion(vector3fa, f, true); - Vector3fa vector3fa1 = new Vector3fa(vec3d1); - - vector3fa1.a(quaternion1); - return vector3fa1; - } - - public InventorySubcontainer getInventory() { - return this.inventory; - } - - @Override - protected void a(EntityItem entityitem) { - ItemStack itemstack = entityitem.getItemStack(); - - if (itemstack.getItem() instanceof ItemBanner) { - super.a(entityitem); - } else { - Item item = itemstack.getItem(); - - if (this.b(item)) { - ItemStack itemstack1 = this.inventory.a(itemstack); - - if (itemstack1.isEmpty()) { - entityitem.die(); - } else { - itemstack.setCount(itemstack1.getCount()); - } - } - } - - } - - private boolean b(Item item) { - return this.ek() && item == Items.WHITE_BANNER; - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - if (super.a_(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; - } - } - } - - @Override - public void a(int i, boolean flag) { - Raid raid = this.ej(); - boolean flag1 = this.random.nextFloat() <= raid.w(); - - if (flag1) { - ItemStack itemstack = new ItemStack(Items.CROSSBOW); - Map map = Maps.newHashMap(); - - if (i > raid.a(EnumDifficulty.NORMAL)) { - map.put(Enchantments.QUICK_CHARGE, 2); - } else if (i > raid.a(EnumDifficulty.EASY)) { - map.put(Enchantments.QUICK_CHARGE, 1); - } - - map.put(Enchantments.MULTISHOT, 1); - EnchantmentManager.a((Map) map, itemstack); - this.setSlot(EnumItemSlot.MAINHAND, itemstack); - } - - } - - @Override - public boolean I() { - return super.I() && this.getInventory().isNotEmpty(); - } - - @Override - public SoundEffect dV() { - return SoundEffects.ENTITY_PILLAGER_CELEBRATE; - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return super.isTypeNotPersistent(d0) && this.getInventory() != null && this.getInventory().isNotEmpty(); // CraftBukkit - null in constructor - } -} diff --git a/src/main/java/net/minecraft/server/EntityPlayer.java b/src/main/java/net/minecraft/server/EntityPlayer.java deleted file mode 100644 index fa79d0bed..000000000 --- a/src/main/java/net/minecraft/server/EntityPlayer.java +++ /dev/null @@ -1,1963 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.authlib.GameProfile; -import com.mojang.datafixers.util.Either; -import io.netty.util.concurrent.Future; -import java.util.ArrayDeque; // Paper -import java.util.Collection; -import java.util.Deque; // Paper -import java.util.Iterator; -import java.util.List; -import java.util.OptionalInt; -import java.util.Random; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import com.google.common.base.Preconditions; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -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.event.inventory.InventoryType; -import org.bukkit.event.player.PlayerChangedMainHandEvent; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerGameModeChangeEvent; -import org.bukkit.event.player.PlayerLocaleChangeEvent; -import org.bukkit.event.player.PlayerPortalEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.inventory.MainHand; -// CraftBukkit end - -public class EntityPlayer extends EntityHuman implements ICrafting { - - private static final Logger LOGGER = LogManager.getLogger(); - public String locale = null; // CraftBukkit - lowercase // Paper - default to null - public PlayerConnection playerConnection; - public final MinecraftServer server; - public final PlayerInteractManager playerInteractManager; - public final Deque removeQueue = new ArrayDeque<>(); // Paper - private final AdvancementDataPlayer advancementDataPlayer; - private final ServerStatisticManager serverStatisticManager; - private float lastHealthScored = Float.MIN_VALUE; - private int lastFoodScored = Integer.MIN_VALUE; - private int lastAirScored = Integer.MIN_VALUE; - private int lastArmorScored = Integer.MIN_VALUE; - private int lastExpLevelScored = Integer.MIN_VALUE; - private int lastExpTotalScored = Integer.MIN_VALUE; - private float lastHealthSent = -1.0E8F; - private int lastFoodSent = -99999999; - private boolean lastSentSaturationZero = true; - public int lastSentExp = -99999999; - public int invulnerableTicks = 60; - private EnumChatVisibility ck; - private boolean cl = true; - private long cm = SystemUtils.getMonotonicMillis(); - private Entity spectatedEntity; private void setSpectatorTargetField(Entity e) { this.spectatedEntity = e; } // Paper - OBFHELPER - public boolean worldChangeInvuln; - private boolean cp; private void setHasSeenCredits(boolean has) { this.cp = has; } // Paper - OBFHELPER - private final RecipeBookServer recipeBook; - private Vec3D cr; - private int cs; - private boolean ct; - @Nullable - private Vec3D cu; - private SectionPosition cv = SectionPosition.a(0, 0, 0); - private int containerCounter; - public boolean e; - public int ping; - public boolean viewingCredits; - private int containerUpdateDelay; // Paper - public long loginTime; // Paper - // Paper start - cancellable death event - public boolean queueHealthUpdatePacket = false; - public net.minecraft.server.PacketPlayOutUpdateHealth queuedHealthUpdatePacket; - // Paper end - // Paper start - mob spawning rework - public static final int ENUMCREATURETYPE_TOTAL_ENUMS = EnumCreatureType.values().length; - public final int[] mobCounts = new int[ENUMCREATURETYPE_TOTAL_ENUMS]; // Paper - public final com.destroystokyo.paper.util.PooledHashSets.PooledObjectLinkedOpenHashSet cachedSingleMobDistanceMap; - // Paper end - - // CraftBukkit start - 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; - public boolean sentListPacket = false; - public Integer clientViewDistance; - // CraftBukkit end - - public EntityPlayer(MinecraftServer minecraftserver, WorldServer worldserver, GameProfile gameprofile, PlayerInteractManager playerinteractmanager) { - super((World) worldserver, gameprofile); - playerinteractmanager.player = this; - this.playerInteractManager = playerinteractmanager; - this.server = minecraftserver; - this.recipeBook = new RecipeBookServer(minecraftserver.getCraftingManager()); - this.serverStatisticManager = minecraftserver.getPlayerList().getStatisticManager(this); - this.advancementDataPlayer = minecraftserver.getPlayerList().f(this); - this.K = 1.0F; - this.a(worldserver); - - // CraftBukkit start - this.displayName = this.getName(); - this.canPickUpLoot = true; - this.maxHealthCache = this.getMaxHealth(); - this.cachedSingleMobDistanceMap = new com.destroystokyo.paper.util.PooledHashSets.PooledObjectLinkedOpenHashSet<>(this); // Paper - } - - // Yes, this doesn't match Vanilla, but it's the best we can do for now. - // If this is an issue, PRs are welcome - public final BlockPosition getSpawnPoint(WorldServer worldserver) { - BlockPosition blockposition = worldserver.getSpawn(); - - if (worldserver.worldProvider.g() && worldserver.getWorldData().getGameType() != EnumGamemode.ADVENTURE) { - int i = Math.max(0, this.server.a(worldserver)); - int j = MathHelper.floor(worldserver.getWorldBorder().b((double) blockposition.getX(), (double) blockposition.getZ())); - - if (j < i) { - i = j; - } - - if (j <= 1) { - i = 1; - } - - int k = (i * 2 + 1) * (i * 2 + 1); - int l = this.t(k); - int i1 = (new Random()).nextInt(k); - - for (int j1 = 0; j1 < k; ++j1) { - int k1 = (i1 + l * j1) % k; - int l1 = k1 % (i * 2 + 1); - int i2 = k1 / (i * 2 + 1); - BlockPosition blockposition1 = worldserver.getWorldProvider().a(blockposition.getX() + l1 - i, blockposition.getZ() + i2 - i, false); - - if (blockposition1 != null) { - return blockposition1; - } - } - } - - return blockposition; - } - // CraftBukkit end - - private void a(WorldServer worldserver) { - BlockPosition blockposition = worldserver.getSpawn(); - - if (worldserver.worldProvider.g() && worldserver.getWorldData().getGameType() != EnumGamemode.ADVENTURE) { - int i = Math.max(0, this.server.a(worldserver)); - int j = MathHelper.floor(worldserver.getWorldBorder().b((double) blockposition.getX(), (double) blockposition.getZ())); - - if (j < i) { - i = j; - } - - if (j <= 1) { - i = 1; - } - - long k = (long) (i * 2 + 1); - long l = k * k; - int i1 = l > 2147483647L ? Integer.MAX_VALUE : (int) l; - int j1 = this.t(i1); - int k1 = (new Random()).nextInt(i1); - - for (int l1 = 0; l1 < i1; ++l1) { - int i2 = (k1 + j1 * l1) % i1; - int j2 = i2 % (i * 2 + 1); - int k2 = i2 / (i * 2 + 1); - BlockPosition blockposition1 = worldserver.getWorldProvider().a(blockposition.getX() + j2 - i, blockposition.getZ() + k2 - i, false); - - if (blockposition1 != null) { - this.setPositionRotation(blockposition1, 0.0F, 0.0F); - if (worldserver.getCubes(this)) { - break; - } - } - } - } else { - this.setPositionRotation(blockposition, 0.0F, 0.0F); - - while (!worldserver.getCubes(this) && this.locY < 255.0D) { - this.setPosition(this.locX, this.locY + 1.0D, this.locZ); - } - } - - } - - private int t(int i) { - return i <= 16 ? i - 1 : 17; - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (this.locY > 300) this.locY = 257; // Paper - bring down to a saner Y level if out of world - if (nbttagcompound.hasKeyOfType("playerGameType", 99)) { - if (this.getMinecraftServer().getForceGamemode()) { - this.playerInteractManager.setGameMode(this.getMinecraftServer().getGamemode()); - } else { - this.playerInteractManager.setGameMode(EnumGamemode.getById(nbttagcompound.getInt("playerGameType"))); - } - } - - if (nbttagcompound.hasKeyOfType("enteredNetherPosition", 10)) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("enteredNetherPosition"); - - this.cu = new Vec3D(nbttagcompound1.getDouble("x"), nbttagcompound1.getDouble("y"), nbttagcompound1.getDouble("z")); - } - - this.cp = nbttagcompound.getBoolean("seenCredits"); - if (nbttagcompound.hasKeyOfType("recipeBook", 10)) { - this.recipeBook.a(nbttagcompound.getCompound("recipeBook")); - } - this.getBukkitEntity().readExtraData(nbttagcompound); // CraftBukkit - - if (this.isSleeping()) { - this.dy(); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("playerGameType", this.playerInteractManager.getGameMode().getId()); - nbttagcompound.setBoolean("seenCredits", this.cp); - if (this.cu != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - nbttagcompound1.setDouble("x", this.cu.x); - nbttagcompound1.setDouble("y", this.cu.y); - nbttagcompound1.setDouble("z", this.cu.z); - nbttagcompound.set("enteredNetherPosition", nbttagcompound1); - } - - Entity entity = this.getRootVehicle(); - Entity entity1 = this.getVehicle(); - - // CraftBukkit start - handle non-persistent vehicles - boolean persistVehicle = true; - if (entity1 != null) { - Entity vehicle; - for (vehicle = entity1; vehicle != null; vehicle = vehicle.getVehicle()) { - if (!vehicle.persist) { - persistVehicle = false; - break; - } - } - } - - if (persistVehicle && entity1 != null && entity != this && entity.hasSinglePlayerPassenger()) { - // CraftBukkit end - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - NBTTagCompound nbttagcompound3 = new NBTTagCompound(); - - entity.d(nbttagcompound3); - nbttagcompound2.a("Attach", entity1.getUniqueID()); - nbttagcompound2.set("Entity", nbttagcompound3); - nbttagcompound.set("RootVehicle", nbttagcompound2); - } - - nbttagcompound.set("recipeBook", this.recipeBook.save()); - 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; - Vec3D position = null; - if (this.spawnWorld != null && !this.spawnWorld.equals("")) { - CraftWorld cworld = (CraftWorld) Bukkit.getServer().getWorld(this.spawnWorld); - if (cworld != null && this.getBed() != null) { - world = cworld.getHandle(); - position = EntityHuman.getBed(cworld.getHandle(), this.getBed(), false).orElse(null); - } - } - if (world == null || position == null) { - world = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle(); - position = new Vec3D(world.getSpawn()); - } - this.world = world; - this.setPosition(position.getX(), position.getY(), position.getZ()); - } - this.dimension = ((WorldServer) this.world).getWorldProvider().getDimensionManager(); - this.playerInteractManager.a((WorldServer) world); - } - // CraftBukkit end - - public void a(int i) { - float f = (float) this.getExpToLevel(); - float f1 = (f - 1.0F) / f; - - this.exp = MathHelper.a((float) i / f, 0.0F, f1); - this.lastSentExp = -1; - } - - public void b(int i) { - this.expLevel = i; - this.lastSentExp = -1; - } - - @Override - public void levelDown(int i) { - super.levelDown(i); - this.lastSentExp = -1; - } - - @Override - public void enchantDone(ItemStack itemstack, int i) { - super.enchantDone(itemstack, i); - this.lastSentExp = -1; - } - - public void syncInventory() { - this.activeContainer.addSlotListener(this); - } - - @Override - public void enterCombat() { - super.enterCombat(); - this.playerConnection.sendPacket(new PacketPlayOutCombatEvent(this.getCombatTracker(), PacketPlayOutCombatEvent.EnumCombatEventType.ENTER_COMBAT)); - } - - @Override - public void exitCombat() { - super.exitCombat(); - this.playerConnection.sendPacket(new PacketPlayOutCombatEvent(this.getCombatTracker(), PacketPlayOutCombatEvent.EnumCombatEventType.END_COMBAT)); - } - - @Override - protected void a(IBlockData iblockdata) { - CriterionTriggers.d.a(this, iblockdata); - } - - @Override - protected ItemCooldown g() { - return new ItemCooldownPlayer(this); - } - - @Override - public void tick() { - // CraftBukkit start - if (this.joining) { - this.joining = false; - } - // CraftBukkit end - this.playerInteractManager.a(); - --this.invulnerableTicks; - if (this.noDamageTicks > 0) { - --this.noDamageTicks; - } - - // Paper start - Configurable container update tick rate - if (--containerUpdateDelay <= 0) { - this.activeContainer.c(); - containerUpdateDelay = world.paperConfig.containerUpdateTickRate; - } - // Paper end - if (!this.world.isClientSide && !this.activeContainer.canUse(this)) { - this.closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.CANT_USE); // Paper - this.activeContainer = this.defaultContainer; - } - - while (!this.removeQueue.isEmpty()) { - int i = Math.min(this.removeQueue.size(), Integer.MAX_VALUE); - int[] aint = new int[i]; - //Iterator iterator = this.removeQueue.iterator(); // Paper - int j = 0; - - // Paper start - /* while (iterator.hasNext() && j < i) { - aint[j++] = (Integer) iterator.next(); - iterator.remove(); - } */ - - Integer integer; - while (j < i && (integer = this.removeQueue.poll()) != null) { - aint[j++] = integer.intValue(); - } - // Paper end - - this.playerConnection.sendPacket(new PacketPlayOutEntityDestroy(aint)); - } - - Entity entity = this.getSpecatorTarget(); - - if (entity != this) { - if (entity.isAlive()) { - this.setLocation(entity.locX, entity.locY, entity.locZ, entity.yaw, entity.pitch); - this.getWorldServer().getChunkProvider().movePlayer(this); - if (this.isSneaking()) { - this.setSpectatorTarget(this); - } - } else { - this.setSpectatorTarget(this); - } - } - - CriterionTriggers.w.a(this); - if (this.cr != null) { - CriterionTriggers.u.a(this, this.cr, this.ticksLived - this.cs); - } - - this.advancementDataPlayer.b(this); - } - - public void playerTick() { - try { - if (!this.isSpectator() || this.world.isLoaded(new BlockPosition(this))) { - super.tick(); - } - - for (int i = 0; i < this.inventory.getSize(); ++i) { - ItemStack itemstack = this.inventory.getItem(i); - - if (itemstack.getItem().O_()) { - Packet packet = ((ItemWorldMapBase) itemstack.getItem()).a(itemstack, this.world, (EntityHuman) this); - - if (packet != null) { - this.playerConnection.sendPacket(packet); - } - } - } - - if (this.getHealth() != this.lastHealthSent || this.lastFoodSent != this.foodData.getFoodLevel() || this.foodData.getSaturationLevel() == 0.0F != this.lastSentSaturationZero) { - this.playerConnection.sendPacket(new PacketPlayOutUpdateHealth(this.getBukkitEntity().getScaledHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel())); // CraftBukkit - this.lastHealthSent = this.getHealth(); - this.lastFoodSent = this.foodData.getFoodLevel(); - this.lastSentSaturationZero = this.foodData.getSaturationLevel() == 0.0F; - } - - if (this.getHealth() + this.getAbsorptionHearts() != this.lastHealthScored) { - this.lastHealthScored = this.getHealth() + this.getAbsorptionHearts(); - this.a(IScoreboardCriteria.HEALTH, MathHelper.f(this.lastHealthScored)); - } - - if (this.foodData.getFoodLevel() != this.lastFoodScored) { - this.lastFoodScored = this.foodData.getFoodLevel(); - this.a(IScoreboardCriteria.FOOD, MathHelper.f((float) this.lastFoodScored)); - } - - if (this.getAirTicks() != this.lastAirScored) { - this.lastAirScored = this.getAirTicks(); - this.a(IScoreboardCriteria.AIR, MathHelper.f((float) this.lastAirScored)); - } - - if (this.getArmorStrength() != this.lastArmorScored) { - this.lastArmorScored = this.getArmorStrength(); - this.a(IScoreboardCriteria.ARMOR, MathHelper.f((float) this.lastArmorScored)); - } - - if (this.expTotal != this.lastExpTotalScored) { - this.lastExpTotalScored = this.expTotal; - this.a(IScoreboardCriteria.XP, MathHelper.f((float) this.lastExpTotalScored)); - } - - // CraftBukkit start - Force max health updates - if (this.maxHealthCache != this.getMaxHealth()) { - this.getBukkitEntity().updateScaledHealth(); - } - // CraftBukkit end - - if (this.expLevel != this.lastExpLevelScored) { - this.lastExpLevelScored = this.expLevel; - this.a(IScoreboardCriteria.LEVEL, MathHelper.f((float) this.lastExpLevelScored)); - } - - if (this.expTotal != this.lastSentExp) { - this.lastSentExp = this.expTotal; - this.playerConnection.sendPacket(new PacketPlayOutExperience(this.exp, this.expTotal, this.expLevel)); - } - - if (this.ticksLived % 20 == 0) { - CriterionTriggers.p.a(this); - } - - // 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((EntityPlayer) 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); - } - } - - private void a(IScoreboardCriteria iscoreboardcriteria, int i) { - // CraftBukkit - Use our scores instead - this.world.getServer().getScoreboardManager().getScoreboardScores(iscoreboardcriteria, this.getName(), (scoreboardscore) -> { - scoreboardscore.setScore(i); - }); - } - - // Paper start - process inventory - private static void processKeep(org.bukkit.event.entity.PlayerDeathEvent event, NonNullList inv) { - List itemsToKeep = event.getItemsToKeep(); - if (inv == null) { - // remainder of items left in toKeep - plugin added stuff on death that wasn't in the initial loot? - if (!itemsToKeep.isEmpty()) { - for (org.bukkit.inventory.ItemStack itemStack : itemsToKeep) { - event.getEntity().getInventory().addItem(itemStack); - } - } - - return; - } - - for (int i = 0; i < inv.size(); ++i) { - ItemStack item = inv.get(i); - if (EnchantmentManager.shouldNotDrop(item) || itemsToKeep.isEmpty() || item.isEmpty()) { - inv.set(i, ItemStack.NULL_ITEM); - continue; - } - - final org.bukkit.inventory.ItemStack bukkitStack = item.getBukkitStack(); - boolean keep = false; - final Iterator iterator = itemsToKeep.iterator(); - while (iterator.hasNext()) { - final org.bukkit.inventory.ItemStack itemStack = iterator.next(); - if (bukkitStack.equals(itemStack)) { - iterator.remove(); - keep = true; - break; - } - } - - if (!keep) { - inv.set(i, ItemStack.NULL_ITEM); - } - } - } - // Paper end - - @Override - public void die(DamageSource damagesource) { - boolean flag = this.world.getGameRules().getBoolean(GameRules.SHOW_DEATH_MESSAGES); - // CraftBukkit start - fire PlayerDeathEvent - if (this.dead) { - return; - } - java.util.List loot = new java.util.ArrayList(this.inventory.getSize()); - boolean keepInventory = this.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY) || this.isSpectator(); - - if (!keepInventory) { - for (ItemStack item : this.inventory.getContents()) { - if (!item.isEmpty() && !EnchantmentManager.shouldNotDrop(item)) { - loot.add(CraftItemStack.asCraftMirror(item)); - } - } - } - // SPIGOT-5071: manually add player loot tables (SPIGOT-5195 - ignores keepInventory rule) - this.a(damagesource, this.lastDamageByPlayerTime > 0); - for (org.bukkit.inventory.ItemStack item : this.drops) { - loot.add(item); - } - this.drops.clear(); // SPIGOT-5188: make sure to clear - - IChatBaseComponent defaultMessage = this.getCombatTracker().getDeathMessage(); - - String deathmessage = defaultMessage.getString(); - org.bukkit.event.entity.PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, loot, deathmessage, keepInventory); - // Paper start - cancellable death event - if (event.isCancelled()) { - // make compatible with plugins that might have already set the health in an event listener - if (this.getHealth() <= 0) { - this.setHealth((float) event.getReviveHealth()); - } - return; - } - // Paper end - - // SPIGOT-943 - only call if they have an inventory open - if (this.activeContainer != this.defaultContainer) { - this.closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.DEATH); // Paper - } - - String deathMessage = event.getDeathMessage(); - - if (deathMessage != null && deathMessage.length() > 0 && flag) { // TODO: allow plugins to override? - IChatBaseComponent ichatbasecomponent; - if (deathMessage.equals(deathmessage)) { - ichatbasecomponent = this.getCombatTracker().getDeathMessage(); - } else { - ichatbasecomponent = org.bukkit.craftbukkit.util.CraftChatMessage.fromStringOrNull(deathMessage); - } - - this.playerConnection.a((Packet) (new PacketPlayOutCombatEvent(this.getCombatTracker(), PacketPlayOutCombatEvent.EnumCombatEventType.ENTITY_DIED, ichatbasecomponent)), (future) -> { - if (!future.isSuccess()) { - boolean flag1 = true; - String s = ichatbasecomponent.a(256); - ChatMessage chatmessage = new ChatMessage("death.attack.message_too_long", new Object[]{(new ChatComponentText(s)).a(EnumChatFormat.YELLOW)}); - IChatBaseComponent ichatbasecomponent1 = (new ChatMessage("death.attack.even_more_magic", new Object[]{this.getScoreboardDisplayName()})).a((chatmodifier) -> { - chatmodifier.setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_TEXT, chatmessage)); - }); - - this.playerConnection.sendPacket(new PacketPlayOutCombatEvent(this.getCombatTracker(), PacketPlayOutCombatEvent.EnumCombatEventType.ENTITY_DIED, ichatbasecomponent1)); - } - - }); - ScoreboardTeamBase scoreboardteambase = this.getScoreboardTeam(); - - if (scoreboardteambase != null && scoreboardteambase.getDeathMessageVisibility() != ScoreboardTeamBase.EnumNameTagVisibility.ALWAYS) { - if (scoreboardteambase.getDeathMessageVisibility() == ScoreboardTeamBase.EnumNameTagVisibility.HIDE_FOR_OTHER_TEAMS) { - this.server.getPlayerList().a((EntityHuman) this, ichatbasecomponent); - } else if (scoreboardteambase.getDeathMessageVisibility() == ScoreboardTeamBase.EnumNameTagVisibility.HIDE_FOR_OWN_TEAM) { - this.server.getPlayerList().b(this, ichatbasecomponent); - } - } else { - this.server.getPlayerList().sendMessage(ichatbasecomponent); - } - } else { - this.playerConnection.sendPacket(new PacketPlayOutCombatEvent(this.getCombatTracker(), PacketPlayOutCombatEvent.EnumCombatEventType.ENTITY_DIED)); - } - - this.releaseShoulderEntities(); - // we clean the player's inventory after the EntityDeathEvent is called so plugins can get the exact state of the inventory. - if (!event.getKeepInventory()) { - // Paper start - replace logic - for (NonNullList inv : this.inventory.getComponents()) { - processKeep(event, inv); - } - processKeep(event, null); - // Paper end - } - - this.setSpectatorTarget(this); // Remove spectated target - // CraftBukkit end - - // CraftBukkit - Get our scores instead - this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.DEATH_COUNT, this.getName(), ScoreboardScore::incrementScore); - EntityLiving entityliving = this.getKillingEntity(); - - if (entityliving != null) { - this.b(StatisticList.ENTITY_KILLED_BY.b(entityliving.getEntityType())); - entityliving.a(this, this.aY, damagesource); - if (!this.world.isClientSide && entityliving instanceof EntityWither) { - boolean flag1 = false; - - if (this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - BlockPosition blockposition = new BlockPosition(this.locX, this.locY, this.locZ); - IBlockData iblockdata = Blocks.WITHER_ROSE.getBlockData(); - - if (this.world.getType(blockposition).isAir() && iblockdata.canPlace(this.world, blockposition)) { - this.world.setTypeAndData(blockposition, iblockdata, 3); - flag1 = true; - } - } - - if (!flag1) { - EntityItem entityitem = new EntityItem(this.world, this.locX, this.locY, this.locZ, new ItemStack(Items.bg)); - - this.world.addEntity(entityitem); - } - } - } - - this.a(StatisticList.DEATHS); - this.a(StatisticList.CUSTOM.b(StatisticList.TIME_SINCE_DEATH)); - this.a(StatisticList.CUSTOM.b(StatisticList.TIME_SINCE_REST)); - this.extinguish(); - this.setFlag(0, false); - this.getCombatTracker().g(); - } - - @Override - public void a(Entity entity, int i, DamageSource damagesource) { - if (entity != this) { - super.a(entity, i, damagesource); - this.addScore(i); - String s = this.getName(); - String s1 = entity.getName(); - - // CraftBukkit - Get our scores instead - this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.TOTAL_KILL_COUNT, s, ScoreboardScore::incrementScore); - if (entity instanceof EntityHuman) { - this.a(StatisticList.PLAYER_KILLS); - // CraftBukkit - Get our scores instead - this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.PLAYER_KILL_COUNT, s, ScoreboardScore::incrementScore); - } else { - this.a(StatisticList.MOB_KILLS); - } - - this.a(s, s1, IScoreboardCriteria.m); - this.a(s1, s, IScoreboardCriteria.n); - CriterionTriggers.b.a(this, entity, damagesource); - } - } - - private void a(String s, String s1, IScoreboardCriteria[] aiscoreboardcriteria) { - ScoreboardTeam scoreboardteam = this.getScoreboard().getPlayerTeam(s1); - - if (scoreboardteam != null) { - int i = scoreboardteam.getColor().b(); - - if (i >= 0 && i < aiscoreboardcriteria.length) { - // CraftBukkit - Get our scores instead - this.world.getServer().getScoreboardManager().getScoreboardScores(aiscoreboardcriteria[i], s, ScoreboardScore::incrementScore); - } - } - - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - boolean flag = this.server.S() && this.canPvP() && "fall".equals(damagesource.translationIndex); - - if (!flag && this.invulnerableTicks > 0 && damagesource != DamageSource.OUT_OF_WORLD) { - return false; - } else { - if (damagesource instanceof EntityDamageSource) { - Entity entity = damagesource.getEntity(); - - if (entity instanceof EntityHuman && !this.a((EntityHuman) entity)) { - return false; - } - - if (entity instanceof EntityArrow) { - EntityArrow entityarrow = (EntityArrow) entity; - Entity entity1 = entityarrow.getShooter(); - - if (entity1 instanceof EntityHuman && !this.a((EntityHuman) entity1)) { - return false; - } - } - } - // Paper start - cancellable death events - //return super.damageEntity(damagesource, f); - this.queueHealthUpdatePacket = true; - boolean damaged = super.damageEntity(damagesource, f); - this.queueHealthUpdatePacket = false; - if (this.queuedHealthUpdatePacket != null) { - this.playerConnection.sendPacket(this.queuedHealthUpdatePacket); - this.queuedHealthUpdatePacket = null; - } - return damaged; - // Paper end - } - } - } - - @Override - public boolean a(EntityHuman entityhuman) { - return !this.canPvP() ? false : super.a(entityhuman); - } - - private boolean canPvP() { - // CraftBukkit - this.server.getPvP() -> this.world.pvpMode - return this.world.pvpMode; - } - - @Nullable - @Override - public Entity a(DimensionManager dimensionmanager) { - // CraftBukkit start - return a(dimensionmanager, TeleportCause.UNKNOWN); - } - - @Nullable - public Entity a(DimensionManager dimensionmanager, PlayerTeleportEvent.TeleportCause cause) { - // CraftBukkit end - if (this.isSleeping()) return this; // CraftBukkit - SPIGOT-3154 - // this.worldChangeInvuln = true; // CraftBukkit - Moved down and into PlayerList#changeDimension - DimensionManager dimensionmanager1 = this.dimension; - - if (dimensionmanager1.getType() == DimensionManager.THE_END && dimensionmanager.getType() == DimensionManager.OVERWORLD) { // CraftBukkit - getType() - this.worldChangeInvuln = true; // CraftBukkit - Moved down from above - this.decouple(); - this.getWorldServer().removePlayer(this); - if (!this.viewingCredits) { - this.viewingCredits = true; - if (world.paperConfig.disableEndCredits) this.setHasSeenCredits(true); // Paper - Toggle to always disable end credits - this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(4, this.cp ? 0.0F : 1.0F)); - this.cp = true; - } - - return this; - } else { - WorldServer worldserver = this.server.getWorldServer(dimensionmanager1); - - // this.dimension = dimensionmanager; // CraftBukkit - WorldServer worldserver1 = this.server.getWorldServer(dimensionmanager); - WorldData worlddata = this.world.getWorldData(); - - // CraftBukkit start - /* - this.playerConnection.sendPacket(new PacketPlayOutRespawn(dimensionmanager, worlddata.getType(), this.playerInteractManager.getGameMode())); - this.playerConnection.sendPacket(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); - PlayerList playerlist = this.server.getPlayerList(); - - playerlist.d(this); - worldserver.removePlayer(this); - this.dead = false; - */ - // CraftBukkit end - double d0 = this.locX; - double d1 = this.locY; - double d2 = this.locZ; - float f = this.pitch; - float f1 = this.yaw; - double d3 = 8.0D; - float f2 = f1; - - worldserver.getMethodProfiler().enter("moving"); - if (worldserver1 == null) { } else // CraftBukkit - empty to fall through to null to event - if (dimensionmanager1 == DimensionManager.OVERWORLD && dimensionmanager == DimensionManager.NETHER) { - this.cu = new Vec3D(this.locX, this.locY, this.locZ); - d0 /= 8.0D; - d2 /= 8.0D; - } else if (dimensionmanager1 == DimensionManager.NETHER && dimensionmanager == DimensionManager.OVERWORLD) { - d0 *= 8.0D; - d2 *= 8.0D; - } else if (dimensionmanager1 == DimensionManager.OVERWORLD && dimensionmanager == DimensionManager.THE_END) { - BlockPosition blockposition = worldserver1.getDimensionSpawn(); - - d0 = (double) blockposition.getX(); - d1 = (double) blockposition.getY(); - d2 = (double) blockposition.getZ(); - f1 = 90.0F; - f = 0.0F; - } - - // CraftBukkit start - Location enter = this.getBukkitEntity().getLocation(); - Location exit = (worldserver1 == null) ? null : new Location(worldserver1.getWorld(), d0, d1, d2, f1, f); - PlayerPortalEvent event = new PlayerPortalEvent(this.getBukkitEntity(), enter, exit, cause); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled() || event.getTo() == null) { - return null; - } - - exit = event.getTo(); - if (exit == null) { - return null; - } - - PlayerTeleportEvent tpEvent = new PlayerTeleportEvent(this.getBukkitEntity(), enter, exit, cause); - Bukkit.getServer().getPluginManager().callEvent(tpEvent); - if (tpEvent.isCancelled() || tpEvent.getTo() == null) { - return null; - } - - exit = tpEvent.getTo(); - if (exit == null) { - return null; - } - worldserver1 = ((CraftWorld) exit.getWorld()).getHandle(); - d0 = exit.getX(); - d1 = exit.getY(); - d2 = exit.getZ(); - f1 = exit.getYaw(); - f = exit.getPitch(); - this.worldChangeInvuln = true; // CraftBukkit - Set teleport invulnerability only if player changing worlds - dimensionmanager = worldserver1.getWorldProvider().getDimensionManager(); - // CraftBukkit end - - // CraftBukkit start - this.dimension = dimensionmanager; - - this.playerConnection.sendPacket(new PacketPlayOutRespawn(worldserver1.worldProvider.getDimensionManager().getType(), this.world.getWorldData().getType(), this.playerInteractManager.getGameMode())); - this.playerConnection.sendPacket(new PacketPlayOutServerDifficulty(this.world.getDifficulty(), this.world.getWorldData().isDifficultyLocked())); - PlayerList playerlist = this.server.getPlayerList(); - - playerlist.d(this); - worldserver.removePlayer(this); - this.dead = false; - // CraftBukkit end - - this.setPositionRotation(d0, d1, d2, f1, f); - worldserver.getMethodProfiler().exit(); - worldserver.getMethodProfiler().enter("placing"); - double d4 = Math.min(-2.9999872E7D, worldserver1.getWorldBorder().c() + 16.0D); - double d5 = Math.min(-2.9999872E7D, worldserver1.getWorldBorder().d() + 16.0D); - double d6 = Math.min(2.9999872E7D, worldserver1.getWorldBorder().e() - 16.0D); - double d7 = Math.min(2.9999872E7D, worldserver1.getWorldBorder().f() - 16.0D); - - d0 = MathHelper.a(d0, d4, d6); - d2 = MathHelper.a(d2, d5, d7); - this.setPositionRotation(d0, d1, d2, f1, f); - if (dimensionmanager.getType() == DimensionManager.THE_END) { // CraftBukkit - getType() - int i = MathHelper.floor(this.locX); - int j = MathHelper.floor(this.locY) - 1; - int k = MathHelper.floor(this.locZ); - boolean flag = true; - boolean flag1 = false; - org.bukkit.craftbukkit.util.BlockStateListPopulator blockList = new org.bukkit.craftbukkit.util.BlockStateListPopulator(worldserver1); // CraftBukkit - Use BlockStateListPopulator - - 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 * 1 + l * 0; - int l1 = j + j1; - int i2 = k + i1 * 0 - l * 1; - boolean flag2 = j1 < 0; - - blockList.setTypeAndData(new BlockPosition(k1, l1, i2), flag2 ? Blocks.OBSIDIAN.getBlockData() : Blocks.AIR.getBlockData(), 3); // CraftBukkit - } - } - } - - // CraftBukkit start - org.bukkit.World bworld = worldserver1.getWorld(); - org.bukkit.event.world.PortalCreateEvent portalEvent = new org.bukkit.event.world.PortalCreateEvent((List) (List) blockList.getList(), bworld, this.getBukkitEntity(), org.bukkit.event.world.PortalCreateEvent.CreateReason.END_PLATFORM); - - this.world.getServer().getPluginManager().callEvent(portalEvent); - if (!portalEvent.isCancelled()) { - blockList.updateList(); - } - // CraftBukkit end - this.setPositionRotation((double) i, (double) j, (double) k, f1, 0.0F); - this.setMot(Vec3D.a); - } else if (!worldserver1.getTravelAgent().a(this, f2)) { - worldserver1.getTravelAgent().a((Entity) this); - worldserver1.getTravelAgent().a(this, f2); - } - - worldserver.getMethodProfiler().exit(); - this.spawnIn(worldserver1); - worldserver1.addPlayerPortal(this); - this.b(worldserver); - this.playerConnection.a(this.locX, this.locY, this.locZ, f1, f); - this.playerInteractManager.a(worldserver1); - this.playerConnection.sendPacket(new PacketPlayOutAbilities(this.abilities)); - playerlist.a(this, worldserver1); - playerlist.updateClient(this); - Iterator iterator = this.getEffects().iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - this.playerConnection.sendPacket(new PacketPlayOutEntityEffect(this.getId(), mobeffect)); - } - - this.playerConnection.sendPacket(new PacketPlayOutWorldEvent(1032, BlockPosition.ZERO, 0, false)); - this.lastSentExp = -1; - this.lastHealthSent = -1.0F; - this.lastFoodSent = -1; - - // CraftBukkit start - PlayerChangedWorldEvent changeEvent = new PlayerChangedWorldEvent(this.getBukkitEntity(), worldserver.getWorld()); - this.world.getServer().getPluginManager().callEvent(changeEvent); - // CraftBukkit end - return this; - } - } - - public void b(WorldServer worldserver) { // PAIL - DimensionManager dimensionmanager = worldserver.worldProvider.getDimensionManager(); - DimensionManager dimensionmanager1 = this.world.worldProvider.getDimensionManager(); - - CriterionTriggers.v.a(this, dimensionmanager, dimensionmanager1); - if (dimensionmanager == DimensionManager.NETHER && dimensionmanager1 == DimensionManager.OVERWORLD && this.cu != null) { - CriterionTriggers.C.a(this, this.cu); - } - - if (dimensionmanager1 != DimensionManager.NETHER) { - this.cu = null; - } - - } - - @Override - public boolean a(EntityPlayer entityplayer) { - return entityplayer.isSpectator() ? this.getSpecatorTarget() == this : (this.isSpectator() ? false : super.a(entityplayer)); - } - - private void a(TileEntity tileentity) { - if (tileentity != null) { - PacketPlayOutTileEntityData packetplayouttileentitydata = tileentity.getUpdatePacket(); - - if (packetplayouttileentitydata != null) { - this.playerConnection.sendPacket(packetplayouttileentitydata); - } - } - - } - - @Override - public void receive(Entity entity, int i) { - super.receive(entity, i); - this.activeContainer.c(); - } - - @Override - public Either sleep(BlockPosition blockposition) { - // CraftBukkit start - add force parameter - return this.sleep(blockposition, false); - } - - @Override - public Either sleep(BlockPosition blockposition, boolean force) { - // CraftBukkit end - return super.sleep(blockposition, force).ifRight((unit) -> { - this.a(StatisticList.SLEEP_IN_BED); - CriterionTriggers.q.a(this); - }); - } - - @Override - public void wakeup(boolean flag, boolean flag1, boolean flag2) { - if (!this.isSleeping()) return; // CraftBukkit - Can't leave bed if not in one! - if (this.isSleeping()) { - this.getWorldServer().getChunkProvider().broadcastIncludingSelf(this, new PacketPlayOutAnimation(this, 2)); - } - - super.wakeup(flag, flag1, flag2); - if (this.playerConnection != null) { - this.playerConnection.a(this.locX, this.locY, this.locZ, this.yaw, this.pitch); - } - - } - - @Override - public boolean a(Entity entity, boolean flag) { - Entity entity1 = this.getVehicle(); - - if (!super.a(entity, flag)) { - return false; - } else { - Entity entity2 = this.getVehicle(); - - if (entity2 != entity1 && this.playerConnection != null) { - this.playerConnection.a(this.locX, this.locY, this.locZ, this.yaw, this.pitch); - } - - return true; - } - } - - // Paper start - @Override public void stopRiding() { stopRiding(false); } - @Override public void stopRiding(boolean suppressCancellation) { - // paper end - Entity entity = this.getVehicle(); - - super.stopRiding(suppressCancellation); // Paper - Entity entity1 = this.getVehicle(); - - if (entity1 != entity && this.playerConnection != null) { - this.playerConnection.a(this.locX, this.locY, this.locZ, this.yaw, this.pitch); - } - // Paper start - "Fixes" an issue in which the vehicle player would not be notified that the passenger dismounted - if (entity instanceof EntityPlayer) { - // TODO verify this solution - WorldServer worldServer = (WorldServer) entity.getWorld(); - worldServer.getChunkProvider().playerChunkMap.removeEntity(this); - worldServer.getChunkProvider().playerChunkMap.addEntity(this); - } - // Paper end - - } - - @Override - public boolean isInvulnerable(DamageSource damagesource) { - return super.isInvulnerable(damagesource) || this.H() || this.abilities.isInvulnerable && damagesource == DamageSource.WITHER; - } - - @Override - protected void a(double d0, boolean flag, IBlockData iblockdata, BlockPosition blockposition) {} - - @Override - protected void b(BlockPosition blockposition) { - if (!this.isSpectator()) { - super.b(blockposition); - } - - } - - public void a(double d0, boolean flag) { - int i = MathHelper.floor(this.locX); - int j = MathHelper.floor(this.locY - 0.20000000298023224D); - int k = MathHelper.floor(this.locZ); - BlockPosition blockposition = new BlockPosition(i, j, k); - - if (this.world.isLoaded(blockposition)) { - IBlockData iblockdata = this.world.getType(blockposition); - - if (iblockdata.isAir()) { - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata1 = this.world.getType(blockposition1); - Block block = iblockdata1.getBlock(); - - if (block.a(TagsBlock.FENCES) || block.a(TagsBlock.WALLS) || block instanceof BlockFenceGate) { - blockposition = blockposition1; - iblockdata = iblockdata1; - } - } - - super.a(d0, flag, iblockdata, blockposition); - } - } - - @Override - public void openSign(TileEntitySign tileentitysign) { - tileentitysign.a((EntityHuman) this); - this.playerConnection.sendPacket(new PacketPlayOutOpenSignEditor(tileentitysign.getPosition())); - } - - public int nextContainerCounter() { // CraftBukkit - void -> int - this.containerCounter = this.containerCounter % 100 + 1; - return containerCounter; // CraftBukkit - } - - @Override - public OptionalInt openContainer(@Nullable ITileInventory itileinventory) { - if (itileinventory == null) { - return OptionalInt.empty(); - } else { - if (this.activeContainer != this.defaultContainer) { - this.closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.OPEN_NEW); // Paper - } - - this.nextContainerCounter(); - Container container = itileinventory.createMenu(this.containerCounter, this.inventory, this); - - // CraftBukkit start - Inventory open hook - if (container != null) { - container.setTitle(itileinventory.getScoreboardDisplayName()); - - boolean cancelled = false; - container = CraftEventFactory.callInventoryOpenEvent(this, container, cancelled); - if (container == null && !cancelled) { // Let pre-cancelled events fall through - // SPIGOT-5263 - close chest if cancelled - if (itileinventory instanceof IInventory) { - ((IInventory) itileinventory).closeContainer(this); - } else if (itileinventory instanceof BlockChest.DoubleInventory) { - // SPIGOT-5355 - double chests too :( - ((BlockChest.DoubleInventory) itileinventory).inventorylargechest.closeContainer(this); - } - return OptionalInt.empty(); - } - } - // CraftBukkit end - if (container == null) { - if (this.isSpectator()) { - this.a((new ChatMessage("container.spectatorCantOpen", new Object[0])).a(EnumChatFormat.RED), true); - } - - return OptionalInt.empty(); - } else { - // CraftBukkit start - this.activeContainer = container; - this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(container.windowId, container.getType(), container.getTitle())); - // CraftBukkit end - container.addSlotListener(this); - return OptionalInt.of(this.containerCounter); - } - } - } - - @Override - public void openTrade(int i, MerchantRecipeList merchantrecipelist, int j, int k, boolean flag, boolean flag1) { - this.playerConnection.sendPacket(new PacketPlayOutOpenWindowMerchant(i, merchantrecipelist, j, k, flag, flag1)); - } - - @Override - public void openHorseInventory(EntityHorseAbstract entityhorseabstract, IInventory iinventory) { - // CraftBukkit start - Inventory open hook - this.nextContainerCounter(); - Container container = new ContainerHorse(this.containerCounter, this.inventory, iinventory, entityhorseabstract); - container.setTitle(entityhorseabstract.getScoreboardDisplayName()); - container = CraftEventFactory.callInventoryOpenEvent(this, container); - - if (container == null) { - iinventory.closeContainer(this); - return; - } - // CraftBukkit end - if (this.activeContainer != this.defaultContainer) { - this.closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.OPEN_NEW); // Paper - } - - // this.nextContainerCounter(); // CraftBukkit - moved up - this.playerConnection.sendPacket(new PacketPlayOutOpenWindowHorse(this.containerCounter, iinventory.getSize(), entityhorseabstract.getId())); - this.activeContainer = container; // CraftBukkit - this.activeContainer.addSlotListener(this); - } - - @Override - public void openBook(ItemStack itemstack, EnumHand enumhand) { - Item item = itemstack.getItem(); - - if (item == Items.WRITTEN_BOOK) { - if (ItemWrittenBook.a(itemstack, this.getCommandListener(), (EntityHuman) this)) { - this.activeContainer.c(); - } - - this.playerConnection.sendPacket(new PacketPlayOutOpenBook(enumhand)); - } - - } - - @Override - public void a(TileEntityCommand tileentitycommand) { - tileentitycommand.c(true); - this.a((TileEntity) tileentitycommand); - } - - @Override - public void a(Container container, int i, ItemStack itemstack) { - if (!(container.getSlot(i) instanceof SlotResult)) { - if (container == this.defaultContainer) { - CriterionTriggers.e.a(this, this.inventory); - } - - if (!this.e) { - this.playerConnection.sendPacket(new PacketPlayOutSetSlot(container.windowId, i, itemstack)); - } - } - } - - public void updateInventory(Container container) { - this.a(container, container.b()); - } - - @Override - public void a(Container container, NonNullList nonnulllist) { - this.playerConnection.sendPacket(new PacketPlayOutWindowItems(container.windowId, nonnulllist)); - this.playerConnection.sendPacket(new PacketPlayOutSetSlot(-1, -1, this.inventory.getCarried())); - // CraftBukkit start - Send a Set Slot to update the crafting result slot - if (java.util.EnumSet.of(InventoryType.CRAFTING,InventoryType.WORKBENCH).contains(container.getBukkitView().getType())) { - this.playerConnection.sendPacket(new PacketPlayOutSetSlot(container.windowId, 0, container.getSlot(0).getItem())); - } - // CraftBukkit end - } - - @Override - public void setContainerData(Container container, int i, int j) { - this.playerConnection.sendPacket(new PacketPlayOutWindowData(container.windowId, i, j)); - } - - @Override - public void closeInventory() { - // Paper start - closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.UNKNOWN); - } - public void closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason reason) { - CraftEventFactory.handleInventoryCloseEvent(this, reason); // CraftBukkit - // Paper end - this.playerConnection.sendPacket(new PacketPlayOutCloseWindow(this.activeContainer.windowId)); - this.m(); - } - - public void broadcastCarriedItem() { - if (!this.e) { - this.playerConnection.sendPacket(new PacketPlayOutSetSlot(-1, -1, this.inventory.getCarried())); - } - } - - public void m() { - this.activeContainer.b((EntityHuman) this); - this.activeContainer = this.defaultContainer; - } - - public void a(float f, float f1, boolean flag, boolean flag1) { - if (this.isPassenger()) { - if (f >= -1.0F && f <= 1.0F) { - this.bb = f; - } - - if (f1 >= -1.0F && f1 <= 1.0F) { - this.bd = f1; - } - - this.jumping = flag; - this.setSneaking(flag1); - } - - } - - @Override - public void a(Statistic statistic, int i) { - this.serverStatisticManager.b(this, statistic, i); - this.world.getServer().getScoreboardManager().getScoreboardScores(statistic, this.getName(), (scoreboardscore) -> { // CraftBukkit - Get our scores instead - scoreboardscore.addScore(i); - }); - } - - @Override - public void a(Statistic statistic) { - this.serverStatisticManager.setStatistic(this, statistic, 0); - this.world.getServer().getScoreboardManager().getScoreboardScores(statistic, this.getName(), ScoreboardScore::c); // CraftBukkit - Get our scores instead - } - - @Override - public int discoverRecipes(Collection> collection) { - return this.recipeBook.a(collection, this); - } - - @Override - public void a(MinecraftKey[] aminecraftkey) { - List> list = Lists.newArrayList(); - MinecraftKey[] aminecraftkey1 = aminecraftkey; - int i = aminecraftkey.length; - - for (int j = 0; j < i; ++j) { - MinecraftKey minecraftkey = aminecraftkey1[j]; - - this.server.getCraftingManager().a(minecraftkey).ifPresent(list::add); - } - - this.discoverRecipes(list); - } - - @Override - public int undiscoverRecipes(Collection> collection) { - return this.recipeBook.b(collection, this); - } - - @Override - public void giveExp(int i) { - super.giveExp(i); - this.lastSentExp = -1; - } - - public void n() { - this.ct = true; - this.ejectPassengers(); - - // Paper start - Workaround an issue where the vehicle doesn't track the passenger disconnection dismount. - if (this.isPassenger() && this.getVehicle() instanceof EntityPlayer) { - this.stopRiding(); - } - // Paper end - - if (this.isSleeping()) { - this.wakeup(true, false, false); - } - - } - - public boolean o() { - return this.ct; - } - - public void triggerHealthUpdate() { - this.lastHealthSent = -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); - } - } - // CraftBukkit end - - @Override - public void a(IChatBaseComponent ichatbasecomponent, boolean flag) { - this.playerConnection.sendPacket(new PacketPlayOutChat(ichatbasecomponent, flag ? ChatMessageType.GAME_INFO : ChatMessageType.CHAT)); - } - - @Override - protected void q() { - if (!this.activeItem.isEmpty() && this.isHandRaised()) { - this.playerConnection.sendPacket(new PacketPlayOutEntityStatus(this, (byte) 9)); - super.q(); - } - - } - - @Override - public void a(ArgumentAnchor.Anchor argumentanchor_anchor, Vec3D vec3d) { - super.a(argumentanchor_anchor, vec3d); - this.playerConnection.sendPacket(new PacketPlayOutLookAt(argumentanchor_anchor, vec3d.x, vec3d.y, vec3d.z)); - } - - public void a(ArgumentAnchor.Anchor argumentanchor_anchor, Entity entity, ArgumentAnchor.Anchor argumentanchor_anchor1) { - Vec3D vec3d = argumentanchor_anchor1.a(entity); - - super.a(argumentanchor_anchor, vec3d); - this.playerConnection.sendPacket(new PacketPlayOutLookAt(argumentanchor_anchor, entity, argumentanchor_anchor1)); - } - - public void copyFrom(EntityPlayer entityplayer, boolean flag) { - if (flag) { - this.inventory.a(entityplayer.inventory); - this.setHealth(entityplayer.getHealth()); - this.foodData = entityplayer.foodData; - this.expLevel = entityplayer.expLevel; - this.expTotal = entityplayer.expTotal; - this.exp = entityplayer.exp; - this.setScore(entityplayer.getScore()); - this.al = entityplayer.al; - this.am = entityplayer.am; - this.an = entityplayer.an; - } else if (this.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY) || entityplayer.isSpectator()) { - this.inventory.a(entityplayer.inventory); - this.expLevel = entityplayer.expLevel; - this.expTotal = entityplayer.expTotal; - this.exp = entityplayer.exp; - this.setScore(entityplayer.getScore()); - } - - this.bR = entityplayer.bR; - this.enderChest = entityplayer.enderChest; - this.getDataWatcher().set(EntityPlayer.bt, entityplayer.getDataWatcher().get(EntityPlayer.bt)); - this.lastSentExp = -1; - this.lastHealthSent = -1.0F; - this.lastFoodSent = -1; - // this.recipeBook.a((RecipeBook) entityplayer.recipeBook); // CraftBukkit - // Paper start - Optimize remove queue - vanilla copies player objects, but CB doesn't. This method currently only - // Applies to the same player, so we need to not duplicate our removal queue. The rest of this method does "resetting" - // type logic so it does need to be called, maybe? This is silly. - //this.removeQueue.addAll(entityplayer.removeQueue); - if (this.removeQueue != entityplayer.removeQueue) { - this.removeQueue.addAll(entityplayer.removeQueue); - } - // Paper end - this.cp = entityplayer.cp; - this.cu = entityplayer.cu; - this.setShoulderEntityLeft(entityplayer.getShoulderEntityLeft()); - this.setShoulderEntityRight(entityplayer.getShoulderEntityRight()); - - this.inLava = false; // SPIGOT-4767 - } - - @Override - protected void a(MobEffect mobeffect) { - super.a(mobeffect); - this.playerConnection.sendPacket(new PacketPlayOutEntityEffect(this.getId(), mobeffect)); - if (mobeffect.getMobEffect() == MobEffects.LEVITATION) { - this.cs = this.ticksLived; - this.cr = new Vec3D(this.locX, this.locY, this.locZ); - } - - CriterionTriggers.A.a(this); - } - - @Override - protected void a(MobEffect mobeffect, boolean flag) { - super.a(mobeffect, flag); - this.playerConnection.sendPacket(new PacketPlayOutEntityEffect(this.getId(), mobeffect)); - CriterionTriggers.A.a(this); - } - - @Override - protected void b(MobEffect mobeffect) { - super.b(mobeffect); - this.playerConnection.sendPacket(new PacketPlayOutRemoveEntityEffect(this.getId(), mobeffect.getMobEffect())); - if (mobeffect.getMobEffect() == MobEffects.LEVITATION) { - this.cr = null; - } - - CriterionTriggers.A.a(this); - } - - @Override - public void enderTeleportTo(double d0, double d1, double d2) { - this.playerConnection.a(d0, d1, d2, this.yaw, this.pitch); - } - - @Override - public void a(Entity entity) { - this.getWorldServer().getChunkProvider().broadcastIncludingSelf(this, new PacketPlayOutAnimation(entity, 4)); - } - - @Override - public void b(Entity entity) { - this.getWorldServer().getChunkProvider().broadcastIncludingSelf(this, new PacketPlayOutAnimation(entity, 5)); - } - - @Override - public void updateAbilities() { - if (this.playerConnection != null) { - this.playerConnection.sendPacket(new PacketPlayOutAbilities(this.abilities)); - this.C(); - } - } - - public WorldServer getWorldServer() { - return (WorldServer) this.world; - } - - @Override - public void a(EnumGamemode enumgamemode) { - // CraftBukkit start - if (enumgamemode == this.playerInteractManager.getGameMode()) { - return; - } - - PlayerGameModeChangeEvent event = new PlayerGameModeChangeEvent(getBukkitEntity(), GameMode.getByValue(enumgamemode.getId())); - world.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - // CraftBukkit end - - this.playerInteractManager.setGameMode(enumgamemode); - this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(3, (float) enumgamemode.getId())); - if (enumgamemode == EnumGamemode.SPECTATOR) { - this.releaseShoulderEntities(); - this.stopRiding(); - } else { - this.setSpectatorTarget(this); - } - - this.updateAbilities(); - this.dh(); - } - - @Override - public boolean isSpectator() { - return this.playerInteractManager.getGameMode() == EnumGamemode.SPECTATOR; - } - - @Override - public boolean isCreative() { - return this.playerInteractManager.getGameMode() == EnumGamemode.CREATIVE; - } - - @Override - public void sendMessage(IChatBaseComponent ichatbasecomponent) { - this.a(ichatbasecomponent, ChatMessageType.SYSTEM); - } - - public void a(IChatBaseComponent ichatbasecomponent, ChatMessageType chatmessagetype) { - this.playerConnection.a((Packet) (new PacketPlayOutChat(ichatbasecomponent, chatmessagetype)), (future) -> { - if (!future.isSuccess() && (chatmessagetype == ChatMessageType.GAME_INFO || chatmessagetype == ChatMessageType.SYSTEM)) { - boolean flag = true; - String s = ichatbasecomponent.a(256); - IChatBaseComponent ichatbasecomponent1 = (new ChatComponentText(s)).a(EnumChatFormat.YELLOW); - - this.playerConnection.sendPacket(new PacketPlayOutChat((new ChatMessage("multiplayer.message_not_delivered", new Object[]{ichatbasecomponent1})).a(EnumChatFormat.RED), ChatMessageType.SYSTEM)); - } - - }); - } - - public String v() { - 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) { - // CraftBukkit start - if (getMainHand() != packetplayinsettings.getMainHand()) { - PlayerChangedMainHandEvent event = new PlayerChangedMainHandEvent(getBukkitEntity(), getMainHand() == EnumMainHand.LEFT ? MainHand.LEFT : MainHand.RIGHT); - this.server.server.getPluginManager().callEvent(event); - } - if (this.locale == null || !this.locale.equals(packetplayinsettings.b())) { // Paper - check for null - PlayerLocaleChangeEvent event = new PlayerLocaleChangeEvent(getBukkitEntity(), packetplayinsettings.b()); - this.server.server.getPluginManager().callEvent(event); - } - this.clientViewDistance = packetplayinsettings.viewDistance; - // CraftBukkit end - // Paper start - add PlayerLocaleChangeEvent - // Since the field is initialized to null, this event should always fire the first time the packet is received - String oldLocale = this.locale; - this.locale = packetplayinsettings.b(); - if (!this.locale.equals(oldLocale)) { - new com.destroystokyo.paper.event.player.PlayerLocaleChangeEvent(this.getBukkitEntity(), oldLocale, this.locale).callEvent(); - } - // Paper end - this.ck = packetplayinsettings.d(); - this.cl = packetplayinsettings.e(); - this.getDataWatcher().set(EntityPlayer.bt, (byte) packetplayinsettings.f()); - this.getDataWatcher().set(EntityPlayer.bu, (byte) (packetplayinsettings.getMainHand() == EnumMainHand.LEFT ? 0 : 1)); - } - - public EnumChatVisibility getChatFlags() { - return this.ck; - } - - public void setResourcePack(String s, String s1) { - this.playerConnection.sendPacket(new PacketPlayOutResourcePackSend(s, s1)); - } - - @Override - protected int y() { - return this.server.a(this.getProfile()); - } - - public void resetIdleTimer() { - this.cm = SystemUtils.getMonotonicMillis(); - } - - public ServerStatisticManager getStatisticManager() { - return this.serverStatisticManager; - } - - public RecipeBookServer B() { - return this.recipeBook; - } - - public void c(Entity entity) { - if (entity instanceof EntityHuman) { - this.playerConnection.sendPacket(new PacketPlayOutEntityDestroy(new int[]{entity.getId()})); - } else { - this.removeQueue.add((Integer) entity.getId()); // CraftBukkit - decompile error - } - - } - - public void d(Entity entity) { - this.removeQueue.remove((Integer) entity.getId()); // CraftBukkit - decompile error - } - - @Override - protected void C() { - if (this.isSpectator()) { - this.cy(); - this.setInvisible(true); - } else { - super.C(); - } - - } - - public Entity getSpecatorTarget() { - return (Entity) (this.spectatedEntity == null ? this : this.spectatedEntity); - } - - public void setSpectatorTarget(Entity newSpectatorTarget) { - // Paper start - Add PlayerStartSpectatingEntityEvent and PlayerStopSpectatingEntity Event - Entity entity1 = this.getSpecatorTarget(); - - if (newSpectatorTarget == null) { - newSpectatorTarget = this; - } - - if (entity1 == newSpectatorTarget) return; // new spec target is the current spec target - - if (newSpectatorTarget == this) { - com.destroystokyo.paper.event.player.PlayerStopSpectatingEntityEvent playerStopSpectatingEntityEvent = new com.destroystokyo.paper.event.player.PlayerStopSpectatingEntityEvent(this.getBukkitEntity(), entity1.getBukkitEntity()); - - if (!playerStopSpectatingEntityEvent.callEvent()) { - return; - } - } else { - com.destroystokyo.paper.event.player.PlayerStartSpectatingEntityEvent playerStartSpectatingEntityEvent = new com.destroystokyo.paper.event.player.PlayerStartSpectatingEntityEvent(this.getBukkitEntity(), entity1.getBukkitEntity(), newSpectatorTarget.getBukkitEntity()); - - if (!playerStartSpectatingEntityEvent.callEvent()) { - return; - } - } - - setSpectatorTargetField(newSpectatorTarget); - - this.playerConnection.sendPacket(new PacketPlayOutCamera(newSpectatorTarget)); - this.playerConnection.a(this.spectatedEntity.locX, this.spectatedEntity.locY, this.spectatedEntity.locZ, this.yaw, this.pitch, TeleportCause.SPECTATE); // CraftBukkit - // Paper end - } - - @Override - protected void E() { - if (this.portalCooldown > 0 && !this.worldChangeInvuln) { - --this.portalCooldown; - } - - } - - @Override - public void attack(Entity entity) { - if (this.playerInteractManager.getGameMode() == EnumGamemode.SPECTATOR) { - this.setSpectatorTarget(entity); - } else { - super.attack(entity); - } - - } - - public long F() { - return this.cm; - } - - @Nullable - public IChatBaseComponent getPlayerListName() { - return listName; // CraftBukkit - } - - @Override - public void a(EnumHand enumhand) { - super.a(enumhand); - this.dZ(); - } - - public boolean H() { - return this.worldChangeInvuln; - } - - public void I() { - this.worldChangeInvuln = false; - } - - public void J() { - if (!CraftEventFactory.callToggleGlideEvent(this, true).isCancelled()) // CraftBukkit - this.setFlag(7, true); - } - - public void K() { - // CraftBukkit start - if (!CraftEventFactory.callToggleGlideEvent(this, false).isCancelled()) { - this.setFlag(7, true); - this.setFlag(7, false); - } - // CraftBukkit end - } - - public AdvancementDataPlayer getAdvancementData() { - return this.advancementDataPlayer; - } - - // CraftBukkit start - public void a(WorldServer worldserver, double d0, double d1, double d2, float f, float f1) { - this.a(worldserver, d0, d1, d2, f, f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.UNKNOWN); - } - - public void a(WorldServer worldserver, double d0, double d1, double d2, float f, float f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause cause) { - // CraftBukkit end - this.setSpectatorTarget(this); - this.stopRiding(); - /* CraftBukkit start - replace with bukkit handling for multi-world - if (worldserver == this.world) { - this.playerConnection.a(d0, d1, d2, f, f1); - } else { - WorldServer worldserver1 = this.getWorldServer(); - - this.dimension = worldserver.worldProvider.getDimensionManager(); - WorldData worlddata = worldserver.getWorldData(); - - this.playerConnection.sendPacket(new PacketPlayOutRespawn(this.dimension, worlddata.getType(), this.playerInteractManager.getGameMode())); - this.playerConnection.sendPacket(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); - this.server.getPlayerList().d(this); - worldserver1.removePlayer(this); - this.dead = false; - this.setPositionRotation(d0, d1, d2, f, f1); - this.spawnIn(worldserver); - worldserver.addPlayerCommand(this); - this.b(worldserver1); - this.playerConnection.a(d0, d1, d2, f, f1); - this.playerInteractManager.a(worldserver); - this.server.getPlayerList().a(this, worldserver); - this.server.getPlayerList().updateClient(this); - } - */ - this.getBukkitEntity().teleport(new Location(worldserver.getWorld(), d0, d1, d2, f, f1), cause); - // CraftBukkit end - - } - - public void a(ChunkCoordIntPair chunkcoordintpair, Packet packet, Packet packet1) { - this.playerConnection.sendPacket(packet1); - this.playerConnection.sendPacket(packet); - } - - public void a(ChunkCoordIntPair chunkcoordintpair) { - this.playerConnection.sendPacket(new PacketPlayOutUnloadChunk(chunkcoordintpair.x, chunkcoordintpair.z)); - } - - public SectionPosition getPlayerMapSection() { return this.M(); } // Paper - OBFHELPER - public SectionPosition M() { - return this.cv; - } - - public void a(SectionPosition sectionposition) { - this.cv = sectionposition; - } - - @Override - public void a(SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) { - this.playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(soundeffect, soundcategory, this.locX, this.locY, this.locZ, f, f1)); - } - - @Override - public Packet N() { - return new PacketPlayOutNamedEntitySpawn(this); - } - - @Override - public EntityItem a(ItemStack itemstack, boolean flag, boolean flag1) { - EntityItem entityitem = super.a(itemstack, flag, flag1); - - if (entityitem == null) { - return null; - } else { - this.world.addEntity(entityitem); - ItemStack itemstack1 = entityitem.getItemStack(); - - if (flag1) { - if (!itemstack1.isEmpty()) { - this.a(StatisticList.ITEM_DROPPED.b(itemstack1.getItem()), itemstack.getCount()); - } - - this.a(StatisticList.DROP); - } - - return entityitem; - } - } - - // CraftBukkit start - Add per-player time and weather. - public long timeOffset = 0; - public boolean relativeTime = true; - - 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 weather = null; - - 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)); - } - } - - private float pluginRainPosition; - private float pluginRainPositionPrevious; - - 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.01; - } else { - pluginRainPosition -= 0.01; - } - - 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 + ")"; - } - - // SPIGOT-1903, MC-98153 - public void forceSetPositionRotation(double x, double y, double z, float yaw, float pitch) { - this.setPositionRotation(x, y, z, yaw, pitch); - this.playerConnection.syncPosition(); - } - - @Override - protected boolean isFrozen() { - return super.isFrozen() || (this.playerConnection != null && this.playerConnection.isDisconnected()); // Paper - } - - @Override - public Scoreboard getScoreboard() { - return getBukkitEntity().getScoreboard().getHandle(); - } - - public void reset() { - float exp = 0; - boolean keepInventory = this.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY); - - if (this.keepLevel || keepInventory) { - exp = this.exp; - this.newTotalExp = this.expTotal; - this.newLevel = this.expLevel; - } - - this.setHealth(this.getMaxHealth()); - this.setAirTicks(this.getMaxAirTicks()); // Paper - 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.setArrowCount(0); - this.removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.DEATH); - 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(); - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/EntityPotion.java b/src/main/java/net/minecraft/server/EntityPotion.java deleted file mode 100644 index 998336557..000000000 --- a/src/main/java/net/minecraft/server/EntityPotion.java +++ /dev/null @@ -1,268 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.function.Predicate; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -// CraftBukkit start -import java.util.HashMap; -import java.util.Map; -import org.bukkit.craftbukkit.entity.CraftLivingEntity; -import org.bukkit.entity.LivingEntity; -// CraftBukkit end - -public class EntityPotion extends EntityProjectile { - - private static final DataWatcherObject f = DataWatcher.a(EntityPotion.class, DataWatcherRegistry.g); - private static final Logger LOGGER = LogManager.getLogger(); - public static final Predicate e = EntityPotion::a; - - public EntityPotion(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityPotion(World world, EntityLiving entityliving) { - super(EntityTypes.POTION, entityliving, world); - } - - public EntityPotion(World world, double d0, double d1, double d2) { - super(EntityTypes.POTION, d0, d1, d2, world); - } - - @Override - protected void initDatawatcher() { - this.getDataWatcher().register(EntityPotion.f, ItemStack.a); - } - - public ItemStack getItem() { - ItemStack itemstack = (ItemStack) this.getDataWatcher().get(EntityPotion.f); - - if (itemstack.getItem() != Items.SPLASH_POTION && itemstack.getItem() != Items.LINGERING_POTION) { - if (this.world != null) { - EntityPotion.LOGGER.error("ThrownPotion entity {} has no item?!", this.getId()); - } - - return new ItemStack(Items.SPLASH_POTION); - } else { - return itemstack; - } - } - - public void setItem(ItemStack itemstack) { - this.getDataWatcher().set(EntityPotion.f, itemstack.cloneItemStack()); - } - - @Override - protected float l() { - return 0.05F; - } - - @Override - protected void a(MovingObjectPosition movingobjectposition) { - if (!this.world.isClientSide) { - ItemStack itemstack = this.getItem(); - PotionRegistry potionregistry = PotionUtil.d(itemstack); - List list = PotionUtil.getEffects(itemstack); - boolean flag = potionregistry == Potions.WATER && list.isEmpty(); - - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK && flag) { - MovingObjectPositionBlock movingobjectpositionblock = (MovingObjectPositionBlock) movingobjectposition; - EnumDirection enumdirection = movingobjectpositionblock.getDirection(); - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition().shift(enumdirection); - - this.a(blockposition, enumdirection); - this.a(blockposition.shift(enumdirection.opposite()), enumdirection); - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection1 = (EnumDirection) iterator.next(); - - this.a(blockposition.shift(enumdirection1), enumdirection1); - } - } - - if (flag) { - this.splash(); - } else if (true || !list.isEmpty()) { // CraftBukkit - Call event even if no effects to apply - if (this.isLingering()) { - this.a(itemstack, potionregistry); - } else { - this.a(list, movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY ? ((MovingObjectPositionEntity) movingobjectposition).getEntity() : null); - } - } - - int i = potionregistry.b() ? 2007 : 2002; - - this.world.triggerEffect(i, new BlockPosition(this), PotionUtil.c(itemstack)); - this.die(); - } - } - - private void splash() { - AxisAlignedBB axisalignedbb = this.getBoundingBox().grow(4.0D, 2.0D, 4.0D); - List list = this.world.a(EntityLiving.class, axisalignedbb, EntityPotion.e); - - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityLiving entityliving = (EntityLiving) iterator.next(); - double d0 = this.h(entityliving); - - if (d0 < 16.0D && a(entityliving)) { - entityliving.damageEntity(DamageSource.c(entityliving, this.getShooter()), 1.0F); - } - } - } - - } - - private void a(List list, @Nullable Entity entity) { - AxisAlignedBB axisalignedbb = this.getBoundingBox().grow(4.0D, 2.0D, 4.0D); - List list1 = this.world.a(EntityLiving.class, axisalignedbb); - Map affected = new HashMap(); // CraftBukkit - - if (!list1.isEmpty()) { - Iterator iterator = list1.iterator(); - - while (iterator.hasNext()) { - EntityLiving entityliving = (EntityLiving) iterator.next(); - - if (entityliving.dt()) { - double d0 = this.h(entityliving); - - if (d0 < 16.0D) { - double d1 = 1.0D - Math.sqrt(d0) / 4.0D; - - if (entityliving == 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); - 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 - - Iterator iterator1 = list.iterator(); - - while (iterator1.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator1.next(); - MobEffectList mobeffectlist = mobeffect.getMobEffect(); - // CraftBukkit start - Abide by PVP settings - for players only! - if (!this.world.pvpMode && this.getShooter() instanceof EntityPlayer && entityliving instanceof EntityPlayer && entityliving != this.getShooter()) { - int i = MobEffectList.getId(mobeffectlist); - // 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.isInstant()) { - mobeffectlist.applyInstantEffect(this, this.getShooter(), entityliving, mobeffect.getAmplifier(), d1); - } else { - int i = (int) (d1 * (double) mobeffect.getDuration() + 0.5D); - - if (i > 20) { - entityliving.addEffect(new MobEffect(mobeffectlist, i, mobeffect.getAmplifier(), mobeffect.isAmbient(), mobeffect.isShowParticles()), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.POTION_SPLASH); // CraftBukkit - } - } - } - } - } - - } - - private void a(ItemStack itemstack, PotionRegistry potionregistry) { - EntityAreaEffectCloud entityareaeffectcloud = new EntityAreaEffectCloud(this.world, this.locX, this.locY, this.locZ); - - entityareaeffectcloud.setSource(this.getShooter()); - entityareaeffectcloud.setRadius(3.0F); - entityareaeffectcloud.setRadiusOnUse(-0.5F); - entityareaeffectcloud.setWaitTime(10); - entityareaeffectcloud.setRadiusPerTick(-entityareaeffectcloud.getRadius() / (float) entityareaeffectcloud.getDuration()); - entityareaeffectcloud.a(potionregistry); - Iterator iterator = PotionUtil.b(itemstack).iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - entityareaeffectcloud.addEffect(new MobEffect(mobeffect)); - } - - NBTTagCompound nbttagcompound = itemstack.getTag(); - - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("CustomPotionColor", 99)) { - entityareaeffectcloud.setColor(nbttagcompound.getInt("CustomPotionColor")); - } - - // CraftBukkit start - org.bukkit.event.entity.LingeringPotionSplashEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callLingeringPotionSplashEvent(this, entityareaeffectcloud); - if (!(event.isCancelled() || entityareaeffectcloud.dead)) { - this.world.addEntity(entityareaeffectcloud); - } else { - entityareaeffectcloud.dead = true; - } - // CraftBukkit end - } - - public boolean isLingering() { - return this.getItem().getItem() == Items.LINGERING_POTION; - } - - private void a(BlockPosition blockposition, EnumDirection enumdirection) { - IBlockData iblockdata = this.world.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (block == Blocks.FIRE) { - this.world.douseFire((EntityHuman) null, blockposition.shift(enumdirection), enumdirection.opposite()); - } else if (block == Blocks.CAMPFIRE && (Boolean) iblockdata.get(BlockCampfire.b)) { - this.world.a((EntityHuman) null, 1009, blockposition, 0); - this.world.setTypeUpdate(blockposition, (IBlockData) iblockdata.set(BlockCampfire.b, false)); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - ItemStack itemstack = ItemStack.a(nbttagcompound.getCompound("Potion")); - - if (itemstack.isEmpty()) { - this.die(); - } else { - this.setItem(itemstack); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - ItemStack itemstack = this.getItem(); - - if (!itemstack.isEmpty()) { - nbttagcompound.set("Potion", itemstack.save(new NBTTagCompound())); - } - - } - - private static boolean a(EntityLiving entityliving) { - return entityliving instanceof EntityEnderman || entityliving instanceof EntityBlaze; - } -} diff --git a/src/main/java/net/minecraft/server/EntityProjectile.java b/src/main/java/net/minecraft/server/EntityProjectile.java deleted file mode 100644 index bd4ca73f6..000000000 --- a/src/main/java/net/minecraft/server/EntityProjectile.java +++ /dev/null @@ -1,241 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.UUID; -import javax.annotation.Nullable; - -public abstract class EntityProjectile extends Entity implements IProjectile { - - private int blockX; - private int blockY; - private int blockZ; - protected boolean inGround; - public int shake; - public EntityLiving shooter; - public UUID shooterId; - private Entity as; - private int at; - - protected EntityProjectile(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.blockX = -1; - this.blockY = -1; - this.blockZ = -1; - } - - protected EntityProjectile(EntityTypes entitytypes, double d0, double d1, double d2, World world) { - this(entitytypes, world); - this.setPosition(d0, d1, d2); - } - - protected EntityProjectile(EntityTypes entitytypes, EntityLiving entityliving, World world) { - this(entitytypes, entityliving.locX, entityliving.locY + (double) entityliving.getHeadHeight() - 0.10000000149011612D, entityliving.locZ, world); - this.shooter = entityliving; - this.shooterId = entityliving.getUniqueID(); - this.projectileSource = (org.bukkit.entity.LivingEntity) entityliving.getBukkitEntity(); // CraftBukkit - } - - public void a(Entity entity, float f, float f1, float f2, float f3, float f4) { - float f5 = -MathHelper.sin(f1 * 0.017453292F) * MathHelper.cos(f * 0.017453292F); - float f6 = -MathHelper.sin((f + f2) * 0.017453292F); - float f7 = MathHelper.cos(f1 * 0.017453292F) * MathHelper.cos(f * 0.017453292F); - - this.shoot((double) f5, (double) f6, (double) f7, f3, f4); - Vec3D vec3d = entity.getMot(); - - if (!entity.world.paperConfig.disableRelativeProjectileVelocity) this.setMot(this.getMot().add(vec3d.x, entity.onGround ? 0.0D : vec3d.y, vec3d.z)); // Paper - allow disabling relative velocity - } - - @Override - public void shoot(double d0, double d1, double d2, float f, float f1) { - Vec3D vec3d = (new Vec3D(d0, d1, d2)).d().add(this.random.nextGaussian() * 0.007499999832361937D * (double) f1, this.random.nextGaussian() * 0.007499999832361937D * (double) f1, this.random.nextGaussian() * 0.007499999832361937D * (double) f1).a((double) f); - - this.setMot(vec3d); - float f2 = MathHelper.sqrt(b(vec3d)); - - this.yaw = (float) (MathHelper.d(vec3d.x, vec3d.z) * 57.2957763671875D); - this.pitch = (float) (MathHelper.d(vec3d.y, (double) f2) * 57.2957763671875D); - this.lastYaw = this.yaw; - this.lastPitch = this.pitch; - } - - @Override - public void tick() { - this.H = this.locX; - this.I = this.locY; - this.J = this.locZ; - super.tick(); - if (this.shake > 0) { - --this.shake; - } - - if (this.inGround) { - this.inGround = false; - this.setMot(this.getMot().d((double) (this.random.nextFloat() * 0.2F), (double) (this.random.nextFloat() * 0.2F), (double) (this.random.nextFloat() * 0.2F))); - } - - AxisAlignedBB axisalignedbb = this.getBoundingBox().a(this.getMot()).g(1.0D); - Iterator iterator = this.world.getEntities(this, axisalignedbb, (entity) -> { - return !entity.isSpectator() && entity.isInteractable(); - }).iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (entity == this.as) { - ++this.at; - break; - } - - if (this.shooter != null && this.ticksLived < 2 && this.as == null && this.shooter == entity) { // CraftBukkit - MC-88491 - this.as = entity; - this.at = 3; - break; - } - } - - MovingObjectPosition movingobjectposition = ProjectileHelper.a(this, axisalignedbb, (entity1) -> { - return !entity1.isSpectator() && entity1.isInteractable() && entity1 != this.as; - }, RayTrace.BlockCollisionOption.OUTLINE, true); - - if (this.as != null && this.at-- <= 0) { - this.as = null; - } - - // Paper start - Call ProjectileCollideEvent - if (movingobjectposition instanceof MovingObjectPositionEntity) { - com.destroystokyo.paper.event.entity.ProjectileCollideEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileCollideEvent(this, (MovingObjectPositionEntity)movingobjectposition); - if (event.isCancelled()) { - movingobjectposition = null; - } - } - // Paper end - - if (movingobjectposition != null && movingobjectposition.getType() != MovingObjectPosition.EnumMovingObjectType.MISS) { // Paper - add null check in case cancelled - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK && this.world.getType(((MovingObjectPositionBlock) movingobjectposition).getBlockPosition()).getBlock() == Blocks.NETHER_PORTAL) { - this.c(((MovingObjectPositionBlock) movingobjectposition).getBlockPosition()); - } else { - this.a(movingobjectposition); - // CraftBukkit start - if (this.dead) { - org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileHitEvent(this, movingobjectposition); - } - // CraftBukkit end - } - } - - Vec3D vec3d = this.getMot(); - - this.locX += vec3d.x; - this.locY += vec3d.y; - this.locZ += vec3d.z; - float f = MathHelper.sqrt(b(vec3d)); - - this.yaw = (float) (MathHelper.d(vec3d.x, vec3d.z) * 57.2957763671875D); - - for (this.pitch = (float) (MathHelper.d(vec3d.y, (double) f) * 57.2957763671875D); 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 = MathHelper.g(0.2F, this.lastPitch, this.pitch); - this.yaw = MathHelper.g(0.2F, this.lastYaw, this.yaw); - float f1; - - if (this.isInWater()) { - for (int i = 0; i < 4; ++i) { - float f2 = 0.25F; - - this.world.addParticle(Particles.BUBBLE, this.locX - vec3d.x * 0.25D, this.locY - vec3d.y * 0.25D, this.locZ - vec3d.z * 0.25D, vec3d.x, vec3d.y, vec3d.z); - } - - f1 = 0.8F; - } else { - f1 = 0.99F; - } - - this.setMot(vec3d.a((double) f1)); - if (!this.isNoGravity()) { - Vec3D vec3d1 = this.getMot(); - - this.setMot(vec3d1.x, vec3d1.y - (double) this.l(), vec3d1.z); - } - - this.setPosition(this.locX, this.locY, this.locZ); - } - - protected float l() { - return 0.03F; - } - - protected abstract void a(MovingObjectPosition movingobjectposition); - - @Override - public void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setInt("xTile", this.blockX); - nbttagcompound.setInt("yTile", this.blockY); - nbttagcompound.setInt("zTile", this.blockZ); - nbttagcompound.setByte("shake", (byte) this.shake); - nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); - if (this.shooterId != null) { - nbttagcompound.set("owner", GameProfileSerializer.a(this.shooterId)); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.blockX = nbttagcompound.getInt("xTile"); - this.blockY = nbttagcompound.getInt("yTile"); - this.blockZ = nbttagcompound.getInt("zTile"); - this.shake = nbttagcompound.getByte("shake") & 255; - this.inGround = nbttagcompound.getByte("inGround") == 1; - this.shooter = null; - if (nbttagcompound.hasKeyOfType("owner", 10)) { - this.shooterId = GameProfileSerializer.b(nbttagcompound.getCompound("owner")); - } - if (this instanceof EntityEnderPearl && this.world != null && this.world.paperConfig.disableEnderpearlExploit) { this.shooterId = null; } // Paper - Don't store shooter name for pearls to block enderpearl travel exploit - - } - - @Nullable - public EntityLiving getShooter() { - if (this.shooter == null && this.shooterId != null && this.world instanceof WorldServer) { - Entity entity = ((WorldServer) this.world).getEntity(this.shooterId); - // Paper start - MC-50319 - shooter might be in another world (arrows through portals) - if (entity == null) { - for (WorldServer world : world.getMinecraftServer().getWorlds()) { - entity = world.getEntity(this.shooterId); - if (entity != null) { - break; - } - } - } - // Paper end - - if (entity instanceof EntityLiving) { - this.shooter = (EntityLiving) entity; - } else { - //this.shooterId = null; // Paper - don't unset shooterId - } - } - - return this.shooter; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntityPufferFish.java b/src/main/java/net/minecraft/server/EntityPufferFish.java deleted file mode 100644 index f5d384add..000000000 --- a/src/main/java/net/minecraft/server/EntityPufferFish.java +++ /dev/null @@ -1,203 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.function.Predicate; - -public class EntityPufferFish extends EntityFish { - - private static final DataWatcherObject b = DataWatcher.a(EntityPufferFish.class, DataWatcherRegistry.b); - private int c; - private int d; - private static final Predicate bz = (entityliving) -> { - return entityliving == null ? false : (entityliving instanceof EntityHuman && (entityliving.isSpectator() || ((EntityHuman) entityliving).isCreative()) ? false : entityliving.getMonsterType() != EnumMonsterType.e); - }; - - public EntityPufferFish(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityPufferFish.b, 0); - } - - public int getPuffState() { - return (Integer) this.datawatcher.get(EntityPufferFish.b); - } - - public void setPuffState(int i) { - this.datawatcher.set(EntityPufferFish.b, i); - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityPufferFish.b.equals(datawatcherobject)) { - this.updateSize(); - } - - super.a(datawatcherobject); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("PuffState", this.getPuffState()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setPuffState(nbttagcompound.getInt("PuffState")); - } - - @Override - protected ItemStack l() { - return new ItemStack(Items.PUFFERFISH_BUCKET); - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(1, new EntityPufferFish.a(this)); - } - - @Override - public void tick() { - if (!this.world.isClientSide && this.isAlive() && this.df()) { - if (this.c > 0) { - if (this.getPuffState() == 0) { - this.a(SoundEffects.ENTITY_PUFFER_FISH_BLOW_UP, this.getSoundVolume(), this.cV()); - this.setPuffState(1); - } else if (this.c > 40 && this.getPuffState() == 1) { - this.a(SoundEffects.ENTITY_PUFFER_FISH_BLOW_UP, this.getSoundVolume(), this.cV()); - this.setPuffState(2); - } - - ++this.c; - } else if (this.getPuffState() != 0) { - if (this.d > 60 && this.getPuffState() == 2) { - this.a(SoundEffects.ENTITY_PUFFER_FISH_BLOW_OUT, this.getSoundVolume(), this.cV()); - this.setPuffState(1); - } else if (this.d > 100 && this.getPuffState() == 1) { - this.a(SoundEffects.ENTITY_PUFFER_FISH_BLOW_OUT, this.getSoundVolume(), this.cV()); - this.setPuffState(0); - } - - ++this.d; - } - } - - super.tick(); - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.isAlive() && this.getPuffState() > 0) { - List list = this.world.a(EntityInsentient.class, this.getBoundingBox().g(0.3D), EntityPufferFish.bz); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityInsentient entityinsentient = (EntityInsentient) iterator.next(); - - if (entityinsentient.isAlive()) { - this.a(entityinsentient); - } - } - } - - } - - private void a(EntityInsentient entityinsentient) { - int i = this.getPuffState(); - - if (entityinsentient.damageEntity(DamageSource.mobAttack(this), (float) (1 + i))) { - entityinsentient.addEffect(new MobEffect(MobEffects.POISON, 60 * i, 0), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - this.a(SoundEffects.ENTITY_PUFFER_FISH_STING, 1.0F, 1.0F); - } - - } - - @Override - public void pickup(EntityHuman entityhuman) { - int i = this.getPuffState(); - - if (entityhuman instanceof EntityPlayer && i > 0 && entityhuman.damageEntity(DamageSource.mobAttack(this), (float) (1 + i))) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutGameStateChange(9, 0.0F)); - entityhuman.addEffect(new MobEffect(MobEffects.POISON, 60 * i, 0), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_PUFFER_FISH_AMBIENT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_PUFFER_FISH_DEATH; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_PUFFER_FISH_HURT; - } - - @Override - protected SoundEffect getSoundFlop() { - return SoundEffects.ENTITY_PUFFER_FISH_FLOP; - } - - @Override - public EntitySize a(EntityPose entitypose) { - return super.a(entitypose).a(r(this.getPuffState())); - } - - private static float r(int i) { - switch (i) { - case 0: - return 0.5F; - case 1: - return 0.7F; - default: - return 1.0F; - } - } - - static class a extends PathfinderGoal { - - private final EntityPufferFish a; - - public a(EntityPufferFish entitypufferfish) { - this.a = entitypufferfish; - } - - @Override - public boolean a() { - List list = this.a.world.a(EntityLiving.class, this.a.getBoundingBox().g(2.0D), EntityPufferFish.bz); - - return !list.isEmpty(); - } - - @Override - public void c() { - this.a.c = 1; - this.a.d = 0; - } - - @Override - public void d() { - this.a.c = 0; - } - - @Override - public boolean b() { - List list = this.a.world.a(EntityLiving.class, this.a.getBoundingBox().g(2.0D), EntityPufferFish.bz); - - return !list.isEmpty(); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityRabbit.java b/src/main/java/net/minecraft/server/EntityRabbit.java deleted file mode 100644 index 10fca4977..000000000 --- a/src/main/java/net/minecraft/server/EntityRabbit.java +++ /dev/null @@ -1,557 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public class EntityRabbit extends EntityAnimal { - - private static final DataWatcherObject bz = DataWatcher.a(EntityRabbit.class, DataWatcherRegistry.b); - private static final MinecraftKey bA = new MinecraftKey("killer_bunny"); - private int bB; - private int bC; - private boolean bD; - private int bE; - private int bF; - - public EntityRabbit(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.bt = new EntityRabbit.ControllerJumpRabbit(this); - this.moveController = new EntityRabbit.ControllerMoveRabbit(this); - this.initializePathFinderGoals(); // CraftBukkit - moved code - } - - // CraftBukkit start - code from constructor - public void initializePathFinderGoals(){ - this.d(0.0D); - } - // CraftBukkit end - - @Override - protected void initPathfinder() { - this.goalSelector.a(1, new PathfinderGoalFloat(this)); - this.goalSelector.a(1, new EntityRabbit.PathfinderGoalRabbitPanic(this, 2.2D)); - this.goalSelector.a(2, new PathfinderGoalBreed(this, 0.8D)); - this.goalSelector.a(3, new PathfinderGoalTempt(this, 1.0D, RecipeItemStack.a(Items.CARROT, Items.GOLDEN_CARROT, Blocks.DANDELION), false)); - this.goalSelector.a(4, new EntityRabbit.PathfinderGoalRabbitAvoidTarget<>(this, EntityHuman.class, 8.0F, 2.2D, 2.2D)); - this.goalSelector.a(4, new EntityRabbit.PathfinderGoalRabbitAvoidTarget<>(this, EntityWolf.class, 10.0F, 2.2D, 2.2D)); - this.goalSelector.a(4, new EntityRabbit.PathfinderGoalRabbitAvoidTarget<>(this, EntityMonster.class, 4.0F, 2.2D, 2.2D)); - this.goalSelector.a(5, new EntityRabbit.PathfinderGoalEatCarrots(this)); - this.goalSelector.a(6, new PathfinderGoalRandomStrollLand(this, 0.6D)); - this.goalSelector.a(11, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 10.0F)); - } - - @Override - protected float cX() { - if (!this.positionChanged && (!this.moveController.b() || this.moveController.e() <= this.locY + 0.5D)) { - PathEntity pathentity = this.navigation.l(); - - if (pathentity != null && pathentity.f() < pathentity.e()) { - Vec3D vec3d = pathentity.a((Entity) this); - - if (vec3d.y > this.locY + 0.5D) { - return 0.5F; - } - } - - return this.moveController.c() <= 0.6D ? 0.2F : 0.3F; - } else { - return 0.5F; - } - } - - @Override - protected void jump() { - super.jump(); - double d0 = this.moveController.c(); - - if (d0 > 0.0D) { - double d1 = b(this.getMot()); - - if (d1 < 0.01D) { - this.a(0.1F, new Vec3D(0.0D, 0.0D, 1.0D)); - } - } - - if (!this.world.isClientSide) { - this.world.broadcastEntityEffect(this, (byte) 1); - } - - } - - public void d(double d0) { - this.getNavigation().a(d0); - this.moveController.a(this.moveController.d(), this.moveController.e(), this.moveController.f(), d0); - } - - @Override - public void setJumping(boolean flag) { - super.setJumping(flag); - if (flag) { - this.a(this.getSoundJump(), this.getSoundVolume(), ((this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F) * 0.8F); - } - - } - - public void dV() { - this.setJumping(true); - this.bC = 10; - this.bB = 0; - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityRabbit.bz, 0); - } - - @Override - public void mobTick() { - if (this.bE > 0) { - --this.bE; - } - - if (this.bF > 0) { - this.bF -= this.random.nextInt(3); - if (this.bF < 0) { - this.bF = 0; - } - } - - if (this.onGround) { - if (!this.bD) { - this.setJumping(false); - this.ef(); - } - - if (this.getRabbitType() == 99 && this.bE == 0) { - EntityLiving entityliving = this.getGoalTarget(); - - if (entityliving != null && this.h((Entity) entityliving) < 16.0D) { - this.b(entityliving.locX, entityliving.locZ); - this.moveController.a(entityliving.locX, entityliving.locY, entityliving.locZ, this.moveController.c()); - this.dV(); - this.bD = true; - } - } - - EntityRabbit.ControllerJumpRabbit entityrabbit_controllerjumprabbit = (EntityRabbit.ControllerJumpRabbit) this.bt; - - if (!entityrabbit_controllerjumprabbit.c()) { - if (this.moveController.b() && this.bE == 0) { - PathEntity pathentity = this.navigation.l(); - Vec3D vec3d = new Vec3D(this.moveController.d(), this.moveController.e(), this.moveController.f()); - - if (pathentity != null && pathentity.f() < pathentity.e()) { - vec3d = pathentity.a((Entity) this); - } - - this.b(vec3d.x, vec3d.z); - this.dV(); - } - } else if (!entityrabbit_controllerjumprabbit.d()) { - this.dY(); - } - } - - this.bD = this.onGround; - } - - @Override - public void aA() {} - - private void b(double d0, double d1) { - this.yaw = (float) (MathHelper.d(d1 - this.locZ, d0 - this.locX) * 57.2957763671875D) - 90.0F; - } - - private void dY() { - ((EntityRabbit.ControllerJumpRabbit) this.bt).a(true); - } - - private void dZ() { - ((EntityRabbit.ControllerJumpRabbit) this.bt).a(false); - } - - private void ee() { - if (this.moveController.c() < 2.2D) { - this.bE = 10; - } else { - this.bE = 1; - } - - } - - private void ef() { - this.ee(); - this.dZ(); - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.bB != this.bC) { - ++this.bB; - } else if (this.bC != 0) { - this.bB = 0; - this.bC = 0; - this.setJumping(false); - } - - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(3.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("RabbitType", this.getRabbitType()); - nbttagcompound.setInt("MoreCarrotTicks", this.bF); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setRabbitType(nbttagcompound.getInt("RabbitType")); - this.bF = nbttagcompound.getInt("MoreCarrotTicks"); - } - - protected SoundEffect getSoundJump() { - return SoundEffects.ENTITY_RABBIT_JUMP; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_RABBIT_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_RABBIT_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_RABBIT_DEATH; - } - - @Override - public boolean C(Entity entity) { - if (this.getRabbitType() == 99) { - this.a(SoundEffects.ENTITY_RABBIT_ATTACK, 1.0F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F); - return entity.damageEntity(DamageSource.mobAttack(this), 8.0F); - } else { - return entity.damageEntity(DamageSource.mobAttack(this), 3.0F); - } - } - - @Override - public SoundCategory getSoundCategory() { - return this.getRabbitType() == 99 ? SoundCategory.HOSTILE : SoundCategory.NEUTRAL; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - return this.isInvulnerable(damagesource) ? false : super.damageEntity(damagesource, f); - } - - private boolean b(Item item) { - return item == Items.CARROT || item == Items.GOLDEN_CARROT || item == Blocks.DANDELION.getItem(); - } - - @Override - public EntityRabbit createChild(EntityAgeable entityageable) { - EntityRabbit entityrabbit = (EntityRabbit) EntityTypes.RABBIT.a(this.world); - int i = this.a((GeneratorAccess) this.world); - - if (this.random.nextInt(20) != 0) { - if (entityageable instanceof EntityRabbit && this.random.nextBoolean()) { - i = ((EntityRabbit) entityageable).getRabbitType(); - } else { - i = this.getRabbitType(); - } - } - - entityrabbit.setRabbitType(i); - return entityrabbit; - } - - @Override - public boolean i(ItemStack itemstack) { - return this.b(itemstack.getItem()); - } - - public int getRabbitType() { - return (Integer) this.datawatcher.get(EntityRabbit.bz); - } - - public void setRabbitType(int i) { - if (i == 99) { - this.getAttributeInstance(GenericAttributes.ARMOR).setValue(8.0D); - this.goalSelector.a(4, new EntityRabbit.PathfinderGoalKillerRabbitMeleeAttack(this)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[0])).a(new Class[0])); // CraftBukkit - decompile error - 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(new ChatMessage(SystemUtils.a("entity", EntityRabbit.bA), new Object[0])); - } - } - - this.datawatcher.set(EntityRabbit.bz, i); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - Object object = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - int i = this.a(generatoraccess); - boolean flag = false; - - if (object instanceof EntityRabbit.GroupDataRabbit) { - i = ((EntityRabbit.GroupDataRabbit) object).a; - flag = true; - } else { - object = new EntityRabbit.GroupDataRabbit(i); - } - - this.setRabbitType(i); - if (flag) { - this.setAgeRaw(-24000); - } - - return (GroupDataEntity) object; - } - - private int a(GeneratorAccess generatoraccess) { - BiomeBase biomebase = generatoraccess.getBiome(new BlockPosition(this)); - int i = this.random.nextInt(100); - - return biomebase.b() == BiomeBase.Precipitation.SNOW ? (i < 80 ? 1 : 3) : (biomebase.o() == BiomeBase.Geography.DESERT ? 4 : (i < 50 ? 0 : (i < 90 ? 5 : 2))); - } - - public static boolean c(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - Block block = generatoraccess.getType(blockposition.down()).getBlock(); - - return (block == Blocks.GRASS_BLOCK || block == Blocks.SNOW || block == Blocks.SAND) && generatoraccess.getLightLevel(blockposition, 0) > 8; - } - - private boolean eg() { - return this.bF == 0; - } - - static class PathfinderGoalKillerRabbitMeleeAttack extends PathfinderGoalMeleeAttack { - - public PathfinderGoalKillerRabbitMeleeAttack(EntityRabbit entityrabbit) { - super(entityrabbit, 1.4D, true); - } - - @Override - protected double a(EntityLiving entityliving) { - return (double) (4.0F + entityliving.getWidth()); - } - } - - static class PathfinderGoalRabbitPanic extends PathfinderGoalPanic { - - private final EntityRabbit f; - - public PathfinderGoalRabbitPanic(EntityRabbit entityrabbit, double d0) { - super(entityrabbit, d0); - this.f = entityrabbit; - } - - @Override - public void e() { - super.e(); - this.f.d(this.b); - } - } - - static class PathfinderGoalEatCarrots extends PathfinderGoalGotoTarget { - - private final EntityRabbit entity; - private boolean h; - private boolean i; - - public PathfinderGoalEatCarrots(EntityRabbit entityrabbit) { - super(entityrabbit, 0.699999988079071D, 16); - this.entity = entityrabbit; - } - - @Override - public boolean a() { - if (this.c <= 0) { - if (!this.entity.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - return false; - } - - this.i = false; - this.h = this.entity.eg(); - this.h = true; - } - - return super.a(); - } - - @Override - public boolean b() { - return this.i && super.b(); - } - - @Override - public void e() { - super.e(); - this.entity.getControllerLook().a((double) this.e.getX() + 0.5D, (double) (this.e.getY() + 1), (double) this.e.getZ() + 0.5D, 10.0F, (float) this.entity.M()); - if (this.k()) { - World world = this.entity.world; - BlockPosition blockposition = this.e.up(); - IBlockData iblockdata = world.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (this.i && block instanceof BlockCarrots) { - Integer integer = (Integer) iblockdata.get(BlockCarrots.AGE); - - if (integer == 0) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.entity, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 2); - world.b(blockposition, true); - } else { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent( - this.entity, - blockposition, - iblockdata.set(BlockCarrots.AGE, integer - 1) - ).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockCarrots.AGE, integer - 1), 2); - world.triggerEffect(2001, blockposition, Block.getCombinedId(iblockdata)); - } - - this.entity.bF = 40; - } - - this.i = false; - this.c = 10; - } - - } - - @Override - protected boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - Block block = iworldreader.getType(blockposition).getBlock(); - - if (block == Blocks.FARMLAND && this.h && !this.i) { - blockposition = blockposition.up(); - IBlockData iblockdata = iworldreader.getType(blockposition); - - block = iblockdata.getBlock(); - if (block instanceof BlockCarrots && ((BlockCarrots) block).isRipe(iblockdata)) { - this.i = true; - return true; - } - } - - return false; - } - } - - static class PathfinderGoalRabbitAvoidTarget extends PathfinderGoalAvoidTarget { - - private final EntityRabbit i; - - public PathfinderGoalRabbitAvoidTarget(EntityRabbit entityrabbit, Class oclass, float f, double d0, double d1) { - super(entityrabbit, oclass, f, d0, d1); - this.i = entityrabbit; - } - - @Override - public boolean a() { - return this.i.getRabbitType() != 99 && super.a(); - } - } - - static class ControllerMoveRabbit extends ControllerMove { - - private final EntityRabbit i; - private double j; - - public ControllerMoveRabbit(EntityRabbit entityrabbit) { - super(entityrabbit); - this.i = entityrabbit; - } - - @Override - public void a() { - if (this.i.onGround && !this.i.jumping && !((EntityRabbit.ControllerJumpRabbit) this.i.bt).c()) { - this.i.d(0.0D); - } else if (this.b()) { - this.i.d(this.j); - } - - super.a(); - } - - @Override - public void a(double d0, double d1, double d2, double d3) { - if (this.i.isInWater()) { - d3 = 1.5D; - } - - super.a(d0, d1, d2, d3); - if (d3 > 0.0D) { - this.j = d3; - } - - } - } - - public class ControllerJumpRabbit extends ControllerJump { - - private final EntityRabbit c; - private boolean d; - - 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; - } - - @Override - public void b() { - if (this.a) { - this.c.dV(); - this.a = false; - } - - } - } - - public static class GroupDataRabbit implements GroupDataEntity { - - public final int a; - - public GroupDataRabbit(int i) { - this.a = i; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityRaider.java b/src/main/java/net/minecraft/server/EntityRaider.java deleted file mode 100644 index 6ffb35729..000000000 --- a/src/main/java/net/minecraft/server/EntityRaider.java +++ /dev/null @@ -1,531 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public abstract class EntityRaider extends EntityMonsterPatrolling { - - protected static final DataWatcherObject c = DataWatcher.a(EntityRaider.class, DataWatcherRegistry.i); - private static final Predicate b = (entityitem) -> { - return !entityitem.q() && entityitem.isAlive() && ItemStack.matches(entityitem.getItemStack(), Raid.s()); - }; - @Nullable - protected Raid d; - private int bz; - private boolean bA; - private int bB; - - protected EntityRaider(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(1, new EntityRaider.b<>(this)); - this.goalSelector.a(3, new PathfinderGoalRaid<>(this)); - this.goalSelector.a(4, new EntityRaider.d(this, 1.0499999523162842D, 1)); - this.goalSelector.a(5, new EntityRaider.c(this)); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityRaider.c, false); - } - - public abstract void a(int i, boolean flag); - - public boolean ei() { - return this.bA; - } - - public void t(boolean flag) { - this.bA = flag; - } - - @Override - public void movementTick() { - if (this.world instanceof WorldServer && this.isAlive()) { - Raid raid = this.ej(); - - if (this.ei()) { - if (raid == null) { - if (this.world.getTime() % 20L == 0L) { - Raid raid1 = ((WorldServer) this.world).c_(new BlockPosition(this)); - - if (raid1 != null && PersistentRaid.a(this, raid1)) { - raid1.a(raid1.k(), this, (BlockPosition) null, true); - } - } - } else { - EntityLiving entityliving = this.getGoalTarget(); - - if (entityliving != null && (entityliving.getEntityType() == EntityTypes.PLAYER || entityliving.getEntityType() == EntityTypes.IRON_GOLEM)) { - this.ticksFarFromPlayer = 0; - } - } - } - } - - super.movementTick(); - } - - @Override - protected void eb() { - this.ticksFarFromPlayer += 2; - } - - @Override - public void die(DamageSource damagesource) { - if (this.world instanceof WorldServer) { - Entity entity = damagesource.getEntity(); - Raid raid = this.ej(); - - if (raid != null) { - if (this.isPatrolLeader()) { - raid.c(this.el()); - } - - if (entity != null && entity.getEntityType() == EntityTypes.PLAYER) { - raid.a(entity); - } - - raid.a(this, false); - } - - if (this.isPatrolLeader() && raid == null && ((WorldServer) this.world).c_(new BlockPosition(this)) == null) { - ItemStack itemstack = this.getEquipment(EnumItemSlot.HEAD); - EntityHuman entityhuman = null; - - if (entity instanceof EntityHuman) { - entityhuman = (EntityHuman) entity; - } else if (entity instanceof EntityWolf) { - EntityWolf entitywolf = (EntityWolf) entity; - EntityLiving entityliving = entitywolf.getOwner(); - - if (entitywolf.isTamed() && entityliving instanceof EntityHuman) { - entityhuman = (EntityHuman) entityliving; - } - } - - if (!itemstack.isEmpty() && ItemStack.matches(itemstack, Raid.s()) && entityhuman != null) { - MobEffect mobeffect = entityhuman.getEffect(MobEffects.BAD_OMEN); - byte b0 = 1; - int i; - - if (mobeffect != null) { - i = b0 + mobeffect.getAmplifier(); - entityhuman.c(MobEffects.BAD_OMEN); - } else { - i = b0 - 1; - } - - i = MathHelper.clamp(i, 0, 5); - MobEffect mobeffect1 = new MobEffect(MobEffects.BAD_OMEN, 120000, i, false, false, true); - - if (!this.world.getGameRules().getBoolean(GameRules.x)) { - entityhuman.addEffect(mobeffect1); - } - } - } - } - - super.die(damagesource); - } - - @Override - public boolean ec() { - return !this.ek(); - } - - public void a(@Nullable Raid raid) { - this.d = raid; - } - - @Nullable - public Raid ej() { - return this.d; - } - - public boolean ek() { - return this.ej() != null && this.ej().v(); - } - - public void a(int i) { - this.bz = i; - } - - public int el() { - return this.bz; - } - - public void u(boolean flag) { - this.datawatcher.set(EntityRaider.c, flag); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("Wave", this.bz); - nbttagcompound.setBoolean("CanJoinRaid", this.bA); - if (this.d != null) { - nbttagcompound.setInt("RaidId", this.d.u()); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.bz = nbttagcompound.getInt("Wave"); - this.bA = nbttagcompound.getBoolean("CanJoinRaid"); - if (nbttagcompound.hasKeyOfType("RaidId", 3)) { - if (this.world instanceof WorldServer) { - this.d = ((WorldServer) this.world).C().a(nbttagcompound.getInt("RaidId")); - } - - if (this.d != null) { - this.d.a(this.bz, this, false); - if (this.isPatrolLeader()) { - this.d.a(this.bz, this); - } - } - } - - } - - @Override - protected void a(EntityItem entityitem) { - ItemStack itemstack = entityitem.getItemStack(); - boolean flag = this.ek() && this.ej().b(this.el()) != null; - - if (this.ek() && !flag && ItemStack.matches(itemstack, Raid.s())) { - EnumItemSlot enumitemslot = EnumItemSlot.HEAD; - ItemStack itemstack1 = this.getEquipment(enumitemslot); - double d0 = (double) this.d(enumitemslot); - - if (!itemstack1.isEmpty() && (double) (this.random.nextFloat() - 0.1F) < d0) { - this.a(itemstack1); - } - - this.setSlot(enumitemslot, itemstack); - this.receive(entityitem, itemstack.getCount()); - entityitem.die(); - this.ej().a(this.el(), this); - this.setPatrolLeader(true); - } else { - super.a(entityitem); - } - - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return this.ej() == null ? super.isTypeNotPersistent(d0) : false; - } - - @Override - public boolean I() { - return this.ej() != null; - } - - public int en() { - return this.bB; - } - - public void b(int i) { - this.bB = i; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.ek()) { - this.ej().p(); - } - - return super.damageEntity(damagesource, f); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.t(this.getEntityType() != EntityTypes.WITCH || enummobspawn != EnumMobSpawn.NATURAL); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - public abstract SoundEffect dV(); - - static class d extends PathfinderGoal { - - private final EntityRaider a; - private final double b; - private BlockPosition c; - private final List d = Lists.newArrayList(); - private final int e; - private boolean f; - - public d(EntityRaider entityraider, double d0, int i) { - this.a = entityraider; - this.b = d0; - this.e = i; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - this.j(); - return this.g() && this.h() && this.a.getGoalTarget() == null; - } - - private boolean g() { - return this.a.ek() && !this.a.ej().a(); - } - - private boolean h() { - WorldServer worldserver = (WorldServer) this.a.world; - BlockPosition blockposition = new BlockPosition(this.a); - Optional optional = worldserver.B().a((villageplacetype) -> { - return villageplacetype == VillagePlaceType.q; - }, this::a, VillagePlace.Occupancy.ANY, blockposition, 48, this.a.random); - - if (!optional.isPresent()) { - return false; - } else { - this.c = ((BlockPosition) optional.get()).immutableCopy(); - return true; - } - } - - @Override - public boolean b() { - return this.a.getNavigation().n() ? false : this.a.getGoalTarget() == null && !this.c.a((IPosition) this.a.getPositionVector(), (double) (this.a.getWidth() + (float) this.e)) && !this.f; - } - - @Override - public void d() { - if (this.c.a((IPosition) this.a.getPositionVector(), (double) this.e)) { - this.d.add(this.c); - } - - } - - @Override - public void c() { - super.c(); - this.a.n(0); - this.a.getNavigation().a((double) this.c.getX(), (double) this.c.getY(), (double) this.c.getZ(), this.b); - this.f = false; - } - - @Override - public void e() { - if (this.a.getNavigation().n()) { - int i = this.c.getX(); - int j = this.c.getY(); - int k = this.c.getZ(); - Vec3D vec3d = RandomPositionGenerator.a((EntityCreature) this.a, 16, 7, new Vec3D((double) i, (double) j, (double) k), 0.3141592741012573D); - - if (vec3d == null) { - vec3d = RandomPositionGenerator.a(this.a, 8, 7, new Vec3D((double) i, (double) j, (double) k)); - } - - if (vec3d == null) { - this.f = true; - return; - } - - this.a.getNavigation().a(vec3d.x, vec3d.y, vec3d.z, this.b); - } - - } - - private boolean a(BlockPosition blockposition) { - Iterator iterator = this.d.iterator(); - - BlockPosition blockposition1; - - do { - if (!iterator.hasNext()) { - return true; - } - - blockposition1 = (BlockPosition) iterator.next(); - } while (!Objects.equals(blockposition, blockposition1)); - - return false; - } - - private void j() { - if (this.d.size() > 2) { - this.d.remove(0); - } - - } - } - - public class a extends PathfinderGoal { - - private final EntityRaider c; - private final float d; - public final PathfinderTargetCondition a = (new PathfinderTargetCondition()).a(8.0D).d().a().b().c().e(); - - public a(EntityIllagerAbstract entityillagerabstract, float f) { - this.c = entityillagerabstract; - this.d = f * f; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - EntityLiving entityliving = this.c.getLastDamager(); - - return this.c.ej() == null && this.c.isPatrolling() && this.c.getGoalTarget() != null && !this.c.dR() && (entityliving == null || entityliving.getEntityType() != EntityTypes.PLAYER); - } - - @Override - public void c() { - super.c(); - this.c.getNavigation().o(); - List list = this.c.world.a(EntityRaider.class, this.a, this.c, this.c.getBoundingBox().grow(8.0D, 8.0D, 8.0D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityRaider entityraider = (EntityRaider) iterator.next(); - - entityraider.setGoalTarget(this.c.getGoalTarget(), org.bukkit.event.entity.EntityTargetEvent.TargetReason.FOLLOW_LEADER, true); // CraftBukkit - } - - } - - @Override - public void d() { - super.d(); - EntityLiving entityliving = this.c.getGoalTarget(); - - if (entityliving != null) { - List list = this.c.world.a(EntityRaider.class, this.a, this.c, this.c.getBoundingBox().grow(8.0D, 8.0D, 8.0D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityRaider entityraider = (EntityRaider) iterator.next(); - - entityraider.setGoalTarget(this.c.getGoalTarget(), org.bukkit.event.entity.EntityTargetEvent.TargetReason.FOLLOW_LEADER, true); // CraftBukkit - entityraider.q(true); - } - - this.c.q(true); - } - - } - - @Override - public void e() { - EntityLiving entityliving = this.c.getGoalTarget(); - - if (entityliving != null) { - if (this.c.h((Entity) entityliving) > (double) this.d) { - this.c.getControllerLook().a(entityliving, 30.0F, 30.0F); - if (this.c.random.nextInt(50) == 0) { - this.c.B(); - } - } else { - this.c.q(true); - } - - super.e(); - } - } - } - - public class c extends PathfinderGoal { - - private final EntityRaider b; - - c(EntityRaider entityraider) { - this.b = entityraider; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - Raid raid = this.b.ej(); - - return this.b.isAlive() && this.b.getGoalTarget() == null && raid != null && raid.f(); - } - - @Override - public void c() { - this.b.u(true); - super.c(); - } - - @Override - public void d() { - this.b.u(false); - super.d(); - } - - @Override - public void e() { - if (!this.b.isSilent() && this.b.random.nextInt(100) == 0) { - EntityRaider.this.a(EntityRaider.this.dV(), EntityRaider.this.getSoundVolume(), EntityRaider.this.cV()); - } - - if (!this.b.isPassenger() && this.b.random.nextInt(50) == 0) { - this.b.getControllerJump().jump(); - } - - super.e(); - } - } - - public class b extends PathfinderGoal { - - private final T b; - - public b(T entityraider) { // CraftBukkit - decompile error - this.b = entityraider; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - Raid raid = this.b.ej(); - - if (this.b.ek() && !this.b.ej().a() && this.b.dX() && !ItemStack.matches(this.b.getEquipment(EnumItemSlot.HEAD), Raid.s())) { - EntityRaider entityraider = raid.b(this.b.el()); - - if (entityraider == null || !entityraider.isAlive()) { - List list = this.b.world.a(EntityItem.class, this.b.getBoundingBox().grow(16.0D, 8.0D, 16.0D), EntityRaider.b); - - if (!list.isEmpty()) { - return this.b.getNavigation().a((Entity) list.get(0), 1.149999976158142D); - } - } - - return false; - } else { - return false; - } - } - - @Override - public void e() { - if (this.b.getNavigation().h().a((IPosition) this.b.getPositionVector(), 1.414D)) { - List list = this.b.world.a(EntityItem.class, this.b.getBoundingBox().grow(4.0D, 4.0D, 4.0D), EntityRaider.b); - - if (!list.isEmpty()) { - this.b.a((EntityItem) list.get(0)); - } - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityRavager.java b/src/main/java/net/minecraft/server/EntityRavager.java deleted file mode 100644 index 971ea097b..000000000 --- a/src/main/java/net/minecraft/server/EntityRavager.java +++ /dev/null @@ -1,312 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntityRavager extends EntityRaider { - - private static final Predicate b = (entity) -> { - return entity.isAlive() && !(entity instanceof EntityRavager); - }; - private int bz; - private int bA; - private int bB; - - public EntityRavager(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.K = 1.0F; - this.f = 20; - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(4, new EntityRavager.a()); - this.goalSelector.a(5, new PathfinderGoalRandomStrollLand(this, 0.4D)); - this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); - this.goalSelector.a(10, new PathfinderGoalLookAtPlayer(this, EntityInsentient.class, 8.0F)); - this.targetSelector.a(2, (new PathfinderGoalHurtByTarget(this, new Class[]{EntityRaider.class})).a(new Class[0])); // CraftBukkit - decompile error - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); - this.targetSelector.a(4, new PathfinderGoalNearestAttackableTarget<>(this, EntityVillagerAbstract.class, true)); - this.targetSelector.a(4, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); - } - - @Override - protected void F() { - boolean flag = !(this.getRidingPassenger() instanceof EntityInsentient) || this.getRidingPassenger().getEntityType().a(TagsEntity.RADIERS); - boolean flag1 = !(this.getVehicle() instanceof EntityBoat); - - this.goalSelector.a(PathfinderGoal.Type.MOVE, flag); - this.goalSelector.a(PathfinderGoal.Type.JUMP, flag && flag1); - this.goalSelector.a(PathfinderGoal.Type.LOOK, flag); - this.goalSelector.a(PathfinderGoal.Type.TARGET, flag); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(100.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.3D); - this.getAttributeInstance(GenericAttributes.KNOCKBACK_RESISTANCE).setValue(0.5D); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(12.0D); - this.getAttributeInstance(GenericAttributes.ATTACK_KNOCKBACK).setValue(1.5D); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(32.0D); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("AttackTick", this.bz); - nbttagcompound.setInt("StunTick", this.bA); - nbttagcompound.setInt("RoarTick", this.bB); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.bz = nbttagcompound.getInt("AttackTick"); - this.bA = nbttagcompound.getInt("StunTick"); - this.bB = nbttagcompound.getInt("RoarTick"); - } - - @Override - public SoundEffect dV() { - return SoundEffects.ENTITY_RAVAGER_CELEBRATE; - } - - @Override - protected NavigationAbstract b(World world) { - return new EntityRavager.b(this, world); - } - - @Override - public int dA() { - return 45; - } - - @Override - public double aP() { - return 2.1D; - } - - @Override - public boolean dD() { - return !this.isNoAI() && this.getRidingPassenger() instanceof EntityLiving; - } - - @Nullable - @Override - public Entity getRidingPassenger() { - return this.getPassengers().isEmpty() ? null : (Entity) this.getPassengers().get(0); - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.isAlive()) { - if (this.isFrozen()) { - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.0D); - } else { - double d0 = this.getGoalTarget() != null ? 0.35D : 0.3D; - double d1 = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getBaseValue(); - - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(MathHelper.d(0.1D, d1, d0)); - } - - if (this.positionChanged && this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - boolean flag = false; - AxisAlignedBB axisalignedbb = this.getBoundingBox().g(0.2D); - Iterator iterator = BlockPosition.b(MathHelper.floor(axisalignedbb.minX), MathHelper.floor(axisalignedbb.minY), MathHelper.floor(axisalignedbb.minZ), MathHelper.floor(axisalignedbb.maxX), MathHelper.floor(axisalignedbb.maxY), MathHelper.floor(axisalignedbb.maxZ)).iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition = (BlockPosition) iterator.next(); - IBlockData iblockdata = this.world.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (block instanceof BlockLeaves && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { // CraftBukkit - flag = this.world.b(blockposition, true) || flag; - } - } - - if (!flag && this.onGround) { - this.jump(); - } - } - - if (this.bB > 0) { - --this.bB; - if (this.bB == 10) { - this.eh(); - } - } - - if (this.bz > 0) { - --this.bz; - } - - if (this.bA > 0) { - --this.bA; - this.eg(); - if (this.bA == 0) { - this.a(SoundEffects.ENTITY_RAVAGER_ROAR, 1.0F, 1.0F); - this.bB = 20; - } - } - - } - } - - private void eg() { - if (this.random.nextInt(6) == 0) { - double d0 = this.locX - (double) this.getWidth() * Math.sin((double) (this.aK * 0.017453292F)) + (this.random.nextDouble() * 0.6D - 0.3D); - double d1 = this.locY + (double) this.getHeight() - 0.3D; - double d2 = this.locZ + (double) this.getWidth() * Math.cos((double) (this.aK * 0.017453292F)) + (this.random.nextDouble() * 0.6D - 0.3D); - - this.world.addParticle(Particles.ENTITY_EFFECT, d0, d1, d2, 0.4980392156862745D, 0.5137254901960784D, 0.5725490196078431D); - } - - } - - @Override - protected boolean isFrozen() { - return super.isFrozen() || this.bz > 0 || this.bA > 0 || this.bB > 0; - } - - @Override - public boolean hasLineOfSight(Entity entity) { - return this.bA <= 0 && this.bB <= 0 ? super.hasLineOfSight(entity) : false; - } - - @Override - protected void e(EntityLiving entityliving) { - if (this.bB == 0) { - if (this.random.nextDouble() < 0.5D) { - this.bA = 40; - this.a(SoundEffects.ENTITY_RAVAGER_STUNNED, 1.0F, 1.0F); - this.world.broadcastEntityEffect(this, (byte) 39); - entityliving.collide(this); - } else { - this.a((Entity) entityliving); - } - - entityliving.velocityChanged = true; - } - - } - - private void eh() { - if (this.isAlive()) { - List list = this.world.a(EntityLiving.class, this.getBoundingBox().g(4.0D), EntityRavager.b); - - Entity entity; - - for (Iterator iterator = list.iterator(); iterator.hasNext(); this.a(entity)) { - entity = (Entity) iterator.next(); - if (!(entity instanceof EntityIllagerAbstract)) { - entity.damageEntity(DamageSource.mobAttack(this), 6.0F); - } - } - - Vec3D vec3d = this.getBoundingBox().f(); - - for (int i = 0; i < 40; ++i) { - double d0 = this.random.nextGaussian() * 0.2D; - double d1 = this.random.nextGaussian() * 0.2D; - double d2 = this.random.nextGaussian() * 0.2D; - - this.world.addParticle(Particles.POOF, vec3d.x, vec3d.y, vec3d.z, d0, d1, d2); - } - } - - } - - private void a(Entity entity) { - double d0 = entity.locX - this.locX; - double d1 = entity.locZ - this.locZ; - double d2 = Math.max(d0 * d0 + d1 * d1, 0.001D); - - entity.f(d0 / d2 * 4.0D, 0.2D, d1 / d2 * 4.0D); - } - - @Override - public boolean C(Entity entity) { - this.bz = 10; - this.world.broadcastEntityEffect(this, (byte) 4); - this.a(SoundEffects.ENTITY_RAVAGER_ATTACK, 1.0F, 1.0F); - return super.C(entity); - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_RAVAGER_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_RAVAGER_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_RAVAGER_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_RAVAGER_STEP, 0.15F, 1.0F); - } - - @Override - public boolean a(IWorldReader iworldreader) { - return !iworldreader.containsLiquid(this.getBoundingBox()); - } - - @Override - public void a(int i, boolean flag) {} - - @Override - public boolean dX() { - return false; - } - - static class c extends PathfinderNormal { - - private c() {} - - @Override - protected PathType a(IBlockAccess iblockaccess, boolean flag, boolean flag1, BlockPosition blockposition, PathType pathtype) { - return pathtype == PathType.LEAVES ? PathType.OPEN : super.a(iblockaccess, flag, flag1, blockposition, pathtype); - } - } - - static class b extends Navigation { - - public b(EntityInsentient entityinsentient, World world) { - super(entityinsentient, world); - } - - @Override - protected Pathfinder a(int i) { - this.o = new EntityRavager.c(); - return new Pathfinder(this.o, i); - } - } - - class a extends PathfinderGoalMeleeAttack { - - public a() { - super(EntityRavager.this, 1.0D, true); - } - - @Override - protected double a(EntityLiving entityliving) { - float f = EntityRavager.this.getWidth() - 0.1F; - - return (double) (f * 2.0F * f * 2.0F + entityliving.getWidth()); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntitySelector.java b/src/main/java/net/minecraft/server/EntitySelector.java deleted file mode 100644 index 8ae668f67..000000000 --- a/src/main/java/net/minecraft/server/EntitySelector.java +++ /dev/null @@ -1,236 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.UUID; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntitySelector { - - private final int a; - private final boolean b; - private final boolean c; - private final Predicate d; - private final CriterionConditionValue.FloatRange e; - private final Function f; - @Nullable - private final AxisAlignedBB g; - private final BiConsumer> h; - private final boolean i; - @Nullable - private final String j; - @Nullable - private final UUID k; - @Nullable - private final EntityTypes l; - private final boolean checkPermissions; - - public EntitySelector(int i, boolean flag, boolean flag1, Predicate predicate, CriterionConditionValue.FloatRange criterionconditionvalue_floatrange, Function function, @Nullable AxisAlignedBB axisalignedbb, BiConsumer> biconsumer, boolean flag2, @Nullable String s, @Nullable UUID uuid, @Nullable EntityTypes entitytypes, boolean flag3) { - this.a = i; - this.b = flag; - this.c = flag1; - this.d = predicate; - this.e = criterionconditionvalue_floatrange; - this.f = function; - this.g = axisalignedbb; - this.h = biconsumer; - this.i = flag2; - this.j = s; - this.k = uuid; - this.l = entitytypes; - this.checkPermissions = flag3; - } - - public int a() { - return this.a; - } - - public boolean b() { - return this.b; - } - - public boolean c() { - return this.i; - } - - public boolean d() { - return this.c; - } - - private void e(CommandListenerWrapper commandlistenerwrapper) throws CommandSyntaxException { - if (this.checkPermissions && !commandlistenerwrapper.hasPermission(2, "minecraft.command.selector")) { // CraftBukkit - throw ArgumentEntity.f.create(); - } - } - - public Entity a(CommandListenerWrapper commandlistenerwrapper) throws CommandSyntaxException { - this.e(commandlistenerwrapper); - List list = this.getEntities(commandlistenerwrapper); - - if (list.isEmpty()) { - throw ArgumentEntity.d.create(); - } else if (list.size() > 1) { - throw ArgumentEntity.a.create(); - } else { - return (Entity) list.get(0); - } - } - - public List getEntities(CommandListenerWrapper commandlistenerwrapper) throws CommandSyntaxException { - this.e(commandlistenerwrapper); - if (!this.b) { - return this.d(commandlistenerwrapper); - } else if (this.j != null) { - EntityPlayer entityplayer = commandlistenerwrapper.getServer().getPlayerList().getPlayer(this.j); - - return (List) (entityplayer == null ? Collections.emptyList() : Lists.newArrayList(new EntityPlayer[]{entityplayer})); - } else if (this.k != null) { - Iterator iterator = commandlistenerwrapper.getServer().getWorlds().iterator(); - - Entity entity; - - do { - if (!iterator.hasNext()) { - return Collections.emptyList(); - } - - WorldServer worldserver = (WorldServer) iterator.next(); - - entity = worldserver.getEntity(this.k); - } while (entity == null); - - return Lists.newArrayList(new Entity[]{entity}); - } else { - Vec3D vec3d = (Vec3D) this.f.apply(commandlistenerwrapper.getPosition()); - Predicate predicate = this.a(vec3d); - - if (this.i) { - return (List) (commandlistenerwrapper.getEntity() != null && predicate.test(commandlistenerwrapper.getEntity()) ? Lists.newArrayList(new Entity[]{commandlistenerwrapper.getEntity()}) : Collections.emptyList()); - } else { - List list = Lists.newArrayList(); - - if (this.d()) { - this.a(list, commandlistenerwrapper.getWorld(), vec3d, predicate); - } else { - Iterator iterator1 = commandlistenerwrapper.getServer().getWorlds().iterator(); - - while (iterator1.hasNext()) { - WorldServer worldserver1 = (WorldServer) iterator1.next(); - - this.a(list, worldserver1, vec3d, predicate); - } - } - - return this.a(vec3d, (List) list); - } - } - } - - private void a(List list, WorldServer worldserver, Vec3D vec3d, Predicate predicate) { - if (this.g != null) { - list.addAll(worldserver.a(this.l, this.g.b(vec3d), predicate)); - } else { - list.addAll(worldserver.a(this.l, predicate)); - } - - } - - public EntityPlayer c(CommandListenerWrapper commandlistenerwrapper) throws CommandSyntaxException { - this.e(commandlistenerwrapper); - List list = this.d(commandlistenerwrapper); - - if (list.size() != 1) { - throw ArgumentEntity.e.create(); - } else { - return (EntityPlayer) list.get(0); - } - } - - public List d(CommandListenerWrapper commandlistenerwrapper) throws CommandSyntaxException { - this.e(commandlistenerwrapper); - EntityPlayer entityplayer; - - if (this.j != null) { - entityplayer = commandlistenerwrapper.getServer().getPlayerList().getPlayer(this.j); - return (List) (entityplayer == null ? Collections.emptyList() : Lists.newArrayList(new EntityPlayer[]{entityplayer})); - } else if (this.k != null) { - entityplayer = commandlistenerwrapper.getServer().getPlayerList().a(this.k); - return (List) (entityplayer == null ? Collections.emptyList() : Lists.newArrayList(new EntityPlayer[]{entityplayer})); - } else { - Vec3D vec3d = (Vec3D) this.f.apply(commandlistenerwrapper.getPosition()); - Predicate predicate = this.a(vec3d); - - if (this.i) { - if (commandlistenerwrapper.getEntity() instanceof EntityPlayer) { - EntityPlayer entityplayer1 = (EntityPlayer) commandlistenerwrapper.getEntity(); - - if (predicate.test(entityplayer1)) { - return Lists.newArrayList(new EntityPlayer[]{entityplayer1}); - } - } - - return Collections.emptyList(); - } else { - Object object; - - if (this.d()) { - WorldServer worldserver = commandlistenerwrapper.getWorld(); - - predicate.getClass(); - object = worldserver.a(predicate::test); - } else { - object = Lists.newArrayList(); - Iterator iterator = commandlistenerwrapper.getServer().getPlayerList().getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer2 = (EntityPlayer) iterator.next(); - - if (predicate.test(entityplayer2)) { - ((List) object).add(entityplayer2); - } - } - } - - return this.a(vec3d, (List) object); - } - } - } - - private Predicate a(Vec3D vec3d) { - Predicate predicate = this.d; - - if (this.g != null) { - AxisAlignedBB axisalignedbb = this.g.b(vec3d); - - predicate = predicate.and((entity) -> { - return axisalignedbb.c(entity.getBoundingBox()); - }); - } - - if (!this.e.c()) { - predicate = predicate.and((entity) -> { - return this.e.a(entity.c(vec3d)); - }); - } - - return predicate; - } - - private List a(Vec3D vec3d, List list) { - if (list.size() > 1) { - this.h.accept(vec3d, list); - } - - return list.subList(0, Math.min(this.a, list.size())); - } - - public static IChatBaseComponent a(List list) { - return ChatComponentUtils.b(list, Entity::getScoreboardDisplayName); - } -} diff --git a/src/main/java/net/minecraft/server/EntitySheep.java b/src/main/java/net/minecraft/server/EntitySheep.java deleted file mode 100644 index ec13d4f37..000000000 --- a/src/main/java/net/minecraft/server/EntitySheep.java +++ /dev/null @@ -1,327 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.event.entity.SheepRegrowWoolEvent; -import org.bukkit.event.player.PlayerShearEntityEvent; -import org.bukkit.inventory.InventoryView; -// CraftBukkit end - -public class EntitySheep extends EntityAnimal { - - private static final DataWatcherObject bz = DataWatcher.a(EntitySheep.class, DataWatcherRegistry.a); - private static final Map bA = (Map) SystemUtils.a(Maps.newEnumMap(EnumColor.class), (enummap) -> { // CraftBukkit - decompile error - enummap.put(EnumColor.WHITE, Blocks.WHITE_WOOL); - enummap.put(EnumColor.ORANGE, Blocks.ORANGE_WOOL); - enummap.put(EnumColor.MAGENTA, Blocks.MAGENTA_WOOL); - enummap.put(EnumColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_WOOL); - enummap.put(EnumColor.YELLOW, Blocks.YELLOW_WOOL); - enummap.put(EnumColor.LIME, Blocks.LIME_WOOL); - enummap.put(EnumColor.PINK, Blocks.PINK_WOOL); - enummap.put(EnumColor.GRAY, Blocks.GRAY_WOOL); - enummap.put(EnumColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_WOOL); - enummap.put(EnumColor.CYAN, Blocks.CYAN_WOOL); - enummap.put(EnumColor.PURPLE, Blocks.PURPLE_WOOL); - enummap.put(EnumColor.BLUE, Blocks.BLUE_WOOL); - enummap.put(EnumColor.BROWN, Blocks.BROWN_WOOL); - enummap.put(EnumColor.GREEN, Blocks.GREEN_WOOL); - enummap.put(EnumColor.RED, Blocks.RED_WOOL); - enummap.put(EnumColor.BLACK, Blocks.BLACK_WOOL); - }); - private static final Map bB = Maps.newEnumMap((Map) Arrays.stream(EnumColor.values()).collect(Collectors.toMap((enumcolor) -> { - return enumcolor; - }, EntitySheep::c))); - private int bC; - private PathfinderGoalEatTile bD; - - private static float[] c(EnumColor enumcolor) { - if (enumcolor == EnumColor.WHITE) { - return new float[]{0.9019608F, 0.9019608F, 0.9019608F}; - } else { - float[] afloat = enumcolor.d(); - float f = 0.75F; - - return new float[]{afloat[0] * 0.75F, afloat[1] * 0.75F, afloat[2] * 0.75F}; - } - } - - public EntitySheep(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - this.bD = new PathfinderGoalEatTile(this); - 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, RecipeItemStack.a(Items.WHEAT), false)); - this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.1D)); - this.goalSelector.a(5, this.bD); - this.goalSelector.a(6, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); - this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); - } - - @Override - protected void mobTick() { - this.bC = this.bD.g(); - super.mobTick(); - } - - @Override - public void movementTick() { - if (this.world.isClientSide) { - this.bC = Math.max(0, this.bC - 1); - } - - super.movementTick(); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(8.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.23000000417232513D); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntitySheep.bz, (byte) 0); - } - - @Override - public MinecraftKey getDefaultLootTable() { - if (this.isSheared()) { - return this.getEntityType().h(); - } else { - switch (this.getColor()) { - case WHITE: - default: - return LootTables.L; - case ORANGE: - return LootTables.M; - case MAGENTA: - return LootTables.N; - case LIGHT_BLUE: - return LootTables.O; - case YELLOW: - return LootTables.P; - case LIME: - return LootTables.Q; - case PINK: - return LootTables.R; - case GRAY: - return LootTables.S; - case LIGHT_GRAY: - return LootTables.T; - case CYAN: - return LootTables.U; - case PURPLE: - return LootTables.V; - case BLUE: - return LootTables.W; - case BROWN: - return LootTables.X; - case GREEN: - return LootTables.Y; - case RED: - return LootTables.Z; - case BLACK: - return LootTables.aa; - } - } - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (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.shear(); - if (!this.world.isClientSide) { - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(enumhand); - }); - } - } - - return super.a(entityhuman, enumhand); - } - - public void shear() { - if (!this.world.isClientSide) { - this.setSheared(true); - int i = 1 + this.random.nextInt(3); - - for (int j = 0; j < i; ++j) { - this.forceDrops = true; // CraftBukkit - EntityItem entityitem = this.a((IMaterial) EntitySheep.bA.get(this.getColor()), 1); - this.forceDrops = false; // CraftBukkit - - if (entityitem != null) { - entityitem.setMot(entityitem.getMot().add((double) ((this.random.nextFloat() - this.random.nextFloat()) * 0.1F), (double) (this.random.nextFloat() * 0.05F), (double) ((this.random.nextFloat() - this.random.nextFloat()) * 0.1F))); - } - } - } - - this.a(SoundEffects.ENTITY_SHEEP_SHEAR, 1.0F, 1.0F); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("Sheared", this.isSheared()); - nbttagcompound.setByte("Color", (byte) this.getColor().getColorIndex()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setSheared(nbttagcompound.getBoolean("Sheared")); - this.setColor(EnumColor.fromColorIndex(nbttagcompound.getByte("Color"))); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_SHEEP_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_SHEEP_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_SHEEP_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_SHEEP_STEP, 0.15F, 1.0F); - } - - public EnumColor getColor() { - return EnumColor.fromColorIndex((Byte) this.datawatcher.get(EntitySheep.bz) & 15); - } - - public void setColor(EnumColor enumcolor) { - byte b0 = (Byte) this.datawatcher.get(EntitySheep.bz); - - this.datawatcher.set(EntitySheep.bz, (byte) (b0 & 240 | enumcolor.getColorIndex() & 15)); - } - - public boolean isSheared() { - return ((Byte) this.datawatcher.get(EntitySheep.bz) & 16) != 0; - } - - public void setSheared(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntitySheep.bz); - - if (flag) { - this.datawatcher.set(EntitySheep.bz, (byte) (b0 | 16)); - } else { - this.datawatcher.set(EntitySheep.bz, (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.LIGHT_GRAY : (i < 18 ? EnumColor.BROWN : (random.nextInt(500) == 0 ? EnumColor.PINK : EnumColor.WHITE)))); - } - - @Override - public EntitySheep createChild(EntityAgeable entityageable) { - EntitySheep entitysheep = (EntitySheep) entityageable; - EntitySheep entitysheep1 = (EntitySheep) EntityTypes.SHEEP.a(this.world); - - entitysheep1.setColor(this.a((EntityAnimal) this, (EntityAnimal) entitysheep)); - return entitysheep1; - } - - @Override - public void blockEaten() { - // CraftBukkit start - SheepRegrowWoolEvent event = new SheepRegrowWoolEvent((org.bukkit.entity.Sheep) this.getBukkitEntity()); - this.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) return; - // CraftBukkit end - this.setSheared(false); - if (this.isBaby()) { - this.setAge(60); - } - - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - groupdataentity = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - this.setColor(a(generatoraccess.getRandom())); - return groupdataentity; - } - - private EnumColor a(EntityAnimal entityanimal, EntityAnimal entityanimal1) { - EnumColor enumcolor = ((EntitySheep) entityanimal).getColor(); - EnumColor enumcolor1 = ((EntitySheep) entityanimal1).getColor(); - InventoryCrafting inventorycrafting = a(enumcolor, enumcolor1); - Optional optional = this.world.getCraftingManager().craft(Recipes.CRAFTING, inventorycrafting, this.world).map((recipecrafting) -> { // Eclipse fail - return recipecrafting.a(inventorycrafting); - }).map(ItemStack::getItem); - - ItemDye.class.getClass(); - optional = optional.filter(ItemDye.class::isInstance); - ItemDye.class.getClass(); - return (EnumColor) optional.map(ItemDye.class::cast).map(ItemDye::d).orElseGet(() -> { - return this.world.random.nextBoolean() ? enumcolor : enumcolor1; - }); - } - - private static InventoryCrafting a(EnumColor enumcolor, EnumColor enumcolor1) { - InventoryCrafting inventorycrafting = new InventoryCrafting(new Container((Containers) null, -1) { - @Override - public boolean canUse(EntityHuman entityhuman) { - return false; - } - - // CraftBukkit start - @Override - public InventoryView getBukkitView() { - return null; // TODO: O.O - } - // CraftBukkit end - }, 2, 1); - - inventorycrafting.setItem(0, new ItemStack(ItemDye.a(enumcolor))); - inventorycrafting.setItem(1, new ItemStack(ItemDye.a(enumcolor1))); - inventorycrafting.resultInventory = new InventoryCraftResult(); // CraftBukkit - add result slot for event - return inventorycrafting; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 0.95F * entitysize.height; - } -} diff --git a/src/main/java/net/minecraft/server/EntityShulker.java b/src/main/java/net/minecraft/server/EntityShulker.java deleted file mode 100644 index aec2e2456..000000000 --- a/src/main/java/net/minecraft/server/EntityShulker.java +++ /dev/null @@ -1,603 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.event.entity.EntityTeleportEvent; -// CraftBukkit end - -public class EntityShulker extends EntityGolem implements IMonster { - - private static final UUID bA = UUID.fromString("7E0292F2-9434-48D5-A29F-9583AF7DF27F"); - private static final AttributeModifier bB = (new AttributeModifier(EntityShulker.bA, "Covered armor bonus", 20.0D, AttributeModifier.Operation.ADDITION)).a(false); - protected static final DataWatcherObject b = DataWatcher.a(EntityShulker.class, DataWatcherRegistry.n); - protected static final DataWatcherObject> c = DataWatcher.a(EntityShulker.class, DataWatcherRegistry.m); - protected static final DataWatcherObject d = DataWatcher.a(EntityShulker.class, DataWatcherRegistry.a); - public static final DataWatcherObject COLOR = DataWatcher.a(EntityShulker.class, DataWatcherRegistry.a); - private float bC; - private float bD; - private BlockPosition bE; - private int bF; - - public EntityShulker(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.aL = 180.0F; - this.aK = 180.0F; - this.bE = null; - this.f = 5; - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.aK = 180.0F; - this.aL = 180.0F; - this.yaw = 180.0F; - this.lastYaw = 180.0F; - this.aM = 180.0F; - this.aN = 180.0F; - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(1, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); - this.goalSelector.a(4, new EntityShulker.a()); - this.goalSelector.a(7, new EntityShulker.e()); - this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[0])).a(new Class[0])); // CraftBukkit - decompile error - this.targetSelector.a(2, new EntityShulker.d(this)); - this.targetSelector.a(3, new EntityShulker.c(this)); - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.HOSTILE; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_SHULKER_AMBIENT; - } - - @Override - public void B() { - if (!this.ed()) { - super.B(); - } - - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_SHULKER_DEATH; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return this.ed() ? SoundEffects.ENTITY_SHULKER_HURT_CLOSED : SoundEffects.ENTITY_SHULKER_HURT; - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityShulker.b, EnumDirection.DOWN); - this.datawatcher.register(EntityShulker.c, Optional.empty()); - this.datawatcher.register(EntityShulker.d, (byte) 0); - this.datawatcher.register(EntityShulker.COLOR, (byte) 16); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(30.0D); - } - - @Override - protected EntityAIBodyControl o() { - return new EntityShulker.b(this); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.datawatcher.set(EntityShulker.b, EnumDirection.fromType1(nbttagcompound.getByte("AttachFace"))); - this.datawatcher.set(EntityShulker.d, nbttagcompound.getByte("Peek")); - this.datawatcher.set(EntityShulker.COLOR, nbttagcompound.getByte("Color")); - if (nbttagcompound.hasKey("APX")) { - int i = nbttagcompound.getInt("APX"); - int j = nbttagcompound.getInt("APY"); - int k = nbttagcompound.getInt("APZ"); - - this.datawatcher.set(EntityShulker.c, Optional.of(new BlockPosition(i, j, k))); - } else { - this.datawatcher.set(EntityShulker.c, Optional.empty()); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setByte("AttachFace", (byte) ((EnumDirection) this.datawatcher.get(EntityShulker.b)).a()); - nbttagcompound.setByte("Peek", (Byte) this.datawatcher.get(EntityShulker.d)); - nbttagcompound.setByte("Color", (Byte) this.datawatcher.get(EntityShulker.COLOR)); - BlockPosition blockposition = this.dW(); - - if (blockposition != null) { - nbttagcompound.setInt("APX", blockposition.getX()); - nbttagcompound.setInt("APY", blockposition.getY()); - nbttagcompound.setInt("APZ", blockposition.getZ()); - } - - } - - @Override - public void tick() { - super.tick(); - BlockPosition blockposition = (BlockPosition) ((Optional) this.datawatcher.get(EntityShulker.c)).orElse((Object) null); - - if (blockposition == null && !this.world.isClientSide) { - blockposition = new BlockPosition(this); - this.datawatcher.set(EntityShulker.c, Optional.of(blockposition)); - } - - float f; - - if (this.isPassenger()) { - blockposition = null; - f = this.getVehicle().yaw; - this.yaw = f; - this.aK = f; - this.aL = f; - this.bF = 0; - } else if (!this.world.isClientSide) { - IBlockData iblockdata = this.world.getType(blockposition); - - if (!iblockdata.isAir()) { - EnumDirection enumdirection; - - if (iblockdata.getBlock() == Blocks.MOVING_PISTON) { - enumdirection = (EnumDirection) iblockdata.get(BlockPiston.FACING); - if (this.world.isEmpty(blockposition.shift(enumdirection))) { - blockposition = blockposition.shift(enumdirection); - this.datawatcher.set(EntityShulker.c, Optional.of(blockposition)); - } else { - this.l(); - } - } else if (iblockdata.getBlock() == Blocks.PISTON_HEAD) { - enumdirection = (EnumDirection) iblockdata.get(BlockPistonExtension.FACING); - if (this.world.isEmpty(blockposition.shift(enumdirection))) { - blockposition = blockposition.shift(enumdirection); - this.datawatcher.set(EntityShulker.c, Optional.of(blockposition)); - } else { - this.l(); - } - } else { - this.l(); - } - } - - BlockPosition blockposition1 = blockposition.shift(this.dV()); - - if (!this.world.a(blockposition1, (Entity) this)) { - boolean flag = false; - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection1 = aenumdirection[j]; - - blockposition1 = blockposition.shift(enumdirection1); - if (this.world.a(blockposition1, (Entity) this)) { - this.datawatcher.set(EntityShulker.b, enumdirection1); - flag = true; - break; - } - } - - if (!flag) { - this.l(); - } - } - - BlockPosition blockposition2 = blockposition.shift(this.dV().opposite()); - - if (this.world.a(blockposition2, (Entity) this)) { - this.l(); - } - } - - f = (float) this.dX() * 0.01F; - this.bC = this.bD; - if (this.bD > f) { - this.bD = MathHelper.a(this.bD - 0.05F, f, 1.0F); - } else if (this.bD < f) { - this.bD = MathHelper.a(this.bD + 0.05F, 0.0F, f); - } - - if (blockposition != null) { - if (this.world.isClientSide) { - if (this.bF > 0 && this.bE != null) { - --this.bF; - } else { - this.bE = blockposition; - } - } - - this.locX = (double) blockposition.getX() + 0.5D; - this.locY = (double) blockposition.getY(); - this.locZ = (double) blockposition.getZ() + 0.5D; - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - this.H = this.locX; - this.I = this.locY; - this.J = this.locZ; - double d0 = 0.5D - (double) MathHelper.sin((0.5F + this.bD) * 3.1415927F) * 0.5D; - double d1 = 0.5D - (double) MathHelper.sin((0.5F + this.bC) * 3.1415927F) * 0.5D; - EnumDirection enumdirection2 = this.dV().opposite(); - - this.a((new AxisAlignedBB(this.locX - 0.5D, this.locY, this.locZ - 0.5D, this.locX + 0.5D, this.locY + 1.0D, this.locZ + 0.5D)).b((double) enumdirection2.getAdjacentX() * d0, (double) enumdirection2.getAdjacentY() * d0, (double) enumdirection2.getAdjacentZ() * d0)); - double d2 = d0 - d1; - - if (d2 > 0.0D) { - List list = this.world.getEntities(this, this.getBoundingBox()); - - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - - if (!(entity instanceof EntityShulker) && !entity.noclip) { - entity.move(EnumMoveType.SHULKER, new Vec3D(d2 * (double) enumdirection2.getAdjacentX(), d2 * (double) enumdirection2.getAdjacentY(), d2 * (double) enumdirection2.getAdjacentZ())); - } - } - } - } - } - - } - - @Override - public void move(EnumMoveType enummovetype, Vec3D vec3d) { - if (enummovetype == EnumMoveType.SHULKER_BOX) { - this.l(); - } else { - super.move(enummovetype, vec3d); - } - - } - - @Override - public void setPosition(double d0, double d1, double d2) { - super.setPosition(d0, d1, d2); - if (this.datawatcher != null && this.ticksLived != 0) { - Optional optional = (Optional) this.datawatcher.get(EntityShulker.c); - Optional optional1 = Optional.of(new BlockPosition(d0, d1, d2)); - - if (!optional1.equals(optional)) { - this.datawatcher.set(EntityShulker.c, optional1); - this.datawatcher.set(EntityShulker.d, (byte) 0); - this.impulse = true; - } - - } - } - - protected boolean l() { - if (!this.isNoAI() && this.isAlive()) { - BlockPosition blockposition = new BlockPosition(this); - - for (int i = 0; i < 5; ++i) { - BlockPosition blockposition1 = blockposition.b(8 - this.random.nextInt(17), 8 - this.random.nextInt(17), 8 - this.random.nextInt(17)); - - if (blockposition1.getY() > 0 && this.world.isEmpty(blockposition1) && this.world.getWorldBorder().a(blockposition1) && this.world.getCubes(this, new AxisAlignedBB(blockposition1))) { - boolean flag = false; - EnumDirection[] aenumdirection = EnumDirection.values(); - int j = aenumdirection.length; - - for (int k = 0; k < j; ++k) { - EnumDirection enumdirection = aenumdirection[k]; - - if (this.world.a(blockposition1.shift(enumdirection), (Entity) this)) { - // CraftBukkit start - EntityTeleportEvent teleport = new EntityTeleportEvent(this.getBukkitEntity(), this.getBukkitEntity().getLocation(), new Location(this.world.getWorld(), blockposition1.getX(), blockposition1.getY(), blockposition1.getZ())); - this.world.getServer().getPluginManager().callEvent(teleport); - if (!teleport.isCancelled()) { - Location to = teleport.getTo(); - blockposition1 = new BlockPosition(to.getX(), to.getY(), to.getZ()); - - this.datawatcher.set(EntityShulker.b, enumdirection); - flag = true; - } - // CraftBukkit end - break; - } - } - - if (flag) { - this.a(SoundEffects.ENTITY_SHULKER_TELEPORT, 1.0F, 1.0F); - this.datawatcher.set(EntityShulker.c, Optional.of(blockposition1)); - this.datawatcher.set(EntityShulker.d, (byte) 0); - this.setGoalTarget((EntityLiving) null); - return true; - } - } - } - - return false; - } else { - return true; - } - } - - @Override - public void movementTick() { - super.movementTick(); - this.setMot(Vec3D.a); - this.aL = 180.0F; - this.aK = 180.0F; - this.yaw = 180.0F; - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityShulker.c.equals(datawatcherobject) && this.world.isClientSide && !this.isPassenger()) { - BlockPosition blockposition = this.dW(); - - if (blockposition != null) { - if (this.bE == null) { - this.bE = blockposition; - } else { - this.bF = 6; - } - - this.locX = (double) blockposition.getX() + 0.5D; - this.locY = (double) blockposition.getY(); - this.locZ = (double) blockposition.getZ() + 0.5D; - if (valid) ((WorldServer) world).chunkCheck(this); // CraftBukkit - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - this.H = this.locX; - this.I = this.locY; - this.J = this.locZ; - } - } - - super.a(datawatcherobject); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.ed()) { - Entity entity = damagesource.j(); - - if (entity instanceof EntityArrow) { - return false; - } - } - - if (super.damageEntity(damagesource, f)) { - if ((double) this.getHealth() < (double) this.getMaxHealth() * 0.5D && this.random.nextInt(4) == 0) { - this.l(); - } - - return true; - } else { - return false; - } - } - - private boolean ed() { - return this.dX() == 0; - } - - @Nullable - @Override - public AxisAlignedBB aq() { - return this.isAlive() ? this.getBoundingBox() : null; - } - - public EnumDirection dV() { - return (EnumDirection) this.datawatcher.get(EntityShulker.b); - } - - @Nullable - public BlockPosition dW() { - return (BlockPosition) ((Optional) this.datawatcher.get(EntityShulker.c)).orElse((Object) null); - } - - public void g(@Nullable BlockPosition blockposition) { - this.datawatcher.set(EntityShulker.c, Optional.ofNullable(blockposition)); - } - - public int dX() { - return (Byte) this.datawatcher.get(EntityShulker.d); - } - - public void a(int i) { - if (!this.world.isClientSide) { - this.getAttributeInstance(GenericAttributes.ARMOR).removeModifier(EntityShulker.bB); - if (i == 0) { - this.getAttributeInstance(GenericAttributes.ARMOR).addModifier(EntityShulker.bB); - this.a(SoundEffects.ENTITY_SHULKER_CLOSE, 1.0F, 1.0F); - } else { - this.a(SoundEffects.ENTITY_SHULKER_OPEN, 1.0F, 1.0F); - } - } - - this.datawatcher.set(EntityShulker.d, (byte) i); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 0.5F; - } - - @Override - public int M() { - return 180; - } - - @Override - public int dA() { - return 180; - } - - @Override - public void collide(Entity entity) {} - - @Override - public float aS() { - return 0.0F; - } - - static class c extends PathfinderGoalNearestAttackableTarget { - - public c(EntityShulker entityshulker) { - super(entityshulker, EntityLiving.class, 10, true, false, (entityliving) -> { - return entityliving instanceof IMonster; - }); - } - - @Override - public boolean a() { - return this.e.getScoreboardTeam() == null ? false : super.a(); - } - - @Override - protected AxisAlignedBB a(double d0) { - EnumDirection enumdirection = ((EntityShulker) this.e).dV(); - - return enumdirection.k() == EnumDirection.EnumAxis.X ? this.e.getBoundingBox().grow(4.0D, d0, d0) : (enumdirection.k() == EnumDirection.EnumAxis.Z ? this.e.getBoundingBox().grow(d0, d0, 4.0D) : this.e.getBoundingBox().grow(d0, 4.0D, d0)); - } - } - - class d extends PathfinderGoalNearestAttackableTarget { - - public d(EntityShulker entityshulker) { - super(entityshulker, EntityHuman.class, true); - } - - @Override - public boolean a() { - return EntityShulker.this.world.getDifficulty() == EnumDifficulty.PEACEFUL ? false : super.a(); - } - - @Override - protected AxisAlignedBB a(double d0) { - EnumDirection enumdirection = ((EntityShulker) this.e).dV(); - - return enumdirection.k() == EnumDirection.EnumAxis.X ? this.e.getBoundingBox().grow(4.0D, d0, d0) : (enumdirection.k() == EnumDirection.EnumAxis.Z ? this.e.getBoundingBox().grow(d0, d0, 4.0D) : this.e.getBoundingBox().grow(d0, 4.0D, d0)); - } - } - - class a extends PathfinderGoal { - - private int b; - - public a() { - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - EntityLiving entityliving = EntityShulker.this.getGoalTarget(); - - return entityliving != null && entityliving.isAlive() ? EntityShulker.this.world.getDifficulty() != EnumDifficulty.PEACEFUL : false; - } - - @Override - public void c() { - this.b = 20; - EntityShulker.this.a(100); - } - - @Override - public void d() { - EntityShulker.this.a(0); - } - - @Override - public void e() { - if (EntityShulker.this.world.getDifficulty() != EnumDifficulty.PEACEFUL) { - --this.b; - EntityLiving entityliving = EntityShulker.this.getGoalTarget(); - - EntityShulker.this.getControllerLook().a(entityliving, 180.0F, 180.0F); - double d0 = EntityShulker.this.h((Entity) entityliving); - - if (d0 < 400.0D) { - if (this.b <= 0) { - this.b = 20 + EntityShulker.this.random.nextInt(10) * 20 / 2; - EntityShulker.this.world.addEntity(new EntityShulkerBullet(EntityShulker.this.world, EntityShulker.this, entityliving, EntityShulker.this.dV().k())); - EntityShulker.this.a(SoundEffects.ENTITY_SHULKER_SHOOT, 2.0F, (EntityShulker.this.random.nextFloat() - EntityShulker.this.random.nextFloat()) * 0.2F + 1.0F); - } - } else { - EntityShulker.this.setGoalTarget((EntityLiving) null); - } - - super.e(); - } - } - } - - class e extends PathfinderGoal { - - private int b; - - private e() {} - - @Override - public boolean a() { - return EntityShulker.this.getGoalTarget() == null && EntityShulker.this.random.nextInt(40) == 0; - } - - @Override - public boolean b() { - return EntityShulker.this.getGoalTarget() == null && this.b > 0; - } - - @Override - public void c() { - this.b = 20 * (1 + EntityShulker.this.random.nextInt(3)); - EntityShulker.this.a(30); - } - - @Override - public void d() { - if (EntityShulker.this.getGoalTarget() == null) { - EntityShulker.this.a(0); - } - - } - - @Override - public void e() { - --this.b; - } - } - - class b extends EntityAIBodyControl { - - public b(EntityInsentient entityinsentient) { - super(entityinsentient); - } - - @Override - public void a() {} - } -} diff --git a/src/main/java/net/minecraft/server/EntityShulkerBullet.java b/src/main/java/net/minecraft/server/EntityShulkerBullet.java deleted file mode 100644 index 5fe06d80d..000000000 --- a/src/main/java/net/minecraft/server/EntityShulkerBullet.java +++ /dev/null @@ -1,357 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; -import java.util.UUID; -import javax.annotation.Nullable; - -public class EntityShulkerBullet extends Entity { - - private EntityLiving shooter; - private Entity target; - @Nullable - private EnumDirection dir; - private int e; - private double f; - private double g; - private double ar; - @Nullable - private UUID as; - private BlockPosition at; - @Nullable - private UUID au; - private BlockPosition av; - - public EntityShulkerBullet(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.noclip = true; - } - - public EntityShulkerBullet(World world, EntityLiving entityliving, Entity entity, EnumDirection.EnumAxis enumdirection_enumaxis) { - this(EntityTypes.SHULKER_BULLET, world); - this.shooter = entityliving; - BlockPosition blockposition = new BlockPosition(entityliving); - double d0 = (double) blockposition.getX() + 0.5D; - double d1 = (double) blockposition.getY() + 0.5D; - double d2 = (double) blockposition.getZ() + 0.5D; - - this.setPositionRotation(d0, d1, d2, this.yaw, this.pitch); - this.target = entity; - this.dir = EnumDirection.UP; - this.a(enumdirection_enumaxis); - projectileSource = (org.bukkit.entity.LivingEntity) entityliving.getBukkitEntity(); // CraftBukkit - } - - // CraftBukkit start - public EntityLiving getShooter() { - return this.shooter; - } - - public void setShooter(EntityLiving e) { - this.shooter = e; - } - - public Entity getTarget() { - return this.target; - } - - public void setTarget(Entity e) { - this.target = e; - this.dir = EnumDirection.UP; - this.a(EnumDirection.EnumAxis.X); - } - // CraftBukkit end - - @Override - public SoundCategory getSoundCategory() { - return SoundCategory.HOSTILE; - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - BlockPosition blockposition; - NBTTagCompound nbttagcompound1; - - if (this.shooter != null) { - blockposition = new BlockPosition(this.shooter); - nbttagcompound1 = GameProfileSerializer.a(this.shooter.getUniqueID()); - nbttagcompound1.setInt("X", blockposition.getX()); - nbttagcompound1.setInt("Y", blockposition.getY()); - nbttagcompound1.setInt("Z", blockposition.getZ()); - nbttagcompound.set("Owner", nbttagcompound1); - } - - if (this.target != null) { - blockposition = new BlockPosition(this.target); - nbttagcompound1 = GameProfileSerializer.a(this.target.getUniqueID()); - nbttagcompound1.setInt("X", blockposition.getX()); - nbttagcompound1.setInt("Y", blockposition.getY()); - nbttagcompound1.setInt("Z", blockposition.getZ()); - nbttagcompound.set("Target", nbttagcompound1); - } - - if (this.dir != null) { - nbttagcompound.setInt("Dir", this.dir.a()); - } - - nbttagcompound.setInt("Steps", this.e); - nbttagcompound.setDouble("TXD", this.f); - nbttagcompound.setDouble("TYD", this.g); - nbttagcompound.setDouble("TZD", this.ar); - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - this.e = nbttagcompound.getInt("Steps"); - this.f = nbttagcompound.getDouble("TXD"); - this.g = nbttagcompound.getDouble("TYD"); - this.ar = nbttagcompound.getDouble("TZD"); - if (nbttagcompound.hasKeyOfType("Dir", 99)) { - this.dir = EnumDirection.fromType1(nbttagcompound.getInt("Dir")); - } - - NBTTagCompound nbttagcompound1; - - if (nbttagcompound.hasKeyOfType("Owner", 10)) { - nbttagcompound1 = nbttagcompound.getCompound("Owner"); - this.as = GameProfileSerializer.b(nbttagcompound1); - this.at = new BlockPosition(nbttagcompound1.getInt("X"), nbttagcompound1.getInt("Y"), nbttagcompound1.getInt("Z")); - } - - if (nbttagcompound.hasKeyOfType("Target", 10)) { - nbttagcompound1 = nbttagcompound.getCompound("Target"); - this.au = GameProfileSerializer.b(nbttagcompound1); - this.av = new BlockPosition(nbttagcompound1.getInt("X"), nbttagcompound1.getInt("Y"), nbttagcompound1.getInt("Z")); - } - - } - - @Override - protected void initDatawatcher() {} - - private void a(@Nullable EnumDirection enumdirection) { - this.dir = enumdirection; - } - - private void a(@Nullable EnumDirection.EnumAxis enumdirection_enumaxis) { - double d0 = 0.5D; - BlockPosition blockposition; - - if (this.target == null) { - blockposition = (new BlockPosition(this)).down(); - } else { - d0 = (double) this.target.getHeight() * 0.5D; - blockposition = new BlockPosition(this.target.locX, this.target.locY + d0, this.target.locZ); - } - - double d1 = (double) blockposition.getX() + 0.5D; - double d2 = (double) blockposition.getY() + d0; - double d3 = (double) blockposition.getZ() + 0.5D; - EnumDirection enumdirection = null; - - if (!blockposition.a((IPosition) this.getPositionVector(), 2.0D)) { - BlockPosition blockposition1 = new BlockPosition(this); - List list = Lists.newArrayList(); - - if (enumdirection_enumaxis != EnumDirection.EnumAxis.X) { - if (blockposition1.getX() < blockposition.getX() && this.world.isEmpty(blockposition1.east())) { - list.add(EnumDirection.EAST); - } else if (blockposition1.getX() > blockposition.getX() && this.world.isEmpty(blockposition1.west())) { - list.add(EnumDirection.WEST); - } - } - - if (enumdirection_enumaxis != EnumDirection.EnumAxis.Y) { - if (blockposition1.getY() < blockposition.getY() && this.world.isEmpty(blockposition1.up())) { - list.add(EnumDirection.UP); - } else if (blockposition1.getY() > blockposition.getY() && this.world.isEmpty(blockposition1.down())) { - list.add(EnumDirection.DOWN); - } - } - - if (enumdirection_enumaxis != EnumDirection.EnumAxis.Z) { - if (blockposition1.getZ() < blockposition.getZ() && this.world.isEmpty(blockposition1.south())) { - list.add(EnumDirection.SOUTH); - } else if (blockposition1.getZ() > blockposition.getZ() && this.world.isEmpty(blockposition1.north())) { - list.add(EnumDirection.NORTH); - } - } - - enumdirection = EnumDirection.a(this.random); - if (list.isEmpty()) { - for (int i = 5; !this.world.isEmpty(blockposition1.shift(enumdirection)) && i > 0; --i) { - enumdirection = EnumDirection.a(this.random); - } - } else { - enumdirection = (EnumDirection) list.get(this.random.nextInt(list.size())); - } - - d1 = this.locX + (double) enumdirection.getAdjacentX(); - d2 = this.locY + (double) enumdirection.getAdjacentY(); - d3 = this.locZ + (double) enumdirection.getAdjacentZ(); - } - - this.a(enumdirection); - double d4 = d1 - this.locX; - double d5 = d2 - this.locY; - double d6 = d3 - this.locZ; - double d7 = (double) MathHelper.sqrt(d4 * d4 + d5 * d5 + d6 * d6); - - if (d7 == 0.0D) { - this.f = 0.0D; - this.g = 0.0D; - this.ar = 0.0D; - } else { - this.f = d4 / d7 * 0.15D; - this.g = d5 / d7 * 0.15D; - this.ar = d6 / d7 * 0.15D; - } - - this.impulse = true; - this.e = 10 + this.random.nextInt(5) * 10; - } - - @Override - public void tick() { - if (!this.world.isClientSide && this.world.getDifficulty() == EnumDifficulty.PEACEFUL) { - this.die(); - } else { - super.tick(); - Vec3D vec3d; - - if (!this.world.isClientSide) { - List list; - Iterator iterator; - EntityLiving entityliving; - - if (this.target == null && this.au != null) { - list = this.world.a(EntityLiving.class, new AxisAlignedBB(this.av.b(-2, -2, -2), this.av.b(2, 2, 2))); - iterator = list.iterator(); - - while (iterator.hasNext()) { - entityliving = (EntityLiving) iterator.next(); - if (entityliving.getUniqueID().equals(this.au)) { - this.target = entityliving; - break; - } - } - - this.au = null; - } - - if (this.shooter == null && this.as != null) { - list = this.world.a(EntityLiving.class, new AxisAlignedBB(this.at.b(-2, -2, -2), this.at.b(2, 2, 2))); - iterator = list.iterator(); - - while (iterator.hasNext()) { - entityliving = (EntityLiving) iterator.next(); - if (entityliving.getUniqueID().equals(this.as)) { - this.shooter = entityliving; - break; - } - } - - this.as = null; - } - - if (this.target != null && this.target.isAlive() && (!(this.target instanceof EntityHuman) || !((EntityHuman) this.target).isSpectator())) { - this.f = MathHelper.a(this.f * 1.025D, -1.0D, 1.0D); - this.g = MathHelper.a(this.g * 1.025D, -1.0D, 1.0D); - this.ar = MathHelper.a(this.ar * 1.025D, -1.0D, 1.0D); - vec3d = this.getMot(); - this.setMot(vec3d.add((this.f - vec3d.x) * 0.2D, (this.g - vec3d.y) * 0.2D, (this.ar - vec3d.z) * 0.2D)); - } else if (!this.isNoGravity()) { - this.setMot(this.getMot().add(0.0D, -0.04D, 0.0D)); - } - - MovingObjectPosition movingobjectposition = ProjectileHelper.a(this, true, false, this.shooter, RayTrace.BlockCollisionOption.COLLIDER); - - if (movingobjectposition.getType() != MovingObjectPosition.EnumMovingObjectType.MISS) { - this.a(movingobjectposition); - } - } - - vec3d = this.getMot(); - this.setPosition(this.locX + vec3d.x, this.locY + vec3d.y, this.locZ + vec3d.z); - ProjectileHelper.a(this, 0.5F); - if (this.world.isClientSide) { - this.world.addParticle(Particles.END_ROD, this.locX - vec3d.x, this.locY - vec3d.y + 0.15D, this.locZ - vec3d.z, 0.0D, 0.0D, 0.0D); - } else if (this.target != null && !this.target.dead) { - if (this.e > 0) { - --this.e; - if (this.e == 0) { - this.a(this.dir == null ? null : this.dir.k()); - } - } - - if (this.dir != null) { - BlockPosition blockposition = new BlockPosition(this); - EnumDirection.EnumAxis enumdirection_enumaxis = this.dir.k(); - - if (this.world.a(blockposition.shift(this.dir), (Entity) this)) { - this.a(enumdirection_enumaxis); - } else { - BlockPosition blockposition1 = new BlockPosition(this.target); - - if (enumdirection_enumaxis == EnumDirection.EnumAxis.X && blockposition.getX() == blockposition1.getX() || enumdirection_enumaxis == EnumDirection.EnumAxis.Z && blockposition.getZ() == blockposition1.getZ() || enumdirection_enumaxis == EnumDirection.EnumAxis.Y && blockposition.getY() == blockposition1.getY()) { - this.a(enumdirection_enumaxis); - } - } - } - } - - } - } - - @Override - public boolean isBurning() { - return false; - } - - @Override - public float aF() { - return 1.0F; - } - - protected void a(MovingObjectPosition movingobjectposition) { - org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileHitEvent(this, movingobjectposition); // Craftbukkit - Call event - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - Entity entity = ((MovingObjectPositionEntity) movingobjectposition).getEntity(); - boolean flag = entity.damageEntity(DamageSource.a(this, this.shooter).c(), 4.0F); - - if (flag) { - this.a(this.shooter, entity); - if (entity instanceof EntityLiving) { - ((EntityLiving) entity).addEffect(new MobEffect(MobEffects.LEVITATION, 200), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - } - } else { - ((WorldServer) this.world).a(Particles.EXPLOSION, this.locX, this.locY, this.locZ, 2, 0.2D, 0.2D, 0.2D, 0.0D); - this.a(SoundEffects.ENTITY_SHULKER_BULLET_HIT, 1.0F, 1.0F); - } - - this.die(); - } - - @Override - public boolean isInteractable() { - return true; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (!this.world.isClientSide) { - this.a(SoundEffects.ENTITY_SHULKER_BULLET_HURT, 1.0F, 1.0F); - ((WorldServer) this.world).a(Particles.CRIT, this.locX, this.locY, this.locZ, 15, 0.2D, 0.2D, 0.2D, 0.0D); - this.die(); - } - - return true; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } -} diff --git a/src/main/java/net/minecraft/server/EntitySilverfish.java b/src/main/java/net/minecraft/server/EntitySilverfish.java deleted file mode 100644 index eb3c56fef..000000000 --- a/src/main/java/net/minecraft/server/EntitySilverfish.java +++ /dev/null @@ -1,236 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Random; - -public class EntitySilverfish extends EntityMonster { - - private EntitySilverfish.PathfinderGoalSilverfishWakeOthers b; - - public EntitySilverfish(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - this.b = new EntitySilverfish.PathfinderGoalSilverfishWakeOthers(this); - this.goalSelector.a(1, new PathfinderGoalFloat(this)); - this.goalSelector.a(3, this.b); - this.goalSelector.a(4, new PathfinderGoalMeleeAttack(this, 1.0D, false)); - this.goalSelector.a(5, new EntitySilverfish.PathfinderGoalSilverfishHideInBlock(this)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[0])).a(new Class[0])); // CraftBukkit - decompile error - this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); - } - - @Override - public double aO() { - return 0.1D; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 0.1F; - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(8.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(1.0D); - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_SILVERFISH_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_SILVERFISH_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_SILVERFISH_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_SILVERFISH_STEP, 0.15F, 1.0F); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - if ((damagesource instanceof EntityDamageSource || damagesource == DamageSource.MAGIC) && this.b != null) { - this.b.g(); - } - - return super.damageEntity(damagesource, f); - } - } - - @Override - public void tick() { - this.aK = this.yaw; - super.tick(); - } - - @Override - public void l(float f) { - this.yaw = f; - super.l(f); - } - - @Override - public float a(BlockPosition blockposition, IWorldReader iworldreader) { - return BlockMonsterEggs.j(iworldreader.getType(blockposition.down())) ? 10.0F : super.a(blockposition, iworldreader); - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - if (d(entitytypes, generatoraccess, enummobspawn, blockposition, random)) { - EntityHuman entityhuman = generatoraccess.a((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, 5.0D, true); - - return !(entityhuman != null && !entityhuman.affectsSpawning) && entityhuman == null; // Paper - Affects Spawning API - } else { - return false; - } - } - - @Override - public EnumMonsterType getMonsterType() { - return EnumMonsterType.ARTHROPOD; - } - - static class PathfinderGoalSilverfishHideInBlock extends PathfinderGoalRandomStroll { - - private EnumDirection h; - private boolean i; - - public PathfinderGoalSilverfishHideInBlock(EntitySilverfish entitysilverfish) { - super(entitysilverfish, 1.0D, 10); - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - if (this.a.getGoalTarget() != null) { - return false; - } else if (!this.a.getNavigation().n()) { - return false; - } else { - Random random = this.a.getRandom(); - - if (this.a.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) && random.nextInt(10) == 0) { - this.h = EnumDirection.a(random); - BlockPosition blockposition = (new BlockPosition(this.a.locX, this.a.locY + 0.5D, this.a.locZ)).shift(this.h); - IBlockData iblockdata = this.a.world.getType(blockposition); - - if (BlockMonsterEggs.j(iblockdata)) { - this.i = true; - return true; - } - } - - this.i = false; - return super.a(); - } - } - - @Override - public boolean b() { - return this.i ? false : super.b(); - } - - @Override - public void c() { - if (!this.i) { - super.c(); - } else { - World world = this.a.world; - BlockPosition blockposition = (new BlockPosition(this.a.locX, this.a.locY + 0.5D, this.a.locZ)).shift(this.h); - IBlockData iblockdata = world.getType(blockposition); - - if (BlockMonsterEggs.j(iblockdata)) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.a, blockposition, BlockMonsterEggs.e(iblockdata.getBlock())).isCancelled()) { - return; - } - // CraftBukkit end - world.setTypeAndData(blockposition, BlockMonsterEggs.e(iblockdata.getBlock()), 3); - this.a.doSpawnEffect(); - this.a.die(); - } - - } - } - } - - static class PathfinderGoalSilverfishWakeOthers extends PathfinderGoal { - - private final EntitySilverfish silverfish; - private int b; - - public PathfinderGoalSilverfishWakeOthers(EntitySilverfish entitysilverfish) { - this.silverfish = entitysilverfish; - } - - public void g() { - if (this.b == 0) { - this.b = 20; - } - - } - - @Override - public boolean a() { - return this.b > 0; - } - - @Override - public void e() { - --this.b; - if (this.b <= 0) { - World world = this.silverfish.world; - Random random = this.silverfish.getRandom(); - BlockPosition blockposition = new BlockPosition(this.silverfish); - - for (int i = 0; i <= 5 && i >= -5; i = (i <= 0 ? 1 : 0) - i) { - for (int j = 0; j <= 10 && j >= -10; j = (j <= 0 ? 1 : 0) - j) { - for (int k = 0; k <= 10 && k >= -10; k = (k <= 0 ? 1 : 0) - k) { - BlockPosition blockposition1 = blockposition.b(j, i, k); - IBlockData iblockdata = world.getType(blockposition1); - Block block = iblockdata.getBlock(); - - if (block instanceof BlockMonsterEggs) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.silverfish, blockposition1, Blocks.AIR.getBlockData()).isCancelled()) { - continue; - } - // CraftBukkit end - if (world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - world.b(blockposition1, true); - } else { - world.setTypeAndData(blockposition1, ((BlockMonsterEggs) block).d().getBlockData(), 3); - } - - if (random.nextBoolean()) { - return; - } - } - } - } - } - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/EntitySkeletonAbstract.java b/src/main/java/net/minecraft/server/EntitySkeletonAbstract.java deleted file mode 100644 index 8f1b5a550..000000000 --- a/src/main/java/net/minecraft/server/EntitySkeletonAbstract.java +++ /dev/null @@ -1,202 +0,0 @@ -package net.minecraft.server; - -import java.time.LocalDate; -import java.time.temporal.ChronoField; -import javax.annotation.Nullable; - -public abstract class EntitySkeletonAbstract extends EntityMonster implements IRangedEntity { - - private final PathfinderGoalBowShoot b = new PathfinderGoalBowShoot<>(this, 1.0D, 20, 15.0F); - private final PathfinderGoalMeleeAttack c = new PathfinderGoalMeleeAttack(this, 1.2D, false) { - @Override - public void d() { - super.d(); - EntitySkeletonAbstract.this.q(false); - } - - @Override - public void c() { - super.c(); - EntitySkeletonAbstract.this.q(true); - } - }; - - protected EntitySkeletonAbstract(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.dV(); - } - - @Override - protected void initPathfinder() { - 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(5, new PathfinderGoalRandomStrollLand(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, new Class[0])); - this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityTurtle.class, 10, true, false, EntityTurtle.bz)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(this.l(), 0.15F, 1.0F); - } - - abstract SoundEffect l(); - - @Override - public EnumMonsterType getMonsterType() { - return EnumMonsterType.UNDEAD; - } - - @Override - public void movementTick() { - boolean flag = this.dS(); - - if (flag) { - ItemStack itemstack = this.getEquipment(EnumItemSlot.HEAD); - - if (!itemstack.isEmpty()) { - if (itemstack.e()) { - itemstack.setDamage(itemstack.getDamage() + this.random.nextInt(2)); - if (itemstack.getDamage() >= itemstack.h()) { - this.c(EnumItemSlot.HEAD); - this.setSlot(EnumItemSlot.HEAD, ItemStack.a); - } - } - - flag = false; - } - - if (flag) { - this.setOnFire(8); - } - } - - super.movementTick(); - } - - @Override - public void passengerTick() { - super.passengerTick(); - if (this.getVehicle() instanceof EntityCreature) { - EntityCreature entitycreature = (EntityCreature) this.getVehicle(); - - this.aK = entitycreature.aK; - } - - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - super.a(difficultydamagescaler); - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.BOW)); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - groupdataentity = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - this.a(difficultydamagescaler); - this.b(difficultydamagescaler); - this.dV(); - this.setCanPickupLoot(this.random.nextFloat() < 0.55F * difficultydamagescaler.d()); - if (this.getEquipment(EnumItemSlot.HEAD).isEmpty()) { - LocalDate localdate = LocalDate.now(); - int i = localdate.get(ChronoField.DAY_OF_MONTH); - int j = localdate.get(ChronoField.MONTH_OF_YEAR); - - if (j == 10 && i == 31 && this.random.nextFloat() < 0.25F) { - this.setSlot(EnumItemSlot.HEAD, new ItemStack(this.random.nextFloat() < 0.1F ? Blocks.JACK_O_LANTERN : Blocks.CARVED_PUMPKIN)); - this.dropChanceArmor[EnumItemSlot.HEAD.b()] = 0.0F; - } - } - - return groupdataentity; - } - - public void dV() { - if (this.world != null && !this.world.isClientSide) { - this.goalSelector.a((PathfinderGoal) this.c); - this.goalSelector.a((PathfinderGoal) this.b); - ItemStack itemstack = this.b(ProjectileHelper.a(this, Items.BOW)); - - if (itemstack.getItem() == Items.BOW) { - byte b0 = 20; - - if (this.world.getDifficulty() != EnumDifficulty.HARD) { - b0 = 40; - } - - this.b.a(b0); - this.goalSelector.a(4, this.b); - } else { - this.goalSelector.a(4, this.c); - } - - } - } - - @Override - public void a(EntityLiving entityliving, float f) { - ItemStack itemstack = this.f(this.b(ProjectileHelper.a(this, Items.BOW))); - EntityArrow entityarrow = this.b(itemstack, f); - double d0 = entityliving.locX - this.locX; - double d1 = entityliving.getBoundingBox().minY + (double) (entityliving.getHeight() / 3.0F) - entityarrow.locY; - double d2 = entityliving.locZ - this.locZ; - double d3 = (double) MathHelper.sqrt(d0 * d0 + d2 * d2); - - entityarrow.shoot(d0, d1 + d3 * 0.20000000298023224D, d2, 1.6F, (float) (14 - this.world.getDifficulty().a() * 4)); - // CraftBukkit start - org.bukkit.event.entity.EntityShootBowEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityShootBowEvent(this, this.getItemInMainHand(), this.getItemInOffHand(), entityarrow, 0.8F); // Paper - if (event.isCancelled()) { - event.getProjectile().remove(); - return; - } - - if (event.getProjectile() == entityarrow.getBukkitEntity()) { - world.addEntity(entityarrow); - } - // CraftBukkit end - this.a(SoundEffects.ENTITY_SKELETON_SHOOT, 1.0F, 1.0F / (this.getRandom().nextFloat() * 0.4F + 0.8F)); - // this.world.addEntity(entityarrow); // CraftBukkit - moved up - } - - protected EntityArrow b(ItemStack itemstack, float f) { - return ProjectileHelper.a(this, itemstack, f); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.dV(); - } - - @Override - public void setSlot(EnumItemSlot enumitemslot, ItemStack itemstack) { - super.setSlot(enumitemslot, itemstack); - if (!this.world.isClientSide) { - this.dV(); - } - - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 1.74F; - } - - @Override - public double aO() { - return -0.6D; - } -} diff --git a/src/main/java/net/minecraft/server/EntitySkeletonWither.java b/src/main/java/net/minecraft/server/EntitySkeletonWither.java deleted file mode 100644 index 872f79cc6..000000000 --- a/src/main/java/net/minecraft/server/EntitySkeletonWither.java +++ /dev/null @@ -1,96 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class EntitySkeletonWither extends EntitySkeletonAbstract { - - public EntitySkeletonWither(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.a(PathType.LAVA, 8.0F); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_WITHER_SKELETON_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_WITHER_SKELETON_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_WITHER_SKELETON_DEATH; - } - - @Override - SoundEffect l() { - return SoundEffects.ENTITY_WITHER_SKELETON_STEP; - } - - @Override - protected void dropDeathLoot(DamageSource damagesource, int i, boolean flag) { - super.dropDeathLoot(damagesource, i, flag); - Entity entity = damagesource.getEntity(); - - if (entity instanceof EntityCreeper) { - EntityCreeper entitycreeper = (EntityCreeper) entity; - - if (entitycreeper.canCauseHeadDrop()) { - entitycreeper.setCausedHeadDrop(); - this.a((IMaterial) Items.WITHER_SKELETON_SKULL); - } - } - - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.STONE_SWORD)); - } - - @Override - protected void b(DifficultyDamageScaler difficultydamagescaler) {} - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - GroupDataEntity groupdataentity1 = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(4.0D); - this.dV(); - return groupdataentity1; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 2.1F; - } - - @Override - public boolean C(Entity entity) { - if (!super.C(entity)) { - return false; - } else { - if (entity instanceof EntityLiving) { - ((EntityLiving) entity).addEffect(new MobEffect(MobEffects.WITHER, 200), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - - return true; - } - } - - @Override - protected EntityArrow b(ItemStack itemstack, float f) { - EntityArrow entityarrow = super.b(itemstack, f); - - entityarrow.setOnFire(100); - return entityarrow; - } - - @Override - public boolean d(MobEffect mobeffect) { - return mobeffect.getMobEffect() == MobEffects.WITHER ? false : super.d(mobeffect); - } -} diff --git a/src/main/java/net/minecraft/server/EntitySlime.java b/src/main/java/net/minecraft/server/EntitySlime.java deleted file mode 100644 index 253ff9594..000000000 --- a/src/main/java/net/minecraft/server/EntitySlime.java +++ /dev/null @@ -1,551 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Random; -import javax.annotation.Nullable; -// Paper start -import com.destroystokyo.paper.event.entity.SlimeChangeDirectionEvent; -import com.destroystokyo.paper.event.entity.SlimeSwimEvent; -import com.destroystokyo.paper.event.entity.SlimeTargetLivingEntityEvent; -import com.destroystokyo.paper.event.entity.SlimeWanderEvent; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Slime; -// Paper end -// CraftBukkit start -import java.util.ArrayList; -import java.util.List; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityTransformEvent; -import org.bukkit.event.entity.SlimeSplitEvent; -// CraftBukkit end - -public class EntitySlime extends EntityInsentient implements IMonster { - - private static final DataWatcherObject bz = DataWatcher.a(EntitySlime.class, DataWatcherRegistry.b); - public float b; - public float c; - public float d; - private boolean bA; - - public EntitySlime(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.moveController = new EntitySlime.ControllerMoveSlime(this); - } - - @Override - protected void initPathfinder() { - 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 PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, 10, true, false, (entityliving) -> { - return Math.abs(entityliving.locY - this.locY) <= 4.0D; - })); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntitySlime.bz, 1); - } - - public void setSize(int i, boolean flag) { - this.datawatcher.set(EntitySlime.bz, i); - this.setPosition(this.locX, this.locY, this.locZ); - this.updateSize(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue((double) (i * i)); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue((double) (0.2F + 0.1F * (float) i)); - if (flag) { - this.setHealth(this.getMaxHealth()); - } - - this.f = i; - } - - public int getSize() { - return (Integer) this.datawatcher.get(EntitySlime.bz); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("Size", this.getSize() - 1); - nbttagcompound.setBoolean("wasOnGround", this.bA); - nbttagcompound.setBoolean("Paper.canWander", this.canWander); // Paper - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - int i = nbttagcompound.getInt("Size"); - - if (i < 0) { - i = 0; - } - - this.setSize(i + 1, false); - this.bA = nbttagcompound.getBoolean("wasOnGround"); - // Paper start - check exists before loading or this will be loaded as false - if (nbttagcompound.hasKey("Paper.canWander")) { - this.canWander = nbttagcompound.getBoolean("Paper.canWander"); - } - // Paper end - } - - public boolean ea() { - return this.getSize() <= 1; - } - - protected ParticleParam l() { - return Particles.ITEM_SLIME; - } - - @Override - public void tick() { - if (!this.world.isClientSide && this.world.getDifficulty() == EnumDifficulty.PEACEFUL && this.getSize() > 0) { - this.dead = true; - } - - this.c += (this.b - this.c) * 0.5F; - this.d = this.c; - super.tick(); - if (this.onGround && !this.bA) { - int i = this.getSize(); - - for (int j = 0; j < i * 8; ++j) { - float f = this.random.nextFloat() * 6.2831855F; - float f1 = this.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; - World world = this.world; - ParticleParam particleparam = this.l(); - double d0 = this.locX + (double) f2; - double d1 = this.locZ + (double) f3; - - world.addParticle(particleparam, d0, this.getBoundingBox().minY, d1, 0.0D, 0.0D, 0.0D); - } - - this.a(this.getSoundSquish(), this.getSoundVolume(), ((this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F) / 0.8F); - this.b = -0.5F; - } else if (!this.onGround && this.bA) { - this.b = 1.0F; - } - - this.bA = this.onGround; - this.dU(); - } - - protected void dU() { - this.b *= 0.6F; - } - - protected int dT() { - return this.random.nextInt(20) + 10; - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntitySlime.bz.equals(datawatcherobject)) { - this.updateSize(); - this.yaw = this.aM; - this.aK = this.aM; - if (this.isInWater() && this.random.nextInt(20) == 0) { - this.az(); - } - } - - super.a(datawatcherobject); - } - - @Override - public EntityTypes getEntityType() { - return (EntityTypes) super.getEntityType(); // CraftBukkit - decompile error - } - - @Override - public void die() { - int i = this.getSize(); - - if (!this.world.isClientSide && i > 1 && this.getHealth() <= 0.0F) { - int j = 2 + this.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; - } - List slimes = new ArrayList<>(j); - // 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 = (EntitySlime) this.getEntityType().a(this.world); - - if (this.hasCustomName()) { - entityslime.setCustomName(this.getCustomName()); - } - - if (this.isPersistent()) { - entityslime.setPersistent(); - } - - entityslime.setSize(i / 2, true); - entityslime.setPositionRotation(this.locX + (double) f, this.locY + 0.5D, this.locZ + (double) f1, this.random.nextFloat() * 360.0F, 0.0F); - - slimes.add(entityslime); // CraftBukkit - } - - // CraftBukkit start - if (CraftEventFactory.callEntityTransformEvent(this, slimes, EntityTransformEvent.TransformReason.SPLIT).isCancelled()) { - return; - } - for (EntityLiving living : slimes) { - this.world.addEntity(living, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SLIME_SPLIT); // CraftBukkit - SpawnReason - } - // CraftBukkit end - } - - super.die(); - } - - @Override - public void collide(Entity entity) { - super.collide(entity); - if (entity instanceof EntityIronGolem && this.dV()) { - this.h((EntityLiving) entity); - } - - } - - @Override - public void pickup(EntityHuman entityhuman) { - if (this.dV()) { - this.h((EntityLiving) entityhuman); - } - - } - - protected void h(EntityLiving entityliving) { - if (this.isAlive()) { - int i = this.getSize(); - - if (this.h((Entity) entityliving) < 0.6D * (double) i * 0.6D * (double) i && this.hasLineOfSight(entityliving) && entityliving.damageEntity(DamageSource.mobAttack(this), (float) this.dW())) { - this.a(SoundEffects.ENTITY_SLIME_ATTACK, 1.0F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F); - this.a((EntityLiving) this, (Entity) entityliving); - } - } - - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 0.625F * entitysize.height; - } - - protected boolean dV() { - return !this.ea() && this.df(); - } - - protected int dW() { - return this.getSize(); - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return this.ea() ? SoundEffects.ENTITY_SLIME_HURT_SMALL : SoundEffects.ENTITY_SLIME_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return this.ea() ? SoundEffects.ENTITY_SLIME_DEATH_SMALL : SoundEffects.ENTITY_SLIME_DEATH; - } - - protected SoundEffect getSoundSquish() { - return this.ea() ? SoundEffects.ENTITY_SLIME_SQUISH_SMALL : SoundEffects.ENTITY_SLIME_SQUISH; - } - - @Override - protected MinecraftKey getDefaultLootTable() { - return this.getSize() == 1 ? this.getEntityType().h() : LootTables.a; - } - - public static boolean c(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - if (generatoraccess.getWorldData().getType() == WorldType.FLAT && random.nextInt(4) != 1) { - return false; - } else { - if (generatoraccess.getDifficulty() != EnumDifficulty.PEACEFUL) { - BiomeBase biomebase = generatoraccess.getBiome(blockposition); - - if (biomebase == Biomes.SWAMP && blockposition.getY() > 50 && blockposition.getY() < 70 && random.nextFloat() < 0.5F && random.nextFloat() < generatoraccess.aa() && generatoraccess.getLightLevel(blockposition) <= random.nextInt(8)) { - return a(entitytypes, generatoraccess, enummobspawn, blockposition, random); - } - - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(blockposition); - boolean flag = generatoraccess.getMinecraftWorld().paperConfig.allChunksAreSlimeChunks || SeededRandom.a(chunkcoordintpair.x, chunkcoordintpair.z, generatoraccess.getSeed(), generatoraccess.getMinecraftWorld().spigotConfig.slimeSeed).nextInt(10) == 0; // Spigot // Paper - - if (random.nextInt(10) == 0 && flag && blockposition.getY() < 40) { - return a(entitytypes, generatoraccess, enummobspawn, blockposition, random); - } - } - - return false; - } - } - - @Override - protected float getSoundVolume() { - return 0.4F * (float) this.getSize(); - } - - @Override - public int M() { - return 0; - } - - protected boolean eb() { - return this.getSize() > 0; - } - - @Override - protected void jump() { - Vec3D vec3d = this.getMot(); - - this.setMot(vec3d.x, 0.41999998688697815D, vec3d.z); - this.impulse = true; - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - int i = this.random.nextInt(3); - - if (i < 2 && this.random.nextFloat() < 0.5F * difficultydamagescaler.d()) { - ++i; - } - - int j = 1 << i; - - this.setSize(j, true); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - protected SoundEffect getSoundJump() { - return this.ea() ? SoundEffects.ENTITY_SLIME_JUMP_SMALL : SoundEffects.ENTITY_SLIME_JUMP; - } - - @Override - public EntitySize a(EntityPose entitypose) { - return super.a(entitypose).a(0.255F * (float) this.getSize()); - } - - static class PathfinderGoalSlimeIdle extends PathfinderGoal { - - private final EntitySlime a; - - public PathfinderGoalSlimeIdle(EntitySlime entityslime) { - this.a = entityslime; - this.a(EnumSet.of(PathfinderGoal.Type.JUMP, PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - return !this.a.isPassenger() && this.a.canWander && new SlimeWanderEvent((Slime) this.a.getBukkitEntity()).callEvent(); // Paper - } - - @Override - 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(EnumSet.of(PathfinderGoal.Type.JUMP, PathfinderGoal.Type.MOVE)); - entityslime.getNavigation().d(true); - } - - @Override - public boolean a() { - return (this.a.isInWater() || this.a.aD()) && this.a.getControllerMove() instanceof EntitySlime.ControllerMoveSlime && this.a.canWander && new SlimeSwimEvent((Slime) this.a.getBukkitEntity()).callEvent(); // Paper - } - - @Override - public void e() { - if (this.a.getRandom().nextFloat() < 0.8F) { - this.a.getControllerJump().jump(); - } - - ((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(EnumSet.of(PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - return this.a.canWander && this.a.getGoalTarget() == null && (this.a.onGround || this.a.isInWater() || this.a.aD() || this.a.hasEffect(MobEffects.LEVITATION)) && this.a.getControllerMove() instanceof EntitySlime.ControllerMoveSlime; - } - - @Override - public void e() { - if (--this.c <= 0) { - this.c = 40 + this.a.getRandom().nextInt(60); - // Paper start - SlimeChangeDirectionEvent event = new SlimeChangeDirectionEvent((Slime) this.a.getBukkitEntity(), (float) this.a.getRandom().nextInt(360)); - if (!this.a.canWander || !event.callEvent()) return; - this.b = event.getNewYaw(); - // Paper end - } - - ((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(EnumSet.of(PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - EntityLiving entityliving = this.a.getGoalTarget(); - - // Paper start - if (entityliving == null || !entityliving.isAlive()) { - return false; - } - if (entityliving instanceof EntityHuman && ((EntityHuman) entityliving).abilities.isInvulnerable) { - return false; - } - return this.a.getControllerMove() instanceof EntitySlime.ControllerMoveSlime && this.a.canWander && new SlimeTargetLivingEntityEvent((Slime) this.a.getBukkitEntity(), (LivingEntity) entityliving.getBukkitEntity()).callEvent(); - // Paper end - } - - @Override - public void c() { - this.b = 300; - super.c(); - } - - @Override - public boolean b() { - EntityLiving entityliving = this.a.getGoalTarget(); - - // Paper start - if (entityliving == null || !entityliving.isAlive()) { - return false; - } - if (entityliving instanceof EntityHuman && ((EntityHuman) entityliving).abilities.isInvulnerable) { - return false; - } - return --this.b > 0 && this.a.canWander && new SlimeTargetLivingEntityEvent((Slime) this.a.getBukkitEntity(), (LivingEntity) entityliving.getBukkitEntity()).callEvent(); - // Paper end - } - - @Override - public void e() { - this.a.a((Entity) this.a.getGoalTarget(), 10.0F, 10.0F); - ((EntitySlime.ControllerMoveSlime) this.a.getControllerMove()).a(this.a.yaw, this.a.dV()); - } - - // Paper start - clear timer and target when goal resets - public void d() { - this.b = 0; - this.a.setGoalTarget(null); - } - // Paper end - } - - static class ControllerMoveSlime extends ControllerMove { - - private float i; - private int j; - private final EntitySlime k; - private boolean l; - - public ControllerMoveSlime(EntitySlime entityslime) { - super(entityslime); - this.k = entityslime; - this.i = 180.0F * entityslime.yaw / 3.1415927F; - } - - public void a(float f, boolean flag) { - this.i = f; - this.l = flag; - } - - public void a(double d0) { - this.e = d0; - this.h = ControllerMove.Operation.MOVE_TO; - } - - @Override - public void a() { - this.a.yaw = this.a(this.a.yaw, this.i, 90.0F); - this.a.aM = this.a.yaw; - this.a.aK = this.a.yaw; - if (this.h != ControllerMove.Operation.MOVE_TO) { - this.a.r(0.0F); - } else { - this.h = ControllerMove.Operation.WAIT; - if (this.a.onGround) { - this.a.o((float) (this.e * this.a.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue())); - if (this.j-- <= 0) { - this.j = this.k.dT(); - if (this.l) { - this.j /= 3; - } - - this.k.getControllerJump().jump(); - if (this.k.eb()) { - this.k.a(this.k.getSoundJump(), this.k.getSoundVolume(), ((this.k.getRandom().nextFloat() - this.k.getRandom().nextFloat()) * 0.2F + 1.0F) * 0.8F); - } - } else { - this.k.bb = 0.0F; - this.k.bd = 0.0F; - this.a.o(0.0F); - } - } else { - this.a.o((float) (this.e * this.a.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue())); - } - - } - } - } - - // Paper start - private boolean canWander = true; - public boolean canWander() { - return canWander; - } - - public void setWander(boolean canWander) { - this.canWander = canWander; - } - // Paper end -} diff --git a/src/main/java/net/minecraft/server/EntitySmallFireball.java b/src/main/java/net/minecraft/server/EntitySmallFireball.java deleted file mode 100644 index c0071eb1f..000000000 --- a/src/main/java/net/minecraft/server/EntitySmallFireball.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.event.entity.EntityCombustByEntityEvent; // CraftBukkit - -public class EntitySmallFireball extends EntityFireballFireball { - - public EntitySmallFireball(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntitySmallFireball(World world, EntityLiving entityliving, double d0, double d1, double d2) { - super(EntityTypes.SMALL_FIREBALL, entityliving, d0, d1, d2, world); - // CraftBukkit start - if (this.shooter != null && this.shooter instanceof EntityInsentient) { - isIncendiary = this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING); - } - // CraftBukkit end - } - - public EntitySmallFireball(World world, double d0, double d1, double d2, double d3, double d4, double d5) { - super(EntityTypes.SMALL_FIREBALL, d0, d1, d2, d3, d4, d5, world); - } - - @Override - protected void a(MovingObjectPosition movingobjectposition) { - if (!this.world.isClientSide) { - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - Entity entity = ((MovingObjectPositionEntity) movingobjectposition).getEntity(); - - if (!entity.isFireProof()) { - int i = entity.ad(); - - // CraftBukkit start - Entity damage by entity event + combust event - if (isIncendiary) { - EntityCombustByEntityEvent event = new EntityCombustByEntityEvent((org.bukkit.entity.Projectile) this.getBukkitEntity(), entity.getBukkitEntity(), 5); - entity.world.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - entity.setOnFire(event.getDuration(), false); - } - } - // CraftBukkit end - boolean flag = entity.damageEntity(DamageSource.fireball(this, this.shooter), 5.0F); - - if (flag) { - this.a(this.shooter, entity); - } else { - entity.g(i); - } - } - } else if (isIncendiary) { // CraftBukkit - MovingObjectPositionBlock movingobjectpositionblock = (MovingObjectPositionBlock) movingobjectposition; - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition().shift(movingobjectpositionblock.getDirection()); - - if (this.world.isEmpty(blockposition) && !org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition, this).isCancelled()) { // CraftBukkit - this.world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); - } - } - - this.die(); - } - - } - - @Override - public boolean isInteractable() { - return false; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/EntitySnowman.java b/src/main/java/net/minecraft/server/EntitySnowman.java deleted file mode 100644 index fe1381cc1..000000000 --- a/src/main/java/net/minecraft/server/EntitySnowman.java +++ /dev/null @@ -1,166 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.player.PlayerShearEntityEvent; -// CraftBukkit end - -public class EntitySnowman extends EntityGolem implements IRangedEntity { - - private static final DataWatcherObject b = DataWatcher.a(EntitySnowman.class, DataWatcherRegistry.a); - - public EntitySnowman(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(1, new PathfinderGoalArrowAttack(this, 1.25D, 20, 10.0F)); - this.goalSelector.a(2, new PathfinderGoalRandomStrollLand(this, 1.0D, 1.0000001E-5F)); - 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, (entityliving) -> { - return entityliving instanceof IMonster; - })); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(4.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.20000000298023224D); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntitySnowman.b, (byte) 16); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("Pumpkin", this.hasPumpkin()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKey("Pumpkin")) { - this.setHasPumpkin(nbttagcompound.getBoolean("Pumpkin")); - } - - } - - @Override - public void movementTick() { - super.movementTick(); - if (!this.world.isClientSide) { - int i = MathHelper.floor(this.locX); - int j = MathHelper.floor(this.locY); - int k = MathHelper.floor(this.locZ); - - if (this.au()) { - this.damageEntity(DamageSource.DROWN, 1.0F); - } - - if (this.world.getBiome(new BlockPosition(i, 0, k)).getAdjustedTemperature(new BlockPosition(i, j, k)) > 1.0F) { - this.damageEntity(CraftEventFactory.MELTING, 1.0F); // CraftBukkit - DamageSource.BURN -> CraftEventFactory.MELTING - } - - if (!this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - return; - } - - IBlockData iblockdata = Blocks.SNOW.getBlockData(); - - 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).isAir() && this.world.getBiome(blockposition).getAdjustedTemperature(blockposition) < 0.8F && iblockdata.canPlace(this.world, blockposition)) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(this.world, blockposition, iblockdata, this); // CraftBukkit - } - } - } - - } - - @Override - 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.a(SoundEffects.ENTITY_SNOW_GOLEM_SHOOT, 1.0F, 1.0F / (this.getRandom().nextFloat() * 0.4F + 0.8F)); - this.world.addEntity(entitysnowball); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 1.7F; - } - - @Override - protected boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() == Items.SHEARS && this.hasPumpkin() && !this.world.isClientSide) { - // 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.setHasPumpkin(false); - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(enumhand); - }); - } - - return super.a(entityhuman, enumhand); - } - - public boolean hasPumpkin() { - return ((Byte) this.datawatcher.get(EntitySnowman.b) & 16) != 0; - } - - public void setHasPumpkin(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntitySnowman.b); - - if (flag) { - this.datawatcher.set(EntitySnowman.b, (byte) (b0 | 16)); - } else { - this.datawatcher.set(EntitySnowman.b, (byte) (b0 & -17)); - } - - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_SNOW_GOLEM_AMBIENT; - } - - @Nullable - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_SNOW_GOLEM_HURT; - } - - @Nullable - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_SNOW_GOLEM_DEATH; - } -} diff --git a/src/main/java/net/minecraft/server/EntitySpectralArrow.java b/src/main/java/net/minecraft/server/EntitySpectralArrow.java deleted file mode 100644 index fad23ed2b..000000000 --- a/src/main/java/net/minecraft/server/EntitySpectralArrow.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.minecraft.server; - -public class EntitySpectralArrow extends EntityArrow { - - public int duration = 200; - - public EntitySpectralArrow(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntitySpectralArrow(World world, EntityLiving entityliving) { - super(EntityTypes.SPECTRAL_ARROW, entityliving, world); - } - - public EntitySpectralArrow(World world, double d0, double d1, double d2) { - super(EntityTypes.SPECTRAL_ARROW, d0, d1, d2, world); - } - - @Override - public void tick() { - super.tick(); - if (this.world.isClientSide && !this.inGround) { - this.world.addParticle(Particles.INSTANT_EFFECT, this.locX, this.locY, this.locZ, 0.0D, 0.0D, 0.0D); - } - - } - - @Override - protected ItemStack getItemStack() { - return new ItemStack(Items.SPECTRAL_ARROW); - } - - @Override - protected void a(EntityLiving entityliving) { - super.a(entityliving); - MobEffect mobeffect = new MobEffect(MobEffects.GLOWING, this.duration, 0); - - entityliving.addEffect(mobeffect, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ARROW); // CraftBukkit - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKey("Duration")) { - this.duration = nbttagcompound.getInt("Duration"); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("Duration", this.duration); - } -} diff --git a/src/main/java/net/minecraft/server/EntitySpider.java b/src/main/java/net/minecraft/server/EntitySpider.java deleted file mode 100644 index 3929c86f8..000000000 --- a/src/main/java/net/minecraft/server/EntitySpider.java +++ /dev/null @@ -1,219 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public class EntitySpider extends EntityMonster { - - private static final DataWatcherObject b = DataWatcher.a(EntitySpider.class, DataWatcherRegistry.a); - - public EntitySpider(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(1, new PathfinderGoalFloat(this)); - this.goalSelector.a(3, new PathfinderGoalLeapAtTarget(this, 0.4F)); - this.goalSelector.a(4, new EntitySpider.PathfinderGoalSpiderMeleeAttack(this)); - this.goalSelector.a(5, new PathfinderGoalRandomStrollLand(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, new Class[0])); - this.targetSelector.a(2, new EntitySpider.PathfinderGoalSpiderNearestAttackableTarget<>(this, EntityHuman.class)); - this.targetSelector.a(3, new EntitySpider.PathfinderGoalSpiderNearestAttackableTarget<>(this, EntityIronGolem.class)); - } - - @Override - public double aP() { - return (double) (this.getHeight() * 0.5F); - } - - @Override - protected NavigationAbstract b(World world) { - return new NavigationSpider(this, world); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntitySpider.b, (byte) 0); - } - - @Override - public void tick() { - super.tick(); - if (!this.world.isClientSide) { - this.r(this.positionChanged); - } - - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(16.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_SPIDER_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_SPIDER_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_SPIDER_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_SPIDER_STEP, 0.15F, 1.0F); - } - - @Override - public boolean isClimbing() { - return this.l(); - } - - @Override - public void a(IBlockData iblockdata, Vec3D vec3d) { - if (iblockdata.getBlock() != Blocks.COBWEB) { - super.a(iblockdata, vec3d); - } - - } - - @Override - public EnumMonsterType getMonsterType() { - return EnumMonsterType.ARTHROPOD; - } - - @Override - public boolean d(MobEffect mobeffect) { - return mobeffect.getMobEffect() == MobEffects.POISON ? false : super.d(mobeffect); - } - - public boolean l() { - return ((Byte) this.datawatcher.get(EntitySpider.b) & 1) != 0; - } - - public void r(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntitySpider.b); - - if (flag) { - b0 = (byte) (b0 | 1); - } else { - b0 &= -2; - } - - this.datawatcher.set(EntitySpider.b, b0); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - Object object = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - - if (generatoraccess.getRandom().nextInt(100) == 0) { - EntitySkeleton entityskeleton = (EntitySkeleton) EntityTypes.SKELETON.a(this.world); - - entityskeleton.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, 0.0F); - entityskeleton.prepare(generatoraccess, difficultydamagescaler, enummobspawn, (GroupDataEntity) null, (NBTTagCompound) null); - generatoraccess.addEntity(entityskeleton, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.JOCKEY); // CraftBukkit - add SpawnReason - entityskeleton.startRiding(this); - } - - if (object == null) { - object = new EntitySpider.GroupDataSpider(); - if (generatoraccess.getDifficulty() == EnumDifficulty.HARD && generatoraccess.getRandom().nextFloat() < 0.1F * difficultydamagescaler.d()) { - ((EntitySpider.GroupDataSpider) object).a(generatoraccess.getRandom()); - } - } - - if (object instanceof EntitySpider.GroupDataSpider) { - MobEffectList mobeffectlist = ((EntitySpider.GroupDataSpider) object).a; - - if (mobeffectlist != null) { - this.addEffect(new MobEffect(mobeffectlist, Integer.MAX_VALUE), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.SPIDER_SPAWN); // CraftBukkit - } - } - - return (GroupDataEntity) object; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 0.65F; - } - - static class PathfinderGoalSpiderNearestAttackableTarget extends PathfinderGoalNearestAttackableTarget { - - public PathfinderGoalSpiderNearestAttackableTarget(EntitySpider entityspider, Class oclass) { - super(entityspider, oclass, true); - } - - @Override - public boolean a() { - float f = this.e.aF(); - - return f >= 0.5F ? false : super.a(); - } - } - - static class PathfinderGoalSpiderMeleeAttack extends PathfinderGoalMeleeAttack { - - public PathfinderGoalSpiderMeleeAttack(EntitySpider entityspider) { - super(entityspider, 1.0D, true); - } - - @Override - public boolean a() { - return super.a() && !this.a.isVehicle(); - } - - @Override - public boolean b() { - float f = this.a.aF(); - - if (f >= 0.5F && this.a.getRandom().nextInt(100) == 0) { - this.a.setGoalTarget((EntityLiving) null); - return false; - } else { - return super.b(); - } - } - - @Override - protected double a(EntityLiving entityliving) { - return (double) (4.0F + entityliving.getWidth()); - } - } - - public static class GroupDataSpider implements GroupDataEntity { - - public MobEffectList a; - - public GroupDataSpider() {} - - public void a(Random random) { - int i = random.nextInt(5); - - if (i <= 1) { - this.a = MobEffects.FASTER_MOVEMENT; - } else if (i <= 2) { - this.a = MobEffects.INCREASE_DAMAGE; - } else if (i <= 3) { - this.a = MobEffects.REGENERATION; - } else if (i <= 4) { - this.a = MobEffects.INVISIBILITY; - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/EntitySquid.java b/src/main/java/net/minecraft/server/EntitySquid.java deleted file mode 100644 index a4d2ff64d..000000000 --- a/src/main/java/net/minecraft/server/EntitySquid.java +++ /dev/null @@ -1,277 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class EntitySquid extends EntityWaterAnimal { - - public float b; - public float c; - public float d; - public float bz; - public float bA; - public float bB; - public float bC; - public float bD; - private float bE; - private float bF; - private float bG; - private float bH; - private float bI; - private float bJ; - - public EntitySquid(EntityTypes entitytypes, World world) { - super(entitytypes, world); - //this.random.setSeed((long) this.getId()); // Paper - this.bF = 1.0F / (this.random.nextFloat() + 1.0F) * 0.2F; - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(0, new EntitySquid.PathfinderGoalSquid(this)); - this.goalSelector.a(1, new EntitySquid.a()); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(10.0D); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * 0.5F; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_SQUID_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_SQUID_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_SQUID_DEATH; - } - - @Override - protected float getSoundVolume() { - return 0.4F; - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - public void movementTick() { - super.movementTick(); - this.c = this.b; - this.bz = this.d; - this.bB = this.bA; - this.bD = this.bC; - this.bA += this.bF; - if ((double) this.bA > 6.283185307179586D) { - if (this.world.isClientSide) { - this.bA = 6.2831855F; - } else { - this.bA = (float) ((double) this.bA - 6.283185307179586D); - if (this.random.nextInt(10) == 0) { - this.bF = 1.0F / (this.random.nextFloat() + 1.0F) * 0.2F; - } - - this.world.broadcastEntityEffect(this, (byte) 19); - } - } - - if (this.av()) { - if (this.bA < 3.1415927F) { - float f = this.bA / 3.1415927F; - - this.bC = MathHelper.sin(f * f * 3.1415927F) * 3.1415927F * 0.25F; - if ((double) f > 0.75D) { - this.bE = 1.0F; - this.bG = 1.0F; - } else { - this.bG *= 0.8F; - } - } else { - this.bC = 0.0F; - this.bE *= 0.9F; - this.bG *= 0.99F; - } - - if (!this.world.isClientSide) { - this.setMot((double) (this.bH * this.bE), (double) (this.bI * this.bE), (double) (this.bJ * this.bE)); - } - - Vec3D vec3d = this.getMot(); - float f1 = MathHelper.sqrt(b(vec3d)); - - this.aK += (-((float) MathHelper.d(vec3d.x, vec3d.z)) * 57.295776F - this.aK) * 0.1F; - this.yaw = this.aK; - this.d = (float) ((double) this.d + 3.141592653589793D * (double) this.bG * 1.5D); - this.b += (-((float) MathHelper.d((double) f1, vec3d.y)) * 57.295776F - this.b) * 0.1F; - } else { - this.bC = MathHelper.e(MathHelper.sin(this.bA)) * 3.1415927F * 0.25F; - if (!this.world.isClientSide) { - double d0 = this.getMot().y; - - if (this.hasEffect(MobEffects.LEVITATION)) { - d0 = 0.05D * (double) (this.getEffect(MobEffects.LEVITATION).getAmplifier() + 1); - } else if (!this.isNoGravity()) { - d0 -= 0.08D; - } - - this.setMot(0.0D, d0 * 0.9800000190734863D, 0.0D); - } - - this.b = (float) ((double) this.b + (double) (-90.0F - this.b) * 0.02D); - } - - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (super.damageEntity(damagesource, f) && this.getLastDamager() != null) { - this.dV(); - return true; - } else { - return false; - } - } - - private Vec3D f(Vec3D vec3d) { - Vec3D vec3d1 = vec3d.a(this.c * 0.017453292F); - - vec3d1 = vec3d1.b(-this.aL * 0.017453292F); - return vec3d1; - } - - private void dV() { - this.a(SoundEffects.ENTITY_SQUID_SQUIRT, this.getSoundVolume(), this.cV()); - Vec3D vec3d = this.f(new Vec3D(0.0D, -1.0D, 0.0D)).add(this.locX, this.locY, this.locZ); - - for (int i = 0; i < 30; ++i) { - Vec3D vec3d1 = this.f(new Vec3D((double) this.random.nextFloat() * 0.6D - 0.3D, -1.0D, (double) this.random.nextFloat() * 0.6D - 0.3D)); - Vec3D vec3d2 = vec3d1.a(0.3D + (double) (this.random.nextFloat() * 2.0F)); - - ((WorldServer) this.world).a(Particles.SQUID_INK, vec3d.x, vec3d.y + 0.5D, vec3d.z, 0, vec3d2.x, vec3d2.y, vec3d2.z, 0.10000000149011612D); - } - - } - - @Override - public void e(Vec3D vec3d) { - this.move(EnumMoveType.SELF, this.getMot()); - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - final double maxHeight = generatoraccess.getMinecraftWorld().paperConfig.squidMaxSpawnHeight > 0 ? generatoraccess.getMinecraftWorld().paperConfig.squidMaxSpawnHeight : generatoraccess.getSeaLevel(); // Paper - return blockposition.getY() > generatoraccess.getMinecraftWorld().spigotConfig.squidSpawnRangeMin && blockposition.getY() < maxHeight; // Spigot // Paper - } - - public void a(float f, float f1, float f2) { - this.bH = f; - this.bI = f1; - this.bJ = f2; - } - - public boolean l() { - return this.bH != 0.0F || this.bI != 0.0F || this.bJ != 0.0F; - } - - class a extends PathfinderGoal { - - private int b; - - private a() {} - - @Override - public boolean a() { - EntityLiving entityliving = EntitySquid.this.getLastDamager(); - - return EntitySquid.this.isInWater() && entityliving != null ? EntitySquid.this.h((Entity) entityliving) < 100.0D : false; - } - - @Override - public void c() { - this.b = 0; - } - - @Override - public void e() { - ++this.b; - EntityLiving entityliving = EntitySquid.this.getLastDamager(); - - if (entityliving != null) { - Vec3D vec3d = new Vec3D(EntitySquid.this.locX - entityliving.locX, EntitySquid.this.locY - entityliving.locY, EntitySquid.this.locZ - entityliving.locZ); - IBlockData iblockdata = EntitySquid.this.world.getType(new BlockPosition(EntitySquid.this.locX + vec3d.x, EntitySquid.this.locY + vec3d.y, EntitySquid.this.locZ + vec3d.z)); - Fluid fluid = EntitySquid.this.world.getFluid(new BlockPosition(EntitySquid.this.locX + vec3d.x, EntitySquid.this.locY + vec3d.y, EntitySquid.this.locZ + vec3d.z)); - - if (fluid.a(TagsFluid.WATER) || iblockdata.isAir()) { - double d0 = vec3d.f(); - - if (d0 > 0.0D) { - vec3d.d(); - float f = 3.0F; - - if (d0 > 5.0D) { - f = (float) ((double) f - (d0 - 5.0D) / 5.0D); - } - - if (f > 0.0F) { - vec3d = vec3d.a((double) f); - } - } - - if (iblockdata.isAir()) { - vec3d = vec3d.a(0.0D, vec3d.y, 0.0D); - } - - EntitySquid.this.a((float) vec3d.x / 20.0F, (float) vec3d.y / 20.0F, (float) vec3d.z / 20.0F); - } - - if (this.b % 10 == 5) { - EntitySquid.this.world.addParticle(Particles.BUBBLE, EntitySquid.this.locX, EntitySquid.this.locY, EntitySquid.this.locZ, 0.0D, 0.0D, 0.0D); - } - - } - } - } - - class PathfinderGoalSquid extends PathfinderGoal { - - private final EntitySquid b; - - public PathfinderGoalSquid(EntitySquid entitysquid) { - this.b = entitysquid; - } - - @Override - public boolean a() { - return true; - } - - @Override - public void e() { - int i = this.b.cw(); - - if (i > 100) { - this.b.a(0.0F, 0.0F, 0.0F); - } else if (this.b.getRandom().nextInt(50) == 0 || !this.b.inWater || !this.b.l()) { - float f = this.b.getRandom().nextFloat() * 6.2831855F; - float f1 = MathHelper.cos(f) * 0.2F; - float f2 = -0.1F + this.b.getRandom().nextFloat() * 0.2F; - float f3 = MathHelper.sin(f) * 0.2F; - - this.b.a(f1, f2, f3); - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityTNTPrimed.java b/src/main/java/net/minecraft/server/EntityTNTPrimed.java deleted file mode 100644 index dc0d944ea..000000000 --- a/src/main/java/net/minecraft/server/EntityTNTPrimed.java +++ /dev/null @@ -1,179 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -import org.bukkit.event.entity.ExplosionPrimeEvent; // CraftBukkit - -public class EntityTNTPrimed extends Entity { - - private static final DataWatcherObject FUSE_TICKS = DataWatcher.a(EntityTNTPrimed.class, DataWatcherRegistry.b); - @Nullable - private EntityLiving source; - private int fuseTicks; - public float yield = 4; // CraftBukkit - add field - public boolean isIncendiary = false; // CraftBukkit - add field - - public EntityTNTPrimed(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.fuseTicks = 80; - this.i = true; - } - - public EntityTNTPrimed(World world, double d0, double d1, double d2, @Nullable EntityLiving entityliving) { - this(EntityTypes.TNT, world); - this.setPosition(d0, d1, d2); - double d3 = world.random.nextDouble() * 6.2831854820251465D; - - this.setMot(-Math.sin(d3) * 0.02D, 0.20000000298023224D, -Math.cos(d3) * 0.02D); - this.setFuseTicks(80); - this.lastX = d0; - this.lastY = d1; - this.lastZ = d2; - this.source = entityliving; - } - - @Override - protected void initDatawatcher() { - this.datawatcher.register(EntityTNTPrimed.FUSE_TICKS, 80); - } - - @Override - protected boolean playStepSound() { - return false; - } - - @Override - public boolean isInteractable() { - return !this.dead; - } - - @Override - public void tick() { - if (world.spigotConfig.currentPrimedTnt++ > world.spigotConfig.maxTntTicksPerTick) { return; } // Spigot - this.lastX = this.locX; - this.lastY = this.locY; - this.lastZ = this.locZ; - if (!this.isNoGravity()) { - this.setMot(this.getMot().add(0.0D, -0.04D, 0.0D)); - } - - this.move(EnumMoveType.SELF, this.getMot()); - // Paper start - Configurable TNT entity height nerf - if (this.world.paperConfig.entityTNTHeightNerf != 0 && this.locY > this.world.paperConfig.entityTNTHeightNerf) { - this.die(); - } - // Paper end - this.setMot(this.getMot().a(0.98D)); - if (this.onGround) { - this.setMot(this.getMot().d(0.7D, -0.5D, 0.7D)); - } - - --this.fuseTicks; - if (this.fuseTicks <= 0) { - // CraftBukkit start - Need to reverse the order of the explosion and the entity death so we have a location for the event - // this.die(); - if (!this.world.isClientSide) { - this.explode(); - } - this.die(); - // CraftBukkit end - } else { - this.ay(); - this.world.addParticle(Particles.SMOKE, this.locX, this.locY + 0.5D, this.locZ, 0.0D, 0.0D, 0.0D); - } - // Paper start - Optional prevent TNT from moving in water - if (!this.dead && this.inWater && this.world.paperConfig.preventTntFromMovingInWater) { - /* - * Author: Jedediah Smith - */ - // Send position and velocity updates to nearby players on every tick while the TNT is in water. - // This does pretty well at keeping their clients in sync with the server. - PlayerChunkMap.EntityTracker ete = this.tracker; - if (ete != null) { - PacketPlayOutEntityVelocity velocityPacket = new PacketPlayOutEntityVelocity(this); - PacketPlayOutEntityTeleport positionPacket = new PacketPlayOutEntityTeleport(this); - - ete.trackedPlayers.stream() - .filter(viewer -> (viewer.locX - this.locX) * (viewer.locY - this.locY) * (viewer.locZ - this.locZ) < 16 * 16) - .forEach(viewer -> { - viewer.playerConnection.sendPacket(velocityPacket); - viewer.playerConnection.sendPacket(positionPacket); - }); - } - } - // Paper end - } - - private void explode() { - // CraftBukkit start - // float f = 4.0F; - - ExplosionPrimeEvent event = new ExplosionPrimeEvent((org.bukkit.entity.Explosive) this.getBukkitEntity()); - this.world.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - this.world.createExplosion(this, this.locX, this.locY + (double) (this.getHeight() / 16.0F), this.locZ, event.getRadius(), event.getFire(), Explosion.Effect.BREAK); - } - // CraftBukkit end - } - - @Override - protected void b(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("Fuse", (short) this.getFuseTicks()); - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - this.setFuseTicks(nbttagcompound.getShort("Fuse")); - // Paper start - Try and load origin location from the old NBT tags for backwards compatibility - if (nbttagcompound.hasKey("SourceLoc_x")) { - int srcX = nbttagcompound.getInt("SourceLoc_x"); - int srcY = nbttagcompound.getInt("SourceLoc_y"); - int srcZ = nbttagcompound.getInt("SourceLoc_z"); - origin = new org.bukkit.Location(world.getWorld(), srcX, srcY, srcZ); - } - // Paper end - } - - @Nullable - public EntityLiving getSource() { - return this.source; - } - - @Override - protected float getHeadHeight(EntityPose entitypose, EntitySize entitysize) { - return 0.0F; - } - - public void setFuseTicks(int i) { - this.datawatcher.set(EntityTNTPrimed.FUSE_TICKS, i); - this.fuseTicks = i; - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityTNTPrimed.FUSE_TICKS.equals(datawatcherobject)) { - this.fuseTicks = this.i(); - } - - } - - public int i() { - return (Integer) this.datawatcher.get(EntityTNTPrimed.FUSE_TICKS); - } - - public int getFuseTicks() { - return this.fuseTicks; - } - - @Override - public Packet N() { - return new PacketPlayOutSpawnEntity(this); - } - - // Paper start - Optional prevent TNT from moving in water - @Override - public boolean pushedByWater() { - return !world.paperConfig.preventTntFromMovingInWater && super.pushedByWater(); - } - // Paper end -} diff --git a/src/main/java/net/minecraft/server/EntityThrownExpBottle.java b/src/main/java/net/minecraft/server/EntityThrownExpBottle.java deleted file mode 100644 index 05970c564..000000000 --- a/src/main/java/net/minecraft/server/EntityThrownExpBottle.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.minecraft.server; - -public class EntityThrownExpBottle extends EntityProjectileThrowable { - - public EntityThrownExpBottle(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityThrownExpBottle(World world, EntityLiving entityliving) { - super(EntityTypes.EXPERIENCE_BOTTLE, entityliving, world); - } - - public EntityThrownExpBottle(World world, double d0, double d1, double d2) { - super(EntityTypes.EXPERIENCE_BOTTLE, d0, d1, d2, world); - } - - @Override - protected Item i() { - return Items.EXPERIENCE_BOTTLE; - } - - @Override - protected float l() { - return 0.07F; - } - - @Override - protected void a(MovingObjectPosition movingobjectposition) { - if (!this.world.isClientSide) { - // CraftBukkit - moved to after event - // this.world.triggerEffect(2002, new BlockPosition(this), PotionUtil.a(Potions.WATER)); - 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), PotionUtil.a(Potions.WATER)); - } - // 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, org.bukkit.entity.ExperienceOrb.SpawnReason.EXP_BOTTLE, getShooter(), this)); // Paper - } - - this.die(); - } - - } -} diff --git a/src/main/java/net/minecraft/server/EntityThrownTrident.java b/src/main/java/net/minecraft/server/EntityThrownTrident.java deleted file mode 100644 index 392cadf31..000000000 --- a/src/main/java/net/minecraft/server/EntityThrownTrident.java +++ /dev/null @@ -1,180 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class EntityThrownTrident extends EntityArrow { - - private static final DataWatcherObject as = DataWatcher.a(EntityThrownTrident.class, DataWatcherRegistry.a); - public ItemStack trident; - private boolean au; - public int ar; - - public EntityThrownTrident(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.trident = new ItemStack(Items.TRIDENT); - } - - public EntityThrownTrident(World world, EntityLiving entityliving, ItemStack itemstack) { - super(EntityTypes.TRIDENT, entityliving, world); - this.trident = new ItemStack(Items.TRIDENT); - this.trident = itemstack.cloneItemStack(); - this.datawatcher.set(EntityThrownTrident.as, (byte) EnchantmentManager.f(itemstack)); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityThrownTrident.as, (byte) 0); - } - - @Override - public void tick() { - if (this.d > 4) { - this.au = true; - } - - Entity entity = this.getShooter(); - - if ((this.au || this.v()) && entity != null) { - byte b0 = (Byte) this.datawatcher.get(EntityThrownTrident.as); - - if (b0 > 0 && !this.w()) { - if (!this.world.isClientSide && this.fromPlayer == EntityArrow.PickupStatus.ALLOWED) { - this.a(this.getItemStack(), 0.1F); - } - - this.die(); - } else if (b0 > 0) { - this.n(true); - Vec3D vec3d = new Vec3D(entity.locX - this.locX, entity.locY + (double) entity.getHeadHeight() - this.locY, entity.locZ - this.locZ); - - this.locY += vec3d.y * 0.015D * (double) b0; - if (this.world.isClientSide) { - this.I = this.locY; - } - - double d0 = 0.05D * (double) b0; - - this.setMot(this.getMot().a(0.95D).e(vec3d.d().a(d0))); - if (this.ar == 0) { - this.a(SoundEffects.ITEM_TRIDENT_RETURN, 10.0F, 1.0F); - } - - ++this.ar; - } - } - - super.tick(); - } - - private boolean w() { - Entity entity = this.getShooter(); - - return entity != null && entity.isAlive() ? !(entity instanceof EntityPlayer) || !entity.isSpectator() : false; - } - - @Override - protected ItemStack getItemStack() { - return this.trident.cloneItemStack(); - } - - @Nullable - @Override - protected MovingObjectPositionEntity a(Vec3D vec3d, Vec3D vec3d1) { - return this.au ? null : super.a(vec3d, vec3d1); - } - - @Override - protected void a(MovingObjectPositionEntity movingobjectpositionentity) { - Entity entity = movingobjectpositionentity.getEntity(); - float f = 8.0F; - - if (entity instanceof EntityLiving) { - EntityLiving entityliving = (EntityLiving) entity; - - f += EnchantmentManager.a(this.trident, entityliving.getMonsterType()); - } - - Entity entity1 = this.getShooter(); - DamageSource damagesource = DamageSource.a(this, (Entity) (entity1 == null ? this : entity1)); - - this.au = true; - SoundEffect soundeffect = SoundEffects.ITEM_TRIDENT_HIT; - - if (entity.damageEntity(damagesource, f) && entity instanceof EntityLiving) { - EntityLiving entityliving1 = (EntityLiving) entity; - - if (entity1 instanceof EntityLiving) { - EnchantmentManager.a(entityliving1, entity1); - EnchantmentManager.b((EntityLiving) entity1, (Entity) entityliving1); - } - - this.a(entityliving1); - } - - this.setMot(this.getMot().d(-0.01D, -0.1D, -0.01D)); - float f1 = 1.0F; - - if (this.world instanceof WorldServer && this.world.U() && EnchantmentManager.h(this.trident)) { - BlockPosition blockposition = entity.getChunkCoordinates(); - - if (this.world.f(blockposition)) { - EntityLightning entitylightning = new EntityLightning(this.world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, false); - - entitylightning.d(entity1 instanceof EntityPlayer ? (EntityPlayer) entity1 : null); - ((WorldServer) this.world).strikeLightning(entitylightning, org.bukkit.event.weather.LightningStrikeEvent.Cause.TRIDENT); // CraftBukkit - soundeffect = SoundEffects.ITEM_TRIDENT_THUNDER; - f1 = 5.0F; - } - } - - this.a(soundeffect, f1, 1.0F); - } - - @Override - protected SoundEffect k() { - return SoundEffects.ITEM_TRIDENT_HIT_GROUND; - } - - @Override - public void pickup(EntityHuman entityhuman) { - Entity entity = this.getShooter(); - - if (entity == null || entity.getUniqueID() == entityhuman.getUniqueID()) { - super.pickup(entityhuman); - } - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("Trident", 10)) { - this.trident = ItemStack.a(nbttagcompound.getCompound("Trident")); - } - - this.au = nbttagcompound.getBoolean("DealtDamage"); - this.datawatcher.set(EntityThrownTrident.as, (byte) EnchantmentManager.f(this.trident)); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.set("Trident", this.trident.save(new NBTTagCompound())); - nbttagcompound.setBoolean("DealtDamage", this.au); - } - - @Override - protected void i() { - byte b0 = (Byte) this.datawatcher.get(EntityThrownTrident.as); - - if (this.fromPlayer != EntityArrow.PickupStatus.ALLOWED || b0 <= 0) { - super.i(); - } - - } - - @Override - protected float u() { - return 0.99F; - } -} diff --git a/src/main/java/net/minecraft/server/EntityTippedArrow.java b/src/main/java/net/minecraft/server/EntityTippedArrow.java deleted file mode 100644 index ddf420ea2..000000000 --- a/src/main/java/net/minecraft/server/EntityTippedArrow.java +++ /dev/null @@ -1,236 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Sets; -import java.util.Collection; -import java.util.Iterator; -import java.util.Set; - -public class EntityTippedArrow extends EntityArrow { - - private static final DataWatcherObject COLOR = DataWatcher.a(EntityTippedArrow.class, DataWatcherRegistry.b); - private PotionRegistry potionRegistry; - public final Set effects; - private boolean hasColor; - - public EntityTippedArrow(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.potionRegistry = Potions.EMPTY; - this.effects = Sets.newHashSet(); - } - - public EntityTippedArrow(World world, double d0, double d1, double d2) { - super(EntityTypes.ARROW, d0, d1, d2, world); - this.potionRegistry = Potions.EMPTY; - this.effects = Sets.newHashSet(); - } - - public EntityTippedArrow(World world, EntityLiving entityliving) { - super(EntityTypes.ARROW, entityliving, world); - this.potionRegistry = Potions.EMPTY; - this.effects = Sets.newHashSet(); - } - - public void b(ItemStack itemstack) { - if (itemstack.getItem() == Items.TIPPED_ARROW) { - this.potionRegistry = PotionUtil.d(itemstack); - Collection collection = PotionUtil.b(itemstack); - - if (!collection.isEmpty()) { - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - this.effects.add(new MobEffect(mobeffect)); - } - } - - int i = c(itemstack); - - if (i == -1) { - this.z(); - } else { - this.setColor(i); - } - } else if (itemstack.getItem() == Items.ARROW) { - this.potionRegistry = Potions.EMPTY; - this.effects.clear(); - this.datawatcher.set(EntityTippedArrow.COLOR, -1); - } - - } - - public static int c(ItemStack itemstack) { - NBTTagCompound nbttagcompound = itemstack.getTag(); - - return nbttagcompound != null && nbttagcompound.hasKeyOfType("CustomPotionColor", 99) ? nbttagcompound.getInt("CustomPotionColor") : -1; - } - - private void z() { - this.hasColor = false; - this.datawatcher.set(EntityTippedArrow.COLOR, PotionUtil.a((Collection) PotionUtil.a(this.potionRegistry, (Collection) this.effects))); - } - - public void addEffect(MobEffect mobeffect) { - this.effects.add(mobeffect); - this.getDataWatcher().set(EntityTippedArrow.COLOR, PotionUtil.a((Collection) PotionUtil.a(this.potionRegistry, (Collection) this.effects))); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityTippedArrow.COLOR, -1); - } - - @Override - public void tick() { - super.tick(); - if (this.world.isClientSide) { - if (this.inGround) { - if (this.d % 5 == 0) { - this.b(1); - } - } else { - this.b(2); - } - } else if (this.inGround && this.d != 0 && !this.effects.isEmpty() && this.d >= 600) { - this.world.broadcastEntityEffect(this, (byte) 0); - this.potionRegistry = Potions.EMPTY; - this.effects.clear(); - this.datawatcher.set(EntityTippedArrow.COLOR, -1); - } - - } - - private void b(int i) { - int j = this.getColor(); - - if (j != -1 && i > 0) { - double d0 = (double) (j >> 16 & 255) / 255.0D; - double d1 = (double) (j >> 8 & 255) / 255.0D; - double d2 = (double) (j >> 0 & 255) / 255.0D; - - for (int k = 0; k < i; ++k) { - this.world.addParticle(Particles.ENTITY_EFFECT, this.locX + (this.random.nextDouble() - 0.5D) * (double) this.getWidth(), this.locY + this.random.nextDouble() * (double) this.getHeight(), this.locZ + (this.random.nextDouble() - 0.5D) * (double) this.getWidth(), d0, d1, d2); - } - - } - } - - // CraftBukkit start accessor methods - public void refreshEffects() { - this.getDataWatcher().set(EntityTippedArrow.COLOR, PotionUtil.a((Collection) PotionUtil.a(this.potionRegistry, (Collection) this.effects))); - } - - public String getType() { - return IRegistry.POTION.getKey(this.potionRegistry).toString(); - } - - public void setType(String string) { - this.potionRegistry = IRegistry.POTION.get(new MinecraftKey(string)); - this.getDataWatcher().set(EntityTippedArrow.COLOR, PotionUtil.a((Collection) PotionUtil.a(this.potionRegistry, (Collection) this.effects))); - } - - public boolean isTipped() { - return !(this.effects.isEmpty() && this.potionRegistry == Potions.EMPTY); - } - // CraftBukkit end - - public int getColor() { - return (Integer) this.datawatcher.get(EntityTippedArrow.COLOR); - } - - public void setColor(int i) { - this.hasColor = true; - this.datawatcher.set(EntityTippedArrow.COLOR, i); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - if (this.potionRegistry != Potions.EMPTY && this.potionRegistry != null) { - nbttagcompound.setString("Potion", IRegistry.POTION.getKey(this.potionRegistry).toString()); - } - - if (this.hasColor) { - nbttagcompound.setInt("Color", this.getColor()); - } - - if (!this.effects.isEmpty()) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.effects.iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - nbttaglist.add(mobeffect.a(new NBTTagCompound())); - } - - nbttagcompound.set("CustomPotionEffects", nbttaglist); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("Potion", 8)) { - this.potionRegistry = PotionUtil.c(nbttagcompound); - } - - Iterator iterator = PotionUtil.b(nbttagcompound).iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - this.addEffect(mobeffect); - } - - if (nbttagcompound.hasKeyOfType("Color", 99)) { - this.setColor(nbttagcompound.getInt("Color")); - } else { - this.z(); - } - - } - - @Override - protected void a(EntityLiving entityliving) { - super.a(entityliving); - Iterator iterator = this.potionRegistry.a().iterator(); - - MobEffect mobeffect; - - while (iterator.hasNext()) { - mobeffect = (MobEffect) iterator.next(); - entityliving.addEffect(new MobEffect(mobeffect.getMobEffect(), Math.max(mobeffect.getDuration() / 8, 1), mobeffect.getAmplifier(), mobeffect.isAmbient(), mobeffect.isShowParticles()), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ARROW); // CraftBukkit - } - - if (!this.effects.isEmpty()) { - iterator = this.effects.iterator(); - - while (iterator.hasNext()) { - mobeffect = (MobEffect) iterator.next(); - entityliving.addEffect(mobeffect, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ARROW); // CraftBukkit - } - } - - } - - @Override - protected ItemStack getItemStack() { - if (this.effects.isEmpty() && this.potionRegistry == Potions.EMPTY) { - return new ItemStack(Items.ARROW); - } else { - ItemStack itemstack = new ItemStack(Items.TIPPED_ARROW); - - PotionUtil.a(itemstack, this.potionRegistry); - PotionUtil.a(itemstack, (Collection) this.effects); - if (this.hasColor) { - itemstack.getOrCreateTag().setInt("CustomPotionColor", this.getColor()); - } - - return itemstack; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityTrackerEntry.java b/src/main/java/net/minecraft/server/EntityTrackerEntry.java deleted file mode 100644 index 460c687d3..000000000 --- a/src/main/java/net/minecraft/server/EntityTrackerEntry.java +++ /dev/null @@ -1,395 +0,0 @@ -package net.minecraft.server; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerVelocityEvent; -// CraftBukkit end - -public class EntityTrackerEntry { - - private static final Logger LOGGER = LogManager.getLogger(); - private final WorldServer b; - private final Entity tracker; - private final int d; - private final boolean e; - private final Consumer> f; private Consumer> getPacketConsumer() { return f; } // Paper - OBFHELPER - private long xLoc; - private long yLoc; - private long zLoc; - private int yRot; - private int xRot; - private int headYaw; - private Vec3D m; - private int n; - private int o; - private List p; - private boolean q; - private boolean r; - // CraftBukkit start - final Set trackedPlayers; // Paper - private -> package - // Paper start - private java.util.Map trackedPlayerMap = null; - - /** - * Requested in https://github.com/PaperMC/Paper/issues/1537 to allow intercepting packets - */ - public void sendPlayerPacket(EntityPlayer player, Packet packet) { - player.playerConnection.sendPacket(packet); - } - - public EntityTrackerEntry(WorldServer worldserver, Entity entity, int i, boolean flag, Consumer> consumer, java.util.Map trackedPlayers) { - this(worldserver, entity, i, flag, consumer, trackedPlayers.keySet()); - trackedPlayerMap = trackedPlayers; - } - - public EntityTrackerEntry(WorldServer worldserver, Entity entity, int i, boolean flag, Consumer> consumer, Set trackedPlayers) { - // Paper end - this.trackedPlayers = trackedPlayers; - // CraftBukkit end - this.m = Vec3D.a; - this.p = Collections.emptyList(); - this.b = worldserver; - this.f = consumer; - this.tracker = entity; - this.d = i; - this.e = flag; - this.d(); - this.yRot = MathHelper.d(entity.yaw * 256.0F / 360.0F); - this.xRot = MathHelper.d(entity.pitch * 256.0F / 360.0F); - this.headYaw = MathHelper.d(entity.getHeadRotation() * 256.0F / 360.0F); - this.r = entity.onGround; - } - - public void a() { - List list = this.tracker.getPassengers(); - - if (!list.equals(this.p)) { - this.p = list; - this.broadcastIncludingSelf(new PacketPlayOutMount(this.tracker)); // CraftBukkit - } - - // PAIL : rename - if (this.tracker instanceof EntityItemFrame /*&& this.n % 10 == 0*/) { // CraftBukkit - Moved below, should always enter this block - EntityItemFrame entityitemframe = (EntityItemFrame) this.tracker; - ItemStack itemstack = entityitemframe.getItem(); - - if (this.n % 10 == 0 && itemstack.getItem() instanceof ItemWorldMap) { // CraftBukkit - Moved this.n % 10 logic here so item frames do not enter the other blocks - WorldMap worldmap = ItemWorldMap.getSavedMap(itemstack, this.b); - Iterator iterator = this.trackedPlayers.iterator(); // CraftBukkit - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - worldmap.a((EntityHuman) entityplayer, itemstack); - Packet packet = ((ItemWorldMap) itemstack.getItem()).a(itemstack, (World) this.b, (EntityHuman) entityplayer); - - if (packet != null) { - entityplayer.playerConnection.sendPacket(packet); - } - } - } - - this.c(); - } - - if (this.n % this.d == 0 || this.tracker.impulse || this.tracker.getDataWatcher().a()) { - int i; - int j; - - if (this.tracker.isPassenger()) { - i = MathHelper.d(this.tracker.yaw * 256.0F / 360.0F); - j = MathHelper.d(this.tracker.pitch * 256.0F / 360.0F); - boolean flag = Math.abs(i - this.yRot) >= 1 || Math.abs(j - this.xRot) >= 1; - - if (flag) { - this.f.accept(new PacketPlayOutEntity.PacketPlayOutEntityLook(this.tracker.getId(), (byte) i, (byte) j, this.tracker.onGround)); - this.yRot = i; - this.xRot = j; - } - - this.d(); - this.c(); - this.q = true; - } else { - ++this.o; - i = MathHelper.d(this.tracker.yaw * 256.0F / 360.0F); - j = MathHelper.d(this.tracker.pitch * 256.0F / 360.0F); - Vec3D vec3d = (new Vec3D(this.tracker.locX, this.tracker.locY, this.tracker.locZ)).d(PacketPlayOutEntity.a(this.xLoc, this.yLoc, this.zLoc)); - boolean flag1 = vec3d.g() >= 7.62939453125E-6D; - Packet packet1 = null; - boolean flag2 = flag1 || this.n % 60 == 0; - boolean flag3 = Math.abs(i - this.yRot) >= 1 || Math.abs(j - this.xRot) >= 1; - - // CraftBukkit start - Code moved from below - if (flag2) { - this.d(); - } - - if (flag3) { - this.yRot = i; - this.xRot = j; - } - // CraftBukkit end - - if (this.n > 0 || this.tracker instanceof EntityArrow) { - long k = PacketPlayOutEntity.a(vec3d.x); - long l = PacketPlayOutEntity.a(vec3d.y); - long i1 = PacketPlayOutEntity.a(vec3d.z); - boolean flag4 = k < -32768L || k > 32767L || l < -32768L || l > 32767L || i1 < -32768L || i1 > 32767L; - - if (!flag4 && this.o <= 400 && !this.q && this.r == this.tracker.onGround) { - if ((!flag2 || !flag3) && !(this.tracker instanceof EntityArrow)) { - if (flag2) { - packet1 = new PacketPlayOutEntity.PacketPlayOutRelEntityMove(this.tracker.getId(), (short) ((int) k), (short) ((int) l), (short) ((int) i1), this.tracker.onGround); - } else if (flag3) { - packet1 = new PacketPlayOutEntity.PacketPlayOutEntityLook(this.tracker.getId(), (byte) i, (byte) j, this.tracker.onGround); - } - } else { - packet1 = new PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook(this.tracker.getId(), (short) ((int) k), (short) ((int) l), (short) ((int) i1), (byte) i, (byte) j, this.tracker.onGround); - } - } else { - this.r = this.tracker.onGround; - this.o = 0; - packet1 = new PacketPlayOutEntityTeleport(this.tracker); - } - } - - if ((this.e || this.tracker.impulse || this.tracker instanceof EntityLiving && ((EntityLiving) this.tracker).isGliding()) && this.n > 0) { - Vec3D vec3d1 = this.tracker.getMot(); - double d0 = vec3d1.distanceSquared(this.m); - - if (d0 > 1.0E-7D || d0 > 0.0D && vec3d1.g() == 0.0D) { - this.m = vec3d1; - this.f.accept(new PacketPlayOutEntityVelocity(this.tracker.getId(), this.m)); - } - } - - if (packet1 != null) { - // paper start - if (trackedPlayerMap == null || packet1 instanceof PacketPlayOutEntityTeleport) { - this.f.accept((packet1)); - } else { - PacketPlayOutEntityTeleport teleportPacket = null; - - for (java.util.Map.Entry viewer : trackedPlayerMap.entrySet()) { - if (viewer.getValue()) { - viewer.setValue(false); - if (teleportPacket == null) { - teleportPacket = new PacketPlayOutEntityTeleport(this.tracker); - } - sendPlayerPacket(viewer.getKey(), teleportPacket); - } else { - sendPlayerPacket(viewer.getKey(), packet1); - } - } - } - // Paper end - } - - this.c(); - /* CraftBukkit start - Code moved up - if (flag2) { - this.d(); - } - - if (flag3) { - this.yRot = i; - this.xRot = j; - } - // CraftBukkit end */ - - this.q = false; - } - - i = MathHelper.d(this.tracker.getHeadRotation() * 256.0F / 360.0F); - if (Math.abs(i - this.headYaw) >= 1) { - this.f.accept(new PacketPlayOutEntityHeadRotation(this.tracker, (byte) i)); - this.headYaw = i; - } - - this.tracker.impulse = false; - } - - ++this.n; - if (this.tracker.velocityChanged) { - // CraftBukkit start - Create PlayerVelocity event - boolean cancelled = false; - - if (this.tracker instanceof EntityPlayer) { - Player player = (Player) this.tracker.getBukkitEntity(); - org.bukkit.util.Vector velocity = player.getVelocity(); - - PlayerVelocityEvent event = new PlayerVelocityEvent(player, velocity.clone()); - this.tracker.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - cancelled = true; - } else if (!velocity.equals(event.getVelocity())) { - player.setVelocity(event.getVelocity()); - } - } - - if (!cancelled) { - this.broadcastIncludingSelf(new PacketPlayOutEntityVelocity(this.tracker)); - } - // CraftBukkit end - this.tracker.velocityChanged = false; - } - - } - - public void a(EntityPlayer entityplayer) { - this.tracker.c(entityplayer); - entityplayer.c(this.tracker); - } - - public void b(EntityPlayer entityplayer) { - PlayerConnection playerconnection = entityplayer.playerConnection; - - entityplayer.playerConnection.getClass(); - this.a(playerconnection::sendPacket, entityplayer); // CraftBukkit - add player - this.tracker.b(entityplayer); - entityplayer.d(this.tracker); - } - - public void a(Consumer> consumer, EntityPlayer entityplayer) { // CraftBukkit - add player - if (this.tracker.dead) { - // CraftBukkit start - Remove useless error spam, just return - // EntityTrackerEntry.LOGGER.warn("Fetching packet for removed entity " + this.tracker); - return; - // CraftBukkit end - } - - Packet packet = this.tracker.N(); - - this.headYaw = MathHelper.d(this.tracker.getHeadRotation() * 256.0F / 360.0F); - consumer.accept(packet); - if (!this.tracker.getDataWatcher().d()) { - consumer.accept(new PacketPlayOutEntityMetadata(this.tracker.getId(), this.tracker.getDataWatcher(), true)); - } - - boolean flag = this.e; - - if (this.tracker instanceof EntityLiving) { - AttributeMapServer attributemapserver = (AttributeMapServer) ((EntityLiving) this.tracker).getAttributeMap(); - Collection collection = attributemapserver.c(); - - // CraftBukkit start - If sending own attributes send scaled health instead of current maximum health - if (this.tracker.getId() == entityplayer.getId()) { - ((EntityPlayer) this.tracker).getBukkitEntity().injectScaledMaxHealth(collection, false); - } - // CraftBukkit end - - if (!collection.isEmpty()) { - consumer.accept(new PacketPlayOutUpdateAttributes(this.tracker.getId(), collection)); - } - - if (((EntityLiving) this.tracker).isGliding()) { - flag = true; - } - } - - this.m = this.tracker.getMot(); - if (flag && !(packet instanceof PacketPlayOutSpawnEntityLiving)) { - consumer.accept(new PacketPlayOutEntityVelocity(this.tracker.getId(), this.m)); - } - - if (this.tracker instanceof EntityLiving) { - EnumItemSlot[] aenumitemslot = EnumItemSlot.values(); - int i = aenumitemslot.length; - - for (int j = 0; j < i; ++j) { - EnumItemSlot enumitemslot = aenumitemslot[j]; - ItemStack itemstack = ((EntityLiving) this.tracker).getEquipment(enumitemslot); - - if (!itemstack.isEmpty()) { - consumer.accept(new PacketPlayOutEntityEquipment(this.tracker.getId(), enumitemslot, itemstack)); - } - } - } - - // CraftBukkit start - Fix for nonsensical head yaw - this.headYaw = MathHelper.d(this.tracker.getHeadRotation() * 256.0F / 360.0F); - consumer.accept(new PacketPlayOutEntityHeadRotation(this.tracker, (byte) headYaw)); - // CraftBukkit end - - if (this.tracker instanceof EntityLiving) { - EntityLiving entityliving = (EntityLiving) this.tracker; - Iterator iterator = entityliving.getEffects().iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - consumer.accept(new PacketPlayOutEntityEffect(this.tracker.getId(), mobeffect)); - } - } - - if (!this.tracker.getPassengers().isEmpty()) { - consumer.accept(new PacketPlayOutMount(this.tracker)); - } - - if (this.tracker.isPassenger()) { - consumer.accept(new PacketPlayOutMount(this.tracker.getVehicle())); - } - - } - - private void c() { - DataWatcher datawatcher = this.tracker.getDataWatcher(); - - if (datawatcher.a()) { - this.broadcastIncludingSelf(new PacketPlayOutEntityMetadata(this.tracker.getId(), datawatcher, false)); - } - - if (this.tracker instanceof EntityLiving) { - AttributeMapServer attributemapserver = (AttributeMapServer) ((EntityLiving) this.tracker).getAttributeMap(); - Set set = attributemapserver.getAttributes(); - - if (!set.isEmpty()) { - // CraftBukkit start - Send scaled max health - if (this.tracker instanceof EntityPlayer) { - ((EntityPlayer) this.tracker).getBukkitEntity().injectScaledMaxHealth(set, false); - } - // CraftBukkit end - this.broadcastIncludingSelf(new PacketPlayOutUpdateAttributes(this.tracker.getId(), set)); - } - - set.clear(); - } - - } - - private void d() { - this.xLoc = PacketPlayOutEntity.a(this.tracker.locX); - this.yLoc = PacketPlayOutEntity.a(this.tracker.locY); - this.zLoc = PacketPlayOutEntity.a(this.tracker.locZ); - } - - public Vec3D b() { - return PacketPlayOutEntity.a(this.xLoc, this.yLoc, this.zLoc); - } - - // Paper start - Add broadcast method - void broadcast(Packet packet) { - this.getPacketConsumer().accept(packet); - } - // Paper end - - private void broadcastIncludingSelf(Packet packet) { - this.f.accept(packet); - if (this.tracker instanceof EntityPlayer) { - ((EntityPlayer) this.tracker).playerConnection.sendPacket(packet); - } - - } -} diff --git a/src/main/java/net/minecraft/server/EntityTurtle.java b/src/main/java/net/minecraft/server/EntityTurtle.java deleted file mode 100644 index 0bd80e562..000000000 --- a/src/main/java/net/minecraft/server/EntityTurtle.java +++ /dev/null @@ -1,754 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Sets; -import java.util.EnumSet; -import java.util.Random; -import java.util.Set; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntityTurtle extends EntityAnimal { - - private static final DataWatcherObject bA = DataWatcher.a(EntityTurtle.class, DataWatcherRegistry.l); - private static final DataWatcherObject bB = DataWatcher.a(EntityTurtle.class, DataWatcherRegistry.i); - private static final DataWatcherObject bC = DataWatcher.a(EntityTurtle.class, DataWatcherRegistry.i); - private static final DataWatcherObject bD = DataWatcher.a(EntityTurtle.class, DataWatcherRegistry.l); - private static final DataWatcherObject bE = DataWatcher.a(EntityTurtle.class, DataWatcherRegistry.i); - private static final DataWatcherObject bF = DataWatcher.a(EntityTurtle.class, DataWatcherRegistry.i); - private int bG; - public static final Predicate bz = (entityliving) -> { - return entityliving.isBaby() && !entityliving.isInWater(); - }; - - public EntityTurtle(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.moveController = new EntityTurtle.e(this); - this.K = 1.0F; - } - - public final void setHome(BlockPosition pos) { g(pos); } // Paper - OBFHELPER - public void g(BlockPosition blockposition) { - this.datawatcher.set(EntityTurtle.bA, blockposition); - } - - public final BlockPosition getHome() { return this.dX(); } // Paper - OBFHELPER - private BlockPosition dX() { - return (BlockPosition) this.datawatcher.get(EntityTurtle.bA); - } - - public final void setTravelPos(BlockPosition pos) { this.h(pos); } // Paper - OBFHELPER - private void h(BlockPosition blockposition) { - this.datawatcher.set(EntityTurtle.bD, blockposition); - } - - public final BlockPosition getTravelPos() { return this.dY(); } // Paper - OBFHELPER - private BlockPosition dY() { - return (BlockPosition) this.datawatcher.get(EntityTurtle.bD); - } - - public final boolean hasEgg() { return this.dV(); } // Paper - OBFHELPER - public boolean dV() { - return (Boolean) this.datawatcher.get(EntityTurtle.bB); - } - - public final void setHasEgg(boolean hasEgg) { this.r(hasEgg); } // Paper - OBFHELPER - private void r(boolean flag) { - this.datawatcher.set(EntityTurtle.bB, flag); - } - - public final boolean isDigging() { return this.dW(); } // Paper - OBFHELPER - public boolean dW() { - return (Boolean) this.datawatcher.get(EntityTurtle.bC); - } - - public final void setDigging(boolean digging) { this.s(digging); } // Paper - OBFHELPER - private void s(boolean flag) { - this.bG = flag ? 1 : 0; - this.datawatcher.set(EntityTurtle.bC, flag); - } - - public final boolean isGoingHome() { return this.dZ(); } // Paper - OBFHELPER - private boolean dZ() { - return (Boolean) this.datawatcher.get(EntityTurtle.bE); - } - - public final void setGoingHome(boolean goingHome) { this.t(goingHome); } // Paper - OBFHELPER - private void t(boolean flag) { - this.datawatcher.set(EntityTurtle.bE, flag); - } - - public final boolean isTravelling() { return this.ee(); } // Paper - OBFHELPER - private boolean ee() { - return (Boolean) this.datawatcher.get(EntityTurtle.bF); - } - - public final void setTravelling(boolean travelling) { this.u(travelling); } // Paper - OBFHELPER - private void u(boolean flag) { - this.datawatcher.set(EntityTurtle.bF, flag); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityTurtle.bA, BlockPosition.ZERO); - this.datawatcher.register(EntityTurtle.bB, false); - this.datawatcher.register(EntityTurtle.bD, BlockPosition.ZERO); - this.datawatcher.register(EntityTurtle.bE, false); - this.datawatcher.register(EntityTurtle.bF, false); - this.datawatcher.register(EntityTurtle.bC, false); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("HomePosX", this.dX().getX()); - nbttagcompound.setInt("HomePosY", this.dX().getY()); - nbttagcompound.setInt("HomePosZ", this.dX().getZ()); - nbttagcompound.setBoolean("HasEgg", this.dV()); - nbttagcompound.setInt("TravelPosX", this.dY().getX()); - nbttagcompound.setInt("TravelPosY", this.dY().getY()); - nbttagcompound.setInt("TravelPosZ", this.dY().getZ()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - int i = nbttagcompound.getInt("HomePosX"); - int j = nbttagcompound.getInt("HomePosY"); - int k = nbttagcompound.getInt("HomePosZ"); - - this.g(new BlockPosition(i, j, k)); - super.a(nbttagcompound); - this.r(nbttagcompound.getBoolean("HasEgg")); - int l = nbttagcompound.getInt("TravelPosX"); - int i1 = nbttagcompound.getInt("TravelPosY"); - int j1 = nbttagcompound.getInt("TravelPosZ"); - - this.h(new BlockPosition(l, i1, j1)); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.g(new BlockPosition(this)); - this.h(BlockPosition.ZERO); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - public static boolean c(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return blockposition.getY() < generatoraccess.getSeaLevel() + 4 && generatoraccess.getType(blockposition.down()).getBlock() == Blocks.SAND && generatoraccess.getLightLevel(blockposition, 0) > 8; - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(0, new EntityTurtle.f(this, 1.2D)); - this.goalSelector.a(1, new EntityTurtle.a(this, 1.0D)); - this.goalSelector.a(1, new EntityTurtle.d(this, 1.0D)); - this.goalSelector.a(2, new EntityTurtle.i(this, 1.1D, Blocks.SEAGRASS.getItem())); - this.goalSelector.a(3, new EntityTurtle.c(this, 1.0D)); - this.goalSelector.a(4, new EntityTurtle.b(this, 1.0D)); - this.goalSelector.a(7, new EntityTurtle.j(this, 1.0D)); - this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); - this.goalSelector.a(9, new EntityTurtle.h(this, 1.0D, 100)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(30.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); - } - - @Override - public boolean bE() { - return false; - } - - @Override - public boolean cm() { - return true; - } - - @Override - public EnumMonsterType getMonsterType() { - return EnumMonsterType.e; - } - - @Override - public int A() { - return 200; - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - return !this.isInWater() && this.onGround && !this.isBaby() ? SoundEffects.ENTITY_TURTLE_AMBIENT_LAND : super.getSoundAmbient(); - } - - @Override - protected void d(float f) { - super.d(f * 1.5F); - } - - @Override - protected SoundEffect getSoundSwim() { - return SoundEffects.ENTITY_TURTLE_SWIM; - } - - @Nullable - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return this.isBaby() ? SoundEffects.ENTITY_TURTLE_HURT_BABY : SoundEffects.ENTITY_TURTLE_HURT; - } - - @Nullable - @Override - protected SoundEffect getSoundDeath() { - return this.isBaby() ? SoundEffects.ENTITY_TURTLE_DEATH_BABY : SoundEffects.ENTITY_TURTLE_DEATH; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - SoundEffect soundeffect = this.isBaby() ? SoundEffects.ENTITY_TURTLE_SHAMBLE_BABY : SoundEffects.ENTITY_TURTLE_SHAMBLE; - - this.a(soundeffect, 0.15F, 1.0F); - } - - @Override - public boolean ea() { - return super.ea() && !this.dV(); - } - - @Override - protected float ag() { - return this.F + 0.15F; - } - - @Override - public float cn() { - return this.isBaby() ? 0.3F : 1.0F; - } - - @Override - protected NavigationAbstract b(World world) { - return new EntityTurtle.g(this, world); - } - - @Nullable - @Override - public EntityAgeable createChild(EntityAgeable entityageable) { - return (EntityAgeable) EntityTypes.TURTLE.a(this.world); - } - - @Override - public boolean i(ItemStack itemstack) { - return itemstack.getItem() == Blocks.SEAGRASS.getItem(); - } - - @Override - public float a(BlockPosition blockposition, IWorldReader iworldreader) { - return !this.dZ() && iworldreader.getFluid(blockposition).a(TagsFluid.WATER) ? 10.0F : (iworldreader.getType(blockposition.down()).getBlock() == Blocks.SAND ? 10.0F : iworldreader.v(blockposition) - 0.5F); - } - - @Override - public void movementTick() { - super.movementTick(); - if (this.isAlive() && this.dW() && this.bG >= 1 && this.bG % 5 == 0) { - BlockPosition blockposition = new BlockPosition(this); - - if (this.world.getType(blockposition.down()).getBlock() == Blocks.SAND) { - this.world.triggerEffect(2001, blockposition, Block.getCombinedId(Blocks.SAND.getBlockData())); - } - } - - } - - @Override - protected void l() { - super.l(); - if (!this.isBaby() && this.world.getGameRules().getBoolean(GameRules.DO_MOB_LOOT)) { - this.forceDrops = true; // CraftBukkit - this.a((IMaterial) Items.SCUTE, 1); - this.forceDrops = false; // CraftBukkit - } - - } - - @Override - public void e(Vec3D vec3d) { - if (this.df() && this.isInWater()) { - this.a(0.1F, vec3d); - this.move(EnumMoveType.SELF, this.getMot()); - this.setMot(this.getMot().a(0.9D)); - if (this.getGoalTarget() == null && (!this.dZ() || !this.dX().a((IPosition) this.getPositionVector(), 20.0D))) { - this.setMot(this.getMot().add(0.0D, -0.005D, 0.0D)); - } - } else { - super.e(vec3d); - } - - } - - @Override - public boolean a(EntityHuman entityhuman) { - return false; - } - - @Override - public void onLightningStrike(EntityLightning entitylightning) { - org.bukkit.craftbukkit.event.CraftEventFactory.entityDamage = entitylightning; // CraftBukkit - this.damageEntity(DamageSource.LIGHTNING, Float.MAX_VALUE); - org.bukkit.craftbukkit.event.CraftEventFactory.entityDamage = null; // CraftBukkit - } - - static class g extends NavigationGuardian { - - g(EntityTurtle entityturtle, World world) { - super(entityturtle, world); - } - - @Override - protected boolean a() { - return true; - } - - @Override - protected Pathfinder a(int i) { - return new Pathfinder(new PathfinderTurtle(), i); - } - - @Override - public boolean a(BlockPosition blockposition) { - if (this.a instanceof EntityTurtle) { - EntityTurtle entityturtle = (EntityTurtle) this.a; - - if (entityturtle.ee()) { - return this.b.getType(blockposition).getBlock() == Blocks.WATER; - } - } - - return !this.b.getType(blockposition.down()).isAir(); - } - } - - static class e extends ControllerMove { - - private final EntityTurtle i; - - e(EntityTurtle entityturtle) { - super(entityturtle); - this.i = entityturtle; - } - - private void g() { - if (this.i.isInWater()) { - this.i.setMot(this.i.getMot().add(0.0D, 0.005D, 0.0D)); - if (!this.i.dX().a((IPosition) this.i.getPositionVector(), 16.0D)) { - this.i.o(Math.max(this.i.db() / 2.0F, 0.08F)); - } - - if (this.i.isBaby()) { - this.i.o(Math.max(this.i.db() / 3.0F, 0.06F)); - } - } else if (this.i.onGround) { - this.i.o(Math.max(this.i.db() / 2.0F, 0.06F)); - } - - } - - @Override - public void a() { - this.g(); - if (this.h == ControllerMove.Operation.MOVE_TO && !this.i.getNavigation().n()) { - double d0 = this.b - this.i.locX; - double d1 = this.c - this.i.locY; - double d2 = this.d - this.i.locZ; - double d3 = (double) MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); - - d1 /= d3; - float f = (float) (MathHelper.d(d2, d0) * 57.2957763671875D) - 90.0F; - - this.i.yaw = this.a(this.i.yaw, f, 90.0F); - this.i.aK = this.i.yaw; - float f1 = (float) (this.e * this.i.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue()); - - this.i.o(MathHelper.g(0.125F, this.i.db(), f1)); - this.i.setMot(this.i.getMot().add(0.0D, (double) this.i.db() * d1 * 0.1D, 0.0D)); - } else { - this.i.o(0.0F); - } - } - } - - static class c extends PathfinderGoalGotoTarget { - - private final EntityTurtle g; - - private c(EntityTurtle entityturtle, double d0) { - super(entityturtle, entityturtle.isBaby() ? 2.0D : d0, 24); - this.g = entityturtle; - this.f = -1; - } - - @Override - public boolean b() { - return !this.g.isInWater() && this.d <= 1200 && this.a(this.g.world, this.e); - } - - @Override - public boolean a() { - return this.g.isBaby() && !this.g.isInWater() ? super.a() : (!this.g.dZ() && !this.g.isInWater() && !this.g.dV() ? super.a() : false); - } - - @Override - public boolean j() { - return this.d % 160 == 0; - } - - @Override - protected boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - Block block = iworldreader.getType(blockposition).getBlock(); - - return block == Blocks.WATER; - } - } - - static class h extends PathfinderGoalRandomStroll { - - private final EntityTurtle h; - - private h(EntityTurtle entityturtle, double d0, int i) { - super(entityturtle, d0, i); - this.h = entityturtle; - } - - @Override - public boolean a() { - return !this.a.isInWater() && !this.h.dZ() && !this.h.dV() ? super.a() : false; - } - } - - static class d extends PathfinderGoalGotoTarget { - - private final EntityTurtle g; - - d(EntityTurtle entityturtle, double d0) { - super(entityturtle, d0, 16); - this.g = entityturtle; - } - - @Override - public boolean a() { - return this.g.dV() && this.g.dX().a((IPosition) this.g.getPositionVector(), 9.0D) ? super.a() : false; - } - - @Override - public boolean b() { - return super.b() && this.g.dV() && this.g.dX().a((IPosition) this.g.getPositionVector(), 9.0D); - } - - @Override - public void e() { - super.e(); - BlockPosition blockposition = new BlockPosition(this.g); - - if (!this.g.isInWater() && this.k()) { - if (this.g.bG < 1) { - this.g.setDigging(new com.destroystokyo.paper.event.entity.TurtleStartDiggingEvent((org.bukkit.entity.Turtle) this.g.getBukkitEntity(), MCUtil.toLocation(this.g.world, this.e)).callEvent()); // Paper - } else if (this.g.bG > 200) { - World world = this.g.world; - - // CraftBukkit start - // Paper start - int eggCount = this.g.random.nextInt(4) + 1; - com.destroystokyo.paper.event.entity.TurtleLayEggEvent layEggEvent = new com.destroystokyo.paper.event.entity.TurtleLayEggEvent((org.bukkit.entity.Turtle) this.g.getBukkitEntity(), MCUtil.toLocation(this.g.world, this.e.up()), eggCount); - if (layEggEvent.callEvent() && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.g, this.e.up(), Blocks.TURTLE_EGG.getBlockData().set(BlockTurtleEgg.b, layEggEvent.getEggCount())).isCancelled()) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.ENTITY_TURTLE_LAY_EGG, SoundCategory.BLOCKS, 0.3F, 0.9F + world.random.nextFloat() * 0.2F); - world.setTypeAndData(this.e.up(), (IBlockData) Blocks.TURTLE_EGG.getBlockData().set(BlockTurtleEgg.b, layEggEvent.getEggCount()), 3); - } - // CraftBukkit end - this.g.r(false); - this.g.s(false); - this.g.setLoveTicks(600); - } - - if (this.g.dW()) { - this.g.bG++; - } - } - - } - - @Override - protected boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - if (!iworldreader.isEmpty(blockposition.up())) { - return false; - } else { - Block block = iworldreader.getType(blockposition).getBlock(); - - return block == Blocks.SAND; - } - } - } - - static class a extends PathfinderGoalBreed { - - private final EntityTurtle d; - - a(EntityTurtle entityturtle, double d0) { - super(entityturtle, d0); - this.d = entityturtle; - } - - @Override - public boolean a() { - return super.a() && !this.d.dV(); - } - - @Override - protected void g() { - EntityPlayer entityplayer = this.animal.getBreedCause(); - - if (entityplayer == null && this.partner.getBreedCause() != null) { - entityplayer = this.partner.getBreedCause(); - } - - if (entityplayer != null) { - entityplayer.a(StatisticList.ANIMALS_BRED); - CriterionTriggers.o.a(entityplayer, this.animal, this.partner, (EntityAgeable) null); - } - - this.d.r(true); - this.animal.resetLove(); - this.partner.resetLove(); - Random random = this.animal.getRandom(); - - if (this.b.getGameRules().getBoolean(GameRules.DO_MOB_LOOT)) { - this.b.addEntity(new EntityExperienceOrb(this.b, this.animal.locX, this.animal.locY, this.animal.locZ, random.nextInt(7) + 1, org.bukkit.entity.ExperienceOrb.SpawnReason.BREED, entityplayer)); // Paper; - } - - } - } - - static class i extends PathfinderGoal { - - private static final PathfinderTargetCondition a = (new PathfinderTargetCondition()).a(10.0D).b().a(); - private final EntityTurtle b; - private final double c; - private EntityHuman d; - private int e; - private final Set f; - - i(EntityTurtle entityturtle, double d0, Item item) { - this.b = entityturtle; - this.c = d0; - this.f = Sets.newHashSet(new Item[]{item}); - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - if (this.e > 0) { - --this.e; - return false; - } else { - this.d = this.b.world.a(this.a, (EntityLiving) this.b); // CraftBukkit - decompile error - return this.d == null ? false : this.a(this.d.getItemInMainHand()) || this.a(this.d.getItemInOffHand()); - } - } - - private boolean a(ItemStack itemstack) { - return this.f.contains(itemstack.getItem()); - } - - @Override - public boolean b() { - return this.a(); - } - - @Override - public void d() { - this.d = null; - this.b.getNavigation().o(); - this.e = 100; - } - - @Override - public void e() { - this.b.getControllerLook().a(this.d, (float) (this.b.dA() + 20), (float) this.b.M()); - if (this.b.h((Entity) this.d) < 6.25D) { - this.b.getNavigation().o(); - } else { - this.b.getNavigation().a((Entity) this.d, this.c); - } - - } - } - - static class b extends PathfinderGoal { - - private final EntityTurtle a; - private final double b; - private boolean c; - private int d; - - b(EntityTurtle entityturtle, double d0) { - this.a = entityturtle; - this.b = d0; - } - - @Override - public boolean a() { - return this.a.isBaby() ? false : (this.a.dW() ? true : (this.a.getRandom().nextInt(700) != 0 ? false : !this.a.dY().a((IPosition) this.a.getPositionVector(), 64.0D))) && new com.destroystokyo.paper.event.entity.TurtleGoHomeEvent((org.bukkit.entity.Turtle) this.a.getBukkitEntity()).callEvent(); // Paper - } - - @Override - public void c() { - this.a.t(true); - this.c = false; - this.d = 0; - } - - @Override - public void d() { - this.a.t(false); - } - - @Override - public boolean b() { - return !this.a.dX().a((IPosition) this.a.getPositionVector(), 7.0D) && !this.c && this.d <= 600; - } - - @Override - public void e() { - BlockPosition blockposition = this.a.dX(); - boolean flag = blockposition.a((IPosition) this.a.getPositionVector(), 16.0D); - - if (flag) { - ++this.d; - } - - if (this.a.getNavigation().n()) { - Vec3D vec3d = RandomPositionGenerator.a((EntityCreature) this.a, 16, 3, new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()), 0.3141592741012573D); - - if (vec3d == null) { - vec3d = RandomPositionGenerator.a(this.a, 8, 7, new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ())); - } - - if (vec3d != null && !flag && this.a.world.getType(new BlockPosition(vec3d)).getBlock() != Blocks.WATER) { - vec3d = RandomPositionGenerator.a(this.a, 16, 5, new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ())); - } - - if (vec3d == null) { - this.c = true; - return; - } - - this.a.getNavigation().a(vec3d.x, vec3d.y, vec3d.z, this.b); - } - - } - } - - static class j extends PathfinderGoal { - - private final EntityTurtle a; - private final double b; - private boolean c; - - j(EntityTurtle entityturtle, double d0) { - this.a = entityturtle; - this.b = d0; - } - - @Override - public boolean a() { - return !this.a.dZ() && !this.a.dV() && this.a.isInWater(); - } - - @Override - public void c() { - boolean flag = true; - boolean flag1 = true; - Random random = this.a.random; - int i = random.nextInt(1025) - 512; - int j = random.nextInt(9) - 4; - int k = random.nextInt(1025) - 512; - - if ((double) j + this.a.locY > (double) (this.a.world.getSeaLevel() - 1)) { - j = 0; - } - - BlockPosition blockposition = new BlockPosition((double) i + this.a.locX, (double) j + this.a.locY, (double) k + this.a.locZ); - - this.a.h(blockposition); - this.a.u(true); - this.c = false; - } - - @Override - public void e() { - if (this.a.getNavigation().n()) { - BlockPosition blockposition = this.a.dY(); - Vec3D vec3d = RandomPositionGenerator.a((EntityCreature) this.a, 16, 3, new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()), 0.3141592741012573D); - - if (vec3d == null) { - vec3d = RandomPositionGenerator.a(this.a, 8, 7, new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ())); - } - - if (vec3d != null) { - int i = MathHelper.floor(vec3d.x); - int j = MathHelper.floor(vec3d.z); - boolean flag = true; - - if (!this.a.world.isAreaLoaded(i - 34, 0, j - 34, i + 34, 0, j + 34)) { - vec3d = null; - } - } - - if (vec3d == null) { - this.c = true; - return; - } - - this.a.getNavigation().a(vec3d.x, vec3d.y, vec3d.z, this.b); - } - - } - - @Override - public boolean b() { - return !this.a.getNavigation().n() && !this.c && !this.a.dZ() && !this.a.isInLove() && !this.a.dV(); - } - - @Override - public void d() { - this.a.u(false); - super.d(); - } - } - - static class f extends PathfinderGoalPanic { - - f(EntityTurtle entityturtle, double d0) { - super(entityturtle, d0); - } - - @Override - public boolean a() { - if (this.a.getLastDamager() == null && !this.a.isBurning()) { - return false; - } else { - BlockPosition blockposition = this.a(this.a.world, this.a, 7, 4); - - if (blockposition != null) { - this.c = (double) blockposition.getX(); - this.d = (double) blockposition.getY(); - this.e = (double) blockposition.getZ(); - return true; - } else { - return this.g(); - } - } - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityTypes.java b/src/main/java/net/minecraft/server/EntityTypes.java deleted file mode 100644 index 612b9b7e3..000000000 --- a/src/main/java/net/minecraft/server/EntityTypes.java +++ /dev/null @@ -1,447 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.DataFixUtils; -import java.util.Collections; -import java.util.Optional; -import java.util.Set; // Paper -import java.util.Map; // Paper -import java.util.UUID; -import java.util.function.Function; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class EntityTypes { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final EntityTypes AREA_EFFECT_CLOUD = a("area_effect_cloud", EntityTypes.a.a(EntityAreaEffectCloud::new, EnumCreatureType.MISC).c().a(6.0F, 0.5F)); - public static final EntityTypes ARMOR_STAND = a("armor_stand", EntityTypes.a.a(EntityArmorStand::new, EnumCreatureType.MISC).a(0.5F, 1.975F)); - public static final EntityTypes ARROW = a("arrow", EntityTypes.a.a(EntityTippedArrow::new, EnumCreatureType.MISC).a(0.5F, 0.5F)); - public static final EntityTypes BAT = a("bat", EntityTypes.a.a(EntityBat::new, EnumCreatureType.AMBIENT).a(0.5F, 0.9F)); - public static final EntityTypes BLAZE = a("blaze", EntityTypes.a.a(EntityBlaze::new, EnumCreatureType.MONSTER).c().a(0.6F, 1.8F)); - public static final EntityTypes BOAT = a("boat", EntityTypes.a.a(EntityBoat::new, EnumCreatureType.MISC).a(1.375F, 0.5625F)); - public static final EntityTypes CAT = a("cat", EntityTypes.a.a(EntityCat::new, EnumCreatureType.CREATURE).a(0.6F, 0.7F)); - public static final EntityTypes CAVE_SPIDER = a("cave_spider", EntityTypes.a.a(EntityCaveSpider::new, EnumCreatureType.MONSTER).a(0.7F, 0.5F)); - public static final EntityTypes CHICKEN = a("chicken", EntityTypes.a.a(EntityChicken::new, EnumCreatureType.CREATURE).a(0.4F, 0.7F)); - public static final EntityTypes COD = a("cod", EntityTypes.a.a(EntityCod::new, EnumCreatureType.WATER_CREATURE).a(0.5F, 0.3F)); - public static final EntityTypes COW = a("cow", EntityTypes.a.a(EntityCow::new, EnumCreatureType.CREATURE).a(0.9F, 1.4F)); - public static final EntityTypes CREEPER = a("creeper", EntityTypes.a.a(EntityCreeper::new, EnumCreatureType.MONSTER).a(0.6F, 1.7F)); - public static final EntityTypes DONKEY = a("donkey", EntityTypes.a.a(EntityHorseDonkey::new, EnumCreatureType.CREATURE).a(1.3964844F, 1.5F)); - public static final EntityTypes DOLPHIN = a("dolphin", EntityTypes.a.a(EntityDolphin::new, EnumCreatureType.WATER_CREATURE).a(0.9F, 0.6F)); - public static final EntityTypes DRAGON_FIREBALL = a("dragon_fireball", EntityTypes.a.a(EntityDragonFireball::new, EnumCreatureType.MISC).a(1.0F, 1.0F)); - public static final EntityTypes DROWNED = a("drowned", EntityTypes.a.a(EntityDrowned::new, EnumCreatureType.MONSTER).a(0.6F, 1.95F)); - public static final EntityTypes ELDER_GUARDIAN = a("elder_guardian", EntityTypes.a.a(EntityGuardianElder::new, EnumCreatureType.MONSTER).a(1.9975F, 1.9975F)); - public static final EntityTypes END_CRYSTAL = a("end_crystal", EntityTypes.a.a(EntityEnderCrystal::new, EnumCreatureType.MISC).a(2.0F, 2.0F)); - public static final EntityTypes ENDER_DRAGON = a("ender_dragon", EntityTypes.a.a(EntityEnderDragon::new, EnumCreatureType.MONSTER).c().a(16.0F, 8.0F)); - public static final EntityTypes ENDERMAN = a("enderman", EntityTypes.a.a(EntityEnderman::new, EnumCreatureType.MONSTER).a(0.6F, 2.9F)); - public static final EntityTypes ENDERMITE = a("endermite", EntityTypes.a.a(EntityEndermite::new, EnumCreatureType.MONSTER).a(0.4F, 0.3F)); - public static final EntityTypes EVOKER_FANGS = a("evoker_fangs", EntityTypes.a.a(EntityEvokerFangs::new, EnumCreatureType.MISC).a(0.5F, 0.8F)); - public static final EntityTypes EVOKER = a("evoker", EntityTypes.a.a(EntityEvoker::new, EnumCreatureType.MONSTER).a(0.6F, 1.95F)); - public static final EntityTypes EXPERIENCE_ORB = a("experience_orb", EntityTypes.a.a(EntityExperienceOrb::new, EnumCreatureType.MISC).a(0.5F, 0.5F)); - public static final EntityTypes EYE_OF_ENDER = a("eye_of_ender", EntityTypes.a.a(EntityEnderSignal::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes FALLING_BLOCK = a("falling_block", EntityTypes.a.a(EntityFallingBlock::new, EnumCreatureType.MISC).a(0.98F, 0.98F)); - public static final EntityTypes FIREWORK_ROCKET = a("firework_rocket", EntityTypes.a.a(EntityFireworks::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes FOX = a("fox", EntityTypes.a.a(EntityFox::new, EnumCreatureType.CREATURE).a(0.6F, 0.7F)); - public static final EntityTypes GHAST = a("ghast", EntityTypes.a.a(EntityGhast::new, EnumCreatureType.MONSTER).c().a(4.0F, 4.0F)); - public static final EntityTypes GIANT = a("giant", EntityTypes.a.a(EntityGiantZombie::new, EnumCreatureType.MONSTER).a(3.6F, 12.0F)); - public static final EntityTypes GUARDIAN = a("guardian", EntityTypes.a.a(EntityGuardian::new, EnumCreatureType.MONSTER).a(0.85F, 0.85F)); - public static final EntityTypes HORSE = a("horse", EntityTypes.a.a(EntityHorse::new, EnumCreatureType.CREATURE).a(1.3964844F, 1.6F)); - public static final EntityTypes HUSK = a("husk", EntityTypes.a.a(EntityZombieHusk::new, EnumCreatureType.MONSTER).a(0.6F, 1.95F)); - public static final EntityTypes ILLUSIONER = a("illusioner", EntityTypes.a.a(EntityIllagerIllusioner::new, EnumCreatureType.MONSTER).a(0.6F, 1.95F)); - public static final EntityTypes ITEM = a("item", EntityTypes.a.a(EntityItem::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes ITEM_FRAME = a("item_frame", EntityTypes.a.a(EntityItemFrame::new, EnumCreatureType.MISC).a(0.5F, 0.5F)); - public static final EntityTypes FIREBALL = a("fireball", EntityTypes.a.a(EntityLargeFireball::new, EnumCreatureType.MISC).a(1.0F, 1.0F)); - public static final EntityTypes LEASH_KNOT = a("leash_knot", EntityTypes.a.a(EntityLeash::new, EnumCreatureType.MISC).b().a(0.5F, 0.5F)); - public static final EntityTypes LLAMA = a("llama", EntityTypes.a.a(EntityLlama::new, EnumCreatureType.CREATURE).a(0.9F, 1.87F)); - public static final EntityTypes LLAMA_SPIT = a("llama_spit", EntityTypes.a.a(EntityLlamaSpit::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes MAGMA_CUBE = a("magma_cube", EntityTypes.a.a(EntityMagmaCube::new, EnumCreatureType.MONSTER).c().a(2.04F, 2.04F)); - public static final EntityTypes MINECART = a("minecart", EntityTypes.a.a(EntityMinecartRideable::new, EnumCreatureType.MISC).a(0.98F, 0.7F)); - public static final EntityTypes CHEST_MINECART = a("chest_minecart", EntityTypes.a.a(EntityMinecartChest::new, EnumCreatureType.MISC).a(0.98F, 0.7F)); - public static final EntityTypes COMMAND_BLOCK_MINECART = a("command_block_minecart", EntityTypes.a.a(EntityMinecartCommandBlock::new, EnumCreatureType.MISC).a(0.98F, 0.7F)); - public static final EntityTypes FURNACE_MINECART = a("furnace_minecart", EntityTypes.a.a(EntityMinecartFurnace::new, EnumCreatureType.MISC).a(0.98F, 0.7F)); - public static final EntityTypes HOPPER_MINECART = a("hopper_minecart", EntityTypes.a.a(EntityMinecartHopper::new, EnumCreatureType.MISC).a(0.98F, 0.7F)); - public static final EntityTypes SPAWNER_MINECART = a("spawner_minecart", EntityTypes.a.a(EntityMinecartMobSpawner::new, EnumCreatureType.MISC).a(0.98F, 0.7F)); - public static final EntityTypes TNT_MINECART = a("tnt_minecart", EntityTypes.a.a(EntityMinecartTNT::new, EnumCreatureType.MISC).a(0.98F, 0.7F)); - public static final EntityTypes MULE = a("mule", EntityTypes.a.a(EntityHorseMule::new, EnumCreatureType.CREATURE).a(1.3964844F, 1.6F)); - public static final EntityTypes MOOSHROOM = a("mooshroom", EntityTypes.a.a(EntityMushroomCow::new, EnumCreatureType.CREATURE).a(0.9F, 1.4F)); - public static final EntityTypes OCELOT = a("ocelot", EntityTypes.a.a(EntityOcelot::new, EnumCreatureType.CREATURE).a(0.6F, 0.7F)); - public static final EntityTypes PAINTING = a("painting", EntityTypes.a.a(EntityPainting::new, EnumCreatureType.MISC).a(0.5F, 0.5F)); - public static final EntityTypes PANDA = a("panda", EntityTypes.a.a(EntityPanda::new, EnumCreatureType.CREATURE).a(1.3F, 1.25F)); - public static final EntityTypes PARROT = a("parrot", EntityTypes.a.a(EntityParrot::new, EnumCreatureType.CREATURE).a(0.5F, 0.9F)); - public static final EntityTypes PIG = a("pig", EntityTypes.a.a(EntityPig::new, EnumCreatureType.CREATURE).a(0.9F, 0.9F)); - public static final EntityTypes PUFFERFISH = a("pufferfish", EntityTypes.a.a(EntityPufferFish::new, EnumCreatureType.WATER_CREATURE).a(0.7F, 0.7F)); - public static final EntityTypes ZOMBIE_PIGMAN = a("zombie_pigman", EntityTypes.a.a(EntityPigZombie::new, EnumCreatureType.MONSTER).c().a(0.6F, 1.95F)); - public static final EntityTypes POLAR_BEAR = a("polar_bear", EntityTypes.a.a(EntityPolarBear::new, EnumCreatureType.CREATURE).a(1.4F, 1.4F)); - public static final EntityTypes TNT = a("tnt", EntityTypes.a.a(EntityTNTPrimed::new, EnumCreatureType.MISC).c().a(0.98F, 0.98F)); - public static final EntityTypes RABBIT = a("rabbit", EntityTypes.a.a(EntityRabbit::new, EnumCreatureType.CREATURE).a(0.4F, 0.5F)); - public static final EntityTypes SALMON = a("salmon", EntityTypes.a.a(EntitySalmon::new, EnumCreatureType.WATER_CREATURE).a(0.7F, 0.4F)); - public static final EntityTypes SHEEP = a("sheep", EntityTypes.a.a(EntitySheep::new, EnumCreatureType.CREATURE).a(0.9F, 1.3F)); - public static final EntityTypes SHULKER = a("shulker", EntityTypes.a.a(EntityShulker::new, EnumCreatureType.MONSTER).c().d().a(1.0F, 1.0F)); - public static final EntityTypes SHULKER_BULLET = a("shulker_bullet", EntityTypes.a.a(EntityShulkerBullet::new, EnumCreatureType.MISC).a(0.3125F, 0.3125F)); - public static final EntityTypes SILVERFISH = a("silverfish", EntityTypes.a.a(EntitySilverfish::new, EnumCreatureType.MONSTER).a(0.4F, 0.3F)); - public static final EntityTypes SKELETON = a("skeleton", EntityTypes.a.a(EntitySkeleton::new, EnumCreatureType.MONSTER).a(0.6F, 1.99F)); - public static final EntityTypes SKELETON_HORSE = a("skeleton_horse", EntityTypes.a.a(EntityHorseSkeleton::new, EnumCreatureType.CREATURE).a(1.3964844F, 1.6F)); - public static final EntityTypes SLIME = a("slime", EntityTypes.a.a(EntitySlime::new, EnumCreatureType.MONSTER).a(2.04F, 2.04F)); - public static final EntityTypes SMALL_FIREBALL = a("small_fireball", EntityTypes.a.a(EntitySmallFireball::new, EnumCreatureType.MISC).a(0.3125F, 0.3125F)); - public static final EntityTypes SNOW_GOLEM = a("snow_golem", EntityTypes.a.a(EntitySnowman::new, EnumCreatureType.MISC).a(0.7F, 1.9F)); - public static final EntityTypes SNOWBALL = a("snowball", EntityTypes.a.a(EntitySnowball::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes SPECTRAL_ARROW = a("spectral_arrow", EntityTypes.a.a(EntitySpectralArrow::new, EnumCreatureType.MISC).a(0.5F, 0.5F)); - public static final EntityTypes SPIDER = a("spider", EntityTypes.a.a(EntitySpider::new, EnumCreatureType.MONSTER).a(1.4F, 0.9F)); - public static final EntityTypes SQUID = a("squid", EntityTypes.a.a(EntitySquid::new, EnumCreatureType.WATER_CREATURE).a(0.8F, 0.8F)); - public static final EntityTypes STRAY = a("stray", EntityTypes.a.a(EntitySkeletonStray::new, EnumCreatureType.MONSTER).a(0.6F, 1.99F)); - public static final EntityTypes TRADER_LLAMA = a("trader_llama", EntityTypes.a.a(EntityLlamaTrader::new, EnumCreatureType.CREATURE).a(0.9F, 1.87F)); - public static final EntityTypes TROPICAL_FISH = a("tropical_fish", EntityTypes.a.a(EntityTropicalFish::new, EnumCreatureType.WATER_CREATURE).a(0.5F, 0.4F)); - public static final EntityTypes TURTLE = a("turtle", EntityTypes.a.a(EntityTurtle::new, EnumCreatureType.CREATURE).a(1.2F, 0.4F)); - public static final EntityTypes EGG = a("egg", EntityTypes.a.a(EntityEgg::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes ENDER_PEARL = a("ender_pearl", EntityTypes.a.a(EntityEnderPearl::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes EXPERIENCE_BOTTLE = a("experience_bottle", EntityTypes.a.a(EntityThrownExpBottle::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes POTION = a("potion", EntityTypes.a.a(EntityPotion::new, EnumCreatureType.MISC).a(0.25F, 0.25F)); - public static final EntityTypes TRIDENT = a("trident", EntityTypes.a.a(EntityThrownTrident::new, EnumCreatureType.MISC).a(0.5F, 0.5F)); - public static final EntityTypes VEX = a("vex", EntityTypes.a.a(EntityVex::new, EnumCreatureType.MONSTER).c().a(0.4F, 0.8F)); - public static final EntityTypes VILLAGER = a("villager", EntityTypes.a.a(EntityVillager::new, EnumCreatureType.MISC).a(0.6F, 1.95F)); - public static final EntityTypes IRON_GOLEM = a("iron_golem", EntityTypes.a.a(EntityIronGolem::new, EnumCreatureType.MISC).a(1.4F, 2.7F)); - public static final EntityTypes VINDICATOR = a("vindicator", EntityTypes.a.a(EntityVindicator::new, EnumCreatureType.MONSTER).a(0.6F, 1.95F)); - public static final EntityTypes PILLAGER = a("pillager", EntityTypes.a.a(EntityPillager::new, EnumCreatureType.MONSTER).d().a(0.6F, 1.95F)); - public static final EntityTypes WANDERING_TRADER = a("wandering_trader", EntityTypes.a.a(EntityVillagerTrader::new, EnumCreatureType.CREATURE).a(0.6F, 1.95F)); - public static final EntityTypes WITCH = a("witch", EntityTypes.a.a(EntityWitch::new, EnumCreatureType.MONSTER).a(0.6F, 1.95F)); - public static final EntityTypes WITHER = a("wither", EntityTypes.a.a(EntityWither::new, EnumCreatureType.MONSTER).c().a(0.9F, 3.5F)); - public static final EntityTypes WITHER_SKELETON = a("wither_skeleton", EntityTypes.a.a(EntitySkeletonWither::new, EnumCreatureType.MONSTER).c().a(0.7F, 2.4F)); - public static final EntityTypes WITHER_SKULL = a("wither_skull", EntityTypes.a.a(EntityWitherSkull::new, EnumCreatureType.MISC).a(0.3125F, 0.3125F)); - public static final EntityTypes WOLF = a("wolf", EntityTypes.a.a(EntityWolf::new, EnumCreatureType.CREATURE).a(0.6F, 0.85F)); - public static final EntityTypes ZOMBIE = a("zombie", EntityTypes.a.a(EntityZombie::new, EnumCreatureType.MONSTER).a(0.6F, 1.95F)); - public static final EntityTypes ZOMBIE_HORSE = a("zombie_horse", EntityTypes.a.a(EntityHorseZombie::new, EnumCreatureType.CREATURE).a(1.3964844F, 1.6F)); - public static final EntityTypes ZOMBIE_VILLAGER = a("zombie_villager", EntityTypes.a.a(EntityZombieVillager::new, EnumCreatureType.MONSTER).a(0.6F, 1.95F)); - public static final EntityTypes PHANTOM = a("phantom", EntityTypes.a.a(EntityPhantom::new, EnumCreatureType.MONSTER).a(0.9F, 0.5F)); - public static final EntityTypes RAVAGER = a("ravager", EntityTypes.a.a(EntityRavager::new, EnumCreatureType.MONSTER).a(1.95F, 2.2F)); - public static final EntityTypes LIGHTNING_BOLT = a("lightning_bolt", EntityTypes.a.a(EnumCreatureType.MISC).b().a(0.0F, 0.0F)); - public static final EntityTypes PLAYER = a("player", EntityTypes.a.a(EnumCreatureType.MISC).b().a().a(0.6F, 1.8F)); - public static final EntityTypes FISHING_BOBBER = a("fishing_bobber", EntityTypes.a.a(EnumCreatureType.MISC).b().a().a(0.25F, 0.25F)); - private final EntityTypes.b aZ; - private final EnumCreatureType ba; - private final boolean bb; - private final boolean bc; - private final boolean bd; - private final boolean be; - @Nullable - private String bf; - @Nullable - private IChatBaseComponent bg; - @Nullable - private MinecraftKey bh; - private final EntitySize bi; - - private static EntityTypes a(String s, EntityTypes.a entitytypes_a) { // CraftBukkit - decompile error - return (EntityTypes) IRegistry.a((IRegistry) IRegistry.ENTITY_TYPE, s, (Object) entitytypes_a.a(s)); - } - - public static MinecraftKey getName(EntityTypes entitytypes) { - return IRegistry.ENTITY_TYPE.getKey(entitytypes); - } - - public static Optional> a(String s) { - return IRegistry.ENTITY_TYPE.getOptional(MinecraftKey.a(s)); - } - - public EntityTypes(EntityTypes.b entitytypes_b, EnumCreatureType enumcreaturetype, boolean flag, boolean flag1, boolean flag2, boolean flag3, EntitySize entitysize) { - this.aZ = entitytypes_b; - this.ba = enumcreaturetype; - this.be = flag3; - this.bb = flag; - this.bc = flag1; - this.bd = flag2; - this.bi = entitysize; - } - - @Nullable - public Entity spawnCreature(World world, @Nullable ItemStack itemstack, @Nullable EntityHuman entityhuman, BlockPosition blockposition, EnumMobSpawn enummobspawn, boolean flag, boolean flag1) { - return this.spawnCreature(world, itemstack == null ? null : itemstack.getTag(), itemstack != null && itemstack.hasName() ? itemstack.getName() : null, entityhuman, blockposition, enummobspawn, flag, flag1); - } - - @Nullable - public T spawnCreature(World world, @Nullable NBTTagCompound nbttagcompound, @Nullable IChatBaseComponent ichatbasecomponent, @Nullable EntityHuman entityhuman, BlockPosition blockposition, EnumMobSpawn enummobspawn, boolean flag, boolean flag1) { - // CraftBukkit start - return this.spawnCreature(world, nbttagcompound, ichatbasecomponent, entityhuman, blockposition, enummobspawn, flag, flag1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SPAWNER_EGG); - } - - @Nullable - public T spawnCreature(World world, @Nullable NBTTagCompound nbttagcompound, @Nullable IChatBaseComponent ichatbasecomponent, @Nullable EntityHuman entityhuman, BlockPosition blockposition, EnumMobSpawn enummobspawn, boolean flag, boolean flag1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { - T t0 = this.b(world, nbttagcompound, ichatbasecomponent, entityhuman, blockposition, enummobspawn, flag, flag1); - - return world.addEntity(t0, spawnReason) ? t0 : null; // Don't return an entity when CreatureSpawnEvent is canceled - // CraftBukkit end - } - - @Nullable - public T b(World world, @Nullable NBTTagCompound nbttagcompound, @Nullable IChatBaseComponent ichatbasecomponent, @Nullable EntityHuman entityhuman, BlockPosition blockposition, EnumMobSpawn enummobspawn, boolean flag, boolean flag1) { - T t0 = this.a(world); - - if (t0 == null) { - return null; - } else { - double d0; - - if (flag) { - t0.setPosition((double) blockposition.getX() + 0.5D, (double) (blockposition.getY() + 1), (double) blockposition.getZ() + 0.5D); - d0 = a(world, blockposition, flag1, t0.getBoundingBox()); - } else { - d0 = 0.0D; - } - - t0.setPositionRotation((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + d0, (double) blockposition.getZ() + 0.5D, MathHelper.g(world.random.nextFloat() * 360.0F), 0.0F); - if (t0 instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) t0; - - entityinsentient.aM = entityinsentient.yaw; - entityinsentient.aK = entityinsentient.yaw; - entityinsentient.prepare(world, world.getDamageScaler(new BlockPosition(entityinsentient)), enummobspawn, (GroupDataEntity) null, nbttagcompound); - entityinsentient.B(); - } - - if (ichatbasecomponent != null && t0 instanceof EntityLiving) { - t0.setCustomName(ichatbasecomponent); - } - - a(world, entityhuman, t0, nbttagcompound); - return t0; - } - } - - protected static double a(IWorldReader iworldreader, BlockPosition blockposition, boolean flag, AxisAlignedBB axisalignedbb) { - AxisAlignedBB axisalignedbb1 = new AxisAlignedBB(blockposition); - - if (flag) { - axisalignedbb1 = axisalignedbb1.b(0.0D, -1.0D, 0.0D); - } - - Stream stream = iworldreader.c((Entity) null, axisalignedbb1, Collections.emptySet()); - - return 1.0D + VoxelShapes.a(EnumDirection.EnumAxis.Y, axisalignedbb, stream, flag ? -2.0D : -1.0D); - } - - public static void a(World world, @Nullable EntityHuman entityhuman, @Nullable Entity entity, @Nullable NBTTagCompound nbttagcompound) { - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("EntityTag", 10)) { - MinecraftServer minecraftserver = world.getMinecraftServer(); - - if (minecraftserver != null && entity != null) { - if (world.isClientSide || !entity.bT() || entityhuman != null && minecraftserver.getPlayerList().isOp(entityhuman.getProfile())) { - NBTTagCompound nbttagcompound1 = entity.save(new NBTTagCompound()); - UUID uuid = entity.getUniqueID(); - - nbttagcompound1.a(nbttagcompound.getCompound("EntityTag")); - entity.a(uuid); - entity.f(nbttagcompound1); - } - } - } - } - - public boolean isPersistable() { return a(); } // Paper - OBFHELPER - public boolean a() { - return this.bb; - } - - public boolean b() { - return this.bc; - } - - public boolean c() { - return this.bd; - } - - public boolean d() { - return this.be; - } - - public EnumCreatureType getEnumCreatureType() { return this.e(); } // Paper - OBFHELPER - public EnumCreatureType e() { - return this.ba; - } - - public String f() { - if (this.bf == null) { - this.bf = SystemUtils.a("entity", IRegistry.ENTITY_TYPE.getKey(this)); - } - - return this.bf; - } - - public IChatBaseComponent g() { - if (this.bg == null) { - this.bg = new ChatMessage(this.f(), new Object[0]); - } - - return this.bg; - } - - public MinecraftKey h() { - if (this.bh == null) { - MinecraftKey minecraftkey = IRegistry.ENTITY_TYPE.getKey(this); - - this.bh = new MinecraftKey(minecraftkey.getNamespace(), "entities/" + minecraftkey.getKey()); - } - - return this.bh; - } - - public float i() { - return this.bi.width; - } - - public float j() { - return this.bi.height; - } - - public T create(World world) { return this.a(world); } // Paper - OBFHELPER - @Nullable public T a(World world) { // Paper - OBFHELPER - return this.aZ.create(this, world); - } - - public static Optional a(NBTTagCompound nbttagcompound, World world) { - return SystemUtils.a(a(nbttagcompound).map((entitytypes) -> { - return entitytypes.a(world); - }), (entity) -> { - entity.f(nbttagcompound); - }, () -> { - EntityTypes.LOGGER.warn("Skipping Entity with id {}", nbttagcompound.getString("id")); - }); - } - - public AxisAlignedBB a(double d0, double d1, double d2) { - float f = this.i() / 2.0F; - - return new AxisAlignedBB(d0 - (double) f, d1, d2 - (double) f, d0 + (double) f, d1 + (double) this.j(), d2 + (double) f); - } - - public EntitySize k() { - return this.bi; - } - - public static Optional> a(NBTTagCompound nbttagcompound) { - return IRegistry.ENTITY_TYPE.getOptional(new MinecraftKey(nbttagcompound.getString("id"))); - } - - @Nullable - public static Entity a(NBTTagCompound nbttagcompound, World world, Function function) { - return (Entity) b(nbttagcompound, world).map(function).map((entity) -> { - if (nbttagcompound.hasKeyOfType("Passengers", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("Passengers", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - Entity entity1 = a(nbttaglist.getCompound(i), world, function); - - if (entity1 != null) { - entity1.a(entity, true); - } - } - } - - return entity; - }).orElse(null); // CraftBukkit - decompile error - } - - private static Optional b(NBTTagCompound nbttagcompound, World world) { - try { - return a(nbttagcompound, world); - } catch (RuntimeException runtimeexception) { - EntityTypes.LOGGER.warn("Exception loading entity: ", runtimeexception); - return Optional.empty(); - } - } - - public int getChunkRange() { - return this == EntityTypes.PLAYER ? 32 : (this == EntityTypes.END_CRYSTAL ? 16 : (this != EntityTypes.ENDER_DRAGON && this != EntityTypes.TNT && this != EntityTypes.FALLING_BLOCK && this != EntityTypes.ITEM_FRAME && this != EntityTypes.LEASH_KNOT && this != EntityTypes.PAINTING && this != EntityTypes.ARMOR_STAND && this != EntityTypes.EXPERIENCE_ORB && this != EntityTypes.AREA_EFFECT_CLOUD && this != EntityTypes.EVOKER_FANGS ? (this != EntityTypes.FISHING_BOBBER && this != EntityTypes.ARROW && this != EntityTypes.SPECTRAL_ARROW && this != EntityTypes.TRIDENT && this != EntityTypes.SMALL_FIREBALL && this != EntityTypes.DRAGON_FIREBALL && this != EntityTypes.FIREBALL && this != EntityTypes.WITHER_SKULL && this != EntityTypes.SNOWBALL && this != EntityTypes.LLAMA_SPIT && this != EntityTypes.ENDER_PEARL && this != EntityTypes.EYE_OF_ENDER && this != EntityTypes.EGG && this != EntityTypes.POTION && this != EntityTypes.EXPERIENCE_BOTTLE && this != EntityTypes.FIREWORK_ROCKET && this != EntityTypes.ITEM ? 5 : 4) : 10)); - } - - public int getUpdateInterval() { - // CraftBukkit - SPIGOT-3729: track area effect clouds - return this != EntityTypes.PLAYER && this != EntityTypes.EVOKER_FANGS ? (this == EntityTypes.EYE_OF_ENDER ? 4 : (this == EntityTypes.FISHING_BOBBER ? 5 : (this != EntityTypes.SMALL_FIREBALL && this != EntityTypes.DRAGON_FIREBALL && this != EntityTypes.FIREBALL && this != EntityTypes.WITHER_SKULL && this != EntityTypes.SNOWBALL && this != EntityTypes.LLAMA_SPIT && this != EntityTypes.ENDER_PEARL && this != EntityTypes.EGG && this != EntityTypes.POTION && this != EntityTypes.EXPERIENCE_BOTTLE && this != EntityTypes.FIREWORK_ROCKET && this != EntityTypes.TNT ? (this != EntityTypes.ARROW && this != EntityTypes.SPECTRAL_ARROW && this != EntityTypes.TRIDENT && this != EntityTypes.ITEM && this != EntityTypes.FALLING_BLOCK && this != EntityTypes.EXPERIENCE_ORB ? (this != EntityTypes.ITEM_FRAME && this != EntityTypes.LEASH_KNOT && this != EntityTypes.PAINTING && this != EntityTypes.END_CRYSTAL ? 3 : Integer.MAX_VALUE) : 20) : 10))) : 2; - } - - public boolean isDeltaTracking() { - return this != EntityTypes.PLAYER && this != EntityTypes.LLAMA_SPIT && this != EntityTypes.WITHER && this != EntityTypes.BAT && this != EntityTypes.ITEM_FRAME && this != EntityTypes.LEASH_KNOT && this != EntityTypes.PAINTING && this != EntityTypes.END_CRYSTAL && this != EntityTypes.EVOKER_FANGS; - } - - public boolean a(Tag> tag) { - return tag.isTagged(this); - } - - public interface b { - - T create(EntityTypes entitytypes, World world); - } - - public static class a { - - private final EntityTypes.b a; - private final EnumCreatureType b; - private boolean c = true; - private boolean d = true; - private boolean e; - private boolean f; - private EntitySize g = EntitySize.b(0.6F, 1.8F); - - private a(EntityTypes.b entitytypes_b, EnumCreatureType enumcreaturetype) { - this.a = entitytypes_b; - this.b = enumcreaturetype; - this.f = enumcreaturetype == EnumCreatureType.CREATURE || enumcreaturetype == EnumCreatureType.MISC; - } - - public static EntityTypes.a a(EntityTypes.b entitytypes_b, EnumCreatureType enumcreaturetype) { // CraftBukkit - decompile error - return new EntityTypes.a<>(entitytypes_b, enumcreaturetype); - } - - public static EntityTypes.a a(EnumCreatureType enumcreaturetype) { - return new EntityTypes.a<>((entitytypes, world) -> { - return null; - }, enumcreaturetype); - } - - public EntityTypes.a a(float f, float f1) { - this.g = EntitySize.b(f, f1); - return this; - } - - public EntityTypes.a a() { - this.d = false; - return this; - } - - public EntityTypes.a b() { - this.c = false; - return this; - } - - public EntityTypes.a c() { - this.e = true; - return this; - } - - public EntityTypes.a d() { - this.f = true; - return this; - } - - public EntityTypes a(String s) { - if (this.c) { - try { - DataConverterRegistry.a().getSchema(DataFixUtils.makeKey(SharedConstants.a().getWorldVersion())).getChoiceType(DataConverterTypes.o, s); - } catch (IllegalStateException illegalstateexception) { - if (SharedConstants.b) { - throw illegalstateexception; - } - - EntityTypes.LOGGER.warn("No data fixer registered for entity {}", s); - } - } - - return new EntityTypes<>(this.a, this.b, this.c, this.d, this.e, this.f, this.g); - } - } - - // Paper start - public static Set getEntityNameList() { - return IRegistry.ENTITY_TYPE.keySet(); - } - // Paper end -} diff --git a/src/main/java/net/minecraft/server/EntityVex.java b/src/main/java/net/minecraft/server/EntityVex.java deleted file mode 100644 index 51c05376d..000000000 --- a/src/main/java/net/minecraft/server/EntityVex.java +++ /dev/null @@ -1,324 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import javax.annotation.Nullable; -import org.bukkit.event.entity.EntityTargetEvent; - -public class EntityVex extends EntityMonster { - - protected static final DataWatcherObject b = DataWatcher.a(EntityVex.class, DataWatcherRegistry.a); - private EntityInsentient c; - @Nullable - private BlockPosition d; - private boolean bz; - private int bA; - - public EntityVex(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.moveController = new EntityVex.c(this); - this.f = 3; - } - - @Override - public void move(EnumMoveType enummovetype, Vec3D vec3d) { - super.move(enummovetype, vec3d); - this.checkBlockCollisions(); - } - - @Override - public void tick() { - this.noclip = true; - super.tick(); - this.noclip = false; - this.setNoGravity(true); - if (this.bz && --this.bA <= 0) { - this.bA = 20; - this.damageEntity(DamageSource.STARVE, 1.0F); - } - - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(4, new EntityVex.a()); - this.goalSelector.a(8, new EntityVex.d()); - this.goalSelector.a(9, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 3.0F, 1.0F)); - this.goalSelector.a(10, new PathfinderGoalLookAtPlayer(this, EntityInsentient.class, 8.0F)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[]{EntityRaider.class})).a(new Class[0])); // CraftBukkit - decompile error - this.targetSelector.a(2, new EntityVex.b(this)); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(14.0D); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(4.0D); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityVex.b, (byte) 0); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKey("BoundX")) { - this.d = new BlockPosition(nbttagcompound.getInt("BoundX"), nbttagcompound.getInt("BoundY"), nbttagcompound.getInt("BoundZ")); - } - - if (nbttagcompound.hasKey("LifeTicks")) { - this.a(nbttagcompound.getInt("LifeTicks")); - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - if (this.d != null) { - nbttagcompound.setInt("BoundX", this.d.getX()); - nbttagcompound.setInt("BoundY", this.d.getY()); - nbttagcompound.setInt("BoundZ", this.d.getZ()); - } - - if (this.bz) { - nbttagcompound.setInt("LifeTicks", this.bA); - } - - } - - public EntityInsentient getOwner() { return l(); } // Paper - OBFHELPER - public EntityInsentient l() { - return this.c; - } - - @Nullable - public BlockPosition dV() { - return this.d; - } - - public void g(@Nullable BlockPosition blockposition) { - this.d = blockposition; - } - - private boolean b(int i) { - byte b0 = (Byte) this.datawatcher.get(EntityVex.b); - - return (b0 & i) != 0; - } - - private void a(int i, boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityVex.b); - int j; - - if (flag) { - j = b0 | i; - } else { - j = b0 & ~i; - } - - this.datawatcher.set(EntityVex.b, (byte) (j & 255)); - } - - public boolean isCharging() { - return this.b(1); - } - - public void setCharging(boolean flag) { - this.a(1, flag); - } - - public void setOwner(EntityInsentient entityinsentient) { a(entityinsentient); } // Paper - OBFHELPER - public void a(EntityInsentient entityinsentient) { - this.c = entityinsentient; - } - - public void a(int i) { - this.bz = true; - this.bA = i; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_VEX_AMBIENT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_VEX_DEATH; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_VEX_HURT; - } - - @Override - public float aF() { - return 1.0F; - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.a(difficultydamagescaler); - this.b(difficultydamagescaler); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.IRON_SWORD)); - this.a(EnumItemSlot.MAINHAND, 0.0F); - } - - class b extends PathfinderGoalTarget { - - private final PathfinderTargetCondition b = (new PathfinderTargetCondition()).c().e(); - - public b(EntityCreature entitycreature) { - super(entitycreature, false); - } - - @Override - public boolean a() { - return EntityVex.this.c != null && EntityVex.this.c.getGoalTarget() != null && this.a(EntityVex.this.c.getGoalTarget(), this.b); - } - - @Override - public void c() { - EntityVex.this.setGoalTarget(EntityVex.this.c.getGoalTarget(), EntityTargetEvent.TargetReason.OWNER_ATTACKED_TARGET, true); // CraftBukkit - super.c(); - } - } - - class d extends PathfinderGoal { - - public d() { - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - return !EntityVex.this.getControllerMove().b() && EntityVex.this.random.nextInt(7) == 0; - } - - @Override - public boolean b() { - return false; - } - - @Override - public void e() { - BlockPosition blockposition = EntityVex.this.dV(); - - if (blockposition == null) { - blockposition = new BlockPosition(EntityVex.this); - } - - for (int i = 0; i < 3; ++i) { - BlockPosition blockposition1 = blockposition.b(EntityVex.this.random.nextInt(15) - 7, EntityVex.this.random.nextInt(11) - 5, EntityVex.this.random.nextInt(15) - 7); - - if (EntityVex.this.world.isEmpty(blockposition1)) { - EntityVex.this.moveController.a((double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 0.5D, (double) blockposition1.getZ() + 0.5D, 0.25D); - if (EntityVex.this.getGoalTarget() == null) { - EntityVex.this.getControllerLook().a((double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 0.5D, (double) blockposition1.getZ() + 0.5D, 180.0F, 20.0F); - } - break; - } - } - - } - } - - class a extends PathfinderGoal { - - public a() { - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - return EntityVex.this.getGoalTarget() != null && !EntityVex.this.getControllerMove().b() && EntityVex.this.random.nextInt(7) == 0 ? EntityVex.this.h((Entity) EntityVex.this.getGoalTarget()) > 4.0D : false; - } - - @Override - public boolean b() { - return EntityVex.this.getControllerMove().b() && EntityVex.this.isCharging() && EntityVex.this.getGoalTarget() != null && EntityVex.this.getGoalTarget().isAlive(); - } - - @Override - public void c() { - EntityLiving entityliving = EntityVex.this.getGoalTarget(); - Vec3D vec3d = entityliving.j(1.0F); - - EntityVex.this.moveController.a(vec3d.x, vec3d.y, vec3d.z, 1.0D); - EntityVex.this.setCharging(true); - EntityVex.this.a(SoundEffects.ENTITY_VEX_CHARGE, 1.0F, 1.0F); - } - - @Override - public void d() { - EntityVex.this.setCharging(false); - } - - @Override - public void e() { - EntityLiving entityliving = EntityVex.this.getGoalTarget(); - - if (EntityVex.this.getBoundingBox().c(entityliving.getBoundingBox())) { - EntityVex.this.C(entityliving); - EntityVex.this.setCharging(false); - } else { - double d0 = EntityVex.this.h((Entity) entityliving); - - if (d0 < 9.0D) { - Vec3D vec3d = entityliving.j(1.0F); - - EntityVex.this.moveController.a(vec3d.x, vec3d.y, vec3d.z, 1.0D); - } - } - - } - } - - class c extends ControllerMove { - - public c(EntityVex entityvex) { - super(entityvex); - } - - @Override - public void a() { - if (this.h == ControllerMove.Operation.MOVE_TO) { - Vec3D vec3d = new Vec3D(this.b - EntityVex.this.locX, this.c - EntityVex.this.locY, this.d - EntityVex.this.locZ); - double d0 = vec3d.f(); - - if (d0 < EntityVex.this.getBoundingBox().a()) { - this.h = ControllerMove.Operation.WAIT; - EntityVex.this.setMot(EntityVex.this.getMot().a(0.5D)); - } else { - EntityVex.this.setMot(EntityVex.this.getMot().e(vec3d.a(this.e * 0.05D / d0))); - if (EntityVex.this.getGoalTarget() == null) { - Vec3D vec3d1 = EntityVex.this.getMot(); - - EntityVex.this.yaw = -((float) MathHelper.d(vec3d1.x, vec3d1.z)) * 57.295776F; - EntityVex.this.aK = EntityVex.this.yaw; - } else { - double d1 = EntityVex.this.getGoalTarget().locX - EntityVex.this.locX; - double d2 = EntityVex.this.getGoalTarget().locZ - EntityVex.this.locZ; - - EntityVex.this.yaw = -((float) MathHelper.d(d1, d2)) * 57.295776F; - EntityVex.this.aK = EntityVex.this.yaw; - } - } - - } - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityVillager.java b/src/main/java/net/minecraft/server/EntityVillager.java deleted file mode 100644 index 7f747fac9..000000000 --- a/src/main/java/net/minecraft/server/EntityVillager.java +++ /dev/null @@ -1,985 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.types.DynamicOps; -import com.mojang.datafixers.util.Pair; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.Map.Entry; -import java.util.function.BiPredicate; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.entity.CraftVillager; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.craftbukkit.inventory.CraftMerchantRecipe; -import org.bukkit.entity.Villager; -import org.bukkit.event.entity.EntityTransformEvent; -import org.bukkit.event.entity.VillagerAcquireTradeEvent; -import org.bukkit.event.entity.VillagerReplenishTradeEvent; -// CraftBukkit end - -public class EntityVillager extends EntityVillagerAbstract implements ReputationHandler, VillagerDataHolder { - - private static final DataWatcherObject bC = DataWatcher.a(EntityVillager.class, DataWatcherRegistry.q); - public static final Map bA = ImmutableMap.of(Items.BREAD, 4, Items.POTATO, 1, Items.CARROT, 1, Items.BEETROOT, 1); - private static final Set bD = ImmutableSet.of(Items.BREAD, Items.POTATO, Items.CARROT, Items.WHEAT, Items.WHEAT_SEEDS, Items.BEETROOT, new Item[]{Items.BEETROOT_SEEDS}); - private int bE; - private boolean bF; - @Nullable - private EntityHuman bG; - private byte bI; - private final Reputation bJ; - private long bK; - private long bL; - private int bM; - private long bN; - private int bO; - private long bP; - private static final ImmutableList> bQ = ImmutableList.of(MemoryModuleType.HOME, MemoryModuleType.JOB_SITE, MemoryModuleType.MEETING_POINT, MemoryModuleType.MOBS, MemoryModuleType.VISIBLE_MOBS, MemoryModuleType.VISIBLE_VILLAGER_BABIES, MemoryModuleType.NEAREST_PLAYERS, MemoryModuleType.NEAREST_VISIBLE_PLAYER, MemoryModuleType.WALK_TARGET, MemoryModuleType.LOOK_TARGET, MemoryModuleType.INTERACTION_TARGET, MemoryModuleType.BREED_TARGET, new MemoryModuleType[]{MemoryModuleType.PATH, MemoryModuleType.INTERACTABLE_DOORS, MemoryModuleType.OPENED_DOORS, MemoryModuleType.NEAREST_BED, MemoryModuleType.HURT_BY, MemoryModuleType.HURT_BY_ENTITY, MemoryModuleType.NEAREST_HOSTILE, MemoryModuleType.SECONDARY_JOB_SITE, MemoryModuleType.HIDING_PLACE, MemoryModuleType.HEARD_BELL_TIME, MemoryModuleType.CANT_REACH_WALK_TARGET_SINCE, MemoryModuleType.LAST_SLEPT, MemoryModuleType.LAST_WORKED_AT_POI, MemoryModuleType.GOLEM_LAST_SEEN_TIME}); - private static final ImmutableList>> bR = ImmutableList.of(SensorType.b, SensorType.c, SensorType.d, SensorType.e, SensorType.f, SensorType.g, SensorType.h, SensorType.i, SensorType.j); - public static final Map, BiPredicate> bB = ImmutableMap.of(MemoryModuleType.HOME, (entityvillager, villageplacetype) -> { - return villageplacetype == VillagePlaceType.q; - }, MemoryModuleType.JOB_SITE, (entityvillager, villageplacetype) -> { - return entityvillager.getVillagerData().getProfession().b() == villageplacetype; - }, MemoryModuleType.MEETING_POINT, (entityvillager, villageplacetype) -> { - return villageplacetype == VillagePlaceType.r; - }); - - public EntityVillager(EntityTypes entitytypes, World world) { - this(entitytypes, world, VillagerType.PLAINS); - } - - public EntityVillager(EntityTypes entitytypes, World world, VillagerType villagertype) { - super(entitytypes, world); - this.bJ = new Reputation(); - ((Navigation) this.getNavigation()).a(true); - this.getNavigation().d(true); - this.setCanPickupLoot(true); - this.setVillagerData(this.getVillagerData().withType(villagertype).withProfession(VillagerProfession.NONE)); - this.br = this.a(new Dynamic(DynamicOpsNBT.a, new NBTTagCompound())); - } - - @Override - public BehaviorController getBehaviorController() { - return (BehaviorController) super.getBehaviorController(); // CraftBukkit - decompile error - } - - @Override - protected BehaviorController a(Dynamic dynamic) { - BehaviorController behaviorcontroller = new BehaviorController<>(EntityVillager.bQ, EntityVillager.bR, dynamic); - - this.a(behaviorcontroller); - return behaviorcontroller; - } - - public void a(WorldServer worldserver) { - BehaviorController behaviorcontroller = this.getBehaviorController(); - - behaviorcontroller.b(worldserver, this); - this.br = behaviorcontroller.f(); - this.a(this.getBehaviorController()); - } - - private void a(BehaviorController behaviorcontroller) { - VillagerProfession villagerprofession = this.getVillagerData().getProfession(); - float f = (float) this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue(); - - if (this.isBaby()) { - behaviorcontroller.setSchedule(Schedule.VILLAGER_BABY); - behaviorcontroller.a(Activity.PLAY, Behaviors.a(f)); - } else { - behaviorcontroller.setSchedule(Schedule.VILLAGER_DEFAULT); - behaviorcontroller.a(Activity.WORK, Behaviors.b(villagerprofession, f), (Set) ImmutableSet.of(Pair.of(MemoryModuleType.JOB_SITE, MemoryStatus.VALUE_PRESENT))); - } - - behaviorcontroller.a(Activity.CORE, Behaviors.a(villagerprofession, f)); - behaviorcontroller.a(Activity.MEET, Behaviors.d(villagerprofession, f), (Set) ImmutableSet.of(Pair.of(MemoryModuleType.MEETING_POINT, MemoryStatus.VALUE_PRESENT))); - behaviorcontroller.a(Activity.REST, Behaviors.c(villagerprofession, f)); - behaviorcontroller.a(Activity.IDLE, Behaviors.e(villagerprofession, f)); - behaviorcontroller.a(Activity.PANIC, Behaviors.f(villagerprofession, f)); - behaviorcontroller.a(Activity.PRE_RAID, Behaviors.g(villagerprofession, f)); - behaviorcontroller.a(Activity.RAID, Behaviors.h(villagerprofession, f)); - behaviorcontroller.a(Activity.HIDE, Behaviors.i(villagerprofession, f)); - behaviorcontroller.a((Set) ImmutableSet.of(Activity.CORE)); - behaviorcontroller.b(Activity.IDLE); - behaviorcontroller.a(Activity.IDLE); - behaviorcontroller.a(this.world.getDayTime(), this.world.getTime()); - } - - @Override - protected void l() { - super.l(); - if (this.world instanceof WorldServer) { - this.a((WorldServer) this.world); - } - - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.5D); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(48.0D); - } - - // Spigot Start - @Override - public void inactiveTick() { - // SPIGOT-3874, SPIGOT-3894, SPIGOT-3846, SPIGOT-5286 :( - if (world.spigotConfig.tickInactiveVillagers && this.df()) { - this.mobTick(); - } - super.inactiveTick(); - } - // Spigot End - - @Override - protected void mobTick() { - this.world.getMethodProfiler().enter("brain"); - this.getBehaviorController().a((WorldServer) this.world, this); // CraftBukkit - decompile error - this.world.getMethodProfiler().exit(); - if (!this.dY() && this.bE > 0) { - --this.bE; - if (this.bE <= 0) { - if (this.bF) { - this.populateTrades(); - this.bF = false; - } - - this.addEffect(new MobEffect(MobEffects.REGENERATION, 200, 0), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.VILLAGER_TRADE); // CraftBukkit - } - } - - if (this.bG != null && this.world instanceof WorldServer) { - ((WorldServer) this.world).a(ReputationEvent.e, (Entity) this.bG, (ReputationHandler) this); - this.world.broadcastEntityEffect(this, (byte) 14); - this.bG = null; - } - - if (!this.isNoAI() && this.random.nextInt(100) == 0) { - Raid raid = ((WorldServer) this.world).c_(new BlockPosition(this)); - - if (raid != null && raid.v() && !raid.a()) { - this.world.broadcastEntityEffect(this, (byte) 42); - } - } - - if (this.getVillagerData().getProfession() == VillagerProfession.NONE && this.dY()) { - this.ed(); - } - - super.mobTick(); - } - - @Override - public void tick() { - super.tick(); - if (this.dV() > 0) { - this.r(this.dV() - 1); - } - - this.eF(); - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - boolean flag = itemstack.getItem() == Items.NAME_TAG; - - if (flag) { - itemstack.a(entityhuman, (EntityLiving) this, enumhand); - return true; - } else if (itemstack.getItem() != Items.VILLAGER_SPAWN_EGG && this.isAlive() && !this.dY() && !this.isSleeping()) { - if (this.isBaby()) { - this.et(); - return super.a(entityhuman, enumhand); - } else { - boolean flag1 = this.getOffers().isEmpty(); - - if (enumhand == EnumHand.MAIN_HAND) { - if (flag1 && !this.world.isClientSide) { - this.et(); - } - - entityhuman.a(StatisticList.TALKED_TO_VILLAGER); - } - - if (flag1) { - return super.a(entityhuman, enumhand); - } else { - if (!this.world.isClientSide && !this.trades.isEmpty()) { - this.g(entityhuman); - } - - return true; - } - } - } else { - return super.a(entityhuman, enumhand); - } - } - - private void et() { - this.r(40); - if (!this.world.e()) { - this.a(SoundEffects.ENTITY_VILLAGER_NO, this.getSoundVolume(), this.cV()); - } - - } - - private void g(EntityHuman entityhuman) { - this.h(entityhuman); - this.setTradingPlayer(entityhuman); - this.openTrade(entityhuman, this.getScoreboardDisplayName(), this.getVillagerData().getLevel()); - } - - @Override - public void setTradingPlayer(@Nullable EntityHuman entityhuman) { - boolean flag = this.getTrader() != null && entityhuman == null; - - super.setTradingPlayer(entityhuman); - if (flag) { - this.ed(); - } - - } - - @Override - protected void ed() { - super.ed(); - this.eu(); - } - - private void eu() { - Iterator iterator = this.getOffers().iterator(); - - while (iterator.hasNext()) { - MerchantRecipe merchantrecipe = (MerchantRecipe) iterator.next(); - - merchantrecipe.setSpecialPrice(); - } - - } - - @Override - public boolean ei() { - return true; - } - - public void ej() { - this.ey(); - Iterator iterator = this.getOffers().iterator(); - - while (iterator.hasNext()) { - MerchantRecipe merchantrecipe = (MerchantRecipe) iterator.next(); - - merchantrecipe.resetUses(); - } - - if (this.getVillagerData().getProfession() == VillagerProfession.FARMER) { - this.eE(); - } - - this.bN = this.world.getTime(); - ++this.bO; - } - - private boolean ev() { - Iterator iterator = this.getOffers().iterator(); - - MerchantRecipe merchantrecipe; - - do { - if (!iterator.hasNext()) { - return false; - } - - merchantrecipe = (MerchantRecipe) iterator.next(); - } while (!merchantrecipe.isFullyUsed()); - - return true; - } - - private boolean ew() { - return this.bO < 2 && this.world.getTime() > this.bN + 2400L; - } - - public boolean ek() { - long i = this.bN + 12000L; - boolean flag = this.world.getTime() > i; - long j = this.world.getDayTime(); - - if (this.bP > 0L) { - long k = this.bP / 24000L; - long l = j / 24000L; - - flag |= l > k; - } - - this.bP = j; - if (flag) { - this.eH(); - } - - return this.ew() && this.ev(); - } - - private void ex() { - int i = 2 - this.bO; - - if (i > 0) { - Iterator iterator = this.getOffers().iterator(); - - while (iterator.hasNext()) { - MerchantRecipe merchantrecipe = (MerchantRecipe) iterator.next(); - - merchantrecipe.resetUses(); - } - } - - for (int j = 0; j < i; ++j) { - this.ey(); - } - - } - - private void ey() { - Iterator iterator = this.getOffers().iterator(); - - while (iterator.hasNext()) { - MerchantRecipe merchantrecipe = (MerchantRecipe) iterator.next(); - - merchantrecipe.e(); - } - - } - - private void h(EntityHuman entityhuman) { - int i = this.f(entityhuman); - - if (i != 0) { - Iterator iterator = this.getOffers().iterator(); - - while (iterator.hasNext()) { - MerchantRecipe merchantrecipe = (MerchantRecipe) iterator.next(); - - // CraftBukkit start - int bonus = -MathHelper.d((float) i * merchantrecipe.getPriceMultiplier()); - VillagerReplenishTradeEvent event = new VillagerReplenishTradeEvent((Villager) this.getBukkitEntity(), merchantrecipe.asBukkit(), bonus); - Bukkit.getPluginManager().callEvent(event); - if (!event.isCancelled()) { - merchantrecipe.increaseSpecialPrice(event.getBonus()); - } - // CraftBukkit end - } - } - - if (entityhuman.hasEffect(MobEffects.HERO_OF_THE_VILLAGE)) { - MobEffect mobeffect = entityhuman.getEffect(MobEffects.HERO_OF_THE_VILLAGE); - int j = mobeffect.getAmplifier(); - Iterator iterator1 = this.getOffers().iterator(); - - while (iterator1.hasNext()) { - MerchantRecipe merchantrecipe1 = (MerchantRecipe) iterator1.next(); - double d0 = 0.3D + 0.0625D * (double) j; - int k = (int) Math.floor(d0 * (double) merchantrecipe1.a().getCount()); - - merchantrecipe1.increaseSpecialPrice(-Math.max(k, 1)); - } - } - - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityVillager.bC, new VillagerData(VillagerType.PLAINS, VillagerProfession.NONE, 1)); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.set("VillagerData", (NBTBase) this.getVillagerData().a(DynamicOpsNBT.a)); - nbttagcompound.setByte("FoodLevel", this.bI); - nbttagcompound.set("Gossips", (NBTBase) this.bJ.a((DynamicOps) DynamicOpsNBT.a).getValue()); - nbttagcompound.setInt("Xp", this.bM); - nbttagcompound.setLong("LastRestock", this.bN); - nbttagcompound.setLong("LastGossipDecay", this.bL); - nbttagcompound.setInt("RestocksToday", this.bO); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("VillagerData", 10)) { - this.setVillagerData(new VillagerData(new Dynamic(DynamicOpsNBT.a, nbttagcompound.get("VillagerData")))); - } - - if (nbttagcompound.hasKeyOfType("Offers", 10)) { - this.trades = new MerchantRecipeList(nbttagcompound.getCompound("Offers")); - } - - if (nbttagcompound.hasKeyOfType("FoodLevel", 1)) { - this.bI = nbttagcompound.getByte("FoodLevel"); - } - - NBTTagList nbttaglist = nbttagcompound.getList("Gossips", 10); - - this.bJ.a(new Dynamic(DynamicOpsNBT.a, nbttaglist)); - if (nbttagcompound.hasKeyOfType("Xp", 3)) { - this.bM = nbttagcompound.getInt("Xp"); - } - - this.bN = nbttagcompound.getLong("LastRestock"); - this.bL = nbttagcompound.getLong("LastGossipDecay"); - this.setCanPickupLoot(true); - this.a((WorldServer) this.world); - this.bO = nbttagcompound.getInt("RestocksToday"); - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return false; - } - - @Nullable - @Override - protected SoundEffect getSoundAmbient() { - return this.isSleeping() ? null : (this.dY() ? SoundEffects.ENTITY_VILLAGER_TRADE : SoundEffects.ENTITY_VILLAGER_AMBIENT); - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_VILLAGER_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_VILLAGER_DEATH; - } - - public void el() { - SoundEffect soundeffect = this.getVillagerData().getProfession().b().e(); - - if (soundeffect != null) { - this.a(soundeffect, this.getSoundVolume(), this.cV()); - } - - } - - public void setVillagerData(VillagerData villagerdata) { - VillagerData villagerdata1 = this.getVillagerData(); - - if (villagerdata1.getProfession() != villagerdata.getProfession()) { - this.trades = null; - } - - this.datawatcher.set(EntityVillager.bC, villagerdata); - } - - @Override - public VillagerData getVillagerData() { - return (VillagerData) this.datawatcher.get(EntityVillager.bC); - } - - @Override - protected void b(MerchantRecipe merchantrecipe) { - int i = 3 + this.random.nextInt(4); - - this.bM += merchantrecipe.getXp(); - this.bG = this.getTrader(); - if (this.eB()) { - this.bE = 40; - this.bF = true; - i += 5; - } - - if (merchantrecipe.isRewardExp()) { - this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY + 0.5D, this.locZ, i, org.bukkit.entity.ExperienceOrb.SpawnReason.VILLAGER_TRADE, this.getTrader(), this)); // Paper - } - - } - - @Override - public void setLastDamager(@Nullable EntityLiving entityliving) { - if (entityliving != null && this.world instanceof WorldServer) { - ((WorldServer) this.world).a(ReputationEvent.c, (Entity) entityliving, (ReputationHandler) this); - if (this.isAlive() && entityliving instanceof EntityHuman) { - this.world.broadcastEntityEffect(this, (byte) 13); - } - } - - super.setLastDamager(entityliving); - } - - @Override - public void die(DamageSource damagesource) { - Entity entity = damagesource.getEntity(); - - if (entity != null) { - this.a(entity); - } - - this.a(MemoryModuleType.HOME); - this.a(MemoryModuleType.JOB_SITE); - this.a(MemoryModuleType.MEETING_POINT); - super.die(damagesource); - } - - private void a(Entity entity) { - if (this.world instanceof WorldServer) { - Optional> optional = this.br.getMemory(MemoryModuleType.VISIBLE_MOBS); - - if (optional.isPresent()) { - WorldServer worldserver = (WorldServer) this.world; - - ((List) optional.get()).stream().filter((entityliving) -> { - return entityliving instanceof ReputationHandler; - }).forEach((entityliving) -> { - worldserver.a(ReputationEvent.d, entity, (ReputationHandler) entityliving); - }); - } - } - } - - public void a(MemoryModuleType memorymoduletype) { - if (this.world instanceof WorldServer) { - MinecraftServer minecraftserver = ((WorldServer) this.world).getMinecraftServer(); - - this.br.getMemory(memorymoduletype).ifPresent((globalpos) -> { - WorldServer worldserver = minecraftserver.getWorldServer(globalpos.getDimensionManager()); - VillagePlace villageplace = worldserver.B(); - Optional optional = villageplace.c(globalpos.getBlockPosition()); - BiPredicate bipredicate = (BiPredicate) EntityVillager.bB.get(memorymoduletype); - - if (optional.isPresent() && bipredicate.test(this, optional.get())) { - villageplace.b(globalpos.getBlockPosition()); - PacketDebug.c(worldserver, globalpos.getBlockPosition()); - } - - }); - } - } - - public boolean canBreed() { - return this.bI + this.eD() >= 12 && this.getAge() == 0; - } - - private boolean ez() { - return this.bI < 12; - } - - private void eA() { - if (this.ez() && this.eD() != 0) { - for (int i = 0; i < this.getInventory().getSize(); ++i) { - ItemStack itemstack = this.getInventory().getItem(i); - - if (!itemstack.isEmpty()) { - Integer integer = (Integer) EntityVillager.bA.get(itemstack.getItem()); - - if (integer != null) { - int j = itemstack.getCount(); - - for (int k = j; k > 0; --k) { - this.bI = (byte) (this.bI + integer); - this.getInventory().splitStack(i, 1); - if (!this.ez()) { - return; - } - } - } - } - } - - } - } - - public int f(EntityHuman entityhuman) { - return this.bJ.a(entityhuman.getUniqueID(), (reputationtype) -> { - return true; - }); - } - - private void u(int i) { - this.bI = (byte) (this.bI - i); - } - - public void eo() { - this.eA(); - this.u(12); - } - - public void b(MerchantRecipeList merchantrecipelist) { - this.trades = merchantrecipelist; - } - - private boolean eB() { - int i = this.getVillagerData().getLevel(); - - return VillagerData.d(i) && this.bM >= VillagerData.c(i); - } - - public void populateTrades() { - this.setVillagerData(this.getVillagerData().withLevel(this.getVillagerData().getLevel() + 1)); - this.eh(); - } - - @Override - public IChatBaseComponent getScoreboardDisplayName() { - ScoreboardTeamBase scoreboardteambase = this.getScoreboardTeam(); - IChatBaseComponent ichatbasecomponent = this.getCustomName(); - - if (ichatbasecomponent != null) { - return ScoreboardTeam.a(scoreboardteambase, ichatbasecomponent).a((chatmodifier) -> { - chatmodifier.setChatHoverable(this.bK()).setInsertion(this.getUniqueIDString()); - }); - } else { - VillagerProfession villagerprofession = this.getVillagerData().getProfession(); - IChatBaseComponent ichatbasecomponent1 = (new ChatMessage(this.getEntityType().f() + '.' + IRegistry.VILLAGER_PROFESSION.getKey(villagerprofession).getKey(), new Object[0])).a((chatmodifier) -> { - chatmodifier.setChatHoverable(this.bK()).setInsertion(this.getUniqueIDString()); - }); - - if (scoreboardteambase != null) { - ichatbasecomponent1.a(scoreboardteambase.getColor()); - } - - return ichatbasecomponent1; - } - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - if (enummobspawn == EnumMobSpawn.BREEDING) { - this.setVillagerData(this.getVillagerData().withProfession(VillagerProfession.NONE)); - } - - if (enummobspawn == EnumMobSpawn.COMMAND || enummobspawn == EnumMobSpawn.SPAWN_EGG || enummobspawn == EnumMobSpawn.SPAWNER) { - this.setVillagerData(this.getVillagerData().withType(VillagerType.a(generatoraccess.getBiome(new BlockPosition(this))))); - } - - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - @Override - public EntityVillager createChild(EntityAgeable entityageable) { - double d0 = this.random.nextDouble(); - VillagerType villagertype; - - if (d0 < 0.5D) { - villagertype = VillagerType.a(this.world.getBiome(new BlockPosition(this))); - } else if (d0 < 0.75D) { - villagertype = this.getVillagerData().getType(); - } else { - villagertype = ((EntityVillager) entityageable).getVillagerData().getType(); - } - - EntityVillager entityvillager = new EntityVillager(EntityTypes.VILLAGER, this.world, villagertype); - - entityvillager.prepare(this.world, this.world.getDamageScaler(new BlockPosition(entityvillager)), EnumMobSpawn.BREEDING, (GroupDataEntity) null, (NBTTagCompound) null); - return entityvillager; - } - - @Override - public void onLightningStrike(EntityLightning entitylightning) { - EntityWitch entitywitch = (EntityWitch) EntityTypes.WITCH.a(this.world); - - // Paper start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityZapEvent(this, entitylightning, entitywitch).isCancelled()) { - return; - } - // Paper end - - entitywitch.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, this.pitch); - entitywitch.prepare(this.world, this.world.getDamageScaler(new BlockPosition(entitywitch)), EnumMobSpawn.CONVERSION, (GroupDataEntity) null, (NBTTagCompound) null); - entitywitch.setNoAI(this.isNoAI()); - if (this.hasCustomName()) { - entitywitch.setCustomName(this.getCustomName()); - entitywitch.setCustomNameVisible(this.getCustomNameVisible()); - } - - // CraftBukkit start - if (CraftEventFactory.callEntityTransformEvent(this, entitywitch, EntityTransformEvent.TransformReason.LIGHTNING).isCancelled()) { - return; - } - if (!new com.destroystokyo.paper.event.entity.EntityTransformedEvent(this.getBukkitEntity(), entitywitch.getBukkitEntity(), com.destroystokyo.paper.event.entity.EntityTransformedEvent.TransformedReason.LIGHTNING).callEvent()) return; // Paper - this.world.addEntity(entitywitch, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.LIGHTNING); - // CraftBukkit end - this.die(); - } - - @Override - protected void a(EntityItem entityitem) { - ItemStack itemstack = entityitem.getItemStack(); - Item item = itemstack.getItem(); - - if (this.b(item)) { - InventorySubcontainer inventorysubcontainer = this.getInventory(); - boolean flag = false; - - ItemStack itemstack1; - int i; - - for (i = 0; i < inventorysubcontainer.getSize(); ++i) { - itemstack1 = inventorysubcontainer.getItem(i); - if (itemstack1.isEmpty() || itemstack1.getItem() == item && itemstack1.getCount() < itemstack1.getMaxStackSize()) { - flag = true; - break; - } - } - - if (!flag) { - return; - } - - i = inventorysubcontainer.a(item); - if (i == 256) { - return; - } - - if (i > 256) { - inventorysubcontainer.a(item, i - 256); - return; - } - - this.receive(entityitem, itemstack.getCount()); - itemstack1 = inventorysubcontainer.a(itemstack); - if (itemstack1.isEmpty()) { - entityitem.die(); - } else { - itemstack.setCount(itemstack1.getCount()); - } - } - - } - - public boolean b(Item item) { - return EntityVillager.bD.contains(item) || this.getVillagerData().getProfession().c().contains(item); - } - - public boolean ep() { - return this.eD() >= 24; - } - - public boolean eq() { - return this.eD() < 12; - } - - private int eD() { - InventorySubcontainer inventorysubcontainer = this.getInventory(); - - return EntityVillager.bA.entrySet().stream().mapToInt((entry) -> { - return inventorysubcontainer.a((Item) entry.getKey()) * (Integer) entry.getValue(); - }).sum(); - } - - private void eE() { - InventorySubcontainer inventorysubcontainer = this.getInventory(); - int i = inventorysubcontainer.a(Items.WHEAT); - int j = i / 3; - - if (j != 0) { - int k = j * 3; - - inventorysubcontainer.a(Items.WHEAT, k); - ItemStack itemstack = inventorysubcontainer.a(new ItemStack(Items.BREAD, j)); - - if (!itemstack.isEmpty()) { - this.a(itemstack, 0.5F); - } - - } - } - - public boolean er() { - InventorySubcontainer inventorysubcontainer = this.getInventory(); - - return inventorysubcontainer.a((Set) ImmutableSet.of(Items.WHEAT_SEEDS, Items.POTATO, Items.CARROT, Items.BEETROOT_SEEDS)); - } - - @Override - protected void eh() { - VillagerData villagerdata = this.getVillagerData(); - Int2ObjectMap int2objectmap = (Int2ObjectMap) VillagerTrades.a.get(villagerdata.getProfession()); - - if (int2objectmap != null && !int2objectmap.isEmpty()) { - VillagerTrades.IMerchantRecipeOption[] avillagertrades_imerchantrecipeoption = (VillagerTrades.IMerchantRecipeOption[]) int2objectmap.get(villagerdata.getLevel()); - - if (avillagertrades_imerchantrecipeoption != null) { - MerchantRecipeList merchantrecipelist = this.getOffers(); - - this.a(merchantrecipelist, avillagertrades_imerchantrecipeoption, 2); - } - } - } - - public void a(EntityVillager entityvillager, long i) { - if ((i < this.bK || i >= this.bK + 1200L) && (i < entityvillager.bK || i >= entityvillager.bK + 1200L)) { - this.bJ.a(entityvillager.bJ, this.random, 10); - this.bK = i; - entityvillager.bK = i; - this.a(i, 5); - } - } - - private void eF() { - long i = this.world.getTime(); - - if (this.bL == 0L) { - this.bL = i; - } else if (i >= this.bL + 24000L) { - this.bJ.b(); - this.bL = i; - } - } - - public void a(long i, int j) { - if (this.a(i)) { - AxisAlignedBB axisalignedbb = this.getBoundingBox().grow(10.0D, 10.0D, 10.0D); - List list = this.world.a(EntityVillager.class, axisalignedbb); - List list1 = (List) list.stream().filter((entityvillager) -> { - return entityvillager.a(i); - }).limit(5L).collect(Collectors.toList()); - - if (list1.size() >= j) { - EntityIronGolem entityirongolem = this.eG(); - - if (entityirongolem != null) { - list.forEach((entityvillager) -> { - entityvillager.b(i); - }); - } - } - } - } - - private void b(long i) { - this.br.setMemory(MemoryModuleType.GOLEM_LAST_SEEN_TIME, i); // CraftBukkit - decompile error - } - - private boolean c(long i) { - Optional optional = this.br.getMemory(MemoryModuleType.GOLEM_LAST_SEEN_TIME); - - if (!optional.isPresent()) { - return false; - } else { - Long olong = (Long) optional.get(); - - return i - olong <= 600L; - } - } - - public boolean a(long i) { - VillagerData villagerdata = this.getVillagerData(); - - return villagerdata.getProfession() != VillagerProfession.NONE && villagerdata.getProfession() != VillagerProfession.NITWIT ? (!this.d(this.world.getTime()) ? false : !this.c(i)) : false; - } - - @Nullable - private EntityIronGolem eG() { - BlockPosition blockposition = new BlockPosition(this); - int i = 0; - - while (i < 10) { - double d0 = (double) (this.world.random.nextInt(16) - 8); - double d1 = (double) (this.world.random.nextInt(16) - 8); - double d2 = 6.0D; - int j = 0; - - while (true) { - if (j >= -12) { - BlockPosition blockposition1 = blockposition.a(d0, d2 + (double) j, d1); - - if (!this.world.getType(blockposition1).isAir() && !this.world.getType(blockposition1).getMaterial().isLiquid() || !this.world.getType(blockposition1.down()).getMaterial().f()) { - --j; - continue; - } - - d2 += (double) j; - } - - BlockPosition blockposition2 = blockposition.a(d0, d2, d1); - EntityIronGolem entityirongolem = (EntityIronGolem) EntityTypes.IRON_GOLEM.b(this.world, (NBTTagCompound) null, (IChatBaseComponent) null, (EntityHuman) null, blockposition2, EnumMobSpawn.MOB_SUMMONED, false, false); - - if (entityirongolem != null) { - if (entityirongolem.a((GeneratorAccess) this.world, EnumMobSpawn.MOB_SUMMONED) && entityirongolem.a((IWorldReader) this.world)) { - this.world.addEntity(entityirongolem, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.VILLAGE_DEFENSE); // CraftBukkit - return entityirongolem; - } - - entityirongolem.die(); - } - - ++i; - break; - } - } - - return null; - } - - @Override - public void a(ReputationEvent reputationevent, Entity entity) { - if (reputationevent == ReputationEvent.a) { - this.bJ.a(entity.getUniqueID(), ReputationType.MAJOR_POSITIVE, 20); - this.bJ.a(entity.getUniqueID(), ReputationType.MINOR_POSITIVE, 25); - } else if (reputationevent == ReputationEvent.e) { - this.bJ.a(entity.getUniqueID(), ReputationType.TRADING, 2); - } else if (reputationevent == ReputationEvent.c) { - this.bJ.a(entity.getUniqueID(), ReputationType.MINOR_NEGATIVE, 25); - } else if (reputationevent == ReputationEvent.d) { - this.bJ.a(entity.getUniqueID(), ReputationType.MAJOR_NEGATIVE, 25); - } - - } - - @Override - public int getExperience() { - return this.bM; - } - - public void setExperience(int i) { - this.bM = i; - } - - private void eH() { - this.ex(); - this.bO = 0; - } - - public Reputation es() { - return this.bJ; - } - - public void a(NBTBase nbtbase) { - this.bJ.a(new Dynamic(DynamicOpsNBT.a, nbtbase)); - } - - @Override - protected void K() { - super.K(); - PacketDebug.a(this); - } - - @Override - public void e(BlockPosition blockposition) { - super.e(blockposition); - this.br.setMemory(MemoryModuleType.LAST_SLEPT, MinecraftSerializableLong.a(this.world.getTime())); // CraftBukkit - decompile error - } - - private boolean d(long i) { - Optional optional = this.br.getMemory(MemoryModuleType.LAST_SLEPT); - Optional optional1 = this.br.getMemory(MemoryModuleType.LAST_WORKED_AT_POI); - - return optional.isPresent() && optional1.isPresent() ? i - ((MinecraftSerializableLong) optional.get()).a() < 24000L && i - ((MinecraftSerializableLong) optional1.get()).a() < 36000L : false; - } -} diff --git a/src/main/java/net/minecraft/server/EntityVillagerAbstract.java b/src/main/java/net/minecraft/server/EntityVillagerAbstract.java deleted file mode 100644 index f161ccb97..000000000 --- a/src/main/java/net/minecraft/server/EntityVillagerAbstract.java +++ /dev/null @@ -1,253 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Sets; -import java.util.Iterator; -import java.util.Set; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.inventory.CraftMerchant; -import org.bukkit.craftbukkit.inventory.CraftMerchantRecipe; -import org.bukkit.entity.AbstractVillager; -import org.bukkit.event.entity.VillagerAcquireTradeEvent; -// CraftBukkit end - -public abstract class EntityVillagerAbstract extends EntityAgeable implements NPC, IMerchant { - - // CraftBukkit start - private CraftMerchant craftMerchant; - - @Override - public CraftMerchant getCraftMerchant() { - return (craftMerchant == null) ? craftMerchant = new CraftMerchant(this) : craftMerchant; - } - // CraftBukkit end - private static final DataWatcherObject bA = DataWatcher.a(EntityVillagerAbstract.class, DataWatcherRegistry.b); - @Nullable - private EntityHuman tradingPlayer; - @Nullable - protected MerchantRecipeList trades; - private final InventorySubcontainer inventory = new InventorySubcontainer(8, (org.bukkit.craftbukkit.entity.CraftAbstractVillager) this.getBukkitEntity()); // CraftBukkit add argument - - public EntityVillagerAbstract(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public int dV() { - return (Integer) this.datawatcher.get(EntityVillagerAbstract.bA); - } - - public void r(int i) { - this.datawatcher.set(EntityVillagerAbstract.bA, i); - } - - @Override - public int getExperience() { - return 0; - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return this.isBaby() ? 0.81F : 1.62F; - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityVillagerAbstract.bA, 0); - } - - @Override - public void setTradingPlayer(@Nullable EntityHuman entityhuman) { - this.tradingPlayer = entityhuman; - } - - @Nullable - @Override - public EntityHuman getTrader() { - return this.tradingPlayer; - } - - public boolean dY() { - return this.tradingPlayer != null; - } - - @Override - public MerchantRecipeList getOffers() { - if (this.trades == null) { - this.trades = new MerchantRecipeList(); - this.eh(); - } - - return this.trades; - } - - @Override - public void s(int i) {} - - @Override - public void a(MerchantRecipe merchantrecipe) { - merchantrecipe.increaseUses(); - this.e = -this.A(); - this.b(merchantrecipe); - if (this.tradingPlayer instanceof EntityPlayer) { - CriterionTriggers.s.a((EntityPlayer) this.tradingPlayer, this, merchantrecipe.getSellingItem()); - } - - } - - protected abstract void b(MerchantRecipe merchantrecipe); - - @Override - public boolean ea() { - return true; - } - - @Override - public void i(ItemStack itemstack) { - if (!this.world.isClientSide && this.e > -this.A() + 20) { - this.e = -this.A(); - this.a(this.r(!itemstack.isEmpty()), this.getSoundVolume(), this.cV()); - } - - } - - @Override - public SoundEffect eb() { - return SoundEffects.ENTITY_VILLAGER_YES; - } - - protected SoundEffect r(boolean flag) { - return flag ? SoundEffects.ENTITY_VILLAGER_YES : SoundEffects.ENTITY_VILLAGER_NO; - } - - public void ec() { - this.a(SoundEffects.ENTITY_VILLAGER_CELEBRATE, this.getSoundVolume(), this.cV()); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - MerchantRecipeList merchantrecipelist = this.getOffers(); - - if (!merchantrecipelist.isEmpty()) { - nbttagcompound.set("Offers", merchantrecipelist.a()); - } - - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.inventory.getSize(); ++i) { - ItemStack itemstack = this.inventory.getItem(i); - - if (!itemstack.isEmpty()) { - nbttaglist.add(itemstack.save(new NBTTagCompound())); - } - } - - nbttagcompound.set("Inventory", nbttaglist); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("Offers", 10)) { - this.trades = new MerchantRecipeList(nbttagcompound.getCompound("Offers")); - } - - NBTTagList nbttaglist = nbttagcompound.getList("Inventory", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - ItemStack itemstack = ItemStack.a(nbttaglist.getCompound(i)); - - if (!itemstack.isEmpty()) { - this.inventory.a(itemstack); - } - } - - } - - @Nullable - @Override - public Entity a(DimensionManager dimensionmanager) { - this.ed(); - return super.a(dimensionmanager); - } - - protected void ed() { - this.setTradingPlayer((EntityHuman) null); - } - - @Override - public void die(DamageSource damagesource) { - super.die(damagesource); - this.ed(); - } - - @Override - public boolean a(EntityHuman entityhuman) { - return false; - } - - public InventorySubcontainer getInventory() { - return this.inventory; - } - - @Override - public boolean a_(int i, ItemStack itemstack) { - if (super.a_(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; - } - } - } - - @Override - public World getWorld() { - return this.world; - } - - protected abstract void eh(); - - protected void a(MerchantRecipeList merchantrecipelist, VillagerTrades.IMerchantRecipeOption[] avillagertrades_imerchantrecipeoption, int i) { - Set set = Sets.newHashSet(); - - if (avillagertrades_imerchantrecipeoption.length > i) { - while (set.size() < i) { - set.add(this.random.nextInt(avillagertrades_imerchantrecipeoption.length)); - } - } else { - for (int j = 0; j < avillagertrades_imerchantrecipeoption.length; ++j) { - set.add(j); - } - } - - Iterator iterator = set.iterator(); - - while (iterator.hasNext()) { - Integer integer = (Integer) iterator.next(); - VillagerTrades.IMerchantRecipeOption villagertrades_imerchantrecipeoption = avillagertrades_imerchantrecipeoption[integer]; - MerchantRecipe merchantrecipe = villagertrades_imerchantrecipeoption.a(this, this.random); - - if (merchantrecipe != null) { - // CraftBukkit start - VillagerAcquireTradeEvent event = new VillagerAcquireTradeEvent((AbstractVillager) getBukkitEntity(), merchantrecipe.asBukkit()); - // Suppress during worldgen - if (this.valid) { - Bukkit.getPluginManager().callEvent(event); - } - if (!event.isCancelled()) { - merchantrecipelist.add(CraftMerchantRecipe.fromBukkit(event.getRecipe()).toMinecraft()); - } - // CraftBukkit end - } - } - - } -} diff --git a/src/main/java/net/minecraft/server/EntityVillagerTrader.java b/src/main/java/net/minecraft/server/EntityVillagerTrader.java deleted file mode 100644 index a24e7127d..000000000 --- a/src/main/java/net/minecraft/server/EntityVillagerTrader.java +++ /dev/null @@ -1,267 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.inventory.CraftMerchantRecipe; -import org.bukkit.entity.AbstractVillager; -import org.bukkit.event.entity.VillagerAcquireTradeEvent; -// CraftBukkit end - -public class EntityVillagerTrader extends EntityVillagerAbstract { - - @Nullable - private BlockPosition bA; - private int bB; - - public EntityVillagerTrader(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.attachedToPlayer = true; - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(0, new PathfinderGoalUseItem<>(this, PotionUtil.a(new ItemStack(Items.POTION), Potions.INVISIBILITY), SoundEffects.ENTITY_WANDERING_TRADER_DISAPPEARED, (entityvillagertrader) -> { - return !this.world.J() && !entityvillagertrader.isInvisible(); - })); - this.goalSelector.a(0, new PathfinderGoalUseItem<>(this, new ItemStack(Items.MILK_BUCKET), SoundEffects.ENTITY_WANDERING_TRADER_REAPPEARED, (entityvillagertrader) -> { - return this.world.J() && entityvillagertrader.isInvisible(); - })); - this.goalSelector.a(1, new PathfinderGoalTradeWithPlayer(this)); - this.goalSelector.a(1, new PathfinderGoalAvoidTarget<>(this, EntityZombie.class, 8.0F, 0.5D, 0.5D)); - this.goalSelector.a(1, new PathfinderGoalAvoidTarget<>(this, EntityEvoker.class, 12.0F, 0.5D, 0.5D)); - this.goalSelector.a(1, new PathfinderGoalAvoidTarget<>(this, EntityVindicator.class, 8.0F, 0.5D, 0.5D)); - this.goalSelector.a(1, new PathfinderGoalAvoidTarget<>(this, EntityVex.class, 8.0F, 0.5D, 0.5D)); - this.goalSelector.a(1, new PathfinderGoalAvoidTarget<>(this, EntityPillager.class, 15.0F, 0.5D, 0.5D)); - this.goalSelector.a(1, new PathfinderGoalAvoidTarget<>(this, EntityIllagerIllusioner.class, 12.0F, 0.5D, 0.5D)); - this.goalSelector.a(1, new PathfinderGoalPanic(this, 0.5D)); - this.goalSelector.a(1, new PathfinderGoalLookAtTradingPlayer(this)); - this.goalSelector.a(2, new EntityVillagerTrader.a(this, 2.0D, 0.35D)); - this.goalSelector.a(4, new PathfinderGoalMoveTowardsRestriction(this, 1.0D)); - this.goalSelector.a(8, new PathfinderGoalRandomStrollLand(this, 0.35D)); - this.goalSelector.a(9, new PathfinderGoalInteract(this, EntityHuman.class, 3.0F, 1.0F)); - this.goalSelector.a(10, new PathfinderGoalLookAtPlayer(this, EntityInsentient.class, 8.0F)); - } - - @Nullable - @Override - public EntityAgeable createChild(EntityAgeable entityageable) { - return null; - } - - @Override - public boolean ea() { - return false; - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - boolean flag = itemstack.getItem() == Items.NAME_TAG; - - if (flag) { - itemstack.a(entityhuman, (EntityLiving) this, enumhand); - return true; - } else if (itemstack.getItem() != Items.VILLAGER_SPAWN_EGG && this.isAlive() && !this.dY() && !this.isBaby()) { - if (enumhand == EnumHand.MAIN_HAND) { - entityhuman.a(StatisticList.TALKED_TO_VILLAGER); - } - - if (this.getOffers().isEmpty()) { - return super.a(entityhuman, enumhand); - } else { - if (!this.world.isClientSide) { - this.setTradingPlayer(entityhuman); - this.openTrade(entityhuman, this.getScoreboardDisplayName(), 1); - } - - return true; - } - } else { - return super.a(entityhuman, enumhand); - } - } - - @Override - protected void eh() { - VillagerTrades.IMerchantRecipeOption[] avillagertrades_imerchantrecipeoption = (VillagerTrades.IMerchantRecipeOption[]) VillagerTrades.b.get(1); - VillagerTrades.IMerchantRecipeOption[] avillagertrades_imerchantrecipeoption1 = (VillagerTrades.IMerchantRecipeOption[]) VillagerTrades.b.get(2); - - if (avillagertrades_imerchantrecipeoption != null && avillagertrades_imerchantrecipeoption1 != null) { - MerchantRecipeList merchantrecipelist = this.getOffers(); - - this.a(merchantrecipelist, avillagertrades_imerchantrecipeoption, 5); - int i = this.random.nextInt(avillagertrades_imerchantrecipeoption1.length); - VillagerTrades.IMerchantRecipeOption villagertrades_imerchantrecipeoption = avillagertrades_imerchantrecipeoption1[i]; - MerchantRecipe merchantrecipe = villagertrades_imerchantrecipeoption.a(this, this.random); - - if (merchantrecipe != null) { - // CraftBukkit start - VillagerAcquireTradeEvent event = new VillagerAcquireTradeEvent((AbstractVillager) getBukkitEntity(), merchantrecipe.asBukkit()); - // Suppress during worldgen - if (this.valid) { - Bukkit.getPluginManager().callEvent(event); - } - if (!event.isCancelled()) { - merchantrecipelist.add(CraftMerchantRecipe.fromBukkit(event.getRecipe()).toMinecraft()); - } - // CraftBukkit end - } - - } - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("DespawnDelay", this.bB); - if (this.bA != null) { - nbttagcompound.set("WanderTarget", GameProfileSerializer.a(this.bA)); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("DespawnDelay", 99)) { - this.bB = nbttagcompound.getInt("DespawnDelay"); - } - - if (nbttagcompound.hasKey("WanderTarget")) { - this.bA = GameProfileSerializer.c(nbttagcompound.getCompound("WanderTarget")); - } - - this.setAgeRaw(Math.max(0, this.getAge())); - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return false; - } - - @Override - protected void b(MerchantRecipe merchantrecipe) { - if (merchantrecipe.isRewardExp()) { - int i = 3 + this.random.nextInt(4); - - this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY + 0.5D, this.locZ, i, org.bukkit.entity.ExperienceOrb.SpawnReason.VILLAGER_TRADE, this.getTrader(), this)); // Paper - } - - } - - @Override - protected SoundEffect getSoundAmbient() { - return this.dY() ? SoundEffects.ENTITY_WANDERING_TRADER_TRADE : SoundEffects.ENTITY_WANDERING_TRADER_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_WANDERING_TRADER_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_WANDERING_TRADER_DEATH; - } - - @Override - protected SoundEffect c(ItemStack itemstack) { - Item item = itemstack.getItem(); - - return item == Items.MILK_BUCKET ? SoundEffects.ENTITY_WANDERING_TRADER_DRINK_MILK : SoundEffects.ENTITY_WANDERING_TRADER_DRINK_POTION; - } - - @Override - protected SoundEffect r(boolean flag) { - return flag ? SoundEffects.ENTITY_WANDERING_TRADER_YES : SoundEffects.ENTITY_WANDERING_TRADER_NO; - } - - @Override - public SoundEffect eb() { - return SoundEffects.ENTITY_WANDERING_TRADER_YES; - } - - public void t(int i) { - this.bB = i; - } - - public int ef() { - return this.bB; - } - - @Override - public void movementTick() { - super.movementTick(); - if (!this.world.isClientSide) { - this.ej(); - } - - } - - private void ej() { - if (this.bB > 0 && !this.dY() && --this.bB == 0) { - this.die(); - } - - } - - public void g(@Nullable BlockPosition blockposition) { - this.bA = blockposition; - } - - @Nullable - private BlockPosition ek() { - return this.bA; - } - - class a extends PathfinderGoal { - - final EntityVillagerTrader a; - final double b; - final double c; - - a(EntityVillagerTrader entityvillagertrader, double d0, double d1) { - this.a = entityvillagertrader; - this.b = d0; - this.c = d1; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public void d() { - this.a.g((BlockPosition) null); - EntityVillagerTrader.this.navigation.o(); - } - - @Override - public boolean a() { - BlockPosition blockposition = this.a.ek(); - - return blockposition != null && this.a(blockposition, this.b); - } - - @Override - public void e() { - BlockPosition blockposition = this.a.ek(); - - if (blockposition != null && EntityVillagerTrader.this.navigation.n()) { - if (this.a(blockposition, 10.0D)) { - Vec3D vec3d = (new Vec3D((double) blockposition.getX() - this.a.locX, (double) blockposition.getY() - this.a.locY, (double) blockposition.getZ() - this.a.locZ)).d(); - Vec3D vec3d1 = vec3d.a(10.0D).add(this.a.locX, this.a.locY, this.a.locZ); - - EntityVillagerTrader.this.navigation.a(vec3d1.x, vec3d1.y, vec3d1.z, this.c); - } else { - EntityVillagerTrader.this.navigation.a((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), this.c); - } - } - - } - - private boolean a(BlockPosition blockposition, double d0) { - return !blockposition.a((IPosition) this.a.getPositionVector(), d0); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityVindicator.java b/src/main/java/net/minecraft/server/EntityVindicator.java deleted file mode 100644 index ffbd6e926..000000000 --- a/src/main/java/net/minecraft/server/EntityVindicator.java +++ /dev/null @@ -1,216 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.EnumSet; -import java.util.Map; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class EntityVindicator extends EntityIllagerAbstract { - - private static final Predicate b = (enumdifficulty) -> { - return enumdifficulty == EnumDifficulty.NORMAL || enumdifficulty == EnumDifficulty.HARD; - }; - private boolean bz; public boolean isJohnny() { return bz; } public void setJohnny(boolean johnny) { bz = johnny; } // Paper - OBFHELPER - - public EntityVindicator(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.goalSelector.a(0, new PathfinderGoalFloat(this)); - this.goalSelector.a(1, new EntityVindicator.a(this)); - this.goalSelector.a(2, new EntityIllagerAbstract.b(this)); - this.goalSelector.a(3, new EntityRaider.a(this, 10.0F)); - this.goalSelector.a(4, new EntityVindicator.c(this)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[]{EntityRaider.class})).a(new Class[0])); // Paper - decompile fix - this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityVillagerAbstract.class, true)); - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); - this.targetSelector.a(4, new EntityVindicator.b(this)); - this.goalSelector.a(8, new PathfinderGoalRandomStroll(this, 0.6D)); - this.goalSelector.a(9, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 3.0F, 1.0F)); - this.goalSelector.a(10, new PathfinderGoalLookAtPlayer(this, EntityInsentient.class, 8.0F)); - } - - @Override - protected void mobTick() { - if (!this.isNoAI()) { - if (((WorldServer) this.world).d_(new BlockPosition(this))) { - ((Navigation) this.getNavigation()).a(true); - } else { - ((Navigation) this.getNavigation()).a(false); - } - } - - super.mobTick(); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.3499999940395355D); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(12.0D); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(24.0D); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(5.0D); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - if (this.bz) { - nbttagcompound.setBoolean("Johnny", true); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("Johnny", 99)) { - this.bz = nbttagcompound.getBoolean("Johnny"); - } - - } - - @Override - public SoundEffect dV() { - return SoundEffects.ENTITY_VINDICATOR_CELEBRATE; - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - GroupDataEntity groupdataentity1 = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - - ((Navigation) this.getNavigation()).a(true); - this.a(difficultydamagescaler); - this.b(difficultydamagescaler); - return groupdataentity1; - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - if (this.ej() == null) { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.IRON_AXE)); - } - - } - - @Override - public boolean r(Entity entity) { - return super.r(entity) ? true : (entity instanceof EntityLiving && ((EntityLiving) entity).getMonsterType() == EnumMonsterType.ILLAGER ? this.getScoreboardTeam() == null && entity.getScoreboardTeam() == null : false); - } - - @Override - public void setCustomName(@Nullable IChatBaseComponent ichatbasecomponent) { - super.setCustomName(ichatbasecomponent); - if (!this.bz && ichatbasecomponent != null && ichatbasecomponent.getString().equals("Johnny")) { - this.bz = true; - } - - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_VINDICATOR_AMBIENT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_VINDICATOR_DEATH; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_VINDICATOR_HURT; - } - - @Override - public void a(int i, boolean flag) { - ItemStack itemstack = new ItemStack(Items.IRON_AXE); - Raid raid = this.ej(); - byte b0 = 1; - - if (i > raid.a(EnumDifficulty.NORMAL)) { - b0 = 2; - } - - boolean flag1 = this.random.nextFloat() <= raid.w(); - - if (flag1) { - Map map = Maps.newHashMap(); - - map.put(Enchantments.DAMAGE_ALL, Integer.valueOf(b0)); - EnchantmentManager.a((Map) map, itemstack); - } - - this.setSlot(EnumItemSlot.MAINHAND, itemstack); - } - - static class b extends PathfinderGoalNearestAttackableTarget { - - public b(EntityVindicator entityvindicator) { - super(entityvindicator, EntityLiving.class, 0, true, true, EntityLiving::du); - } - - @Override - public boolean a() { - return ((EntityVindicator) this.e).bz && super.a(); - } - - @Override - public void c() { - super.c(); - this.e.n(0); - } - } - - static class a extends PathfinderGoalBreakDoor { - - public a(EntityInsentient entityinsentient) { - super(entityinsentient, 6, EntityVindicator.b); - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean b() { - EntityVindicator entityvindicator = (EntityVindicator) this.entity; - - return entityvindicator.ek() && super.b(); - } - - @Override - public boolean a() { - EntityVindicator entityvindicator = (EntityVindicator) this.entity; - - return entityvindicator.ek() && entityvindicator.random.nextInt(10) == 0 && super.a(); - } - - @Override - public void c() { - super.c(); - this.entity.n(0); - } - } - - class c extends PathfinderGoalMeleeAttack { - - public c(EntityVindicator entityvindicator) { - super(entityvindicator, 1.0D, false); - } - - @Override - protected double a(EntityLiving entityliving) { - if (this.a.getVehicle() instanceof EntityRavager) { - float f = this.a.getVehicle().getWidth() - 0.1F; - - return (double) (f * 2.0F * f * 2.0F + entityliving.getWidth()); - } else { - return super.a(entityliving); - } - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityWitch.java b/src/main/java/net/minecraft/server/EntityWitch.java deleted file mode 100644 index 0b849f37c..000000000 --- a/src/main/java/net/minecraft/server/EntityWitch.java +++ /dev/null @@ -1,243 +0,0 @@ -package net.minecraft.server; - -// Paper start -import com.destroystokyo.paper.event.entity.WitchReadyPotionEvent; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.entity.Witch; -// Paper end - -import java.util.Iterator; -import java.util.List; -import java.util.UUID; -import java.util.function.Predicate; - -public class EntityWitch extends EntityRaider implements IRangedEntity { - - private static final UUID b = UUID.fromString("5CD17E52-A79A-43D3-A529-90FDE04B181E"); - private static final AttributeModifier bz = (new AttributeModifier(EntityWitch.b, "Drinking speed penalty", -0.25D, AttributeModifier.Operation.ADDITION)).a(false); private static final AttributeModifier DRINKING_SPEED = bz; // Paper - OBFHELPER - private static final DataWatcherObject bA = DataWatcher.a(EntityWitch.class, DataWatcherRegistry.i); - private int bB; public int getPotionUseTimeLeft() { return bB; } public void setPotionUseTimeLeft(int timeLeft) { bB = timeLeft; } // Paper - OBFHELPER - private PathfinderGoalNearestHealableRaider bC; - private PathfinderGoalNearestAttackableTargetWitch bD; - - public EntityWitch(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - @Override - protected void initPathfinder() { - super.initPathfinder(); - this.bC = new PathfinderGoalNearestHealableRaider<>(this, EntityRaider.class, true, (entityliving) -> { - return entityliving != null && this.ek() && entityliving.getEntityType() != EntityTypes.WITCH; - }); - this.bD = new PathfinderGoalNearestAttackableTargetWitch<>(this, EntityHuman.class, 10, true, false, (Predicate) null); - this.goalSelector.a(1, new PathfinderGoalFloat(this)); - this.goalSelector.a(2, new PathfinderGoalArrowAttack(this, 1.0D, 60, 10.0F)); - this.goalSelector.a(2, new PathfinderGoalRandomStrollLand(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, new Class[]{EntityRaider.class})); - this.targetSelector.a(2, this.bC); - this.targetSelector.a(3, this.bD); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.getDataWatcher().register(EntityWitch.bA, false); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_WITCH_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_WITCH_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_WITCH_DEATH; - } - - public void setDrinkingPotion(boolean drinkingPotion) { s(drinkingPotion); } // Paper - OBFHELPER - public void s(boolean flag) { - this.getDataWatcher().set(EntityWitch.bA, flag); - } - - public boolean isDrinkingPotion() { return l(); } // Paper - OBFHELPER - public boolean l() { - return (Boolean) this.getDataWatcher().get(EntityWitch.bA); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(26.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); - } - - @Override - public void movementTick() { - if (!this.world.isClientSide && this.isAlive()) { - this.bC.j(); - if (this.bC.h() <= 0) { - this.bD.a(true); - } else { - this.bD.a(false); - } - - if (this.l()) { - if (this.bB-- <= 0) { - this.s(false); - ItemStack itemstack = this.getItemInMainHand(); - - this.setSlot(EnumItemSlot.MAINHAND, ItemStack.a); - if (itemstack.getItem() == Items.POTION) { - // Paper start - com.destroystokyo.paper.event.entity.WitchConsumePotionEvent event = new com.destroystokyo.paper.event.entity.WitchConsumePotionEvent((org.bukkit.entity.Witch) this.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack)); - - List list = event.callEvent() ? PotionUtil.getEffects(org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(event.getPotion())) : null; - // Paper end - - if (list != null) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - this.addEffect(new MobEffect(mobeffect), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - } - } - - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).removeModifier(EntityWitch.bz); - } - } else { - PotionRegistry potionregistry = null; - - if (this.random.nextFloat() < 0.15F && this.a(TagsFluid.WATER) && !this.hasEffect(MobEffects.WATER_BREATHING)) { - potionregistry = Potions.WATER_BREATHING; - } else if (this.random.nextFloat() < 0.15F && (this.isBurning() || this.cE() != null && this.cE().p()) && !this.hasEffect(MobEffects.FIRE_RESISTANCE)) { - potionregistry = Potions.FIRE_RESISTANCE; - } else if (this.random.nextFloat() < 0.05F && this.getHealth() < this.getMaxHealth()) { - potionregistry = Potions.HEALING; - } else if (this.random.nextFloat() < 0.5F && this.getGoalTarget() != null && !this.hasEffect(MobEffects.FASTER_MOVEMENT) && this.getGoalTarget().h((Entity) this) > 121.0D) { - potionregistry = Potions.SWIFTNESS; - } - - if (potionregistry != null) { - // Paper start - move all this down into its own method -// ItemStack potion = PotionUtil.a(new ItemStack(Items.POTION), potionregistry); -// org.bukkit.inventory.ItemStack bukkitStack = com.destroystokyo.paper.event.entity.WitchReadyPotionEvent.process((org.bukkit.entity.Witch) this.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(potion)); -// this.setSlot(EnumItemSlot.MAINHAND, org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(bukkitStack)); -// // Paper end -// this.bB = this.getItemInMainHand().k(); -// this.s(true); -// this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_WITCH_DRINK, this.getSoundCategory(), 1.0F, 0.8F + this.random.nextFloat() * 0.4F); -// AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); -// -// attributeinstance.removeModifier(EntityWitch.bz); -// attributeinstance.addModifier(EntityWitch.bz); - this.setDrinkingPotion(PotionUtil.addPotionToItemStack(new ItemStack(Items.POTION), potionregistry)); - // Paper end - } - } - - if (this.random.nextFloat() < 7.5E-4F) { - this.world.broadcastEntityEffect(this, (byte) 15); - } - } - - super.movementTick(); - } - - // Paper start - public void setDrinkingPotion(ItemStack potion) { - setSlot(EnumItemSlot.MAINHAND, CraftItemStack.asNMSCopy(WitchReadyPotionEvent.process((Witch) getBukkitEntity(), CraftItemStack.asCraftMirror(potion)))); - setPotionUseTimeLeft(getItemInMainHand().getItemUseMaxDuration()); - setDrinkingPotion(true); - world.sendSoundEffect(null, locX, locY, locZ, SoundEffects.ENTITY_WITCH_DRINK, getSoundCategory(), 1.0F, 0.8F + random.nextFloat() * 0.4F); - AttributeInstance attributeinstance = getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); - attributeinstance.removeModifier(EntityWitch.DRINKING_SPEED); - attributeinstance.addModifier(EntityWitch.DRINKING_SPEED); - } - // Paper end - - @Override - public SoundEffect dV() { - return SoundEffects.ENTITY_WITCH_CELEBRATE; - } - - @Override - 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; - } - - @Override - public void a(EntityLiving entityliving, float f) { - if (!this.l()) { - Vec3D vec3d = entityliving.getMot(); - double d0 = entityliving.locX + vec3d.x - this.locX; - double d1 = entityliving.locY + (double) entityliving.getHeadHeight() - 1.100000023841858D - this.locY; - double d2 = entityliving.locZ + vec3d.z - this.locZ; - float f1 = MathHelper.sqrt(d0 * d0 + d2 * d2); - PotionRegistry potionregistry = Potions.HARMING; - - if (entityliving instanceof EntityRaider) { - if (entityliving.getHealth() <= 4.0F) { - potionregistry = Potions.HEALING; - } else { - potionregistry = Potions.REGENERATION; - } - - this.setGoalTarget((EntityLiving) null); - } else if (f1 >= 8.0F && !entityliving.hasEffect(MobEffects.SLOWER_MOVEMENT)) { - potionregistry = Potions.SLOWNESS; - } else if (entityliving.getHealth() >= 8.0F && !entityliving.hasEffect(MobEffects.POISON)) { - potionregistry = Potions.POISON; - } else if (f1 <= 3.0F && !entityliving.hasEffect(MobEffects.WEAKNESS) && this.random.nextFloat() < 0.25F) { - potionregistry = Potions.WEAKNESS; - } - - // Paper start - ItemStack potion = PotionUtil.a(new ItemStack(Items.SPLASH_POTION), potionregistry); - com.destroystokyo.paper.event.entity.WitchThrowPotionEvent event = new com.destroystokyo.paper.event.entity.WitchThrowPotionEvent((org.bukkit.entity.Witch) this.getBukkitEntity(), (org.bukkit.entity.LivingEntity) entityliving.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(potion)); - if (!event.callEvent()) { - return; - } - potion = org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(event.getPotion()); - EntityPotion entitypotion = new EntityPotion(this.world, this); - entitypotion.setItem(potion); - // Paper end - entitypotion.pitch -= -20.0F; - entitypotion.shoot(d0, d1 + (double) (f1 * 0.2F), d2, 0.75F, 8.0F); - this.world.playSound((EntityHuman) null, this.locX, this.locY, this.locZ, SoundEffects.ENTITY_WITCH_THROW, this.getSoundCategory(), 1.0F, 0.8F + this.random.nextFloat() * 0.4F); - this.world.addEntity(entitypotion); - } - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return 1.62F; - } - - @Override - public void a(int i, boolean flag) {} - - @Override - public boolean dX() { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/EntityWither.java b/src/main/java/net/minecraft/server/EntityWither.java deleted file mode 100644 index 8b3052b11..000000000 --- a/src/main/java/net/minecraft/server/EntityWither.java +++ /dev/null @@ -1,564 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableList; -import java.util.EnumSet; -import java.util.List; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityRegainHealthEvent; -import org.bukkit.event.entity.EntityTargetEvent; -import org.bukkit.event.entity.ExplosionPrimeEvent; -// CraftBukkit end - -public class EntityWither extends EntityMonster implements IRangedEntity { - - private static final DataWatcherObject b = DataWatcher.a(EntityWither.class, DataWatcherRegistry.b); - private static final DataWatcherObject c = DataWatcher.a(EntityWither.class, DataWatcherRegistry.b); - private static final DataWatcherObject d = DataWatcher.a(EntityWither.class, DataWatcherRegistry.b); - private static final List> bz = ImmutableList.of(EntityWither.b, EntityWither.c, EntityWither.d); - private static final DataWatcherObject bA = DataWatcher.a(EntityWither.class, DataWatcherRegistry.b); - private final float[] bB = new float[2]; - private final float[] bC = new float[2]; - private final float[] bD = new float[2]; - private final float[] bE = new float[2]; - private final int[] bF = new int[2]; - private final int[] bG = new int[2]; - private int bH; - public final BossBattleServer bossBattle; - private static final Predicate bJ = (entityliving) -> { - return entityliving.getMonsterType() != EnumMonsterType.UNDEAD && entityliving.du(); - }; - private static final PathfinderTargetCondition bK = (new PathfinderTargetCondition()).a(20.0D).a(EntityWither.bJ); - - public EntityWither(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.bossBattle = (BossBattleServer) (new BossBattleServer(this.getScoreboardDisplayName(), BossBattle.BarColor.PURPLE, BossBattle.BarStyle.PROGRESS)).setDarkenSky(true); - this.setHealth(this.getMaxHealth()); - this.getNavigation().d(true); - this.f = 50; - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(0, new EntityWither.a()); - this.goalSelector.a(2, new PathfinderGoalArrowAttack(this, 1.0D, 40, 20.0F)); - this.goalSelector.a(5, new PathfinderGoalRandomStrollLand(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, new Class[0])); - this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityInsentient.class, 0, false, false, EntityWither.bJ)); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityWither.b, 0); - this.datawatcher.register(EntityWither.c, 0); - this.datawatcher.register(EntityWither.d, 0); - this.datawatcher.register(EntityWither.bA, 0); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setInt("Invul", this.dV()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.r(nbttagcompound.getInt("Invul")); - if (this.hasCustomName()) { - this.bossBattle.a(this.getScoreboardDisplayName()); - } - - } - - @Override - public void setCustomName(@Nullable IChatBaseComponent ichatbasecomponent) { - super.setCustomName(ichatbasecomponent); - this.bossBattle.a(this.getScoreboardDisplayName()); - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_WITHER_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_WITHER_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_WITHER_DEATH; - } - - @Override - public void movementTick() { - Vec3D vec3d = this.getMot().d(1.0D, 0.6D, 1.0D); - - if (!this.world.isClientSide && this.getHeadTarget(0) > 0) { - Entity entity = this.world.getEntity(this.getHeadTarget(0)); - - if (entity != null) { - double d0 = vec3d.y; - - if (this.locY < entity.locY || !this.dW() && this.locY < entity.locY + 5.0D) { - d0 = Math.max(0.0D, d0); - d0 += 0.3D - d0 * 0.6000000238418579D; - } - - vec3d = new Vec3D(vec3d.x, d0, vec3d.z); - Vec3D vec3d1 = new Vec3D(entity.locX - this.locX, 0.0D, entity.locZ - this.locZ); - - if (b(vec3d1) > 9.0D) { - Vec3D vec3d2 = vec3d1.d(); - - vec3d = vec3d.add(vec3d2.x * 0.3D - vec3d.x * 0.6D, 0.0D, vec3d2.z * 0.3D - vec3d.z * 0.6D); - } - } - } - - this.setMot(vec3d); - if (b(vec3d) > 0.05D) { - this.yaw = (float) MathHelper.d(vec3d.z, vec3d.x) * 57.295776F - 90.0F; - } - - super.movementTick(); - - int i; - - for (i = 0; i < 2; ++i) { - this.bE[i] = this.bC[i]; - this.bD[i] = this.bB[i]; - } - - int j; - - for (i = 0; i < 2; ++i) { - j = this.getHeadTarget(i + 1); - Entity entity1 = null; - - if (j > 0) { - entity1 = this.world.getEntity(j); - } - - if (entity1 != null) { - double d1 = this.t(i + 1); - double d2 = this.u(i + 1); - double d3 = this.v(i + 1); - double d4 = entity1.locX - d1; - double d5 = entity1.locY + (double) entity1.getHeadHeight() - d2; - double d6 = entity1.locZ - d3; - double d7 = (double) MathHelper.sqrt(d4 * d4 + d6 * d6); - float f = (float) (MathHelper.d(d6, d4) * 57.2957763671875D) - 90.0F; - float f1 = (float) (-(MathHelper.d(d5, d7) * 57.2957763671875D)); - - this.bB[i] = this.a(this.bB[i], f1, 40.0F); - this.bC[i] = this.a(this.bC[i], f, 10.0F); - } else { - this.bC[i] = this.a(this.bC[i], this.aK, 10.0F); - } - } - - boolean flag = this.dW(); - - for (j = 0; j < 3; ++j) { - double d8 = this.t(j); - double d9 = this.u(j); - double d10 = this.v(j); - - this.world.addParticle(Particles.SMOKE, d8 + this.random.nextGaussian() * 0.30000001192092896D, d9 + this.random.nextGaussian() * 0.30000001192092896D, d10 + this.random.nextGaussian() * 0.30000001192092896D, 0.0D, 0.0D, 0.0D); - if (flag && this.world.random.nextInt(4) == 0) { - this.world.addParticle(Particles.ENTITY_EFFECT, d8 + this.random.nextGaussian() * 0.30000001192092896D, d9 + this.random.nextGaussian() * 0.30000001192092896D, d10 + this.random.nextGaussian() * 0.30000001192092896D, 0.699999988079071D, 0.699999988079071D, 0.5D); - } - } - - if (this.dV() > 0) { - for (j = 0; j < 3; ++j) { - this.world.addParticle(Particles.ENTITY_EFFECT, this.locX + this.random.nextGaussian(), this.locY + (double) (this.random.nextFloat() * 3.3F), this.locZ + this.random.nextGaussian(), 0.699999988079071D, 0.699999988079071D, 0.8999999761581421D); - } - } - - } - - @Override - protected void mobTick() { - int i; - - if (this.dV() > 0) { - i = this.dV() - 1; - if (i <= 0) { - Explosion.Effect explosion_effect = this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) ? Explosion.Effect.DESTROY : Explosion.Effect.NONE; - // CraftBukkit start - // this.world.createExplosion(this, this.locX, this.locY + (double) this.getHeadHeight(), this.locZ, 7.0F, false, explosion_effect); - 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(), explosion_effect); - } - // CraftBukkit end - - // CraftBukkit start - Use relative location for far away sounds - // this.world.b(1023, new BlockPosition(this), 0); - // Paper start - int viewDistance = ((WorldServer) this.world).spigotConfig.viewDistance * 16; // Paper - updated to use worlds actual view distance incase we have to uncomment this due to removal of player view distance API - for (EntityPlayer player : ((WorldServer)world).getPlayers()) { - //final int viewDistance = player.getViewDistance(); // TODO apply view distance api patch - // Paper end - 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(1023, new BlockPosition((int) relativeX, (int) this.locY, (int) relativeZ), 0, true)); - } else { - player.playerConnection.sendPacket(new PacketPlayOutWorldEvent(1023, 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.mobTick(); - - int j; - - for (i = 1; i < 3; ++i) { - if (this.ticksLived >= this.bF[i - 1]) { - this.bF[i - 1] = this.ticksLived + 10 + this.random.nextInt(10); - if (this.world.getDifficulty() == EnumDifficulty.NORMAL || this.world.getDifficulty() == EnumDifficulty.HARD) { - int k = i - 1; - int l = this.bG[i - 1]; - - this.bG[k] = this.bG[i - 1] + 1; - if (l > 15) { - float f = 10.0F; - float f1 = 5.0F; - double d0 = MathHelper.a(this.random, this.locX - 10.0D, this.locX + 10.0D); - double d1 = MathHelper.a(this.random, this.locY - 5.0D, this.locY + 5.0D); - double d2 = MathHelper.a(this.random, this.locZ - 10.0D, this.locZ + 10.0D); - - this.a(i + 1, d0, d1, d2, true); - this.bG[i - 1] = 0; - } - } - - j = this.getHeadTarget(i); - if (j > 0) { - Entity entity = this.world.getEntity(j); - - if (entity != null && entity.isAlive() && this.h(entity) <= 900.0D && this.hasLineOfSight(entity)) { - if (entity instanceof EntityHuman && ((EntityHuman) entity).abilities.isInvulnerable) { - this.setHeadTarget(i, 0); - } else { - this.a(i + 1, (EntityLiving) entity); - this.bF[i - 1] = this.ticksLived + 40 + this.random.nextInt(20); - this.bG[i - 1] = 0; - } - } else { - this.setHeadTarget(i, 0); - } - } else { - List list = this.world.a(EntityLiving.class, EntityWither.bK, this, this.getBoundingBox().grow(20.0D, 8.0D, 20.0D)); - - for (int i1 = 0; i1 < 10 && !list.isEmpty(); ++i1) { - EntityLiving entityliving = (EntityLiving) list.get(this.random.nextInt(list.size())); - - if (entityliving != this && entityliving.isAlive() && this.hasLineOfSight(entityliving)) { - if (entityliving instanceof EntityHuman) { - if (!((EntityHuman) entityliving).abilities.isInvulnerable) { - if (CraftEventFactory.callEntityTargetLivingEvent(this, entityliving, EntityTargetEvent.TargetReason.CLOSEST_PLAYER).isCancelled()) continue; // CraftBukkit - this.setHeadTarget(i, entityliving.getId()); - } - } else { - if (CraftEventFactory.callEntityTargetLivingEvent(this, entityliving, EntityTargetEvent.TargetReason.CLOSEST_ENTITY).isCancelled()) continue; // CraftBukkit - this.setHeadTarget(i, entityliving.getId()); - } - break; - } - - list.remove(entityliving); - } - } - } - } - - if (this.getGoalTarget() != null) { - this.setHeadTarget(0, this.getGoalTarget().getId()); - } else { - this.setHeadTarget(0, 0); - } - - if (this.bH > 0) { - --this.bH; - if (this.bH == 0 && this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - 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); - IBlockData iblockdata = this.world.getType(blockposition); - - if (b(iblockdata)) { - // CraftBukkit start - if (CraftEventFactory.callEntityChangeBlockEvent(this, blockposition, Blocks.AIR.getBlockData()).isCancelled()) { - continue; - } - // CraftBukkit end - flag = this.world.b(blockposition, true) || flag; - } - } - } - } - - if (flag) { - this.world.a((EntityHuman) null, 1022, new BlockPosition(this), 0); - } - } - } - - if (this.ticksLived % 20 == 0) { - this.heal(1.0F, EntityRegainHealthEvent.RegainReason.REGEN); // CraftBukkit - } - - this.bossBattle.setProgress(this.getHealth() / this.getMaxHealth()); - } - } - - public static boolean b(IBlockData iblockdata) { - return !iblockdata.isAir() && !TagsBlock.WITHER_IMMUNE.isTagged(iblockdata.getBlock()); - } - - public void l() { - this.r(220); - this.setHealth(this.getMaxHealth() / 3.0F); - } - - @Override - public void a(IBlockData iblockdata, Vec3D vec3d) {} - - @Override - public void b(EntityPlayer entityplayer) { - super.b(entityplayer); - this.bossBattle.addPlayer(entityplayer); - } - - @Override - public void c(EntityPlayer entityplayer) { - super.c(entityplayer); - this.bossBattle.removePlayer(entityplayer); - } - - private double t(int i) { - if (i <= 0) { - return this.locX; - } else { - float f = (this.aK + (float) (180 * (i - 1))) * 0.017453292F; - 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.aK + (float) (180 * (i - 1))) * 0.017453292F; - float f1 = MathHelper.sin(f); - - return this.locZ + (double) f1 * 1.3D; - } - } - - 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; - } - - private void a(int i, EntityLiving entityliving) { - this.a(i, entityliving.locX, entityliving.locY + (double) entityliving.getHeadHeight() * 0.5D, entityliving.locZ, i == 0 && this.random.nextFloat() < 0.001F); - } - - private void a(int i, double d0, double d1, double d2, boolean flag) { - this.world.a((EntityHuman) null, 1024, 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); - } - - @Override - public void a(EntityLiving entityliving, float f) { - this.a(0, entityliving); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else if (damagesource != DamageSource.DROWN && !(damagesource.getEntity() instanceof EntityWither)) { - if (this.dV() > 0 && damagesource != DamageSource.OUT_OF_WORLD) { - return false; - } else { - Entity entity; - - if (this.dW()) { - entity = damagesource.j(); - if (entity instanceof EntityArrow) { - return false; - } - } - - entity = damagesource.getEntity(); - if (entity != null && !(entity instanceof EntityHuman) && entity instanceof EntityLiving && ((EntityLiving) entity).getMonsterType() == this.getMonsterType()) { - return false; - } else { - if (this.bH <= 0) { - this.bH = 20; - } - - for (int i = 0; i < this.bG.length; ++i) { - this.bG[i] += 3; - } - - return super.damageEntity(damagesource, f); - } - } - } else { - return false; - } - } - - @Override - protected void dropDeathLoot(DamageSource damagesource, int i, boolean flag) { - super.dropDeathLoot(damagesource, i, flag); - EntityItem entityitem = this.a((IMaterial) Items.NETHER_STAR); - - if (entityitem != null) { - entityitem.s(); - } - - } - - @Override - protected void checkDespawn() { - this.ticksFarFromPlayer = 0; - } - - @Override - public void b(float f, float f1) {} - - @Override - public boolean addEffect(MobEffect mobeffect) { - return false; - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(300.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.6000000238418579D); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(40.0D); - this.getAttributeInstance(GenericAttributes.ARMOR).setValue(4.0D); - } - - public int dV() { - return (Integer) this.datawatcher.get(EntityWither.bA); - } - - public void r(int i) { - this.datawatcher.set(EntityWither.bA, i); - } - - public int getHeadTarget(int i) { - return (Integer) this.datawatcher.get((DataWatcherObject) EntityWither.bz.get(i)); - } - - public void setHeadTarget(int i, int j) { - this.datawatcher.set((DataWatcherObject) EntityWither.bz.get(i), j); - } - - public boolean dW() { - return this.getHealth() <= this.getMaxHealth() / 2.0F; - } - - @Override - public EnumMonsterType getMonsterType() { - return EnumMonsterType.UNDEAD; - } - - @Override - protected boolean n(Entity entity) { - return false; - } - - @Override - public boolean canPortal() { - return false; - } - - @Override - public boolean d(MobEffect mobeffect) { - return mobeffect.getMobEffect() == MobEffects.WITHER ? false : super.d(mobeffect); - } - - class a extends PathfinderGoal { - - public a() { - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.JUMP, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - return EntityWither.this.dV() > 0; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityWitherSkull.java b/src/main/java/net/minecraft/server/EntityWitherSkull.java deleted file mode 100644 index 2a056024f..000000000 --- a/src/main/java/net/minecraft/server/EntityWitherSkull.java +++ /dev/null @@ -1,112 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.event.entity.ExplosionPrimeEvent; // CraftBukkit - -public class EntityWitherSkull extends EntityFireball { - - private static final DataWatcherObject f = DataWatcher.a(EntityWitherSkull.class, DataWatcherRegistry.i); - - public EntityWitherSkull(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public EntityWitherSkull(World world, EntityLiving entityliving, double d0, double d1, double d2) { - super(EntityTypes.WITHER_SKULL, entityliving, d0, d1, d2, world); - } - - @Override - protected float k() { - return this.isCharged() ? 0.73F : super.k(); - } - - @Override - public boolean isBurning() { - return false; - } - - @Override - public float a(Explosion explosion, IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, Fluid fluid, float f) { - return this.isCharged() && EntityWither.b(iblockdata) ? Math.min(0.8F, f) : f; - } - - @Override - protected void a(MovingObjectPosition movingobjectposition) { - if (!this.world.isClientSide) { - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - Entity entity = ((MovingObjectPositionEntity) movingobjectposition).getEntity(); - - // Spigot start - boolean didDamage = false; - if (this.shooter != null) { - didDamage = entity.damageEntity(DamageSource.projectile(this, shooter), 8.0F); - if (didDamage) { // CraftBukkit - if (entity.isAlive()) { - this.a(this.shooter, entity); - } else { - this.shooter.heal(5.0F, org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.WITHER); // CraftBukkit - } - } - } else { - didDamage = entity.damageEntity(DamageSource.MAGIC, 5.0F); - } - - if (didDamage && 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) entity).addEffect(new MobEffect(MobEffects.WITHER, 20 * b0, 1), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - } - } - - Explosion.Effect explosion_effect = this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) ? Explosion.Effect.DESTROY : Explosion.Effect.NONE; - - // CraftBukkit start - // this.world.createExplosion(this, this.locX, this.locY, this.locZ, 1.0F, false, explosion_effect); - 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(), explosion_effect); - } - // CraftBukkit end - this.die(); - } - - } - - @Override - public boolean isInteractable() { - return false; - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - return false; - } - - @Override - protected void initDatawatcher() { - this.datawatcher.register(EntityWitherSkull.f, false); - } - - public boolean isCharged() { - return (Boolean) this.datawatcher.get(EntityWitherSkull.f); - } - - public void setCharged(boolean flag) { - this.datawatcher.set(EntityWitherSkull.f, flag); - } - - @Override - protected boolean K_() { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/EntityWolf.java b/src/main/java/net/minecraft/server/EntityWolf.java deleted file mode 100644 index 02492663a..000000000 --- a/src/main/java/net/minecraft/server/EntityWolf.java +++ /dev/null @@ -1,467 +0,0 @@ -package net.minecraft.server; - -import java.util.UUID; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityTargetEvent.TargetReason; -// CraftBukkit end - -public class EntityWolf extends EntityTameableAnimal { - - private static final DataWatcherObject DATA_HEALTH = DataWatcher.a(EntityWolf.class, DataWatcherRegistry.c); - private static final DataWatcherObject bE = DataWatcher.a(EntityWolf.class, DataWatcherRegistry.i); - private static final DataWatcherObject bF = DataWatcher.a(EntityWolf.class, DataWatcherRegistry.b); - public static final Predicate bC = (entityliving) -> { - EntityTypes entitytypes = entityliving.getEntityType(); - - return entitytypes == EntityTypes.SHEEP || entitytypes == EntityTypes.RABBIT || entitytypes == EntityTypes.FOX; - }; - private float bG; - private float bH; - private boolean bI; - private boolean bJ; - private float bK; - private float bL; - - public EntityWolf(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.setTamed(false); - } - - @Override - protected void initPathfinder() { - this.goalSit = new PathfinderGoalSit(this); - this.goalSelector.a(1, new PathfinderGoalFloat(this)); - this.goalSelector.a(2, this.goalSit); - this.goalSelector.a(3, new EntityWolf.a<>(this, EntityLlama.class, 24.0F, 1.5D, 1.5D)); - this.goalSelector.a(4, new PathfinderGoalLeapAtTarget(this, 0.4F)); - this.goalSelector.a(5, new PathfinderGoalMeleeAttack(this, 1.0D, true)); - this.goalSelector.a(6, new PathfinderGoalFollowOwner(this, 1.0D, 10.0F, 2.0F)); - this.goalSelector.a(7, new PathfinderGoalBreed(this, 1.0D)); - this.goalSelector.a(8, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.goalSelector.a(9, new PathfinderGoalBeg(this, 8.0F)); - this.goalSelector.a(10, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); - this.goalSelector.a(10, new PathfinderGoalRandomLookaround(this)); - this.targetSelector.a(1, new PathfinderGoalOwnerHurtByTarget(this)); - this.targetSelector.a(2, new PathfinderGoalOwnerHurtTarget(this)); - this.targetSelector.a(3, (new PathfinderGoalHurtByTarget(this, new Class[0])).a(new Class[0])); // CraftBukkit - decompile error - this.targetSelector.a(4, new PathfinderGoalRandomTargetNonTamed<>(this, EntityAnimal.class, false, EntityWolf.bC)); - this.targetSelector.a(4, new PathfinderGoalRandomTargetNonTamed<>(this, EntityTurtle.class, false, EntityTurtle.bz)); - this.targetSelector.a(5, new PathfinderGoalNearestAttackableTarget<>(this, EntitySkeletonAbstract.class, false)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); - if (this.isTamed()) { - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(20.0D); - } else { - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(8.0D); - } - - this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(2.0D); - } - - // CraftBukkit - add overriden version - @Override - public boolean setGoalTarget(EntityLiving entityliving, org.bukkit.event.entity.EntityTargetEvent.TargetReason reason, boolean fire) { - if (!super.setGoalTarget(entityliving, reason, fire)) { - return false; - } - entityliving = getGoalTarget(); - if (entityliving == null) { - this.setAngry(false); - } else if (!this.isTamed()) { - this.setAngry(true); - } - return true; - } - // CraftBukkit end - - @Override - public void setGoalTarget(@Nullable EntityLiving entityliving) { - super.setGoalTarget(entityliving); - if (entityliving == null) { - this.setAngry(false); - } else if (!this.isTamed()) { - this.setAngry(true); - } - - } - - @Override - protected void mobTick() { - this.datawatcher.set(EntityWolf.DATA_HEALTH, this.getHealth()); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityWolf.DATA_HEALTH, this.getHealth()); - this.datawatcher.register(EntityWolf.bE, false); - this.datawatcher.register(EntityWolf.bF, EnumColor.RED.getColorIndex()); - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(SoundEffects.ENTITY_WOLF_STEP, 0.15F, 1.0F); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.setBoolean("Angry", this.isAngry()); - nbttagcompound.setByte("CollarColor", (byte) this.getCollarColor().getColorIndex()); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - this.setAngry(nbttagcompound.getBoolean("Angry")); - // CraftBukkit start - moved from below, SPIGOT-4893 - if (this.getGoalTarget() == null && this.isAngry()) { - this.setAngry(false); - } - // CraftBukkit end - if (nbttagcompound.hasKeyOfType("CollarColor", 99)) { - this.setCollarColor(EnumColor.fromColorIndex(nbttagcompound.getInt("CollarColor"))); - } - - } - - @Override - protected SoundEffect getSoundAmbient() { - return this.isAngry() ? SoundEffects.ENTITY_WOLF_GROWL : (this.random.nextInt(3) == 0 ? (this.isTamed() && (Float) this.datawatcher.get(EntityWolf.DATA_HEALTH) < 10.0F ? SoundEffects.ENTITY_WOLF_WHINE : SoundEffects.ENTITY_WOLF_PANT) : SoundEffects.ENTITY_WOLF_AMBIENT); - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_WOLF_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_WOLF_DEATH; - } - - @Override - protected float getSoundVolume() { - return 0.4F; - } - - @Override - public void movementTick() { - super.movementTick(); - if (!this.world.isClientSide && this.bI && !this.bJ && !this.dT() && this.onGround) { - this.bJ = true; - this.bK = 0.0F; - this.bL = 0.0F; - this.world.broadcastEntityEffect(this, (byte) 8); - } - - if (false && !this.world.isClientSide && this.getGoalTarget() == null && this.isAngry()) { // CraftBukkit - SPIGOT-4893 - this.setAngry(false); - } - - } - - @Override - public void tick() { - super.tick(); - if (this.isAlive()) { - this.bH = this.bG; - if (this.ei()) { - this.bG += (1.0F - this.bG) * 0.4F; - } else { - this.bG += (0.0F - this.bG) * 0.4F; - } - - if (this.au()) { - this.bI = true; - this.bJ = false; - this.bK = 0.0F; - this.bL = 0.0F; - } else if ((this.bI || this.bJ) && this.bJ) { - if (this.bK == 0.0F) { - this.a(SoundEffects.ENTITY_WOLF_SHAKE, this.getSoundVolume(), (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F); - } - - this.bL = this.bK; - this.bK += 0.05F; - if (this.bL >= 2.0F) { - this.bI = false; - this.bJ = false; - this.bL = 0.0F; - this.bK = 0.0F; - } - - if (this.bK > 0.4F) { - float f = (float) this.getBoundingBox().minY; - int i = (int) (MathHelper.sin((this.bK - 0.4F) * 3.1415927F) * 7.0F); - Vec3D vec3d = this.getMot(); - - for (int j = 0; j < i; ++j) { - float f1 = (this.random.nextFloat() * 2.0F - 1.0F) * this.getWidth() * 0.5F; - float f2 = (this.random.nextFloat() * 2.0F - 1.0F) * this.getWidth() * 0.5F; - - this.world.addParticle(Particles.SPLASH, this.locX + (double) f1, (double) (f + 0.8F), this.locZ + (double) f2, vec3d.x, vec3d.y, vec3d.z); - } - } - } - - } - } - - @Override - public void die(DamageSource damagesource) { - this.bI = false; - this.bJ = false; - this.bL = 0.0F; - this.bK = 0.0F; - super.die(damagesource); - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return entitysize.height * 0.8F; - } - - @Override - public int M() { - return this.isSitting() ? 20 : super.M(); - } - - @Override - public boolean damageEntity(DamageSource damagesource, float f) { - if (this.isInvulnerable(damagesource)) { - return false; - } else { - Entity entity = damagesource.getEntity(); - - if (this.goalSit != null) { - // CraftBukkit - moved into EntityLiving.d(DamageSource, float) - // this.goalSit.setSitting(false); - } - - if (entity != null && !(entity instanceof EntityHuman) && !(entity instanceof EntityArrow)) { - f = (f + 1.0F) / 2.0F; - } - - return super.damageEntity(damagesource, f); - } - } - - @Override - public boolean C(Entity entity) { - boolean flag = entity.damageEntity(DamageSource.mobAttack(this), (float) ((int) this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue())); - - if (flag) { - this.a((EntityLiving) this, entity); - } - - return flag; - } - - @Override - public void setTamed(boolean flag) { - super.setTamed(flag); - if (flag) { - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(20.0D); - } else { - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(8.0D); - } - - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(4.0D); - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - Item item = itemstack.getItem(); - - if (this.isTamed()) { - if (!itemstack.isEmpty()) { - if (item.isFood()) { - if (item.getFoodInfo().c() && (Float) this.datawatcher.get(EntityWolf.DATA_HEALTH) < 20.0F) { - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - this.heal((float) item.getFoodInfo().getNutrition(), org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.EATING); // CraftBukkit - return true; - } - } else if (item instanceof ItemDye) { - EnumColor enumcolor = ((ItemDye) item).d(); - - if (enumcolor != this.getCollarColor()) { - this.setCollarColor(enumcolor); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - return true; - } - } - } - - if (this.h((EntityLiving) entityhuman) && !this.world.isClientSide && !this.i(itemstack)) { - this.goalSit.setSitting(!this.isSitting()); - this.jumping = false; - this.navigation.o(); - this.setGoalTarget((EntityLiving) null, TargetReason.FORGOT_TARGET, true); // CraftBukkit - reason - } - } else if (item == Items.BONE && !this.isAngry()) { - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - if (!this.world.isClientSide) { - // CraftBukkit - added event call and isCancelled check. - if (this.random.nextInt(3) == 0 && !CraftEventFactory.callEntityTameEvent(this, entityhuman).isCancelled()) { - this.tame(entityhuman); - this.navigation.o(); - this.setGoalTarget((EntityLiving) null); - this.goalSit.setSitting(true); - this.setHealth(this.getMaxHealth()); // CraftBukkit - 20.0 -> getMaxHealth() - this.r(true); - this.world.broadcastEntityEffect(this, (byte) 7); - } else { - this.r(false); - this.world.broadcastEntityEffect(this, (byte) 6); - } - } - - return true; - } - - return super.a(entityhuman, enumhand); - } - - @Override - public boolean i(ItemStack itemstack) { - Item item = itemstack.getItem(); - - return item.isFood() && item.getFoodInfo().c(); - } - - @Override - public int dC() { - return 8; - } - - public boolean isAngry() { - return ((Byte) this.datawatcher.get(EntityWolf.bz) & 2) != 0; - } - - public void setAngry(boolean flag) { - byte b0 = (Byte) this.datawatcher.get(EntityWolf.bz); - - if (flag) { - this.datawatcher.set(EntityWolf.bz, (byte) (b0 | 2)); - } else { - this.datawatcher.set(EntityWolf.bz, (byte) (b0 & -3)); - } - - } - - public EnumColor getCollarColor() { - return EnumColor.fromColorIndex((Integer) this.datawatcher.get(EntityWolf.bF)); - } - - public void setCollarColor(EnumColor enumcolor) { - this.datawatcher.set(EntityWolf.bF, enumcolor.getColorIndex()); - } - - @Override - public EntityWolf createChild(EntityAgeable entityageable) { - EntityWolf entitywolf = (EntityWolf) EntityTypes.WOLF.a(this.world); - UUID uuid = this.getOwnerUUID(); - - if (uuid != null) { - entitywolf.setOwnerUUID(uuid); - entitywolf.setTamed(true); - } - - return entitywolf; - } - - public void v(boolean flag) { - this.datawatcher.set(EntityWolf.bE, flag); - } - - @Override - 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() ? false : (entitywolf.isSitting() ? false : this.isInLove() && entitywolf.isInLove()); - } - } - - public boolean ei() { - return (Boolean) this.datawatcher.get(EntityWolf.bE); - } - - @Override - 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) ? false : (entityliving instanceof EntityHorseAbstract && ((EntityHorseAbstract) entityliving).isTamed() ? false : !(entityliving instanceof EntityCat) || !((EntityCat) entityliving).isTamed()); - } else { - return false; - } - } - - @Override - public boolean a(EntityHuman entityhuman) { - return !this.isAngry() && super.a(entityhuman); - } - - class a extends PathfinderGoalAvoidTarget { - - private final EntityWolf j; - - public a(EntityWolf entitywolf, Class oclass, float f, double d0, double d1) { - super(entitywolf, oclass, f, d0, d1); - this.j = entitywolf; - } - - @Override - public boolean a() { - return super.a() && this.b instanceof EntityLlama ? !this.j.isTamed() && this.a((EntityLlama) this.b) : false; - } - - private boolean a(EntityLlama entityllama) { - return entityllama.getStrength() >= EntityWolf.this.random.nextInt(5); - } - - @Override - public void c() { - EntityWolf.this.setGoalTarget((EntityLiving) null); - super.c(); - } - - @Override - public void e() { - EntityWolf.this.setGoalTarget((EntityLiving) null); - super.e(); - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityZombie.java b/src/main/java/net/minecraft/server/EntityZombie.java deleted file mode 100644 index d747d36f8..000000000 --- a/src/main/java/net/minecraft/server/EntityZombie.java +++ /dev/null @@ -1,600 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.types.DynamicOps; -import java.time.LocalDate; -import java.time.temporal.ChronoField; -import java.util.List; -import java.util.UUID; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.entity.Zombie; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.entity.EntityTargetEvent; -import org.bukkit.event.entity.EntityTransformEvent; -// CraftBukkit end - -public class EntityZombie extends EntityMonster { - - protected static final IAttribute d = (new AttributeRanged((IAttribute) null, "zombie.spawnReinforcements", 0.0D, 0.0D, 1.0D)).a("Spawn Reinforcements Chance"); - private static final UUID b = UUID.fromString("B9766B59-9566-4402-BC1F-2EE2A276D836"); - private final AttributeModifier c = new AttributeModifier(EntityZombie.b, "Baby speed boost", world.paperConfig.babyZombieMovementModifier, AttributeModifier.Operation.MULTIPLY_BASE); private final AttributeModifier babyModifier = this.c; // Paper - remove static - Make baby speed configurable - private static final DataWatcherObject bz = DataWatcher.a(EntityZombie.class, DataWatcherRegistry.i); - private static final DataWatcherObject bA = DataWatcher.a(EntityZombie.class, DataWatcherRegistry.b); - public static final DataWatcherObject DROWN_CONVERTING = DataWatcher.a(EntityZombie.class, DataWatcherRegistry.i); - private static final Predicate bC = (enumdifficulty) -> { - return enumdifficulty == EnumDifficulty.HARD; - }; - private final PathfinderGoalBreakDoor bD; - private boolean bE; - private int bF; - public int drownedConversionTime; - private int lastTick = MinecraftServer.currentTick; // CraftBukkit - add field - private boolean shouldBurnInDay = true; // Paper - - public EntityZombie(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.bD = new PathfinderGoalBreakDoor(this, EntityZombie.bC); - } - - public EntityZombie(World world) { - this(EntityTypes.ZOMBIE, world); - } - - @Override - protected void initPathfinder() { - this.goalSelector.a(4, new EntityZombie.a(this, 1.0D, 3)); - this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); - this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); - this.l(); - } - - protected void l() { - this.goalSelector.a(2, new PathfinderGoalZombieAttack(this, 1.0D, false)); - this.goalSelector.a(6, new PathfinderGoalMoveThroughVillage(this, 1.0D, true, 4, this::ed)); - this.goalSelector.a(7, new PathfinderGoalRandomStrollLand(this, 1.0D)); - this.targetSelector.a(1, (new PathfinderGoalHurtByTarget(this, new Class[0])).a(EntityPigZombie.class)); - this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); - if ( world.spigotConfig.zombieAggressiveTowardsVillager ) this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityVillagerAbstract.class, false)); // Spigot - this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); - this.targetSelector.a(5, new PathfinderGoalNearestAttackableTarget<>(this, EntityTurtle.class, 10, true, false, EntityTurtle.bz)); - } - - @Override - protected void initAttributes() { - super.initAttributes(); - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(35.0D); - this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.23000000417232513D); - this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(3.0D); - this.getAttributeInstance(GenericAttributes.ARMOR).setValue(2.0D); - this.getAttributeMap().b(EntityZombie.d).setValue(this.random.nextDouble() * 0.10000000149011612D); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.getDataWatcher().register(EntityZombie.bz, false); - this.getDataWatcher().register(EntityZombie.bA, 0); - this.getDataWatcher().register(EntityZombie.DROWN_CONVERTING, false); - } - - public boolean isDrowning() { return isDrownConverting(); } // Paper - OBFHELPER - public boolean isDrownConverting() { - return (Boolean) this.getDataWatcher().get(EntityZombie.DROWN_CONVERTING); - } - - public boolean ed() { - return this.bE; - } - - public void s(boolean flag) { - if (this.dV()) { - if (this.bE != flag) { - this.bE = flag; - ((Navigation) this.getNavigation()).a(flag); - if (flag) { - this.goalSelector.a(1, this.bD); - } else { - this.goalSelector.a((PathfinderGoal) this.bD); - } - } - } else if (this.bE) { - this.goalSelector.a((PathfinderGoal) this.bD); - this.bE = false; - } - - } - - protected boolean dV() { - return true; - } - - @Override - public boolean isBaby() { - return (Boolean) this.getDataWatcher().get(EntityZombie.bz); - } - - @Override - protected int getExpValue(EntityHuman entityhuman) { - if (this.isBaby()) { - this.f = (int) ((float) this.f * 2.5F); - } - - return super.getExpValue(entityhuman); - } - - public void setBaby(boolean flag) { - this.getDataWatcher().set(EntityZombie.bz, flag); - if (this.world != null && !this.world.isClientSide) { - AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); - - attributeinstance.removeModifier(this.babyModifier); // Paper - if (flag) { - attributeinstance.addModifier(this.babyModifier); // Paper - } - } - - } - - @Override - public void a(DataWatcherObject datawatcherobject) { - if (EntityZombie.bz.equals(datawatcherobject)) { - this.updateSize(); - } - - super.a(datawatcherobject); - } - - protected boolean dY() { - return true; - } - - @Override - public void tick() { - if (!this.world.isClientSide && this.isAlive()) { - if (this.isDrownConverting()) { - // CraftBukkit start - Use wall time instead of ticks for conversion - int elapsedTicks = MinecraftServer.currentTick - this.lastTick; - this.lastTick = MinecraftServer.currentTick; - this.drownedConversionTime -= elapsedTicks; - // CraftBukkit end - if (this.drownedConversionTime < 0) { - this.ea(); - } - } else if (this.dY()) { - if (this.a(TagsFluid.WATER)) { - ++this.bF; - if (this.bF >= 600) { - this.startDrownedConversion(300); - this.lastTick = MinecraftServer.currentTick; // Paper - Make sure this is set at start of process - GH-1887 - } - } else { - this.bF = -1; - } - } - } - - super.tick(); - } - - @Override - public void movementTick() { - if (this.isAlive()) { - boolean flag = this.I_() && this.dS(); - - if (flag) { - ItemStack itemstack = this.getEquipment(EnumItemSlot.HEAD); - - if (!itemstack.isEmpty()) { - if (itemstack.e()) { - itemstack.setDamage(itemstack.getDamage() + this.random.nextInt(2)); - if (itemstack.getDamage() >= itemstack.h()) { - this.c(EnumItemSlot.HEAD); - this.setSlot(EnumItemSlot.HEAD, ItemStack.a); - } - } - - flag = false; - } - - if (flag) { - this.setOnFire(8); - } - } - } - - super.movementTick(); - } - - public void startDrownedConversion(int i) { - this.lastTick = MinecraftServer.currentTick; // CraftBukkit - this.drownedConversionTime = i; - this.getDataWatcher().set(EntityZombie.DROWN_CONVERTING, true); - } - - // Paper start - public void stopDrowning() { - this.drownedConversionTime = -1; - this.getDataWatcher().set(EntityZombie.DROWN_CONVERTING, false); - } - // Paper end - - protected void ea() { - this.b(EntityTypes.DROWNED); - this.world.a((EntityHuman) null, 1040, new BlockPosition(this), 0); - } - - protected void b(EntityTypes entitytypes) { - if (!this.dead) { - EntityZombie entityzombie = (EntityZombie) entitytypes.a(this.world); - - entityzombie.u(this); - entityzombie.setCanPickupLoot(this.canPickupLoot()); - entityzombie.s(entityzombie.dV() && this.ed()); - entityzombie.v(entityzombie.world.getDamageScaler(new BlockPosition(entityzombie)).d()); - entityzombie.setBaby(this.isBaby()); - entityzombie.setNoAI(this.isNoAI()); - EnumItemSlot[] aenumitemslot = EnumItemSlot.values(); - int i = aenumitemslot.length; - - for (int j = 0; j < i; ++j) { - EnumItemSlot enumitemslot = aenumitemslot[j]; - ItemStack itemstack = this.getEquipment(enumitemslot); - - if (!itemstack.isEmpty()) { - entityzombie.setSlot(enumitemslot, itemstack.cloneItemStack()); - entityzombie.a(enumitemslot, this.d(enumitemslot)); - itemstack.setCount(0); - } - } - - if (this.hasCustomName()) { - entityzombie.setCustomName(this.getCustomName()); - entityzombie.setCustomNameVisible(this.getCustomNameVisible()); - } - - // CraftBukkit start - if (CraftEventFactory.callEntityTransformEvent(this, entityzombie, EntityTransformEvent.TransformReason.DROWNED).isCancelled()) { - ((Zombie) getBukkitEntity()).setConversionTime(-1); // SPIGOT-5208: End conversion to stop event spam - return; - } - // CraftBukkit end - if (!new com.destroystokyo.paper.event.entity.EntityTransformedEvent(this.getBukkitEntity(), entityzombie.getBukkitEntity(), com.destroystokyo.paper.event.entity.EntityTransformedEvent.TransformedReason.DROWNED).callEvent()) return; // Paper - this.world.addEntity(entityzombie, CreatureSpawnEvent.SpawnReason.DROWNED); // CraftBukkit - added spawn reason - this.die(); - } - } - - public boolean shouldBurnInDay() { return I_(); } // Paper - OBFHELPER - protected boolean I_() { - return shouldBurnInDay; - } - - // Paper start - public void setShouldBurnInDay(boolean shouldBurnInDay) { - this.shouldBurnInDay = shouldBurnInDay; - } - // Paper end - - @Override - 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) this.random.nextFloat() < this.getAttributeInstance(EntityZombie.d).getValue() && this.world.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING)) { - 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(this.random, 7, 40) * MathHelper.nextInt(this.random, -1, 1); - int j1 = j + MathHelper.nextInt(this.random, 7, 40) * MathHelper.nextInt(this.random, -1, 1); - int k1 = k + MathHelper.nextInt(this.random, 7, 40) * MathHelper.nextInt(this.random, -1, 1); - BlockPosition blockposition = new BlockPosition(i1, j1 - 1, k1); - - if (this.world.getType(blockposition).a((IBlockAccess) this.world, blockposition, (Entity) entityzombie) && this.world.getLightLevel(new BlockPosition(i1, j1, k1)) < 10) { - entityzombie.setPosition((double) i1, (double) j1, (double) k1); - if (!this.world.isPlayerNearby((double) i1, (double) j1, (double) k1, 7.0D) && this.world.i((Entity) entityzombie) && this.world.getCubes(entityzombie) && !this.world.containsLiquid(entityzombie.getBoundingBox())) { - this.world.addEntity(entityzombie, CreatureSpawnEvent.SpawnReason.REINFORCEMENTS); // CraftBukkit - entityzombie.setGoalTarget(entityliving, EntityTargetEvent.TargetReason.REINFORCEMENT_TARGET, true); // CraftBukkit - entityzombie.prepare(this.world, this.world.getDamageScaler(new BlockPosition(entityzombie)), EnumMobSpawn.REINFORCEMENT, (GroupDataEntity) null, (NBTTagCompound) null); - this.getAttributeInstance(EntityZombie.d).addModifier(new AttributeModifier("Zombie reinforcement caller charge", -0.05000000074505806D, AttributeModifier.Operation.ADDITION)); - entityzombie.getAttributeInstance(EntityZombie.d).addModifier(new AttributeModifier("Zombie reinforcement callee charge", -0.05000000074505806D, AttributeModifier.Operation.ADDITION)); - break; - } - } - } - } - - return true; - } else { - return false; - } - } - - @Override - public boolean C(Entity entity) { - boolean flag = super.C(entity); - - if (flag) { - float f = this.world.getDamageScaler(new BlockPosition(this)).b(); - - if (this.getItemInMainHand().isEmpty() && this.isBurning() && this.random.nextFloat() < f * 0.3F) { - // CraftBukkit start - EntityCombustByEntityEvent event = new EntityCombustByEntityEvent(this.getBukkitEntity(), entity.getBukkitEntity(), 2 * (int) f); // PAIL: fixme - this.world.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - entity.setOnFire(event.getDuration(), false); - } - // CraftBukkit end - } - } - - return flag; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_ZOMBIE_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_ZOMBIE_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_ZOMBIE_DEATH; - } - - protected SoundEffect getSoundStep() { - return SoundEffects.ENTITY_ZOMBIE_STEP; - } - - @Override - protected void a(BlockPosition blockposition, IBlockData iblockdata) { - this.a(this.getSoundStep(), 0.15F, 1.0F); - } - - @Override - public EnumMonsterType getMonsterType() { - return EnumMonsterType.UNDEAD; - } - - @Override - protected void a(DifficultyDamageScaler difficultydamagescaler) { - super.a(difficultydamagescaler); - if (this.random.nextFloat() < (this.world.getDifficulty() == EnumDifficulty.HARD ? 0.05F : 0.01F)) { - int i = this.random.nextInt(3); - - if (i == 0) { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.IRON_SWORD)); - } else { - this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.IRON_SHOVEL)); - } - } - - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - if (this.isBaby()) { - nbttagcompound.setBoolean("IsBaby", true); - } - - nbttagcompound.setBoolean("CanBreakDoors", this.ed()); - nbttagcompound.setInt("InWaterTime", this.isInWater() ? this.bF : -1); - nbttagcompound.setInt("DrownedConversionTime", this.isDrownConverting() ? this.drownedConversionTime : -1); - nbttagcompound.setBoolean("Paper.ShouldBurnInDay", shouldBurnInDay); // Paper - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.getBoolean("IsBaby")) { - this.setBaby(true); - } - - this.s(nbttagcompound.getBoolean("CanBreakDoors")); - this.bF = nbttagcompound.getInt("InWaterTime"); - if (nbttagcompound.hasKeyOfType("DrownedConversionTime", 99) && nbttagcompound.getInt("DrownedConversionTime") > -1) { - this.startDrownedConversion(nbttagcompound.getInt("DrownedConversionTime")); - } - // Paper start - if (nbttagcompound.hasKey("Paper.ShouldBurnInDay")) { - shouldBurnInDay = nbttagcompound.getBoolean("Paper.ShouldBurnInDay"); - } - // Paper end - } - - @Override - public void b(EntityLiving entityliving) { - super.b(entityliving); - if ((this.world.getDifficulty() == EnumDifficulty.NORMAL || this.world.getDifficulty() == EnumDifficulty.HARD) && entityliving instanceof EntityVillager) { - if (this.world.getDifficulty() != EnumDifficulty.HARD && this.random.nextBoolean()) { - return; - } - - EntityVillager entityvillager = (EntityVillager) entityliving; - EntityZombieVillager entityzombievillager = (EntityZombieVillager) EntityTypes.ZOMBIE_VILLAGER.a(this.world); - - entityzombievillager.u(entityvillager); - // entityvillager.die(); // CraftBukkit - moved down - entityzombievillager.prepare(this.world, this.world.getDamageScaler(new BlockPosition(entityzombievillager)), EnumMobSpawn.CONVERSION, new EntityZombie.GroupDataZombie(false), (NBTTagCompound) null); - entityzombievillager.setVillagerData(entityvillager.getVillagerData()); - entityzombievillager.a((NBTBase) entityvillager.es().a((DynamicOps) DynamicOpsNBT.a).getValue()); - entityzombievillager.setOffers(entityvillager.getOffers().a()); - entityzombievillager.a(entityvillager.getExperience()); - entityzombievillager.setBaby(entityvillager.isBaby()); - entityzombievillager.setNoAI(entityvillager.isNoAI()); - if (entityvillager.hasCustomName()) { - entityzombievillager.setCustomName(entityvillager.getCustomName()); - entityzombievillager.setCustomNameVisible(entityvillager.getCustomNameVisible()); - } - - // CraftBukkit start - if (CraftEventFactory.callEntityTransformEvent(this, entityzombievillager, EntityTransformEvent.TransformReason.INFECTION).isCancelled()) { - return; - } - if (!new com.destroystokyo.paper.event.entity.EntityTransformedEvent(this.getBukkitEntity(), entityvillager.getBukkitEntity(), com.destroystokyo.paper.event.entity.EntityTransformedEvent.TransformedReason.INFECTED).callEvent()) return; // Paper - entityvillager.die(); // CraftBukkit - from above - this.world.addEntity(entityzombievillager, CreatureSpawnEvent.SpawnReason.INFECTION); // CraftBukkit - add SpawnReason - // CraftBukkit end - this.world.a((EntityHuman) null, 1026, new BlockPosition(this), 0); - } - - } - - @Override - protected float b(EntityPose entitypose, EntitySize entitysize) { - return this.isBaby() ? 0.93F : 1.74F; - } - - @Override - protected boolean g(ItemStack itemstack) { - return itemstack.getItem() == Items.EGG && this.isBaby() && this.isPassenger() ? false : super.g(itemstack); - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - Object object = super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - float f = difficultydamagescaler.d(); - - this.setCanPickupLoot(this.random.nextFloat() < 0.55F * f); - if (object == null) { - object = new EntityZombie.GroupDataZombie(generatoraccess.getRandom().nextFloat() < 0.05F); - } - - if (object instanceof EntityZombie.GroupDataZombie) { - EntityZombie.GroupDataZombie entityzombie_groupdatazombie = (EntityZombie.GroupDataZombie) object; - - if (entityzombie_groupdatazombie.a) { - this.setBaby(true); - if ((double) generatoraccess.getRandom().nextFloat() < 0.05D) { - List list = generatoraccess.a(EntityChicken.class, this.getBoundingBox().grow(5.0D, 3.0D, 5.0D), IEntitySelector.c); - - if (!list.isEmpty()) { - EntityChicken entitychicken = (EntityChicken) list.get(0); - - entitychicken.r(true); - this.startRiding(entitychicken); - } - } else if ((double) generatoraccess.getRandom().nextFloat() < 0.05D) { - EntityChicken entitychicken1 = (EntityChicken) EntityTypes.CHICKEN.a(this.world); - - entitychicken1.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, 0.0F); - entitychicken1.prepare(generatoraccess, difficultydamagescaler, EnumMobSpawn.JOCKEY, (GroupDataEntity) null, (NBTTagCompound) null); - entitychicken1.r(true); - generatoraccess.addEntity(entitychicken1, CreatureSpawnEvent.SpawnReason.MOUNT); // CraftBukkit - this.startRiding(entitychicken1); - } - } - - this.s(this.dV() && this.random.nextFloat() < f * 0.1F); - this.a(difficultydamagescaler); - this.b(difficultydamagescaler); - } - - if (this.getEquipment(EnumItemSlot.HEAD).isEmpty()) { - LocalDate localdate = LocalDate.now(); - int i = localdate.get(ChronoField.DAY_OF_MONTH); - int j = localdate.get(ChronoField.MONTH_OF_YEAR); - - if (j == 10 && i == 31 && this.random.nextFloat() < 0.25F) { - this.setSlot(EnumItemSlot.HEAD, new ItemStack(this.random.nextFloat() < 0.1F ? Blocks.JACK_O_LANTERN : Blocks.CARVED_PUMPKIN)); - this.dropChanceArmor[EnumItemSlot.HEAD.b()] = 0.0F; - } - } - - this.v(f); - return (GroupDataEntity) object; - } - - protected void v(float f) { - this.getAttributeInstance(GenericAttributes.KNOCKBACK_RESISTANCE).addModifier(new AttributeModifier("Random spawn bonus", this.random.nextDouble() * 0.05000000074505806D, AttributeModifier.Operation.ADDITION)); - double d0 = this.random.nextDouble() * 1.5D * (double) f; - - if (d0 > 1.0D) { - this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).addModifier(new AttributeModifier("Random zombie-spawn bonus", d0, AttributeModifier.Operation.MULTIPLY_TOTAL)); - } - - if (this.random.nextFloat() < f * 0.05F) { - this.getAttributeInstance(EntityZombie.d).addModifier(new AttributeModifier("Leader zombie bonus", this.random.nextDouble() * 0.25D + 0.5D, AttributeModifier.Operation.ADDITION)); - this.getAttributeInstance(GenericAttributes.MAX_HEALTH).addModifier(new AttributeModifier("Leader zombie bonus", this.random.nextDouble() * 3.0D + 1.0D, AttributeModifier.Operation.MULTIPLY_TOTAL)); - this.s(this.dV()); - } - - } - - @Override - public double aO() { - return this.isBaby() ? 0.0D : -0.45D; - } - - @Override - protected void dropDeathLoot(DamageSource damagesource, int i, boolean flag) { - super.dropDeathLoot(damagesource, i, flag); - Entity entity = damagesource.getEntity(); - - if (entity instanceof EntityCreeper) { - EntityCreeper entitycreeper = (EntityCreeper) entity; - - if (entitycreeper.canCauseHeadDrop()) { - entitycreeper.setCausedHeadDrop(); - ItemStack itemstack = this.dX(); - - if (!itemstack.isEmpty()) { - this.a(itemstack); - } - } - } - - } - - protected ItemStack dX() { - return new ItemStack(Items.ZOMBIE_HEAD); - } - - class a extends PathfinderGoalRemoveBlock { - - a(EntityCreature entitycreature, double d0, int i) { - super(Blocks.TURTLE_EGG, entitycreature, d0, i); - } - - @Override - public void a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - generatoraccess.playSound((EntityHuman) null, blockposition, SoundEffects.ENTITY_ZOMBIE_DESTROY_EGG, SoundCategory.HOSTILE, 0.5F, 0.9F + EntityZombie.this.random.nextFloat() * 0.2F); - } - - @Override - public void a(World world, BlockPosition blockposition) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.ENTITY_TURTLE_EGG_BREAK, SoundCategory.BLOCKS, 0.7F, 0.9F + world.random.nextFloat() * 0.2F); - } - - @Override - public double h() { - return 1.14D; - } - } - - public class GroupDataZombie implements GroupDataEntity { - - public final boolean a; - - private GroupDataZombie(boolean flag) { - this.a = flag; - } - } -} diff --git a/src/main/java/net/minecraft/server/EntityZombieHusk.java b/src/main/java/net/minecraft/server/EntityZombieHusk.java deleted file mode 100644 index 4c8b2dd09..000000000 --- a/src/main/java/net/minecraft/server/EntityZombieHusk.java +++ /dev/null @@ -1,68 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class EntityZombieHusk extends EntityZombie { - - public EntityZombieHusk(EntityTypes entitytypes, World world) { - super(entitytypes, world); - } - - public static boolean b(EntityTypes entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, Random random) { - return c(entitytypes, generatoraccess, enummobspawn, blockposition, random) && (enummobspawn == EnumMobSpawn.SPAWNER || generatoraccess.f(blockposition)); - } - - @Override - protected boolean I_() { - return false; - } - - @Override - protected SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_HUSK_AMBIENT; - } - - @Override - protected SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_HUSK_HURT; - } - - @Override - protected SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_HUSK_DEATH; - } - - @Override - protected SoundEffect getSoundStep() { - return SoundEffects.ENTITY_HUSK_STEP; - } - - @Override - public boolean C(Entity entity) { - boolean flag = super.C(entity); - - if (flag && this.getItemInMainHand().isEmpty() && entity instanceof EntityLiving) { - float f = this.world.getDamageScaler(new BlockPosition(this)).b(); - - ((EntityLiving) entity).addEffect(new MobEffect(MobEffects.HUNGER, 140 * (int) f), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.ATTACK); // CraftBukkit - } - - return flag; - } - - @Override - protected boolean dY() { - return true; - } - - @Override - protected void ea() { - this.b(EntityTypes.ZOMBIE); - this.world.a((EntityHuman) null, 1041, new BlockPosition(this), 0); - } - - @Override - protected ItemStack dX() { - return ItemStack.a; - } -} diff --git a/src/main/java/net/minecraft/server/EntityZombieVillager.java b/src/main/java/net/minecraft/server/EntityZombieVillager.java deleted file mode 100644 index d2bd3bb31..000000000 --- a/src/main/java/net/minecraft/server/EntityZombieVillager.java +++ /dev/null @@ -1,282 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.UUID; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.entity.ZombieVillager; -import org.bukkit.event.entity.EntityTransformEvent; -// CraftBukkit end - -public class EntityZombieVillager extends EntityZombie implements VillagerDataHolder { - - public static final DataWatcherObject CONVERTING = DataWatcher.a(EntityZombieVillager.class, DataWatcherRegistry.i); - private static final DataWatcherObject c = DataWatcher.a(EntityZombieVillager.class, DataWatcherRegistry.q); - public int conversionTime; - public UUID conversionPlayer; - private NBTBase bB; - private NBTTagCompound bC; - private int bD; - private int lastTick = MinecraftServer.currentTick; // CraftBukkit - add field - - public EntityZombieVillager(EntityTypes entitytypes, World world) { - super(entitytypes, world); - this.setVillagerData(this.getVillagerData().withProfession((VillagerProfession) IRegistry.VILLAGER_PROFESSION.a(this.random))); - } - - @Override - protected void initDatawatcher() { - super.initDatawatcher(); - this.datawatcher.register(EntityZombieVillager.CONVERTING, false); - this.datawatcher.register(EntityZombieVillager.c, new VillagerData(VillagerType.PLAINS, VillagerProfession.NONE, 1)); - } - - @Override - public void b(NBTTagCompound nbttagcompound) { - super.b(nbttagcompound); - nbttagcompound.set("VillagerData", (NBTBase) this.getVillagerData().a(DynamicOpsNBT.a)); - if (this.bC != null) { - nbttagcompound.set("Offers", this.bC); - } - - if (this.bB != null) { - nbttagcompound.set("Gossips", this.bB); - } - - nbttagcompound.setInt("ConversionTime", this.isConverting() ? this.conversionTime : -1); - if (this.conversionPlayer != null) { - nbttagcompound.a("ConversionPlayer", this.conversionPlayer); - } - - nbttagcompound.setInt("Xp", this.bD); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("VillagerData", 10)) { - this.setVillagerData(new VillagerData(new Dynamic(DynamicOpsNBT.a, nbttagcompound.get("VillagerData")))); - } - - if (nbttagcompound.hasKeyOfType("Offers", 10)) { - this.bC = nbttagcompound.getCompound("Offers"); - } - - if (nbttagcompound.hasKeyOfType("Gossips", 10)) { - this.bB = nbttagcompound.getList("Gossips", 10); - } - - if (nbttagcompound.hasKeyOfType("ConversionTime", 99) && nbttagcompound.getInt("ConversionTime") > -1) { - this.startConversion(nbttagcompound.b("ConversionPlayer") ? nbttagcompound.a("ConversionPlayer") : null, nbttagcompound.getInt("ConversionTime")); - } - - if (nbttagcompound.hasKeyOfType("Xp", 3)) { - this.bD = nbttagcompound.getInt("Xp"); - } - - } - - @Override - public void tick() { - if (!this.world.isClientSide && this.isAlive() && this.isConverting()) { - int i = this.getConversionProgress(); - // 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.conversionTime -= i; - if (this.conversionTime <= 0) { - this.a((WorldServer) this.world); - } - } - - super.tick(); - } - - @Override - public boolean a(EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getItem() == Items.GOLDEN_APPLE && this.hasEffect(MobEffects.WEAKNESS)) { - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - if (!this.world.isClientSide) { - this.startConversion(entityhuman.getUniqueID(), this.random.nextInt(2401) + 3600); - } - - return true; - } else { - return false; - } - } - - @Override - protected boolean dY() { - return false; - } - - @Override - public boolean isTypeNotPersistent(double d0) { - return !this.isConverting(); - } - - public boolean isConverting() { - return (Boolean) this.getDataWatcher().get(EntityZombieVillager.CONVERTING); - } - - public void startConversion(@Nullable UUID uuid, int i) { - this.conversionPlayer = uuid; - this.conversionTime = i; - this.getDataWatcher().set(EntityZombieVillager.CONVERTING, true); - // CraftBukkit start - this.persistent = true; // CraftBukkit - SPIGOT-4684 update persistence - this.removeEffect(MobEffects.WEAKNESS, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION); - this.addEffect(new MobEffect(MobEffects.INCREASE_DAMAGE, i, Math.min(this.world.getDifficulty().a() - 1, 0)), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION); - // CraftBukkit end - this.world.broadcastEntityEffect(this, (byte) 16); - } - - private void a(WorldServer worldserver) { - EntityVillager entityvillager = (EntityVillager) EntityTypes.VILLAGER.a((World) worldserver); - - entityvillager.u(this); - entityvillager.setVillagerData(this.getVillagerData()); - if (this.bB != null) { - entityvillager.a(this.bB); - } - - if (this.bC != null) { - entityvillager.b(new MerchantRecipeList(this.bC)); - } - - entityvillager.setExperience(this.bD); - entityvillager.prepare(worldserver, worldserver.getDamageScaler(new BlockPosition(entityvillager)), EnumMobSpawn.CONVERSION, (GroupDataEntity) null, (NBTTagCompound) null); - if (this.isBaby()) { - entityvillager.setAgeRaw(-24000); - } - - // this.die(); // CraftBukkit - moved down - entityvillager.setNoAI(this.isNoAI()); - if (this.hasCustomName()) { - entityvillager.setCustomName(this.getCustomName()); - entityvillager.setCustomNameVisible(this.getCustomNameVisible()); - } - - // CraftBukkit start - if (CraftEventFactory.callEntityTransformEvent(this, entityvillager, EntityTransformEvent.TransformReason.CURED).isCancelled()) { - ((ZombieVillager) getBukkitEntity()).setConversionTime(-1); // SPIGOT-5208: End conversion to stop event spam - return; - } - if (!new com.destroystokyo.paper.event.entity.EntityTransformedEvent(this.getBukkitEntity(), entityvillager.getBukkitEntity(), com.destroystokyo.paper.event.entity.EntityTransformedEvent.TransformedReason.CURED).callEvent()) return; // Paper - this.die(); // CraftBukkit - from above - worldserver.addEntity(entityvillager, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.CURED); // CraftBukkit - add SpawnReason - // CraftBukkit end - if (this.conversionPlayer != null) { - EntityHuman entityhuman = worldserver.b(this.conversionPlayer); - - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.r.a((EntityPlayer) entityhuman, this, entityvillager); - worldserver.a(ReputationEvent.a, (Entity) entityhuman, (ReputationHandler) entityvillager); - } - } - - entityvillager.addEffect(new MobEffect(MobEffects.CONFUSION, 200, 0), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION); // CraftBukkit - worldserver.a((EntityHuman) null, 1027, new BlockPosition(this), 0); - } - - private int getConversionProgress() { - int i = 1; - - if (this.random.nextFloat() < 0.01F) { - int j = 0; - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - 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(blockposition_mutableblockposition.d(k, l, i1)).getBlock(); - - if (block == Blocks.IRON_BARS || block instanceof BlockBed) { - if (this.random.nextFloat() < 0.3F) { - ++i; - } - - ++j; - } - } - } - } - } - - return i; - } - - @Override - protected float cV() { - return this.isBaby() ? (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 2.0F : (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F; - } - - @Override - public SoundEffect getSoundAmbient() { - return SoundEffects.ENTITY_ZOMBIE_VILLAGER_AMBIENT; - } - - @Override - public SoundEffect getSoundHurt(DamageSource damagesource) { - return SoundEffects.ENTITY_ZOMBIE_VILLAGER_HURT; - } - - @Override - public SoundEffect getSoundDeath() { - return SoundEffects.ENTITY_ZOMBIE_VILLAGER_DEATH; - } - - @Override - public SoundEffect getSoundStep() { - return SoundEffects.ENTITY_ZOMBIE_VILLAGER_STEP; - } - - @Override - protected ItemStack dX() { - return ItemStack.a; - } - - public void setOffers(NBTTagCompound nbttagcompound) { - this.bC = nbttagcompound; - } - - public void a(NBTBase nbtbase) { - this.bB = nbtbase; - } - - @Nullable - @Override - public GroupDataEntity prepare(GeneratorAccess generatoraccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) { - this.setVillagerData(this.getVillagerData().withType(VillagerType.a(generatoraccess.getBiome(new BlockPosition(this))))); - return super.prepare(generatoraccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound); - } - - public void setVillagerData(VillagerData villagerdata) { - VillagerData villagerdata1 = this.getVillagerData(); - - if (villagerdata1.getProfession() != villagerdata.getProfession()) { - this.bC = null; - } - - this.datawatcher.set(EntityZombieVillager.c, villagerdata); - } - - @Override - public VillagerData getVillagerData() { - return (VillagerData) this.datawatcher.get(EntityZombieVillager.c); - } - - public void a(int i) { - this.bD = i; - } -} diff --git a/src/main/java/net/minecraft/server/EnumItemSlot.java b/src/main/java/net/minecraft/server/EnumItemSlot.java deleted file mode 100644 index 60b235f16..000000000 --- a/src/main/java/net/minecraft/server/EnumItemSlot.java +++ /dev/null @@ -1,72 +0,0 @@ -package net.minecraft.server; - -public enum EnumItemSlot { - - MAINHAND(EnumItemSlot.Function.HAND, 0, 0, "mainhand"), OFFHAND(EnumItemSlot.Function.HAND, 1, 5, "offhand"), FEET(EnumItemSlot.Function.ARMOR, 0, 1, "feet"), LEGS(EnumItemSlot.Function.ARMOR, 1, 2, "legs"), CHEST(EnumItemSlot.Function.ARMOR, 2, 3, "chest"), HEAD(EnumItemSlot.Function.ARMOR, 3, 4, "head"); - - private final EnumItemSlot.Function g; - private final int h; - private final int i; - private final String j; - - private EnumItemSlot(EnumItemSlot.Function enumitemslot_function, int i, int j, String s) { - this.g = enumitemslot_function; - this.h = i; - this.i = j; - this.j = s; - } - - public EnumItemSlot.Function getType() { return this.a(); } // Paper - OBFHELPER - public EnumItemSlot.Function a() { - return this.g; - } - - public int b() { - return this.h; - } - - public int c() { - return this.i; - } - - public String getSlotName() { - return this.j; - } - - public static EnumItemSlot fromName(String s) { - EnumItemSlot[] aenumitemslot = values(); - int i = aenumitemslot.length; - - for (int j = 0; j < i; ++j) { - EnumItemSlot enumitemslot = aenumitemslot[j]; - - if (enumitemslot.getSlotName().equals(s)) { - return enumitemslot; - } - } - - throw new IllegalArgumentException("Invalid slot '" + s + "'"); - } - - public static EnumItemSlot a(EnumItemSlot.Function enumitemslot_function, int i) { - EnumItemSlot[] aenumitemslot = values(); - int j = aenumitemslot.length; - - for (int k = 0; k < j; ++k) { - EnumItemSlot enumitemslot = aenumitemslot[k]; - - if (enumitemslot.a() == enumitemslot_function && enumitemslot.b() == i) { - return enumitemslot; - } - } - - throw new IllegalArgumentException("Invalid slot '" + enumitemslot_function + "': " + i); - } - - public static enum Function { - - HAND, ARMOR; - - private Function() {} - } -} diff --git a/src/main/java/net/minecraft/server/ExpirableListEntry.java b/src/main/java/net/minecraft/server/ExpirableListEntry.java deleted file mode 100644 index 79b095c05..000000000 --- a/src/main/java/net/minecraft/server/ExpirableListEntry.java +++ /dev/null @@ -1,99 +0,0 @@ -package net.minecraft.server; - -import com.google.gson.JsonObject; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import javax.annotation.Nullable; - -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, @Nullable Date date, @Nullable String s, @Nullable Date date1, @Nullable 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 String getSource() { - return this.c; - } - - public Date getExpires() { - return this.d; - } - - public String getReason() { - return this.e; - } - - public abstract IChatBaseComponent e(); - - @Override - boolean hasExpired() { - return this.d == null ? false : this.d.before(new Date()); - } - - @Override - 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 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/src/main/java/net/minecraft/server/Explosion.java b/src/main/java/net/minecraft/server/Explosion.java deleted file mode 100644 index 8cfdac036..000000000 --- a/src/main/java/net/minecraft/server/Explosion.java +++ /dev/null @@ -1,444 +0,0 @@ -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.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.Location; -import org.bukkit.event.block.BlockExplodeEvent; -// CraftBukkit end - -public class Explosion { - - private final boolean a; - private final Explosion.Effect b; - private final Random c = new Random(); - private final World world; - private final double posX; - private final double posY; - private final double posZ; - public final Entity source; - private final float size; - private DamageSource j; - private final List blocks = Lists.newArrayList(); - private final Map l = Maps.newHashMap(); - public boolean wasCanceled = false; // CraftBukkit - add field - - public Explosion(World world, @Nullable Entity entity, double d0, double d1, double d2, float f, boolean flag, Explosion.Effect explosion_effect) { - this.world = world; - this.source = entity; - this.size = (float) Math.max(f, 0.0); // CraftBukkit - clamp bad values - this.posX = d0; - this.posY = d1; - this.posZ = d2; - this.a = flag; - this.b = explosion_effect; - this.j = DamageSource.explosion(this); - } - - public static float a(Vec3D vec3d, Entity entity) { - AxisAlignedBB axisalignedbb = entity.getBoundingBox(); - double d0 = 1.0D / ((axisalignedbb.maxX - axisalignedbb.minX) * 2.0D + 1.0D); - double d1 = 1.0D / ((axisalignedbb.maxY - axisalignedbb.minY) * 2.0D + 1.0D); - double d2 = 1.0D / ((axisalignedbb.maxZ - axisalignedbb.minZ) * 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) ((double) f + d0)) { - for (float f1 = 0.0F; f1 <= 1.0F; f1 = (float) ((double) f1 + d1)) { - for (float f2 = 0.0F; f2 <= 1.0F; f2 = (float) ((double) f2 + d2)) { - double d5 = MathHelper.d((double) f, axisalignedbb.minX, axisalignedbb.maxX); - double d6 = MathHelper.d((double) f1, axisalignedbb.minY, axisalignedbb.maxY); - double d7 = MathHelper.d((double) f2, axisalignedbb.minZ, axisalignedbb.maxZ); - Vec3D vec3d1 = new Vec3D(d5 + d3, d6, d7 + d4); - - if (entity.world.rayTrace(new RayTrace(vec3d1, vec3d, RayTrace.BlockCollisionOption.OUTLINE, RayTrace.FluidCollisionOption.NONE, entity)).getType() == MovingObjectPosition.EnumMovingObjectType.MISS) { - ++i; - } - - ++j; - } - } - } - - return (float) i / (float) j; - } else { - return 0.0F; - } - } - - public void a() { - // CraftBukkit start - if (this.size < 0.1F) { - return; - } - // CraftBukkit end - Set set = Sets.newHashSet(); - boolean flag = true; - - int i; - int j; - - for (int k = 0; k < 16; ++k) { - for (i = 0; i < 16; ++i) { - for (j = 0; j < 16; ++j) { - if (k == 0 || k == 15 || i == 0 || i == 15 || j == 0 || j == 15) { - double d0 = (double) ((float) k / 15.0F * 2.0F - 1.0F); - double d1 = (double) ((float) i / 15.0F * 2.0F - 1.0F); - double d2 = (double) ((float) j / 15.0F * 2.0F - 1.0F); - double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); - - d0 /= d3; - d1 /= d3; - d2 /= d3; - float f = this.size * (0.7F + this.world.random.nextFloat() * 0.6F); - double d4 = this.posX; - double d5 = this.posY; - double d6 = this.posZ; - - for (float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) { - BlockPosition blockposition = new BlockPosition(d4, d5, d6); - IBlockData iblockdata = this.world.getType(blockposition); - Fluid fluid = this.world.getFluid(blockposition); - - if (!iblockdata.isAir() || !fluid.isEmpty()) { - float f2 = Math.max(iblockdata.getBlock().getDurability(), fluid.l()); - - if (this.source != null) { - f2 = this.source.a(this, this.world, blockposition, iblockdata, fluid, f2); - } - - f -= (f2 + 0.3F) * 0.3F; - } - - if (f > 0.0F && (this.source == null || this.source.a(this, this.world, blockposition, iblockdata, f)) && blockposition.getY() < 256 && blockposition.getY() >= 0) { // CraftBukkit - don't wrap explosions - set.add(blockposition); - } - - d4 += d0 * 0.30000001192092896D; - d5 += d1 * 0.30000001192092896D; - d6 += d2 * 0.30000001192092896D; - } - } - } - } - } - - this.blocks.addAll(set); - float f3 = this.size * 2.0F; - - i = MathHelper.floor(this.posX - (double) f3 - 1.0D); - j = MathHelper.floor(this.posX + (double) f3 + 1.0D); - int l = MathHelper.floor(this.posY - (double) f3 - 1.0D); - int i1 = MathHelper.floor(this.posY + (double) f3 + 1.0D); - int j1 = MathHelper.floor(this.posZ - (double) f3 - 1.0D); - int k1 = MathHelper.floor(this.posZ + (double) f3 + 1.0D); - // Paper start - Fix lag from explosions processing dead entities - List list = this.world.getEntities(this.source, new AxisAlignedBB((double) i, (double) l, (double) j1, (double) j, (double) i1, (double) k1), new com.google.common.base.Predicate() { - @Override - public boolean apply(Entity entity) { - return IEntitySelector.canAITarget().test(entity) && !entity.dead; - } - }); - // Paper end - Vec3D vec3d = new Vec3D(this.posX, this.posY, this.posZ); - - for (int l1 = 0; l1 < list.size(); ++l1) { - Entity entity = (Entity) list.get(l1); - - if (!entity.bS()) { - double d7 = (double) (MathHelper.sqrt(entity.c(new Vec3D(this.posX, this.posY, this.posZ))) / f3); - - if (d7 <= 1.0D) { - double d8 = entity.locX - this.posX; - double d9 = entity.locY + (double) entity.getHeadHeight() - this.posY; - double d10 = entity.locZ - this.posZ; - double d11 = (double) MathHelper.sqrt(d8 * d8 + d9 * d9 + d10 * d10); - - if (d11 != 0.0D) { - d8 /= d11; - d9 /= d11; - d10 /= d11; - double d12 = this.getBlockDensity(vec3d, entity); // Paper - Optimize explosions - double d13 = (1.0D - d7) * d12; - - // CraftBukkit start - // entity.damageEntity(this.b(), (float) ((int) ((d13 * d13 + d13) / 2.0D * 7.0D * (double) f3 + 1.0D))); - CraftEventFactory.entityDamage = source; - entity.forceExplosionKnockback = false; - boolean wasDamaged = entity.damageEntity(this.b(), (float) ((int) ((d13 * d13 + d13) / 2.0D * 7.0D * (double) f3 + 1.0D))); - CraftEventFactory.entityDamage = null; - if (!wasDamaged && !(entity instanceof EntityTNTPrimed || entity instanceof EntityFallingBlock) && !entity.forceExplosionKnockback) { - continue; - } - // CraftBukkit end - double d14 = d13; - - if (entity instanceof EntityLiving) { - d14 = entity instanceof EntityHuman && world.paperConfig.disableExplosionKnockback ? 0 : EnchantmentProtection.a((EntityLiving) entity, d13); // Paper - Disable explosion knockback - } - - entity.setMot(entity.getMot().add(d8 * d14, d9 * d14, d10 * d14)); - if (entity instanceof EntityHuman) { - EntityHuman entityhuman = (EntityHuman) entity; - - if (!entityhuman.isSpectator() && (!entityhuman.isCreative() && !world.paperConfig.disableExplosionKnockback || !entityhuman.abilities.isFlying)) { // Paper - Disable explosion knockback - this.l.put(entityhuman, new Vec3D(d8 * d13, d9 * d13, d10 * d13)); - } - } - } - } - } - } - - } - - public void a(boolean flag) { - this.world.playSound((EntityHuman) null, this.posX, this.posY, this.posZ, SoundEffects.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 4.0F, (1.0F + (this.world.random.nextFloat() - this.world.random.nextFloat()) * 0.2F) * 0.7F); - boolean flag1 = this.b != Explosion.Effect.NONE; - - if (this.size >= 2.0F && flag1) { - this.world.addParticle(Particles.EXPLOSION_EMITTER, this.posX, this.posY, this.posZ, 1.0D, 0.0D, 0.0D); - } else { - this.world.addParticle(Particles.EXPLOSION, this.posX, this.posY, this.posZ, 1.0D, 0.0D, 0.0D); - } - - Iterator iterator; - BlockPosition blockposition; - - if (flag1) { - // CraftBukkit start - org.bukkit.World bworld = this.world.getWorld(); - org.bukkit.entity.Entity explode = this.source == null ? null : this.source.getBukkitEntity(); - Location location = new Location(bworld, this.posX, this.posY, this.posZ); - - List blockList = Lists.newArrayList(); - for (int i1 = this.blocks.size() - 1; i1 >= 0; i1--) { - BlockPosition cpos = (BlockPosition) this.blocks.get(i1); - org.bukkit.block.Block bblock = bworld.getBlockAt(cpos.getX(), cpos.getY(), cpos.getZ()); - if (bblock.getType() != org.bukkit.Material.AIR) { - blockList.add(bblock); - } - } - - boolean cancelled; - List bukkitBlocks; - float yield; - - if (explode != null) { - EntityExplodeEvent event = new EntityExplodeEvent(explode, location, blockList, this.b == Explosion.Effect.DESTROY ? 1.0F / this.size : 1.0F); - this.world.getServer().getPluginManager().callEvent(event); - cancelled = event.isCancelled(); - bukkitBlocks = event.blockList(); - yield = event.getYield(); - } else { - BlockExplodeEvent event = new BlockExplodeEvent(location.getBlock(), blockList, this.b == Explosion.Effect.DESTROY ? 1.0F / this.size : 1.0F); - this.world.getServer().getPluginManager().callEvent(event); - cancelled = event.isCancelled(); - bukkitBlocks = event.blockList(); - yield = event.getYield(); - } - - this.blocks.clear(); - - for (org.bukkit.block.Block bblock : bukkitBlocks) { - BlockPosition coords = new BlockPosition(bblock.getX(), bblock.getY(), bblock.getZ()); - blocks.add(coords); - } - - if (cancelled) { - this.wasCanceled = true; - return; - } - // CraftBukkit end - iterator = this.blocks.iterator(); - - while (iterator.hasNext()) { - blockposition = (BlockPosition) iterator.next(); - IBlockData iblockdata = this.world.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (flag) { - double d0 = (double) ((float) blockposition.getX() + this.world.random.nextFloat()); - double d1 = (double) ((float) blockposition.getY() + this.world.random.nextFloat()); - double d2 = (double) ((float) blockposition.getZ() + this.world.random.nextFloat()); - double d3 = d0 - this.posX; - double d4 = d1 - this.posY; - double d5 = d2 - this.posZ; - double d6 = (double) MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5); - - d3 /= d6; - d4 /= d6; - d5 /= d6; - double d7 = 0.5D / (d6 / (double) this.size + 0.1D); - - d7 *= (double) (this.world.random.nextFloat() * this.world.random.nextFloat() + 0.3F); - d3 *= d7; - d4 *= d7; - d5 *= d7; - this.world.addParticle(Particles.POOF, (d0 + this.posX) / 2.0D, (d1 + this.posY) / 2.0D, (d2 + this.posZ) / 2.0D, d3, d4, d5); - this.world.addParticle(Particles.SMOKE, d0, d1, d2, d3, d4, d5); - } - - if (!iblockdata.isAir()) { - if (block.a(this) && this.world instanceof WorldServer) { - TileEntity tileentity = block.isTileEntity() ? this.world.getTileEntity(blockposition) : null; - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder((WorldServer) this.world)).a(this.world.random).set(LootContextParameters.POSITION, blockposition).set(LootContextParameters.TOOL, ItemStack.a).setOptional(LootContextParameters.BLOCK_ENTITY, tileentity); - - if (this.b == Explosion.Effect.DESTROY || yield < 1.0F) { // CraftBukkit - add yield - loottableinfo_builder.set(LootContextParameters.EXPLOSION_RADIUS, 1.0F / yield); // CraftBukkit - add yield - } - - Block.b(iblockdata, loottableinfo_builder); - } - - this.world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3); - block.wasExploded(this.world, blockposition, this); - } - } - } - - if (this.a) { - iterator = this.blocks.iterator(); - - while (iterator.hasNext()) { - blockposition = (BlockPosition) iterator.next(); - if (this.world.getType(blockposition).isAir() && this.world.getType(blockposition.down()).g(this.world, blockposition.down()) && this.c.nextInt(3) == 0) { - // CraftBukkit start - Ignition by explosion - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(this.world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this).isCancelled()) { - this.world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); - } - // CraftBukkit end - } - } - } - - } - - public DamageSource b() { - return this.j; - } - - public void a(DamageSource damagesource) { - this.j = damagesource; - } - - public Map c() { - return this.l; - } - - @Nullable - public EntityLiving getSource() { - // CraftBukkit start - obtain Fireball shooter for explosion tracking - 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))); - // CraftBukkit end - } - - public void clearBlocks() { - this.blocks.clear(); - } - - public List getBlocks() { - return this.blocks; - } - - public static enum Effect { - - NONE, BREAK, DESTROY; - - private Effect() {} - } - // Paper start - Optimize explosions - private float getBlockDensity(Vec3D vec3d, Entity entity) { - if (!this.world.paperConfig.optimizeExplosions) { - return a(vec3d, entity); - } - CacheKey key = new CacheKey(this, entity.getBoundingBox()); - Float blockDensity = this.world.explosionDensityCache.get(key); - if (blockDensity == null) { - blockDensity = a(vec3d, entity); - this.world.explosionDensityCache.put(key, blockDensity); - } - - return blockDensity; - } - - static class CacheKey { - private final World world; - private final double posX, posY, posZ; - private final double minX, minY, minZ; - private final double maxX, maxY, maxZ; - - public CacheKey(Explosion explosion, AxisAlignedBB aabb) { - this.world = explosion.world; - this.posX = explosion.posX; - this.posY = explosion.posY; - this.posZ = explosion.posZ; - this.minX = aabb.minX; - this.minY = aabb.minY; - this.minZ = aabb.minZ; - this.maxX = aabb.maxX; - this.maxY = aabb.maxY; - this.maxZ = aabb.maxZ; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CacheKey cacheKey = (CacheKey) o; - - if (Double.compare(cacheKey.posX, posX) != 0) return false; - if (Double.compare(cacheKey.posY, posY) != 0) return false; - if (Double.compare(cacheKey.posZ, posZ) != 0) return false; - if (Double.compare(cacheKey.minX, minX) != 0) return false; - if (Double.compare(cacheKey.minY, minY) != 0) return false; - if (Double.compare(cacheKey.minZ, minZ) != 0) return false; - if (Double.compare(cacheKey.maxX, maxX) != 0) return false; - if (Double.compare(cacheKey.maxY, maxY) != 0) return false; - if (Double.compare(cacheKey.maxZ, maxZ) != 0) return false; - return world.equals(cacheKey.world); - } - - @Override - public int hashCode() { - int result; - long temp; - result = world.hashCode(); - temp = Double.doubleToLongBits(posX); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(posY); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(posZ); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(minX); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(minY); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(minZ); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(maxX); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(maxY); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(maxZ); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - return result; - } - } - // Paper end -} diff --git a/src/main/java/net/minecraft/server/FluidTypeFlowing.java b/src/main/java/net/minecraft/server/FluidTypeFlowing.java deleted file mode 100644 index 4660b9538..000000000 --- a/src/main/java/net/minecraft/server/FluidTypeFlowing.java +++ /dev/null @@ -1,535 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.mojang.datafixers.util.Pair; -import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; -import it.unimi.dsi.fastutil.shorts.Short2BooleanMap; -import it.unimi.dsi.fastutil.shorts.Short2BooleanOpenHashMap; -import it.unimi.dsi.fastutil.shorts.Short2ObjectMap; -import it.unimi.dsi.fastutil.shorts.Short2ObjectOpenHashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -// CraftBukkit start -import org.bukkit.block.BlockFace; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.block.FluidLevelChangeEvent; -// CraftBukkit end - -public abstract class FluidTypeFlowing extends FluidType { - - public static final BlockStateBoolean FALLING = BlockProperties.i; - public static final BlockStateInteger LEVEL = BlockProperties.an; - private static final ThreadLocal> e = ThreadLocal.withInitial(() -> { - Object2ByteLinkedOpenHashMap object2bytelinkedopenhashmap = new Object2ByteLinkedOpenHashMap(200) { - protected void rehash(int i) {} - }; - - object2bytelinkedopenhashmap.defaultReturnValue((byte) 127); - return object2bytelinkedopenhashmap; - }); - private final Map f = Maps.newIdentityHashMap(); - - public FluidTypeFlowing() {} - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - blockstatelist_a.a(FluidTypeFlowing.FALLING); - } - - @Override - public Vec3D a(IBlockAccess iblockaccess, BlockPosition blockposition, Fluid fluid) { - double d0 = 0.0D; - double d1 = 0.0D; - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - Vec3D vec3d; - - try { - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - - blockposition_pooledblockposition.g(blockposition).c(enumdirection); - Fluid fluid1 = iblockaccess.getFluid(blockposition_pooledblockposition); - - if (this.g(fluid1)) { - float f = fluid1.f(); - float f1 = 0.0F; - - if (f == 0.0F) { - if (!iblockaccess.getType(blockposition_pooledblockposition).getMaterial().isSolid()) { - BlockPosition blockposition1 = blockposition_pooledblockposition.down(); - Fluid fluid2 = iblockaccess.getFluid(blockposition1); - - if (this.g(fluid2)) { - f = fluid2.f(); - if (f > 0.0F) { - f1 = fluid.f() - (f - 0.8888889F); - } - } - } - } else if (f > 0.0F) { - f1 = fluid.f() - f; - } - - if (f1 != 0.0F) { - d0 += (double) ((float) enumdirection.getAdjacentX() * f1); - d1 += (double) ((float) enumdirection.getAdjacentZ() * f1); - } - } - } - - Vec3D vec3d1 = new Vec3D(d0, 0.0D, d1); - - if ((Boolean) fluid.get(FluidTypeFlowing.FALLING)) { - Iterator iterator1 = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator1.hasNext()) { - EnumDirection enumdirection1 = (EnumDirection) iterator1.next(); - - blockposition_pooledblockposition.g(blockposition).c(enumdirection1); - if (this.a(iblockaccess, (BlockPosition) blockposition_pooledblockposition, enumdirection1) || this.a(iblockaccess, blockposition_pooledblockposition.up(), enumdirection1)) { - vec3d1 = vec3d1.d().add(0.0D, -6.0D, 0.0D); - break; - } - } - } - - vec3d = vec3d1.d(); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - - return vec3d; - } - - private boolean g(Fluid fluid) { - return fluid.isEmpty() || fluid.getType().a((FluidType) this); - } - - protected boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - IBlockData iblockdata = iblockaccess.getType(blockposition); - Fluid fluid = iblockaccess.getFluid(blockposition); - - return fluid.getType().a((FluidType) this) ? false : (enumdirection == EnumDirection.UP ? true : (iblockdata.getMaterial() == Material.ICE ? false : iblockdata.d(iblockaccess, blockposition, enumdirection))); - } - - protected void a(GeneratorAccess generatoraccess, BlockPosition blockposition, Fluid fluid) { - if (!fluid.isEmpty()) { - IBlockData iblockdata = generatoraccess.getType(blockposition); - BlockPosition blockposition1 = blockposition.down(); - IBlockData iblockdata1 = generatoraccess.getType(blockposition1); - Fluid fluid1 = this.a((IWorldReader) generatoraccess, blockposition1, iblockdata1); - - if (this.a(generatoraccess, blockposition, iblockdata, EnumDirection.DOWN, blockposition1, iblockdata1, generatoraccess.getFluid(blockposition1), fluid1.getType())) { - // CraftBukkit start - org.bukkit.block.Block source = CraftBlock.at(generatoraccess, blockposition); - BlockFromToEvent event = new BlockFromToEvent(source, BlockFace.DOWN); - generatoraccess.getMinecraftWorld().getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - // CraftBukkit end - this.a(generatoraccess, blockposition1, iblockdata1, EnumDirection.DOWN, fluid1); - if (this.a((IWorldReader) generatoraccess, blockposition) >= 3) { - this.a(generatoraccess, blockposition, fluid, iblockdata); - } - } else if (fluid.isSource() || !this.a((IBlockAccess) generatoraccess, fluid1.getType(), blockposition, iblockdata, blockposition1, iblockdata1)) { - this.a(generatoraccess, blockposition, fluid, iblockdata); - } - - } - } - - private void a(GeneratorAccess generatoraccess, BlockPosition blockposition, Fluid fluid, IBlockData iblockdata) { - int i = fluid.g() - this.c((IWorldReader) generatoraccess); - - if ((Boolean) fluid.get(FluidTypeFlowing.FALLING)) { - i = 7; - } - - if (i > 0) { - Map map = this.b((IWorldReader) generatoraccess, blockposition, iblockdata); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - EnumDirection enumdirection = (EnumDirection) entry.getKey(); - Fluid fluid1 = (Fluid) entry.getValue(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - IBlockData iblockdata1 = generatoraccess.getTypeIfLoaded(blockposition1); // Paper - if (iblockdata1 == null) continue; // Paper - - if (this.a(generatoraccess, blockposition, iblockdata, enumdirection, blockposition1, iblockdata1, generatoraccess.getFluid(blockposition1), fluid1.getType())) { - // CraftBukkit start - org.bukkit.block.Block source = CraftBlock.at(generatoraccess, blockposition); - BlockFromToEvent event = new BlockFromToEvent(source, org.bukkit.craftbukkit.block.CraftBlock.notchToBlockFace(enumdirection)); - generatoraccess.getMinecraftWorld().getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - continue; - } - // CraftBukkit end - this.a(generatoraccess, blockposition1, iblockdata1, enumdirection, fluid1); - } - } - - } - } - - protected Fluid a(IWorldReader iworldreader, BlockPosition blockposition, IBlockData iblockdata) { - int i = 0; - int j = 0; - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - IBlockData iblockdata1 = iworldreader.getTypeIfLoaded(blockposition1); // Paper - if (iblockdata1 == null) continue; // Paper - Fluid fluid = iblockdata1.p(); - - if (fluid.getType().a((FluidType) this) && this.a(enumdirection, (IBlockAccess) iworldreader, blockposition, iblockdata, blockposition1, iblockdata1)) { - if (fluid.isSource()) { - ++j; - } - - i = Math.max(i, fluid.g()); - } - } - - if (this.g() && j >= 2) { - IBlockData iblockdata2 = iworldreader.getType(blockposition.down()); - Fluid fluid1 = iblockdata2.p(); - - if (iblockdata2.getMaterial().isBuildable() || this.h(fluid1)) { - return this.a(false); - } - } - - BlockPosition blockposition2 = blockposition.up(); - IBlockData iblockdata3 = iworldreader.getType(blockposition2); - Fluid fluid2 = iblockdata3.p(); - - if (!fluid2.isEmpty() && fluid2.getType().a((FluidType) this) && this.a(EnumDirection.UP, (IBlockAccess) iworldreader, blockposition, iblockdata, blockposition2, iblockdata3)) { - return this.a(8, true); - } else { - int k = i - this.c(iworldreader); - - return k <= 0 ? FluidTypes.EMPTY.i() : this.a(k, false); - } - } - - private boolean a(EnumDirection enumdirection, IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, BlockPosition blockposition1, IBlockData iblockdata1) { - Object2ByteLinkedOpenHashMap object2bytelinkedopenhashmap; - - if (!iblockdata.getBlock().p() && !iblockdata1.getBlock().p()) { - object2bytelinkedopenhashmap = (Object2ByteLinkedOpenHashMap) FluidTypeFlowing.e.get(); - } else { - object2bytelinkedopenhashmap = null; - } - - Block.a block_a; - - if (object2bytelinkedopenhashmap != null) { - block_a = new Block.a(iblockdata, iblockdata1, enumdirection); - byte b0 = object2bytelinkedopenhashmap.getAndMoveToFirst(block_a); - - if (b0 != 127) { - return b0 != 0; - } - } else { - block_a = null; - } - - VoxelShape voxelshape = iblockdata.getCollisionShape(iblockaccess, blockposition); - VoxelShape voxelshape1 = iblockdata1.getCollisionShape(iblockaccess, blockposition1); - boolean flag = !VoxelShapes.b(voxelshape, voxelshape1, enumdirection); - - if (object2bytelinkedopenhashmap != null) { - if (object2bytelinkedopenhashmap.size() == 200) { - object2bytelinkedopenhashmap.removeLastByte(); - } - - object2bytelinkedopenhashmap.putAndMoveToFirst(block_a, (byte) (flag ? 1 : 0)); - } - - return flag; - } - - public abstract FluidType e(); - - public Fluid a(int i, boolean flag) { - return (Fluid) ((Fluid) this.e().i().set(FluidTypeFlowing.LEVEL, i)).set(FluidTypeFlowing.FALLING, flag); - } - - public abstract FluidType f(); - - public Fluid a(boolean flag) { - return (Fluid) this.f().i().set(FluidTypeFlowing.FALLING, flag); - } - - protected abstract boolean g(); - - protected void a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection, Fluid fluid) { - if (iblockdata.getBlock() instanceof IFluidContainer) { - ((IFluidContainer) iblockdata.getBlock()).place(generatoraccess, blockposition, iblockdata, fluid); - } else { - if (!iblockdata.isAir()) { - this.a(generatoraccess, blockposition, iblockdata); - } - - generatoraccess.setTypeAndData(blockposition, fluid.getBlockData(), 3); - } - - } - - protected abstract void a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata); - - private static short a(BlockPosition blockposition, BlockPosition blockposition1) { - int i = blockposition1.getX() - blockposition.getX(); - int j = blockposition1.getZ() - blockposition.getZ(); - - return (short) ((i + 128 & 255) << 8 | j + 128 & 255); - } - - protected int a(IWorldReader iworldreader, BlockPosition blockposition, int i, EnumDirection enumdirection, IBlockData iblockdata, BlockPosition blockposition1, Short2ObjectMap> short2objectmap, Short2BooleanMap short2booleanmap) { - int j = 1000; - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection1 = (EnumDirection) iterator.next(); - - if (enumdirection1 != enumdirection) { - BlockPosition blockposition2 = blockposition.shift(enumdirection1); - short short0 = a(blockposition1, blockposition2); - // Paper start - avoid loading chunks - Pair pair = short2objectmap.get(short0); - if (pair == null) { - IBlockData iblockdatax = iworldreader.getTypeIfLoaded(blockposition2); - if (iblockdatax == null) { - continue; - } - - pair = Pair.of(iblockdatax, iblockdatax.p()); - short2objectmap.put(short0, pair); - - } - // Paper end - IBlockData iblockdata1 = (IBlockData) pair.getFirst(); - Fluid fluid = (Fluid) pair.getSecond(); - - if (this.a(iworldreader, this.e(), blockposition, iblockdata, enumdirection1, blockposition2, iblockdata1, fluid)) { - boolean flag = short2booleanmap.computeIfAbsent(short0, (k) -> { - BlockPosition blockposition3 = blockposition2.down(); - IBlockData iblockdata2 = iworldreader.getType(blockposition3); - - return this.a((IBlockAccess) iworldreader, this.e(), blockposition2, iblockdata1, blockposition3, iblockdata2); - }); - - if (flag) { - return i; - } - - if (i < this.b(iworldreader)) { - int k = this.a(iworldreader, blockposition2, i + 1, enumdirection1.opposite(), iblockdata1, blockposition1, short2objectmap, short2booleanmap); - - if (k < j) { - j = k; - } - } - } - } - } - - return j; - } - - private boolean a(IBlockAccess iblockaccess, FluidType fluidtype, BlockPosition blockposition, IBlockData iblockdata, BlockPosition blockposition1, IBlockData iblockdata1) { - return !this.a(EnumDirection.DOWN, iblockaccess, blockposition, iblockdata, blockposition1, iblockdata1) ? false : (iblockdata1.p().getType().a((FluidType) this) ? true : this.a(iblockaccess, blockposition1, iblockdata1, fluidtype)); - } - - private boolean a(IBlockAccess iblockaccess, FluidType fluidtype, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection, BlockPosition blockposition1, IBlockData iblockdata1, Fluid fluid) { - return !this.h(fluid) && this.a(enumdirection, iblockaccess, blockposition, iblockdata, blockposition1, iblockdata1) && this.a(iblockaccess, blockposition1, iblockdata1, fluidtype); - } - - private boolean h(Fluid fluid) { - return fluid.getType().a((FluidType) this) && fluid.isSource(); - } - - protected abstract int b(IWorldReader iworldreader); - - private int a(IWorldReader iworldreader, BlockPosition blockposition) { - int i = 0; - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - Fluid fluid = iworldreader.getFluid(blockposition1); - - if (this.h(fluid)) { - ++i; - } - } - - return i; - } - - protected Map b(IWorldReader iworldreader, BlockPosition blockposition, IBlockData iblockdata) { - int i = 1000; - Map map = Maps.newEnumMap(EnumDirection.class); - Short2ObjectMap> short2objectmap = new Short2ObjectOpenHashMap(); - Short2BooleanOpenHashMap short2booleanopenhashmap = new Short2BooleanOpenHashMap(); - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - short short0 = a(blockposition, blockposition1); - // Paper start - Pair pair = (Pair) short2objectmap.get(short0); - if (pair == null) { - IBlockData iblockdatax = iworldreader.getTypeIfLoaded(blockposition1); - if (iblockdatax == null) continue; - - pair = Pair.of(iblockdatax, iblockdatax.p()); - short2objectmap.put(short0, pair); - } - // Paper end - IBlockData iblockdata1 = (IBlockData) pair.getFirst(); - Fluid fluid = (Fluid) pair.getSecond(); - Fluid fluid1 = this.a(iworldreader, blockposition1, iblockdata1); - - if (this.a(iworldreader, fluid1.getType(), blockposition, iblockdata, enumdirection, blockposition1, iblockdata1, fluid)) { - BlockPosition blockposition2 = blockposition1.down(); - boolean flag = short2booleanopenhashmap.computeIfAbsent(short0, (j) -> { - IBlockData iblockdata2 = iworldreader.getType(blockposition2); - - return this.a((IBlockAccess) iworldreader, this.e(), blockposition1, iblockdata1, blockposition2, iblockdata2); - }); - int j; - - if (flag) { - j = 0; - } else { - j = this.a(iworldreader, blockposition1, 1, enumdirection.opposite(), iblockdata1, blockposition, short2objectmap, short2booleanopenhashmap); - } - - if (j < i) { - map.clear(); - } - - if (j <= i) { - map.put(enumdirection, fluid1); - i = j; - } - } - } - - return map; - } - - private boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, FluidType fluidtype) { - Block block = iblockdata.getBlock(); - - if (block instanceof IFluidContainer) { - return ((IFluidContainer) block).canPlace(iblockaccess, blockposition, iblockdata, fluidtype); - } else if (!(block instanceof BlockDoor) && !block.a(TagsBlock.SIGNS) && block != Blocks.LADDER && block != Blocks.SUGAR_CANE && block != Blocks.BUBBLE_COLUMN) { - Material material = iblockdata.getMaterial(); - - return material != Material.PORTAL && material != Material.STRUCTURE_VOID && material != Material.WATER_PLANT && material != Material.REPLACEABLE_WATER_PLANT ? !material.isSolid() : false; - } else { - return false; - } - } - - protected boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection, BlockPosition blockposition1, IBlockData iblockdata1, Fluid fluid, FluidType fluidtype) { - return fluid.a(iblockaccess, blockposition1, fluidtype, enumdirection) && this.a(enumdirection, iblockaccess, blockposition, iblockdata, blockposition1, iblockdata1) && this.a(iblockaccess, blockposition1, iblockdata1, fluidtype); - } - - protected abstract int c(IWorldReader iworldreader); - - protected int a(World world, BlockPosition blockposition, Fluid fluid, Fluid fluid1) { - return this.a((IWorldReader) world); - } - - @Override - public void a(World world, BlockPosition blockposition, Fluid fluid) { - if (!fluid.isSource()) { - Fluid fluid1 = this.a((IWorldReader) world, blockposition, world.getType(blockposition)); - int i = this.a(world, blockposition, fluid, fluid1); - - if (fluid1.isEmpty()) { - fluid = fluid1; - // CraftBukkit start - FluidLevelChangeEvent event = CraftEventFactory.callFluidLevelChangeEvent(world, blockposition, Blocks.AIR.getBlockData()); - if (event.isCancelled()) { - return; - } - world.setTypeAndData(blockposition, ((CraftBlockData) event.getNewData()).getState(), 3); - // CraftBukkit end - } else if (!fluid1.equals(fluid)) { - fluid = fluid1; - IBlockData iblockdata = fluid1.getBlockData(); - // CraftBukkit start - FluidLevelChangeEvent event = CraftEventFactory.callFluidLevelChangeEvent(world, blockposition, iblockdata); - if (event.isCancelled()) { - return; - } - world.setTypeAndData(blockposition, ((CraftBlockData) event.getNewData()).getState(), 2); - // CraftBukkit end - world.getFluidTickList().a(blockposition, fluid1.getType(), i); - world.applyPhysics(blockposition, iblockdata.getBlock()); - } - } - - this.a((GeneratorAccess) world, blockposition, fluid); - } - - protected static int e(Fluid fluid) { - return fluid.isSource() ? 0 : 8 - Math.min(fluid.g(), 8) + ((Boolean) fluid.get(FluidTypeFlowing.FALLING) ? 8 : 0); - } - - private static boolean c(Fluid fluid, IBlockAccess iblockaccess, BlockPosition blockposition) { - return fluid.getType().a(iblockaccess.getFluid(blockposition.up()).getType()); - } - - @Override - public float a(Fluid fluid, IBlockAccess iblockaccess, BlockPosition blockposition) { - return c(fluid, iblockaccess, blockposition) ? 1.0F : fluid.f(); - } - - @Override - public float a(Fluid fluid) { - return (float) fluid.g() / 9.0F; - } - - @Override - public VoxelShape b(Fluid fluid, IBlockAccess iblockaccess, BlockPosition blockposition) { - return fluid.g() == 9 && c(fluid, iblockaccess, blockposition) ? VoxelShapes.b() : (VoxelShape) this.f.computeIfAbsent(fluid, (fluid1) -> { - return VoxelShapes.create(0.0D, 0.0D, 0.0D, 1.0D, (double) fluid1.getHeight(iblockaccess, blockposition), 1.0D); - }); - } -} diff --git a/src/main/java/net/minecraft/server/FluidTypeLava.java b/src/main/java/net/minecraft/server/FluidTypeLava.java deleted file mode 100644 index ff677c59e..000000000 --- a/src/main/java/net/minecraft/server/FluidTypeLava.java +++ /dev/null @@ -1,222 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public abstract class FluidTypeLava extends FluidTypeFlowing { - - public FluidTypeLava() {} - - @Override - public FluidType e() { - return FluidTypes.FLOWING_LAVA; - } - - @Override - public FluidType f() { - return FluidTypes.LAVA; - } - - @Override - public Item b() { - return Items.LAVA_BUCKET; - } - - @Override - public void b(World world, BlockPosition blockposition, Fluid fluid, Random random) { - if (world.getGameRules().getBoolean(GameRules.DO_FIRE_TICK)) { - int i = random.nextInt(3); - - if (i > 0) { - BlockPosition blockposition1 = blockposition; - - for (int j = 0; j < i; ++j) { - blockposition1 = blockposition1.b(random.nextInt(3) - 1, 1, random.nextInt(3) - 1); - if (!world.n(blockposition1)) { - return; - } - - IBlockData iblockdata = world.getType(blockposition1); - - if (iblockdata.isAir()) { - if (this.a((IWorldReader) world, blockposition1)) { - // CraftBukkit start - Prevent lava putting something on fire - if (world.getType(blockposition1).getBlock() != Blocks.FIRE) { - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition1, blockposition).isCancelled()) { - continue; - } - } - // CraftBukkit end - world.setTypeUpdate(blockposition1, Blocks.FIRE.getBlockData()); - return; - } - } else if (iblockdata.getMaterial().isSolid()) { - return; - } - } - } else { - for (int k = 0; k < 3; ++k) { - BlockPosition blockposition2 = blockposition.b(random.nextInt(3) - 1, 0, random.nextInt(3) - 1); - - if (!world.n(blockposition2)) { - return; - } - - if (world.isEmpty(blockposition2.up()) && this.b(world, blockposition2)) { - // CraftBukkit start - Prevent lava putting something on fire - BlockPosition up = blockposition2.up(); - if (world.getType(up).getBlock() != Blocks.FIRE) { - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, up, blockposition).isCancelled()) { - continue; - } - } - // CraftBukkit end - world.setTypeUpdate(blockposition2.up(), Blocks.FIRE.getBlockData()); - } - } - } - - } - } - - private boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - EnumDirection[] aenumdirection = EnumDirection.values(); - int i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - if (this.b(iworldreader, blockposition.shift(enumdirection))) { - return true; - } - } - - return false; - } - - private boolean b(IWorldReader iworldreader, BlockPosition blockposition) { - return blockposition.getY() >= 0 && blockposition.getY() < 256 && !iworldreader.isLoaded(blockposition) ? false : iworldreader.getType(blockposition).getMaterial().isBurnable(); - } - - @Override - protected void a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata) { - this.a(generatoraccess, blockposition); - } - - @Override - public int b(IWorldReader iworldreader) { - return iworldreader.getWorldProvider().isNether() ? 4 : 2; - } - - @Override - public IBlockData b(Fluid fluid) { - return (IBlockData) Blocks.LAVA.getBlockData().set(BlockFluids.LEVEL, e(fluid)); - } - - @Override - public boolean a(FluidType fluidtype) { - return fluidtype == FluidTypes.LAVA || fluidtype == FluidTypes.FLOWING_LAVA; - } - - @Override - public int c(IWorldReader iworldreader) { - return iworldreader.getWorldProvider().isNether() ? 1 : 2; - } - - @Override - public boolean a(Fluid fluid, IBlockAccess iblockaccess, BlockPosition blockposition, FluidType fluidtype, EnumDirection enumdirection) { - return fluid.getHeight(iblockaccess, blockposition) >= 0.44444445F && fluidtype.a(TagsFluid.WATER); - } - - @Override - public int a(IWorldReader iworldreader) { - return iworldreader.getWorldProvider().h() ? 10 : 30; - } - - @Override - public int a(World world, BlockPosition blockposition, Fluid fluid, Fluid fluid1) { - int i = this.a((IWorldReader) world); - - if (!fluid.isEmpty() && !fluid1.isEmpty() && !(Boolean) fluid.get(FluidTypeLava.FALLING) && !(Boolean) fluid1.get(FluidTypeLava.FALLING) && fluid1.getHeight(world, blockposition) > fluid.getHeight(world, blockposition) && world.getRandom().nextInt(4) != 0) { - i *= 4; - } - - return i; - } - - private void a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - generatoraccess.triggerEffect(1501, blockposition, 0); - } - - @Override - protected boolean g() { - return false; - } - - @Override - protected void a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection, Fluid fluid) { - if (enumdirection == EnumDirection.DOWN) { - Fluid fluid1 = generatoraccess.getFluid(blockposition); - - if (this.a(TagsFluid.LAVA) && fluid1.a(TagsFluid.WATER)) { - if (iblockdata.getBlock() instanceof BlockFluids) { - // CraftBukkit start - if (!org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(generatoraccess.getMinecraftWorld(), blockposition, Blocks.STONE.getBlockData(), 3)) { - return; - } - // CraftBukkit end - } - - this.a(generatoraccess, blockposition); - return; - } - } - - super.a(generatoraccess, blockposition, iblockdata, enumdirection, fluid); - } - - @Override - protected boolean k() { - return true; - } - - @Override - protected float d() { - return 100.0F; - } - - public static class a extends FluidTypeLava { - - public a() {} - - @Override - protected void a(BlockStateList.a blockstatelist_a) { - super.a(blockstatelist_a); - blockstatelist_a.a(FluidTypeLava.a.LEVEL); - } - - @Override - public int d(Fluid fluid) { - return (Integer) fluid.get(FluidTypeLava.a.LEVEL); - } - - @Override - public boolean c(Fluid fluid) { - return false; - } - } - - public static class b extends FluidTypeLava { - - public b() {} - - @Override - public int d(Fluid fluid) { - return 8; - } - - @Override - public boolean c(Fluid fluid) { - return true; - } - } -} diff --git a/src/main/java/net/minecraft/server/FoodMetaData.java b/src/main/java/net/minecraft/server/FoodMetaData.java deleted file mode 100644 index ea4041190..000000000 --- a/src/main/java/net/minecraft/server/FoodMetaData.java +++ /dev/null @@ -1,134 +0,0 @@ -package net.minecraft.server; - -public class FoodMetaData { - - public int foodLevel = 20; - public float saturationLevel = 5.0F; - public float exhaustionLevel; - private int foodTickTimer; - private EntityHuman entityhuman; // CraftBukkit - private int e = 20; - - 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(Item item, ItemStack itemstack) { - if (item.isFood()) { - FoodInfo foodinfo = item.getFoodInfo(); - // CraftBukkit start - int oldFoodLevel = foodLevel; - - org.bukkit.event.entity.FoodLevelChangeEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callFoodLevelChangeEvent(entityhuman, foodinfo.getNutrition() + oldFoodLevel, itemstack); - - if (!event.isCancelled()) { - this.eat(event.getFoodLevel() - oldFoodLevel, foodinfo.getSaturationModifier()); - } - - ((EntityPlayer) entityhuman).getBukkitEntity().sendHealthUpdate(); - // CraftBukkit end - } - - } - - public void a(EntityHuman entityhuman) { - EnumDifficulty enumdifficulty = entityhuman.world.getDifficulty(); - - this.e = this.foodLevel; - 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(); - } - - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutUpdateHealth(((EntityPlayer) entityhuman).getBukkitEntity().getScaledHealth(), this.foodLevel, this.saturationLevel)); - // CraftBukkit end - } - } - - boolean flag = entityhuman.world.getGameRules().getBoolean(GameRules.NATURAL_REGENERATION); - - if (flag && this.saturationLevel > 0.0F && entityhuman.dP() && this.foodLevel >= 20) { - ++this.foodTickTimer; - if (this.foodTickTimer >= 10) { - float f = Math.min(this.saturationLevel, 6.0F); - - entityhuman.heal(f / 6.0F, org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.SATIATED, true); // CraftBukkit - added RegainReason // Paper - This is fast regen - this.a(f); - this.foodTickTimer = 0; - } - } else if (flag && this.foodLevel >= 18 && entityhuman.dP()) { - ++this.foodTickTimer; - if (this.foodTickTimer >= 80) { - entityhuman.heal(1.0F, org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.SATIATED); // CraftBukkit - added RegainReason - 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/src/main/java/net/minecraft/server/FurnaceRecipe.java b/src/main/java/net/minecraft/server/FurnaceRecipe.java deleted file mode 100644 index 0b15f2530..000000000 --- a/src/main/java/net/minecraft/server/FurnaceRecipe.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import java.util.ArrayList; -import java.util.List; -import org.bukkit.craftbukkit.inventory.CraftFurnaceRecipe; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftRecipe; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.Recipe; -// CraftBukkit end - -public class FurnaceRecipe extends RecipeCooking { - - public FurnaceRecipe(MinecraftKey minecraftkey, String s, RecipeItemStack recipeitemstack, ItemStack itemstack, float f, int i) { - super(Recipes.SMELTING, minecraftkey, s, recipeitemstack, itemstack, f, i); - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.p; - } - - @Override - public Recipe toBukkitRecipe() { - CraftItemStack result = CraftItemStack.asCraftMirror(this.result); - - CraftFurnaceRecipe recipe = new CraftFurnaceRecipe(CraftNamespacedKey.fromMinecraft(this.key), result, CraftRecipe.toBukkit(this.ingredient), this.experience, this.cookingTime); - recipe.setGroup(this.group); - - return recipe; - } -} diff --git a/src/main/java/net/minecraft/server/GameProfileBanEntry.java b/src/main/java/net/minecraft/server/GameProfileBanEntry.java deleted file mode 100644 index 120c71766..000000000 --- a/src/main/java/net/minecraft/server/GameProfileBanEntry.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.minecraft.server; - -import com.google.gson.JsonObject; -import com.mojang.authlib.GameProfile; -import java.util.Date; -import java.util.Objects; -import java.util.UUID; -import javax.annotation.Nullable; - -public class GameProfileBanEntry extends ExpirableListEntry { - - public GameProfileBanEntry(GameProfile gameprofile) { - this(gameprofile, (Date) null, (String) null, (Date) null, (String) null); - } - - public GameProfileBanEntry(GameProfile gameprofile, @Nullable Date date, @Nullable String s, @Nullable Date date1, @Nullable String s1) { - super(gameprofile, date, s, date1, s1); - } - - public GameProfileBanEntry(JsonObject jsonobject) { - super(b(jsonobject), jsonobject); - } - - @Override - 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); - } - } - - @Override - public IChatBaseComponent e() { - GameProfile gameprofile = (GameProfile) this.getKey(); - - return new ChatComponentText(gameprofile.getName() != null ? gameprofile.getName() : Objects.toString(gameprofile.getId(), "(Unknown)")); - } - - 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 = UUID.fromString(s); - } catch (Throwable throwable) { - } - - } - 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/src/main/java/net/minecraft/server/GameRules.java b/src/main/java/net/minecraft/server/GameRules.java deleted file mode 100644 index 45d5675ad..000000000 --- a/src/main/java/net/minecraft/server/GameRules.java +++ /dev/null @@ -1,320 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.arguments.BoolArgumentType; -import com.mojang.brigadier.arguments.IntegerArgumentType; -import com.mojang.brigadier.builder.RequiredArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import java.util.Comparator; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.function.Supplier; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class GameRules { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final Map, GameRules.GameRuleDefinition> z = Maps.newTreeMap(Comparator.comparing((gamerules_gamerulekey) -> { - return gamerules_gamerulekey.a; - })); - public static final GameRules.GameRuleKey DO_FIRE_TICK = a("doFireTick", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey MOB_GRIEFING = a("mobGriefing", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey KEEP_INVENTORY = a("keepInventory", GameRules.GameRuleBoolean.b(false)); - public static final GameRules.GameRuleKey DO_MOB_SPAWNING = a("doMobSpawning", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey DO_MOB_LOOT = a("doMobLoot", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey DO_TILE_DROPS = a("doTileDrops", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey DO_ENTITY_DROPS = a("doEntityDrops", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey COMMAND_BLOCK_OUTPUT = a("commandBlockOutput", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey NATURAL_REGENERATION = a("naturalRegeneration", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey DO_DAYLIGHT_CYCLE = a("doDaylightCycle", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey LOG_ADMIN_COMMANDS = a("logAdminCommands", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey SHOW_DEATH_MESSAGES = a("showDeathMessages", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey RANDOM_TICK_SPEED = a("randomTickSpeed", GameRules.GameRuleInt.b(3)); - public static final GameRules.GameRuleKey SEND_COMMAND_FEEDBACK = a("sendCommandFeedback", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey REDUCED_DEBUG_INFO = a("reducedDebugInfo", GameRules.GameRuleBoolean.b(false, (minecraftserver, gamerules_gameruleboolean) -> { - int i = gamerules_gameruleboolean.a() ? 22 : 23; - Iterator iterator = minecraftserver.getPlayerList().getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, (byte) i)); - } - - })); - public static final GameRules.GameRuleKey SPECTATORS_GENERATE_CHUNKS = a("spectatorsGenerateChunks", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey SPAWN_RADIUS = a("spawnRadius", GameRules.GameRuleInt.b(10)); - public static final GameRules.GameRuleKey DISABLE_ELYTRA_MOVEMENT_CHECK = a("disableElytraMovementCheck", GameRules.GameRuleBoolean.b(false)); - public static final GameRules.GameRuleKey MAX_ENTITY_CRAMMING = a("maxEntityCramming", GameRules.GameRuleInt.b(24)); - public static final GameRules.GameRuleKey DO_WEATHER_CYCLE = a("doWeatherCycle", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey DO_LIMITED_CRAFTING = a("doLimitedCrafting", GameRules.GameRuleBoolean.b(false)); - public static final GameRules.GameRuleKey MAX_COMMAND_CHAIN_LENGTH = a("maxCommandChainLength", GameRules.GameRuleInt.b(65536)); - public static final GameRules.GameRuleKey ANNOUNCE_ADVANCEMENTS = a("announceAdvancements", GameRules.GameRuleBoolean.b(true)); - public static final GameRules.GameRuleKey x = a("disableRaids", GameRules.GameRuleBoolean.b(false)); - private final Map, GameRules.GameRuleValue> A; - - private static > GameRules.GameRuleKey a(String s, GameRules.GameRuleDefinition gamerules_gameruledefinition) { - GameRules.GameRuleKey gamerules_gamerulekey = new GameRules.GameRuleKey<>(s); - GameRules.GameRuleDefinition gamerules_gameruledefinition1 = (GameRules.GameRuleDefinition) GameRules.z.put(gamerules_gamerulekey, gamerules_gameruledefinition); - - if (gamerules_gameruledefinition1 != null) { - throw new IllegalStateException("Duplicate game rule registration for " + s); - } else { - return gamerules_gamerulekey; - } - } - - public GameRules() { - this.A = (Map) GameRules.z.entrySet().stream().collect(ImmutableMap.toImmutableMap(Entry::getKey, (entry) -> { - return ((GameRules.GameRuleDefinition) entry.getValue()).getValue(); - })); - } - - public > T get(GameRules.GameRuleKey gamerules_gamerulekey) { - return (T) this.A.get(gamerules_gamerulekey); // CraftBukkit - decompile error - } - - public NBTTagCompound a() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - this.A.forEach((gamerules_gamerulekey, gamerules_gamerulevalue) -> { - nbttagcompound.setString(gamerules_gamerulekey.a, gamerules_gamerulevalue.getValue()); - }); - return nbttagcompound; - } - - public void a(NBTTagCompound nbttagcompound) { - this.A.forEach((gamerules_gamerulekey, gamerules_gamerulevalue) -> { - gamerules_gamerulevalue.setValue(nbttagcompound.getString(gamerules_gamerulekey.a)); - }); - } - - public static void a(GameRules.GameRuleVisitor gamerules_gamerulevisitor) { - GameRules.z.forEach((gamerules_gamerulekey, gamerules_gameruledefinition) -> { - a(gamerules_gamerulevisitor, gamerules_gamerulekey, gamerules_gameruledefinition); - }); - } - - private static > void a(GameRules.GameRuleVisitor gamerules_gamerulevisitor, GameRules.GameRuleKey gamerules_gamerulekey, GameRules.GameRuleDefinition gamerules_gameruledefinition) { - gamerules_gamerulevisitor.a((GameRules.GameRuleKey) gamerules_gamerulekey, (GameRules.GameRuleDefinition) gamerules_gameruledefinition); // CraftBukkit - decompile error - } - - public boolean getBoolean(GameRules.GameRuleKey gamerules_gamerulekey) { - return ((GameRules.GameRuleBoolean) this.get(gamerules_gamerulekey)).a(); - } - - public int getInt(GameRules.GameRuleKey gamerules_gamerulekey) { - return ((GameRules.GameRuleInt) this.get(gamerules_gamerulekey)).a(); - } - - public static class GameRuleBoolean extends GameRules.GameRuleValue { - - private boolean a; - - private static GameRules.GameRuleDefinition b(boolean flag, BiConsumer biconsumer) { - return new GameRules.GameRuleDefinition<>(BoolArgumentType::bool, (gamerules_gameruledefinition) -> { - return new GameRules.GameRuleBoolean(gamerules_gameruledefinition, flag); - }, biconsumer); - } - - private static GameRules.GameRuleDefinition b(boolean flag) { - return b(flag, (minecraftserver, gamerules_gameruleboolean) -> { - }); - } - - public GameRuleBoolean(GameRules.GameRuleDefinition gamerules_gameruledefinition, boolean flag) { - super(gamerules_gameruledefinition); - this.a = flag; - } - - @Override - protected void a(CommandContext commandcontext, String s) { - this.a = BoolArgumentType.getBool(commandcontext, s); - } - - public boolean a() { - return this.a; - } - - public void a(boolean flag, @Nullable MinecraftServer minecraftserver) { - this.a = flag; - this.onChange(minecraftserver); - } - - @Override - protected String getValue() { - return Boolean.toString(this.a); - } - - @Override - public void setValue(String s) { // PAIL - private->public - this.a = Boolean.parseBoolean(s); - } - - @Override - public int getIntValue() { - return this.a ? 1 : 0; - } - - @Override - protected GameRules.GameRuleBoolean e() { - return this; - } - } - - public static class GameRuleInt extends GameRules.GameRuleValue { - - private int a; - - private static GameRules.GameRuleDefinition a(int i, BiConsumer biconsumer) { - return new GameRules.GameRuleDefinition<>(IntegerArgumentType::integer, (gamerules_gameruledefinition) -> { - return new GameRules.GameRuleInt(gamerules_gameruledefinition, i); - }, biconsumer); - } - - private static GameRules.GameRuleDefinition b(int i) { - return a(i, (minecraftserver, gamerules_gameruleint) -> { - }); - } - - public GameRuleInt(GameRules.GameRuleDefinition gamerules_gameruledefinition, int i) { - super(gamerules_gameruledefinition); - this.a = i; - } - - @Override - protected void a(CommandContext commandcontext, String s) { - this.a = IntegerArgumentType.getInteger(commandcontext, s); - } - - public int a() { - return this.a; - } - - @Override - protected String getValue() { - return Integer.toString(this.a); - } - - @Override - public void setValue(String s) { // PAIL - private->public - this.a = b(s); - } - - private static int b(String s) { - if (!s.isEmpty()) { - try { - return Integer.parseInt(s); - } catch (NumberFormatException numberformatexception) { - GameRules.LOGGER.warn("Failed to parse integer {}", s); - } - } - - return 0; - } - - @Override - public int getIntValue() { - return this.a; - } - - @Override - protected GameRules.GameRuleInt e() { - return this; - } - } - - public abstract static class GameRuleValue> { - - private final GameRules.GameRuleDefinition a; - - public GameRuleValue(GameRules.GameRuleDefinition gamerules_gameruledefinition) { - this.a = gamerules_gameruledefinition; - } - - protected abstract void a(CommandContext commandcontext, String s); - - public void b(CommandContext commandcontext, String s) { - this.a(commandcontext, s); - this.onChange(((CommandListenerWrapper) commandcontext.getSource()).getServer()); - } - - public void onChange(@Nullable MinecraftServer minecraftserver) { - if (minecraftserver != null) { - this.a.c.accept(minecraftserver, this.e()); - } - - } - - public abstract void setValue(String s); // PAIL - private->public - - protected abstract String getValue(); - - public String toString() { - return this.getValue(); - } - - public abstract int getIntValue(); - - protected abstract T e(); - } - - public static class GameRuleDefinition> { - - private final Supplier> a; - private final Function, T> b; - private final BiConsumer c; - - private GameRuleDefinition(Supplier> supplier, Function, T> function, BiConsumer biconsumer) { - this.a = supplier; - this.b = function; - this.c = biconsumer; - } - - public RequiredArgumentBuilder a(String s) { - return CommandDispatcher.a(s, (ArgumentType) this.a.get()); - } - - public T getValue() { - return this.b.apply(this); // CraftBukkit - decompile error - } - } - - public static final class GameRuleKey> { - - private final String a; - - public GameRuleKey(String s) { - this.a = s; - } - - public String toString() { - return this.a; - } - - public boolean equals(Object object) { - return this == object ? true : object instanceof GameRules.GameRuleKey && ((GameRules.GameRuleKey) object).a.equals(this.a); - } - - public int hashCode() { - return this.a.hashCode(); - } - - public String a() { - return this.a; - } - } - - @FunctionalInterface - public interface GameRuleVisitor { - - > void a(GameRules.GameRuleKey gamerules_gamerulekey, GameRules.GameRuleDefinition gamerules_gameruledefinition); - } -} diff --git a/src/main/java/net/minecraft/server/GenericAttributes.java b/src/main/java/net/minecraft/server/GenericAttributes.java deleted file mode 100644 index 469e293c2..000000000 --- a/src/main/java/net/minecraft/server/GenericAttributes.java +++ /dev/null @@ -1,125 +0,0 @@ -package net.minecraft.server; - -import java.util.Collection; -import java.util.Iterator; -import java.util.UUID; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class GenericAttributes { - - private static final Logger LOGGER = LogManager.getLogger(); - // Spigot start - public static final IAttribute MAX_HEALTH = (new AttributeRanged((IAttribute) null, "generic.maxHealth", 20.0D, 0.0D, org.spigotmc.SpigotConfig.maxHealth)).a("Max Health").a(true); - public static final IAttribute FOLLOW_RANGE = (new AttributeRanged((IAttribute) null, "generic.followRange", 32.0D, 0.0D, 2048.0D)).a("Follow Range"); - public static final IAttribute KNOCKBACK_RESISTANCE = (new AttributeRanged((IAttribute) null, "generic.knockbackResistance", 0.0D, 0.0D, 1.0D)).a("Knockback Resistance"); - public static final IAttribute MOVEMENT_SPEED = (new AttributeRanged((IAttribute) null, "generic.movementSpeed", 0.699999988079071D, 0.0D, org.spigotmc.SpigotConfig.movementSpeed)).a("Movement Speed").a(true); - public static final IAttribute FLYING_SPEED = (new AttributeRanged((IAttribute) null, "generic.flyingSpeed", 0.4000000059604645D, 0.0D, 1024.0D)).a("Flying Speed").a(true); - public static final IAttribute ATTACK_DAMAGE = new AttributeRanged((IAttribute) null, "generic.attackDamage", 2.0D, 0.0D, org.spigotmc.SpigotConfig.attackDamage); - public static final IAttribute ATTACK_KNOCKBACK = new AttributeRanged((IAttribute) null, "generic.attackKnockback", 0.0D, 0.0D, 5.0D); - public static final IAttribute ATTACK_SPEED = (new AttributeRanged((IAttribute) null, "generic.attackSpeed", 4.0D, 0.0D, 1024.0D)).a(true); - public static final IAttribute ARMOR = (new AttributeRanged((IAttribute) null, "generic.armor", 0.0D, 0.0D, 30.0D)).a(true); - public static final IAttribute ARMOR_TOUGHNESS = (new AttributeRanged((IAttribute) null, "generic.armorToughness", 0.0D, 0.0D, 20.0D)).a(true); - public static final IAttribute LUCK = (new AttributeRanged((IAttribute) null, "generic.luck", 0.0D, -1024.0D, 1024.0D)).a(true); - // Spigot end - - public static NBTTagList a(AttributeMapBase attributemapbase) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = attributemapbase.a().iterator(); - - while (iterator.hasNext()) { - AttributeInstance attributeinstance = (AttributeInstance) iterator.next(); - - 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.getBaseValue()); - Collection collection = attributeinstance.getModifiers(); - - if (collection != null && !collection.isEmpty()) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - AttributeModifier attributemodifier = (AttributeModifier) iterator.next(); - - if (attributemodifier.e()) { - nbttaglist.add(a(attributemodifier)); - } - } - - nbttagcompound.set("Modifiers", nbttaglist); - } - - return nbttagcompound; - } - - public static NBTTagCompound a(AttributeModifier attributemodifier) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setString("Name", attributemodifier.getName()); - nbttagcompound.setDouble("Amount", attributemodifier.getAmount()); - nbttagcompound.setInt("Operation", attributemodifier.getOperation().a()); - nbttagcompound.a("UUID", attributemodifier.getUniqueId()); - return nbttagcompound; - } - - public static void a(AttributeMapBase attributemapbase, NBTTagList nbttaglist) { - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompound(i); - AttributeInstance attributeinstance = attributemapbase.a(nbttagcompound.getString("Name")); - - if (attributeinstance == null) { - GenericAttributes.LOGGER.warn("Ignoring unknown attribute '{}'", nbttagcompound.getString("Name")); - } else { - a(attributeinstance, nbttagcompound); - } - } - - } - - 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.getCompound(i)); - - if (attributemodifier != null) { - AttributeModifier attributemodifier1 = attributeinstance.a(attributemodifier.getUniqueId()); - - if (attributemodifier1 != null) { - attributeinstance.removeModifier(attributemodifier1); - } - - attributeinstance.addModifier(attributemodifier); - } - } - } - - } - - @Nullable - public static AttributeModifier a(NBTTagCompound nbttagcompound) { - UUID uuid = nbttagcompound.a("UUID"); - - try { - AttributeModifier.Operation attributemodifier_operation = AttributeModifier.Operation.a(nbttagcompound.getInt("Operation")); - - return new AttributeModifier(uuid, nbttagcompound.getString("Name"), nbttagcompound.getDouble("Amount"), attributemodifier_operation); - } catch (Exception exception) { - GenericAttributes.LOGGER.warn("Unable to create attribute: {}", exception.getMessage()); - return null; - } - } -} diff --git a/src/main/java/net/minecraft/server/HandshakeListener.java b/src/main/java/net/minecraft/server/HandshakeListener.java deleted file mode 100644 index 9a8e5e121..000000000 --- a/src/main/java/net/minecraft/server/HandshakeListener.java +++ /dev/null @@ -1,146 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import java.net.InetAddress; -import java.util.HashMap; -// CraftBukkit end - -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 HashMap throttleTracker = new HashMap(); - private static int throttleCounter = 0; - // CraftBukkit end - - private final MinecraftServer a; - private final NetworkManager b; - private NetworkManager getNetworkManager() { return b; } // Paper - OBFHELPER - - public HandshakeListener(MinecraftServer minecraftserver, NetworkManager networkmanager) { - this.a = minecraftserver; - this.b = networkmanager; - } - - @Override - public void a(PacketHandshakingInSetProtocol packethandshakinginsetprotocol) { - switch (packethandshakinginsetprotocol.b()) { - case LOGIN: - this.b.setProtocol(EnumProtocol.LOGIN); - ChatMessage chatmessage; - - // CraftBukkit start - Connection throttle - try { - long currentTime = System.currentTimeMillis(); - long connectionThrottle = MinecraftServer.getServer().server.getConnectionThrottle(); - InetAddress address = ((java.net.InetSocketAddress) this.b.getSocketAddress()).getAddress(); - - synchronized (throttleTracker) { - if (throttleTracker.containsKey(address) && !"127.0.0.1".equals(address.getHostAddress()) && currentTime - throttleTracker.get(address) < connectionThrottle) { - throttleTracker.put(address, currentTime); - chatmessage = new ChatMessage(com.destroystokyo.paper.PaperConfig.connectionThrottleKickMessage); // Paper - Configurable connection throttle kick message - this.b.sendPacket(new PacketLoginOutDisconnect(chatmessage)); - this.b.close(chatmessage); - return; - } - - throttleTracker.put(address, currentTime); - throttleCounter++; - if (throttleCounter > 200) { - throttleCounter = 0; - - // Cleanup stale entries - java.util.Iterator iter = throttleTracker.entrySet().iterator(); - while (iter.hasNext()) { - java.util.Map.Entry entry = (java.util.Map.Entry) iter.next(); - if (entry.getValue() > connectionThrottle) { - iter.remove(); - } - } - } - } - } catch (Throwable t) { - org.apache.logging.log4j.LogManager.getLogger().debug("Failed to check connection throttle", t); - } - // CraftBukkit end - - if (packethandshakinginsetprotocol.c() > SharedConstants.a().getProtocolVersion()) { - chatmessage = new ChatMessage( java.text.MessageFormat.format( org.spigotmc.SpigotConfig.outdatedServerMessage.replaceAll("'", "''"), SharedConstants.a().getName() ) ); // Spigot - this.b.sendPacket(new PacketLoginOutDisconnect(chatmessage)); - this.b.close(chatmessage); - } else if (packethandshakinginsetprotocol.c() < SharedConstants.a().getProtocolVersion()) { - chatmessage = new ChatMessage( java.text.MessageFormat.format( org.spigotmc.SpigotConfig.outdatedClientMessage.replaceAll("'", "''"), SharedConstants.a().getName() ) ); // Spigot - this.b.sendPacket(new PacketLoginOutDisconnect(chatmessage)); - this.b.close(chatmessage); - } else { - this.b.setPacketListener(new LoginListener(this.a, this.b)); - // Paper start - handshake event - boolean proxyLogicEnabled = org.spigotmc.SpigotConfig.bungee; - boolean handledByEvent = false; - // Try and handle the handshake through the event - if (com.destroystokyo.paper.event.player.PlayerHandshakeEvent.getHandlerList().getRegisteredListeners().length != 0) { // Hello? Can you hear me? - com.destroystokyo.paper.event.player.PlayerHandshakeEvent event = new com.destroystokyo.paper.event.player.PlayerHandshakeEvent(packethandshakinginsetprotocol.hostname, !proxyLogicEnabled); - if (event.callEvent()) { - // If we've failed somehow, let the client know so and go no further. - if (event.isFailed()) { - chatmessage = new ChatMessage(event.getFailMessage()); - this.b.sendPacket(new PacketLoginOutDisconnect(chatmessage)); - this.b.close(chatmessage); - return; - } - - packethandshakinginsetprotocol.hostname = event.getServerHostname(); - this.b.socketAddress = new java.net.InetSocketAddress(event.getSocketAddressHostname(), ((java.net.InetSocketAddress) this.b.getSocketAddress()).getPort()); - this.b.spoofedUUID = event.getUniqueId(); - this.b.spoofedProfile = gson.fromJson(event.getPropertiesJson(), com.mojang.authlib.properties.Property[].class); - handledByEvent = true; // Hooray, we did it! - } - } - // Don't try and handle default logic if it's been handled by the event. - if (!handledByEvent && proxyLogicEnabled) { - // Paper end - // Spigot Start - //if (org.spigotmc.SpigotConfig.bungee) { // Paper - comment out, we check above! - String[] split = packethandshakinginsetprotocol.hostname.split("\00"); - if ( split.length == 3 || split.length == 4 ) { - packethandshakinginsetprotocol.hostname = split[0]; - b.socketAddress = new java.net.InetSocketAddress(split[1], ((java.net.InetSocketAddress) b.getSocketAddress()).getPort()); - b.spoofedUUID = com.mojang.util.UUIDTypeAdapter.fromString( split[2] ); - } else - { - chatmessage = new ChatMessage("If you wish to use IP forwarding, please enable it in your BungeeCord config as well!"); - this.b.sendPacket(new PacketLoginOutDisconnect(chatmessage)); - this.b.close(chatmessage); - return; - } - if ( split.length == 4 ) - { - b.spoofedProfile = gson.fromJson(split[3], com.mojang.authlib.properties.Property[].class); - } - } - // Spigot End - ((LoginListener) this.b.i()).hostname = packethandshakinginsetprotocol.hostname + ":" + packethandshakinginsetprotocol.port; // CraftBukkit - set hostname - } - break; - case STATUS: - this.b.setProtocol(EnumProtocol.STATUS); - this.b.setPacketListener(new PacketStatusListener(this.a, this.b)); - break; - default: - throw new UnsupportedOperationException("Invalid intention " + packethandshakinginsetprotocol.b()); - } - - // Paper start - NetworkClient implementation - this.getNetworkManager().protocolVersion = packethandshakinginsetprotocol.getProtocolVersion(); - this.getNetworkManager().virtualHost = com.destroystokyo.paper.network.PaperNetworkClient.prepareVirtualHost(packethandshakinginsetprotocol.hostname, packethandshakinginsetprotocol.port); - // Paper end - } - - @Override - public void a(IChatBaseComponent ichatbasecomponent) {} - - @Override - public NetworkManager a() { - return this.b; - } -} diff --git a/src/main/java/net/minecraft/server/IAsyncTaskHandler.java b/src/main/java/net/minecraft/server/IAsyncTaskHandler.java deleted file mode 100644 index 84024e6ba..000000000 --- a/src/main/java/net/minecraft/server/IAsyncTaskHandler.java +++ /dev/null @@ -1,142 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Queues; -import java.util.Queue; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; -import java.util.concurrent.locks.LockSupport; -import java.util.function.BooleanSupplier; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public abstract class IAsyncTaskHandler implements Mailbox, Executor { - - private final String b; - private static final Logger LOGGER = LogManager.getLogger(); - private final Queue d = Queues.newConcurrentLinkedQueue(); - private int e; - - protected IAsyncTaskHandler(String s) { - this.b = s; - } - - protected abstract R postToMainThread(Runnable runnable); - - protected abstract boolean canExecute(R r0); - - public boolean isMainThread() { - return Thread.currentThread() == this.getThread(); - } - - protected abstract Thread getThread(); - - protected boolean isNotMainThread() { - return !this.isMainThread(); - } - - public int be() { - return this.d.size(); - } - - @Override - public String bf() { - return this.b; - } - - private CompletableFuture executeFuture(Runnable runnable) { - return CompletableFuture.supplyAsync(() -> { - runnable.run(); - return null; - }, this); - } - - public CompletableFuture e(Runnable runnable) { - if (this.isNotMainThread()) { - return this.executeFuture(runnable); - } else { - runnable.run(); - return CompletableFuture.completedFuture(null); // Paper - decompile fix - } - } - - public void executeSync(Runnable runnable) { - if (!this.isMainThread()) { - this.executeFuture(runnable).join(); - } else { - runnable.run(); - } - - } - - // Paper start - public void scheduleOnMain(Runnable r0) { - // postToMainThread does not work the same as older versions of mc - // This method is actually used to create a TickTask, which can then be posted onto main - this.addTask(this.postToMainThread(r0)); - } - // Paper end - - public void addTask(R r0) { a(r0); }; // Paper - OBFHELPER - public void a(R r0) { - this.d.add(r0); - LockSupport.unpark(this.getThread()); - } - - public void execute(Runnable runnable) { - if (this.isNotMainThread()) { - this.a(this.postToMainThread(runnable)); - } else { - runnable.run(); - } - - } - - public void executeAll() { // Paper - protected -> public - while (this.executeNext()) { - ; - } - - } - - protected boolean executeNext() { - R r0 = this.d.peek(); // Paper - decompile fix - - if (r0 == null) { - return false; - } else if (this.e == 0 && !this.canExecute(r0)) { - return false; - } else { - this.executeTask(this.d.remove()); // Paper - decompile fix - return true; - } - } - - public void awaitTasks(BooleanSupplier booleansupplier) { - ++this.e; - - try { - while (!booleansupplier.getAsBoolean()) { - if (!this.executeNext()) { - this.bi(); - } - } - } finally { - --this.e; - } - - } - - protected void bi() { - Thread.yield(); - LockSupport.parkNanos("waiting for tasks", 100000L); - } - - protected void executeTask(R r0) { - try { - r0.run(); - } catch (Exception exception) { - IAsyncTaskHandler.LOGGER.fatal("Error executing task on {}", this.bf(), exception); - } - - } -} diff --git a/src/main/java/net/minecraft/server/IBlockAccess.java b/src/main/java/net/minecraft/server/IBlockAccess.java deleted file mode 100644 index 29cdc0087..000000000 --- a/src/main/java/net/minecraft/server/IBlockAccess.java +++ /dev/null @@ -1,157 +0,0 @@ -package net.minecraft.server; - -import java.util.function.BiFunction; -import java.util.function.Function; -import javax.annotation.Nullable; - -public interface IBlockAccess { - - @Nullable - TileEntity getTileEntity(BlockPosition blockposition); - - IBlockData getTypeIfLoaded(BlockPosition blockposition); // Paper - if loaded util - IBlockData getType(BlockPosition blockposition); - - Fluid getFluidIfLoaded(BlockPosition blockposition); // Paper - if loaded util - Fluid getFluid(BlockPosition blockposition); - - // Paper start - if loaded util - default Material getMaterialIfLoaded(BlockPosition blockposition) { - IBlockData type = this.getTypeIfLoaded(blockposition); - return type == null ? null : type.getMaterial(); - } - - default Block getBlockIfLoaded(BlockPosition blockposition) { - IBlockData type = this.getTypeIfLoaded(blockposition); - return type == null ? null : type.getBlock(); - } - // Paper end - - default int h(BlockPosition blockposition) { - return this.getType(blockposition).h(); - } - - default int H() { - return 15; - } - - default int getBuildHeight() { - return 256; - } - - // CraftBukkit start - moved block handling into separate method for use by Block#rayTrace - default MovingObjectPositionBlock rayTraceBlock(RayTrace raytrace1, BlockPosition blockposition) { - // Paper start - Prevent raytrace from loading chunks - IBlockData iblockdata = this.getTypeIfLoaded(blockposition); - if (iblockdata == null) { - // copied the last function parameter (listed below) - Vec3D vec3d = raytrace1.b().d(raytrace1.a()); - - return MovingObjectPositionBlock.a(raytrace1.a(), EnumDirection.a(vec3d.x, vec3d.y, vec3d.z), new BlockPosition(raytrace1.a())); - } - // Paper end - Fluid fluid = this.getFluid(blockposition); - Vec3D vec3d = raytrace1.b(); - Vec3D vec3d1 = raytrace1.a(); - VoxelShape voxelshape = raytrace1.a(iblockdata, this, blockposition); - MovingObjectPositionBlock movingobjectpositionblock = this.rayTrace(vec3d, vec3d1, blockposition, voxelshape, iblockdata); - VoxelShape voxelshape1 = raytrace1.a(fluid, this, blockposition); - MovingObjectPositionBlock movingobjectpositionblock1 = voxelshape1.rayTrace(vec3d, vec3d1, blockposition); - double d0 = movingobjectpositionblock == null ? Double.MAX_VALUE : raytrace1.b().distanceSquared(movingobjectpositionblock.getPos()); - double d1 = movingobjectpositionblock1 == null ? Double.MAX_VALUE : raytrace1.b().distanceSquared(movingobjectpositionblock1.getPos()); - - return d0 <= d1 ? movingobjectpositionblock : movingobjectpositionblock1; - } - // CraftBukkit end - - default MovingObjectPositionBlock rayTrace(RayTrace raytrace) { - return (MovingObjectPositionBlock) a(raytrace, (raytrace1, blockposition) -> { - return this.rayTraceBlock(raytrace1, blockposition); // CraftBukkit - moved into separate method - }, (raytrace1) -> { - Vec3D vec3d = raytrace1.b().d(raytrace1.a()); - - return MovingObjectPositionBlock.a(raytrace1.a(), EnumDirection.a(vec3d.x, vec3d.y, vec3d.z), new BlockPosition(raytrace1.a())); - }); - } - - @Nullable - default MovingObjectPositionBlock rayTrace(Vec3D vec3d, Vec3D vec3d1, BlockPosition blockposition, VoxelShape voxelshape, IBlockData iblockdata) { - MovingObjectPositionBlock movingobjectpositionblock = voxelshape.rayTrace(vec3d, vec3d1, blockposition); - - if (movingobjectpositionblock != null) { - MovingObjectPositionBlock movingobjectpositionblock1 = iblockdata.k(this, blockposition).rayTrace(vec3d, vec3d1, blockposition); - - if (movingobjectpositionblock1 != null && movingobjectpositionblock1.getPos().d(vec3d).g() < movingobjectpositionblock.getPos().d(vec3d).g()) { - return movingobjectpositionblock.a(movingobjectpositionblock1.getDirection()); - } - } - - return movingobjectpositionblock; - } - - static T a(RayTrace raytrace, BiFunction bifunction, Function function) { - Vec3D vec3d = raytrace.b(); - Vec3D vec3d1 = raytrace.a(); - - if (vec3d.equals(vec3d1)) { - return function.apply(raytrace); - } else { - double d0 = MathHelper.d(-1.0E-7D, vec3d1.x, vec3d.x); - double d1 = MathHelper.d(-1.0E-7D, vec3d1.y, vec3d.y); - double d2 = MathHelper.d(-1.0E-7D, vec3d1.z, vec3d.z); - double d3 = MathHelper.d(-1.0E-7D, vec3d.x, vec3d1.x); - double d4 = MathHelper.d(-1.0E-7D, vec3d.y, vec3d1.y); - double d5 = MathHelper.d(-1.0E-7D, vec3d.z, vec3d1.z); - int i = MathHelper.floor(d3); - int j = MathHelper.floor(d4); - int k = MathHelper.floor(d5); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(i, j, k); - T t0 = bifunction.apply(raytrace, blockposition_mutableblockposition); - - if (t0 != null) { - return t0; - } else { - double d6 = d0 - d3; - double d7 = d1 - d4; - double d8 = d2 - d5; - int l = MathHelper.k(d6); - int i1 = MathHelper.k(d7); - int j1 = MathHelper.k(d8); - double d9 = l == 0 ? Double.MAX_VALUE : (double) l / d6; - double d10 = i1 == 0 ? Double.MAX_VALUE : (double) i1 / d7; - double d11 = j1 == 0 ? Double.MAX_VALUE : (double) j1 / d8; - double d12 = d9 * (l > 0 ? 1.0D - MathHelper.h(d3) : MathHelper.h(d3)); - double d13 = d10 * (i1 > 0 ? 1.0D - MathHelper.h(d4) : MathHelper.h(d4)); - double d14 = d11 * (j1 > 0 ? 1.0D - MathHelper.h(d5) : MathHelper.h(d5)); - - T object; // CraftBukkit - decompile error - - do { - if (d12 > 1.0D && d13 > 1.0D && d14 > 1.0D) { - return function.apply(raytrace); - } - - if (d12 < d13) { - if (d12 < d14) { - i += l; - d12 += d9; - } else { - k += j1; - d14 += d11; - } - } else if (d13 < d14) { - j += i1; - d13 += d10; - } else { - k += j1; - d14 += d11; - } - - object = bifunction.apply(raytrace, blockposition_mutableblockposition.d(i, j, k)); - } while (object == null); - - return object; - } - } - } -} diff --git a/src/main/java/net/minecraft/server/IBlockData.java b/src/main/java/net/minecraft/server/IBlockData.java deleted file mode 100644 index 21f734a73..000000000 --- a/src/main/java/net/minecraft/server/IBlockData.java +++ /dev/null @@ -1,390 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.types.DynamicOps; -import com.mojang.datafixers.util.Pair; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -public class IBlockData extends BlockDataAbstract implements IBlockDataHolder { - - @Nullable - private IBlockData.a c; - private final int d; - private final boolean e; - - public IBlockData(Block block, ImmutableMap, Comparable> immutablemap) { - super(block, immutablemap); - this.d = block.a(this); - this.e = block.n(this); - } - - public void c() { - if (!this.getBlock().p()) { - this.c = new IBlockData.a(this); - } - - } - - public Block getBlock() { - return (Block) this.a; - } - - // Paper start - impl cached craft block data, lazy load to fix issue with loading at the wrong time - private CraftBlockData cachedCraftBlockData; - - public CraftBlockData createCraftBlockData() { - if(cachedCraftBlockData == null) cachedCraftBlockData = CraftBlockData.createData(this); - return (CraftBlockData) cachedCraftBlockData.clone(); - } - // Paper end - - public Material getMaterial() { - return this.getBlock().l(this); - } - - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, EntityTypes entitytypes) { - return this.getBlock().a(this, iblockaccess, blockposition, entitytypes); - } - - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.c != null ? this.c.d : this.getBlock().b(this, iblockaccess, blockposition); - } - - public int b(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.c != null ? this.c.e : this.getBlock().k(this, iblockaccess, blockposition); - } - - public VoxelShape a(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return this.c != null && this.c.f != null ? this.c.f[enumdirection.ordinal()] : VoxelShapes.a(this.j(iblockaccess, blockposition), enumdirection); - } - - public boolean f() { - return this.c == null || this.c.h; - } - - public boolean g() { - return this.e; - } - - public int h() { - return this.d; - } - - public boolean isAir() { - return this.getBlock().e(this); - } - - public MaterialMapColor c(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().e(this, iblockaccess, blockposition); - } - - public IBlockData a(EnumBlockRotation enumblockrotation) { - return this.getBlock().a(this, enumblockrotation); - } - - public IBlockData a(EnumBlockMirror enumblockmirror) { - return this.getBlock().a(this, enumblockmirror); - } - - public EnumRenderType k() { - return this.getBlock().c(this); - } - - public boolean isOccluding(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().isOccluding(this, iblockaccess, blockposition); - } - - public boolean isPowerSource() { - return this.getBlock().isPowerSource(this); - } - - public int b(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return this.getBlock().a(this, iblockaccess, blockposition, enumdirection); - } - - public boolean isComplexRedstone() { - return this.getBlock().isComplexRedstone(this); - } - - public int a(World world, BlockPosition blockposition) { - return this.getBlock().a(this, world, blockposition); - } - - public float f(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().f(this, iblockaccess, blockposition); - } - - public float getDamage(EntityHuman entityhuman, IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().getDamage(this, entityhuman, iblockaccess, blockposition); - } - - public int c(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return this.getBlock().b(this, iblockaccess, blockposition, enumdirection); - } - - public EnumPistonReaction getPushReaction() { - return this.getBlock().getPushReaction(this); - } - - public boolean g(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.c != null ? this.c.c : this.getBlock().j(this, iblockaccess, blockposition); - } - - public boolean o() { - return this.c != null ? this.c.b : this.getBlock().f(this); - } - - public VoxelShape getShape(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.a(iblockaccess, blockposition, VoxelShapeCollision.a()); - } - - public VoxelShape a(IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return this.getBlock().a(this, iblockaccess, blockposition, voxelshapecollision); - } - - public VoxelShape getCollisionShape(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.c != null ? this.c.g : this.b(iblockaccess, blockposition, VoxelShapeCollision.a()); - } - - public final VoxelShape getCollisionShape(IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { return this.b(iblockaccess, blockposition, voxelshapecollision); } // Paper - OBFHELPER - public VoxelShape b(IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return this.getBlock().b(this, iblockaccess, blockposition, voxelshapecollision); - } - - public VoxelShape j(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().h(this, iblockaccess, blockposition); - } - - public VoxelShape k(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().i(this, iblockaccess, blockposition); - } - - public final boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, Entity entity) { - return Block.a(this.b(iblockaccess, blockposition, VoxelShapeCollision.a(entity)), EnumDirection.UP); - } - - public Vec3D l(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().l(this, iblockaccess, blockposition); - } - - public boolean a(World world, BlockPosition blockposition, int i, int j) { - return this.getBlock().a(this, world, blockposition, i, j); - } - - public void doPhysics(World world, BlockPosition blockposition, Block block, BlockPosition blockposition1, boolean flag) { - this.getBlock().doPhysics(this, world, blockposition, block, blockposition1, flag); - } - - public void a(GeneratorAccess generatoraccess, BlockPosition blockposition, int i) { - this.getBlock().a(this, generatoraccess, blockposition, i); - } - - public void b(GeneratorAccess generatoraccess, BlockPosition blockposition, int i) { - this.getBlock().b(this, generatoraccess, blockposition, i); - } - - public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - this.getBlock().onPlace(this, world, blockposition, iblockdata, flag); - } - - public void remove(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - this.getBlock().remove(this, world, blockposition, iblockdata, flag); - } - - public void a(World world, BlockPosition blockposition, Random random) { - this.getBlock().tick(this, world, blockposition, random); - } - - public void b(World world, BlockPosition blockposition, Random random) { - this.getBlock().c(this, world, blockposition, random); - } - - public void a(World world, BlockPosition blockposition, Entity entity) { - this.getBlock().a(this, world, blockposition, entity); - } - - public void dropNaturally(World world, BlockPosition blockposition, ItemStack itemstack) { - this.getBlock().dropNaturally(this, world, blockposition, itemstack); - } - - public List a(LootTableInfo.Builder loottableinfo_builder) { - return this.getBlock().a(this, loottableinfo_builder); - } - - public boolean interact(World world, EntityHuman entityhuman, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - return this.getBlock().interact(this, world, movingobjectpositionblock.getBlockPosition(), entityhuman, enumhand, movingobjectpositionblock); - } - - public void attack(World world, BlockPosition blockposition, EntityHuman entityhuman) { - this.getBlock().attack(this, world, blockposition, entityhuman); - } - - public boolean m(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().c(this, iblockaccess, blockposition); - } - - public IBlockData updateState(EnumDirection enumdirection, IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { - return this.getBlock().updateState(this, enumdirection, iblockdata, generatoraccess, blockposition, blockposition1); - } - - public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, PathMode pathmode) { - return this.getBlock().a(this, iblockaccess, blockposition, pathmode); - } - - public boolean a(BlockActionContext blockactioncontext) { - return this.getBlock().a(this, blockactioncontext); - } - - public boolean canPlace(IWorldReader iworldreader, BlockPosition blockposition) { - return this.getBlock().canPlace(this, iworldreader, blockposition); - } - - public boolean n(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.getBlock().g(this, iblockaccess, blockposition); - } - - @Nullable - public ITileInventory b(World world, BlockPosition blockposition) { - return this.getBlock().getInventory(this, world, blockposition); - } - - public boolean a(Tag tag) { - return this.getBlock().a(tag); - } - - public Fluid p() { - return this.getBlock().g(this); - } - - public boolean q() { - return this.getBlock().isTicking(this); - } - - public final SoundEffectType getStepSound() { return this.r(); } // Paper - OBFHELPER - public SoundEffectType r() { - return this.getBlock().getStepSound(this); - } - - public void a(World world, IBlockData iblockdata, MovingObjectPositionBlock movingobjectpositionblock, Entity entity) { - this.getBlock().a(world, iblockdata, movingobjectpositionblock, entity); - } - - public boolean d(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { - return this.c != null ? this.c.i[enumdirection.ordinal()] : Block.d(this, iblockaccess, blockposition, enumdirection); - } - - public boolean o(IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.c != null ? this.c.j : Block.a(this.getCollisionShape(iblockaccess, blockposition)); - } - - public static Dynamic a(DynamicOps dynamicops, IBlockData iblockdata) { - ImmutableMap, Comparable> immutablemap = iblockdata.getStateMap(); - T object; // Paper - decompile fix - - if (immutablemap.isEmpty()) { - object = dynamicops.createMap(ImmutableMap.of(dynamicops.createString("Name"), dynamicops.createString(IRegistry.BLOCK.getKey(iblockdata.getBlock()).toString()))); - } else { - object = dynamicops.createMap(ImmutableMap.of(dynamicops.createString("Name"), dynamicops.createString(IRegistry.BLOCK.getKey(iblockdata.getBlock()).toString()), dynamicops.createString("Properties"), dynamicops.createMap(immutablemap.entrySet().stream().map((entry) -> { // Paper - decompile fix - return Pair.of(dynamicops.createString(((IBlockState) entry.getKey()).a()), dynamicops.createString(IBlockDataHolder.b((IBlockState) entry.getKey(), (Comparable) entry.getValue()))); - }).collect(Collectors.toMap(Pair::getFirst, Pair::getSecond))))); - } - - return new Dynamic(dynamicops, object); - } - - public static IBlockData a(Dynamic dynamic) { - RegistryBlocks registryblocks = IRegistry.BLOCK; - Optional optional = dynamic.getElement("Name"); - DynamicOps dynamicops = dynamic.getOps(); - - dynamicops.getClass(); - Block block = (Block) registryblocks.get(new MinecraftKey((String) optional.flatMap(dynamicops::getStringValue).orElse("minecraft:air"))); - Map map = dynamic.get("Properties").asMap((dynamic1) -> { - return dynamic1.asString(""); - }, (dynamic1) -> { - return dynamic1.asString(""); - }); - IBlockData iblockdata = block.getBlockData(); - BlockStateList blockstatelist = block.getStates(); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - String s = (String) entry.getKey(); - IBlockState iblockstate = blockstatelist.a(s); - - if (iblockstate != null) { - iblockdata = (IBlockData) IBlockDataHolder.a(iblockdata, iblockstate, s, dynamic.toString(), (String) entry.getValue()); - } - } - - return iblockdata; - } - - static final class a { - - private static final EnumDirection[] a = EnumDirection.values(); - private final boolean b; - private final boolean c; - private final boolean d; - private final int e; - private final VoxelShape[] f; - private final VoxelShape g; - private final boolean h; - private final boolean[] i; - private final boolean j; - - private a(IBlockData iblockdata) { - Block block = iblockdata.getBlock(); - - this.b = block.f(iblockdata); - this.c = block.j(iblockdata, BlockAccessAir.INSTANCE, BlockPosition.ZERO); - this.d = block.b(iblockdata, (IBlockAccess) BlockAccessAir.INSTANCE, BlockPosition.ZERO); - this.e = block.k(iblockdata, BlockAccessAir.INSTANCE, BlockPosition.ZERO); - int i; - - if (!iblockdata.o()) { - this.f = null; - } else { - this.f = new VoxelShape[a.length]; // Paper - decompile fix - VoxelShape voxelshape = block.h(iblockdata, BlockAccessAir.INSTANCE, BlockPosition.ZERO); - EnumDirection[] aenumdirection = a; // Paper - decompile fix - - i = aenumdirection.length; - - for (int j = 0; j < i; ++j) { - EnumDirection enumdirection = aenumdirection[j]; - - this.f[enumdirection.ordinal()] = VoxelShapes.a(voxelshape, enumdirection); - } - } - - this.g = block.b(iblockdata, BlockAccessAir.INSTANCE, BlockPosition.ZERO, VoxelShapeCollision.a()); - this.h = Arrays.stream(EnumDirection.EnumAxis.values()).anyMatch((enumdirection_enumaxis) -> { - return this.g.b(enumdirection_enumaxis) < 0.0D || this.g.c(enumdirection_enumaxis) > 1.0D; - }); - this.i = new boolean[6]; - EnumDirection[] aenumdirection1 = a; // Paper - decompile fix - int k = aenumdirection1.length; - - for (i = 0; i < k; ++i) { - EnumDirection enumdirection1 = aenumdirection1[i]; - - this.i[enumdirection1.ordinal()] = Block.d(iblockdata, BlockAccessAir.INSTANCE, BlockPosition.ZERO, enumdirection1); - } - - this.j = Block.a(iblockdata.getCollisionShape(BlockAccessAir.INSTANCE, BlockPosition.ZERO)); - } - } -} diff --git a/src/main/java/net/minecraft/server/IChatBaseComponent.java b/src/main/java/net/minecraft/server/IChatBaseComponent.java deleted file mode 100644 index 9ccf7f8d6..000000000 --- a/src/main/java/net/minecraft/server/IChatBaseComponent.java +++ /dev/null @@ -1,474 +0,0 @@ -package net.minecraft.server; - -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; -import com.google.gson.stream.JsonReader; -import com.mojang.brigadier.Message; -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Field; -import java.lang.reflect.Type; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.function.Consumer; -import java.util.stream.Stream; -import javax.annotation.Nullable; - -public interface IChatBaseComponent extends Message, Iterable { - - IChatBaseComponent setChatModifier(ChatModifier chatmodifier); - - ChatModifier getChatModifier(); - - default IChatBaseComponent a(String s) { - return this.addSibling(new ChatComponentText(s)); - } - - IChatBaseComponent addSibling(IChatBaseComponent ichatbasecomponent); - - String getText(); - - default String getString() { - StringBuilder stringbuilder = new StringBuilder(); - - this.c().forEach((ichatbasecomponent) -> { - stringbuilder.append(ichatbasecomponent.getText()); - }); - return stringbuilder.toString(); - } - - default String a(int i) { - StringBuilder stringbuilder = new StringBuilder(); - Iterator iterator = this.c().iterator(); - - while (iterator.hasNext()) { - int j = i - stringbuilder.length(); - - if (j <= 0) { - break; - } - - String s = ((IChatBaseComponent) iterator.next()).getText(); - - stringbuilder.append(s.length() <= j ? s : s.substring(0, j)); - } - - return stringbuilder.toString(); - } - - default String e() { - StringBuilder stringbuilder = new StringBuilder(); - String s = ""; - Iterator iterator = this.c().iterator(); - - while (iterator.hasNext()) { - IChatBaseComponent ichatbasecomponent = (IChatBaseComponent) iterator.next(); - String s1 = ichatbasecomponent.getText(); - - if (!s1.isEmpty()) { - String s2 = ichatbasecomponent.getChatModifier().k(); - - if (!s2.equals(s)) { - if (!s.isEmpty()) { - stringbuilder.append(EnumChatFormat.RESET); - } - - stringbuilder.append(s2); - s = s2; - } - - stringbuilder.append(s1); - } - } - - if (!s.isEmpty()) { - stringbuilder.append(EnumChatFormat.RESET); - } - - return stringbuilder.toString(); - } - - List getSiblings(); - - Stream c(); - - default Stream f() { - return this.c().map(IChatBaseComponent::b); - } - - default Iterator iterator() { - return this.f().iterator(); - } - - IChatBaseComponent g(); - - default IChatBaseComponent h() { - IChatBaseComponent ichatbasecomponent = this.g(); - - ichatbasecomponent.setChatModifier(this.getChatModifier().clone()); - Iterator iterator = this.getSiblings().iterator(); - - while (iterator.hasNext()) { - IChatBaseComponent ichatbasecomponent1 = (IChatBaseComponent) iterator.next(); - - ichatbasecomponent.addSibling(ichatbasecomponent1.h()); - } - - return ichatbasecomponent; - } - - default IChatBaseComponent a(Consumer consumer) { - consumer.accept(this.getChatModifier()); - return this; - } - - default IChatBaseComponent a(EnumChatFormat... aenumchatformat) { - EnumChatFormat[] aenumchatformat1 = aenumchatformat; - int i = aenumchatformat.length; - - for (int j = 0; j < i; ++j) { - EnumChatFormat enumchatformat = aenumchatformat1[j]; - - this.a(enumchatformat); - } - - return this; - } - - default IChatBaseComponent a(EnumChatFormat enumchatformat) { - ChatModifier chatmodifier = this.getChatModifier(); - - if (enumchatformat.d()) { - chatmodifier.setColor(enumchatformat); - } - - if (enumchatformat.isFormat()) { - switch (enumchatformat) { - case OBFUSCATED: - chatmodifier.setRandom(true); - break; - case BOLD: - chatmodifier.setBold(true); - break; - case STRIKETHROUGH: - chatmodifier.setStrikethrough(true); - break; - case UNDERLINE: - chatmodifier.setUnderline(true); - break; - case ITALIC: - chatmodifier.setItalic(true); - } - } - - return this; - } - - static IChatBaseComponent b(IChatBaseComponent ichatbasecomponent) { - IChatBaseComponent ichatbasecomponent1 = ichatbasecomponent.g(); - - ichatbasecomponent1.setChatModifier(ichatbasecomponent.getChatModifier().n()); - return ichatbasecomponent1; - } - - public static class ChatSerializer implements JsonDeserializer, JsonSerializer { - - private static final Gson a = (Gson) SystemUtils.a(() -> { - GsonBuilder gsonbuilder = new GsonBuilder(); - - gsonbuilder.disableHtmlEscaping(); - gsonbuilder.registerTypeHierarchyAdapter(IChatBaseComponent.class, new IChatBaseComponent.ChatSerializer()); - gsonbuilder.registerTypeHierarchyAdapter(ChatModifier.class, new ChatModifier.ChatModifierSerializer()); - gsonbuilder.registerTypeAdapterFactory(new ChatTypeAdapterFactory()); - return gsonbuilder.create(); - }); - private static final Field b = (Field) SystemUtils.a(() -> { - try { - new JsonReader(new StringReader("")); - Field field = JsonReader.class.getDeclaredField("pos"); - - field.setAccessible(true); - return field; - } catch (NoSuchFieldException nosuchfieldexception) { - throw new IllegalStateException("Couldn't get field 'pos' for JsonReader", nosuchfieldexception); - } - }); - private static final Field c = (Field) SystemUtils.a(() -> { - try { - new JsonReader(new StringReader("")); - Field field = JsonReader.class.getDeclaredField("lineStart"); - - field.setAccessible(true); - return field; - } catch (NoSuchFieldException nosuchfieldexception) { - throw new IllegalStateException("Couldn't get field 'lineStart' for JsonReader", nosuchfieldexception); - } - }); - - public ChatSerializer() {} - - public IChatBaseComponent deserialize(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(); - IChatBaseComponent ichatbasecomponent = null; - Iterator iterator = jsonarray.iterator(); - - while (iterator.hasNext()) { - JsonElement jsonelement1 = (JsonElement) iterator.next(); - IChatBaseComponent ichatbasecomponent1 = this.deserialize(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(); - Object object; - - if (jsonobject.has("text")) { - object = new ChatComponentText(ChatDeserializer.h(jsonobject, "text")); - } else { - String s; - - if (jsonobject.has("translate")) { - s = ChatDeserializer.h(jsonobject, "translate"); - if (jsonobject.has("with")) { - JsonArray jsonarray1 = ChatDeserializer.u(jsonobject, "with"); - Object[] aobject = new Object[jsonarray1.size()]; - - for (int i = 0; i < aobject.length; ++i) { - aobject[i] = this.deserialize(jsonarray1.get(i), type, jsondeserializationcontext); - if (aobject[i] instanceof ChatComponentText) { - ChatComponentText chatcomponenttext = (ChatComponentText) aobject[i]; - - if (chatcomponenttext.getChatModifier().g() && chatcomponenttext.getSiblings().isEmpty()) { - aobject[i] = chatcomponenttext.i(); - } - } - } - - object = new ChatMessage(s, aobject); - } else { - object = new ChatMessage(s, new Object[0]); - } - } else if (jsonobject.has("score")) { - JsonObject jsonobject1 = ChatDeserializer.t(jsonobject, "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")) { - object = new ChatComponentSelector(ChatDeserializer.h(jsonobject, "selector")); - } else if (jsonobject.has("keybind")) { - object = new ChatComponentKeybind(ChatDeserializer.h(jsonobject, "keybind")); - } else { - if (!jsonobject.has("nbt")) { - throw new JsonParseException("Don't know how to turn " + jsonelement + " into a Component"); - } - - s = ChatDeserializer.h(jsonobject, "nbt"); - boolean flag = ChatDeserializer.a(jsonobject, "interpret", false); - - if (jsonobject.has("block")) { - object = new ChatComponentNBT.a(s, flag, ChatDeserializer.h(jsonobject, "block")); - } else { - if (!jsonobject.has("entity")) { - throw new JsonParseException("Don't know how to turn " + jsonelement + " into a Component"); - } - - object = new ChatComponentNBT.b(s, flag, ChatDeserializer.h(jsonobject, "entity")); - } - } - } - - if (jsonobject.has("extra")) { - JsonArray jsonarray2 = ChatDeserializer.u(jsonobject, "extra"); - - if (jsonarray2.size() <= 0) { - throw new JsonParseException("Unexpected empty array of components"); - } - - for (int j = 0; j < jsonarray2.size(); ++j) { - ((IChatBaseComponent) object).addSibling(this.deserialize(jsonarray2.get(j), type, jsondeserializationcontext)); - } - } - - ((IChatBaseComponent) object).setChatModifier((ChatModifier) jsondeserializationcontext.deserialize(jsonelement, ChatModifier.class)); - return (IChatBaseComponent) object; - } - } - - private void a(ChatModifier chatmodifier, JsonObject jsonobject, JsonSerializationContext jsonserializationcontext) { - JsonElement jsonelement = jsonserializationcontext.serialize(chatmodifier); - - if (jsonelement.isJsonObject()) { - JsonObject jsonobject1 = (JsonObject) jsonelement; - Iterator iterator = jsonobject1.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - jsonobject.add((String) entry.getKey(), (JsonElement) entry.getValue()); - } - } - - } - - public JsonElement serialize(IChatBaseComponent ichatbasecomponent, Type type, JsonSerializationContext jsonserializationcontext) { - JsonObject jsonobject = new JsonObject(); - - if (!ichatbasecomponent.getChatModifier().g()) { - this.a(ichatbasecomponent.getChatModifier(), jsonobject, jsonserializationcontext); - } - - if (!ichatbasecomponent.getSiblings().isEmpty()) { - JsonArray jsonarray = new JsonArray(); - Iterator iterator = ichatbasecomponent.getSiblings().iterator(); - - while (iterator.hasNext()) { - IChatBaseComponent ichatbasecomponent1 = (IChatBaseComponent) iterator.next(); - - jsonarray.add(this.serialize(ichatbasecomponent1, ichatbasecomponent1.getClass(), jsonserializationcontext)); - } - - jsonobject.add("extra", jsonarray); - } - - if (ichatbasecomponent instanceof ChatComponentText) { - jsonobject.addProperty("text", ((ChatComponentText) ichatbasecomponent).i()); - } else if (ichatbasecomponent instanceof ChatMessage) { - ChatMessage chatmessage = (ChatMessage) ichatbasecomponent; - - jsonobject.addProperty("translate", chatmessage.getKey()); - if (chatmessage.getArgs() != null && chatmessage.getArgs().length > 0) { - JsonArray jsonarray1 = new JsonArray(); - Object[] aobject = chatmessage.getArgs(); - int i = aobject.length; - - for (int j = 0; j < i; ++j) { - Object object = aobject[j]; - - if (object instanceof IChatBaseComponent) { - jsonarray1.add(this.serialize((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.i()); - jsonobject1.addProperty("objective", chatcomponentscore.k()); - jsonobject1.addProperty("value", chatcomponentscore.getText()); - jsonobject.add("score", jsonobject1); - } else if (ichatbasecomponent instanceof ChatComponentSelector) { - ChatComponentSelector chatcomponentselector = (ChatComponentSelector) ichatbasecomponent; - - jsonobject.addProperty("selector", chatcomponentselector.i()); - } else if (ichatbasecomponent instanceof ChatComponentKeybind) { - ChatComponentKeybind chatcomponentkeybind = (ChatComponentKeybind) ichatbasecomponent; - - jsonobject.addProperty("keybind", chatcomponentkeybind.j()); - } else { - if (!(ichatbasecomponent instanceof ChatComponentNBT)) { - throw new IllegalArgumentException("Don't know how to serialize " + ichatbasecomponent + " as a Component"); - } - - ChatComponentNBT chatcomponentnbt = (ChatComponentNBT) ichatbasecomponent; - - jsonobject.addProperty("nbt", chatcomponentnbt.i()); - jsonobject.addProperty("interpret", chatcomponentnbt.j()); - if (ichatbasecomponent instanceof ChatComponentNBT.a) { - ChatComponentNBT.a chatcomponentnbt_a = (ChatComponentNBT.a) ichatbasecomponent; - - jsonobject.addProperty("block", chatcomponentnbt_a.k()); - } else { - if (!(ichatbasecomponent instanceof ChatComponentNBT.b)) { - throw new IllegalArgumentException("Don't know how to serialize " + ichatbasecomponent + " as a Component"); - } - - ChatComponentNBT.b chatcomponentnbt_b = (ChatComponentNBT.b) ichatbasecomponent; - - jsonobject.addProperty("entity", chatcomponentnbt_b.k()); - } - } - - return jsonobject; - } - - public static String a(IChatBaseComponent ichatbasecomponent) { - return IChatBaseComponent.ChatSerializer.a.toJson(ichatbasecomponent); - } - - public static JsonElement b(IChatBaseComponent ichatbasecomponent) { - return IChatBaseComponent.ChatSerializer.a.toJsonTree(ichatbasecomponent); - } - - @Nullable public static IChatBaseComponent jsonToComponent(String json) { return a(json);} // Paper - OBFHELPER - @Nullable - public static IChatBaseComponent a(String s) { - return (IChatBaseComponent) ChatDeserializer.a(IChatBaseComponent.ChatSerializer.a, s, IChatBaseComponent.class, false); - } - - @Nullable - public static IChatBaseComponent a(JsonElement jsonelement) { - return (IChatBaseComponent) IChatBaseComponent.ChatSerializer.a.fromJson(jsonelement, IChatBaseComponent.class); - } - - @Nullable - public static IChatBaseComponent b(String s) { - return (IChatBaseComponent) ChatDeserializer.a(IChatBaseComponent.ChatSerializer.a, s, IChatBaseComponent.class, true); - } - - public static IChatBaseComponent a(com.mojang.brigadier.StringReader com_mojang_brigadier_stringreader) { - try { - JsonReader jsonreader = new JsonReader(new StringReader(com_mojang_brigadier_stringreader.getRemaining())); - - jsonreader.setLenient(false); - IChatBaseComponent ichatbasecomponent = (IChatBaseComponent) IChatBaseComponent.ChatSerializer.a.getAdapter(IChatBaseComponent.class).read(jsonreader); - - com_mojang_brigadier_stringreader.setCursor(com_mojang_brigadier_stringreader.getCursor() + a(jsonreader)); - return ichatbasecomponent; - } catch (IOException ioexception) { - throw new JsonParseException(ioexception); - } - } - - private static int a(JsonReader jsonreader) { - try { - return IChatBaseComponent.ChatSerializer.b.getInt(jsonreader) - IChatBaseComponent.ChatSerializer.c.getInt(jsonreader) + 1; - } catch (IllegalAccessException illegalaccessexception) { - throw new IllegalStateException("Couldn't read position of JsonReader", illegalaccessexception); - } - } - } -} diff --git a/src/main/java/net/minecraft/server/IChunkLoader.java b/src/main/java/net/minecraft/server/IChunkLoader.java deleted file mode 100644 index 39f6ddb1d..000000000 --- a/src/main/java/net/minecraft/server/IChunkLoader.java +++ /dev/null @@ -1,110 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.DataFixer; -import java.io.File; -import java.io.IOException; -// Paper start -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -// Paper end -import java.util.function.Supplier; -import javax.annotation.Nullable; - -public class IChunkLoader extends RegionFileCache { - - protected final DataFixer b; - @Nullable - private volatile PersistentStructureLegacy a; // Paper - async chunk loading - - private final Object persistentDataLock = new Object(); // Paper - - public IChunkLoader(File file, DataFixer datafixer) { - super(file); - this.b = datafixer; - } - - // CraftBukkit start - private boolean check(ChunkProviderServer cps, int x, int z) throws IOException { - ChunkCoordIntPair pos = new ChunkCoordIntPair(x, z); - if (cps != null) { - //com.google.common.base.Preconditions.checkState(org.bukkit.Bukkit.isPrimaryThread(), "primary thread"); // Paper - this function is now MT-Safe - if (cps.getChunkAtIfCachedImmediately(x, z) != null) { // Paper - isLoaded is a ticket level check, not a chunk loaded check! - return true; - } - } - - if (this.chunkExists(pos)) { - // Paper start - prioritize - NBTTagCompound nbt = cps == null ? read(pos) : - com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.loadChunkData((WorldServer)cps.getWorld(), x, z, - com.destroystokyo.paper.io.PrioritizedTaskQueue.HIGHER_PRIORITY, false, true).chunkData; - // Paper end - if (nbt != null) { - NBTTagCompound level = nbt.getCompound("Level"); - if (level.getBoolean("TerrainPopulated")) { - return true; - } - - ChunkStatus status = ChunkStatus.a(level.getString("Status")); - if (status != null && status.b(ChunkStatus.FEATURES)) { - return true; - } - } - } - - return false; - } - // CraftBukkit end - - public NBTTagCompound getChunkData(DimensionManager dimensionmanager, Supplier supplier, NBTTagCompound nbttagcompound, ChunkCoordIntPair pos, @Nullable GeneratorAccess generatoraccess) throws IOException { - int i = a(nbttagcompound); - boolean flag = true; - - // CraftBukkit start - if (i < 1466) { - NBTTagCompound level = nbttagcompound.getCompound("Level"); - if (level.getBoolean("TerrainPopulated") && !level.getBoolean("LightPopulated")) { - ChunkProviderServer cps = (generatoraccess == null) ? null : ((WorldServer) generatoraccess).getChunkProvider(); - if (check(cps, pos.x - 1, pos.z) && check(cps, pos.x - 1, pos.z - 1) && check(cps, pos.x, pos.z - 1)) { - level.setBoolean("LightPopulated", true); - } - } - } - // CraftBukkit end - - if (i < 1493) { - nbttagcompound = GameProfileSerializer.a(this.b, DataFixTypes.CHUNK, nbttagcompound, i, 1493); - if (nbttagcompound.getCompound("Level").getBoolean("hasLegacyStructureData")) { - synchronized (this.persistentDataLock) { // Paper - Async chunk loading - if (this.a == null) { - this.a = PersistentStructureLegacy.a(dimensionmanager.getType(), (WorldPersistentData) supplier.get()); // CraftBukkit - getType - } - - nbttagcompound = this.a.a(nbttagcompound); - } // Paper - Async chunk loading - } - } - - nbttagcompound = GameProfileSerializer.a(this.b, DataFixTypes.CHUNK, nbttagcompound, Math.max(1493, i)); - if (i < SharedConstants.a().getWorldVersion()) { - nbttagcompound.setInt("DataVersion", SharedConstants.a().getWorldVersion()); - } - - return nbttagcompound; - } - - public static int a(NBTTagCompound nbttagcompound) { - return nbttagcompound.hasKeyOfType("DataVersion", 99) ? nbttagcompound.getInt("DataVersion") : -1; - } - - @Override - public void write(ChunkCoordIntPair chunkcoordintpair, NBTTagCompound nbttagcompound) throws IOException { - super.write(chunkcoordintpair, nbttagcompound); - if (this.a != null) { - synchronized (this.persistentDataLock) { // Paper - Async chunk loading - this.a.a(chunkcoordintpair.pair()); - } // Paper - Async chunk loading - } - - } -} diff --git a/src/main/java/net/minecraft/server/ICommandListener.java b/src/main/java/net/minecraft/server/ICommandListener.java deleted file mode 100644 index c930ba660..000000000 --- a/src/main/java/net/minecraft/server/ICommandListener.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.minecraft.server; - -public interface ICommandListener { - - ICommandListener DUMMY = new ICommandListener() { - @Override - public void sendMessage(IChatBaseComponent ichatbasecomponent) {} - - @Override - public boolean shouldSendSuccess() { - return false; - } - - @Override - public boolean shouldSendFailure() { - return false; - } - - @Override - public boolean shouldBroadcastCommands() { - return false; - } - - // CraftBukkit start - @Override - public org.bukkit.command.CommandSender getBukkitSender(CommandListenerWrapper wrapper) { - throw new UnsupportedOperationException("Not supported yet."); - } - // CraftBukkit end - }; - - void sendMessage(IChatBaseComponent ichatbasecomponent); - - boolean shouldSendSuccess(); - - boolean shouldSendFailure(); - - boolean shouldBroadcastCommands(); - - org.bukkit.command.CommandSender getBukkitSender(CommandListenerWrapper wrapper); // CraftBukkit -} diff --git a/src/main/java/net/minecraft/server/IDispenseBehavior.java b/src/main/java/net/minecraft/server/IDispenseBehavior.java deleted file mode 100644 index fe3d9d5fa..000000000 --- a/src/main/java/net/minecraft/server/IDispenseBehavior.java +++ /dev/null @@ -1,757 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.Random; -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.TreeType; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.DummyGeneratorAccess; -import org.bukkit.event.block.BlockDispenseEvent; -import org.bukkit.event.world.StructureGrowEvent; -// CraftBukkit end - -public interface IDispenseBehavior { - - IDispenseBehavior NONE = (isourceblock, itemstack) -> { - return itemstack; - }; - - ItemStack dispense(ISourceBlock isourceblock, ItemStack itemstack); - - static void c() { - BlockDispenser.a((IMaterial) Items.ARROW, (IDispenseBehavior) (new DispenseBehaviorProjectile() { - @Override - protected IProjectile a(World world, IPosition iposition, ItemStack itemstack) { - EntityTippedArrow entitytippedarrow = new EntityTippedArrow(world, iposition.getX(), iposition.getY(), iposition.getZ()); - - entitytippedarrow.fromPlayer = EntityArrow.PickupStatus.ALLOWED; - return entitytippedarrow; - } - })); - BlockDispenser.a((IMaterial) Items.TIPPED_ARROW, (IDispenseBehavior) (new DispenseBehaviorProjectile() { - @Override - protected IProjectile a(World world, IPosition iposition, ItemStack itemstack) { - EntityTippedArrow entitytippedarrow = new EntityTippedArrow(world, iposition.getX(), iposition.getY(), iposition.getZ()); - - entitytippedarrow.b(itemstack); - entitytippedarrow.fromPlayer = EntityArrow.PickupStatus.ALLOWED; - return entitytippedarrow; - } - })); - BlockDispenser.a((IMaterial) Items.SPECTRAL_ARROW, (IDispenseBehavior) (new DispenseBehaviorProjectile() { - @Override - protected IProjectile a(World world, IPosition iposition, ItemStack itemstack) { - EntitySpectralArrow entityspectralarrow = new EntitySpectralArrow(world, iposition.getX(), iposition.getY(), iposition.getZ()); - - entityspectralarrow.fromPlayer = EntityArrow.PickupStatus.ALLOWED; - return entityspectralarrow; - } - })); - BlockDispenser.a((IMaterial) Items.EGG, (IDispenseBehavior) (new DispenseBehaviorProjectile() { - @Override - protected IProjectile a(World world, IPosition iposition, ItemStack itemstack) { - return (IProjectile) SystemUtils.a((new EntityEgg(world, iposition.getX(), iposition.getY(), iposition.getZ())), (entityegg) -> { // CraftBukkit - decompile error - entityegg.setItem(itemstack); - }); - } - })); - BlockDispenser.a((IMaterial) Items.SNOWBALL, (IDispenseBehavior) (new DispenseBehaviorProjectile() { - @Override - protected IProjectile a(World world, IPosition iposition, ItemStack itemstack) { - return (IProjectile) SystemUtils.a((new EntitySnowball(world, iposition.getX(), iposition.getY(), iposition.getZ())), (entitysnowball) -> { // CraftBukkit - decompile error - entitysnowball.setItem(itemstack); - }); - } - })); - BlockDispenser.a((IMaterial) Items.EXPERIENCE_BOTTLE, (IDispenseBehavior) (new DispenseBehaviorProjectile() { - @Override - protected IProjectile a(World world, IPosition iposition, ItemStack itemstack) { - return (IProjectile) SystemUtils.a((new EntityThrownExpBottle(world, iposition.getX(), iposition.getY(), iposition.getZ())), (entitythrownexpbottle) -> { // CraftBukkit - decompile error - entitythrownexpbottle.setItem(itemstack); - }); - } - - @Override - protected float a() { - return super.a() * 0.5F; - } - - @Override - protected float getPower() { - return super.getPower() * 1.25F; - } - })); - BlockDispenser.a((IMaterial) Items.SPLASH_POTION, new IDispenseBehavior() { - @Override - public ItemStack dispense(ISourceBlock isourceblock, ItemStack itemstack) { - return (new DispenseBehaviorProjectile() { - @Override - protected IProjectile a(World world, IPosition iposition, ItemStack itemstack1) { - return (IProjectile) SystemUtils.a((new EntityPotion(world, iposition.getX(), iposition.getY(), iposition.getZ())), (entitypotion) -> { // CraftBukkit - decompile error - entitypotion.setItem(itemstack1); - }); - } - - @Override - protected float a() { - return super.a() * 0.5F; - } - - @Override - protected float getPower() { - return super.getPower() * 1.25F; - } - }).dispense(isourceblock, itemstack); - } - }); - BlockDispenser.a((IMaterial) Items.LINGERING_POTION, new IDispenseBehavior() { - @Override - public ItemStack dispense(ISourceBlock isourceblock, ItemStack itemstack) { - return (new DispenseBehaviorProjectile() { - @Override - protected IProjectile a(World world, IPosition iposition, ItemStack itemstack1) { - return (IProjectile) SystemUtils.a((new EntityPotion(world, iposition.getX(), iposition.getY(), iposition.getZ())), (entitypotion) -> { // CraftBukkit - decompile error - entitypotion.setItem(itemstack1); - }); - } - - @Override - protected float a() { - return super.a() * 0.5F; - } - - @Override - protected float getPower() { - return super.getPower() * 1.25F; - } - }).dispense(isourceblock, itemstack); - } - }); - DispenseBehaviorItem dispensebehavioritem = new DispenseBehaviorItem() { - @Override - public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - EntityTypes entitytypes = ((ItemMonsterEgg) itemstack.getItem()).b(itemstack.getTag()); - - // 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(0, 0, 0)); - if (!BlockDispenser.eventFired) { - world.getServer().getPluginManager().callEvent(event); - } - - if (event.isCancelled()) { - itemstack.add(1); - return itemstack; - } - - if (!event.getItem().equals(craftItem)) { - itemstack.add(1); - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - - try { // Paper - entitytypes.spawnCreature(isourceblock.getWorld(), itemstack, (EntityHuman) null, isourceblock.getBlockPosition().shift(enumdirection), EnumMobSpawn.DISPENSER, enumdirection != EnumDirection.UP, false); - // Paper start - } catch (Exception ex){ - MinecraftServer.LOGGER.warn("An exception occurred dispensing entity at {}[{}]", world.getWorld().getName(), isourceblock.getBlockPosition(), ex); - } - // Paper end - - // itemstack.subtract(1); // Handled during event processing - // CraftBukkit end - return itemstack; - } - }; - Iterator iterator = ItemMonsterEgg.d().iterator(); - - while (iterator.hasNext()) { - ItemMonsterEgg itemmonsteregg = (ItemMonsterEgg) iterator.next(); - - BlockDispenser.a((IMaterial) itemmonsteregg, (IDispenseBehavior) dispensebehavioritem); - } - - BlockDispenser.a((IMaterial) Items.FIREWORK_ROCKET, (IDispenseBehavior) (new DispenseBehaviorItem() { - @Override - public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - double d0 = isourceblock.getX() + (double) enumdirection.getAdjacentX(); - double d1 = (double) ((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.add(1); - return itemstack; - } - - if (!event.getItem().equals(craftItem)) { - itemstack.add(1); - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - - itemstack1 = CraftItemStack.asNMSCopy(event.getItem()); - isourceblock.getWorld().addEntity(new EntityFireworks(isourceblock.getWorld(), event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ(), itemstack1)); - // itemstack.subtract(1); // Handled during event processing - // CraftBukkit end - return itemstack; - } - - @Override - protected void a(ISourceBlock isourceblock) { - isourceblock.getWorld().triggerEffect(1004, isourceblock.getBlockPosition(), 0); - } - })); - BlockDispenser.a((IMaterial) Items.FIRE_CHARGE, (IDispenseBehavior) (new DispenseBehaviorItem() { - @Override - public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - 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.add(1); - return itemstack; - } - - if (!event.getItem().equals(craftItem)) { - itemstack.add(1); - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - - EntitySmallFireball entitysmallfireball = new EntitySmallFireball(world, d0, d1, d2, event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ()); - entitysmallfireball.b(itemstack); - entitysmallfireball.projectileSource = new org.bukkit.craftbukkit.projectiles.CraftBlockProjectileSource((TileEntityDispenser) isourceblock.getTileEntity()); - - world.addEntity(entitysmallfireball); - // itemstack.subtract(1); // Handled during event processing - // CraftBukkit end - return itemstack; - } - - @Override - protected void a(ISourceBlock isourceblock) { - isourceblock.getWorld().triggerEffect(1018, isourceblock.getBlockPosition(), 0); - } - })); - BlockDispenser.a((IMaterial) Items.OAK_BOAT, (IDispenseBehavior) (new DispenseBehaviorBoat(EntityBoat.EnumBoatType.OAK))); - BlockDispenser.a((IMaterial) Items.SPRUCE_BOAT, (IDispenseBehavior) (new DispenseBehaviorBoat(EntityBoat.EnumBoatType.SPRUCE))); - BlockDispenser.a((IMaterial) Items.BIRCH_BOAT, (IDispenseBehavior) (new DispenseBehaviorBoat(EntityBoat.EnumBoatType.BIRCH))); - BlockDispenser.a((IMaterial) Items.JUNGLE_BOAT, (IDispenseBehavior) (new DispenseBehaviorBoat(EntityBoat.EnumBoatType.JUNGLE))); - BlockDispenser.a((IMaterial) Items.DARK_OAK_BOAT, (IDispenseBehavior) (new DispenseBehaviorBoat(EntityBoat.EnumBoatType.DARK_OAK))); - BlockDispenser.a((IMaterial) Items.ACACIA_BOAT, (IDispenseBehavior) (new DispenseBehaviorBoat(EntityBoat.EnumBoatType.ACACIA))); - DispenseBehaviorItem dispensebehavioritem1 = new DispenseBehaviorItem() { - private final DispenseBehaviorItem b = new DispenseBehaviorItem(); - - @Override - public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - ItemBucket itembucket = (ItemBucket) itemstack.getItem(); - BlockPosition blockposition = isourceblock.getBlockPosition().shift((EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - World world = isourceblock.getWorld(); - - // CraftBukkit start - int x = blockposition.getX(); - int y = blockposition.getY(); - int z = blockposition.getZ(); - IBlockData iblockdata = world.getType(blockposition); - Material material = iblockdata.getMaterial(); - if (world.isEmpty(blockposition) || !material.isBuildable() || material.isReplaceable() || ((iblockdata.getBlock() instanceof IFluidContainer) && ((IFluidContainer) iblockdata.getBlock()).canPlace(world, blockposition, iblockdata, itembucket.fluidType))) { - 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 = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - - itembucket = (ItemBucket) CraftItemStack.asNMSCopy(event.getItem()).getItem(); - } - // CraftBukkit end - - if (itembucket.a((EntityHuman) null, world, blockposition, (MovingObjectPositionBlock) null)) { - itembucket.a(world, itemstack, blockposition); - // CraftBukkit start - Handle stacked buckets - Item item = Items.BUCKET; - itemstack.subtract(1); - if (itemstack.isEmpty()) { - itemstack.setItem(Items.BUCKET); - itemstack.setCount(1); - } else if (((TileEntityDispenser) isourceblock.getTileEntity()).addItem(new ItemStack(item)) < 0) { - this.b.dispense(isourceblock, new ItemStack(item)); - } - // CraftBukkit end - return itemstack; - } else { - return this.b.dispense(isourceblock, itemstack); - } - } - }; - - BlockDispenser.a((IMaterial) Items.LAVA_BUCKET, (IDispenseBehavior) dispensebehavioritem1); - BlockDispenser.a((IMaterial) Items.WATER_BUCKET, (IDispenseBehavior) dispensebehavioritem1); - BlockDispenser.a((IMaterial) Items.SALMON_BUCKET, (IDispenseBehavior) dispensebehavioritem1); - BlockDispenser.a((IMaterial) Items.COD_BUCKET, (IDispenseBehavior) dispensebehavioritem1); - BlockDispenser.a((IMaterial) Items.PUFFERFISH_BUCKET, (IDispenseBehavior) dispensebehavioritem1); - BlockDispenser.a((IMaterial) Items.TROPICAL_FISH_BUCKET, (IDispenseBehavior) dispensebehavioritem1); - BlockDispenser.a((IMaterial) Items.BUCKET, (IDispenseBehavior) (new DispenseBehaviorItem() { - private final DispenseBehaviorItem b = new DispenseBehaviorItem(); - - @Override - public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - World world = isourceblock.getWorld(); - BlockPosition blockposition = isourceblock.getBlockPosition().shift((EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - IBlockData iblockdata = world.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (block instanceof IFluidSource) { - FluidType fluidtype = ((IFluidSource) block).removeFluid(DummyGeneratorAccess.INSTANCE, blockposition, iblockdata); // CraftBukkit - - if (!(fluidtype instanceof FluidTypeFlowing)) { - return super.a(isourceblock, itemstack); - } else { - Item item = fluidtype.b(); - - // 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 = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - - fluidtype = ((IFluidSource) block).removeFluid(world, blockposition, iblockdata); // From above - // CraftBukkit end - - itemstack.subtract(1); - if (itemstack.isEmpty()) { - return new ItemStack(item); - } else { - if (((TileEntityDispenser) isourceblock.getTileEntity()).addItem(new ItemStack(item)) < 0) { - this.b.dispense(isourceblock, new ItemStack(item)); - } - - return itemstack; - } - } - } else { - return super.a(isourceblock, itemstack); - } - } - })); - BlockDispenser.a((IMaterial) Items.FLINT_AND_STEEL, (IDispenseBehavior) (new DispenseBehaviorMaybe() { - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - World world = isourceblock.getWorld(); - - // 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(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 = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - // CraftBukkit end - - this.dispensed = true; - BlockPosition blockposition = isourceblock.getBlockPosition().shift((EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - IBlockData iblockdata = world.getType(blockposition); - - if (ItemFlintAndSteel.a(iblockdata, (GeneratorAccess) world, blockposition)) { - // CraftBukkit start - Ignition by dispensing flint and steel - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition, isourceblock.getBlockPosition()).isCancelled()) { - world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); - } - // CraftBukkit end - } else if (ItemFlintAndSteel.a(iblockdata)) { - world.setTypeUpdate(blockposition, (IBlockData) iblockdata.set(BlockProperties.r, true)); - } else if (iblockdata.getBlock() instanceof BlockTNT) { - BlockTNT.a(world, blockposition); - world.a(blockposition, false); - } else { - this.dispensed = false; - } - - if (this.dispensed && itemstack.isDamaged(1, world.random, (EntityPlayer) null)) { - itemstack.setCount(0); - } - - return itemstack; - } - })); - BlockDispenser.a((IMaterial) Items.BONE_MEAL, (IDispenseBehavior) (new DispenseBehaviorMaybe() { - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - this.dispensed = true; - World world = isourceblock.getWorld(); - BlockPosition blockposition = isourceblock.getBlockPosition().shift((EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - // 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 = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - - world.captureTreeGeneration = true; - // CraftBukkit end - - if (!ItemBoneMeal.a(itemstack, world, blockposition) && !ItemBoneMeal.a(itemstack, world, blockposition, (EnumDirection) null)) { - this.dispensed = false; - } else if (!world.isClientSide) { - world.triggerEffect(2005, blockposition, 0); - } - // CraftBukkit start - world.captureTreeGeneration = false; - if (world.capturedBlockStates.size() > 0) { - 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 structureEvent = null; - if (treeType != null) { - structureEvent = new StructureGrowEvent(location, treeType, false, null, blocks); - org.bukkit.Bukkit.getPluginManager().callEvent(structureEvent); - } - if (structureEvent == null || !structureEvent.isCancelled()) { - for (org.bukkit.block.BlockState blockstate : blocks) { - blockstate.update(true); - } - } - } - // CraftBukkit end - - return itemstack; - } - })); - BlockDispenser.a((IMaterial) Blocks.TNT, (IDispenseBehavior) (new DispenseBehaviorItem() { - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - World world = isourceblock.getWorld(); - BlockPosition blockposition = isourceblock.getBlockPosition().shift((EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - // EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, (EntityLiving) null); - - // 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((double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D)); - if (!BlockDispenser.eventFired) { - world.getServer().getPluginManager().callEvent(event); - } - - if (event.isCancelled()) { - itemstack.add(1); - return itemstack; - } - - if (!event.getItem().equals(craftItem)) { - itemstack.add(1); - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - - EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(world, event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ(), (EntityLiving) null); - // CraftBukkit end - - world.addEntity(entitytntprimed); - world.playSound((EntityHuman) null, entitytntprimed.locX, entitytntprimed.locY, entitytntprimed.locZ, SoundEffects.ENTITY_TNT_PRIMED, SoundCategory.BLOCKS, 1.0F, 1.0F); - // itemstack.subtract(1); // CraftBukkit - handled above - return itemstack; - } - })); - DispenseBehaviorMaybe dispensebehaviormaybe = new DispenseBehaviorMaybe() { - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - this.dispensed = !ItemArmor.a(isourceblock, itemstack).isEmpty(); - return itemstack; - } - }; - - BlockDispenser.a((IMaterial) Items.CREEPER_HEAD, (IDispenseBehavior) dispensebehaviormaybe); - BlockDispenser.a((IMaterial) Items.ZOMBIE_HEAD, (IDispenseBehavior) dispensebehaviormaybe); - BlockDispenser.a((IMaterial) Items.DRAGON_HEAD, (IDispenseBehavior) dispensebehaviormaybe); - BlockDispenser.a((IMaterial) Items.SKELETON_SKULL, (IDispenseBehavior) dispensebehaviormaybe); - BlockDispenser.a((IMaterial) Items.PLAYER_HEAD, (IDispenseBehavior) dispensebehaviormaybe); - BlockDispenser.a((IMaterial) Items.WITHER_SKELETON_SKULL, (IDispenseBehavior) (new DispenseBehaviorMaybe() { - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - World world = isourceblock.getWorld(); - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - BlockPosition blockposition = isourceblock.getBlockPosition().shift(enumdirection); - - // 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 = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - // CraftBukkit end - - this.dispensed = true; - if (world.isEmpty(blockposition) && BlockWitherSkull.b(world, blockposition, itemstack)) { - world.setTypeAndData(blockposition, (IBlockData) Blocks.WITHER_SKELETON_SKULL.getBlockData().set(BlockSkull.a, enumdirection.k() == EnumDirection.EnumAxis.Y ? 0 : enumdirection.opposite().get2DRotationValue() * 4), 3); - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntitySkull) { - BlockWitherSkull.a(world, blockposition, (TileEntitySkull) tileentity); - } - - itemstack.subtract(1); - } else if (ItemArmor.a(isourceblock, itemstack).isEmpty()) { - this.dispensed = false; - } - - return itemstack; - } - })); - BlockDispenser.a((IMaterial) Blocks.CARVED_PUMPKIN, (IDispenseBehavior) (new DispenseBehaviorMaybe() { - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - World world = isourceblock.getWorld(); - BlockPosition blockposition = isourceblock.getBlockPosition().shift((EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - BlockPumpkinCarved blockpumpkincarved = (BlockPumpkinCarved) Blocks.CARVED_PUMPKIN; - - // 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 = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - // CraftBukkit end - - this.dispensed = true; - if (world.isEmpty(blockposition) && blockpumpkincarved.a((IWorldReader) world, blockposition)) { - if (!world.isClientSide) { - world.setTypeAndData(blockposition, blockpumpkincarved.getBlockData(), 3); - } - - itemstack.subtract(1); - } else { - ItemStack itemstack1 = ItemArmor.a(isourceblock, itemstack); - - if (itemstack1.isEmpty()) { - this.dispensed = false; - } - } - - return itemstack; - } - })); - BlockDispenser.a((IMaterial) Blocks.SHULKER_BOX.getItem(), (IDispenseBehavior) (new DispenseBehaviorShulkerBox())); - EnumColor[] aenumcolor = EnumColor.values(); - int i = aenumcolor.length; - - for (int j = 0; j < i; ++j) { - EnumColor enumcolor = aenumcolor[j]; - - BlockDispenser.a((IMaterial) BlockShulkerBox.a(enumcolor).getItem(), (IDispenseBehavior) (new DispenseBehaviorShulkerBox())); - } - - BlockDispenser.a((IMaterial) Items.SHEARS.getItem(), (IDispenseBehavior) (new DispenseBehaviorMaybe() { - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - World world = isourceblock.getWorld(); - // 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(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 = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - // CraftBukkit end - - if (!world.e()) { - this.dispensed = false; - BlockPosition blockposition = isourceblock.getBlockPosition().shift((EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - List list = world.a(EntitySheep.class, new AxisAlignedBB(blockposition)); - Iterator iterator1 = list.iterator(); - - while (iterator1.hasNext()) { - EntitySheep entitysheep = (EntitySheep) iterator1.next(); - - if (entitysheep.isAlive() && !entitysheep.isSheared() && !entitysheep.isBaby()) { - // CraftBukkit start - if (CraftEventFactory.callBlockShearEntityEvent(entitysheep, bukkitBlock, craftItem).isCancelled()) { - continue; - } - // CraftBukkit end - entitysheep.shear(); - if (itemstack.isDamaged(1, world.random, (EntityPlayer) null)) { - itemstack.setCount(0); - } - - this.dispensed = true; - break; - } - } - } - - return itemstack; - } - })); - } -} diff --git a/src/main/java/net/minecraft/server/IEntityAccess.java b/src/main/java/net/minecraft/server/IEntityAccess.java deleted file mode 100644 index dca18afdb..000000000 --- a/src/main/java/net/minecraft/server/IEntityAccess.java +++ /dev/null @@ -1,232 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.function.Predicate; -import java.util.stream.Stream; -import javax.annotation.Nullable; - -public interface IEntityAccess { - - List getEntities(@Nullable Entity entity, AxisAlignedBB axisalignedbb, @Nullable Predicate predicate); - - List a(Class oclass, AxisAlignedBB axisalignedbb, @Nullable Predicate predicate); - - default List b(Class oclass, AxisAlignedBB axisalignedbb, @Nullable Predicate predicate) { - return this.a(oclass, axisalignedbb, predicate); - } - - List getPlayers(); - - default List getEntities(@Nullable Entity entity, AxisAlignedBB axisalignedbb) { - return this.getEntities(entity, axisalignedbb, IEntitySelector.f); - } - - default boolean a(@Nullable Entity entity, VoxelShape voxelshape) { - return voxelshape.isEmpty() ? true : this.getEntities(entity, voxelshape.getBoundingBox()).stream().filter((entity1) -> { - return !entity1.dead && entity1.i && (entity == null || !entity1.x(entity)); - }).noneMatch((entity1) -> { - return VoxelShapes.c(voxelshape, VoxelShapes.a(entity1.getBoundingBox()), OperatorBoolean.AND); - }); - } - - default List a(Class oclass, AxisAlignedBB axisalignedbb) { - return this.a(oclass, axisalignedbb, IEntitySelector.f); - } - - default List b(Class oclass, AxisAlignedBB axisalignedbb) { - return this.b(oclass, axisalignedbb, IEntitySelector.f); - } - - default Stream a(@Nullable Entity entity, AxisAlignedBB axisalignedbb, Set set) { - if (axisalignedbb.a() < 1.0E-7D) { - return Stream.empty(); - } else { - AxisAlignedBB axisalignedbb1 = axisalignedbb.g(1.0E-7D); - Stream stream = this.getEntities(entity, axisalignedbb1).stream().filter((entity1) -> { // Paper - decompile fix - return !set.contains(entity1); - }).filter((entity1) -> { - return entity == null || !entity.x(entity1); - }).flatMap((entity1) -> { - return Stream.of(entity1.aq(), entity == null ? null : entity.j(entity1)); - }).filter(Objects::nonNull); - - return stream.filter(axisalignedbb1::c).map(VoxelShapes::a); - } - } - - @Nullable - default EntityHuman a(double d0, double d1, double d2, double d3, @Nullable Predicate predicate) { - double d4 = -1.0D; - EntityHuman entityhuman = null; - Iterator iterator = this.getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman1 = (EntityHuman) iterator.next(); - - if (predicate == null || predicate.test(entityhuman1)) { - double d5 = entityhuman1.e(d0, d1, d2); - - if ((d3 < 0.0D || d5 < d3 * d3) && (d4 == -1.0D || d5 < d4)) { - d4 = d5; - entityhuman = entityhuman1; - } - } - } - - return entityhuman; - } - - @Nullable - default EntityHuman findNearbyPlayer(Entity entity, double d0) { - return this.a(entity.locX, entity.locY, entity.locZ, d0, false); - } - - @Nullable - default EntityHuman a(double d0, double d1, double d2, double d3, boolean flag) { - Predicate predicate = flag ? IEntitySelector.e : IEntitySelector.f; - - return this.a(d0, d1, d2, d3, predicate); - } - - @Nullable - default EntityHuman a(double d0, double d1, double d2) { - double d3 = -1.0D; - EntityHuman entityhuman = null; - Iterator iterator = this.getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman1 = (EntityHuman) iterator.next(); - - if (IEntitySelector.f.test(entityhuman1)) { - double d4 = entityhuman1.e(d0, entityhuman1.locY, d1); - - if ((d2 < 0.0D || d4 < d2 * d2) && (d3 == -1.0D || d4 < d3)) { - d3 = d4; - entityhuman = entityhuman1; - } - } - } - - return entityhuman; - } - - default boolean isPlayerNearby(double d0, double d1, double d2, double d3) { - Iterator iterator = this.getPlayers().iterator(); - - double d4; - - do { - EntityHuman entityhuman; - - do { - do { - if (!iterator.hasNext()) { - return false; - } - - entityhuman = (EntityHuman) iterator.next(); - } while (!IEntitySelector.f.test(entityhuman)); - } while (!IEntitySelector.b.test(entityhuman)); - - d4 = entityhuman.e(d0, d1, d2); - } while (d3 >= 0.0D && d4 >= d3 * d3); - - return true; - } - - @Nullable - default EntityHuman a(PathfinderTargetCondition pathfindertargetcondition, EntityLiving entityliving) { - return (EntityHuman) this.a(this.getPlayers(), pathfindertargetcondition, entityliving, entityliving.locX, entityliving.locY, entityliving.locZ); - } - - @Nullable - default EntityHuman a(PathfinderTargetCondition pathfindertargetcondition, EntityLiving entityliving, double d0, double d1, double d2) { - return (EntityHuman) this.a(this.getPlayers(), pathfindertargetcondition, entityliving, d0, d1, d2); - } - - @Nullable - default EntityHuman a(PathfinderTargetCondition pathfindertargetcondition, double d0, double d1, double d2) { - return (EntityHuman) this.a(this.getPlayers(), pathfindertargetcondition, (EntityLiving) null, d0, d1, d2); - } - - @Nullable - default T a(Class oclass, PathfinderTargetCondition pathfindertargetcondition, @Nullable EntityLiving entityliving, double d0, double d1, double d2, AxisAlignedBB axisalignedbb) { - return this.a(this.a(oclass, axisalignedbb, null), pathfindertargetcondition, entityliving, d0, d1, d2); // Paper - decompile fix - } - - @Nullable - default T b(Class oclass, PathfinderTargetCondition pathfindertargetcondition, @Nullable EntityLiving entityliving, double d0, double d1, double d2, AxisAlignedBB axisalignedbb) { - return this.a(this.b(oclass, axisalignedbb, null), pathfindertargetcondition, entityliving, d0, d1, d2); // Paper - decompile fix - } - - @Nullable - default T a(List list, PathfinderTargetCondition pathfindertargetcondition, @Nullable EntityLiving entityliving, double d0, double d1, double d2) { - double d3 = -1.0D; - T t0 = null; - Iterator iterator = list.iterator(); // Paper - decompile fix - - while (iterator.hasNext()) { - T t1 = iterator.next(); // Paper - decompile fix - - if (pathfindertargetcondition.a(entityliving, t1)) { - double d4 = t1.e(d0, d1, d2); - - if (d3 == -1.0D || d4 < d3) { - d3 = d4; - t0 = t1; - } - } - } - - return t0; - } - - default List a(PathfinderTargetCondition pathfindertargetcondition, EntityLiving entityliving, AxisAlignedBB axisalignedbb) { - List list = Lists.newArrayList(); - Iterator iterator = this.getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman = (EntityHuman) iterator.next(); - - if (axisalignedbb.e(entityhuman.locX, entityhuman.locY, entityhuman.locZ) && pathfindertargetcondition.a(entityliving, entityhuman)) { - list.add(entityhuman); - } - } - - return list; - } - - default List a(Class oclass, PathfinderTargetCondition pathfindertargetcondition, EntityLiving entityliving, AxisAlignedBB axisalignedbb) { - List list = this.a(oclass, axisalignedbb, (Predicate) null); - List list1 = Lists.newArrayList(); - Iterator iterator = list.iterator(); // Paper - decompile fix - - while (iterator.hasNext()) { - T t0 = iterator.next(); // Paper - decompile fix - - if (pathfindertargetcondition.a(entityliving, t0)) { - list1.add(t0); - } - } - - return list1; - } - - @Nullable - default EntityHuman b(UUID uuid) { - for (int i = 0; i < this.getPlayers().size(); ++i) { - EntityHuman entityhuman = (EntityHuman) this.getPlayers().get(i); - - if (uuid.equals(entityhuman.getUniqueID())) { - return entityhuman; - } - } - - return null; - } -} diff --git a/src/main/java/net/minecraft/server/IEntitySelector.java b/src/main/java/net/minecraft/server/IEntitySelector.java deleted file mode 100644 index 56739e6ed..000000000 --- a/src/main/java/net/minecraft/server/IEntitySelector.java +++ /dev/null @@ -1,96 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Predicates; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public final class IEntitySelector { - - public static final Predicate a = Entity::isAlive; - public static final Predicate b = EntityLiving::isAlive; - public static final Predicate c = (entity) -> { - return entity.isAlive() && !entity.isVehicle() && !entity.isPassenger(); - }; - public static final Predicate isInventory() { return d; } // Paper - OBFHELPER - public static final Predicate d = (entity) -> { - return entity instanceof IInventory && entity.isAlive(); - }; - public static Predicate canAITarget() { return e; } // Paper - OBFHELPER - public static final Predicate e = (entity) -> { - return !(entity instanceof EntityHuman) || !entity.isSpectator() && !((EntityHuman) entity).isCreative(); - }; - public static Predicate notSpectator() { return f; } // Paper - OBFHELPER - public static final Predicate f = (entity) -> { - return !entity.isSpectator(); - }; - - public static Predicate a(double d0, double d1, double d2, double d3) { - double d4 = d3 * d3; - - return (entity) -> { - return entity != null && entity.e(d0, d1, d2) <= d4; - }; - } - - public static Predicate a(Entity entity) { - ScoreboardTeamBase scoreboardteambase = entity.getScoreboardTeam(); - ScoreboardTeamBase.EnumTeamPush scoreboardteambase_enumteampush = scoreboardteambase == null ? ScoreboardTeamBase.EnumTeamPush.ALWAYS : scoreboardteambase.getCollisionRule(); - - return (Predicate) (scoreboardteambase_enumteampush == ScoreboardTeamBase.EnumTeamPush.NEVER ? Predicates.alwaysFalse() : IEntitySelector.f.and((entity1) -> { - if (!entity1.isCollidable()) { - return false; - } else if (entity.world.isClientSide && (!(entity1 instanceof EntityHuman) || !((EntityHuman) entity1).dG())) { - return false; - } else { - ScoreboardTeamBase scoreboardteambase1 = entity1.getScoreboardTeam(); - ScoreboardTeamBase.EnumTeamPush scoreboardteambase_enumteampush1 = scoreboardteambase1 == null ? ScoreboardTeamBase.EnumTeamPush.ALWAYS : scoreboardteambase1.getCollisionRule(); - - if (scoreboardteambase_enumteampush1 == ScoreboardTeamBase.EnumTeamPush.NEVER) { - return false; - } else { - boolean flag = scoreboardteambase != null && scoreboardteambase.isAlly(scoreboardteambase1); - - return (scoreboardteambase_enumteampush == ScoreboardTeamBase.EnumTeamPush.PUSH_OWN_TEAM || scoreboardteambase_enumteampush1 == ScoreboardTeamBase.EnumTeamPush.PUSH_OWN_TEAM) && flag ? false : scoreboardteambase_enumteampush != ScoreboardTeamBase.EnumTeamPush.PUSH_OTHER_TEAMS && scoreboardteambase_enumteampush1 != ScoreboardTeamBase.EnumTeamPush.PUSH_OTHER_TEAMS || flag; - } - } - })); - } - - public static Predicate b(Entity entity) { - return (entity1) -> { - while (true) { - if (entity1.isPassenger()) { - entity1 = entity1.getVehicle(); - if (entity1 != entity) { - continue; - } - - return false; - } - - return true; - } - }; - } - - public static class EntitySelectorEquipable implements Predicate { - - private final ItemStack a; - - public EntitySelectorEquipable(ItemStack itemstack) { - this.a = itemstack; - } - - public boolean test(@Nullable Entity entity) { - if (!entity.isAlive()) { - return false; - } else if (!(entity instanceof EntityLiving)) { - return false; - } else { - EntityLiving entityliving = (EntityLiving) entity; - - return entityliving.e(this.a); - } - } - } -} diff --git a/src/main/java/net/minecraft/server/IInventory.java b/src/main/java/net/minecraft/server/IInventory.java deleted file mode 100644 index 874f9db9e..000000000 --- a/src/main/java/net/minecraft/server/IInventory.java +++ /dev/null @@ -1,84 +0,0 @@ -package net.minecraft.server; - -import java.util.Set; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; // CraftBukkit - -public interface IInventory extends Clearable { - - int getSize(); - - boolean isNotEmpty(); - - ItemStack getItem(int i); - - ItemStack splitStack(int i, int j); - - ItemStack splitWithoutUpdate(int i); - - void setItem(int i, ItemStack itemstack); - - int getMaxStackSize(); // CraftBukkit - - void update(); - - boolean a(EntityHuman entityhuman); - - default void startOpen(EntityHuman entityhuman) {} - - default void closeContainer(EntityHuman entityhuman) {} - - default boolean b(int i, ItemStack itemstack) { - return true; - } - - default int a(Item item) { - int i = 0; - - for (int j = 0; j < this.getSize(); ++j) { - ItemStack itemstack = this.getItem(j); - - if (itemstack.getItem().equals(item)) { - i += itemstack.getCount(); - } - } - - return i; - } - - default boolean a(Set set) { - for (int i = 0; i < this.getSize(); ++i) { - ItemStack itemstack = this.getItem(i); - - if (set.contains(itemstack.getItem()) && itemstack.getCount() > 0) { - return true; - } - } - - return false; - } - - // CraftBukkit start - java.util.List getContents(); - - void onOpen(CraftHumanEntity who); - - void onClose(CraftHumanEntity who); - - java.util.List getViewers(); - - org.bukkit.inventory.InventoryHolder getOwner(); - - void setMaxStackSize(int size); - - org.bukkit.Location getLocation(); - - default IRecipe getCurrentRecipe() { - return null; - } - - default void setCurrentRecipe(IRecipe recipe) { - } - - int MAX_STACK = 64; - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/IMerchant.java b/src/main/java/net/minecraft/server/IMerchant.java deleted file mode 100644 index cf164fbfe..000000000 --- a/src/main/java/net/minecraft/server/IMerchant.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.minecraft.server; - -import java.util.OptionalInt; -import javax.annotation.Nullable; - -public interface IMerchant { - - void setTradingPlayer(@Nullable EntityHuman entityhuman); - - @Nullable - EntityHuman getTrader(); - - MerchantRecipeList getOffers(); - - void a(MerchantRecipe merchantrecipe); - - void i(ItemStack itemstack); - - World getWorld(); - - int getExperience(); - - void s(int i); - - boolean ea(); - - SoundEffect eb(); - - default boolean ei() { - return false; - } - - default void openTrade(EntityHuman entityhuman, IChatBaseComponent ichatbasecomponent, int i) { - OptionalInt optionalint = entityhuman.openContainer(new TileInventory((j, playerinventory, entityhuman1) -> { - return new ContainerMerchant(j, playerinventory, this); - }, ichatbasecomponent)); - - if (optionalint.isPresent()) { - MerchantRecipeList merchantrecipelist = this.getOffers(); - - if (!merchantrecipelist.isEmpty()) { - entityhuman.openTrade(optionalint.getAsInt(), merchantrecipelist, i, this.getExperience(), this.ea(), this.ei()); - } - } - - } - - org.bukkit.craftbukkit.inventory.CraftMerchant getCraftMerchant(); // CraftBukkit -} diff --git a/src/main/java/net/minecraft/server/IRangedEntity.java b/src/main/java/net/minecraft/server/IRangedEntity.java deleted file mode 100644 index 9b79ac77d..000000000 --- a/src/main/java/net/minecraft/server/IRangedEntity.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.minecraft.server; - -public interface IRangedEntity { - - void a(EntityLiving entityliving, float f); default void rangedAttack(EntityLiving entityliving, float f) { a(entityliving, f); } // Paper - OBFHELPER - - // - see EntitySkeletonAbstract melee goal - void q(boolean flag); default void setChargingAttack(boolean charging) { q(charging); }; // Paper -} diff --git a/src/main/java/net/minecraft/server/IRecipe.java b/src/main/java/net/minecraft/server/IRecipe.java deleted file mode 100644 index 2da873e25..000000000 --- a/src/main/java/net/minecraft/server/IRecipe.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.minecraft.server; - -public interface IRecipe { - - boolean a(C c0, World world); - - ItemStack a(C c0); - - ItemStack c(); - - default NonNullList b(C c0) { - NonNullList nonnulllist = NonNullList.a(c0.getSize(), ItemStack.a); - - for (int i = 0; i < nonnulllist.size(); ++i) { - Item item = c0.getItem(i).getItem(); - - if (item.o()) { - nonnulllist.set(i, new ItemStack(item.n())); - } - } - - return nonnulllist; - } - - default NonNullList a() { - return NonNullList.a(); - } - - default boolean isComplex() { - return false; - } - - MinecraftKey getKey(); - - RecipeSerializer getRecipeSerializer(); - - Recipes g(); - - org.bukkit.inventory.Recipe toBukkitRecipe(); // CraftBukkit -} diff --git a/src/main/java/net/minecraft/server/IWorldReader.java b/src/main/java/net/minecraft/server/IWorldReader.java deleted file mode 100644 index a25736e23..000000000 --- a/src/main/java/net/minecraft/server/IWorldReader.java +++ /dev/null @@ -1,272 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Streams; -import java.util.Collections; -import java.util.Set; -import java.util.Spliterators.AbstractSpliterator; -import java.util.function.Consumer; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; -import javax.annotation.Nullable; - -public interface IWorldReader extends IIBlockAccess { - - default boolean isEmpty(BlockPosition blockposition) { - return this.getType(blockposition).isAir(); - } - - default boolean u(BlockPosition blockposition) { - if (blockposition.getY() >= this.getSeaLevel()) { - return this.f(blockposition); - } else { - BlockPosition blockposition1 = new BlockPosition(blockposition.getX(), this.getSeaLevel(), blockposition.getZ()); - - if (!this.f(blockposition1)) { - return false; - } else { - for (blockposition1 = blockposition1.down(); blockposition1.getY() > blockposition.getY(); blockposition1 = blockposition1.down()) { - IBlockData iblockdata = this.getType(blockposition1); - - if (iblockdata.b((IBlockAccess) this, blockposition1) > 0 && !iblockdata.getMaterial().isLiquid()) { - return false; - } - } - - return true; - } - } - } - - int getLightLevel(BlockPosition blockposition, int i); - - @Nullable IChunkAccess getChunkIfLoadedImmediately(int x, int z); // Paper - ifLoaded api (we need this since current impl blocks if the chunk is loading) - @Nullable - IChunkAccess getChunkAt(int i, int j, ChunkStatus chunkstatus, boolean flag); - - @Deprecated - boolean isChunkLoaded(int i, int j); - - BlockPosition getHighestBlockYAt(HeightMap.Type heightmap_type, BlockPosition blockposition); - - int a(HeightMap.Type heightmap_type, int i, int j); - - default float v(BlockPosition blockposition) { - return this.getWorldProvider().i()[this.getLightLevel(blockposition)]; - } - - int c(); - - WorldBorder getWorldBorder(); - - boolean a(@Nullable Entity entity, VoxelShape voxelshape); - - default int c(BlockPosition blockposition, EnumDirection enumdirection) { - return this.getType(blockposition).c(this, blockposition, enumdirection); - } - - boolean e(); - - int getSeaLevel(); - - default IChunkAccess w(BlockPosition blockposition) { - return this.getChunkAt(blockposition.getX() >> 4, blockposition.getZ() >> 4); - } - - default IChunkAccess getChunkAt(int i, int j) { - return this.getChunkAt(i, j, ChunkStatus.FULL, true); - } - - default IChunkAccess getChunkAt(int i, int j, ChunkStatus chunkstatus) { - return this.getChunkAt(i, j, chunkstatus, true); - } - - default ChunkStatus O() { - return ChunkStatus.EMPTY; - } - - default boolean a(IBlockData iblockdata, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - VoxelShape voxelshape = iblockdata.b((IBlockAccess) this, blockposition, voxelshapecollision); - - return voxelshape.isEmpty() || this.a((Entity) null, voxelshape.a((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ())); - } - - default boolean i(Entity entity) { - return this.a(entity, VoxelShapes.a(entity.getBoundingBox())); - } - - default boolean c(AxisAlignedBB axisalignedbb) { - return this.b((Entity) null, axisalignedbb, Collections.emptySet()); - } - - default boolean getCubes(Entity entity) { - return this.b(entity, entity.getBoundingBox(), Collections.emptySet()); - } - - default boolean getCubes(Entity entity, AxisAlignedBB axisalignedbb) { - return this.b(entity, axisalignedbb, Collections.emptySet()); - } - - default boolean b(@Nullable Entity entity, AxisAlignedBB axisalignedbb, Set set) { - return this.c(entity, axisalignedbb, set).allMatch(VoxelShape::isEmpty); - } - - default Stream a(@Nullable Entity entity, AxisAlignedBB axisalignedbb, Set set) { - return Stream.empty(); - } - - default Stream c(@Nullable Entity entity, AxisAlignedBB axisalignedbb, Set set) { - return Streams.concat(new Stream[]{this.b(entity, axisalignedbb), this.a(entity, axisalignedbb, set)}); - } - - default Stream b(@Nullable final Entity entity, AxisAlignedBB axisalignedbb) { - int i = MathHelper.floor(axisalignedbb.minX - 1.0E-7D) - 1; - int j = MathHelper.floor(axisalignedbb.maxX + 1.0E-7D) + 1; - int k = MathHelper.floor(axisalignedbb.minY - 1.0E-7D) - 1; - int l = MathHelper.floor(axisalignedbb.maxY + 1.0E-7D) + 1; - int i1 = MathHelper.floor(axisalignedbb.minZ - 1.0E-7D) - 1; - int j1 = MathHelper.floor(axisalignedbb.maxZ + 1.0E-7D) + 1; - final VoxelShapeCollision voxelshapecollision = entity == null ? VoxelShapeCollision.a() : VoxelShapeCollision.a(entity); - final CursorPosition cursorposition = new CursorPosition(i, k, i1, j, l, j1); - final BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - final VoxelShape voxelshape = VoxelShapes.a(axisalignedbb); - - return StreamSupport.stream(new AbstractSpliterator(Long.MAX_VALUE, 1280) { - boolean a = entity == null; - - public boolean tryAdvance(Consumer consumer) { - if (!this.a) { - this.a = true; - VoxelShape voxelshape1 = IWorldReader.this.getWorldBorder().a(); - boolean flag = VoxelShapes.c(voxelshape1, VoxelShapes.a(entity.getBoundingBox().shrink(1.0E-7D)), OperatorBoolean.AND); - boolean flag1 = VoxelShapes.c(voxelshape1, VoxelShapes.a(entity.getBoundingBox().g(1.0E-7D)), OperatorBoolean.AND); - - if (!flag && flag1) { - consumer.accept(voxelshape1); - return true; - } - } - - while (cursorposition.a()) { - int k1 = cursorposition.b(); - int l1 = cursorposition.c(); - int i2 = cursorposition.d(); - int j2 = cursorposition.e(); - - if (j2 != 3) { - int k2 = k1 >> 4; - int l2 = i2 >> 4; - IChunkAccess ichunkaccess = IWorldReader.this.getChunkAt(k2, l2, IWorldReader.this.O(), false); - - if (ichunkaccess != null) { - blockposition_mutableblockposition.d(k1, l1, i2); - IBlockData iblockdata = ichunkaccess.getType(blockposition_mutableblockposition); - - if ((j2 != 1 || iblockdata.f()) && (j2 != 2 || iblockdata.getBlock() == Blocks.MOVING_PISTON)) { - VoxelShape voxelshape2 = iblockdata.b((IBlockAccess) IWorldReader.this, blockposition_mutableblockposition, voxelshapecollision); - VoxelShape voxelshape3 = voxelshape2.a((double) k1, (double) l1, (double) i2); - - if (VoxelShapes.c(voxelshape, voxelshape3, OperatorBoolean.AND)) { - consumer.accept(voxelshape3); - return true; - } - } - } - } - } - - return false; - } - }, false); - } - - default boolean x(BlockPosition blockposition) { - return this.getFluid(blockposition).a(TagsFluid.WATER); - } - - default boolean containsLiquid(AxisAlignedBB axisalignedbb) { - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.f(axisalignedbb.maxX); - int k = MathHelper.floor(axisalignedbb.minY); - int l = MathHelper.f(axisalignedbb.maxY); - int i1 = MathHelper.floor(axisalignedbb.minZ); - int j1 = MathHelper.f(axisalignedbb.maxZ); - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - 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(blockposition_pooledblockposition.d(k1, l1, i2)); - - if (!iblockdata.p().isEmpty()) { - boolean flag = true; - - return flag; - } - } - } - } - - return false; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - } - - default int getLightLevel(BlockPosition blockposition) { - return this.d(blockposition, this.c()); - } - - default int d(BlockPosition blockposition, int i) { - return blockposition.getX() >= -30000000 && blockposition.getZ() >= -30000000 && blockposition.getX() < 30000000 && blockposition.getZ() < 30000000 ? this.getLightLevel(blockposition, i) : 15; - } - - @Deprecated - default boolean isLoaded(BlockPosition blockposition) { - return this.isChunkLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4); - } - - @Deprecated - default boolean areChunksLoadedBetween(BlockPosition blockposition, BlockPosition blockposition1) { - return this.isAreaLoaded(blockposition.getX(), blockposition.getY(), blockposition.getZ(), blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); - } - - @Deprecated - default boolean isAreaLoaded(int i, int j, int k, int l, int i1, int j1) { - 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 (!this.isChunkLoaded(k1, l1)) { - return false; - } - } - } - - return true; - } else { - return false; - } - } - - WorldProvider getWorldProvider(); -} diff --git a/src/main/java/net/minecraft/server/IWorldWriter.java b/src/main/java/net/minecraft/server/IWorldWriter.java deleted file mode 100644 index 38cb1d6e3..000000000 --- a/src/main/java/net/minecraft/server/IWorldWriter.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.minecraft.server; - -public interface IWorldWriter { - - boolean setTypeAndData(BlockPosition blockposition, IBlockData iblockdata, int i); - - boolean a(BlockPosition blockposition, boolean flag); - - boolean b(BlockPosition blockposition, boolean flag); - - default boolean addEntity(Entity entity) { - return false; - } - - // CraftBukkit start - default boolean addEntity(Entity entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason reason) { - return false; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/InventoryCraftResult.java b/src/main/java/net/minecraft/server/InventoryCraftResult.java deleted file mode 100644 index 06c0bc5b1..000000000 --- a/src/main/java/net/minecraft/server/InventoryCraftResult.java +++ /dev/null @@ -1,118 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -// CraftBukkit end - -public class InventoryCraftResult implements IInventory, RecipeHolder { - - private final NonNullList items; - private IRecipe b; - - // CraftBukkit start - private int maxStack = MAX_STACK; - - public java.util.List 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(); - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - - @Override - public Location getLocation() { - return null; - } - // CraftBukkit end - - public InventoryCraftResult() { - this.items = NonNullList.a(1, ItemStack.a); - } - - @Override - public int getSize() { - return 1; - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public ItemStack getItem(int i) { - return (ItemStack) this.items.get(0); - } - - @Override - public ItemStack splitStack(int i, int j) { - return ContainerUtil.a(this.items, 0); - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - return ContainerUtil.a(this.items, 0); - } - - @Override - public void setItem(int i, ItemStack itemstack) { - this.items.set(0, itemstack); - } - - @Override - public void update() {} - - @Override - public boolean a(EntityHuman entityhuman) { - return true; - } - - @Override - public void clear() { - this.items.clear(); - } - - @Override - public void a(@Nullable IRecipe irecipe) { - this.b = irecipe; - } - - @Nullable - @Override - public IRecipe U_() { - return this.b; - } -} diff --git a/src/main/java/net/minecraft/server/InventoryCrafting.java b/src/main/java/net/minecraft/server/InventoryCrafting.java deleted file mode 100644 index e02de1985..000000000 --- a/src/main/java/net/minecraft/server/InventoryCrafting.java +++ /dev/null @@ -1,170 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -// CraftBukkit start -import java.util.List; -import org.bukkit.Location; - -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.inventory.InventoryType; -// CraftBukkit end - -public class InventoryCrafting implements IInventory, AutoRecipeOutput { - - private final NonNullList items; - private final int b; - private final int c; - public final Container container; - - // CraftBukkit start - add fields - public List transaction = new java.util.ArrayList(); - private IRecipe currentRecipe; - public IInventory resultInventory; - private EntityHuman owner; - private int maxStack = MAX_STACK; - - public List getContents() { - return this.items; - } - - public void onOpen(CraftHumanEntity who) { - transaction.add(who); - } - - public InventoryType getInvType() { - return items.size() == 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(); - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - resultInventory.setMaxStackSize(size); - } - - @Override - public Location getLocation() { - return container instanceof ContainerWorkbench ? ((ContainerWorkbench) container).containerAccess.getLocation() : owner.getBukkitEntity().getLocation(); - } - - @Override - public IRecipe getCurrentRecipe() { - return currentRecipe; - } - - @Override - public void setCurrentRecipe(IRecipe currentRecipe) { - this.currentRecipe = currentRecipe; - } - - 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) { - this.items = NonNullList.a(i * j, ItemStack.a); - this.container = container; - this.b = i; - this.c = j; - } - - @Override - public int getSize() { - return this.items.size(); - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public ItemStack getItem(int i) { - return i >= this.getSize() ? ItemStack.a : (ItemStack) this.items.get(i); - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - return ContainerUtil.a(this.items, i); - } - - @Override - public ItemStack splitStack(int i, int j) { - ItemStack itemstack = ContainerUtil.a(this.items, i, j); - - if (!itemstack.isEmpty()) { - this.container.a((IInventory) this); - } - - return itemstack; - } - - @Override - public void setItem(int i, ItemStack itemstack) { - this.items.set(i, itemstack); - this.container.a((IInventory) this); - } - - @Override - public void update() {} - - @Override - public boolean a(EntityHuman entityhuman) { - return true; - } - - @Override - public void clear() { - this.items.clear(); - } - - public int f() { - return this.c; - } - - public int g() { - return this.b; - } - - @Override - public void a(AutoRecipeStackManager autorecipestackmanager) { - Iterator iterator = this.items.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - - autorecipestackmanager.a(itemstack); - } - - } -} diff --git a/src/main/java/net/minecraft/server/InventoryEnderChest.java b/src/main/java/net/minecraft/server/InventoryEnderChest.java deleted file mode 100644 index fd31b9a6d..000000000 --- a/src/main/java/net/minecraft/server/InventoryEnderChest.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.Location; -import org.bukkit.inventory.InventoryHolder; - -public class InventoryEnderChest extends InventorySubcontainer { - - private TileEntityEnderChest a; public TileEntityEnderChest getTileEntity() { return a; } // Paper - OBFHELPER - // CraftBukkit start - private final EntityHuman owner; - - public InventoryHolder getBukkitOwner() { - return owner.getBukkitEntity(); - } - - @Override - public Location getLocation() { - if (getTileEntity() == null) return null; // Paper - return null if there is no TE bound (opened by plugin) - return new Location(this.a.getWorld().getWorld(), this.a.getPosition().getX(), this.a.getPosition().getY(), this.a.getPosition().getZ()); - } - - public InventoryEnderChest(EntityHuman owner) { - super(27); - this.owner = owner; - // CraftBukkit end - } - - 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, ItemStack.a); - } - - for (i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompound(i); - int j = nbttagcompound.getByte("Slot") & 255; - - if (j >= 0 && j < this.getSize()) { - this.setItem(j, ItemStack.a(nbttagcompound)); - } - } - - } - - public NBTTagList f() { - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.getSize(); ++i) { - ItemStack itemstack = this.getItem(i); - - if (!itemstack.isEmpty()) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setByte("Slot", (byte) i); - itemstack.save(nbttagcompound); - nbttaglist.add(nbttagcompound); - } - } - - return nbttaglist; - } - - @Override - public boolean a(EntityHuman entityhuman) { - return this.a != null && !this.a.a(entityhuman) ? false : super.a(entityhuman); - } - - @Override - public void startOpen(EntityHuman entityhuman) { - if (this.a != null) { - this.a.d(); - } - - super.startOpen(entityhuman); - } - - @Override - public void closeContainer(EntityHuman entityhuman) { - if (this.a != null) { - this.a.f(); - } - - super.closeContainer(entityhuman); - this.a = null; - } -} diff --git a/src/main/java/net/minecraft/server/InventoryLargeChest.java b/src/main/java/net/minecraft/server/InventoryLargeChest.java deleted file mode 100644 index d4c39f0b3..000000000 --- a/src/main/java/net/minecraft/server/InventoryLargeChest.java +++ /dev/null @@ -1,149 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Location; - -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -// CraftBukkit end - -public class InventoryLargeChest implements IInventory { - - public final IInventory left; - public final IInventory right; - - // CraftBukkit start - add fields and methods - public List transaction = new java.util.ArrayList(); - - public List getContents() { - List result = new ArrayList(this.getSize()); - for (int i = 0; i < this.getSize(); i++) { - result.add(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); - } - - @Override - public Location getLocation() { - return left.getLocation(); // TODO: right? - } - // CraftBukkit end - - public InventoryLargeChest(IInventory iinventory, IInventory iinventory1) { - if (iinventory == null) { - iinventory = iinventory1; - } - - if (iinventory1 == null) { - iinventory1 = iinventory; - } - - this.left = iinventory; - this.right = iinventory1; - } - - @Override - public int getSize() { - return this.left.getSize() + this.right.getSize(); - } - - @Override - public boolean isNotEmpty() { - return this.left.isNotEmpty() && this.right.isNotEmpty(); - } - - public boolean a(IInventory iinventory) { - return this.left == iinventory || this.right == iinventory; - } - - @Override - public ItemStack getItem(int i) { - return i >= this.left.getSize() ? this.right.getItem(i - this.left.getSize()) : this.left.getItem(i); - } - - @Override - 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); - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - return i >= this.left.getSize() ? this.right.splitWithoutUpdate(i - this.left.getSize()) : this.left.splitWithoutUpdate(i); - } - - @Override - 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); - } - - } - - @Override - public int getMaxStackSize() { - return Math.min(this.left.getMaxStackSize(), this.right.getMaxStackSize()); // CraftBukkit - check both sides - } - - @Override - public void update() { - this.left.update(); - this.right.update(); - } - - @Override - public boolean a(EntityHuman entityhuman) { - return this.left.a(entityhuman) && this.right.a(entityhuman); - } - - @Override - public void startOpen(EntityHuman entityhuman) { - this.left.startOpen(entityhuman); - this.right.startOpen(entityhuman); - } - - @Override - public void closeContainer(EntityHuman entityhuman) { - this.left.closeContainer(entityhuman); - this.right.closeContainer(entityhuman); - } - - @Override - public boolean b(int i, ItemStack itemstack) { - return i >= this.left.getSize() ? this.right.b(i - this.left.getSize(), itemstack) : this.left.b(i, itemstack); - } - - @Override - public void clear() { - this.left.clear(); - this.right.clear(); - } -} diff --git a/src/main/java/net/minecraft/server/InventoryMerchant.java b/src/main/java/net/minecraft/server/InventoryMerchant.java deleted file mode 100644 index 26d7bad5c..000000000 --- a/src/main/java/net/minecraft/server/InventoryMerchant.java +++ /dev/null @@ -1,198 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import javax.annotation.Nullable; -// CraftBukkit start -import java.util.List; -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.craftbukkit.entity.CraftAbstractVillager; -import org.bukkit.entity.HumanEntity; -// CraftBukkit end - -public class InventoryMerchant implements IInventory { - - private final IMerchant merchant; - private final NonNullList itemsInSlots; - @Nullable - private MerchantRecipe recipe; - public int selectedIndex; - private int e; - - // CraftBukkit start - add fields and methods - public List transaction = new java.util.ArrayList(); - private int maxStack = MAX_STACK; - - public List getContents() { - return this.itemsInSlots; - } - - public void onOpen(CraftHumanEntity who) { - transaction.add(who); - } - - public void onClose(CraftHumanEntity who) { - transaction.remove(who); - merchant.setTradingPlayer((EntityHuman) null); // SPIGOT-4860 - } - - public List getViewers() { - return transaction; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int i) { - maxStack = i; - } - - public org.bukkit.inventory.InventoryHolder getOwner() { - return (merchant instanceof EntityVillagerAbstract) ? (CraftAbstractVillager) ((EntityVillagerAbstract) this.merchant).getBukkitEntity() : null; - } - - @Override - public Location getLocation() { - return (merchant instanceof EntityVillager) ? ((EntityVillager) this.merchant).getBukkitEntity().getLocation() : null; - } - // CraftBukkit end - - public InventoryMerchant(IMerchant imerchant) { - this.itemsInSlots = NonNullList.a(3, ItemStack.a); - this.merchant = imerchant; - } - - @Override - public int getSize() { - return this.itemsInSlots.size(); - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.itemsInSlots.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public ItemStack getItem(int i) { - return (ItemStack) this.itemsInSlots.get(i); - } - - @Override - public ItemStack splitStack(int i, int j) { - ItemStack itemstack = (ItemStack) this.itemsInSlots.get(i); - - if (i == 2 && !itemstack.isEmpty()) { - return ContainerUtil.a(this.itemsInSlots, i, itemstack.getCount()); - } else { - ItemStack itemstack1 = ContainerUtil.a(this.itemsInSlots, i, j); - - if (!itemstack1.isEmpty() && this.d(i)) { - this.f(); - } - - return itemstack1; - } - } - - private boolean d(int i) { - return i == 0 || i == 1; - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - return ContainerUtil.a(this.itemsInSlots, i); - } - - @Override - public void setItem(int i, ItemStack itemstack) { - this.itemsInSlots.set(i, itemstack); - if (!itemstack.isEmpty() && itemstack.getCount() > this.getMaxStackSize()) { - itemstack.setCount(this.getMaxStackSize()); - } - - if (this.d(i)) { - this.f(); - } - - } - - @Override - public boolean a(EntityHuman entityhuman) { - return this.merchant.getTrader() == entityhuman; - } - - @Override - public void update() { - this.f(); - } - - public void f() { - this.recipe = null; - ItemStack itemstack; - ItemStack itemstack1; - - if (((ItemStack) this.itemsInSlots.get(0)).isEmpty()) { - itemstack = (ItemStack) this.itemsInSlots.get(1); - itemstack1 = ItemStack.a; - } else { - itemstack = (ItemStack) this.itemsInSlots.get(0); - itemstack1 = (ItemStack) this.itemsInSlots.get(1); - } - - if (itemstack.isEmpty()) { - this.setItem(2, ItemStack.a); - this.e = 0; - } else { - MerchantRecipeList merchantrecipelist = this.merchant.getOffers(); - - if (!merchantrecipelist.isEmpty()) { - MerchantRecipe merchantrecipe = merchantrecipelist.a(itemstack, itemstack1, this.selectedIndex); - - if (merchantrecipe == null || merchantrecipe.isFullyUsed()) { - this.recipe = merchantrecipe; - merchantrecipe = merchantrecipelist.a(itemstack1, itemstack, this.selectedIndex); - } - - if (merchantrecipe != null && !merchantrecipe.isFullyUsed()) { - this.recipe = merchantrecipe; - this.setItem(2, merchantrecipe.f()); - this.e = merchantrecipe.getXp(); - } else { - this.setItem(2, ItemStack.a); - this.e = 0; - } - } - - this.merchant.i(this.getItem(2)); - } - } - - @Nullable - public MerchantRecipe getRecipe() { - return this.recipe; - } - - public void c(int i) { - this.selectedIndex = i; - this.f(); - } - - @Override - public void clear() { - this.itemsInSlots.clear(); - } -} diff --git a/src/main/java/net/minecraft/server/InventorySubcontainer.java b/src/main/java/net/minecraft/server/InventorySubcontainer.java deleted file mode 100644 index af84469d9..000000000 --- a/src/main/java/net/minecraft/server/InventorySubcontainer.java +++ /dev/null @@ -1,264 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; -import java.util.stream.Collectors; - -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -// CraftBukkit end - -public class InventorySubcontainer implements IInventory, AutoRecipeOutput { - - private final int a; - public final NonNullList items; - private List c; - - // CraftBukkit start - add fields and methods - public List transaction = new java.util.ArrayList(); - private int maxStack = MAX_STACK; - protected org.bukkit.inventory.InventoryHolder bukkitOwner; - - public List 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; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int i) { - maxStack = i; - } - - public org.bukkit.inventory.InventoryHolder getOwner() { - return bukkitOwner; - } - - @Override - public Location getLocation() { - return null; - } - - public InventorySubcontainer(int i) { - this(i, null); - } - - public InventorySubcontainer(int i, org.bukkit.inventory.InventoryHolder owner) { - this.bukkitOwner = owner; - // CraftBukkit end - this.a = i; - this.items = NonNullList.a(i, ItemStack.a); - } - - public InventorySubcontainer(ItemStack... aitemstack) { - this.a = aitemstack.length; - this.items = NonNullList.a(ItemStack.a, aitemstack); - } - - public void a(IInventoryListener iinventorylistener) { - if (this.c == null) { - this.c = Lists.newArrayList(); - } - - this.c.add(iinventorylistener); - } - - public void b(IInventoryListener iinventorylistener) { - this.c.remove(iinventorylistener); - } - - @Override - public ItemStack getItem(int i) { - return i >= 0 && i < this.items.size() ? (ItemStack) this.items.get(i) : ItemStack.a; - } - - @Override - public ItemStack splitStack(int i, int j) { - ItemStack itemstack = ContainerUtil.a(this.items, i, j); - - if (!itemstack.isEmpty()) { - this.update(); - } - - return itemstack; - } - - public ItemStack a(Item item, int i) { - ItemStack itemstack = new ItemStack(item, 0); - - for (int j = this.a - 1; j >= 0; --j) { - ItemStack itemstack1 = this.getItem(j); - - if (itemstack1.getItem().equals(item)) { - int k = i - itemstack.getCount(); - ItemStack itemstack2 = itemstack1.cloneAndSubtract(k); - - itemstack.add(itemstack2.getCount()); - if (itemstack.getCount() == i) { - break; - } - } - } - - if (!itemstack.isEmpty()) { - this.update(); - } - - return itemstack; - } - - public ItemStack a(ItemStack itemstack) { - ItemStack itemstack1 = itemstack.cloneItemStack(); - - this.c(itemstack1); - if (itemstack1.isEmpty()) { - return ItemStack.a; - } else { - this.b(itemstack1); - return itemstack1.isEmpty() ? ItemStack.a : itemstack1; - } - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - ItemStack itemstack = (ItemStack) this.items.get(i); - - if (itemstack.isEmpty()) { - return ItemStack.a; - } else { - this.items.set(i, ItemStack.a); - return itemstack; - } - } - - @Override - public void setItem(int i, ItemStack itemstack) { - this.items.set(i, itemstack); - if (!itemstack.isEmpty() && itemstack.getCount() > this.getMaxStackSize()) { - itemstack.setCount(this.getMaxStackSize()); - } - - this.update(); - } - - @Override - public int getSize() { - return this.a; - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public void update() { - if (this.c != null) { - Iterator iterator = this.c.iterator(); - - while (iterator.hasNext()) { - IInventoryListener iinventorylistener = (IInventoryListener) iterator.next(); - - iinventorylistener.a(this); - } - } - - } - - @Override - public boolean a(EntityHuman entityhuman) { - return true; - } - - @Override - public void clear() { - this.items.clear(); - this.update(); - } - - @Override - public void a(AutoRecipeStackManager autorecipestackmanager) { - Iterator iterator = this.items.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - - autorecipestackmanager.b(itemstack); - } - - } - - public String toString() { - return ((List) this.items.stream().filter((itemstack) -> { - return !itemstack.isEmpty(); - }).collect(Collectors.toList())).toString(); - } - - private void b(ItemStack itemstack) { - for (int i = 0; i < this.a; ++i) { - ItemStack itemstack1 = this.getItem(i); - - if (itemstack1.isEmpty()) { - this.setItem(i, itemstack.cloneItemStack()); - itemstack.setCount(0); - return; - } - } - - } - - private void c(ItemStack itemstack) { - for (int i = 0; i < this.a; ++i) { - ItemStack itemstack1 = this.getItem(i); - - if (ItemStack.c(itemstack1, itemstack)) { - this.a(itemstack, itemstack1); - if (itemstack.isEmpty()) { - return; - } - } - } - - } - - private void a(ItemStack itemstack, ItemStack itemstack1) { - int i = Math.min(this.getMaxStackSize(), itemstack1.getMaxStackSize()); - int j = Math.min(itemstack.getCount(), i - itemstack1.getCount()); - - if (j > 0) { - itemstack1.add(j); - itemstack.subtract(j); - this.update(); - } - - } -} diff --git a/src/main/java/net/minecraft/server/ItemArmor.java b/src/main/java/net/minecraft/server/ItemArmor.java deleted file mode 100644 index dec03e4ae..000000000 --- a/src/main/java/net/minecraft/server/ItemArmor.java +++ /dev/null @@ -1,132 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Multimap; -import java.util.List; -import java.util.UUID; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.event.block.BlockDispenseArmorEvent; -// CraftBukkit end - -public class ItemArmor extends Item { - - private static final UUID[] k = new UUID[]{UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")}; - public static final IDispenseBehavior a = new DispenseBehaviorItem() { - @Override - protected ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - ItemStack itemstack1 = ItemArmor.a(isourceblock, itemstack); - - return itemstack1.isEmpty() ? super.a(isourceblock, itemstack) : itemstack1; - } - }; - protected final EnumItemSlot b; - protected final int c; - protected final float d; - protected final ArmorMaterial e; - - public static ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - BlockPosition blockposition = isourceblock.getBlockPosition().shift((EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING)); - List list = isourceblock.getWorld().a(EntityLiving.class, new AxisAlignedBB(blockposition), IEntitySelector.f.and(new IEntitySelector.EntitySelectorEquipable(itemstack))); - - if (list.isEmpty()) { - return ItemStack.a; - } else { - EntityLiving entityliving = (EntityLiving) list.get(0); - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - ItemStack itemstack1 = itemstack.cloneAndSubtract(1); - // CraftBukkit start - 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.getBukkitEntity()); - if (!BlockDispenser.eventFired) { - world.getServer().getPluginManager().callEvent(event); - } - - if (event.isCancelled()) { - itemstack.add(1); - return itemstack; - } - - if (!event.getItem().equals(craftItem)) { - itemstack.add(1); - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != ItemArmor.a) { - idispensebehavior.dispense(isourceblock, eventStack); - return itemstack; - } - } - // CraftBukkit end - - entityliving.setSlot(enumitemslot, itemstack1); - if (entityliving instanceof EntityInsentient) { - ((EntityInsentient) entityliving).a(enumitemslot, 2.0F); - ((EntityInsentient) entityliving).setPersistent(); - } - - return itemstack; - } - } - - public ItemArmor(ArmorMaterial armormaterial, EnumItemSlot enumitemslot, Item.Info item_info) { - super(item_info.b(armormaterial.a(enumitemslot))); - this.e = armormaterial; - this.b = enumitemslot; - this.c = armormaterial.b(enumitemslot); - this.d = armormaterial.e(); - BlockDispenser.a((IMaterial) this, ItemArmor.a); - } - - public EnumItemSlot b() { - return this.b; - } - - @Override - public int c() { - return this.e.a(); - } - - public ArmorMaterial d() { - return this.e; - } - - @Override - public boolean a(ItemStack itemstack, ItemStack itemstack1) { - return this.e.c().test(itemstack1) || super.a(itemstack, itemstack1); - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - EnumItemSlot enumitemslot = EntityInsentient.h(itemstack); - ItemStack itemstack1 = entityhuman.getEquipment(enumitemslot); - - if (itemstack1.isEmpty()) { - entityhuman.setSlot(enumitemslot, itemstack.cloneItemStack()); - itemstack.setCount(0); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } else { - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } - } - - @Override - public Multimap a(EnumItemSlot enumitemslot) { - Multimap multimap = super.a(enumitemslot); - - if (enumitemslot == this.b) { - multimap.put(GenericAttributes.ARMOR.getName(), new AttributeModifier(ItemArmor.k[enumitemslot.b()], "Armor modifier", (double) this.c, AttributeModifier.Operation.ADDITION)); - multimap.put(GenericAttributes.ARMOR_TOUGHNESS.getName(), new AttributeModifier(ItemArmor.k[enumitemslot.b()], "Armor toughness", (double) this.d, AttributeModifier.Operation.ADDITION)); - } - - return multimap; - } - - public int e() { - return this.c; - } -} diff --git a/src/main/java/net/minecraft/server/ItemArmorStand.java b/src/main/java/net/minecraft/server/ItemArmorStand.java deleted file mode 100644 index dfe932c16..000000000 --- a/src/main/java/net/minecraft/server/ItemArmorStand.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import java.util.Random; - -public class ItemArmorStand extends Item { - - public ItemArmorStand(Item.Info item_info) { - super(item_info); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - EnumDirection enumdirection = itemactioncontext.getClickedFace(); - - if (enumdirection == EnumDirection.DOWN) { - return EnumInteractionResult.FAIL; - } else { - World world = itemactioncontext.getWorld(); - BlockActionContext blockactioncontext = new BlockActionContext(itemactioncontext); - BlockPosition blockposition = blockactioncontext.getClickPosition(); - BlockPosition blockposition1 = blockposition.up(); - - if (blockactioncontext.b() && world.getType(blockposition1).a(blockactioncontext)) { - double d0 = (double) blockposition.getX(); - double d1 = (double) blockposition.getY(); - double d2 = (double) blockposition.getZ(); - List list = world.getEntities((Entity) null, new AxisAlignedBB(d0, d1, d2, d0 + 1.0D, d1 + 2.0D, d2 + 1.0D)); - - if (!list.isEmpty()) { - return EnumInteractionResult.FAIL; - } else { - ItemStack itemstack = itemactioncontext.getItemStack(); - - if (!world.isClientSide) { - world.a(blockposition, false); - world.a(blockposition1, false); - EntityArmorStand entityarmorstand = new EntityArmorStand(world, d0 + 0.5D, d1, d2 + 0.5D); - float f = (float) MathHelper.d((MathHelper.g(itemactioncontext.h() - 180.0F) + 22.5F) / 45.0F) * 45.0F; - - entityarmorstand.setPositionRotation(d0 + 0.5D, d1, d2 + 0.5D, f, 0.0F); - this.a(entityarmorstand, world.random); - EntityTypes.a(world, itemactioncontext.getEntity(), (Entity) entityarmorstand, itemstack.getTag()); - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityPlaceEvent(itemactioncontext, entityarmorstand).isCancelled()) { - return EnumInteractionResult.FAIL; - } - // CraftBukkit end - world.addEntity(entityarmorstand); - world.playSound((EntityHuman) null, entityarmorstand.locX, entityarmorstand.locY, entityarmorstand.locZ, SoundEffects.ENTITY_ARMOR_STAND_PLACE, SoundCategory.BLOCKS, 0.75F, 0.8F); - } - - itemstack.subtract(1); - return EnumInteractionResult.SUCCESS; - } - } else { - return EnumInteractionResult.FAIL; - } - } - } - - private void a(EntityArmorStand entityarmorstand, Random random) { - Vector3f vector3f = entityarmorstand.r(); - 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.s(); - f = random.nextFloat() * 10.0F - 5.0F; - vector3f1 = new Vector3f(vector3f.getX(), vector3f.getY() + f, vector3f.getZ()); - entityarmorstand.setBodyPose(vector3f1); - } -} diff --git a/src/main/java/net/minecraft/server/ItemBlock.java b/src/main/java/net/minecraft/server/ItemBlock.java deleted file mode 100644 index 0c8b11bbe..000000000 --- a/src/main/java/net/minecraft/server/ItemBlock.java +++ /dev/null @@ -1,213 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Map; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.event.block.BlockCanBuildEvent; -// CraftBukkit end - -public class ItemBlock extends Item { - - @Deprecated - private final Block a; - - public ItemBlock(Block block, Item.Info item_info) { - super(item_info); - this.a = block; - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - EnumInteractionResult enuminteractionresult = this.a(new BlockActionContext(itemactioncontext)); - - return enuminteractionresult != EnumInteractionResult.SUCCESS && this.isFood() ? this.a(itemactioncontext.e, itemactioncontext.b, itemactioncontext.c).a() : enuminteractionresult; - } - - public EnumInteractionResult a(BlockActionContext blockactioncontext) { - if (!blockactioncontext.b()) { - return EnumInteractionResult.FAIL; - } else { - BlockActionContext blockactioncontext1 = this.b(blockactioncontext); - - if (blockactioncontext1 == null) { - return EnumInteractionResult.FAIL; - } else { - IBlockData iblockdata = this.c(blockactioncontext1); - - if (iblockdata == null) { - return EnumInteractionResult.FAIL; - } else if (!this.a(blockactioncontext1, iblockdata)) { - return EnumInteractionResult.FAIL; - } else { - BlockPosition blockposition = blockactioncontext1.getClickPosition(); - World world = blockactioncontext1.getWorld(); - EntityHuman entityhuman = blockactioncontext1.getEntity(); - ItemStack itemstack = blockactioncontext1.getItemStack(); - IBlockData iblockdata1 = world.getType(blockposition); - Block block = iblockdata1.getBlock(); - - if (block == iblockdata.getBlock()) { - iblockdata1 = this.a(blockposition, world, itemstack, iblockdata1); - this.a(blockposition, world, entityhuman, itemstack, iblockdata1); - block.postPlace(world, blockposition, iblockdata1, entityhuman, itemstack); - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.y.a((EntityPlayer) entityhuman, blockposition, itemstack); - } - } - - SoundEffectType soundeffecttype = iblockdata1.r(); - - // world.playSound(entityhuman, blockposition, this.a(iblockdata1), SoundCategory.BLOCKS, (soundeffecttype.a() + 1.0F) / 2.0F, soundeffecttype.b() * 0.8F); - itemstack.subtract(1); - return EnumInteractionResult.SUCCESS; - } - } - } - } - - protected SoundEffect a(IBlockData iblockdata) { - return iblockdata.r().e(); - } - - @Nullable - public BlockActionContext b(BlockActionContext blockactioncontext) { - return blockactioncontext; - } - - protected boolean a(BlockPosition blockposition, World world, @Nullable EntityHuman entityhuman, ItemStack itemstack, IBlockData iblockdata) { - return a(world, entityhuman, blockposition, itemstack); - } - - @Nullable - protected IBlockData c(BlockActionContext blockactioncontext) { - IBlockData iblockdata = this.getBlock().getPlacedState(blockactioncontext); - - return iblockdata != null && this.b(blockactioncontext, iblockdata) ? iblockdata : null; - } - - private IBlockData a(BlockPosition blockposition, World world, ItemStack itemstack, IBlockData iblockdata) { - IBlockData iblockdata1 = iblockdata; - NBTTagCompound nbttagcompound = itemstack.getTag(); - - if (nbttagcompound != null) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("BlockStateTag"); - // CraftBukkit start - iblockdata1 = getBlockState(iblockdata1, nbttagcompound1); - } - - if (iblockdata1 != iblockdata) { - world.setTypeAndData(blockposition, iblockdata1, 2); - } - - return iblockdata1; - } - - public static IBlockData getBlockState(IBlockData iblockdata, NBTTagCompound nbttagcompound1) { - IBlockData iblockdata1 = iblockdata; - { - // CraftBukkit end - BlockStateList blockstatelist = iblockdata.getBlock().getStates(); - Iterator iterator = nbttagcompound1.getKeys().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - IBlockState iblockstate = blockstatelist.a(s); - - if (iblockstate != null) { - String s1 = nbttagcompound1.get(s).asString(); - - iblockdata1 = a(iblockdata1, iblockstate, s1); - } - } - } - return iblockdata1; - } - - private static > IBlockData a(IBlockData iblockdata, IBlockState iblockstate, String s) { - return (IBlockData) iblockstate.b(s).map((comparable) -> { - return (IBlockData) iblockdata.set(iblockstate, comparable); - }).orElse(iblockdata); - } - - protected boolean b(BlockActionContext blockactioncontext, IBlockData iblockdata) { - EntityHuman entityhuman = blockactioncontext.getEntity(); - VoxelShapeCollision voxelshapecollision = entityhuman == null ? VoxelShapeCollision.a() : VoxelShapeCollision.a((Entity) entityhuman); - // CraftBukkit start - store default return - World world = blockactioncontext.getWorld(); // Paper - boolean defaultReturn = (!this.d() || iblockdata.canPlace(world, blockactioncontext.getClickPosition())) && world.checkEntityCollision(iblockdata, entityhuman, voxelshapecollision, blockactioncontext.getClickPosition(), true); // Paper - org.bukkit.entity.Player player = (blockactioncontext.getEntity() instanceof EntityPlayer) ? (org.bukkit.entity.Player) blockactioncontext.getEntity().getBukkitEntity() : null; - - BlockCanBuildEvent event = new BlockCanBuildEvent(CraftBlock.at(blockactioncontext.getWorld(), blockactioncontext.getClickPosition()), player, CraftBlockData.fromData(iblockdata), defaultReturn); - blockactioncontext.getWorld().getServer().getPluginManager().callEvent(event); - - return event.isBuildable(); - // CraftBukkit end - } - - protected boolean d() { - return true; - } - - protected boolean a(BlockActionContext blockactioncontext, IBlockData iblockdata) { - return blockactioncontext.getWorld().setTypeAndData(blockactioncontext.getClickPosition(), iblockdata, 11); - } - - public static boolean a(World world, @Nullable EntityHuman entityhuman, BlockPosition blockposition, ItemStack itemstack) { - MinecraftServer minecraftserver = world.getMinecraftServer(); - - if (minecraftserver == null) { - return false; - } else { - NBTTagCompound nbttagcompound = itemstack.b("BlockEntityTag"); - - if (nbttagcompound != null) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity != null) { - if (!world.isClientSide && tileentity.isFilteredNBT() && (entityhuman == null || !(entityhuman.isCreativeAndOp() || (entityhuman.abilities.canInstantlyBuild && entityhuman.getBukkitEntity().hasPermission("minecraft.nbt.place"))))) { // Spigot - add permission - return false; - } - - NBTTagCompound nbttagcompound1 = tileentity.save(new NBTTagCompound()); - NBTTagCompound nbttagcompound2 = nbttagcompound1.clone(); - - nbttagcompound1.a(nbttagcompound); - nbttagcompound1.setInt("x", blockposition.getX()); - nbttagcompound1.setInt("y", blockposition.getY()); - nbttagcompound1.setInt("z", blockposition.getZ()); - if (!nbttagcompound1.equals(nbttagcompound2)) { - tileentity.load(nbttagcompound1); - tileentity.update(); - return true; - } - } - } - - return false; - } - } - - @Override - public String getName() { - return this.getBlock().l(); - } - - @Override - public void a(CreativeModeTab creativemodetab, NonNullList nonnulllist) { - if (this.a(creativemodetab)) { - this.getBlock().a(creativemodetab, nonnulllist); - } - - } - - public Block getBlock() { - return this.a; - } - - public void a(Map map, Item item) { - map.put(this.getBlock(), item); - } -} diff --git a/src/main/java/net/minecraft/server/ItemBoat.java b/src/main/java/net/minecraft/server/ItemBoat.java deleted file mode 100644 index 03956c6b5..000000000 --- a/src/main/java/net/minecraft/server/ItemBoat.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.function.Predicate; - -public class ItemBoat extends Item { - - private static final Predicate a = IEntitySelector.f.and(Entity::isInteractable); - private final EntityBoat.EnumBoatType b; - - public ItemBoat(EntityBoat.EnumBoatType entityboat_enumboattype, Item.Info item_info) { - super(item_info); - this.b = entityboat_enumboattype; - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - MovingObjectPosition movingobjectposition = a(world, entityhuman, RayTrace.FluidCollisionOption.ANY); - - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.MISS) { - return new InteractionResultWrapper<>(EnumInteractionResult.PASS, itemstack); - } else { - Vec3D vec3d = entityhuman.f(1.0F); - double d0 = 5.0D; - List list = world.getEntities(entityhuman, entityhuman.getBoundingBox().a(vec3d.a(5.0D)).g(1.0D), ItemBoat.a); - - if (!list.isEmpty()) { - Vec3D vec3d1 = entityhuman.j(1.0F); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - AxisAlignedBB axisalignedbb = entity.getBoundingBox().g((double) entity.aS()); - - if (axisalignedbb.c(vec3d1)) { - return new InteractionResultWrapper<>(EnumInteractionResult.PASS, itemstack); - } - } - } - - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { - // CraftBukkit start - Boat placement - MovingObjectPositionBlock movingobjectpositionblock = (MovingObjectPositionBlock) movingobjectposition; - org.bukkit.event.player.PlayerInteractEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerInteractEvent(entityhuman, org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK, movingobjectpositionblock.getBlockPosition(), movingobjectpositionblock.getDirection(), itemstack, enumhand); - - if (event.isCancelled()) { - return new InteractionResultWrapper(EnumInteractionResult.PASS, itemstack); - } - // CraftBukkit end - EntityBoat entityboat = new EntityBoat(world, movingobjectposition.getPos().x, movingobjectposition.getPos().y, movingobjectposition.getPos().z); - - entityboat.setType(this.b); - entityboat.yaw = entityhuman.yaw; - if (!world.getCubes(entityboat, entityboat.getBoundingBox().g(-0.1D))) { - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } else { - if (!world.isClientSide) { - if (!world.addEntity(entityboat)) return new InteractionResultWrapper(EnumInteractionResult.PASS, itemstack); // CraftBukkit - } - - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } - } else { - return new InteractionResultWrapper<>(EnumInteractionResult.PASS, itemstack); - } - } - } -} diff --git a/src/main/java/net/minecraft/server/ItemBow.java b/src/main/java/net/minecraft/server/ItemBow.java deleted file mode 100644 index 90592fd38..000000000 --- a/src/main/java/net/minecraft/server/ItemBow.java +++ /dev/null @@ -1,144 +0,0 @@ -package net.minecraft.server; - -import java.util.function.Predicate; - -public class ItemBow extends ItemProjectileWeapon { - - public ItemBow(Item.Info item_info) { - super(item_info); - // CraftBukkit start - obfuscator went a little crazy - /* - this.a(new MinecraftKey("pull"), (itemstack, world, entityliving) -> { - return entityliving == null ? 0.0F : (entityliving.dl().getItem() != Items.BOW ? 0.0F : (float) (itemstack.k() - entityliving.dm()) / 20.0F); - }); - this.a(new MinecraftKey("pulling"), (itemstack, world, entityliving) -> { - return entityliving != null && entityliving.isHandRaised() && entityliving.dl() == itemstack ? 1.0F : 0.0F; - }); - */ - // CraftBukkit end - } - - @Override - public void a(ItemStack itemstack, World world, EntityLiving entityliving, int i) { - if (entityliving instanceof EntityHuman) { - EntityHuman entityhuman = (EntityHuman) entityliving; - boolean flag = entityhuman.abilities.canInstantlyBuild || EnchantmentManager.getEnchantmentLevel(Enchantments.ARROW_INFINITE, itemstack) > 0; - ItemStack itemstack1 = entityhuman.f(itemstack); - - if (!itemstack1.isEmpty() || flag) { - if (itemstack1.isEmpty()) { - itemstack1 = new ItemStack(Items.ARROW); - } - - int j = this.f_(itemstack) - i; - float f = a(j); - - if ((double) f >= 0.1D) { - boolean flag1 = flag && itemstack1.getItem() == Items.ARROW; - - boolean consumeArrow = true; // Paper - if (!world.isClientSide) { - ItemArrow itemarrow = (ItemArrow) ((ItemArrow) (itemstack1.getItem() instanceof ItemArrow ? itemstack1.getItem() : Items.ARROW)); - EntityArrow entityarrow = itemarrow.a(world, itemstack1, (EntityLiving) entityhuman); - - entityarrow.a(entityhuman, entityhuman.pitch, entityhuman.yaw, 0.0F, f * 3.0F, 1.0F); - if (f == 1.0F) { - entityarrow.setCritical(true); - } - - int k = EnchantmentManager.getEnchantmentLevel(Enchantments.ARROW_DAMAGE, itemstack); - - if (k > 0) { - entityarrow.setDamage(entityarrow.getDamage() + (double) k * 0.5D + 0.5D); - } - - int l = EnchantmentManager.getEnchantmentLevel(Enchantments.ARROW_KNOCKBACK, itemstack); - - if (l > 0) { - entityarrow.setKnockbackStrength(l); - } - - if (EnchantmentManager.getEnchantmentLevel(Enchantments.ARROW_FIRE, itemstack) > 0) { - entityarrow.setOnFire(100); - } - // CraftBukkit start - org.bukkit.event.entity.EntityShootBowEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityShootBowEvent(entityhuman, itemstack, itemstack1, entityarrow, f); // Paper - if (event.isCancelled()) { - event.getProjectile().remove(); - return; - } - // CraftBukkit end - - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(entityhuman.getRaisedHand()); - }); - consumeArrow = event.getConsumeArrow(); // Paper - if (!consumeArrow || flag1 || (entityhuman.abilities.canInstantlyBuild && ((itemstack1.getItem() == Items.SPECTRAL_ARROW) || (itemstack1.getItem() == Items.TIPPED_ARROW)))) { // Paper - add - entityarrow.fromPlayer = EntityArrow.PickupStatus.CREATIVE_ONLY; - } - - // CraftBukkit start - if (event.getProjectile() == entityarrow.getBukkitEntity()) { - if (!world.addEntity(entityarrow)) { - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - return; - } - } - // CraftBukkit end - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_ARROW_SHOOT, SoundCategory.PLAYERS, 1.0F, 1.0F / (ItemBow.i.nextFloat() * 0.4F + 1.2F) + f * 0.5F); - if (!flag1 && !entityhuman.abilities.canInstantlyBuild && consumeArrow) { // Paper - itemstack1.subtract(1); - if (itemstack1.isEmpty()) { - entityhuman.inventory.f(itemstack1); - } - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - } - } - } - } - - public static float a(int i) { - float f = (float) i / 20.0F; - - f = (f * f + f * 2.0F) / 3.0F; - if (f > 1.0F) { - f = 1.0F; - } - - return f; - } - - @Override - public int f_(ItemStack itemstack) { - return 72000; - } - - @Override - public EnumAnimation e_(ItemStack itemstack) { - return EnumAnimation.BOW; - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - boolean flag = !entityhuman.f(itemstack).isEmpty(); - - if (!entityhuman.abilities.canInstantlyBuild && !flag) { - return flag ? new InteractionResultWrapper<>(EnumInteractionResult.PASS, itemstack) : new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } else { - entityhuman.c(enumhand); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } - } - - @Override - public Predicate b() { - return ItemBow.a; - } -} diff --git a/src/main/java/net/minecraft/server/ItemBucket.java b/src/main/java/net/minecraft/server/ItemBucket.java deleted file mode 100644 index 91ff811d8..000000000 --- a/src/main/java/net/minecraft/server/ItemBucket.java +++ /dev/null @@ -1,181 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.DummyGeneratorAccess; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerBucketFillEvent; -// CraftBukkit end - -public class ItemBucket extends Item { - - public final FluidType fluidType; - - public ItemBucket(FluidType fluidtype, Item.Info item_info) { - super(item_info); - this.fluidType = fluidtype; - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - MovingObjectPosition movingobjectposition = a(world, entityhuman, this.fluidType == FluidTypes.EMPTY ? RayTrace.FluidCollisionOption.SOURCE_ONLY : RayTrace.FluidCollisionOption.NONE); - - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.MISS) { - return new InteractionResultWrapper<>(EnumInteractionResult.PASS, itemstack); - } else if (movingobjectposition.getType() != MovingObjectPosition.EnumMovingObjectType.BLOCK) { - return new InteractionResultWrapper<>(EnumInteractionResult.PASS, itemstack); - } else { - MovingObjectPositionBlock movingobjectpositionblock = (MovingObjectPositionBlock) movingobjectposition; - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition(); - - if (world.a(entityhuman, blockposition) && entityhuman.a(blockposition, movingobjectpositionblock.getDirection(), itemstack)) { - IBlockData iblockdata; - - if (this.fluidType == FluidTypes.EMPTY) { - iblockdata = world.getType(blockposition); - if (iblockdata.getBlock() instanceof IFluidSource) { - // CraftBukkit start - FluidType dummyFluid = ((IFluidSource) iblockdata.getBlock()).removeFluid(DummyGeneratorAccess.INSTANCE, blockposition, iblockdata); - PlayerBucketFillEvent event = CraftEventFactory.callPlayerBucketFillEvent(world, entityhuman, blockposition, blockposition, movingobjectpositionblock.getDirection(), itemstack, dummyFluid.b(), enumhand); // Paper - add enumHand - - if (event.isCancelled()) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutBlockChange(world, blockposition)); // SPIGOT-5163 (see PlayerInteractManager) - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); // SPIGOT-4541 - return new InteractionResultWrapper(EnumInteractionResult.FAIL, itemstack); - } - // CraftBukkit end - FluidType fluidtype = ((IFluidSource) iblockdata.getBlock()).removeFluid(world, blockposition, iblockdata); - - if (fluidtype != FluidTypes.EMPTY) { - entityhuman.b(StatisticList.ITEM_USED.b(this)); - entityhuman.a(fluidtype.a(TagsFluid.LAVA) ? SoundEffects.ITEM_BUCKET_FILL_LAVA : SoundEffects.ITEM_BUCKET_FILL, 1.0F, 1.0F); - ItemStack itemstack1 = this.a(itemstack, entityhuman, fluidtype.b(), event.getItemStack()); // CraftBukkit - - if (!world.isClientSide) { - CriterionTriggers.j.a((EntityPlayer) entityhuman, new ItemStack(fluidtype.b())); - } - - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack1); - } - } - - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } else { - iblockdata = world.getType(blockposition); - BlockPosition blockposition1 = iblockdata.getBlock() instanceof IFluidContainer && this.fluidType == FluidTypes.WATER ? blockposition : movingobjectpositionblock.getBlockPosition().shift(movingobjectpositionblock.getDirection()); - - if (this.a(entityhuman, world, blockposition1, movingobjectpositionblock, movingobjectpositionblock.getDirection(), blockposition, itemstack, enumhand)) { // CraftBukkit // Paper - add enumHand - this.a(world, itemstack, blockposition1); - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.y.a((EntityPlayer) entityhuman, blockposition1, itemstack); - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, this.a(itemstack, entityhuman)); - } else { - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } - } - } else { - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } - } - } - - protected ItemStack a(ItemStack itemstack, EntityHuman entityhuman) { - return !entityhuman.abilities.canInstantlyBuild ? new ItemStack(Items.BUCKET) : itemstack; - } - - public void a(World world, ItemStack itemstack, BlockPosition blockposition) {} - - // 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 { - itemstack.subtract(1); - if (itemstack.isEmpty()) { - // CraftBukkit start - return CraftItemStack.asNMSCopy(result); - } else { - if (!entityhuman.inventory.pickup(CraftItemStack.asNMSCopy(result))) { - entityhuman.drop(CraftItemStack.asNMSCopy(result), false); - // CraftBukkit end - } - - return itemstack; - } - } - } - - // CraftBukkit start - public boolean a(@Nullable EntityHuman entityhuman, World world, BlockPosition blockposition, @Nullable MovingObjectPositionBlock movingobjectpositionblock) { - return a(entityhuman, world, blockposition, movingobjectpositionblock, null, null, null); - } - - public boolean a(EntityHuman entityhuman, World world, BlockPosition blockposition, @Nullable MovingObjectPositionBlock movingobjectpositionblock, EnumDirection enumdirection, BlockPosition clicked, ItemStack itemstack) { - // Paper start - add enumHand - return a(entityhuman, world, blockposition, movingobjectpositionblock, enumdirection, clicked, itemstack, null); - } - - public boolean a(EntityHuman entityhuman, World world, BlockPosition blockposition, @Nullable MovingObjectPositionBlock movingobjectpositionblock, EnumDirection enumdirection, BlockPosition clicked, ItemStack itemstack, EnumHand enumhand) { - // Paper end - // CraftBukkit end - if (!(this.fluidType instanceof FluidTypeFlowing)) { - return false; - } else { - IBlockData iblockdata = world.getType(blockposition); - Material material = iblockdata.getMaterial(); - boolean flag = !material.isBuildable(); - boolean flag1 = material.isReplaceable(); - - if (!world.isEmpty(blockposition) && !flag && !flag1 && (!(iblockdata.getBlock() instanceof IFluidContainer) || !((IFluidContainer) iblockdata.getBlock()).canPlace(world, blockposition, iblockdata, this.fluidType))) { - return movingobjectpositionblock == null ? false : this.a(entityhuman, world, movingobjectpositionblock.getBlockPosition().shift(movingobjectpositionblock.getDirection()), (MovingObjectPositionBlock) null, enumdirection, clicked, itemstack, enumhand); // CraftBukkit // Paper - add enumhand - } else { - // CraftBukkit start - if (entityhuman != null) { - PlayerBucketEmptyEvent event = CraftEventFactory.callPlayerBucketEmptyEvent(world, entityhuman, blockposition, clicked, enumdirection, itemstack, enumhand); // Paper - add enumHand - if (event.isCancelled()) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutBlockChange(world, blockposition)); // SPIGOT-4238: needed when looking through entity - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); // SPIGOT-4541 - return false; - } - } - // CraftBukkit end - if (world.worldProvider.isNether() && this.fluidType.a(TagsFluid.WATER)) { - int i = blockposition.getX(); - int j = blockposition.getY(); - int k = blockposition.getZ(); - - world.playSound(entityhuman, blockposition, SoundEffects.BLOCK_FIRE_EXTINGUISH, SoundCategory.BLOCKS, 0.5F, 2.6F + (world.random.nextFloat() - world.random.nextFloat()) * 0.8F); - - for (int l = 0; l < 8; ++l) { - world.addParticle(Particles.LARGE_SMOKE, (double) i + Math.random(), (double) j + Math.random(), (double) k + Math.random(), 0.0D, 0.0D, 0.0D); - } - } else if (iblockdata.getBlock() instanceof IFluidContainer && this.fluidType == FluidTypes.WATER) { - if (((IFluidContainer) iblockdata.getBlock()).place(world, blockposition, iblockdata, ((FluidTypeFlowing) this.fluidType).a(false))) { - this.a(entityhuman, (GeneratorAccess) world, blockposition); - } - } else { - if (!world.isClientSide && (flag || flag1) && !material.isLiquid()) { - world.b(blockposition, true); - } - - this.a(entityhuman, (GeneratorAccess) world, blockposition); - world.setTypeAndData(blockposition, this.fluidType.i().getBlockData(), 11); - } - - return true; - } - } - } - - protected void a(@Nullable EntityHuman entityhuman, GeneratorAccess generatoraccess, BlockPosition blockposition) { - SoundEffect soundeffect = this.fluidType.a(TagsFluid.LAVA) ? SoundEffects.ITEM_BUCKET_EMPTY_LAVA : SoundEffects.ITEM_BUCKET_EMPTY; - - generatoraccess.playSound(entityhuman, blockposition, soundeffect, SoundCategory.BLOCKS, 1.0F, 1.0F); - } -} diff --git a/src/main/java/net/minecraft/server/ItemChorusFruit.java b/src/main/java/net/minecraft/server/ItemChorusFruit.java deleted file mode 100644 index 6b4ea5147..000000000 --- a/src/main/java/net/minecraft/server/ItemChorusFruit.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerTeleportEvent; -// CraftBukkit end - -public class ItemChorusFruit extends Item { - - public ItemChorusFruit(Item.Info item_info) { - super(item_info); - } - - @Override - public ItemStack a(ItemStack itemstack, World world, EntityLiving entityliving) { - ItemStack itemstack1 = super.a(itemstack, world, entityliving); - - if (!world.isClientSide) { - double d0 = entityliving.locX; - double d1 = entityliving.locY; - double d2 = entityliving.locZ; - - for (int i = 0; i < 16; ++i) { - double d3 = entityliving.locX + (entityliving.getRandom().nextDouble() - 0.5D) * 16.0D; - double d4 = MathHelper.a(entityliving.locY + (double) (entityliving.getRandom().nextInt(16) - 8), 0.0D, (double) (world.getHeight() - 1)); - double d5 = entityliving.locZ + (entityliving.getRandom().nextDouble() - 0.5D) * 16.0D; - - // CraftBukkit start - if (entityliving instanceof EntityPlayer) { - Player player = ((EntityPlayer) entityliving).getBukkitEntity(); - PlayerTeleportEvent teleEvent = new PlayerTeleportEvent(player, player.getLocation(), new Location(player.getWorld(), d3, d4, d5), PlayerTeleportEvent.TeleportCause.CHORUS_FRUIT); - world.getServer().getPluginManager().callEvent(teleEvent); - if (teleEvent.isCancelled()) { - break; - } - d3 = teleEvent.getTo().getX(); - d4 = teleEvent.getTo().getY(); - d5 = teleEvent.getTo().getZ(); - } - // CraftBukkit end - - if (entityliving.isPassenger()) { - entityliving.stopRiding(); - } - - if (entityliving.a(d3, d4, d5, true)) { - world.playSound((EntityHuman) null, d0, d1, d2, SoundEffects.ITEM_CHORUS_FRUIT_TELEPORT, SoundCategory.PLAYERS, 1.0F, 1.0F); - entityliving.a(SoundEffects.ITEM_CHORUS_FRUIT_TELEPORT, 1.0F, 1.0F); - break; - } - } - - if (entityliving instanceof EntityHuman) { - ((EntityHuman) entityliving).getCooldownTracker().setCooldown(this, 20); - } - } - - return itemstack1; - } -} diff --git a/src/main/java/net/minecraft/server/ItemCrossbow.java b/src/main/java/net/minecraft/server/ItemCrossbow.java deleted file mode 100644 index f0d784108..000000000 --- a/src/main/java/net/minecraft/server/ItemCrossbow.java +++ /dev/null @@ -1,383 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.List; -import java.util.Random; -import java.util.function.Predicate; - -public class ItemCrossbow extends ItemProjectileWeapon { - - private boolean c = false; - private boolean d = false; - - public ItemCrossbow(Item.Info item_info) { - super(item_info); - // CraftBukkit start - obfuscator went a little crazy - /* - this.a(new MinecraftKey("pull"), (itemstack, world, entityliving) -> { - return entityliving != null && itemstack.getItem() == this ? (d(itemstack) ? 0.0F : (float) (itemstack.k() - entityliving.dm()) / (float) e(itemstack)) : 0.0F; - }); - this.a(new MinecraftKey("pulling"), (itemstack, world, entityliving) -> { - return entityliving != null && entityliving.isHandRaised() && entityliving.dl() == itemstack && !d(itemstack) ? 1.0F : 0.0F; - }); - this.a(new MinecraftKey("charged"), (itemstack, world, entityliving) -> { - return entityliving != null && d(itemstack) ? 1.0F : 0.0F; - }); - this.a(new MinecraftKey("firework"), (itemstack, world, entityliving) -> { - return entityliving != null && d(itemstack) && a(itemstack, Items.FIREWORK_ROCKET) ? 1.0F : 0.0F; - }); - */ - // CraftBukkit end - } - - @Override - public Predicate d() { - return ItemCrossbow.b; - } - - @Override - public Predicate b() { - return ItemCrossbow.a; - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (d(itemstack)) { - a(world, entityhuman, enumhand, itemstack, l(itemstack), 1.0F); - a(itemstack, false); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } else if (!entityhuman.f(itemstack).isEmpty()) { - if (!d(itemstack)) { - this.c = false; - this.d = false; - entityhuman.c(enumhand); - } - - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } else { - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } - } - - @Override - public void a(ItemStack itemstack, World world, EntityLiving entityliving, int i) { - int j = this.f_(itemstack) - i; - float f = a(j, itemstack); - - if (f >= 1.0F && !d(itemstack) && a(entityliving, itemstack)) { - a(itemstack, true); - SoundCategory soundcategory = entityliving instanceof EntityHuman ? SoundCategory.PLAYERS : SoundCategory.HOSTILE; - - world.playSound((EntityHuman) null, entityliving.locX, entityliving.locY, entityliving.locZ, SoundEffects.ITEM_CROSSBOW_LOADING_END, soundcategory, 1.0F, 1.0F / (ItemCrossbow.i.nextFloat() * 0.5F + 1.0F) + 0.2F); - } - - } - - private static boolean a(EntityLiving entityliving, ItemStack itemstack) { - int i = EnchantmentManager.getEnchantmentLevel(Enchantments.MULTISHOT, itemstack); - int j = i == 0 ? 1 : 3; - boolean flag = entityliving instanceof EntityHuman && ((EntityHuman) entityliving).abilities.canInstantlyBuild; - ItemStack itemstack1 = entityliving.f(itemstack); - ItemStack itemstack2 = itemstack1.cloneItemStack(); - - for (int k = 0; k < j; ++k) { - if (k > 0) { - itemstack1 = itemstack2.cloneItemStack(); - } - - if (itemstack1.isEmpty() && flag) { - itemstack1 = new ItemStack(Items.ARROW); - itemstack2 = itemstack1.cloneItemStack(); - } - // CraftBukkit start - SPIGOT-4870, MC-150847 - else if (itemstack1.isEmpty()) { - return false; - } - // CraftBukkit end - - if (!a(entityliving, itemstack, itemstack1, k > 0, flag)) { - return false; - } - } - - return true; - } - - private static boolean a(EntityLiving entityliving, ItemStack itemstack, ItemStack itemstack1, boolean flag, boolean flag1) { - if (itemstack1.isEmpty()) { - return false; - } else { - boolean flag2 = flag1 && itemstack1.getItem() instanceof ItemArrow; - ItemStack itemstack2; - - if (!flag2 && !flag1 && !flag) { - itemstack2 = itemstack1.cloneAndSubtract(1); - if (itemstack1.isEmpty() && entityliving instanceof EntityHuman) { - ((EntityHuman) entityliving).inventory.f(itemstack1); - } - } else { - itemstack2 = itemstack1.cloneItemStack(); - } - - b(itemstack, itemstack2); - return true; - } - } - - public static boolean d(ItemStack itemstack) { - NBTTagCompound nbttagcompound = itemstack.getTag(); - - return nbttagcompound != null && nbttagcompound.getBoolean("Charged"); - } - - public static void a(ItemStack itemstack, boolean flag) { - NBTTagCompound nbttagcompound = itemstack.getOrCreateTag(); - - nbttagcompound.setBoolean("Charged", flag); - } - - private static void b(ItemStack itemstack, ItemStack itemstack1) { - NBTTagCompound nbttagcompound = itemstack.getOrCreateTag(); - NBTTagList nbttaglist; - - if (nbttagcompound.hasKeyOfType("ChargedProjectiles", 9)) { - nbttaglist = nbttagcompound.getList("ChargedProjectiles", 10); - } else { - nbttaglist = new NBTTagList(); - } - - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - itemstack1.save(nbttagcompound1); - nbttaglist.add(nbttagcompound1); - nbttagcompound.set("ChargedProjectiles", nbttaglist); - } - - private static List j(ItemStack itemstack) { - List list = Lists.newArrayList(); - NBTTagCompound nbttagcompound = itemstack.getTag(); - - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("ChargedProjectiles", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("ChargedProjectiles", 10); - - if (nbttaglist != null) { - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompound(i); - - list.add(ItemStack.a(nbttagcompound1)); - } - } - } - - return list; - } - - private static void k(ItemStack itemstack) { - NBTTagCompound nbttagcompound = itemstack.getTag(); - - if (nbttagcompound != null) { - NBTTagList nbttaglist = nbttagcompound.getList("ChargedProjectiles", 9); - - nbttaglist.clear(); - nbttagcompound.set("ChargedProjectiles", nbttaglist); - } - - } - - private static boolean a(ItemStack itemstack, Item item) { - return j(itemstack).stream().anyMatch((itemstack1) -> { - return itemstack1.getItem() == item; - }); - } - - private static void a(World world, EntityLiving entityliving, EnumHand enumhand, ItemStack itemstack, ItemStack itemstack1, float f, boolean flag, float f1, float f2, float f3) { - if (!world.isClientSide) { - boolean flag1 = itemstack1.getItem() == Items.FIREWORK_ROCKET; - Object object; - - if (flag1) { - object = new EntityFireworks(world, itemstack1, entityliving.locX, entityliving.locY + (double) entityliving.getHeadHeight() - 0.15000000596046448D, entityliving.locZ, true); - ((EntityFireworks) object).spawningEntity = entityliving.getUniqueID(); // Paper - } else { - object = a(world, entityliving, itemstack, itemstack1); - if (flag || f3 != 0.0F) { - ((EntityArrow) object).fromPlayer = EntityArrow.PickupStatus.CREATIVE_ONLY; - } - } - - if (entityliving instanceof ICrossbow) { - ICrossbow icrossbow = (ICrossbow) entityliving; - - icrossbow.a(icrossbow.getGoalTarget(), itemstack, (IProjectile) object, f3); - } else { - Vec3D vec3d = entityliving.i(1.0F); - Quaternion quaternion = new Quaternion(new Vector3fa(vec3d), f3, true); - Vec3D vec3d1 = entityliving.f(1.0F); - Vector3fa vector3fa = new Vector3fa(vec3d1); - - vector3fa.a(quaternion); - ((IProjectile) object).shoot((double) vector3fa.a(), (double) vector3fa.b(), (double) vector3fa.c(), f1, f2); - } - // CraftBukkit start - org.bukkit.event.entity.EntityShootBowEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityShootBowEvent(entityliving, itemstack, itemstack1, (IProjectile) object, f); // Paper // TODO: consume?? - if (event.isCancelled()) { - event.getProjectile().remove(); - return; - } - // CraftBukkit end - - itemstack.damage(flag1 ? 3 : 1, entityliving, (entityliving1) -> { - entityliving1.d(enumhand); - }); - // CraftBukkit start - if (event.getProjectile() == ((Entity) object).getBukkitEntity()) { - if (!world.addEntity((Entity) object)) { - if (entityliving instanceof EntityPlayer) { - ((EntityPlayer) entityliving).getBukkitEntity().updateInventory(); - } - return; - } - } - // CraftBukkit end - world.playSound((EntityHuman) null, entityliving.locX, entityliving.locY, entityliving.locZ, SoundEffects.ITEM_CROSSBOW_SHOOT, SoundCategory.PLAYERS, 1.0F, f); - } - } - - private static EntityArrow a(World world, EntityLiving entityliving, ItemStack itemstack, ItemStack itemstack1) { - ItemArrow itemarrow = (ItemArrow) ((ItemArrow) (itemstack1.getItem() instanceof ItemArrow ? itemstack1.getItem() : Items.ARROW)); - EntityArrow entityarrow = itemarrow.a(world, itemstack1, entityliving); - - if (entityliving instanceof EntityHuman) { - entityarrow.setCritical(true); - } - - entityarrow.a(SoundEffects.ITEM_CROSSBOW_HIT); - entityarrow.o(true); - int i = EnchantmentManager.getEnchantmentLevel(Enchantments.PIERCING, itemstack); - - if (i > 0) { - entityarrow.setPierceLevel((byte) i); - } - - return entityarrow; - } - - public static void a(World world, EntityLiving entityliving, EnumHand enumhand, ItemStack itemstack, float f, float f1) { - List list = j(itemstack); - float[] afloat = a(entityliving.getRandom()); - - for (int i = 0; i < list.size(); ++i) { - ItemStack itemstack1 = (ItemStack) list.get(i); - boolean flag = entityliving instanceof EntityHuman && ((EntityHuman) entityliving).abilities.canInstantlyBuild; - - if (!itemstack1.isEmpty()) { - if (i == 0) { - a(world, entityliving, enumhand, itemstack, itemstack1, afloat[i], flag, f, f1, 0.0F); - } else if (i == 1) { - a(world, entityliving, enumhand, itemstack, itemstack1, afloat[i], flag, f, f1, -10.0F); - } else if (i == 2) { - a(world, entityliving, enumhand, itemstack, itemstack1, afloat[i], flag, f, f1, 10.0F); - } - } - } - - a(world, entityliving, itemstack); - } - - private static float[] a(Random random) { - boolean flag = random.nextBoolean(); - - return new float[]{1.0F, a(flag), a(!flag)}; - } - - private static float a(boolean flag) { - float f = flag ? 0.63F : 0.43F; - - return 1.0F / (ItemCrossbow.i.nextFloat() * 0.5F + 1.8F) + f; - } - - private static void a(World world, EntityLiving entityliving, ItemStack itemstack) { - if (entityliving instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entityliving; - - if (!world.isClientSide) { - CriterionTriggers.F.a(entityplayer, itemstack); - } - - entityplayer.b(StatisticList.ITEM_USED.b(itemstack.getItem())); - } - - k(itemstack); - } - - @Override - public void a(World world, EntityLiving entityliving, ItemStack itemstack, int i) { - if (!world.isClientSide) { - int j = EnchantmentManager.getEnchantmentLevel(Enchantments.QUICK_CHARGE, itemstack); - SoundEffect soundeffect = this.a(j); - SoundEffect soundeffect1 = j == 0 ? SoundEffects.ITEM_CROSSBOW_LOADING_MIDDLE : null; - float f = (float) (itemstack.k() - i) / (float) e(itemstack); - - if (f < 0.2F) { - this.c = false; - this.d = false; - } - - if (f >= 0.2F && !this.c) { - this.c = true; - world.playSound((EntityHuman) null, entityliving.locX, entityliving.locY, entityliving.locZ, soundeffect, SoundCategory.PLAYERS, 0.5F, 1.0F); - } - - if (f >= 0.5F && soundeffect1 != null && !this.d) { - this.d = true; - world.playSound((EntityHuman) null, entityliving.locX, entityliving.locY, entityliving.locZ, soundeffect1, SoundCategory.PLAYERS, 0.5F, 1.0F); - } - } - - } - - @Override - public int f_(ItemStack itemstack) { - return e(itemstack) + 3; - } - - public static int e(ItemStack itemstack) { - int i = EnchantmentManager.getEnchantmentLevel(Enchantments.QUICK_CHARGE, itemstack); - - return i == 0 ? 25 : 25 - 5 * i; - } - - @Override - public EnumAnimation e_(ItemStack itemstack) { - return EnumAnimation.CROSSBOW; - } - - private SoundEffect a(int i) { - switch (i) { - case 1: - return SoundEffects.ITEM_CROSSBOW_QUICK_CHARGE_1; - case 2: - return SoundEffects.ITEM_CROSSBOW_QUICK_CHARGE_2; - case 3: - return SoundEffects.ITEM_CROSSBOW_QUICK_CHARGE_3; - default: - return SoundEffects.ITEM_CROSSBOW_LOADING_START; - } - } - - private static float a(int i, ItemStack itemstack) { - float f = (float) i / (float) e(itemstack); - - if (f > 1.0F) { - f = 1.0F; - } - - return f; - } - - private static float l(ItemStack itemstack) { - return itemstack.getItem() == Items.CROSSBOW && a(itemstack, Items.FIREWORK_ROCKET) ? 1.6F : 3.15F; - } -} diff --git a/src/main/java/net/minecraft/server/ItemDebugStick.java b/src/main/java/net/minecraft/server/ItemDebugStick.java deleted file mode 100644 index 519617ded..000000000 --- a/src/main/java/net/minecraft/server/ItemDebugStick.java +++ /dev/null @@ -1,85 +0,0 @@ -package net.minecraft.server; - -import java.util.Collection; -import javax.annotation.Nullable; - -public class ItemDebugStick extends Item { - - public ItemDebugStick(Item.Info item_info) { - super(item_info); - } - - @Override - public boolean a(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman) { - if (!world.isClientSide) { - this.a(entityhuman, iblockdata, world, blockposition, false, entityhuman.b(EnumHand.MAIN_HAND)); - } - - return false; - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - EntityHuman entityhuman = itemactioncontext.getEntity(); - World world = itemactioncontext.getWorld(); - - if (!world.isClientSide && entityhuman != null) { - BlockPosition blockposition = itemactioncontext.getClickPosition(); - - this.a(entityhuman, world.getType(blockposition), world, blockposition, true, itemactioncontext.getItemStack()); - } - - return EnumInteractionResult.SUCCESS; - } - - private void a(EntityHuman entityhuman, IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition, boolean flag, ItemStack itemstack) { - if (entityhuman.isCreativeAndOp() || (entityhuman.abilities.canInstantlyBuild && entityhuman.getBukkitEntity().hasPermission("minecraft.debugstick"))) { - Block block = iblockdata.getBlock(); - BlockStateList blockstatelist = block.getStates(); - Collection> collection = blockstatelist.d(); - String s = IRegistry.BLOCK.getKey(block).toString(); - - if (collection.isEmpty()) { - a(entityhuman, (IChatBaseComponent) (new ChatMessage(this.getName() + ".empty", new Object[]{s}))); - } else { - NBTTagCompound nbttagcompound = itemstack.a("DebugProperty"); - String s1 = nbttagcompound.getString(s); - IBlockState iblockstate = blockstatelist.a(s1); - - if (flag) { - if (iblockstate == null) { - iblockstate = (IBlockState) collection.iterator().next(); - } - - IBlockData iblockdata1 = a(iblockdata, iblockstate, entityhuman.isSneaking()); - - generatoraccess.setTypeAndData(blockposition, iblockdata1, 18); - a(entityhuman, (IChatBaseComponent) (new ChatMessage(this.getName() + ".update", new Object[]{iblockstate.a(), a(iblockdata1, iblockstate)}))); - } else { - iblockstate = (IBlockState) a((Iterable) collection, (Object) iblockstate, entityhuman.isSneaking()); - String s2 = iblockstate.a(); - - nbttagcompound.setString(s, s2); - a(entityhuman, (IChatBaseComponent) (new ChatMessage(this.getName() + ".select", new Object[]{s2, a(iblockdata, iblockstate)}))); - } - - } - } - } - - private static > IBlockData a(IBlockData iblockdata, IBlockState iblockstate, boolean flag) { - return (IBlockData) iblockdata.set(iblockstate, a(iblockstate.getValues(), iblockdata.get(iblockstate), flag)); - } - - private static T a(Iterable iterable, @Nullable T t0, boolean flag) { - return flag ? SystemUtils.b(iterable, t0) : SystemUtils.a(iterable, t0); - } - - private static void a(EntityHuman entityhuman, IChatBaseComponent ichatbasecomponent) { - ((EntityPlayer) entityhuman).a(ichatbasecomponent, ChatMessageType.GAME_INFO); - } - - private static > String a(IBlockData iblockdata, IBlockState iblockstate) { - return iblockstate.a(iblockdata.get(iblockstate)); - } -} diff --git a/src/main/java/net/minecraft/server/ItemDye.java b/src/main/java/net/minecraft/server/ItemDye.java deleted file mode 100644 index da49f6e5a..000000000 --- a/src/main/java/net/minecraft/server/ItemDye.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.Map; - -import org.bukkit.event.entity.SheepDyeWoolEvent; // CraftBukkit - -public class ItemDye extends Item { - - private static final Map a = Maps.newEnumMap(EnumColor.class); - private final EnumColor b; - - public ItemDye(EnumColor enumcolor, Item.Info item_info) { - super(item_info); - this.b = enumcolor; - ItemDye.a.put(enumcolor, this); - } - - @Override - public boolean a(ItemStack itemstack, EntityHuman entityhuman, EntityLiving entityliving, EnumHand enumhand) { - if (entityliving instanceof EntitySheep) { - EntitySheep entitysheep = (EntitySheep) entityliving; - - if (entitysheep.isAlive() && !entitysheep.isSheared() && entitysheep.getColor() != this.b) { - // CraftBukkit start - byte bColor = (byte) this.b.getColorIndex(); - SheepDyeWoolEvent event = new SheepDyeWoolEvent((org.bukkit.entity.Sheep) entitysheep.getBukkitEntity(), org.bukkit.DyeColor.getByWoolData(bColor)); - entitysheep.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return false; - } - - entitysheep.setColor(EnumColor.fromColorIndex((byte) event.getColor().getWoolData())); - // CraftBukkit end - itemstack.subtract(1); - } - - return true; - } else { - return false; - } - } - - public EnumColor d() { - return this.b; - } - - public static ItemDye a(EnumColor enumcolor) { - return (ItemDye) ItemDye.a.get(enumcolor); - } -} diff --git a/src/main/java/net/minecraft/server/ItemEgg.java b/src/main/java/net/minecraft/server/ItemEgg.java deleted file mode 100644 index b92d39600..000000000 --- a/src/main/java/net/minecraft/server/ItemEgg.java +++ /dev/null @@ -1,47 +0,0 @@ -package net.minecraft.server; - -public class ItemEgg extends Item { - - public ItemEgg(Item.Info item_info) { - super(item_info); - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - /* // Paper start - moved down - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_EGG_THROW, SoundCategory.PLAYERS, 0.5F, 0.4F / (ItemEgg.i.nextFloat() * 0.4F + 0.8F)); - */ // Paper end - if (!world.isClientSide) { - EntityEgg entityegg = new EntityEgg(world, entityhuman); - - entityegg.setItem(itemstack); - entityegg.a(entityhuman, entityhuman.pitch, entityhuman.yaw, 0.0F, 1.5F, 1.0F); - // Paper start - com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent event = new com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack), (org.bukkit.entity.Projectile) entityegg.getBukkitEntity()); - if (event.callEvent() && world.addEntity(entityegg)) { - if (event.shouldConsume() && !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_EGG_THROW, SoundCategory.PLAYERS, 0.5F, 0.4F / (Entity.SHARED_RANDOM.nextFloat() * 0.4F + 0.8F)); - } else { - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - return new InteractionResultWrapper(EnumInteractionResult.FAIL, itemstack); - } - // Paper end - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/ItemEndCrystal.java b/src/main/java/net/minecraft/server/ItemEndCrystal.java deleted file mode 100644 index 544e63558..000000000 --- a/src/main/java/net/minecraft/server/ItemEndCrystal.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.minecraft.server; - -import java.util.List; - -public class ItemEndCrystal extends Item { - - public ItemEndCrystal(Item.Info item_info) { - super(item_info); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - World world = itemactioncontext.getWorld(); - BlockPosition blockposition = itemactioncontext.getClickPosition(); - IBlockData iblockdata = world.getType(blockposition); - - if (iblockdata.getBlock() != Blocks.OBSIDIAN && iblockdata.getBlock() != Blocks.BEDROCK) { - return EnumInteractionResult.FAIL; - } else { - BlockPosition blockposition1 = blockposition.up(); - - if (!world.isEmpty(blockposition1)) { - return EnumInteractionResult.FAIL; - } else { - double d0 = (double) blockposition1.getX(); - double d1 = (double) blockposition1.getY(); - double d2 = (double) blockposition1.getZ(); - List list = world.getEntities((Entity) null, new AxisAlignedBB(d0, d1, d2, d0 + 1.0D, d1 + 2.0D, d2 + 1.0D)); - - if (!list.isEmpty()) { - return EnumInteractionResult.FAIL; - } else { - if (!world.isClientSide) { - EntityEnderCrystal entityendercrystal = new EntityEnderCrystal(world, d0 + 0.5D, d1, d2 + 0.5D); - - entityendercrystal.setShowingBottom(false); - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityPlaceEvent(itemactioncontext, entityendercrystal).isCancelled()) { - return EnumInteractionResult.FAIL; - } - // CraftBukkit end - world.addEntity(entityendercrystal); - if (world.worldProvider instanceof WorldProviderTheEnd) { - EnderDragonBattle enderdragonbattle = ((WorldProviderTheEnd) world.worldProvider).q(); - - enderdragonbattle.e(); - } - } - - itemactioncontext.getItemStack().subtract(1); - return EnumInteractionResult.SUCCESS; - } - } - } - } -} diff --git a/src/main/java/net/minecraft/server/ItemEnderPearl.java b/src/main/java/net/minecraft/server/ItemEnderPearl.java deleted file mode 100644 index 570abc8b2..000000000 --- a/src/main/java/net/minecraft/server/ItemEnderPearl.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.minecraft.server; - -public class ItemEnderPearl extends Item { - - public ItemEnderPearl(Item.Info item_info) { - super(item_info); - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - // CraftBukkit start - change order - if (!world.isClientSide) { - EntityEnderPearl entityenderpearl = new EntityEnderPearl(world, entityhuman); - - entityenderpearl.setItem(itemstack); - entityenderpearl.a(entityhuman, entityhuman.pitch, entityhuman.yaw, 0.0F, 1.5F, 1.0F); - // Paper start - com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent event = new com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack), (org.bukkit.entity.Projectile) entityenderpearl.getBukkitEntity()); - if (event.callEvent() && world.addEntity(entityenderpearl)) { - if (event.shouldConsume() && !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_ENDER_PEARL_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (Entity.SHARED_RANDOM.nextFloat() * 0.4F + 0.8F)); - entityhuman.getCooldownTracker().setCooldown(this, 20); - } else { - // Paper end - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - return new InteractionResultWrapper(EnumInteractionResult.FAIL, itemstack); - } - } - -// // Paper start - moved up -// if (!entityhuman.abilities.canInstantlyBuild) { -// itemstack.subtract(1); -// } -// -// world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_ENDER_PEARL_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (ItemEnderPearl.i.nextFloat() * 0.4F + 0.8F)); -// entityhuman.getCooldownTracker().a(this, 20); -// // CraftBukkit end -// // Paper end - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/ItemExpBottle.java b/src/main/java/net/minecraft/server/ItemExpBottle.java deleted file mode 100644 index 2a0aded65..000000000 --- a/src/main/java/net/minecraft/server/ItemExpBottle.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.minecraft.server; - -public class ItemExpBottle extends Item { - - public ItemExpBottle(Item.Info item_info) { - super(item_info); - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - /* // Paper start - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_EXPERIENCE_BOTTLE_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (ItemExpBottle.i.nextFloat() * 0.4F + 0.8F)); - */ // Paper end - if (!world.isClientSide) { - EntityThrownExpBottle entitythrownexpbottle = new EntityThrownExpBottle(world, entityhuman); - - entitythrownexpbottle.setItem(itemstack); - entitythrownexpbottle.a(entityhuman, entityhuman.pitch, entityhuman.yaw, -20.0F, 0.7F, 1.0F); - // Paper start - com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent event = new com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack), (org.bukkit.entity.Projectile) entitythrownexpbottle.getBukkitEntity()); - if (event.callEvent() && world.addEntity(entitythrownexpbottle)) { - if (event.shouldConsume() && !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_EXPERIENCE_BOTTLE_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (Entity.SHARED_RANDOM.nextFloat() * 0.4F + 0.8F)); - } else { - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - return new InteractionResultWrapper(EnumInteractionResult.FAIL, itemstack); - } - // Paper end - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/ItemFireball.java b/src/main/java/net/minecraft/server/ItemFireball.java deleted file mode 100644 index 8924753be..000000000 --- a/src/main/java/net/minecraft/server/ItemFireball.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.minecraft.server; - -public class ItemFireball extends Item { - - public ItemFireball(Item.Info item_info) { - super(item_info); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - World world = itemactioncontext.getWorld(); - - if (world.isClientSide) { - return EnumInteractionResult.SUCCESS; - } else { - BlockPosition blockposition = itemactioncontext.getClickPosition(); - IBlockData iblockdata = world.getType(blockposition); - - if (iblockdata.getBlock() == Blocks.CAMPFIRE) { - if (!(Boolean) iblockdata.get(BlockCampfire.b) && !(Boolean) iblockdata.get(BlockCampfire.d)) { - // CraftBukkit start - fire BlockIgniteEvent - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition, org.bukkit.event.block.BlockIgniteEvent.IgniteCause.FIREBALL, itemactioncontext.getEntity()).isCancelled()) { - if (!itemactioncontext.getEntity().abilities.canInstantlyBuild) { - itemactioncontext.getItemStack().subtract(1); - } - return EnumInteractionResult.PASS; - } - // CraftBukkit end - this.a(world, blockposition); - world.setTypeUpdate(blockposition, (IBlockData) iblockdata.set(BlockCampfire.b, true)); - } - } else { - blockposition = blockposition.shift(itemactioncontext.getClickedFace()); - if (world.getType(blockposition).isAir()) { - // CraftBukkit start - fire BlockIgniteEvent - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition, org.bukkit.event.block.BlockIgniteEvent.IgniteCause.FIREBALL, itemactioncontext.getEntity()).isCancelled()) { - if (!itemactioncontext.getEntity().abilities.canInstantlyBuild) { - itemactioncontext.getItemStack().subtract(1); - } - return EnumInteractionResult.PASS; - } - // CraftBukkit end - this.a(world, blockposition); - world.setTypeUpdate(blockposition, ((BlockFire) Blocks.FIRE).a((IBlockAccess) world, blockposition)); - } - } - - itemactioncontext.getItemStack().subtract(1); - return EnumInteractionResult.SUCCESS; - } - } - - private void a(World world, BlockPosition blockposition) { - world.playSound((EntityHuman) null, blockposition, SoundEffects.ITEM_FIRECHARGE_USE, SoundCategory.BLOCKS, 1.0F, (ItemFireball.i.nextFloat() - ItemFireball.i.nextFloat()) * 0.2F + 1.0F); - } -} diff --git a/src/main/java/net/minecraft/server/ItemFireworks.java b/src/main/java/net/minecraft/server/ItemFireworks.java deleted file mode 100644 index 9e86ef4ce..000000000 --- a/src/main/java/net/minecraft/server/ItemFireworks.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.minecraft.server; - -import java.util.Arrays; -import java.util.Comparator; - -public class ItemFireworks extends Item { - - public ItemFireworks(Item.Info item_info) { - super(item_info); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - World world = itemactioncontext.getWorld(); - - if (!world.isClientSide) { - ItemStack itemstack = itemactioncontext.getItemStack(); - Vec3D vec3d = itemactioncontext.j(); - EntityFireworks entityfireworks = new EntityFireworks(world, vec3d.x, vec3d.y, vec3d.z, itemstack); - entityfireworks.spawningEntity = itemactioncontext.getEntity().getUniqueID(); // Paper - - world.addEntity(entityfireworks); - itemstack.subtract(1); - } - - return EnumInteractionResult.SUCCESS; - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - if (entityhuman.isGliding()) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (!world.isClientSide) { - // Paper start - final EntityFireworks entityfireworks = new EntityFireworks(world, itemstack, entityhuman); - entityfireworks.spawningEntity = entityhuman.getUniqueID(); - // Paper start - com.destroystokyo.paper.event.player.PlayerElytraBoostEvent event = new com.destroystokyo.paper.event.player.PlayerElytraBoostEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack), (org.bukkit.entity.Firework) entityfireworks.getBukkitEntity()); - if (event.callEvent() && world.addEntity(entityfireworks)) { - if (event.shouldConsume() && !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } else ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - // Paper end - } - - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, entityhuman.b(enumhand)); - } else { - return new InteractionResultWrapper<>(EnumInteractionResult.PASS, entityhuman.b(enumhand)); - } - } - - public static enum EffectType { - - SMALL_BALL(0, "small_ball"), LARGE_BALL(1, "large_ball"), STAR(2, "star"), CREEPER(3, "creeper"), BURST(4, "burst"); - - private static final ItemFireworks.EffectType[] f = (ItemFireworks.EffectType[]) Arrays.stream(values()).sorted(Comparator.comparingInt((itemfireworks_effecttype) -> { - return itemfireworks_effecttype.g; - })).toArray((i) -> { - return new ItemFireworks.EffectType[i]; - }); - private final int g; - private final String h; - - private EffectType(int i, String s) { - this.g = i; - this.h = s; - } - - public int a() { - return this.g; - } - } -} diff --git a/src/main/java/net/minecraft/server/ItemFishingRod.java b/src/main/java/net/minecraft/server/ItemFishingRod.java deleted file mode 100644 index 37c4707cf..000000000 --- a/src/main/java/net/minecraft/server/ItemFishingRod.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.event.player.PlayerFishEvent; // CraftBukkit - -public class ItemFishingRod extends Item { - - public ItemFishingRod(Item.Info item_info) { - super(item_info); - // CraftBukkit start - obfuscator went a little crazy - /* - this.a(new MinecraftKey("cast"), (itemstack, world, entityliving) -> { - if (entityliving == null) { - return 0.0F; - } else { - boolean flag = entityliving.getItemInMainHand() == itemstack; - boolean flag1 = entityliving.getItemInOffHand() == itemstack; - - if (entityliving.getItemInMainHand().getItem() instanceof ItemFishingRod) { - flag1 = false; - } - - return (flag || flag1) && entityliving instanceof EntityHuman && ((EntityHuman) entityliving).hookedFish != null ? 1.0F : 0.0F; - } - }); - */ - // CraftBukkit end - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - int i; - - if (entityhuman.hookedFish != null) { - if (!world.isClientSide) { - i = entityhuman.hookedFish.b(itemstack); - itemstack.damage(i, entityhuman, (entityhuman1) -> { - entityhuman1.d(enumhand); - }); - } - - entityhuman.a(enumhand); - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_FISHING_BOBBER_RETRIEVE, SoundCategory.NEUTRAL, 1.0F, 0.4F / (ItemFishingRod.i.nextFloat() * 0.4F + 0.8F)); - } else { - // world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_FISHING_BOBBER_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (ItemFishingRod.i.nextFloat() * 0.4F + 0.8F)); - if (!world.isClientSide) { - i = EnchantmentManager.c(itemstack); - int j = EnchantmentManager.b(itemstack); - - // CraftBukkit start - EntityFishingHook entityfishinghook = new EntityFishingHook(entityhuman, world, j, i); - PlayerFishEvent playerFishEvent = new PlayerFishEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), null, (org.bukkit.entity.FishHook) entityfishinghook.getBukkitEntity(), PlayerFishEvent.State.FISHING); - world.getServer().getPluginManager().callEvent(playerFishEvent); - - if (playerFishEvent.isCancelled()) { - entityhuman.hookedFish = null; - return new InteractionResultWrapper(EnumInteractionResult.PASS, itemstack); - } - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_FISHING_BOBBER_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (ItemFishingRod.i.nextFloat() * 0.4F + 0.8F)); - world.addEntity(entityfishinghook); - // CraftBukkit end - } - - entityhuman.a(enumhand); - entityhuman.b(StatisticList.ITEM_USED.b(this)); - } - - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } - - @Override - public int c() { - return 1; - } -} diff --git a/src/main/java/net/minecraft/server/ItemFlintAndSteel.java b/src/main/java/net/minecraft/server/ItemFlintAndSteel.java deleted file mode 100644 index 298dc620c..000000000 --- a/src/main/java/net/minecraft/server/ItemFlintAndSteel.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; - -public class ItemFlintAndSteel extends Item { - - public ItemFlintAndSteel(Item.Info item_info) { - super(item_info); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - EntityHuman entityhuman = itemactioncontext.getEntity(); - World world = itemactioncontext.getWorld(); - BlockPosition blockposition = itemactioncontext.getClickPosition(); - BlockPosition blockposition1 = blockposition.shift(itemactioncontext.getClickedFace()); - IBlockData iblockdata; - - if (a(world.getType(blockposition1), (GeneratorAccess) world, blockposition1)) { - // CraftBukkit start - Store the clicked block - if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition1, org.bukkit.event.block.BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL, entityhuman).isCancelled()) { - itemactioncontext.getItemStack().damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(itemactioncontext.n()); - }); - return EnumInteractionResult.PASS; - } - // CraftBukkit end - world.playSound(entityhuman, blockposition1, SoundEffects.ITEM_FLINTANDSTEEL_USE, SoundCategory.BLOCKS, 1.0F, ItemFlintAndSteel.i.nextFloat() * 0.4F + 0.8F); - iblockdata = ((BlockFire) Blocks.FIRE).a((IBlockAccess) world, blockposition1); - world.setTypeAndData(blockposition1, iblockdata, 11); - ItemStack itemstack = itemactioncontext.getItemStack(); - - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.y.a((EntityPlayer) entityhuman, blockposition1, itemstack); - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(itemactioncontext.n()); - }); - } - - return EnumInteractionResult.SUCCESS; - } else { - iblockdata = world.getType(blockposition); - if (a(iblockdata)) { - world.playSound(entityhuman, blockposition, SoundEffects.ITEM_FLINTANDSTEEL_USE, SoundCategory.BLOCKS, 1.0F, ItemFlintAndSteel.i.nextFloat() * 0.4F + 0.8F); - world.setTypeAndData(blockposition, (IBlockData) iblockdata.set(BlockProperties.r, true), 11); - if (entityhuman != null) { - itemactioncontext.getItemStack().damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(itemactioncontext.n()); - }); - } - - return EnumInteractionResult.SUCCESS; - } else { - return EnumInteractionResult.FAIL; - } - } - } - - public static boolean a(IBlockData iblockdata) { - return iblockdata.getBlock() == Blocks.CAMPFIRE && !(Boolean) iblockdata.get(BlockProperties.C) && !(Boolean) iblockdata.get(BlockProperties.r); - } - - public static boolean a(IBlockData iblockdata, GeneratorAccess generatoraccess, BlockPosition blockposition) { - IBlockData iblockdata1 = ((BlockFire) Blocks.FIRE).a((IBlockAccess) generatoraccess, blockposition); - boolean flag = false; - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - - if (generatoraccess.getType(blockposition.shift(enumdirection)).getBlock() == Blocks.OBSIDIAN && ((BlockPortal) Blocks.NETHER_PORTAL).b(generatoraccess, blockposition) != null) { - flag = true; - } - } - - return iblockdata.isAir() && (iblockdata1.canPlace(generatoraccess, blockposition) || flag); - } -} diff --git a/src/main/java/net/minecraft/server/ItemHanging.java b/src/main/java/net/minecraft/server/ItemHanging.java deleted file mode 100644 index c49bada2d..000000000 --- a/src/main/java/net/minecraft/server/ItemHanging.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.entity.Player; -import org.bukkit.event.hanging.HangingPlaceEvent; -// CraftBukkit end - -public class ItemHanging extends Item { - - private final EntityTypes a; - - public ItemHanging(EntityTypes entitytypes, Item.Info item_info) { - super(item_info); - this.a = entitytypes; - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - BlockPosition blockposition = itemactioncontext.getClickPosition(); - EnumDirection enumdirection = itemactioncontext.getClickedFace(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - EntityHuman entityhuman = itemactioncontext.getEntity(); - ItemStack itemstack = itemactioncontext.getItemStack(); - - if (entityhuman != null && !this.a(entityhuman, enumdirection, itemstack, blockposition1)) { - return EnumInteractionResult.FAIL; - } else { - World world = itemactioncontext.getWorld(); - Object object; - - if (this.a == EntityTypes.PAINTING) { - object = new EntityPainting(world, blockposition1, enumdirection); - } else { - if (this.a != EntityTypes.ITEM_FRAME) { - return EnumInteractionResult.SUCCESS; - } - - object = new EntityItemFrame(world, blockposition1, enumdirection); - } - - NBTTagCompound nbttagcompound = itemstack.getTag(); - - if (nbttagcompound != null) { - EntityTypes.a(world, entityhuman, (Entity) object, nbttagcompound); - } - - if (((EntityHanging) object).survives()) { - if (!world.isClientSide) { - // CraftBukkit start - fire HangingPlaceEvent - Player who = (itemactioncontext.getEntity() == null) ? null : (Player) itemactioncontext.getEntity().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) object).getBukkitEntity(), who, blockClicked, blockFace); - world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return EnumInteractionResult.FAIL; - } - // CraftBukkit end - ((EntityHanging) object).playPlaceSound(); - world.addEntity((Entity) object); - } - - itemstack.subtract(1); - } - - return EnumInteractionResult.SUCCESS; - } - } - - protected boolean a(EntityHuman entityhuman, EnumDirection enumdirection, ItemStack itemstack, BlockPosition blockposition) { - return !enumdirection.k().b() && entityhuman.a(blockposition, enumdirection, itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/ItemLeash.java b/src/main/java/net/minecraft/server/ItemLeash.java deleted file mode 100644 index 5bdc466de..000000000 --- a/src/main/java/net/minecraft/server/ItemLeash.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; - -import org.bukkit.event.hanging.HangingPlaceEvent; // CraftBukkit - -public class ItemLeash extends Item { - - public ItemLeash(Item.Info item_info) { - super(item_info); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - World world = itemactioncontext.getWorld(); - BlockPosition blockposition = itemactioncontext.getClickPosition(); - Block block = world.getType(blockposition).getBlock(); - - if (block.a(TagsBlock.FENCES)) { - EntityHuman entityhuman = itemactioncontext.getEntity(); - - if (!world.isClientSide && entityhuman != null) { - a(entityhuman, world, blockposition); - } - - return EnumInteractionResult.SUCCESS; - } else { - return EnumInteractionResult.PASS; - } - } - - public static boolean a(EntityHuman entityhuman, World world, BlockPosition blockposition) { - EntityLeash entityleash = null; - 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 - 7.0D, (double) j - 7.0D, (double) k - 7.0D, (double) i + 7.0D, (double) j + 7.0D, (double) k + 7.0D)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityInsentient entityinsentient = (EntityInsentient) iterator.next(); - - if (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; - } -} diff --git a/src/main/java/net/minecraft/server/ItemLingeringPotion.java b/src/main/java/net/minecraft/server/ItemLingeringPotion.java deleted file mode 100644 index ca3f9f8cc..000000000 --- a/src/main/java/net/minecraft/server/ItemLingeringPotion.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.minecraft.server; - -public class ItemLingeringPotion extends ItemPotion { - - public ItemLingeringPotion(Item.Info item_info) { - super(item_info); - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - /* // Paper start - ItemStack itemstack1 = entityhuman.abilities.canInstantlyBuild ? itemstack.cloneItemStack() : itemstack.cloneAndSubtract(1); - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_LINGERING_POTION_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (ItemLingeringPotion.i.nextFloat() * 0.4F + 0.8F)); - */ // Paper end - if (!world.isClientSide) { - - // Paper start - ensure stack count matches vanilla behavior without modifying original stack yet - ItemStack itemstack1 = itemstack.cloneItemStack(); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack1.setCount(1); - } - // Paper end - EntityPotion entitypotion = new EntityPotion(world, entityhuman); - - entitypotion.setItem(itemstack1); - entitypotion.a(entityhuman, entityhuman.pitch, entityhuman.yaw, -20.0F, 0.5F, 1.0F); - // Paper start - com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent event = new com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack), (org.bukkit.entity.Projectile) entitypotion.getBukkitEntity()); - if (event.callEvent() && world.addEntity(entitypotion)) { - if (event.shouldConsume() && !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_LINGERING_POTION_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (Entity.SHARED_RANDOM.nextFloat() * 0.4F + 0.8F)); - } else { - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - return new InteractionResultWrapper(EnumInteractionResult.FAIL, itemstack); - } - // Paper end - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/ItemMilkBucket.java b/src/main/java/net/minecraft/server/ItemMilkBucket.java deleted file mode 100644 index a6477d26a..000000000 --- a/src/main/java/net/minecraft/server/ItemMilkBucket.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.minecraft.server; - -public class ItemMilkBucket extends Item { - - public ItemMilkBucket(Item.Info item_info) { - super(item_info); - } - - @Override - public ItemStack a(ItemStack itemstack, World world, EntityLiving entityliving) { - if (entityliving instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entityliving; - - CriterionTriggers.z.a(entityplayer, itemstack); - entityplayer.b(StatisticList.ITEM_USED.b(this)); - } - - if (entityliving instanceof EntityHuman && !((EntityHuman) entityliving).abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - if (!world.isClientSide) { - entityliving.removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.MILK); // CraftBukkit - } - - return itemstack.isEmpty() ? new ItemStack(Items.BUCKET) : itemstack; - } - - @Override - public int f_(ItemStack itemstack) { - return 32; - } - - @Override - public EnumAnimation e_(ItemStack itemstack) { - return EnumAnimation.DRINK; - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - entityhuman.c(enumhand); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, entityhuman.b(enumhand)); - } -} diff --git a/src/main/java/net/minecraft/server/ItemMinecart.java b/src/main/java/net/minecraft/server/ItemMinecart.java deleted file mode 100644 index ec96fa0a4..000000000 --- a/src/main/java/net/minecraft/server/ItemMinecart.java +++ /dev/null @@ -1,136 +0,0 @@ -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(); - - @Override - public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { - EnumDirection enumdirection = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - 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); - BlockPropertyTrackPosition blockpropertytrackposition = iblockdata.getBlock() instanceof BlockMinecartTrackAbstract ? (BlockPropertyTrackPosition) iblockdata.get(((BlockMinecartTrackAbstract) iblockdata.getBlock()).e()) : BlockPropertyTrackPosition.NORTH_SOUTH; - double d3; - - if (iblockdata.a(TagsBlock.RAILS)) { - if (blockpropertytrackposition.c()) { - d3 = 0.6D; - } else { - d3 = 0.1D; - } - } else { - if (!iblockdata.isAir() || !world.getType(blockposition.down()).a(TagsBlock.RAILS)) { - return this.b.dispense(isourceblock, itemstack); - } - - IBlockData iblockdata1 = world.getType(blockposition.down()); - BlockPropertyTrackPosition blockpropertytrackposition1 = iblockdata1.getBlock() instanceof BlockMinecartTrackAbstract ? (BlockPropertyTrackPosition) iblockdata1.get(((BlockMinecartTrackAbstract) iblockdata1.getBlock()).e()) : BlockPropertyTrackPosition.NORTH_SOUTH; - - if (enumdirection != EnumDirection.DOWN && blockpropertytrackposition1.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.add(1); - return itemstack; - } - - if (!event.getItem().equals(craftItem)) { - itemstack.add(1); - // Chain to handler for new item - ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); - IDispenseBehavior idispensebehavior = (IDispenseBehavior) BlockDispenser.REGISTRY.get(eventStack.getItem()); - if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { - idispensebehavior.dispense(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()); - } - - if (!world.addEntity(entityminecartabstract)) itemstack.add(1); - // itemstack.subtract(1); // CraftBukkit - handled during event processing - // CraftBukkit end - return itemstack; - } - - @Override - protected void a(ISourceBlock isourceblock) { - isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); - } - }; - private final EntityMinecartAbstract.EnumMinecartType b; - - public ItemMinecart(EntityMinecartAbstract.EnumMinecartType entityminecartabstract_enumminecarttype, Item.Info item_info) { - super(item_info); - this.b = entityminecartabstract_enumminecarttype; - BlockDispenser.a((IMaterial) this, ItemMinecart.a); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - World world = itemactioncontext.getWorld(); - BlockPosition blockposition = itemactioncontext.getClickPosition(); - IBlockData iblockdata = world.getType(blockposition); - - if (!iblockdata.a(TagsBlock.RAILS)) { - return EnumInteractionResult.FAIL; - } else { - ItemStack itemstack = itemactioncontext.getItemStack(); - - if (!world.isClientSide) { - BlockPropertyTrackPosition blockpropertytrackposition = iblockdata.getBlock() instanceof BlockMinecartTrackAbstract ? (BlockPropertyTrackPosition) iblockdata.get(((BlockMinecartTrackAbstract) iblockdata.getBlock()).e()) : BlockPropertyTrackPosition.NORTH_SOUTH; - double d0 = 0.0D; - - if (blockpropertytrackposition.c()) { - d0 = 0.5D; - } - - 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()); - } - - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityPlaceEvent(itemactioncontext, entityminecartabstract).isCancelled()) { - return EnumInteractionResult.FAIL; - } - // CraftBukkit end - if (!world.addEntity(entityminecartabstract)) return EnumInteractionResult.PASS; // CraftBukkit - } - - itemstack.subtract(1); - return EnumInteractionResult.SUCCESS; - } - } -} diff --git a/src/main/java/net/minecraft/server/ItemPotion.java b/src/main/java/net/minecraft/server/ItemPotion.java deleted file mode 100644 index d45d990d8..000000000 --- a/src/main/java/net/minecraft/server/ItemPotion.java +++ /dev/null @@ -1,92 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; - -public class ItemPotion extends Item { - - public ItemPotion(Item.Info item_info) { - super(item_info); - } - - @Override - public ItemStack a(ItemStack itemstack, World world, EntityLiving entityliving) { - EntityHuman entityhuman = entityliving instanceof EntityHuman ? (EntityHuman) entityliving : null; - - if (entityhuman == null || !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.z.a((EntityPlayer) entityhuman, itemstack); - } - - if (!world.isClientSide) { - List list = PotionUtil.getEffects(itemstack); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - if (mobeffect.getMobEffect().isInstant()) { - mobeffect.getMobEffect().applyInstantEffect(entityhuman, entityhuman, entityliving, mobeffect.getAmplifier(), 1.0D); - } else { - entityliving.addEffect(new MobEffect(mobeffect), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.POTION_DRINK); // CraftBukkit - } - } - } - - if (entityhuman != null) { - entityhuman.b(StatisticList.ITEM_USED.b(this)); - } - - if (entityhuman == null || !entityhuman.abilities.canInstantlyBuild) { - if (itemstack.isEmpty()) { - return new ItemStack(Items.GLASS_BOTTLE); - } - - if (entityhuman != null) { - entityhuman.inventory.pickup(new ItemStack(Items.GLASS_BOTTLE)); - } - } - - return itemstack; - } - - @Override - public int f_(ItemStack itemstack) { - return 32; - } - - @Override - public EnumAnimation e_(ItemStack itemstack) { - return EnumAnimation.DRINK; - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - entityhuman.c(enumhand); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, entityhuman.b(enumhand)); - } - - @Override - public String f(ItemStack itemstack) { - return PotionUtil.d(itemstack).b(this.getName() + ".effect."); - } - - @Override - public void a(CreativeModeTab creativemodetab, NonNullList nonnulllist) { - if (this.a(creativemodetab)) { - Iterator iterator = IRegistry.POTION.iterator(); - - while (iterator.hasNext()) { - PotionRegistry potionregistry = (PotionRegistry) iterator.next(); - - if (potionregistry != Potions.EMPTY) { - nonnulllist.add(PotionUtil.a(new ItemStack(this), potionregistry)); - } - } - } - - } -} diff --git a/src/main/java/net/minecraft/server/ItemRecord.java b/src/main/java/net/minecraft/server/ItemRecord.java deleted file mode 100644 index d9cfdc0d8..000000000 --- a/src/main/java/net/minecraft/server/ItemRecord.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.Map; - -public class ItemRecord extends Item { - - private static final Map a = Maps.newHashMap(); - private final int b; - private final SoundEffect c; - - protected ItemRecord(int i, SoundEffect soundeffect, Item.Info item_info) { - super(item_info); - this.b = i; - this.c = soundeffect; - ItemRecord.a.put(this.c, this); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - World world = itemactioncontext.getWorld(); - BlockPosition blockposition = itemactioncontext.getClickPosition(); - IBlockData iblockdata = world.getType(blockposition); - - if (iblockdata.getBlock() == Blocks.JUKEBOX && !(Boolean) iblockdata.get(BlockJukeBox.HAS_RECORD)) { - ItemStack itemstack = itemactioncontext.getItemStack(); - - if (!world.isClientSide) { - if (true) return EnumInteractionResult.SUCCESS; // CraftBukkit - handled in ItemStack - ((BlockJukeBox) Blocks.JUKEBOX).a((GeneratorAccess) world, blockposition, iblockdata, itemstack); - world.a((EntityHuman) null, 1010, blockposition, Item.getId(this)); - itemstack.subtract(1); - EntityHuman entityhuman = itemactioncontext.getEntity(); - - if (entityhuman != null) { - entityhuman.a(StatisticList.PLAY_RECORD); - } - } - - return EnumInteractionResult.SUCCESS; - } else { - return EnumInteractionResult.PASS; - } - } - - public int d() { - return this.b; - } -} diff --git a/src/main/java/net/minecraft/server/ItemSign.java b/src/main/java/net/minecraft/server/ItemSign.java deleted file mode 100644 index d85f56655..000000000 --- a/src/main/java/net/minecraft/server/ItemSign.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class ItemSign extends ItemBlockWallable { - - public static BlockPosition openSign; // CraftBukkit - - public ItemSign(Item.Info item_info, Block block, Block block1) { - super(block, block1, item_info); - } - - @Override - protected boolean a(BlockPosition blockposition, World world, @Nullable EntityHuman entityhuman, ItemStack itemstack, IBlockData iblockdata) { - boolean flag = super.a(blockposition, world, entityhuman, itemstack, iblockdata); - - if (!world.isClientSide && !flag && entityhuman != null) { - // CraftBukkit start - SPIGOT-4678 - // entityhuman.openSign((TileEntitySign) world.getTileEntity(blockposition)); - ItemSign.openSign = blockposition; - // CraftBukkit end - } - - return flag; - } -} diff --git a/src/main/java/net/minecraft/server/ItemSkullPlayer.java b/src/main/java/net/minecraft/server/ItemSkullPlayer.java deleted file mode 100644 index 4e4162dc4..000000000 --- a/src/main/java/net/minecraft/server/ItemSkullPlayer.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.minecraft.server; - -import com.mojang.authlib.GameProfile; -import java.util.UUID; -import org.apache.commons.lang3.StringUtils; - -public class ItemSkullPlayer extends ItemBlockWallable { - - public ItemSkullPlayer(Block block, Block block1, Item.Info item_info) { - super(block, block1, item_info); - } - - @Override - public IChatBaseComponent g(ItemStack itemstack) { - if (itemstack.getItem() == Items.PLAYER_HEAD && itemstack.hasTag()) { - String s = null; - NBTTagCompound nbttagcompound = itemstack.getTag(); - - if (nbttagcompound.hasKeyOfType("SkullOwner", 8)) { - s = nbttagcompound.getString("SkullOwner"); - } else if (nbttagcompound.hasKeyOfType("SkullOwner", 10)) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("SkullOwner"); - - if (nbttagcompound1.hasKeyOfType("Name", 8)) { - s = nbttagcompound1.getString("Name"); - } - } - - if (s != null) { - return new ChatMessage(this.getName() + ".named", new Object[]{s}); - } - } - - return super.g(itemstack); - } - - @Override - public boolean a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - if (nbttagcompound.hasKeyOfType("SkullOwner", 8) && !StringUtils.isBlank(nbttagcompound.getString("SkullOwner"))) { - GameProfile gameprofile = new GameProfile((UUID) null, nbttagcompound.getString("SkullOwner")); - - // Spigot start - TileEntitySkull.b(gameprofile, new com.google.common.base.Predicate() { - - @Override - public boolean apply(GameProfile gameprofile) { - nbttagcompound.set("SkullOwner", GameProfileSerializer.serialize(new NBTTagCompound(), gameprofile)); - return false; - } - }, false); - // Spigot end - return true; - } else { - // CraftBukkit start - NBTTagList textures = nbttagcompound.getCompound("SkullOwner").getCompound("Properties").getList("textures", 10); // Safe due to method contracts - for (int i = 0; i < textures.size(); i++) { - if (textures.get(i) instanceof NBTTagCompound && !((NBTTagCompound) textures.get(i)).hasKeyOfType("Signature", 8) && ((NBTTagCompound) textures.get(i)).getString("Value").trim().isEmpty()) { - nbttagcompound.remove("SkullOwner"); - break; - } - } - // CraftBukkit end - return false; - } - } -} diff --git a/src/main/java/net/minecraft/server/ItemSnowball.java b/src/main/java/net/minecraft/server/ItemSnowball.java deleted file mode 100644 index bbd22596e..000000000 --- a/src/main/java/net/minecraft/server/ItemSnowball.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.minecraft.server; - -public class ItemSnowball extends Item { - - public ItemSnowball(Item.Info item_info) { - super(item_info); - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - // CraftBukkit start - moved down - /* - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_SNOWBALL_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (ItemSnowball.i.nextFloat() * 0.4F + 0.8F)); - */ - if (!world.isClientSide) { - EntitySnowball entitysnowball = new EntitySnowball(world, entityhuman); - - entitysnowball.setItem(itemstack); - entitysnowball.a(entityhuman, entityhuman.pitch, entityhuman.yaw, 0.0F, 1.5F, 1.0F); - // Paper start - com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent event = new com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack), (org.bukkit.entity.Projectile) entitysnowball.getBukkitEntity()); - if (event.callEvent() && world.addEntity(entitysnowball)) { - if (event.shouldConsume() && !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_SNOWBALL_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (Entity.SHARED_RANDOM.nextFloat() * 0.4F + 0.8F)); - } else { - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } - } - // CraftBukkit end - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/ItemSplashPotion.java b/src/main/java/net/minecraft/server/ItemSplashPotion.java deleted file mode 100644 index 4460ddc6d..000000000 --- a/src/main/java/net/minecraft/server/ItemSplashPotion.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.minecraft.server; - -public class ItemSplashPotion extends ItemPotion { - - public ItemSplashPotion(Item.Info item_info) { - super(item_info); - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - /* // Paper start - ItemStack itemstack1 = entityhuman.abilities.canInstantlyBuild ? itemstack.cloneItemStack() : itemstack.cloneAndSubtract(1); - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_SPLASH_POTION_THROW, SoundCategory.PLAYERS, 0.5F, 0.4F / (ItemSplashPotion.i.nextFloat() * 0.4F + 0.8F)); - */ // Paper end - if (!world.isClientSide) { - EntityPotion entitypotion = new EntityPotion(world, entityhuman); - // Paper start - ensure stack count matches vanilla behavior without modifying original stack yet - ItemStack itemstack1 = itemstack.cloneItemStack(); - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack1.setCount(1); - } - // Paper end - - entitypotion.setItem(itemstack1); - entitypotion.a(entityhuman, entityhuman.pitch, entityhuman.yaw, -20.0F, 0.5F, 1.0F); - // Paper start - com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent event = new com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack), (org.bukkit.entity.Projectile) entitypotion.getBukkitEntity()); - if (event.callEvent() && world.addEntity(entitypotion)) { - if (event.shouldConsume() && !entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } else if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - - world.playSound((EntityHuman) null, entityhuman.locX, entityhuman.locY, entityhuman.locZ, SoundEffects.ENTITY_SPLASH_POTION_THROW, SoundCategory.PLAYERS, 0.5F, 0.4F / (Entity.SHARED_RANDOM.nextFloat() * 0.4F + 0.8F)); - } else { - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - return new InteractionResultWrapper(EnumInteractionResult.FAIL, itemstack); - } - // Paper end - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } -} diff --git a/src/main/java/net/minecraft/server/ItemStack.java b/src/main/java/net/minecraft/server/ItemStack.java deleted file mode 100644 index 0e164840f..000000000 --- a/src/main/java/net/minecraft/server/ItemStack.java +++ /dev/null @@ -1,915 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import com.google.gson.JsonParseException; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.Collections; -import java.util.Comparator; -import java.util.Locale; -import java.util.Objects; -import java.util.Random; -import java.util.function.Consumer; -import java.util.function.Predicate; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import com.mojang.datafixers.Dynamic; -import java.util.List; -import java.util.Map; - -import org.bukkit.Location; -import org.bukkit.TreeType; -import org.bukkit.block.BlockState; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.block.CraftBlockState; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.entity.Player; -import org.bukkit.event.block.BlockFertilizeEvent; -import org.bukkit.event.player.PlayerItemDamageEvent; -import org.bukkit.event.world.StructureGrowEvent; -// CraftBukkit end - -public final class ItemStack { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final ItemStack a = new ItemStack((Item) null);public static final ItemStack NULL_ITEM = a; // Paper - OBFHELPER - public static final DecimalFormat b = F(); - private int count; - private int e; - // Paper start - private org.bukkit.craftbukkit.inventory.CraftItemStack bukkitStack; - public org.bukkit.inventory.ItemStack getBukkitStack() { - if (bukkitStack == null || bukkitStack.getHandle() != this) { - bukkitStack = org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(this); - } - return bukkitStack; - } - // Paper end - @Deprecated - private Item item; - NBTTagCompound tag; // Paper -> package private - private boolean h; - private EntityItemFrame i; - private ShapeDetectorBlock j; - private boolean k; - private ShapeDetectorBlock l; - private boolean m; - - private static DecimalFormat F() { - DecimalFormat decimalformat = new DecimalFormat("#.##"); - - decimalformat.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ROOT)); - return decimalformat; - } - // Paper start - private static final java.util.Comparator enchantSorter = java.util.Comparator.comparing(o -> o.getString("id")); - private void processEnchantOrder(NBTTagCompound tag) { - if (tag == null || !tag.hasKeyOfType("Enchantments", 9)) { - return; - } - NBTTagList list = tag.getList("Enchantments", 10); - if (list.size() < 2) { - return; - } - try { - //noinspection unchecked - list.sort((Comparator) enchantSorter); // Paper - } catch (Exception ignored) {} - } - // Paper end - - public ItemStack(IMaterial imaterial) { - this(imaterial, 1); - } - - public ItemStack(IMaterial imaterial, int i) { - this.item = imaterial == null ? null : imaterial.getItem(); - this.count = i; - this.checkEmpty(); - } - - // Called to run this stack through the data converter to handle older storage methods and serialized items - public void convertStack(int version) { - if (0 < version && version < CraftMagicNumbers.INSTANCE.getDataVersion()) { - NBTTagCompound savedStack = new NBTTagCompound(); - this.save(savedStack); - savedStack = (NBTTagCompound) MinecraftServer.getServer().dataConverterManager.update(DataConverterTypes.ITEM_STACK, new Dynamic(DynamicOpsNBT.a, savedStack), version, CraftMagicNumbers.INSTANCE.getDataVersion()).getValue(); - this.load(savedStack); - } - } - - private void checkEmpty() { - if (this.h && this == ItemStack.a) throw new AssertionError("TRAP"); // CraftBukkit - this.h = false; - this.h = this.isEmpty(); - } - - // CraftBukkit - break into own method - private void load(NBTTagCompound nbttagcompound) { - this.item = (Item) IRegistry.ITEM.get(new MinecraftKey(nbttagcompound.getString("id"))); - this.count = nbttagcompound.getByte("Count"); - if (nbttagcompound.hasKeyOfType("tag", 10)) { - // CraftBukkit start - make defensive copy as this data may be coming from the save thread - this.tag = (NBTTagCompound) nbttagcompound.getCompound("tag").clone(); - processEnchantOrder(this.tag); // Paper - this.getItem().a(this.tag); - // CraftBukkit end - } - - if (this.getItem().usesDurability()) { - this.setDamage(this.getDamage()); - } - - } - - private ItemStack(NBTTagCompound nbttagcompound) { - this.load(nbttagcompound); - // CraftBukkit end - this.checkEmpty(); - } - - public static ItemStack a(NBTTagCompound nbttagcompound) { - try { - return new ItemStack(nbttagcompound); - } catch (RuntimeException runtimeexception) { - ItemStack.LOGGER.debug("Tried to load invalid item: {}", nbttagcompound, runtimeexception); - return ItemStack.a; - } - } - - public boolean isEmpty() { - return this == ItemStack.a || this.item == null || this.item == Items.AIR || this.count <= 0; // Paper - } - - public ItemStack cloneAndSubtract(int i) { - int j = Math.min(i, this.count); - ItemStack itemstack = this.cloneItemStack(); - - itemstack.setCount(j); - this.subtract(j); - return itemstack; - } - - public Item getItem() { - return this.h ? Items.AIR : this.item; - } - - public EnumInteractionResult placeItem(ItemActionContext itemactioncontext, EnumHand enumhand) { // CraftBukkit - add hand - EntityHuman entityhuman = itemactioncontext.getEntity(); - BlockPosition blockposition = itemactioncontext.getClickPosition(); - ShapeDetectorBlock shapedetectorblock = new ShapeDetectorBlock(itemactioncontext.getWorld(), blockposition, false); - - if (entityhuman != null && !entityhuman.abilities.mayBuild && !this.b(itemactioncontext.getWorld().t(), shapedetectorblock)) { - return EnumInteractionResult.PASS; - } else { - // CraftBukkit start - handle all block place event logic here - NBTTagCompound oldData = this.getTagClone(); - int oldCount = this.getCount(); - World world = itemactioncontext.getWorld(); - - if (!(this.getItem() instanceof ItemBucket)) { // if not bucket - world.captureBlockStates = true; - // special case bonemeal - if (this.getItem() == Items.BONE_MEAL) { - world.captureTreeGeneration = true; - } - } - Item item = this.getItem(); - EnumInteractionResult enuminteractionresult = item.a(itemactioncontext); - NBTTagCompound newData = this.getTagClone(); - int newCount = this.getCount(); - this.setCount(oldCount); - this.setTagClone(oldData); - world.captureBlockStates = false; - if (enuminteractionresult == EnumInteractionResult.SUCCESS && world.captureTreeGeneration && world.capturedBlockStates.size() > 0) { - 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 structureEvent = null; - if (treeType != null) { - boolean isBonemeal = getItem() == Items.BONE_MEAL; - structureEvent = new StructureGrowEvent(location, treeType, isBonemeal, (Player) entityhuman.getBukkitEntity(), blocks); - org.bukkit.Bukkit.getPluginManager().callEvent(structureEvent); - } - - BlockFertilizeEvent fertilizeEvent = new BlockFertilizeEvent(CraftBlock.at(world, blockposition), (Player) entityhuman.getBukkitEntity(), blocks); - fertilizeEvent.setCancelled(structureEvent != null && structureEvent.isCancelled()); - org.bukkit.Bukkit.getPluginManager().callEvent(fertilizeEvent); - - if (!fertilizeEvent.isCancelled()) { - // Change the stack to its new contents if it hasn't been tampered with. - if (this.getCount() == oldCount && Objects.equals(this.tag, oldData)) { - this.setTag(newData); - this.setCount(newCount); - } - for (BlockState blockstate : blocks) { - blockstate.update(true); - } - } - - return enuminteractionresult; - } - world.captureTreeGeneration = false; - - if (entityhuman != null && enuminteractionresult == EnumInteractionResult.SUCCESS) { - 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, enumhand, blocks, blockposition.getX(), blockposition.getY(), blockposition.getZ()); - } else if (blocks.size() == 1) { - placeEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callBlockPlaceEvent(world, entityhuman, enumhand, blocks.get(0), blockposition.getX(), blockposition.getY(), blockposition.getZ()); - } - - if (placeEvent != null && (placeEvent.isCancelled() || !placeEvent.canBuild())) { - enuminteractionresult = EnumInteractionResult.FAIL; // cancel placement - // PAIL: Remove this when MC-99075 fixed - placeEvent.getPlayer().updateInventory(); - world.capturedTileEntities.clear(); // Paper - clear out tile entities as chests and such will pop loot - // revert back all captured blocks - for (BlockState blockstate : blocks) { - blockstate.update(true, false); - } - - // Brute force all possible updates - BlockPosition placedPos = ((CraftBlock) placeEvent.getBlock()).getPosition(); - for (EnumDirection dir : EnumDirection.values()) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutBlockChange(world, placedPos.shift(dir))); - } - } else { - // Change the stack to its new contents if it hasn't been tampered with. - if (this.getCount() == oldCount && Objects.equals(this.tag, oldData)) { - this.setTag(newData); - this.setCount(newCount); - } - - for (Map.Entry e : world.capturedTileEntities.entrySet()) { - world.setTileEntity(e.getKey(), e.getValue()); - } - - for (BlockState blockstate : blocks) { - int updateFlag = ((CraftBlockState) blockstate).getFlag(); - IBlockData oldBlock = ((CraftBlockState) blockstate).getHandle(); - BlockPosition newblockposition = ((CraftBlockState) blockstate).getPosition(); - IBlockData block = world.getType(newblockposition); - - if (!(block.getBlock() instanceof BlockTileEntity)) { // Containers get placed automatically - block.getBlock().onPlace(block, world, newblockposition, oldBlock, true); - } - - world.notifyAndUpdatePhysics(newblockposition, null, oldBlock, block, world.getType(newblockposition), updateFlag); // send null chunk as chunk.k() returns false by this point - } - - // Special case juke boxes as they update their tile entity. Copied from ItemRecord. - // PAIL: checkme on updates. - if (this.item instanceof ItemRecord) { - ((BlockJukeBox) Blocks.JUKEBOX).a(world, blockposition, world.getType(blockposition), this); - world.a((EntityHuman) null, 1010, blockposition, Item.getId(this.item)); - this.subtract(1); - entityhuman.a(StatisticList.PLAY_RECORD); - } - - if (this.item == Items.WITHER_SKELETON_SKULL) { // Special case skulls to allow wither spawns to be cancelled - BlockPosition bp = blockposition; - if (!world.getType(blockposition).getMaterial().isReplaceable()) { - if (!world.getType(blockposition).getMaterial().isBuildable()) { - bp = null; - } else { - bp = bp.shift(itemactioncontext.getClickedFace()); - } - } - if (bp != null) { - TileEntity te = world.getTileEntity(bp); - if (te instanceof TileEntitySkull) { - BlockWitherSkull.a(world, bp, (TileEntitySkull) te); - } - } - } - - // SPIGOT-4678 - if (this.item instanceof ItemSign && ItemSign.openSign != null) { - try { - entityhuman.openSign((TileEntitySign) world.getTileEntity(ItemSign.openSign)); - } finally { - ItemSign.openSign = null; - } - } - - // SPIGOT-1288 - play sound stripped from ItemBlock - if (this.item instanceof ItemBlock) { - SoundEffectType soundeffecttype = ((ItemBlock) this.item).getBlock().stepSound; - world.playSound(entityhuman, blockposition, soundeffecttype.e(), SoundCategory.BLOCKS, (soundeffecttype.a() + 1.0F) / 2.0F, soundeffecttype.b() * 0.8F); - } - - entityhuman.b(StatisticList.ITEM_USED.b(item)); - } - } - world.capturedTileEntities.clear(); - world.capturedBlockStates.clear(); - // CraftBukkit end - - return enuminteractionresult; - } - } - - public float a(IBlockData iblockdata) { - return this.getItem().getDestroySpeed(this, iblockdata); - } - - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - return this.getItem().a(world, entityhuman, enumhand); - } - - public ItemStack a(World world, EntityLiving entityliving) { - return this.getItem().a(this, world, entityliving); - } - - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - MinecraftKey minecraftkey = IRegistry.ITEM.getKey(this.getItem()); - - nbttagcompound.setString("id", minecraftkey == null ? "minecraft:air" : minecraftkey.toString()); - nbttagcompound.setByte("Count", (byte) this.count); - if (this.tag != null) { - nbttagcompound.set("tag", this.tag.clone()); // CraftBukkit - make defensive copy, data is going to another thread - } - - return nbttagcompound; - } - - public int getMaxStackSize() { - return this.getItem().getMaxStackSize(); - } - - public boolean isStackable() { - return this.getMaxStackSize() > 1 && (!this.e() || !this.f()); - } - - public boolean e() { - if (!this.h && this.getItem().getMaxDurability() > 0) { - NBTTagCompound nbttagcompound = this.getTag(); - - return nbttagcompound == null || !nbttagcompound.getBoolean("Unbreakable"); - } else { - return false; - } - } - - public boolean f() { - return this.e() && this.getDamage() > 0; - } - - public int getDamage() { - return this.tag == null ? 0 : this.tag.getInt("Damage"); - } - - public void setDamage(int i) { - // CraftBukkit start - remove Damage tag if 0 - if (i <= 0) { - this.removeTag("Damage"); - return; - } - // CraftBukkit end - this.getOrCreateTag().setInt("Damage", Math.max(0, i)); - } - - public int h() { - return this.getItem().getMaxDurability(); - } - - public boolean isDamaged(int i, Random random, @Nullable EntityPlayer entityplayer) { - if (!this.e()) { - return false; - } else { - int j; - - if (i > 0) { - j = EnchantmentManager.getEnchantmentLevel(Enchantments.DURABILITY, this); - int k = 0; - - for (int l = 0; j > 0 && l < i; ++l) { - if (EnchantmentDurability.a(this, j, random)) { - ++k; - } - } - - i -= k; - // CraftBukkit start - if (entityplayer != null) { - PlayerItemDamageEvent event = new PlayerItemDamageEvent(entityplayer.getBukkitEntity(), CraftItemStack.asCraftMirror(this), i); - event.getPlayer().getServer().getPluginManager().callEvent(event); - - if (i != event.getDamage() || event.isCancelled()) { - event.getPlayer().updateInventory(); - } - if (event.isCancelled()) { - return false; - } - - i = event.getDamage(); - } - // CraftBukkit end - if (i <= 0) { - return false; - } - } - - if (entityplayer != null && i != 0) { - CriterionTriggers.t.a(entityplayer, this, this.getDamage() + i); - } - - j = this.getDamage() + i; - this.setDamage(j); - return j >= this.h(); - } - } - - public void damage(int i, T t0, Consumer consumer) { - if (!t0.world.isClientSide && (!(t0 instanceof EntityHuman) || !((EntityHuman) t0).abilities.canInstantlyBuild)) { - if (this.e()) { - if (this.isDamaged(i, t0.getRandom(), t0 instanceof EntityPlayer ? (EntityPlayer) t0 : null)) { - consumer.accept(t0); - Item item = this.getItem(); - // CraftBukkit start - Check for item breaking - if (this.count == 1 && t0 instanceof EntityHuman) { - org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerItemBreakEvent((EntityHuman) t0, this); - } - // CraftBukkit end - - this.subtract(1); - if (t0 instanceof EntityHuman) { - ((EntityHuman) t0).b(StatisticList.ITEM_BROKEN.b(item)); - } - - this.setDamage(0); - } - - } - } - } - - public void a(EntityLiving entityliving, EntityHuman entityhuman) { - Item item = this.getItem(); - - if (item.a(this, entityliving, (EntityLiving) entityhuman)) { - entityhuman.b(StatisticList.ITEM_USED.b(item)); - } - - } - - public void a(World world, IBlockData iblockdata, BlockPosition blockposition, EntityHuman entityhuman) { - Item item = this.getItem(); - - if (item.a(this, world, iblockdata, blockposition, entityhuman)) { - entityhuman.b(StatisticList.ITEM_USED.b(item)); - } - - } - - public boolean b(IBlockData iblockdata) { - return this.getItem().canDestroySpecialBlock(iblockdata); - } - - public boolean a(EntityHuman entityhuman, EntityLiving entityliving, EnumHand enumhand) { - return this.getItem().a(this, entityhuman, entityliving, enumhand); - } - - public ItemStack cloneItemStack() { return cloneItemStack(false); } // Paper - public ItemStack cloneItemStack(boolean origItem) { // Paper - ItemStack itemstack = new ItemStack(origItem ? this.item : this.getItem(), this.count); // Paper - - itemstack.d(this.C()); - if (this.tag != null) { - itemstack.tag = this.tag.clone(); - } - - return itemstack; - } - - public static boolean equals(ItemStack itemstack, ItemStack itemstack1) { - return itemstack.isEmpty() && itemstack1.isEmpty() ? true : (!itemstack.isEmpty() && !itemstack1.isEmpty() ? (itemstack.tag == null && itemstack1.tag != null ? false : itemstack.tag == null || itemstack.tag.equals(itemstack1.tag)) : false); - } - - public static boolean matches(ItemStack itemstack, ItemStack itemstack1) { - return itemstack.isEmpty() && itemstack1.isEmpty() ? true : (!itemstack.isEmpty() && !itemstack1.isEmpty() ? itemstack.c(itemstack1) : false); - } - - private boolean c(ItemStack itemstack) { - return this.count != itemstack.count ? false : (this.getItem() != itemstack.getItem() ? false : (this.tag == null && itemstack.tag != null ? false : this.tag == null || this.tag.equals(itemstack.tag))); - } - - public static boolean c(ItemStack itemstack, ItemStack itemstack1) { - return itemstack == itemstack1 ? true : (!itemstack.isEmpty() && !itemstack1.isEmpty() ? itemstack.doMaterialsMatch(itemstack1) : false); - } - - public static boolean d(ItemStack itemstack, ItemStack itemstack1) { - return itemstack == itemstack1 ? true : (!itemstack.isEmpty() && !itemstack1.isEmpty() ? itemstack.b(itemstack1) : false); - } - - public boolean doMaterialsMatch(ItemStack itemstack) { - return !itemstack.isEmpty() && this.getItem() == itemstack.getItem(); - } - - public boolean b(ItemStack itemstack) { - return !this.e() ? this.doMaterialsMatch(itemstack) : !itemstack.isEmpty() && this.getItem() == itemstack.getItem(); - } - - public String j() { - return this.getItem().f(this); - } - - public String toString() { - return this.count + " " + this.getItem(); - } - - public void a(World world, Entity entity, int i, boolean flag) { - if (this.e > 0) { - --this.e; - } - - if (this.getItem() != null) { - this.getItem().a(this, world, entity, i, flag); - } - - } - - public void a(World world, EntityHuman entityhuman, int i) { - entityhuman.a(StatisticList.ITEM_CRAFTED.b(this.getItem()), i); - this.getItem().b(this, world, entityhuman); - } - - public int getItemUseMaxDuration() { return k(); } // Paper - OBFHELPER - public int k() { - return this.getItem().f_(this); - } - - public EnumAnimation l() { - return this.getItem().e_(this); - } - - public void a(World world, EntityLiving entityliving, int i) { - this.getItem().a(this, world, entityliving, i); - } - - public boolean m() { - return this.getItem().i(this); - } - - public boolean hasTag() { - return !this.h && this.tag != null && !this.tag.isEmpty(); - } - - @Nullable - public NBTTagCompound getTag() { - return this.tag; - } - - // CraftBukkit start - @Nullable - private NBTTagCompound getTagClone() { - return this.tag == null ? null : this.tag.clone(); - } - - private void setTagClone(@Nullable NBTTagCompound nbtttagcompound) { - this.setTag(nbtttagcompound == null ? null : nbtttagcompound.clone()); - } - // CraftBukkit end - - public NBTTagCompound getOrCreateTag() { - if (this.tag == null) { - this.setTag(new NBTTagCompound()); - } - - return this.tag; - } - - public NBTTagCompound a(String s) { - if (this.tag != null && this.tag.hasKeyOfType(s, 10)) { - return this.tag.getCompound(s); - } else { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - this.a(s, (NBTBase) nbttagcompound); - return nbttagcompound; - } - } - - @Nullable - public NBTTagCompound b(String s) { - return this.tag != null && this.tag.hasKeyOfType(s, 10) ? this.tag.getCompound(s) : null; - } - - public void removeTag(String s) { - if (this.tag != null && this.tag.hasKey(s)) { - this.tag.remove(s); - if (this.tag.isEmpty()) { - this.tag = null; - } - } - - } - - public NBTTagList getEnchantments() { - return this.tag != null ? this.tag.getList("Enchantments", 10) : new NBTTagList(); - } - - // Paper start - (this is just a good no conflict location) - public org.bukkit.inventory.ItemStack asBukkitMirror() { - return CraftItemStack.asCraftMirror(this); - } - public org.bukkit.inventory.ItemStack asBukkitCopy() { - return CraftItemStack.asCraftMirror(this.cloneItemStack()); - } - public static ItemStack fromBukkitCopy(org.bukkit.inventory.ItemStack itemstack) { - return CraftItemStack.asNMSCopy(itemstack); - } - // Paper end - public void setTag(@Nullable NBTTagCompound nbttagcompound) { - this.tag = nbttagcompound; - processEnchantOrder(this.tag); // Paper - } - - public IChatBaseComponent getName() { - NBTTagCompound nbttagcompound = this.b("display"); - - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("Name", 8)) { - try { - IChatBaseComponent ichatbasecomponent = IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("Name")); - - if (ichatbasecomponent != null) { - return ichatbasecomponent; - } - - nbttagcompound.remove("Name"); - } catch (JsonParseException jsonparseexception) { - nbttagcompound.remove("Name"); - } - } - - return this.getItem().g(this); - } - - public ItemStack a(@Nullable IChatBaseComponent ichatbasecomponent) { - NBTTagCompound nbttagcompound = this.a("display"); - - if (ichatbasecomponent != null) { - nbttagcompound.setString("Name", IChatBaseComponent.ChatSerializer.a(ichatbasecomponent)); - } else { - nbttagcompound.remove("Name"); - } - - return this; - } - - public void s() { - NBTTagCompound nbttagcompound = this.b("display"); - - if (nbttagcompound != null) { - nbttagcompound.remove("Name"); - if (nbttagcompound.isEmpty()) { - this.removeTag("display"); - } - } - - if (this.tag != null && this.tag.isEmpty()) { - this.tag = null; - } - - } - - public boolean hasName() { - NBTTagCompound nbttagcompound = this.b("display"); - - return nbttagcompound != null && nbttagcompound.hasKeyOfType("Name", 8); - } - - public EnumItemRarity v() { - return this.getItem().h(this); - } - - public boolean canEnchant() { - return !this.getItem().g_(this) ? false : !this.hasEnchantments(); - } - - public void addEnchantment(Enchantment enchantment, int i) { - this.getOrCreateTag(); - if (!this.tag.hasKeyOfType("Enchantments", 9)) { - this.tag.set("Enchantments", new NBTTagList()); - } - - NBTTagList nbttaglist = this.tag.getList("Enchantments", 10); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setString("id", String.valueOf(IRegistry.ENCHANTMENT.getKey(enchantment))); - nbttagcompound.setShort("lvl", (short) ((byte) i)); - nbttaglist.add(nbttagcompound); - processEnchantOrder(nbttagcompound); // Paper - } - - public boolean hasEnchantments() { - return this.tag != null && this.tag.hasKeyOfType("Enchantments", 9) ? !this.tag.getList("Enchantments", 10).isEmpty() : false; - } - - public void getOrCreateTagAndSet(String s, NBTBase nbtbase) { a(s, nbtbase);} // Paper - OBFHELPER - public void a(String s, NBTBase nbtbase) { - this.getOrCreateTag().set(s, nbtbase); - } - - public boolean y() { - return this.i != null; - } - - public void a(@Nullable EntityItemFrame entityitemframe) { - this.i = entityitemframe; - } - - @Nullable - public EntityItemFrame z() { - return this.h ? null : this.i; - } - - public int getRepairCost() { - return this.hasTag() && this.tag.hasKeyOfType("RepairCost", 3) ? this.tag.getInt("RepairCost") : 0; - } - - public void setRepairCost(int i) { - // CraftBukkit start - remove RepairCost tag when 0 (SPIGOT-3945) - if (i == 0) { - this.removeTag("RepairCost"); - return; - } - // CraftBukkit end - this.getOrCreateTag().setInt("RepairCost", i); - } - - public Multimap a(EnumItemSlot enumitemslot) { - Object 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.getCompound(i); - AttributeModifier attributemodifier = GenericAttributes.a(nbttagcompound); - - if (attributemodifier != null && (!nbttagcompound.hasKeyOfType("Slot", 8) || nbttagcompound.getString("Slot").equals(enumitemslot.getSlotName())) && attributemodifier.getUniqueId().getLeastSignificantBits() != 0L && attributemodifier.getUniqueId().getMostSignificantBits() != 0L) { - ((Multimap) object).put(nbttagcompound.getString("AttributeName"), attributemodifier); - } - } - } else { - object = this.getItem().a(enumitemslot); - } - - return (Multimap) object; - } - - public void a(String s, AttributeModifier attributemodifier, @Nullable EnumItemSlot enumitemslot) { - this.getOrCreateTag(); - if (!this.tag.hasKeyOfType("AttributeModifiers", 9)) { - this.tag.set("AttributeModifiers", new NBTTagList()); - } - - NBTTagList nbttaglist = this.tag.getList("AttributeModifiers", 10); - NBTTagCompound nbttagcompound = GenericAttributes.a(attributemodifier); - - nbttagcompound.setString("AttributeName", s); - if (enumitemslot != null) { - nbttagcompound.setString("Slot", enumitemslot.getSlotName()); - } - - nbttaglist.add(nbttagcompound); - } - - // CraftBukkit start - @Deprecated - public void setItem(Item item) { - this.bukkitStack = null; // Paper - this.item = item; - } - // CraftBukkit end - - public IChatBaseComponent B() { - IChatBaseComponent ichatbasecomponent = (new ChatComponentText("")).addSibling(this.getName()); - - if (this.hasName()) { - ichatbasecomponent.a(EnumChatFormat.ITALIC); - } - - IChatBaseComponent ichatbasecomponent1 = ChatComponentUtils.a(ichatbasecomponent); - - if (!this.h) { - NBTTagCompound nbttagcompound = this.save(new NBTTagCompound()); - - ichatbasecomponent1.a(this.v().e).a((chatmodifier) -> { - chatmodifier.setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_ITEM, new ChatComponentText(nbttagcompound.toString()))); - }); - } - - return ichatbasecomponent1; - } - - private static boolean a(ShapeDetectorBlock shapedetectorblock, @Nullable ShapeDetectorBlock shapedetectorblock1) { - return shapedetectorblock1 != null && shapedetectorblock.a() == shapedetectorblock1.a() ? (shapedetectorblock.b() == null && shapedetectorblock1.b() == null ? true : (shapedetectorblock.b() != null && shapedetectorblock1.b() != null ? Objects.equals(shapedetectorblock.b().save(new NBTTagCompound()), shapedetectorblock1.b().save(new NBTTagCompound())) : false)) : false; - } - - public boolean a(TagRegistry tagregistry, ShapeDetectorBlock shapedetectorblock) { - if (a(shapedetectorblock, this.j)) { - return this.k; - } else { - this.j = shapedetectorblock; - if (this.hasTag() && this.tag.hasKeyOfType("CanDestroy", 9)) { - NBTTagList nbttaglist = this.tag.getList("CanDestroy", 8); - - for (int i = 0; i < nbttaglist.size(); ++i) { - String s = nbttaglist.getString(i); - - try { - Predicate predicate = ArgumentBlockPredicate.a().parse(new StringReader(s)).create(tagregistry); - - if (predicate.test(shapedetectorblock)) { - this.k = true; - return true; - } - } catch (CommandSyntaxException commandsyntaxexception) { - ; - } - } - } - - this.k = false; - return false; - } - } - - public boolean b(TagRegistry tagregistry, ShapeDetectorBlock shapedetectorblock) { - if (a(shapedetectorblock, this.l)) { - return this.m; - } else { - this.l = shapedetectorblock; - if (this.hasTag() && this.tag.hasKeyOfType("CanPlaceOn", 9)) { - NBTTagList nbttaglist = this.tag.getList("CanPlaceOn", 8); - - for (int i = 0; i < nbttaglist.size(); ++i) { - String s = nbttaglist.getString(i); - - try { - Predicate predicate = ArgumentBlockPredicate.a().parse(new StringReader(s)).create(tagregistry); - - if (predicate.test(shapedetectorblock)) { - this.m = true; - return true; - } - } catch (CommandSyntaxException commandsyntaxexception) { - ; - } - } - } - - this.m = false; - return false; - } - } - - public int C() { - return this.e; - } - - public void d(int i) { - this.e = i; - } - - public int getCount() { - return this.h ? 0 : this.count; - } - - public void setCount(int i) { - this.count = i; - this.checkEmpty(); - } - - public void add(int i) { - this.setCount(this.count + i); - } - - public void subtract(int i) { - this.add(-i); - } - - public void b(World world, EntityLiving entityliving, int i) { - this.getItem().a(world, entityliving, this, i); - } - - public boolean E() { - return this.getItem().isFood(); - } -} diff --git a/src/main/java/net/minecraft/server/ItemTrident.java b/src/main/java/net/minecraft/server/ItemTrident.java deleted file mode 100644 index c40815736..000000000 --- a/src/main/java/net/minecraft/server/ItemTrident.java +++ /dev/null @@ -1,171 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Multimap; - -public class ItemTrident extends Item { - - public ItemTrident(Item.Info item_info) { - super(item_info); - // CraftBukkit start - obfuscator went a little crazy - /* - this.a(new MinecraftKey("throwing"), (itemstack, world, entityliving) -> { - return entityliving != null && entityliving.isHandRaised() && entityliving.dl() == itemstack ? 1.0F : 0.0F; - }); - */ - // CraftBukkit end - } - - @Override - public boolean a(IBlockData iblockdata, World world, BlockPosition blockposition, EntityHuman entityhuman) { - return !entityhuman.isCreative(); - } - - @Override - public EnumAnimation e_(ItemStack itemstack) { - return EnumAnimation.SPEAR; - } - - @Override - public int f_(ItemStack itemstack) { - return 72000; - } - - @Override - public void a(ItemStack itemstack, World world, EntityLiving entityliving, int i) { - if (entityliving instanceof EntityHuman) { - EntityHuman entityhuman = (EntityHuman) entityliving; - int j = this.f_(itemstack) - i; - - if (j >= 10) { - int k = EnchantmentManager.g(itemstack); - - if (k <= 0 || entityhuman.isInWaterOrRain()) { - if (!world.isClientSide) { - // CraftBukkit - moved down - /* - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(entityliving.getRaisedHand()); - }); - */ - if (k == 0) { - EntityThrownTrident entitythrowntrident = new EntityThrownTrident(world, entityhuman, itemstack); - - entitythrowntrident.a(entityhuman, entityhuman.pitch, entityhuman.yaw, 0.0F, 2.5F + (float) k * 0.5F, 1.0F); - if (entityhuman.abilities.canInstantlyBuild) { - entitythrowntrident.fromPlayer = EntityArrow.PickupStatus.CREATIVE_ONLY; - } - - // CraftBukkit start - if (!world.addEntity(entitythrowntrident)) { - if (entityhuman instanceof EntityPlayer) { - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); - } - return; - } - - itemstack.damage(1, entityhuman, (entityhuman1) -> { - entityhuman1.d(entityliving.getRaisedHand()); - }); - entitythrowntrident.trident = itemstack.cloneItemStack(); // SPIGOT-4511 update since damage call moved - // CraftBukkit end - - world.playSound((EntityHuman) null, (Entity) entitythrowntrident, SoundEffects.ITEM_TRIDENT_THROW, SoundCategory.PLAYERS, 1.0F, 1.0F); - if (!entityhuman.abilities.canInstantlyBuild) { - entityhuman.inventory.f(itemstack); - } - } - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - if (k > 0) { - // CraftBukkit start - org.bukkit.event.player.PlayerRiptideEvent event = new org.bukkit.event.player.PlayerRiptideEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(itemstack)); - event.getPlayer().getServer().getPluginManager().callEvent(event); - // CraftBukkit end - float f = entityhuman.yaw; - float f1 = entityhuman.pitch; - float f2 = -MathHelper.sin(f * 0.017453292F) * MathHelper.cos(f1 * 0.017453292F); - float f3 = -MathHelper.sin(f1 * 0.017453292F); - float f4 = MathHelper.cos(f * 0.017453292F) * MathHelper.cos(f1 * 0.017453292F); - float f5 = MathHelper.c(f2 * f2 + f3 * f3 + f4 * f4); - float f6 = 3.0F * ((1.0F + (float) k) / 4.0F); - - f2 *= f6 / f5; - f3 *= f6 / f5; - f4 *= f6 / f5; - entityhuman.f((double) f2, (double) f3, (double) f4); - entityhuman.q(20); - if (entityhuman.onGround) { - float f7 = 1.1999999F; - - entityhuman.move(EnumMoveType.SELF, new Vec3D(0.0D, 1.1999999284744263D, 0.0D)); - } - - SoundEffect soundeffect; - - if (k >= 3) { - soundeffect = SoundEffects.ITEM_TRIDENT_RIPTIDE_3; - } else if (k == 2) { - soundeffect = SoundEffects.ITEM_TRIDENT_RIPTIDE_2; - } else { - soundeffect = SoundEffects.ITEM_TRIDENT_RIPTIDE_1; - } - - world.playSound((EntityHuman) null, (Entity) entityhuman, soundeffect, SoundCategory.PLAYERS, 1.0F, 1.0F); - } - - } - } - } - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - - if (itemstack.getDamage() >= itemstack.h()) { - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } else if (EnchantmentManager.g(itemstack) > 0 && !entityhuman.isInWaterOrRain()) { - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } else { - entityhuman.c(enumhand); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } - } - - @Override - public boolean a(ItemStack itemstack, EntityLiving entityliving, EntityLiving entityliving1) { - itemstack.damage(1, entityliving1, (entityliving2) -> { - entityliving2.c(EnumItemSlot.MAINHAND); - }); - return true; - } - - @Override - public boolean a(ItemStack itemstack, World world, IBlockData iblockdata, BlockPosition blockposition, EntityLiving entityliving) { - if ((double) iblockdata.f(world, blockposition) != 0.0D) { - itemstack.damage(2, entityliving, (entityliving1) -> { - entityliving1.c(EnumItemSlot.MAINHAND); - }); - } - - return true; - } - - @Override - public Multimap a(EnumItemSlot enumitemslot) { - Multimap multimap = super.a(enumitemslot); - - if (enumitemslot == EnumItemSlot.MAINHAND) { - multimap.put(GenericAttributes.ATTACK_DAMAGE.getName(), new AttributeModifier(ItemTrident.g, "Tool modifier", 8.0D, AttributeModifier.Operation.ADDITION)); - multimap.put(GenericAttributes.ATTACK_SPEED.getName(), new AttributeModifier(ItemTrident.h, "Tool modifier", -2.9000000953674316D, AttributeModifier.Operation.ADDITION)); - } - - return multimap; - } - - @Override - public int c() { - return 1; - } -} diff --git a/src/main/java/net/minecraft/server/ItemWaterLily.java b/src/main/java/net/minecraft/server/ItemWaterLily.java deleted file mode 100644 index 694a3a70e..000000000 --- a/src/main/java/net/minecraft/server/ItemWaterLily.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.minecraft.server; - -public class ItemWaterLily extends ItemBlock { - - public ItemWaterLily(Block block, Item.Info item_info) { - super(block, item_info); - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - return EnumInteractionResult.PASS; - } - - @Override - public InteractionResultWrapper a(World world, EntityHuman entityhuman, EnumHand enumhand) { - ItemStack itemstack = entityhuman.b(enumhand); - MovingObjectPosition movingobjectposition = a(world, entityhuman, RayTrace.FluidCollisionOption.SOURCE_ONLY); - - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.MISS) { - return new InteractionResultWrapper<>(EnumInteractionResult.PASS, itemstack); - } else { - if (movingobjectposition.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { - MovingObjectPositionBlock movingobjectpositionblock = (MovingObjectPositionBlock) movingobjectposition; - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition(); - EnumDirection enumdirection = movingobjectpositionblock.getDirection(); - - if (!world.a(entityhuman, blockposition) || !entityhuman.a(blockposition.shift(enumdirection), enumdirection, itemstack)) { - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } - - BlockPosition blockposition1 = blockposition.up(); - IBlockData iblockdata = world.getType(blockposition); - Material material = iblockdata.getMaterial(); - Fluid fluid = world.getFluid(blockposition); - - if ((fluid.getType() == FluidTypes.WATER || material == Material.ICE) && 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); - world.setTypeAndData(blockposition1, Blocks.LILY_PAD.getBlockData(), 11); - org.bukkit.event.block.BlockPlaceEvent placeEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callBlockPlaceEvent(world, entityhuman, enumhand, blockstate, blockposition.getX(), blockposition.getY(), blockposition.getZ()); - if (placeEvent != null && (placeEvent.isCancelled() || !placeEvent.canBuild())) { - blockstate.update(true, false); - return new InteractionResultWrapper(EnumInteractionResult.PASS, itemstack); - } - // CraftBukkit end - if (entityhuman instanceof EntityPlayer) { - CriterionTriggers.y.a((EntityPlayer) entityhuman, blockposition1, itemstack); - } - - if (!entityhuman.abilities.canInstantlyBuild) { - itemstack.subtract(1); - } - - entityhuman.b(StatisticList.ITEM_USED.b(this)); - world.playSound(entityhuman, blockposition, SoundEffects.BLOCK_LILY_PAD_PLACE, SoundCategory.BLOCKS, 1.0F, 1.0F); - return new InteractionResultWrapper<>(EnumInteractionResult.SUCCESS, itemstack); - } - } - - return new InteractionResultWrapper<>(EnumInteractionResult.FAIL, itemstack); - } - } -} diff --git a/src/main/java/net/minecraft/server/ItemWorldMap.java b/src/main/java/net/minecraft/server/ItemWorldMap.java deleted file mode 100644 index cf9efcf11..000000000 --- a/src/main/java/net/minecraft/server/ItemWorldMap.java +++ /dev/null @@ -1,384 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Iterables; -import com.google.common.collect.LinkedHashMultiset; -import com.google.common.collect.Multiset; -import com.google.common.collect.Multisets; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.event.server.MapInitializeEvent; -// CraftBukkit end - -public class ItemWorldMap extends ItemWorldMapBase { - - public ItemWorldMap(Item.Info item_info) { - super(item_info); - } - - public static ItemStack createFilledMapView(World world, int i, int j, byte b0, boolean flag, boolean flag1) { - ItemStack itemstack = new ItemStack(Items.FILLED_MAP); - - a(itemstack, world, i, j, b0, flag, flag1, world.worldProvider.getDimensionManager()); - return itemstack; - } - - @Nullable - public static WorldMap a(ItemStack itemstack, World world) { - return world.a(a(e(itemstack))); - } - - @Nullable - public static WorldMap getSavedMap(ItemStack itemstack, World world) { - WorldMap worldmap = a(itemstack, world); - - if (worldmap == null && !world.isClientSide) { - worldmap = a(itemstack, world, world.getWorldData().b(), world.getWorldData().d(), 3, false, false, world.worldProvider.getDimensionManager()); - } - - return worldmap; - } - - public static int e(ItemStack itemstack) { - NBTTagCompound nbttagcompound = itemstack.getTag(); - - return nbttagcompound != null && nbttagcompound.hasKeyOfType("map", 99) ? nbttagcompound.getInt("map") : -1; // CraftBukkit - make new maps for no tag - } - - private static WorldMap a(ItemStack itemstack, World world, int i, int j, int k, boolean flag, boolean flag1, DimensionManager dimensionmanager) { - int l = world.getWorldMapCount(); - WorldMap worldmap = new WorldMap(a(l)); - - worldmap.a(i, j, k, flag, flag1, dimensionmanager); - world.a(worldmap); - itemstack.getOrCreateTag().setInt("map", l); - - // CraftBukkit start - MapInitializeEvent event = new MapInitializeEvent(worldmap.mapView); - Bukkit.getServer().getPluginManager().callEvent(event); - // CraftBukkit end - return worldmap; - } - - public static String a(int i) { - return "map_" + i; - } - - public void a(World world, Entity entity, WorldMap worldmap) { - if (world.worldProvider.getDimensionManager() == 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.h()) { - 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; - Multiset multiset = LinkedHashMultiset.create(); - Chunk chunk = world.getChunkAtWorldCoords(new BlockPosition(k2, 0, l2)); - - if (!chunk.isEmpty()) { - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - int i3 = k2 & 15; - int j3 = l2 & 15; - int k3 = 0; - double d1 = 0.0D; - - if (world.worldProvider.h()) { - int l3 = k2 + l2 * 231871; - - l3 = l3 * l3 * 31287121 + l3 * 11; - if ((l3 >> 20 & 1) == 0) { - multiset.add(Blocks.DIRT.getBlockData().c((IBlockAccess) world, BlockPosition.ZERO), 10); - } else { - multiset.add(Blocks.STONE.getBlockData().c((IBlockAccess) world, BlockPosition.ZERO), 100); - } - - d1 = 100.0D; - } else { - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition1 = new BlockPosition.MutableBlockPosition(); - - for (int i4 = 0; i4 < i; ++i4) { - for (int j4 = 0; j4 < i; ++j4) { - int k4 = chunk.a(HeightMap.Type.WORLD_SURFACE, i4 + i3, j4 + j3) + 1; - IBlockData iblockdata; - - if (k4 > 1) { - do { - --k4; - blockposition_mutableblockposition.d(chunkcoordintpair.d() + i4 + i3, k4, chunkcoordintpair.e() + j4 + j3); - iblockdata = chunk.getType(blockposition_mutableblockposition); - } while (iblockdata.c((IBlockAccess) world, (BlockPosition) blockposition_mutableblockposition) == MaterialMapColor.b && k4 > 0); - - if (k4 > 0 && !iblockdata.p().isEmpty()) { - int l4 = k4 - 1; - - blockposition_mutableblockposition1.g(blockposition_mutableblockposition); - - IBlockData iblockdata1; - - do { - blockposition_mutableblockposition1.p(l4--); - iblockdata1 = chunk.getType(blockposition_mutableblockposition1); - ++k3; - } while (l4 > 0 && !iblockdata1.p().isEmpty()); - - iblockdata = this.a(world, iblockdata, (BlockPosition) blockposition_mutableblockposition); - } - } else { - iblockdata = Blocks.BEDROCK.getBlockData(); - } - - worldmap.a(world, chunkcoordintpair.d() + i4 + i3, chunkcoordintpair.e() + j4 + j3); - d1 += (double) k4 / (double) (i * i); - multiset.add(iblockdata.c((IBlockAccess) world, (BlockPosition) blockposition_mutableblockposition)); - } - } - } - - 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 = (MaterialMapColor) Iterables.getFirst(Multisets.copyHighestCountFirst(multiset), 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.ac * 4 + b0); - - if (b1 != b2) { - worldmap.colors[k1 + l1 * 128] = b2; - worldmap.flagDirty(k1, l1); - flag = true; - } - } - } - } - } - } - } - - } - } - - private IBlockData a(World world, IBlockData iblockdata, BlockPosition blockposition) { - Fluid fluid = iblockdata.p(); - - return !fluid.isEmpty() && !iblockdata.d(world, blockposition, EnumDirection.UP) ? fluid.getBlockData() : iblockdata; - } - - private static boolean a(BiomeBase[] abiomebase, int i, int j, int k) { - return abiomebase[j * i + k * i * 128 * i].g() >= 0.0F; - } - - public static void applySepiaFilter(World world, ItemStack itemstack) { - WorldMap worldmap = getSavedMap(itemstack, world); - - if (worldmap != null) { - if (world.worldProvider.getDimensionManager() == worldmap.map) { - int i = 1 << worldmap.scale; - int j = worldmap.centerX; - int k = worldmap.centerZ; - BiomeBase[] abiomebase = world.getChunkProvider().getChunkGenerator().getWorldChunkManager().a((j / i - 64) * i, (k / i - 64) * i, 128 * i, 128 * i, false); - - for (int l = 0; l < 128; ++l) { - for (int i1 = 0; i1 < 128; ++i1) { - if (l > 0 && i1 > 0 && l < 127 && i1 < 127) { - BiomeBase biomebase = abiomebase[l * i + i1 * i * 128 * i]; - int j1 = 8; - - if (a(abiomebase, i, l - 1, i1 - 1)) { - --j1; - } - - if (a(abiomebase, i, l - 1, i1 + 1)) { - --j1; - } - - if (a(abiomebase, i, l - 1, i1)) { - --j1; - } - - if (a(abiomebase, i, l + 1, i1 - 1)) { - --j1; - } - - if (a(abiomebase, i, l + 1, i1 + 1)) { - --j1; - } - - if (a(abiomebase, i, l + 1, i1)) { - --j1; - } - - if (a(abiomebase, i, l, i1 - 1)) { - --j1; - } - - if (a(abiomebase, i, l, i1 + 1)) { - --j1; - } - - int k1 = 3; - MaterialMapColor materialmapcolor = MaterialMapColor.b; - - if (biomebase.g() < 0.0F) { - materialmapcolor = MaterialMapColor.q; - if (j1 > 7 && i1 % 2 == 0) { - k1 = (l + (int) (MathHelper.sin((float) i1 + 0.0F) * 7.0F)) / 8 % 5; - if (k1 == 3) { - k1 = 1; - } else if (k1 == 4) { - k1 = 0; - } - } else if (j1 > 7) { - materialmapcolor = MaterialMapColor.b; - } else if (j1 > 5) { - k1 = 1; - } else if (j1 > 3) { - k1 = 0; - } else if (j1 > 1) { - k1 = 0; - } - } else if (j1 > 0) { - materialmapcolor = MaterialMapColor.B; - if (j1 > 3) { - k1 = 1; - } else { - k1 = 3; - } - } - - if (materialmapcolor != MaterialMapColor.b) { - worldmap.colors[l + i1 * 128] = (byte) (materialmapcolor.ac * 4 + k1); - worldmap.flagDirty(l, i1); - } - } - } - } - - } - } - } - - @Override - public void a(ItemStack itemstack, World world, Entity entity, int i, boolean flag) { - if (!world.isClientSide) { - WorldMap worldmap = getSavedMap(itemstack, world); - - if (worldmap != null) { - if (entity instanceof EntityHuman) { - EntityHuman entityhuman = (EntityHuman) entity; - - worldmap.a(entityhuman, itemstack); - } - - if (!worldmap.locked && (flag || entity instanceof EntityHuman && ((EntityHuman) entity).getItemInOffHand() == itemstack)) { - this.a(world, entity, worldmap); - } - - } - } - } - - @Nullable - @Override - public Packet a(ItemStack itemstack, World world, EntityHuman entityhuman) { - return getSavedMap(itemstack, world).a(itemstack, world, entityhuman); - } - - @Override - public void b(ItemStack itemstack, World world, EntityHuman entityhuman) { - NBTTagCompound nbttagcompound = itemstack.getTag(); - - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("map_scale_direction", 99)) { - a(itemstack, world, nbttagcompound.getInt("map_scale_direction")); - nbttagcompound.remove("map_scale_direction"); - } - - } - - protected static void a(ItemStack itemstack, World world, int i) { - WorldMap worldmap = getSavedMap(itemstack, world); - - if (worldmap != null) { - a(itemstack, world, worldmap.centerX, worldmap.centerZ, MathHelper.clamp(worldmap.scale + i, 0, 4), worldmap.track, worldmap.unlimitedTracking, worldmap.map); - } - - } - - @Nullable - public static ItemStack b(World world, ItemStack itemstack) { - WorldMap worldmap = getSavedMap(itemstack, world); - - if (worldmap != null) { - ItemStack itemstack1 = itemstack.cloneItemStack(); - WorldMap worldmap1 = a(itemstack1, world, 0, 0, worldmap.scale, worldmap.track, worldmap.unlimitedTracking, worldmap.map); - - worldmap1.a(worldmap); - return itemstack1; - } else { - return null; - } - } - - @Override - public EnumInteractionResult a(ItemActionContext itemactioncontext) { - IBlockData iblockdata = itemactioncontext.getWorld().getType(itemactioncontext.getClickPosition()); - - if (iblockdata.a(TagsBlock.BANNERS)) { - if (!itemactioncontext.e.isClientSide) { - WorldMap worldmap = getSavedMap(itemactioncontext.getItemStack(), itemactioncontext.getWorld()); - - worldmap.a((GeneratorAccess) itemactioncontext.getWorld(), itemactioncontext.getClickPosition()); - } - - return EnumInteractionResult.SUCCESS; - } else { - return super.a(itemactioncontext); - } - } -} diff --git a/src/main/java/net/minecraft/server/JsonList.java b/src/main/java/net/minecraft/server/JsonList.java deleted file mode 100644 index c97be42dd..000000000 --- a/src/main/java/net/minecraft/server/JsonList.java +++ /dev/null @@ -1,241 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.io.Files; -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.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import javax.annotation.Nullable; -import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class JsonList> { - - protected static final Logger LOGGER = LogManager.getLogger(); - protected final Gson b; - private final File c; - // Paper - replace HashMap is ConcurrentHashMap - private final Map d = Maps.newConcurrentMap(); private final Map getBackingMap() { return this.d; } // Paper - OBFHELPER - 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()); - this.b = gsonbuilder.create(); - } - - public boolean isEnabled() { - return this.e; - } - - public void setEnabled(boolean flag) { this.a(flag); } // Paper - OBFHeLPER - 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.LOGGER.warn("Could not save the list after adding a user.", ioexception); - } - - } - - @Nullable - public V get(K k0) { - // Paper start - // this.h(); - // return (V) this.d.get(this.a(k0)); // CraftBukkit - fix decompile error - return (V) this.getBackingMap().computeIfPresent(this.getMappingKey(k0), (k, v) -> { - return v.hasExpired() ? null : v; - }); - // Paper end - } - - public void remove(K k0) { - this.d.remove(this.a(k0)); - - try { - this.save(); - } catch (IOException ioexception) { - JsonList.LOGGER.warn("Could not save the list after removing a user.", ioexception); - } - - } - - public void b(JsonListEntry jsonlistentry) { - this.remove(jsonlistentry.getKey()); - } - - public String[] getEntries() { - return (String[]) this.d.keySet().toArray(new String[this.d.size()]); - } - - // CraftBukkit start - public Collection getValues() { - return this.d.values(); - } - // CraftBukkit end - - public boolean isEmpty() { - // return this.d.size() < 1; // Paper - return this.getBackingMap().isEmpty(); // Paper - readability is the goal. As an aside, isEmpty() uses only sumCount() and a comparison. size() uses sumCount(), casts, and boolean logic - } - - protected final String getMappingKey(K k0) { return a(k0); } // Paper - OBFHELPER - protected String a(K k0) { - return k0.toString(); - } - - protected boolean d(K k0) { - return this.d.containsKey(this.a(k0)); - } - - private void removeStaleEntries() { h(); } // Paper - OBFHELPER - private void h() { - /*List list = Lists.newArrayList(); - Iterator iterator = this.d.values().iterator(); - - while (iterator.hasNext()) { - V v0 = (V) iterator.next(); // CraftBukkit - decompile error - - if (v0.hasExpired()) { - list.add(v0.getKey()); - } - } - - iterator = list.iterator(); - - while (iterator.hasNext()) { - K k0 = (K) iterator.next(); // CraftBukkit - decompile error - - this.d.remove(this.a(k0)); - }*/ - - this.getBackingMap().values().removeIf(JsonListEntry::hasExpired); - // Paper end - } - - protected JsonListEntry a(JsonObject jsonobject) { - return new JsonListEntry<>((K) null, jsonobject); // CraftBukkit - decompile error - } - - public Collection e() { - return this.d.values(); - } - - public void save() throws IOException { - this.removeStaleEntries(); // Paper - remove expired values before saving - Collection collection = this.d.values(); - String s = this.b.toJson(collection); - BufferedWriter bufferedwriter = null; - - try { - bufferedwriter = Files.newWriter(this.c, StandardCharsets.UTF_8); - bufferedwriter.write(s); - } finally { - IOUtils.closeQuietly(bufferedwriter); - } - - } - - public void load() throws FileNotFoundException { - if (this.c.exists()) { - BufferedReader bufferedreader = null; - - try { - bufferedreader = Files.newReader(this.c, StandardCharsets.UTF_8); - Collection> collection = (Collection) ChatDeserializer.a(this.b, (Reader) bufferedreader, (Type) JsonList.f); - - if (collection != null) { - this.d.clear(); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - JsonListEntry jsonlistentry = (JsonListEntry) iterator.next(); - - if (jsonlistentry.getKey() != null) { - this.d.put(this.a((K) jsonlistentry.getKey()), (V) jsonlistentry); // CraftBukkit - fix decompile error - } - } - } - // Spigot Start - } catch ( com.google.gson.JsonParseException ex ) - { - org.bukkit.Bukkit.getLogger().log( java.util.logging.Level.WARNING, "Unable to read file " + this.c + ", backing it up to {0}.backup and creating new copy.", ex ); - File backup = new File( this.c + ".backup" ); - this.c.renameTo( backup ); - this.c.delete(); - // Spigot End - } finally { - IOUtils.closeQuietly(bufferedreader); - } - - } - } - - class JsonListEntrySerializer implements JsonDeserializer>, JsonSerializer> { - - private JsonListEntrySerializer() {} - - public JsonElement serialize(JsonListEntry jsonlistentry, Type type, JsonSerializationContext jsonserializationcontext) { - JsonObject jsonobject = new JsonObject(); - - jsonlistentry.a(jsonobject); - return jsonobject; - } - - public JsonListEntry deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { - if (jsonelement.isJsonObject()) { - JsonObject jsonobject = jsonelement.getAsJsonObject(); - - return JsonList.this.a(jsonobject); - } else { - return null; - } - } - } -} diff --git a/src/main/java/net/minecraft/server/KeyedObject.java b/src/main/java/net/minecraft/server/KeyedObject.java deleted file mode 100644 index 743142d03..000000000 --- a/src/main/java/net/minecraft/server/KeyedObject.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.minecraft.server; - -public interface KeyedObject { - MinecraftKey getMinecraftKey(); - default String getMinecraftKeyString() { - MinecraftKey key = getMinecraftKey(); - return key != null ? key.toString() : null; - } -} diff --git a/src/main/java/net/minecraft/server/LegacyPingHandler.java b/src/main/java/net/minecraft/server/LegacyPingHandler.java deleted file mode 100644 index 4a49fe4cc..000000000 --- a/src/main/java/net/minecraft/server/LegacyPingHandler.java +++ /dev/null @@ -1,241 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.network.PaperLegacyStatusClient; - -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 java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class LegacyPingHandler extends ChannelInboundHandlerAdapter { - - private static final Logger LOGGER = LogManager.getLogger(); - private final ServerConnection b; - private ByteBuf buf; // Paper - - public LegacyPingHandler(ServerConnection serverconnection) { - this.b = serverconnection; - } - - public void channelRead(ChannelHandlerContext channelhandlercontext, Object object) throws Exception { - ByteBuf bytebuf = (ByteBuf) object; - - // Paper start - Make legacy ping handler more reliable - if (this.buf != null) { - try { - readLegacy1_6(channelhandlercontext, bytebuf); - } finally { - bytebuf.release(); - } - return; - } - // Paper end - bytebuf.markReaderIndex(); - boolean flag = true; - - try { - if (bytebuf.readUnsignedByte() != 254) { - return; - } - - InetSocketAddress inetsocketaddress = (InetSocketAddress) channelhandlercontext.channel().remoteAddress(); - MinecraftServer minecraftserver = this.b.d(); - int i = bytebuf.readableBytes(); - String s; - //org.bukkit.event.server.ServerListPingEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callServerListPingEvent(minecraftserver.server, inetsocketaddress.getAddress(), minecraftserver.getMotd(), minecraftserver.getPlayerCount(), minecraftserver.getMaxPlayers()); // CraftBukkit // Paper - com.destroystokyo.paper.event.server.PaperServerListPingEvent event; // Paper - - switch (i) { - case 0: - LegacyPingHandler.LOGGER.debug("Ping: (<1.3.x) from {}:{}", inetsocketaddress.getAddress(), inetsocketaddress.getPort()); - // Paper start - Call PaperServerListPingEvent and use results - event = PaperLegacyStatusClient.processRequest(minecraftserver, inetsocketaddress, 39, null); - if (event == null) { - channelhandlercontext.close(); - break; - } - s = String.format("%s\u00a7%d\u00a7%d", PaperLegacyStatusClient.getUnformattedMotd(event), event.getNumPlayers(), event.getMaxPlayers()); - this.a(channelhandlercontext, this.a(s)); - break; - case 1: - if (bytebuf.readUnsignedByte() != 1) { - return; - } - - LegacyPingHandler.LOGGER.debug("Ping: (1.4-1.5.x) from {}:{}", inetsocketaddress.getAddress(), inetsocketaddress.getPort()); - // Paper start - Call PaperServerListPingEvent and use results - event = PaperLegacyStatusClient.processRequest(minecraftserver, inetsocketaddress, 127, null); // Paper - if (event == null) { - channelhandlercontext.close(); - break; - } - s = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", new Object[] { event.getProtocolVersion(), minecraftserver.getVersion(), event.getMotd(), event.getNumPlayers(), event.getMaxPlayers()}); // CraftBukkit - // Paper end - this.a(channelhandlercontext, this.a(s)); - break; - default: - // Paper start - Replace with improved version below - if (bytebuf.readUnsignedByte() != 0x01 || bytebuf.readUnsignedByte() != 0xFA) return; - readLegacy1_6(channelhandlercontext, bytebuf); - /* - boolean flag1 = bytebuf.readUnsignedByte() == 1; - - flag1 &= bytebuf.readUnsignedByte() == 250; - flag1 &= "MC|PingHost".equals(new String(bytebuf.readBytes(bytebuf.readShort() * 2).array(), StandardCharsets.UTF_16BE)); - int j = bytebuf.readUnsignedShort(); - - flag1 &= bytebuf.readUnsignedByte() >= 73; - flag1 &= 3 + bytebuf.readBytes(bytebuf.readShort() * 2).array().length + 4 == j; - flag1 &= bytebuf.readInt() <= 65535; - flag1 &= bytebuf.readableBytes() == 0; - if (!flag1) { - return; - } - - LegacyPingHandler.LOGGER.debug("Ping: (1.6) from {}:{}", inetsocketaddress.getAddress(), inetsocketaddress.getPort()); - String s1 = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", 127, minecraftserver.getVersion(), event.getMotd(), event.getNumPlayers(), event.getMaxPlayers()); // CraftBukkit - ByteBuf bytebuf1 = this.a(s1); - - try { - this.a(channelhandlercontext, bytebuf1); - } finally { - bytebuf1.release(); - } - */ // Paper end - Replace with improved version below - } - - bytebuf.release(); - flag = false; - } catch (RuntimeException runtimeexception) { - ; - } finally { - if (flag) { - bytebuf.resetReaderIndex(); - channelhandlercontext.channel().pipeline().remove("legacy_query"); - channelhandlercontext.fireChannelRead(object); - } - - } - - } - - // Paper start - private static String readLegacyString(ByteBuf buf) { - int size = buf.readShort() * Character.BYTES; - if (!buf.isReadable(size)) { - return null; - } - - String result = buf.toString(buf.readerIndex(), size, StandardCharsets.UTF_16BE); - buf.skipBytes(size); // toString doesn't increase readerIndex automatically - return result; - } - - private void readLegacy1_6(ChannelHandlerContext ctx, ByteBuf part) { - ByteBuf buf = this.buf; - - if (buf == null) { - this.buf = buf = ctx.alloc().buffer(); - buf.markReaderIndex(); - } else { - buf.resetReaderIndex(); - } - - buf.writeBytes(part); - - if (!buf.isReadable(Short.BYTES + Short.BYTES + Byte.BYTES + Short.BYTES + Integer.BYTES)) { - return; - } - - String s = readLegacyString(buf); - if (s == null) { - return; - } - - if (!s.equals("MC|PingHost")) { - removeHandler(ctx); - return; - } - - if (!buf.isReadable(Short.BYTES) || !buf.isReadable(buf.readShort())) { - return; - } - - MinecraftServer server = this.b.d(); - int protocolVersion = buf.readByte(); - String host = readLegacyString(buf); - if (host == null) { - removeHandler(ctx); - return; - } - int port = buf.readInt(); - - if (buf.isReadable()) { - removeHandler(ctx); - return; - } - - buf.release(); - this.buf = null; - - LOGGER.debug("Ping: (1.6) from {}", ctx.channel().remoteAddress()); - - InetSocketAddress virtualHost = com.destroystokyo.paper.network.PaperNetworkClient.prepareVirtualHost(host, port); - com.destroystokyo.paper.event.server.PaperServerListPingEvent event = PaperLegacyStatusClient.processRequest( - server, (InetSocketAddress) ctx.channel().remoteAddress(), protocolVersion, virtualHost); - if (event == null) { - ctx.close(); - return; - } - - String response = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", event.getProtocolVersion(), event.getVersion(), - PaperLegacyStatusClient.getMotd(event), event.getNumPlayers(), event.getMaxPlayers()); - this.a(ctx, this.a(response)); - } - - private void removeHandler(ChannelHandlerContext ctx) { - ByteBuf buf = this.buf; - this.buf = null; - - buf.resetReaderIndex(); - ctx.pipeline().remove(this); - ctx.fireChannelRead(buf); - } - - @Override - public void handlerRemoved(ChannelHandlerContext ctx) { - if (this.buf != null) { - this.buf.release(); - this.buf = null; - } - } - // Paper end - - private void a(ChannelHandlerContext channelhandlercontext, ByteBuf bytebuf) { - channelhandlercontext.pipeline().firstContext().writeAndFlush(bytebuf).addListener(ChannelFutureListener.CLOSE); - } - - private ByteBuf a(String s) { - ByteBuf bytebuf = Unpooled.buffer(); - - bytebuf.writeByte(255); - char[] achar = s.toCharArray(); - - bytebuf.writeShort(achar.length); - char[] achar1 = achar; - int i = achar.length; - - for (int j = 0; j < i; ++j) { - char c0 = achar1[j]; - - bytebuf.writeChar(c0); - } - - return bytebuf; - } -} diff --git a/src/main/java/net/minecraft/server/LocaleLanguage.java b/src/main/java/net/minecraft/server/LocaleLanguage.java deleted file mode 100644 index 601273933..000000000 --- a/src/main/java/net/minecraft/server/LocaleLanguage.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Pattern; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class LocaleLanguage { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final Pattern b = Pattern.compile("%(\\d+\\$)?[\\d\\.]*[df]"); - private static final 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.json"); - Throwable throwable = null; - - try { - JsonElement jsonelement = (JsonElement) (new Gson()).fromJson(new InputStreamReader(inputstream, StandardCharsets.UTF_8), JsonElement.class); - JsonObject jsonobject = ChatDeserializer.m(jsonelement, "strings"); - Iterator iterator = jsonobject.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - String s = LocaleLanguage.b.matcher(ChatDeserializer.a((JsonElement) entry.getValue(), (String) entry.getKey())).replaceAll("%$1s"); - - this.d.put(entry.getKey(), s); - } - - this.e = SystemUtils.getMonotonicMillis(); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (inputstream != null) { - if (throwable != null) { - try { - inputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - inputstream.close(); - } - } - - } - } catch (JsonParseException | IOException ioexception) { - LocaleLanguage.LOGGER.error("Couldn't read strings from /assets/minecraft/lang/en_us.json", ioexception); - } - - } - - public static LocaleLanguage getInstance() { return a(); } // Paper - OBFHELPER - public static LocaleLanguage a() { - return LocaleLanguage.c; - } - - public synchronized String translateKey(String key) { return a(key); } // Paper - OBFHELPER - public synchronized String a(String s) { - return this.c(s); - } - - 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 b() { - return this.e; - } -} diff --git a/src/main/java/net/minecraft/server/LoginListener.java b/src/main/java/net/minecraft/server/LoginListener.java deleted file mode 100644 index a8773037e..000000000 --- a/src/main/java/net/minecraft/server/LoginListener.java +++ /dev/null @@ -1,394 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.profile.CraftPlayerProfile; -import com.destroystokyo.paper.profile.PlayerProfile; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.exceptions.AuthenticationUnavailableException; -import io.netty.channel.ChannelFuture; -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.security.PrivateKey; -import java.util.Arrays; -import java.util.Random; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import javax.annotation.Nullable; -import javax.crypto.SecretKey; -import org.apache.commons.lang3.Validate; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.util.Waitable; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import org.bukkit.event.player.PlayerPreLoginEvent; -// CraftBukkit end - -public class LoginListener implements PacketLoginInListener { - - private static final AtomicInteger b = new AtomicInteger(0); - private static final Logger LOGGER = LogManager.getLogger(); - private static final Random random = new Random(); - private final byte[] e = new byte[4]; - private final MinecraftServer server; - public final NetworkManager networkManager; - private LoginListener.EnumProtocolState g; public final LoginListener.EnumProtocolState getLoginState() { return this.g; }; // Paper - OBFHELPER - private int h; - private GameProfile i; private void setGameProfile(final GameProfile profile) { this.i = profile; } public GameProfile getGameProfile() { return this.i; } // Paper - OBFHELPER - private final String j; - private SecretKey loginKey; - private EntityPlayer l; - public String hostname = ""; // CraftBukkit - add field - private int velocityLoginMessageId = -1; // Paper - Velocity support - - public LoginListener(MinecraftServer minecraftserver, NetworkManager networkmanager) { - this.g = LoginListener.EnumProtocolState.HELLO; - this.j = ""; - this.server = minecraftserver; - this.networkManager = networkmanager; - LoginListener.random.nextBytes(this.e); - } - - public void tick() { - // Paper start - Do not allow logins while the server is shutting down - if (!MinecraftServer.getServer().isRunning()) { - this.disconnect(new ChatMessage(org.spigotmc.SpigotConfig.restartMessage)); - return; - } - // Paper end - if (this.g == LoginListener.EnumProtocolState.READY_TO_ACCEPT) { - // Paper start - prevent logins to be processed even though disconnect was called - if (networkManager.isConnected()) { - this.c(); - } - // Paper end - } else if (this.g == LoginListener.EnumProtocolState.DELAY_ACCEPT) { - EntityPlayer entityplayer = this.server.getPlayerList().a(this.i.getId()); - - if (entityplayer == null) { - this.g = LoginListener.EnumProtocolState.READY_TO_ACCEPT; - this.server.getPlayerList().a(this.networkManager, this.l); - this.l = null; - } - } - - if (this.h++ == 600) { - this.disconnect(new ChatMessage("multiplayer.disconnect.slow_login", new Object[0])); - } - - } - - // CraftBukkit start - @Deprecated - public void disconnect(String s) { - try { - IChatBaseComponent ichatbasecomponent = new ChatComponentText(s); - LoginListener.LOGGER.info("Disconnecting {}: {}", this.d(), s); - this.networkManager.sendPacket(new PacketLoginOutDisconnect(ichatbasecomponent)); - this.networkManager.close(ichatbasecomponent); - } catch (Exception exception) { - LoginListener.LOGGER.error("Error whilst disconnecting player", exception); - } - } - // CraftBukkit end - - @Override - public NetworkManager a() { - return this.networkManager; - } - - public void disconnect(IChatBaseComponent ichatbasecomponent) { - try { - LoginListener.LOGGER.info("Disconnecting {}: {}", this.d(), ichatbasecomponent.getString()); - this.networkManager.sendPacket(new PacketLoginOutDisconnect(ichatbasecomponent)); - this.networkManager.close(ichatbasecomponent); - } catch (Exception exception) { - LoginListener.LOGGER.error("Error whilst disconnecting player", exception); - } - - } - - // Paper start - Cache authenticator threads - private static final AtomicInteger threadId = new AtomicInteger(0); - private static final java.util.concurrent.ExecutorService authenticatorPool = java.util.concurrent.Executors.newCachedThreadPool( - r -> new Thread(r, "User Authenticator #" + threadId.incrementAndGet()) - ); - // Paper end - // Spigot start - public void initUUID() - { - UUID uuid; - if ( networkManager.spoofedUUID != null ) - { - uuid = networkManager.spoofedUUID; - } else - { - uuid = EntityHuman.getOfflineUUID( this.i.getName() ); - } - - this.i = new GameProfile( uuid, this.i.getName() ); - - if (networkManager.spoofedProfile != null) - { - for ( com.mojang.authlib.properties.Property property : networkManager.spoofedProfile ) - { - this.i.getProperties().put( property.getName(), property ); - } - } - } - // Spigot end - - public void c() { - // Spigot start - Moved to initUUID - /* - if (!this.i.isComplete()) { - this.i = this.a(this.i); - } - */ - // Spigot end - - // CraftBukkit start - fire PlayerLoginEvent - EntityPlayer s = this.server.getPlayerList().attemptLogin(this, this.i, hostname); - - if (s == null) { - // this.disconnect(ichatbasecomponent); - // CraftBukkit end - } else { - this.g = LoginListener.EnumProtocolState.ACCEPTED; - if (this.server.az() >= 0 && !this.networkManager.isLocal()) { - this.networkManager.sendPacket(new PacketLoginOutSetCompression(this.server.az()), (channelfuture) -> { - this.networkManager.setCompressionLevel(this.server.az()); - }); - } - - this.networkManager.sendPacket(new PacketLoginOutSuccess(this.i)); - EntityPlayer entityplayer = this.server.getPlayerList().a(this.i.getId()); - - if (entityplayer != null) { - this.g = LoginListener.EnumProtocolState.DELAY_ACCEPT; - this.l = this.server.getPlayerList().processLogin(this.i, s); // CraftBukkit - add player reference - } else { - this.server.getPlayerList().a(this.networkManager, this.server.getPlayerList().processLogin(this.i, s)); // CraftBukkit - add player reference - } - } - - } - - @Override - public void a(IChatBaseComponent ichatbasecomponent) { - LoginListener.LOGGER.info("{} lost connection: {}", this.d(), ichatbasecomponent.getString()); - } - - public String d() { - return this.i != null ? this.i + " (" + this.networkManager.getSocketAddress() + ")" : String.valueOf(this.networkManager.getSocketAddress()); - } - - @Override - public void a(PacketLoginInStart packetlogininstart) { - Validate.validState(this.g == LoginListener.EnumProtocolState.HELLO, "Unexpected hello packet", new Object[0]); - this.i = packetlogininstart.b(); - if (this.server.getOnlineMode() && !this.networkManager.isLocal()) { - this.g = LoginListener.EnumProtocolState.KEY; - this.networkManager.sendPacket(new PacketLoginOutEncryptionBegin("", this.server.getKeyPair().getPublic(), this.e)); - } else { - // Paper start - Velocity support - if (com.destroystokyo.paper.PaperConfig.velocitySupport) { - this.velocityLoginMessageId = java.util.concurrent.ThreadLocalRandom.current().nextInt(); - PacketLoginOutCustomPayload packet = new PacketLoginOutCustomPayload(this.velocityLoginMessageId, com.destroystokyo.paper.proxy.VelocityProxy.PLAYER_INFO_CHANNEL, new PacketDataSerializer(io.netty.buffer.Unpooled.EMPTY_BUFFER)); - this.networkManager.sendPacket(packet); - return; - } - // Paper end - // Spigot start - // Paper start - Cache authenticator threads - authenticatorPool.execute(new Runnable() { - @Override - public void run() { - try { - initUUID(); - new LoginHandler().fireEvents(); - } catch (Exception ex) { - disconnect("Failed to verify username!"); - server.server.getLogger().log(java.util.logging.Level.WARNING, "Exception verifying " + i.getName(), ex); - } - } - }); - // Paper end - // Spigot end - } - - } - - @Override - public void a(PacketLoginInEncryptionBegin packetlogininencryptionbegin) { - Validate.validState(this.g == LoginListener.EnumProtocolState.KEY, "Unexpected key packet", new Object[0]); - PrivateKey privatekey = this.server.getKeyPair().getPrivate(); - - if (!Arrays.equals(this.e, packetlogininencryptionbegin.b(privatekey))) { - throw new IllegalStateException("Invalid nonce!"); - } else { - this.loginKey = packetlogininencryptionbegin.a(privatekey); - this.g = LoginListener.EnumProtocolState.AUTHENTICATING; - this.networkManager.a(this.loginKey); - // Paper start - Cache authenticator threads - authenticatorPool.execute(new Runnable() { - public void run() { - GameProfile gameprofile = LoginListener.this.i; - - try { - String s = (new BigInteger(MinecraftEncryption.a("", LoginListener.this.server.getKeyPair().getPublic(), LoginListener.this.loginKey))).toString(16); - - LoginListener.this.i = LoginListener.this.server.getMinecraftSessionService().hasJoinedServer(new GameProfile((UUID) null, gameprofile.getName()), s, this.a()); - if (LoginListener.this.i != null) { - // CraftBukkit start - fire PlayerPreLoginEvent - if (!networkManager.isConnected()) { - return; - } - - new LoginHandler().fireEvents(); - } else if (LoginListener.this.server.isEmbeddedServer()) { - LoginListener.LOGGER.warn("Failed to verify username but will let them in anyway!"); - LoginListener.this.i = LoginListener.this.a(gameprofile); - LoginListener.this.g = LoginListener.EnumProtocolState.READY_TO_ACCEPT; - } else { - LoginListener.this.disconnect(new ChatMessage("multiplayer.disconnect.unverified_username", new Object[0])); - LoginListener.LOGGER.error("Username '{}' tried to join with an invalid session", gameprofile.getName()); - } - } catch (AuthenticationUnavailableException authenticationunavailableexception) { - if (LoginListener.this.server.isEmbeddedServer()) { - LoginListener.LOGGER.warn("Authentication servers are down but will let them in anyway!"); - LoginListener.this.i = LoginListener.this.a(gameprofile); - LoginListener.this.g = LoginListener.EnumProtocolState.READY_TO_ACCEPT; - } else { - // Paper start - if (com.destroystokyo.paper.PaperConfig.authenticationServersDownKickMessage != null) { - LoginListener.this.disconnect(new ChatComponentText(com.destroystokyo.paper.PaperConfig.authenticationServersDownKickMessage)); - } else // Paper end - LoginListener.this.disconnect(new ChatMessage("multiplayer.disconnect.authservers_down", new Object[0])); - LoginListener.LOGGER.error("Couldn't verify username because servers are unavailable"); - } - // CraftBukkit start - catch all exceptions - } catch (Exception exception) { - disconnect("Failed to verify username!"); - server.server.getLogger().log(java.util.logging.Level.WARNING, "Exception verifying " + gameprofile.getName(), exception); - // CraftBukkit end - } - - } - - @Nullable - private InetAddress a() { - SocketAddress socketaddress = LoginListener.this.networkManager.getSocketAddress(); - - return LoginListener.this.server.U() && socketaddress instanceof InetSocketAddress ? ((InetSocketAddress) socketaddress).getAddress() : null; - } - }); - // Paper end - } - } - - // Spigot start - public class LoginHandler { - - public void fireEvents() throws Exception { - // Paper start - Velocity support - if (LoginListener.this.velocityLoginMessageId == -1 && com.destroystokyo.paper.PaperConfig.velocitySupport) { - disconnect("This server requires you to connect with Velocity."); - return; - } - // Paper end - String playerName = i.getName(); - java.net.InetAddress address = ((java.net.InetSocketAddress) networkManager.getSocketAddress()).getAddress(); - java.util.UUID uniqueId = i.getId(); - final org.bukkit.craftbukkit.CraftServer server = LoginListener.this.server.server; - - // Paper start - PlayerProfile profile = CraftPlayerProfile.asBukkitMirror(getGameProfile()); - AsyncPlayerPreLoginEvent asyncEvent = new AsyncPlayerPreLoginEvent(playerName, address, uniqueId, profile); - server.getPluginManager().callEvent(asyncEvent); - profile = asyncEvent.getPlayerProfile(); - profile.complete(true); - setGameProfile(CraftPlayerProfile.asAuthlib(profile)); - playerName = i.getName(); - uniqueId = i.getId(); - // Paper end - - if (PlayerPreLoginEvent.getHandlerList().getRegisteredListeners().length != 0) { - final PlayerPreLoginEvent event = new PlayerPreLoginEvent(playerName, address, uniqueId); - if (asyncEvent.getResult() != PlayerPreLoginEvent.Result.ALLOWED) { - event.disallow(asyncEvent.getResult(), asyncEvent.getKickMessage()); - } - Waitable waitable = new Waitable() { - @Override - protected PlayerPreLoginEvent.Result evaluate() { - server.getPluginManager().callEvent(event); - return event.getResult(); - }}; - - LoginListener.this.server.processQueue.add(waitable); - if (waitable.get() != PlayerPreLoginEvent.Result.ALLOWED) { - disconnect(event.getKickMessage()); - return; - } - } else { - if (asyncEvent.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) { - disconnect(asyncEvent.getKickMessage()); - return; - } - } - // CraftBukkit end - LoginListener.LOGGER.info("UUID of player {} is {}", LoginListener.this.i.getName(), LoginListener.this.i.getId()); - LoginListener.this.g = LoginListener.EnumProtocolState.READY_TO_ACCEPT; - } - } - // Spigot end - - public void a(PacketLoginInCustomPayload packetloginincustompayload) { - // Paper start - Velocity support - if (com.destroystokyo.paper.PaperConfig.velocitySupport && packetloginincustompayload.getId() == this.velocityLoginMessageId) { - PacketDataSerializer buf = packetloginincustompayload.getBuf(); - if (buf == null) { - this.disconnect("This server requires you to connect with Velocity."); - return; - } - - if (!com.destroystokyo.paper.proxy.VelocityProxy.checkIntegrity(buf)) { - this.disconnect("Unable to verify player details"); - return; - } - - this.networkManager.setSpoofedRemoteAddress(new java.net.InetSocketAddress(com.destroystokyo.paper.proxy.VelocityProxy.readAddress(buf), ((java.net.InetSocketAddress) this.networkManager.getSocketAddress()).getPort())); - - this.setGameProfile(com.destroystokyo.paper.proxy.VelocityProxy.createProfile(buf)); - - // Proceed with login - authenticatorPool.execute(() -> { - try { - new LoginHandler().fireEvents(); - } catch (Exception ex) { - disconnect("Failed to verify username!"); - server.server.getLogger().log(java.util.logging.Level.WARNING, "Exception verifying " + i.getName(), ex); - } - }); - return; - } - // Paper end - this.disconnect(new ChatMessage("multiplayer.disconnect.unexpected_query_response", new Object[0])); - } - - protected GameProfile a(GameProfile gameprofile) { - UUID uuid = EntityHuman.getOfflineUUID(gameprofile.getName()); - - return new GameProfile(uuid, gameprofile.getName()); - } - - static enum EnumProtocolState { - - HELLO, KEY, AUTHENTICATING, NEGOTIATING, READY_TO_ACCEPT, DELAY_ACCEPT, ACCEPTED; - - private EnumProtocolState() {} - } -} diff --git a/src/main/java/net/minecraft/server/LootContextParameters.java b/src/main/java/net/minecraft/server/LootContextParameters.java deleted file mode 100644 index 1dcbe2b9d..000000000 --- a/src/main/java/net/minecraft/server/LootContextParameters.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.minecraft.server; - -public class LootContextParameters { - - public static final LootContextParameter THIS_ENTITY = a("this_entity"); - public static final LootContextParameter LAST_DAMAGE_PLAYER = a("last_damage_player"); - public static final LootContextParameter DAMAGE_SOURCE = a("damage_source"); - public static final LootContextParameter KILLER_ENTITY = a("killer_entity"); - public static final LootContextParameter DIRECT_KILLER_ENTITY = a("direct_killer_entity"); - public static final LootContextParameter POSITION = a("position"); - public static final LootContextParameter BLOCK_STATE = a("block_state"); - public static final LootContextParameter BLOCK_ENTITY = a("block_entity"); - public static final LootContextParameter TOOL = a("tool"); - public static final LootContextParameter EXPLOSION_RADIUS = a("explosion_radius"); - public static final LootContextParameter LOOTING_MOD = new LootContextParameter<>(new MinecraftKey("bukkit:looting_mod")); // CraftBukkit - - private static LootContextParameter a(String s) { - return new LootContextParameter<>(new MinecraftKey(s)); - } -} diff --git a/src/main/java/net/minecraft/server/LootEnchantFunction.java b/src/main/java/net/minecraft/server/LootEnchantFunction.java deleted file mode 100644 index 542538c4f..000000000 --- a/src/main/java/net/minecraft/server/LootEnchantFunction.java +++ /dev/null @@ -1,107 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import java.util.Set; - -public class LootEnchantFunction extends LootItemFunctionConditional { - - private final LootValueBounds a; - private final int c; - - private LootEnchantFunction(LootItemCondition[] alootitemcondition, LootValueBounds lootvaluebounds, int i) { - super(alootitemcondition); - this.a = lootvaluebounds; - this.c = i; - } - - @Override - public Set> a() { - return ImmutableSet.of(LootContextParameters.KILLER_ENTITY); - } - - private boolean b() { - return this.c > 0; - } - - @Override - public ItemStack a(ItemStack itemstack, LootTableInfo loottableinfo) { - Entity entity = (Entity) loottableinfo.getContextParameter(LootContextParameters.KILLER_ENTITY); - - if (entity instanceof EntityLiving) { - int i = EnchantmentManager.g((EntityLiving) entity); - // CraftBukkit start - use lootingModifier if set by plugin - if (loottableinfo.hasContextParameter(LootContextParameters.LOOTING_MOD)) { - i = loottableinfo.getContextParameter(LootContextParameters.LOOTING_MOD); - } - // CraftBukkit end - - if (i <= 0) { // CraftBukkit - account for possible negative looting values from Bukkit - return itemstack; - } - - float f = (float) i * this.a.b(loottableinfo.b()); - - itemstack.add(Math.round(f)); - if (this.b() && itemstack.getCount() > this.c) { - itemstack.setCount(this.c); - } - } - - return itemstack; - } - - public static LootEnchantFunction.a a(LootValueBounds lootvaluebounds) { - return new LootEnchantFunction.a(lootvaluebounds); - } - - public static class b extends LootItemFunctionConditional.c { - - protected b() { - super(new MinecraftKey("looting_enchant"), LootEnchantFunction.class); - } - - public void a(JsonObject jsonobject, LootEnchantFunction lootenchantfunction, JsonSerializationContext jsonserializationcontext) { - super.a(jsonobject, lootenchantfunction, jsonserializationcontext); // CraftBukkit - decompile error - jsonobject.add("count", jsonserializationcontext.serialize(lootenchantfunction.a)); - if (lootenchantfunction.b()) { - jsonobject.add("limit", jsonserializationcontext.serialize(lootenchantfunction.c)); - } - - } - - @Override - public LootEnchantFunction b(JsonObject jsonobject, JsonDeserializationContext jsondeserializationcontext, LootItemCondition[] alootitemcondition) { - int i = ChatDeserializer.a(jsonobject, "limit", (int) 0); - - return new LootEnchantFunction(alootitemcondition, (LootValueBounds) ChatDeserializer.a(jsonobject, "count", jsondeserializationcontext, LootValueBounds.class), i); - } - } - - public static class a extends LootItemFunctionConditional.a { - - private final LootValueBounds a; - private int b = 0; - - public a(LootValueBounds lootvaluebounds) { - this.a = lootvaluebounds; - } - - @Override - protected LootEnchantFunction.a d() { - return this; - } - - public LootEnchantFunction.a a(int i) { - this.b = i; - return this; - } - - @Override - public LootItemFunction b() { - return new LootEnchantFunction(this.g(), this.a, this.b); - } - } -} diff --git a/src/main/java/net/minecraft/server/LootItemConditionRandomChanceWithLooting.java b/src/main/java/net/minecraft/server/LootItemConditionRandomChanceWithLooting.java deleted file mode 100644 index 1f801ae58..000000000 --- a/src/main/java/net/minecraft/server/LootItemConditionRandomChanceWithLooting.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import java.util.Set; - -public class LootItemConditionRandomChanceWithLooting implements LootItemCondition { - - private final float a; - private final float b; - - private LootItemConditionRandomChanceWithLooting(float f, float f1) { - this.a = f; - this.b = f1; - } - - @Override - public Set> a() { - return ImmutableSet.of(LootContextParameters.KILLER_ENTITY); - } - - public boolean test(LootTableInfo loottableinfo) { - Entity entity = (Entity) loottableinfo.getContextParameter(LootContextParameters.KILLER_ENTITY); - int i = 0; - - if (entity instanceof EntityLiving) { - i = EnchantmentManager.g((EntityLiving) entity); - } - // CraftBukkit start - only use lootingModifier if set by Bukkit - if (loottableinfo.hasContextParameter(LootContextParameters.LOOTING_MOD)) { - i = loottableinfo.getContextParameter(LootContextParameters.LOOTING_MOD); - } - // CraftBukkit end - - return loottableinfo.b().nextFloat() < this.a + (float) i * this.b; - } - - public static LootItemCondition.a a(float f, float f1) { - return () -> { - return new LootItemConditionRandomChanceWithLooting(f, f1); - }; - } - - public static class a extends LootItemCondition.b { - - protected a() { - super(new MinecraftKey("random_chance_with_looting"), LootItemConditionRandomChanceWithLooting.class); - } - - public void a(JsonObject jsonobject, LootItemConditionRandomChanceWithLooting lootitemconditionrandomchancewithlooting, JsonSerializationContext jsonserializationcontext) { - jsonobject.addProperty("chance", lootitemconditionrandomchancewithlooting.a); - jsonobject.addProperty("looting_multiplier", lootitemconditionrandomchancewithlooting.b); - } - - @Override - public LootItemConditionRandomChanceWithLooting b(JsonObject jsonobject, JsonDeserializationContext jsondeserializationcontext) { - return new LootItemConditionRandomChanceWithLooting(ChatDeserializer.l(jsonobject, "chance"), ChatDeserializer.l(jsonobject, "looting_multiplier")); - } - } -} diff --git a/src/main/java/net/minecraft/server/LootItemConditionSurvivesExplosion.java b/src/main/java/net/minecraft/server/LootItemConditionSurvivesExplosion.java deleted file mode 100644 index 67f3a78d1..000000000 --- a/src/main/java/net/minecraft/server/LootItemConditionSurvivesExplosion.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import java.util.Random; -import java.util.Set; - -public class LootItemConditionSurvivesExplosion implements LootItemCondition { - - private static final LootItemConditionSurvivesExplosion a = new LootItemConditionSurvivesExplosion(); - - private LootItemConditionSurvivesExplosion() {} - - @Override - public Set> a() { - return ImmutableSet.of(LootContextParameters.EXPLOSION_RADIUS); - } - - public boolean test(LootTableInfo loottableinfo) { - Float ofloat = (Float) loottableinfo.getContextParameter(LootContextParameters.EXPLOSION_RADIUS); - - if (ofloat != null) { - Random random = loottableinfo.b(); - float f = 1.0F / ofloat; - - // CraftBukkit - <= to < to allow for plugins to completely disable block drops from explosions - return random.nextFloat() < f; - } else { - return true; - } - } - - public static LootItemCondition.a b() { - return () -> { - return LootItemConditionSurvivesExplosion.a; - }; - } - - public static class a extends LootItemCondition.b { - - protected a() { - super(new MinecraftKey("survives_explosion"), LootItemConditionSurvivesExplosion.class); - } - - public void a(JsonObject jsonobject, LootItemConditionSurvivesExplosion lootitemconditionsurvivesexplosion, JsonSerializationContext jsonserializationcontext) {} - - @Override - public LootItemConditionSurvivesExplosion b(JsonObject jsonobject, JsonDeserializationContext jsondeserializationcontext) { - return LootItemConditionSurvivesExplosion.a; - } - } -} diff --git a/src/main/java/net/minecraft/server/LootSelectorEntry.java b/src/main/java/net/minecraft/server/LootSelectorEntry.java deleted file mode 100644 index 2c979e0b7..000000000 --- a/src/main/java/net/minecraft/server/LootSelectorEntry.java +++ /dev/null @@ -1,184 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import java.util.List; -import java.util.Set; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Function; -import org.apache.commons.lang3.ArrayUtils; - -public abstract class LootSelectorEntry extends LootEntryAbstract { - - protected final int e; public int getWeight() { return e; } // Paper - OBFHELPER - protected final int f; public int getQuality() { return f; } // Paper - OBFHELPER - protected final LootItemFunction[] g; - private final BiFunction c; - private final LootEntry h = new LootSelectorEntry.c() { - @Override - public void a(Consumer consumer, LootTableInfo loottableinfo) { - LootSelectorEntry.this.a(LootItemFunction.a(LootSelectorEntry.this.c, consumer, loottableinfo), loottableinfo); - } - }; - - protected LootSelectorEntry(int i, int j, LootItemCondition[] alootitemcondition, LootItemFunction[] alootitemfunction) { - super(alootitemcondition); - this.e = i; - this.f = j; - this.g = alootitemfunction; - this.c = LootItemFunctions.a((BiFunction[]) alootitemfunction); - } - - @Override - public void a(LootCollector lootcollector, Function function, Set set, LootContextParameterSet lootcontextparameterset) { - super.a(lootcollector, function, set, lootcontextparameterset); - - for (int i = 0; i < this.g.length; ++i) { - this.g[i].a(lootcollector.b(".functions[" + i + "]"), function, set, lootcontextparameterset); - } - - } - - protected abstract void a(Consumer consumer, LootTableInfo loottableinfo); - - @Override - public boolean expand(LootTableInfo loottableinfo, Consumer consumer) { - if (this.a(loottableinfo)) { - consumer.accept(this.h); - return true; - } else { - return false; - } - } - - public static LootSelectorEntry.a a(LootSelectorEntry.d lootselectorentry_d) { - return new LootSelectorEntry.b(lootselectorentry_d); - } - - public abstract static class e extends LootEntryAbstract.b { - - public e(MinecraftKey minecraftkey, Class oclass) { - super(minecraftkey, oclass); - } - - public void a(JsonObject jsonobject, T t0, JsonSerializationContext jsonserializationcontext) { - if (t0.e != 1) { - jsonobject.addProperty("weight", t0.e); - } - - if (t0.f != 0) { - jsonobject.addProperty("quality", t0.f); - } - - if (!ArrayUtils.isEmpty(t0.g)) { - jsonobject.add("functions", jsonserializationcontext.serialize(t0.g)); - } - - } - - @Override - public final T b(JsonObject jsonobject, JsonDeserializationContext jsondeserializationcontext, LootItemCondition[] alootitemcondition) { - int i = ChatDeserializer.a(jsonobject, "weight", (int) 1); - int j = ChatDeserializer.a(jsonobject, "quality", (int) 0); - LootItemFunction[] alootitemfunction = (LootItemFunction[]) ChatDeserializer.a(jsonobject, "functions", new LootItemFunction[0], jsondeserializationcontext, LootItemFunction[].class); - - return this.b(jsonobject, jsondeserializationcontext, i, j, alootitemcondition, alootitemfunction); - } - - protected abstract T b(JsonObject jsonobject, JsonDeserializationContext jsondeserializationcontext, int i, int j, LootItemCondition[] alootitemcondition, LootItemFunction[] alootitemfunction); - } - - static class b extends LootSelectorEntry.a { - - private final LootSelectorEntry.d c; - - public b(LootSelectorEntry.d lootselectorentry_d) { - this.c = lootselectorentry_d; - } - - @Override - protected LootSelectorEntry.b d() { - return this; - } - - @Override - public LootEntryAbstract b() { - return this.c.build(this.a, this.b, this.f(), this.a()); - } - } - - @FunctionalInterface - public interface d { - - LootSelectorEntry build(int i, int j, LootItemCondition[] alootitemcondition, LootItemFunction[] alootitemfunction); - } - - public abstract static class a> extends LootEntryAbstract.a implements LootItemFunctionUser { - - protected int a = 1; - protected int b = 0; - private final List c = Lists.newArrayList(); - - public a() {} - - @Override - public T b(LootItemFunction.a lootitemfunction_a) { - this.c.add(lootitemfunction_a.b()); - return this.d(); // Paper - decompile fix - } - - protected LootItemFunction[] a() { - return (LootItemFunction[]) this.c.toArray(new LootItemFunction[0]); - } - - public T a(int i) { - this.a = i; - return this.d(); // Paper - decompile fix - } - - public T b(int i) { - this.b = i; - return this.d(); // Paper - decompile fix - } - } - - public abstract class c implements LootEntry { - - protected c() { - } - - @Override - public int a(float f) { - // Paper start - Offer an alternative loot formula to refactor how luck bonus applies - // SEE: https://luckformula.emc.gs for details and data - if (lastLuck != null && lastLuck == f) { - return lastWeight; - } - // This is vanilla - float qualityModifer = (float) getQuality() * f; - double baseWeight = (getWeight() + qualityModifer); - if (com.destroystokyo.paper.PaperConfig.useAlternativeLuckFormula) { - // Random boost to avoid losing precision in the final int cast on return - final int weightBoost = 100; - baseWeight *= weightBoost; - // If we have vanilla 1, bump that down to 0 so nothing is is impacted - // vanilla 3 = 300, 200 basis = impact 2% - // =($B2*(($B2-100)/100/100)) - double impacted = baseWeight * ((baseWeight - weightBoost) / weightBoost / 100); - // =($B$7/100) - float luckModifier = Math.min(100, f * 10) / 100; - // =B2 - (C2 *($B$7/100)) - baseWeight = Math.ceil(baseWeight - (impacted * luckModifier)); - } - lastLuck = f; - lastWeight = (int) Math.max(0, Math.floor(baseWeight)); - return lastWeight; - } - } - private Float lastLuck = null; - private int lastWeight = 0; - // Paper end -} diff --git a/src/main/java/net/minecraft/server/MCUtil.java b/src/main/java/net/minecraft/server/MCUtil.java deleted file mode 100644 index 14f8b6104..000000000 --- a/src/main/java/net/minecraft/server/MCUtil.java +++ /dev/null @@ -1,538 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.block.TargetBlockInfo; -import com.destroystokyo.paper.profile.CraftPlayerProfile; -import com.destroystokyo.paper.profile.PlayerProfile; -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.internal.Streams; -import com.google.gson.stream.JsonWriter; -import com.mojang.authlib.GameProfile; -import com.mojang.datafixers.util.Either; -import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; -import org.apache.commons.lang.exception.ExceptionUtils; -import org.bukkit.Location; -import org.bukkit.block.BlockFace; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.util.Waitable; -import org.spigotmc.AsyncCatcher; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.Supplier; - -public final class MCUtil { - private static final Executor asyncExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("Paper Async Task Handler Thread - %1$d").build()); - - private MCUtil() {} - - /** - * Quickly generate a stack trace for current location - * - * @return Stacktrace - */ - public static String stack() { - return ExceptionUtils.getFullStackTrace(new Throwable()); - } - - /** - * Quickly generate a stack trace for current location with message - * - * @param str - * @return Stacktrace - */ - public static String stack(String str) { - return ExceptionUtils.getFullStackTrace(new Throwable(str)); - } - - public static boolean isMainThread() { - return MinecraftServer.getServer().isMainThread(); - } - - private static class DelayedRunnable implements Runnable { - - private final int ticks; - private final Runnable run; - - private DelayedRunnable(int ticks, Runnable run) { - this.ticks = ticks; - this.run = run; - } - - @Override - public void run() { - if (ticks <= 0) { - run.run(); - } else { - scheduleTask(ticks-1, run); - } - } - } - - public static void scheduleTask(int ticks, Runnable runnable) { - // We use post to main instead of process queue as we don't want to process these mid tick if - // Someone uses processQueueWhileWaiting - MinecraftServer.getServer().scheduleOnMain(new DelayedRunnable(ticks, runnable)); - } - - public static void processQueue() { - Runnable runnable; - Queue processQueue = getProcessQueue(); - while ((runnable = processQueue.poll()) != null) { - try { - runnable.run(); - } catch (Exception e) { - MinecraftServer.LOGGER.error("Error executing task", e); - } - } - } - public static T processQueueWhileWaiting(CompletableFuture future) { - try { - if (isMainThread()) { - while (!future.isDone()) { - try { - return future.get(1, TimeUnit.MILLISECONDS); - } catch (TimeoutException ignored) { - processQueue(); - } - } - } - return future.get(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static void ensureMain(Runnable run) { - ensureMain(null, run); - } - /** - * Ensures the target code is running on the main thread - * @param reason - * @param run - * @return - */ - public static void ensureMain(String reason, Runnable run) { - if (AsyncCatcher.enabled && Thread.currentThread() != MinecraftServer.getServer().serverThread) { - if (reason != null) { - new IllegalStateException("Asynchronous " + reason + "!").printStackTrace(); - } - getProcessQueue().add(run); - return; - } - run.run(); - } - - private static Queue getProcessQueue() { - return MinecraftServer.getServer().processQueue; - } - - public static T ensureMain(Supplier run) { - return ensureMain(null, run); - } - /** - * Ensures the target code is running on the main thread - * @param reason - * @param run - * @param - * @return - */ - public static T ensureMain(String reason, Supplier run) { - if (AsyncCatcher.enabled && Thread.currentThread() != MinecraftServer.getServer().serverThread) { - if (reason != null) { - new IllegalStateException("Asynchronous " + reason + "! Blocking thread until it returns ").printStackTrace(); - } - Waitable wait = new Waitable() { - @Override - protected T evaluate() { - return run.get(); - } - }; - getProcessQueue().add(wait); - try { - return wait.get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - return null; - } - return run.get(); - } - - public static PlayerProfile toBukkit(GameProfile profile) { - return CraftPlayerProfile.asBukkitMirror(profile); - } - - /** - * Calculates distance between 2 entities - * @param e1 - * @param e2 - * @return - */ - public static double distance(Entity e1, Entity e2) { - return Math.sqrt(distanceSq(e1, e2)); - } - - - /** - * Calculates distance between 2 block positions - * @param e1 - * @param e2 - * @return - */ - public static double distance(BlockPosition e1, BlockPosition e2) { - return Math.sqrt(distanceSq(e1, e2)); - } - - /** - * Gets the distance between 2 positions - * @param x1 - * @param y1 - * @param z1 - * @param x2 - * @param y2 - * @param z2 - * @return - */ - public static double distance(double x1, double y1, double z1, double x2, double y2, double z2) { - return Math.sqrt(distanceSq(x1, y1, z1, x2, y2, z2)); - } - - /** - * Get's the distance squared between 2 entities - * @param e1 - * @param e2 - * @return - */ - public static double distanceSq(Entity e1, Entity e2) { - return distanceSq(e1.locX,e1.locY,e1.locZ, e2.locX,e2.locY,e2.locZ); - } - - /** - * Gets the distance sqaured between 2 block positions - * @param pos1 - * @param pos2 - * @return - */ - public static double distanceSq(BlockPosition pos1, BlockPosition pos2) { - return distanceSq(pos1.getX(), pos1.getY(), pos1.getZ(), pos2.getX(), pos2.getY(), pos2.getZ()); - } - - /** - * Gets the distance squared between 2 positions - * @param x1 - * @param y1 - * @param z1 - * @param x2 - * @param y2 - * @param z2 - * @return - */ - public static double distanceSq(double x1, double y1, double z1, double x2, double y2, double z2) { - return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2); - } - - /** - * Converts a NMS World/BlockPosition to Bukkit Location - * @param world - * @param x - * @param y - * @param z - * @return - */ - public static Location toLocation(World world, double x, double y, double z) { - return new Location(world.getWorld(), x, y, z); - } - - /** - * Converts a NMS World/BlockPosition to Bukkit Location - * @param world - * @param pos - * @return - */ - public static Location toLocation(World world, BlockPosition pos) { - return new Location(world.getWorld(), pos.getX(), pos.getY(), pos.getZ()); - } - - /** - * Converts an NMS entity's current location to a Bukkit Location - * @param entity - * @return - */ - public static Location toLocation(Entity entity) { - return new Location(entity.getWorld().getWorld(), entity.locX, entity.locY, entity.locZ); - } - - public static org.bukkit.block.Block toBukkitBlock(World world, BlockPosition pos) { - return world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); - } - - public static BlockPosition toBlockPosition(Location loc) { - return new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); - } - - public static boolean isEdgeOfChunk(BlockPosition pos) { - final int modX = pos.getX() & 15; - final int modZ = pos.getZ() & 15; - return (modX == 0 || modX == 15 || modZ == 0 || modZ == 15); - } - - /** - * Posts a task to be executed asynchronously - * @param run - */ - public static void scheduleAsyncTask(Runnable run) { - asyncExecutor.execute(run); - } - - @Nullable - public static TileEntityHopper getHopper(World world, BlockPosition pos) { - Chunk chunk = world.getChunkIfLoaded(pos.getX() >> 4, pos.getZ() >> 4); - if (chunk != null && chunk.getType(new BlockPosition(pos.getX(), pos.getY(), pos.getZ())).getBlock() == Blocks.HOPPER) { - TileEntity tileEntity = chunk.getTileEntityImmediately(pos); - if (tileEntity instanceof TileEntityHopper) { - return (TileEntityHopper) tileEntity; - } - } - return null; - } - - @Nonnull - public static World getNMSWorld(@Nonnull org.bukkit.World world) { - return ((CraftWorld) world).getHandle(); - } - - public static World getNMSWorld(@Nonnull org.bukkit.entity.Entity entity) { - return getNMSWorld(entity.getWorld()); - } - - public static RayTrace.FluidCollisionOption getNMSFluidCollisionOption(TargetBlockInfo.FluidMode fluidMode) { - if (fluidMode == TargetBlockInfo.FluidMode.NEVER) { - return RayTrace.FluidCollisionOption.NONE; - } - if (fluidMode == TargetBlockInfo.FluidMode.SOURCE_ONLY) { - return RayTrace.FluidCollisionOption.SOURCE_ONLY; - } - if (fluidMode == TargetBlockInfo.FluidMode.ALWAYS) { - return RayTrace.FluidCollisionOption.ANY; - } - return null; - } - - public static BlockFace toBukkitBlockFace(EnumDirection enumDirection) { - switch (enumDirection) { - 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 null; - } - } - - @Nullable - public static IChatBaseComponent getBaseComponentFromNbt(String key, NBTTagCompound compound) { - if (!compound.hasKey(key)) { - return null; - } - String string = compound.getString(key); - try { - return IChatBaseComponent.ChatSerializer.jsonToComponent(string); - } catch (com.google.gson.JsonParseException e) { - org.bukkit.Bukkit.getLogger().warning("Unable to parse " + key + " from " + compound +": " + e.getMessage()); - } - - return null; - } - - public static ChunkStatus getChunkStatus(PlayerChunk chunk) { - List statuses = ChunkProviderServer.getPossibleChunkStatuses(); - for (int i = statuses.size() - 1; i >= 0; --i) { - ChunkStatus curr = statuses.get(i); - CompletableFuture> future = chunk.getStatusFutureUnchecked(curr); - if (future != PlayerChunk.UNLOADED_CHUNK_ACCESS_FUTURE) { - return curr; - } - } - return null; // unloaded - } - - public static void dumpChunks(File file) throws IOException { - file.getParentFile().mkdirs(); - file.createNewFile(); - /* - * Json format: - * - * Main data format: - * -server-version: - * -data-version: - * -worlds: - * -name: - * -view-distance: - * -keep-spawn-loaded: - * -keep-spawn-loaded-range: - * -visible-chunk-count: - * -loaded-chunk-count: - * -verified-fully-loaded-chunks: - * -players: - * -chunk-data: - * - * Player format: - * -name: - * -x: - * -y: - * -z: - * - * Chunk Format: - * -x: - * -z: - * -ticket-level: - * -state: - * -queued-for-unload: - * -status: - * -tickets: - * - * - * Ticket format: - * -ticket-type: - * -ticket-level: - * -add-tick: - * -object-reason: // This depends on the type of ticket. ie POST_TELEPORT -> entity id - */ - List worlds = org.bukkit.Bukkit.getWorlds(); - JsonObject data = new JsonObject(); - - data.addProperty("server-version", org.bukkit.Bukkit.getVersion()); - data.addProperty("data-version", 0); - - JsonArray worldsData = new JsonArray(); - - for (org.bukkit.World bukkitWorld : worlds) { - JsonObject worldData = new JsonObject(); - - WorldServer world = ((org.bukkit.craftbukkit.CraftWorld)bukkitWorld).getHandle(); - PlayerChunkMap chunkMap = world.getChunkProvider().playerChunkMap; - Long2ObjectLinkedOpenHashMap visibleChunks = chunkMap.visibleChunks; - ChunkMapDistance chunkMapDistance = chunkMap.getChunkMapDistanceManager(); - List allChunks = new ArrayList<>(visibleChunks.values()); - List players = world.players; - - int fullLoadedChunks = 0; - - for (PlayerChunk chunk : allChunks) { - if (chunk.getFullChunkIfCached() != null) { - ++fullLoadedChunks; - } - } - - // sorting by coordinate makes the log easier to read - allChunks.sort((PlayerChunk v1, PlayerChunk v2) -> { - if (v1.location.x != v2.location.x) { - return Integer.compare(v1.location.x, v2.location.x); - } - return Integer.compare(v1.location.z, v2.location.z); - }); - - worldData.addProperty("name", world.getWorldData().getName()); - worldData.addProperty("view-distance", world.spigotConfig.viewDistance); - worldData.addProperty("keep-spawn-loaded", world.keepSpawnInMemory); - worldData.addProperty("keep-spawn-loaded-range", world.paperConfig.keepLoadedRange); - worldData.addProperty("visible-chunk-count", visibleChunks.size()); - worldData.addProperty("loaded-chunk-count", chunkMap.loadedChunks.size()); - worldData.addProperty("verified-fully-loaded-chunks", fullLoadedChunks); - - JsonArray playersData = new JsonArray(); - - for (EntityPlayer player : players) { - JsonObject playerData = new JsonObject(); - - playerData.addProperty("name", player.getName()); - playerData.addProperty("x", player.locX); - playerData.addProperty("y", player.locY); - playerData.addProperty("z", player.locZ); - - playersData.add(playerData); - - } - - worldData.add("players", playersData); - - JsonArray chunksData = new JsonArray(); - - for (PlayerChunk playerChunk : allChunks) { - JsonObject chunkData = new JsonObject(); - - Set> tickets = chunkMapDistance.tickets.get(playerChunk.location.pair()); - ChunkStatus status = getChunkStatus(playerChunk); - - chunkData.addProperty("x", playerChunk.location.x); - chunkData.addProperty("z", playerChunk.location.z); - chunkData.addProperty("ticket-level", playerChunk.getTicketLevel()); - chunkData.addProperty("state", PlayerChunk.getChunkState(playerChunk.getTicketLevel()).toString()); - chunkData.addProperty("queued-for-unload", chunkMap.unloadQueue.contains(playerChunk.location.pair())); - chunkData.addProperty("status", status == null ? "unloaded" : status.toString()); - - JsonArray ticketsData = new JsonArray(); - - if (tickets != null) { - for (Ticket ticket : tickets) { - JsonObject ticketData = new JsonObject(); - - ticketData.addProperty("ticket-type", ticket.getTicketType().toString()); - ticketData.addProperty("ticket-level", ticket.getTicketLevel()); - ticketData.addProperty("object-reason", String.valueOf(ticket.getObjectReason())); - ticketData.addProperty("add-tick", ticket.getCreationTick()); - - ticketsData.add(ticketData); - } - } - - chunkData.add("tickets", ticketsData); - chunksData.add(chunkData); - } - - - worldData.add("chunk-data", chunksData); - worldsData.add(worldData); - } - - data.add("worlds", worldsData); - - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); - jsonWriter.setIndent(" "); - jsonWriter.setLenient(false); - Streams.write(data, jsonWriter); - - String fileData = stringWriter.toString(); - - try (PrintStream out = new PrintStream(new FileOutputStream(file), false, "UTF-8")) { - out.print(fileData); - } - } - - public static int getTicketLevelFor(ChunkStatus status) { - // TODO make sure the constant `33` is correct on future updates. See getChunkAt(int, int, ChunkStatus, boolean) - return 33 + ChunkStatus.getTicketLevelOffset(status); - } -} diff --git a/src/main/java/net/minecraft/server/MerchantRecipe.java b/src/main/java/net/minecraft/server/MerchantRecipe.java deleted file mode 100644 index b5ec1f1bb..000000000 --- a/src/main/java/net/minecraft/server/MerchantRecipe.java +++ /dev/null @@ -1,215 +0,0 @@ -package net.minecraft.server; - -import org.bukkit.craftbukkit.inventory.CraftMerchantRecipe; // CraftBukkit - -public class MerchantRecipe { - - public ItemStack buyingItem1; - public ItemStack buyingItem2; - public final ItemStack sellingItem; - public int uses; - public int maxUses; - public boolean rewardExp; - private int specialPrice; - private int demand; - public float priceMultiplier; - public int xp; - // CraftBukkit start - private CraftMerchantRecipe bukkitHandle; - - public CraftMerchantRecipe asBukkit() { - return (bukkitHandle == null) ? bukkitHandle = new CraftMerchantRecipe(this) : bukkitHandle; - } - - public MerchantRecipe(ItemStack itemstack, ItemStack itemstack1, ItemStack itemstack2, int uses, int maxUses, int experience, float priceMultiplier, CraftMerchantRecipe bukkit) { - this(itemstack, itemstack1, itemstack2, uses, maxUses, experience, priceMultiplier); - this.bukkitHandle = bukkit; - } - // CraftBukkit end - - public MerchantRecipe(NBTTagCompound nbttagcompound) { - this.rewardExp = true; - this.xp = 1; - this.buyingItem1 = ItemStack.a(nbttagcompound.getCompound("buy")); - this.buyingItem2 = ItemStack.a(nbttagcompound.getCompound("buyB")); - this.sellingItem = ItemStack.a(nbttagcompound.getCompound("sell")); - this.uses = nbttagcompound.getInt("uses"); - if (nbttagcompound.hasKeyOfType("maxUses", 99)) { - this.maxUses = nbttagcompound.getInt("maxUses"); - } else { - this.maxUses = 4; - } - - if (nbttagcompound.hasKeyOfType("rewardExp", 1)) { - this.rewardExp = nbttagcompound.getBoolean("rewardExp"); - } - - if (nbttagcompound.hasKeyOfType("xp", 3)) { - this.xp = nbttagcompound.getInt("xp"); - } - - if (nbttagcompound.hasKeyOfType("priceMultiplier", 5)) { - this.priceMultiplier = nbttagcompound.getFloat("priceMultiplier"); - } - - this.specialPrice = nbttagcompound.getInt("specialPrice"); - this.demand = nbttagcompound.getInt("demand"); - } - - public MerchantRecipe(ItemStack itemstack, ItemStack itemstack1, int i, int j, float f) { - this(itemstack, ItemStack.a, itemstack1, i, j, f); - } - - public MerchantRecipe(ItemStack itemstack, ItemStack itemstack1, ItemStack itemstack2, int i, int j, float f) { - this(itemstack, itemstack1, itemstack2, 0, i, j, f); - } - - public MerchantRecipe(ItemStack itemstack, ItemStack itemstack1, ItemStack itemstack2, int i, int j, int k, float f) { - this(itemstack, itemstack1, itemstack2, i, j, k, f, 0); - } - - public MerchantRecipe(ItemStack itemstack, ItemStack itemstack1, ItemStack itemstack2, int i, int j, int k, float f, int l) { - this.rewardExp = true; - this.xp = 1; - this.buyingItem1 = itemstack; - this.buyingItem2 = itemstack1; - this.sellingItem = itemstack2; - this.uses = i; - this.maxUses = j; - this.xp = k; - this.priceMultiplier = f; - this.demand = l; - } - - public ItemStack a() { - return this.buyingItem1; - } - - public ItemStack getBuyItem1() { - int i = this.buyingItem1.getCount(); - ItemStack itemstack = this.buyingItem1.cloneItemStack(); - int j = Math.max(0, MathHelper.d((float) (i * this.demand) * this.priceMultiplier)); - - itemstack.setCount(MathHelper.clamp(i + j + this.specialPrice, 1, this.buyingItem1.getItem().getMaxStackSize())); - return itemstack; - } - - public ItemStack getBuyItem2() { - return this.buyingItem2; - } - - public ItemStack getSellingItem() { - return this.sellingItem; - } - - public void e() { - this.demand = this.demand + this.uses - (this.maxUses - this.uses); - } - - public ItemStack f() { - return this.sellingItem.cloneItemStack(); - } - - public int getUses() { - return this.uses; - } - - public void resetUses() { - this.uses = 0; - } - - public int getMaxUses() { - return this.maxUses; - } - - public void increaseUses() { - ++this.uses; - } - - public int k() { - return this.demand; - } - - public void increaseSpecialPrice(int i) { - this.specialPrice += i; - } - - public void setSpecialPrice() { - this.specialPrice = 0; - } - - public int getSpecialPrice() { - return this.specialPrice; - } - - public void setSpecialPrice(int i) { - this.specialPrice = i; - } - - public float getPriceMultiplier() { - return this.priceMultiplier; - } - - public int getXp() { - return this.xp; - } - - public boolean isFullyUsed() { - return this.uses >= this.maxUses; - } - - public void q() { - this.uses = this.maxUses; - } - - public boolean isRewardExp() { - return this.rewardExp; - } - - public NBTTagCompound s() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.set("buy", this.buyingItem1.save(new NBTTagCompound())); - nbttagcompound.set("sell", this.sellingItem.save(new NBTTagCompound())); - nbttagcompound.set("buyB", this.buyingItem2.save(new NBTTagCompound())); - nbttagcompound.setInt("uses", this.uses); - nbttagcompound.setInt("maxUses", this.maxUses); - nbttagcompound.setBoolean("rewardExp", this.rewardExp); - nbttagcompound.setInt("xp", this.xp); - nbttagcompound.setFloat("priceMultiplier", this.priceMultiplier); - nbttagcompound.setInt("specialPrice", this.specialPrice); - nbttagcompound.setInt("demand", this.demand); - return nbttagcompound; - } - - public boolean a(ItemStack itemstack, ItemStack itemstack1) { - return this.c(itemstack, this.getBuyItem1()) && itemstack.getCount() >= this.getBuyItem1().getCount() && this.c(itemstack1, this.buyingItem2) && itemstack1.getCount() >= this.buyingItem2.getCount(); - } - - private boolean c(ItemStack itemstack, ItemStack itemstack1) { - if (itemstack1.isEmpty() && itemstack.isEmpty()) { - return true; - } else { - ItemStack itemstack2 = itemstack.cloneItemStack(); - - if (itemstack2.getItem().usesDurability()) { - itemstack2.setDamage(itemstack2.getDamage()); - } - - return ItemStack.c(itemstack2, itemstack1) && (!itemstack1.hasTag() || itemstack2.hasTag() && GameProfileSerializer.a(itemstack1.getTag(), itemstack2.getTag(), false)); - } - } - - public boolean b(ItemStack itemstack, ItemStack itemstack1) { - if (!this.a(itemstack, itemstack1)) { - return false; - } else { - itemstack.subtract(this.getBuyItem1().getCount()); - if (!this.getBuyItem2().isEmpty()) { - itemstack1.subtract(this.getBuyItem2().getCount()); - } - - return true; - } - } -} diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java deleted file mode 100644 index 055b0399c..000000000 --- a/src/main/java/net/minecraft/server/MinecraftServer.java +++ /dev/null @@ -1,2216 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Splitter; -import co.aikar.timings.Timings; -import com.destroystokyo.paper.event.server.PaperServerListPingEvent; -import com.google.common.base.Stopwatch; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.gson.JsonElement; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.GameProfileRepository; -import com.mojang.authlib.minecraft.MinecraftSessionService; -import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; -import com.mojang.datafixers.DataFixer; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufOutputStream; -import io.netty.buffer.Unpooled; -import it.unimi.dsi.fastutil.longs.LongIterator; -import java.awt.GraphicsEnvironment; -import java.awt.image.BufferedImage; -import java.io.BufferedWriter; -import java.io.File; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.net.Proxy; -import java.net.URLEncoder; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.KeyPair; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.UUID; -import java.util.Map.Entry; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; -import java.util.function.BooleanSupplier; -import javax.annotation.Nullable; -import javax.imageio.ImageIO; -import joptsimple.NonOptionArgumentSpec; -import joptsimple.OptionParser; -import joptsimple.OptionSet; -import joptsimple.OptionSpec; -import org.apache.commons.lang3.Validate; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -// CraftBukkit start -import joptsimple.OptionSet; -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.Main; -import org.bukkit.event.server.ServerLoadEvent; -// CraftBukkit end -import co.aikar.timings.MinecraftTimings; // Paper -import org.spigotmc.SlackActivityAccountant; // Spigot - -public abstract class MinecraftServer extends IAsyncTaskHandlerReentrant implements IMojangStatistics, ICommandListener, AutoCloseable, Runnable { - - private static MinecraftServer SERVER; // Paper - public static final Logger LOGGER = LogManager.getLogger(); - public static final File b = new File("usercache.json"); - private static final CompletableFuture i = CompletableFuture.completedFuture(Unit.INSTANCE); - public static final WorldSettings c = (new WorldSettings((long) "North Carolina".hashCode(), EnumGamemode.SURVIVAL, true, false, WorldType.NORMAL)).a(); - public Convertable convertable; - private final MojangStatisticsGenerator snooper = new MojangStatisticsGenerator("server", this, SystemUtils.getMonotonicMillis()); - public File universe; - private final List tickables = Lists.newArrayList(); - private final GameProfiler methodProfiler = new GameProfiler(this::aj); - private ServerConnection serverConnection; - public final WorldLoadListenerFactory worldLoadListenerFactory; - private final ServerPing serverPing = new ServerPing(); - private final Random q = new Random(); - public final DataFixer dataConverterManager; - private String serverIp; - private int serverPort = -1; - public final Map worldServer = new com.destroystokyo.paper.PaperWorldMap(); // Paper; - private PlayerList playerList; - private volatile boolean isRunning = true; - private volatile boolean isRestarting = false; // Paper - flag to signify we're attempting to restart - private boolean isStopped; - private int ticks; - protected final Proxy proxy; - private boolean onlineMode; - private boolean A; - private boolean spawnAnimals; - private boolean spawnNPCs; - private boolean pvpMode; - private boolean allowFlight; - @Nullable - private String motd; - private int G; - private int H; - public final long[] f = new long[100]; - @Nullable - private KeyPair I; - @Nullable - private String J; - private final String K; - private boolean demoMode; - private boolean bonusChest; - private String O = ""; - private String P = ""; - private volatile boolean hasTicked; - private long lastOverloadTime; - @Nullable - private IChatBaseComponent S; - private boolean T; - private boolean U; - @Nullable - private final YggdrasilAuthenticationService yggdrasilAuthenticationService; - private final MinecraftSessionService minecraftSessionService; - private final GameProfileRepository gameProfileRepository; - private final UserCache userCache; - private long Z; - public final Thread serverThread = (Thread) SystemUtils.a((new Thread(this, "Server thread")), (thread) -> { // CraftBukkit - decompile error - thread.setUncaughtExceptionHandler((thread1, throwable) -> { - MinecraftServer.LOGGER.error(throwable); - }); - }); - private long nextTick = SystemUtils.getMonotonicMillis(); - private long ab; final long getTickOversleepMaxTime() { return this.ab; } // Paper - OBFHELPER - private boolean ac; final boolean hasExecutedTask() { return this.ac; } // Paper - OBFHELPER - private final IReloadableResourceManager ae; - private final ResourcePackRepository resourcePackRepository; - @Nullable - private ResourcePackSourceFolder resourcePackFolder; - public CommandDispatcher commandDispatcher; - private final CraftingManager ai; - private final TagRegistry aj; - private final ScoreboardServer ak; - private final BossBattleCustomData al; - private final LootTableRegistry am; - private final AdvancementDataWorld an; - private final CustomFunctionData ao; - private final CircularTimer ap; - private boolean aq; - private boolean forceUpgrade; - private boolean eraseCache; - private float at; - public final Executor executorService; - @Nullable - private String av; - - // CraftBukkit start - public org.bukkit.craftbukkit.CraftServer server; - public OptionSet options; - public org.bukkit.command.ConsoleCommandSender console; - public org.bukkit.command.RemoteConsoleCommandSender remoteConsole; - //public ConsoleReader reader; // Paper - public static int currentTick = 0; // Paper - Further improve tick loop - public java.util.Queue processQueue = new java.util.concurrent.ConcurrentLinkedQueue(); - public int autosavePeriod; - public boolean serverAutoSave = false; // Paper - public File bukkitDataPackFolder; - public CommandDispatcher vanillaCommandDispatcher; - private boolean forceTicks; - // CraftBukkit end - // Spigot start - public static final int TPS = 20; - public static final int TICK_TIME = 1000000000 / TPS; - private static final int SAMPLE_INTERVAL = 20; // Paper - public final double[] recentTps = new double[ 3 ]; - public final SlackActivityAccountant slackActivityAccountant = new SlackActivityAccountant(); - // Spigot end - - public MinecraftServer(OptionSet options, Proxy proxy, DataFixer datafixer, CommandDispatcher commanddispatcher, YggdrasilAuthenticationService yggdrasilauthenticationservice, MinecraftSessionService minecraftsessionservice, GameProfileRepository gameprofilerepository, UserCache usercache, WorldLoadListenerFactory worldloadlistenerfactory, String s) { - super("Server"); - this.ae = new ResourceManager(EnumResourcePackType.SERVER_DATA, this.serverThread); - SERVER = this; // Paper - better singleton - this.resourcePackRepository = new ResourcePackRepository<>(ResourcePackLoader::new); - this.ai = new CraftingManager(); - this.aj = new TagRegistry(); - this.ak = new ScoreboardServer(this); - this.al = new BossBattleCustomData(this); - this.am = new LootTableRegistry(); - this.an = new AdvancementDataWorld(); - this.ao = new CustomFunctionData(this); - this.ap = new CircularTimer(); - this.proxy = proxy; - this.commandDispatcher = this.vanillaCommandDispatcher = commanddispatcher; // CraftBukkit - this.yggdrasilAuthenticationService = yggdrasilauthenticationservice; - this.minecraftSessionService = minecraftsessionservice; - this.gameProfileRepository = gameprofilerepository; - this.userCache = usercache; - // this.universe = file; // CraftBukkit - // this.serverConnection = new ServerConnection(this); // CraftBukkit // Spigot - this.worldLoadListenerFactory = worldloadlistenerfactory; - // this.convertable = new Convertable(file.toPath(), file.toPath().resolve("../backups"), datafixer); // CraftBukkit - moved to DedicatedServer.init - this.dataConverterManager = datafixer; - this.ae.a((IReloadListener) this.aj); - this.ae.a((IReloadListener) this.ai); - this.ae.a((IReloadListener) this.am); - this.ae.a((IReloadListener) this.ao); - this.ae.a((IReloadListener) this.an); - this.executorService = SystemUtils.e(); - this.K = s; - // CraftBukkit start - this.options = options; - // Paper start - Handled by TerminalConsoleAppender - // Try to see if we're actually running in a terminal, disable jline if not - /* - if (System.console() == null && System.getProperty("jline.terminal") == null) { - System.setProperty("jline.terminal", "jline.UnsupportedTerminal"); - Main.useJline = false; - } - - try { - reader = new ConsoleReader(System.in, System.out); - reader.setExpandEvents(false); // Avoid parsing exceptions for uncommonly used event designators - } catch (Throwable e) { - try { - // Try again with jline disabled for Windows users without C++ 2008 Redistributable - System.setProperty("jline.terminal", "jline.UnsupportedTerminal"); - System.setProperty("user.language", "en"); - Main.useJline = false; - reader = new ConsoleReader(System.in, System.out); - reader.setExpandEvents(false); - } catch (IOException ex) { - LOGGER.warn((String) null, ex); - } - } - */ - // Paper end - Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.util.ServerShutdownThread(this)); - } - // CraftBukkit end - - private void initializeScoreboards(WorldPersistentData worldpersistentdata) { - PersistentScoreboard persistentscoreboard = (PersistentScoreboard) worldpersistentdata.a(PersistentScoreboard::new, "scoreboard"); - - persistentscoreboard.a((Scoreboard) this.getScoreboard()); - this.getScoreboard().a((Runnable) (new RunnableSaveScoreboard(persistentscoreboard))); - } - - protected abstract boolean init() throws IOException; - - public void convertWorld(String s) { - if (this.getConvertable().isConvertable(s)) { - MinecraftServer.LOGGER.info("Converting map!"); - this.b((IChatBaseComponent) (new ChatMessage("menu.convertingLevel", new Object[0]))); - this.getConvertable().convert(s, new IProgressUpdate() { - private long b = SystemUtils.getMonotonicMillis(); - - @Override - public void a(IChatBaseComponent ichatbasecomponent) {} - - @Override - public void a(int i) { - if (SystemUtils.getMonotonicMillis() - this.b >= 1000L) { - this.b = SystemUtils.getMonotonicMillis(); - MinecraftServer.LOGGER.info("Converting... {}%", i); - } - - } - - @Override - public void c(IChatBaseComponent ichatbasecomponent) {} - }); - } - - if (this.forceUpgrade) { - MinecraftServer.LOGGER.info("Forcing world upgrade! {}", s); // CraftBukkit - WorldData worlddata = this.getConvertable().b(s); // CraftBukkit - - if (worlddata != null) { - WorldUpgrader worldupgrader = new WorldUpgrader(s, this.getConvertable(), worlddata, this.eraseCache); // CraftBukkit - IChatBaseComponent ichatbasecomponent = null; - - while (!worldupgrader.b()) { - IChatBaseComponent ichatbasecomponent1 = worldupgrader.g(); - - if (ichatbasecomponent != ichatbasecomponent1) { - ichatbasecomponent = ichatbasecomponent1; - MinecraftServer.LOGGER.info(worldupgrader.g().getString()); - } - - int i = worldupgrader.d(); - - if (i > 0) { - int j = worldupgrader.e() + worldupgrader.f(); - - MinecraftServer.LOGGER.info("{}% completed ({} / {} chunks)...", MathHelper.d((float) j / (float) i * 100.0F), j, i); - } - - if (this.isStopped()) { - worldupgrader.a(); - } else { - try { - Thread.sleep(1000L); - } catch (InterruptedException interruptedexception) { - ; - } - } - } - } - } - - } - - protected synchronized void b(IChatBaseComponent ichatbasecomponent) { - this.S = ichatbasecomponent; - } - - protected void a(String s, String s1, long i, WorldType worldtype, JsonElement jsonelement) { - // this.convertWorld(s); // CraftBukkit - moved down - this.b((IChatBaseComponent) (new ChatMessage("menu.loadingLevel", new Object[0]))); - /* CraftBukkit start - Remove ticktime arrays and worldsettings - WorldNBTStorage worldnbtstorage = this.getConvertable().a(s, this); - - this.a(this.getWorld(), worldnbtstorage); - WorldData worlddata = worldnbtstorage.getWorldData(); - WorldSettings worldsettings; - - if (worlddata == null) { - if (this.isDemoMode()) { - worldsettings = MinecraftServer.c; - } else { - worldsettings = new WorldSettings(i, this.getGamemode(), this.getGenerateStructures(), this.isHardcore(), worldtype); - worldsettings.setGeneratorSettings(jsonelement); - if (this.bonusChest) { - worldsettings.a(); - } - } - - worlddata = new WorldData(worldsettings, s1); - } else { - worlddata.setName(s1); - worldsettings = new WorldSettings(worlddata); - } - - this.a(worldnbtstorage.getDirectory(), worlddata); - */ - int worldCount = 3; - - for (int j = 0; j < worldCount; ++j) { - WorldServer world; - WorldData worlddata; - 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; - this.convertWorld(name); // Run conversion now - - org.bukkit.generator.ChunkGenerator gen = this.server.getGenerator(name); - WorldSettings worldsettings = new WorldSettings(com.destroystokyo.paper.PaperConfig.seedOverride.getOrDefault(name, i), this.getGamemode(), this.getGenerateStructures(), this.isHardcore(), worldtype); // Paper - worldsettings.setGeneratorSettings(jsonelement); - - if (j == 0) { - WorldNBTStorage worldnbtstorage = new WorldNBTStorage(server.getWorldContainer(), s1, this, this.dataConverterManager); - worlddata = worldnbtstorage.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) - this.a(worldnbtstorage.getDirectory(), worlddata); - WorldLoadListener worldloadlistener = this.worldLoadListenerFactory.create(11); - - if (this.isDemoMode()) { - worlddata.a(MinecraftServer.c); - } - world = new WorldServer(this, this.executorService, worldnbtstorage, worlddata, DimensionManager.OVERWORLD, this.methodProfiler, worldloadlistener, org.bukkit.World.Environment.getEnvironment(dimension), gen); - - this.initializeScoreboards(world.getWorldPersistentData()); - 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); - File oldLevelDat = new File(new File(s), "level.dat"); // The data folders exist on first run as they are created in the PersistentCollection constructor above, but the level.dat won't - - if (!newWorld.isDirectory() && oldWorld.isDirectory() && oldLevelDat.isFile()) { - 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(oldLevelDat, new File(new File(name), "level.dat")); - org.apache.commons.io.FileUtils.copyDirectory(new File(new File(s), "data"), new File(new File(name), "data")); - } 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 ----"); - } - } - - WorldNBTStorage worldnbtstorage = new WorldNBTStorage(server.getWorldContainer(), name, this, this.dataConverterManager); - // world =, b0 to dimension, s1 to name, added Environment and gen - worlddata = worldnbtstorage.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) - WorldLoadListener worldloadlistener = this.worldLoadListenerFactory.create(11); - world = new SecondaryWorldServer(this.getWorldServer(DimensionManager.OVERWORLD), this, this.executorService, worldnbtstorage, DimensionManager.a(dimension), this.methodProfiler, worldloadlistener, worlddata, org.bukkit.World.Environment.getEnvironment(dimension), gen); - } - - this.initWorld(world, worlddata, worldsettings); - this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(world.getWorld())); - - this.worldServer.put(world.getWorldProvider().getDimensionManager(), world); - this.getPlayerList().setPlayerFileData(world); - - if (worlddata.getCustomBossEvents() != null) { - this.getBossBattleCustomData().a(worlddata.getCustomBossEvents()); - } - } - this.a(this.getDifficulty(), true); - for (WorldServer worldserver : com.google.common.collect.Lists.newArrayList(this.getWorlds())) { // Paper - avoid como if 1 world triggers another world - this.loadSpawn(worldserver.getChunkProvider().playerChunkMap.worldLoadListener, worldserver); - this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldLoadEvent(worldserver.getWorld())); - } - - // Paper start - Handle collideRule team for player collision toggle - final Scoreboard scoreboard = this.getScoreboard(); - final java.util.Collection toRemove = scoreboard.getTeams().stream().filter(team -> team.getName().startsWith("collideRule_")).map(ScoreboardTeam::getName).collect(java.util.stream.Collectors.toList()); - for (String teamName : toRemove) { - scoreboard.removeTeam(scoreboard.getTeam(teamName)); // Clean up after ourselves - } - - if (!com.destroystokyo.paper.PaperConfig.enablePlayerCollisions) { - this.getPlayerList().collideRuleTeamName = org.apache.commons.lang3.StringUtils.left("collideRule_" + java.util.concurrent.ThreadLocalRandom.current().nextInt(), 16); - ScoreboardTeam collideTeam = scoreboard.createTeam(this.getPlayerList().collideRuleTeamName); - collideTeam.setCanSeeFriendlyInvisibles(false); // Because we want to mimic them not being on a team at all - } - // Paper end - - this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD); - this.server.getPluginManager().callEvent(new ServerLoadEvent(ServerLoadEvent.LoadType.STARTUP)); - this.serverConnection.acceptConnections(); - // CraftBukkit end - - } - - // CraftBukkit start - public void initWorld(WorldServer worldserver1, WorldData worlddata, WorldSettings worldsettings) { - worldserver1.getWorldBorder().b(worlddata); - - // CraftBukkit start - if (worldserver1.generator != null) { - worldserver1.getWorld().getPopulators().addAll(worldserver1.generator.getDefaultPopulators(worldserver1.getWorld())); - } - // CraftBukkit end - - if (!worlddata.u()) { - try { - worldserver1.a(worldsettings); - if (worlddata.getType() == WorldType.DEBUG_ALL_BLOCK_STATES) { - this.a(worlddata); - } - - worlddata.d(true); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Exception initializing level"); - - try { - worldserver1.a(crashreport); - } catch (Throwable throwable1) { - ; - } - - throw new ReportedException(crashreport); - } - - worlddata.d(true); - } - } - // CraftBukkit end - - private void a(WorldData worlddata) { - worlddata.f(false); - worlddata.c(true); - worlddata.setStorm(false); - worlddata.setThundering(false); - worlddata.g(1000000000); - worlddata.setDayTime(6000L); - worlddata.setGameType(EnumGamemode.SPECTATOR); - worlddata.g(false); - worlddata.setDifficulty(EnumDifficulty.PEACEFUL); - worlddata.e(true); - ((GameRules.GameRuleBoolean) worlddata.v().get(GameRules.DO_DAYLIGHT_CYCLE)).a(false, this); - } - - protected void a(File file, WorldData worlddata) { - this.resourcePackRepository.a((ResourcePackSource) (new ResourcePackSourceVanilla())); - this.resourcePackFolder = new ResourcePackSourceFolder(new File(file, "datapacks")); - // CraftBukkit start - bukkitDataPackFolder = new File(new File(file, "datapacks"), "bukkit"); - if (!bukkitDataPackFolder.exists()) { - bukkitDataPackFolder.mkdirs(); - } - File mcMeta = new File(bukkitDataPackFolder, "pack.mcmeta"); - try { - com.google.common.io.Files.write("{\n" - + " \"pack\": {\n" - + " \"description\": \"Data pack for resources provided by Bukkit plugins\",\n" - + " \"pack_format\": " + SharedConstants.a().getPackVersion() + "\n" - + " }\n" - + "}\n", mcMeta, com.google.common.base.Charsets.UTF_8); - } catch (IOException ex) { - throw new RuntimeException("Could not initialize Bukkit datapack", ex); - } - // CraftBukkit end - this.resourcePackRepository.a((ResourcePackSource) this.resourcePackFolder); - this.resourcePackRepository.a(); - List list = Lists.newArrayList(); - Iterator iterator = worlddata.O().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - ResourcePackLoader resourcepackloader = this.resourcePackRepository.a(s); - - if (resourcepackloader != null) { - list.add(resourcepackloader); - } else { - MinecraftServer.LOGGER.warn("Missing data pack {}", s); - } - } - - this.resourcePackRepository.a((Collection) list); - this.b(worlddata); - } - - // CraftBukkit start - public void loadSpawn(WorldLoadListener worldloadlistener, WorldServer worldserver) { - if (!worldserver.getWorld().getKeepSpawnInMemory()) { - return; - } - - this.b((IChatBaseComponent) (new ChatMessage("menu.generatingTerrain", new Object[0]))); - // WorldServer worldserver = this.getWorldServer(DimensionManager.OVERWORLD); - this.forceTicks = true; - // CraftBukkit end - - // Paper start - configurable spawn reason - int radiusBlocks = worldserver.paperConfig.keepLoadedRange; - int radiusChunks = radiusBlocks / 16 + ((radiusBlocks & 15) != 0 ? 1 : 0); - int totalChunks = ((radiusChunks) * 2 + 1); - totalChunks *= totalChunks; - worldloadlistener.setChunkRadius(radiusBlocks / 16); - // Paper end - - MinecraftServer.LOGGER.info("Preparing start region for dimension '{}'/{}", worldserver.getWorldData().getName(), DimensionManager.a(worldserver.worldProvider.getDimensionManager().getType())); // CraftBukkit - BlockPosition blockposition = worldserver.getSpawn(); - - worldloadlistener.a(new ChunkCoordIntPair(blockposition)); - ChunkProviderServer chunkproviderserver = worldserver.getChunkProvider(); - - chunkproviderserver.getLightEngine().a(500); - this.nextTick = SystemUtils.getMonotonicMillis(); - // Paper start - Configurable spawn radius - if (worldserver.keepSpawnInMemory) { - worldserver.addTicketsForSpawn(radiusBlocks, blockposition); - - // we use a getChunk loop since we don't need to worry about what some plugin does to keepSpawnInMemory - // or the spawn radius while we are loading - // just keep in mind too that executeModerately will handle player network queue (i.e commands) - int centerX = blockposition.getX() >> 4; - int centerZ = blockposition.getZ() >> 4; - radiusChunks += 2; // we need to load radius +2 to get the chunks in ticking level - for (int xoff = -radiusChunks; xoff <= radiusChunks; ++xoff) { - for (int zoff = -radiusChunks; zoff <= radiusChunks; ++zoff) { - worldserver.getChunkAt(centerX + xoff, centerZ + zoff); - } - } - } - // Paper end - LOGGER.info("Loaded " + chunkproviderserver.b() + " spawn chunks for world " + worldserver.getWorldData().getName()); // Paper - - // CraftBukkit start - // this.nextTick = SystemUtils.getMonotonicMillis() + 10L; - this.executeModerately(); - // Iterator iterator = DimensionManager.a().iterator(); - if (true) { - DimensionManager dimensionmanager = worldserver.worldProvider.getDimensionManager(); - ForcedChunk forcedchunk = (ForcedChunk) worldserver.getWorldPersistentData().b(ForcedChunk::new, "chunks"); - // CraftBukkit end - - if (forcedchunk != null) { - WorldServer worldserver1 = this.getWorldServer(dimensionmanager); - LongIterator longiterator = forcedchunk.a().iterator(); - - while (longiterator.hasNext()) { - long i = longiterator.nextLong(); - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i); - - worldserver1.getChunkProvider().a(chunkcoordintpair, true); - } - } - } - - // CraftBukkit start - // this.nextTick = SystemUtils.getMonotonicMillis() + 10L; - this.executeModerately(); - // CraftBukkit end - worldloadlistener.b(); - chunkproviderserver.getLightEngine().a(5); - - // CraftBukkit start - this.forceTicks = false; - // CraftBukkit end - } - - protected void a(String s, WorldNBTStorage worldnbtstorage) { - File file = new File(worldnbtstorage.getDirectory(), "resources.zip"); - - if (file.isFile()) { - try { - this.setResourcePack("level://" + URLEncoder.encode(s, StandardCharsets.UTF_8.toString()) + "/" + "resources.zip", ""); - } catch (UnsupportedEncodingException unsupportedencodingexception) { - MinecraftServer.LOGGER.warn("Something went wrong url encoding {}", s); - } - } - - } - - public abstract boolean getGenerateStructures(); - - public abstract EnumGamemode getGamemode(); - - public abstract EnumDifficulty getDifficulty(); - - public abstract boolean isHardcore(); - - public abstract int j(); - - public abstract int k(); - - public abstract boolean l(); - - public boolean saveChunks(boolean flag, boolean flag1, boolean flag2) { - boolean flag3 = false; - - for (Iterator iterator = this.getWorlds().iterator(); iterator.hasNext(); flag3 = true) { - WorldServer worldserver = (WorldServer) iterator.next(); - - if (!flag) { - MinecraftServer.LOGGER.info("Saving chunks for level '{}'/{}", worldserver.getWorldData().getName(), DimensionManager.a(worldserver.worldProvider.getDimensionManager())); - } - - try { - worldserver.save((IProgressUpdate) null, flag1, worldserver.savingDisabled && !flag2); - } catch (ExceptionWorldConflict exceptionworldconflict) { - MinecraftServer.LOGGER.warn(exceptionworldconflict.getMessage()); - } - } - - // CraftBukkit start - moved to WorldServer.save - /* - WorldServer worldserver1 = this.getWorldServer(DimensionManager.OVERWORLD); - WorldData worlddata = worldserver1.getWorldData(); - - worldserver1.getWorldBorder().a(worlddata); - worlddata.c(this.getBossBattleCustomData().c()); - worldserver1.getDataManager().saveWorldData(worlddata, this.getPlayerList().r()); - */ - // CraftBukkit end - return flag3; - } - - @Override - public void close() { - this.stop(); - } - - // CraftBukkit start - private boolean hasStopped = false; - private final Object stopLock = new Object(); - public final boolean hasStopped() { - synchronized (stopLock) { - return hasStopped; - } - } - // CraftBukkit end - - protected void stop() { - // CraftBukkit start - prevent double stopping on multiple threads - synchronized(stopLock) { - if (hasStopped) return; - hasStopped = true; - } - // CraftBukkit end - MinecraftServer.LOGGER.info("Stopping server"); - MinecraftTimings.stopServer(); // Paper - // CraftBukkit start - if (this.server != null) { - this.server.disablePlugins(); - } - // CraftBukkit end - if (this.getServerConnection() != null) { - this.getServerConnection().b(); - } - - if (this.playerList != null) { - MinecraftServer.LOGGER.info("Saving players"); - this.playerList.savePlayers(); - this.playerList.shutdown(this.isRestarting); // Paper - try { Thread.sleep(100); } catch (InterruptedException ex) {} // CraftBukkit - SPIGOT-625 - give server at least a chance to send packets - } - - MinecraftServer.LOGGER.info("Saving worlds"); - Iterator iterator = this.getWorlds().iterator(); - - WorldServer worldserver; - - while (iterator.hasNext()) { - worldserver = (WorldServer) iterator.next(); - if (worldserver != null) { - worldserver.savingDisabled = false; - } - } - - this.saveChunks(false, true, false); - iterator = this.getWorlds().iterator(); - - while (iterator.hasNext()) { - worldserver = (WorldServer) iterator.next(); - if (worldserver != null) { - try { - worldserver.close(); - } catch (IOException ioexception) { - MinecraftServer.LOGGER.error("Exception closing the level", ioexception); - } - } - } - - if (this.snooper.d()) { - this.snooper.e(); - } - - // Spigot start - if (org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly) { - LOGGER.info("Saving usercache.json"); - this.getUserCache().c(false); // Paper - } - // Spigot end - com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.close(true, true); // Paper - } - - public String getServerIp() { - return this.serverIp; - } - - public void b(String s) { - this.serverIp = s; - } - - public boolean isRunning() { - return this.isRunning; - } - - // Paper start - allow passing of the intent to restart - public void safeShutdown(boolean flag) { - this.safeShutdown(flag, false); - } - public void safeShutdown(boolean flag, boolean isRestarting) { - this.isRunning = false; - this.isRestarting = isRestarting; - if (flag) { - try { - this.serverThread.join(); - } catch (InterruptedException interruptedexception) { - MinecraftServer.LOGGER.error("Error while shutting down", interruptedexception); - } - } - - } - // Paper end - - // Spigot Start - private static double calcTps(double avg, double exp, double tps) - { - return ( avg * exp ) + ( tps * ( 1 - exp ) ); - } - - // Paper start - Further improve server tick loop - private static final long SEC_IN_NANO = 1000000000; - private static final long MAX_CATCHUP_BUFFER = TICK_TIME * TPS * 60L; - private long lastTick = 0; - private long catchupTime = 0; - public final RollingAverage tps1 = new RollingAverage(60); - public final RollingAverage tps5 = new RollingAverage(60 * 5); - public final RollingAverage tps15 = new RollingAverage(60 * 15); - - 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(); - } - } - private static final java.math.BigDecimal TPS_BASE = new java.math.BigDecimal(1E9).multiply(new java.math.BigDecimal(SAMPLE_INTERVAL)); - // Paper End - // Spigot End - - public void run() { - try { - if (this.init()) { - this.nextTick = SystemUtils.getMonotonicMillis(); - this.serverPing.setMOTD(new ChatComponentText(this.motd)); - this.serverPing.setServerInfo(new ServerPing.ServerData(SharedConstants.a().getName(), SharedConstants.a().getProtocolVersion())); - this.a(this.serverPing); - - // Spigot start - org.spigotmc.WatchdogThread.hasStarted = true; // Paper - Arrays.fill( recentTps, 20 ); - long start = System.nanoTime(), curTime, tickSection = start; // Paper - Further improve server tick loop - lastTick = start - TICK_TIME; // Paper - while (this.isRunning) { - long i = ((curTime = System.nanoTime()) / (1000L * 1000L)) - this.nextTick; // Paper - - if (i > 5000L && this.nextTick - this.lastOverloadTime >= 30000L) { // CraftBukkit - long j = i / 50L; - - if (server.getWarnOnOverload()) // CraftBukkit - MinecraftServer.LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", i, j); - this.nextTick += j * 50L; - this.lastOverloadTime = this.nextTick; - } - - if ( ++MinecraftServer.currentTick % 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 - recentTps[0] = tps1.getAverage(); - recentTps[1] = tps5.getAverage(); - recentTps[2] = tps15.getAverage(); - // Paper end - tickSection = curTime; - } - // Spigot end - - //MinecraftServer.currentTick = (int) (System.currentTimeMillis() / 50); // CraftBukkit // Paper - don't overwrite current tick time - lastTick = curTime; - this.nextTick += 50L; - if (this.T) { - this.T = false; - this.methodProfiler.d().d(); - } - - this.methodProfiler.a(); - this.methodProfiler.enter("tick"); - this.a(this::canSleepForTick); - this.methodProfiler.exitEnter("nextTickWait"); - this.ac = true; - this.ab = Math.max(SystemUtils.getMonotonicMillis() + 50L, this.nextTick); - this.sleepForTick(); - this.methodProfiler.exit(); - this.methodProfiler.b(); - this.hasTicked = true; - } - } else { - this.a((CrashReport) null); - } - } catch (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.t(), "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); - } finally { - try { - org.spigotmc.WatchdogThread.doStop(); - this.isStopped = true; - this.stop(); - } catch (Throwable throwable1) { - MinecraftServer.LOGGER.error("Exception stopping the server", throwable1); - } finally { - // CraftBukkit start - Restore terminal to original settings - try { - net.minecrell.terminalconsole.TerminalConsoleAppender.close(); // Paper - Use TerminalConsoleAppender - } catch (Exception ignored) { - } - // CraftBukkit end - this.exit(); - } - - } - - } - - private boolean canSleepForTick() { - // CraftBukkit start - return this.forceTicks || this.isEntered() || SystemUtils.getMonotonicMillis() < (this.ac ? this.ab : this.nextTick); - } - - // Paper start - private boolean canOversleep() { - return this.hasExecutedTask() && SystemUtils.getMonotonicMillis() < this.getTickOversleepMaxTime(); - } - - private boolean canSleepForTickNoOversleep() { - return this.forceTicks || this.isEntered() || SystemUtils.getMonotonicMillis() < this.nextTick; - } - // Paper end - - private void executeModerately() { - this.executeAll(); - java.util.concurrent.locks.LockSupport.parkNanos("executing tasks", 1000L); - } - // CraftBukkit end - - protected void sleepForTick() { - //this.executeAll(); // Paper - move this into the tick method for timings - this.awaitTasks(() -> { - return !this.canSleepForTickNoOversleep(); // Paper - move oversleep into full server tick - }); - } - - @Override - protected TickTask postToMainThread(Runnable runnable) { - return new TickTask(this.ticks, runnable); - } - - protected boolean canExecute(TickTask ticktask) { - return ticktask.a() + 3 < this.ticks || this.canSleepForTick(); - } - - @Override - public boolean executeNext() { - boolean flag = this.aX(); - - this.ac = flag; - return flag; - } - - private boolean aX() { - if (super.executeNext()) { - return true; - } else { - if (this.canSleepForTick()) { - Iterator iterator = this.getWorlds().iterator(); - - while (iterator.hasNext()) { - WorldServer worldserver = (WorldServer) iterator.next(); - - if (worldserver.getChunkProvider().runTasks()) { - return true; - } - } - } - - return false; - } - } - - public void a(ServerPing serverping) { - File file = this.d("server-icon.png"); - - if (!file.exists()) { - file = this.getConvertable().b(this.getWorld(), "icon.png"); - } - - if (file.isFile()) { - ByteBuf bytebuf = Unpooled.buffer(); - - try { - BufferedImage bufferedimage = ImageIO.read(file); - - Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]); - Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]); - ImageIO.write(bufferedimage, "PNG", new ByteBufOutputStream(bytebuf)); - ByteBuffer bytebuffer = Base64.getEncoder().encode(bytebuf.nioBuffer()); - - serverping.setFavicon("data:image/png;base64," + StandardCharsets.UTF_8.decode(bytebuffer)); - } catch (Exception exception) { - MinecraftServer.LOGGER.error("Couldn't load server icon", exception); - } finally { - bytebuf.release(); - } - } - - } - - public File t() { - return new File("."); - } - - protected void a(CrashReport crashreport) {} - - protected void exit() {} - - protected void a(BooleanSupplier booleansupplier) { - co.aikar.timings.TimingsManager.FULL_SERVER_TICK.startTiming(); // Paper - // Paper start - move oversleep into full server tick - MinecraftTimings.serverOversleep.startTiming(); - this.awaitTasks(() -> { - return !this.canOversleep(); - }); - MinecraftTimings.serverOversleep.stopTiming(); - // Paper end - this.slackActivityAccountant.tickStarted(); // Spigot - long i = SystemUtils.getMonotonicNanos(); - new com.destroystokyo.paper.event.server.ServerTickStartEvent(this.ticks+1).callEvent(); // Paper - - ++this.ticks; - this.b(booleansupplier); - if (i - this.Z >= 5000000000L) { - this.Z = i; - this.serverPing.setPlayerSample(new ServerPing.ServerPingPlayerSample(this.getMaxPlayers(), this.getPlayerCount())); - GameProfile[] agameprofile = new GameProfile[Math.min(this.getPlayerCount(), org.spigotmc.SpigotConfig.playerSample)]; // Paper - int j = MathHelper.nextInt(this.q, 0, this.getPlayerCount() - agameprofile.length); - - for (int k = 0; k < agameprofile.length; ++k) { - agameprofile[k] = ((EntityPlayer) this.playerList.getPlayers().get(j + k)).getProfile(); - } - - Collections.shuffle(Arrays.asList(agameprofile)); - this.serverPing.b().a(agameprofile); - } - - //if (autosavePeriod > 0 && this.ticks % autosavePeriod == 0) { // CraftBukkit // Paper - move down - //MinecraftServer.LOGGER.debug("Autosave started"); // Paper - serverAutoSave = (autosavePeriod > 0 && this.ticks % autosavePeriod == 0); // Paper - this.methodProfiler.enter("save"); - if (autosavePeriod > 0 && this.ticks % autosavePeriod == 0) { // Paper - this.playerList.savePlayers(); - }// Paper - // Paper start - for (WorldServer world : getWorlds()) { - if (world.paperConfig.autoSavePeriod > 0) { - try { - world.saveIncrementally(serverAutoSave); - } catch (ExceptionWorldConflict exceptionWorldConflict) { - MinecraftServer.LOGGER.warn(exceptionWorldConflict.getMessage()); - } - } - } - // Paper end - - this.methodProfiler.exit(); - //MinecraftServer.LOGGER.debug("Autosave finished"); // Paper - //} // Paper - - this.methodProfiler.enter("snooper"); - if (((DedicatedServer) this).getDedicatedServerProperties().snooperEnabled && !this.snooper.d() && this.ticks > 100) { // Spigot - this.snooper.a(); - } - - if (((DedicatedServer) this).getDedicatedServerProperties().snooperEnabled && this.ticks % 6000 == 0) { // Spigot - this.snooper.b(); - } - - this.methodProfiler.exit(); - this.methodProfiler.enter("tallying"); - long l = this.f[this.ticks % 100] = SystemUtils.getMonotonicNanos() - i; - - this.at = this.at * 0.8F + (float) l / 1000000.0F * 0.19999999F; - long i1 = SystemUtils.getMonotonicNanos(); - - this.ap.a(i1 - i); - this.methodProfiler.exit(); - org.spigotmc.WatchdogThread.tick(); // Spigot - this.slackActivityAccountant.tickEnded(l); // Spigot - // Paper start - move executeAll() into full server tick timing - try (co.aikar.timings.Timing ignored = MinecraftTimings.processTasksTimer.startTiming()) { - this.executeAll(); - } - // Paper end - // Paper start - long endTime = System.nanoTime(); - long remaining = (TICK_TIME - (endTime - lastTick)) - catchupTime; - new com.destroystokyo.paper.event.server.ServerTickEndEvent(this.ticks, ((double)(endTime - lastTick) / 1000000D), remaining).callEvent(); - // Paper end - co.aikar.timings.TimingsManager.FULL_SERVER_TICK.stopTiming(); // Paper - } - - protected void b(BooleanSupplier booleansupplier) { - MinecraftTimings.bukkitSchedulerTimer.startTiming(); // Spigot // Paper - this.server.getScheduler().mainThreadHeartbeat(this.ticks); // CraftBukkit - MinecraftTimings.bukkitSchedulerTimer.stopTiming(); // Spigot // Paper - this.methodProfiler.enter("commandFunctions"); - MinecraftTimings.commandFunctionsTimer.startTiming(); // Spigot // Paper - this.getFunctionData().tick(); - MinecraftTimings.commandFunctionsTimer.stopTiming(); // Spigot // Paper - this.methodProfiler.exitEnter("levels"); - Iterator iterator = this.getWorlds().iterator(); - - // CraftBukkit start - // Run tasks that are waiting on processing - MinecraftTimings.processQueueTimer.startTiming(); // Spigot - while (!processQueue.isEmpty()) { - processQueue.remove().run(); - } - MinecraftTimings.processQueueTimer.stopTiming(); // Spigot - - MinecraftTimings.timeUpdateTimer.startTiming(); // Spigot // Paper - // Send time updates to everyone, it will get the right time from the world the player is in. - // Paper start - optimize time updates - for (final WorldServer world : this.getWorlds()) { - final boolean doDaylight = world.getGameRules().getBoolean(GameRules.DO_DAYLIGHT_CYCLE); - final long dayTime = world.getDayTime(); - long worldTime = world.getTime(); - final PacketPlayOutUpdateTime worldPacket = new PacketPlayOutUpdateTime(worldTime, dayTime, doDaylight); - for (EntityHuman entityhuman : world.getPlayers()) { - if (!(entityhuman instanceof EntityPlayer) || (ticks + entityhuman.getId()) % 20 != 0) { - continue; - } - EntityPlayer entityplayer = (EntityPlayer) entityhuman; - long playerTime = entityplayer.getPlayerTime(); - PacketPlayOutUpdateTime packet = (playerTime == dayTime) ? worldPacket : - new PacketPlayOutUpdateTime(worldTime, playerTime, doDaylight); - entityplayer.playerConnection.sendPacket(packet); // Add support for per player time - } - } - // Paper end - MinecraftTimings.timeUpdateTimer.stopTiming(); // Spigot // Paper - - while (iterator.hasNext()) { - WorldServer worldserver = (WorldServer) iterator.next(); - - worldserver.hasPhysicsEvent = org.bukkit.event.block.BlockPhysicsEvent.getHandlerList().getRegisteredListeners().length > 0; // Paper - TileEntityHopper.skipHopperEvents = worldserver.paperConfig.disableHopperMoveEvents || org.bukkit.event.inventory.InventoryMoveItemEvent.getHandlerList().getRegisteredListeners().length == 0; // Paper - if (true || worldserver.worldProvider.getDimensionManager() == DimensionManager.OVERWORLD || this.getAllowNether()) { // CraftBukkit - this.methodProfiler.a(() -> { - return worldserver.getWorldData().getName() + " " + IRegistry.DIMENSION_TYPE.getKey(worldserver.worldProvider.getDimensionManager()); - }); - /* Drop global time updates - if (this.ticks % 20 == 0) { - this.methodProfiler.enter("timeSync"); - this.playerList.a((Packet) (new PacketPlayOutUpdateTime(worldserver.getTime(), worldserver.getDayTime(), worldserver.getGameRules().getBoolean(GameRules.DO_DAYLIGHT_CYCLE))), worldserver.worldProvider.getDimensionManager()); - this.methodProfiler.exit(); - } - // CraftBukkit end */ - - this.methodProfiler.enter("tick"); - - try { - worldserver.timings.doTick.startTiming(); // Spigot - worldserver.doTick(booleansupplier); - worldserver.timings.doTick.stopTiming(); // Spigot - } catch (Throwable throwable) { - // Spigot Start - CrashReport crashreport; - try { - crashreport = CrashReport.a(throwable, "Exception ticking world"); - } catch (Throwable t) { - throw new RuntimeException("Error generating crash report", t); - } - // Spigot End - - worldserver.a(crashreport); - throw new ReportedException(crashreport); - } - - this.methodProfiler.exit(); - this.methodProfiler.exit(); - worldserver.explosionDensityCache.clear(); // Paper - Optimize explosions - } - } - - this.methodProfiler.exitEnter("connection"); - MinecraftTimings.connectionTimer.startTiming(); // Spigot - this.getServerConnection().c(); - MinecraftTimings.connectionTimer.stopTiming(); // Spigot - this.methodProfiler.exitEnter("players"); - MinecraftTimings.playerListTimer.startTiming(); // Spigot // Paper - this.playerList.tick(); - MinecraftTimings.playerListTimer.stopTiming(); // Spigot // Paper - this.methodProfiler.exitEnter("server gui refresh"); - - MinecraftTimings.tickablesTimer.startTiming(); // Spigot // Paper - for (int i = 0; i < this.tickables.size(); ++i) { - ((Runnable) this.tickables.get(i)).run(); - } - MinecraftTimings.tickablesTimer.stopTiming(); // Spigot // Paper - - this.methodProfiler.exit(); - } - - public boolean getAllowNether() { - return true; - } - - public void b(Runnable runnable) { - this.tickables.add(runnable); - } - - public static void main(final OptionSet optionset) { // CraftBukkit - replaces main(String[] astring) - /* CraftBukkit start - Replace everything - OptionParser optionparser = new OptionParser(); - OptionSpec optionspec = optionparser.accepts("nogui"); - OptionSpec optionspec1 = optionparser.accepts("initSettings", "Initializes 'server.properties' and 'eula.txt', then quits"); - OptionSpec optionspec2 = optionparser.accepts("demo"); - OptionSpec optionspec3 = optionparser.accepts("bonusChest"); - OptionSpec optionspec4 = optionparser.accepts("forceUpgrade"); - OptionSpec optionspec5 = optionparser.accepts("eraseCache"); - OptionSpec optionspec6 = optionparser.accepts("help").forHelp(); - OptionSpec optionspec7 = optionparser.accepts("singleplayer").withRequiredArg(); - OptionSpec optionspec8 = optionparser.accepts("universe").withRequiredArg().defaultsTo(".", new String[0]); - OptionSpec optionspec9 = optionparser.accepts("world").withRequiredArg(); - OptionSpec optionspec10 = optionparser.accepts("port").withRequiredArg().ofType(Integer.class).defaultsTo(-1, new Integer[0]); - OptionSpec optionspec11 = optionparser.accepts("serverId").withRequiredArg(); - NonOptionArgumentSpec nonoptionargumentspec = optionparser.nonOptions(); - - try { - OptionSet optionset = optionparser.parse(astring); - - if (optionset.has(optionspec6)) { - optionparser.printHelpOn(System.err); - return; - } - */ // CraftBukkit end - - try { - java.nio.file.Path java_nio_file_path = Paths.get("server.properties"); - DedicatedServerSettings dedicatedserversettings = new DedicatedServerSettings(optionset); // CraftBukkit - CLI argument support - - dedicatedserversettings.save(); - java.nio.file.Path java_nio_file_path1 = Paths.get("eula.txt"); - EULA eula = new EULA(java_nio_file_path1); - - if (optionset.has("initSettings")) { // CraftBukkit - MinecraftServer.LOGGER.info("Initialized '" + java_nio_file_path.toAbsolutePath().toString() + "' and '" + java_nio_file_path1.toAbsolutePath().toString() + "'"); - return; - } - - // Spigot Start - boolean eulaAgreed = Boolean.getBoolean( "com.mojang.eula.agree" ); - if ( eulaAgreed ) - { - System.err.println( "You have used the Spigot command line EULA agreement flag." ); - System.err.println( "By using this setting you are indicating your agreement to Mojang's EULA (https://account.mojang.com/documents/minecraft_eula)." ); - System.err.println( "If you do not agree to the above EULA please stop your server and remove this flag immediately." ); - } - // Spigot End - if (!eula.a() && !eulaAgreed) { // Spigot - MinecraftServer.LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info."); - return; - } - - DispenserRegistry.init(); - DispenserRegistry.c(); - String s = "."; // PAIL? - YggdrasilAuthenticationService yggdrasilauthenticationservice = new com.destroystokyo.paper.profile.PaperAuthenticationService(Proxy.NO_PROXY, UUID.randomUUID().toString()); // Paper - MinecraftSessionService minecraftsessionservice = yggdrasilauthenticationservice.createMinecraftSessionService(); - GameProfileRepository gameprofilerepository = yggdrasilauthenticationservice.createProfileRepository(); - UserCache usercache = new UserCache(gameprofilerepository, new File(s, MinecraftServer.b.getName())); - String s1 = (String) Optional.ofNullable(optionset.valueOf("world")).orElse(dedicatedserversettings.getProperties().levelName); - final DedicatedServer dedicatedserver = new DedicatedServer(optionset, dedicatedserversettings, DataConverterRegistry.a(), yggdrasilauthenticationservice, minecraftsessionservice, gameprofilerepository, usercache, WorldLoadListenerLogger::new, s1); - - /* CraftBukkit start - dedicatedserver.i((String) optionset.valueOf(optionspec7)); - dedicatedserver.setPort((Integer) optionset.valueOf(optionspec10)); - dedicatedserver.e(optionset.has(optionspec2)); - dedicatedserver.f(optionset.has(optionspec3)); - dedicatedserver.setForceUpgrade(optionset.has(optionspec4)); - dedicatedserver.setEraseCache(optionset.has(optionspec5)); - dedicatedserver.c((String) optionset.valueOf(optionspec11)); - boolean flag = !optionset.has(optionspec) && !optionset.valuesOf(nonoptionargumentspec).contains("nogui"); - - if (flag && !GraphicsEnvironment.isHeadless()) { - dedicatedserver.aZ(); - } - - dedicatedserver.startServerThread(); - Thread thread = new Thread("Server Shutdown Thread") { - public void run() { - dedicatedserver.safeShutdown(true); - } - }; - - thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(MinecraftServer.LOGGER)); - Runtime.getRuntime().addShutdownHook(thread); - */ - - if (optionset.has("port")) { - int port = (Integer) optionset.valueOf("port"); - if (port > 0) { - dedicatedserver.setPort(port); - } - } - - if (optionset.has("universe")) { - dedicatedserver.universe = (File) optionset.valueOf("universe"); - } - - if (optionset.has("forceUpgrade")) { - dedicatedserver.setForceUpgrade(true); - } - - if (optionset.has("eraseCache")) { - dedicatedserver.setEraseCache(true); - } - - dedicatedserver.serverThread.start(); - // CraftBukkit end - } catch (Exception exception) { - MinecraftServer.LOGGER.fatal("Failed to start the minecraft server", exception); - } - - } - - protected void c(String s) { - this.av = s; - } - - protected void setForceUpgrade(boolean flag) { - this.forceUpgrade = flag; - } - - protected void setEraseCache(boolean flag) { - this.eraseCache = flag; - } - - public void startServerThread() { - /* CraftBukkit start - prevent abuse - this.serverThread.start(); - // CraftBukkit end */ - } - - public File d(String s) { - return new File(this.t(), s); - } - - public void info(String s) { - MinecraftServer.LOGGER.info(s); - } - - public void warning(String s) { - MinecraftServer.LOGGER.warn(s); - } - - public WorldServer getWorldServer(DimensionManager dimensionmanager) { - return (WorldServer) this.worldServer.get(dimensionmanager); - } - - public Iterable getWorlds() { - return this.worldServer.values(); - } - - public String getVersion() { - return SharedConstants.a().getName(); - } - - public int getPlayerCount() { - return this.playerList.getPlayerCount(); - } - - public int getMaxPlayers() { - return this.playerList.getMaxPlayers(); - } - - public String[] getPlayers() { - return this.playerList.e(); - } - - public boolean isDebugging() { - return false; - } - - 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 "Akarin"; // Akarin - Akarin //Paper - Paper > // Spigot - Spigot > // CraftBukkit - cb > vanilla! - } - - public CrashReport b(CrashReport crashreport) { - if (this.playerList != null) { - crashreport.g().a("Player Count", () -> { - return this.playerList.getPlayerCount() + " / " + this.playerList.getMaxPlayers() + "; " + this.playerList.getPlayers(); - }); - } - - crashreport.g().a("Data Packs", () -> { - StringBuilder stringbuilder = new StringBuilder(); - Iterator iterator = this.resourcePackRepository.d().iterator(); - - while (iterator.hasNext()) { - ResourcePackLoader resourcepackloader = (ResourcePackLoader) iterator.next(); - - if (stringbuilder.length() > 0) { - stringbuilder.append(", "); - } - - stringbuilder.append(resourcepackloader.e()); - if (!resourcepackloader.c().a()) { - stringbuilder.append(" (incompatible)"); - } - } - - return stringbuilder.toString(); - }); - if (this.av != null) { - crashreport.g().a("Server Id", () -> { - return this.av; - }); - } - - return crashreport; - } - - public boolean F() { - return true; // CraftBukkit - } - - @Override - public void sendMessage(IChatBaseComponent ichatbasecomponent) { - MinecraftServer.LOGGER.info(org.bukkit.craftbukkit.util.CraftChatMessage.fromComponent(ichatbasecomponent, net.minecraft.server.EnumChatFormat.WHITE));// Paper - Log message with colors - } - - public KeyPair getKeyPair() { - return this.I; - } - - public int getPort() { - return this.serverPort; - } - - public void setPort(int i) { - this.serverPort = i; - } - - public String getSinglePlayerName() { - return this.J; - } - - public void i(String s) { - this.J = s; - } - - public boolean isEmbeddedServer() { - return this.J != null; - } - - public String getWorld() { - return this.K; - } - - public void a(KeyPair keypair) { - this.I = keypair; - } - - public void a(EnumDifficulty enumdifficulty, boolean flag) { - Iterator iterator = this.getWorlds().iterator(); - - while (iterator.hasNext()) { - WorldServer worldserver = (WorldServer) iterator.next(); - WorldData worlddata = worldserver.getWorldData(); - - if (flag || !worlddata.isDifficultyLocked()) { - if (worlddata.isHardcore()) { - worlddata.setDifficulty(EnumDifficulty.HARD); - worldserver.setSpawnFlags(true, true); - } else if (this.isEmbeddedServer()) { - worlddata.setDifficulty(enumdifficulty); - worldserver.setSpawnFlags(worldserver.getDifficulty() != EnumDifficulty.PEACEFUL, true); - } else { - worlddata.setDifficulty(enumdifficulty); - worldserver.setSpawnFlags(this.getSpawnMonsters(), this.spawnAnimals); - } - } - } - - this.getPlayerList().getPlayers().forEach(this::a); - } - - public void d(boolean flag) { - Iterator iterator = this.getWorlds().iterator(); - - while (iterator.hasNext()) { - WorldServer worldserver = (WorldServer) iterator.next(); - WorldData worlddata = worldserver.getWorldData(); - - worlddata.e(flag); - } - - this.getPlayerList().getPlayers().forEach(this::a); - } - - private void a(EntityPlayer entityplayer) { - WorldData worlddata = entityplayer.getWorldServer().getWorldData(); - - entityplayer.playerConnection.sendPacket(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); - } - - protected boolean getSpawnMonsters() { - return true; - } - - public boolean isDemoMode() { - return this.demoMode; - } - - public void e(boolean flag) { - this.demoMode = flag; - } - - public void f(boolean flag) { - this.bonusChest = flag; - } - - public Convertable getConvertable() { - return this.convertable; - } - - 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; - } - - @Override - public void a(MojangStatisticsGenerator mojangstatisticsgenerator) { - mojangstatisticsgenerator.a("whitelist_enabled", false); - mojangstatisticsgenerator.a("whitelist_count", 0); - if (this.playerList != null) { - mojangstatisticsgenerator.a("players_current", this.getPlayerCount()); - mojangstatisticsgenerator.a("players_max", this.getMaxPlayers()); - mojangstatisticsgenerator.a("players_seen", this.getWorldServer(DimensionManager.OVERWORLD).getDataManager().getSeenPlayers().length); - } - - mojangstatisticsgenerator.a("uses_auth", this.onlineMode); - mojangstatisticsgenerator.a("gui_state", this.ai() ? "enabled" : "disabled"); - mojangstatisticsgenerator.a("run_time", (SystemUtils.getMonotonicMillis() - mojangstatisticsgenerator.g()) / 60L * 1000L); - mojangstatisticsgenerator.a("avg_tick_ms", (int) (MathHelper.a(this.f) * 1.0E-6D)); - int i = 0; - Iterator iterator = this.getWorlds().iterator(); - - while (iterator.hasNext()) { - WorldServer worldserver = (WorldServer) iterator.next(); - - if (worldserver != null) { - WorldData worlddata = worldserver.getWorldData(); - - mojangstatisticsgenerator.a("world[" + i + "][dimension]", worldserver.worldProvider.getDimensionManager()); - mojangstatisticsgenerator.a("world[" + i + "][mode]", worlddata.getGameType()); - mojangstatisticsgenerator.a("world[" + i + "][difficulty]", worldserver.getDifficulty()); - mojangstatisticsgenerator.a("world[" + i + "][hardcore]", worlddata.isHardcore()); - mojangstatisticsgenerator.a("world[" + i + "][generator_name]", worlddata.getType().name()); - mojangstatisticsgenerator.a("world[" + i + "][generator_version]", worlddata.getType().getVersion()); - mojangstatisticsgenerator.a("world[" + i + "][height]", this.G); - mojangstatisticsgenerator.a("world[" + i + "][chunks_loaded]", worldserver.getChunkProvider().h()); - ++i; - } - } - - mojangstatisticsgenerator.a("worlds", i); - } - - public abstract boolean S(); - - public boolean getOnlineMode() { - return this.onlineMode; - } - - public void setOnlineMode(boolean flag) { - this.onlineMode = flag; - } - - public boolean U() { - return this.A; - } - - public void h(boolean flag) { - this.A = flag; - } - - public boolean getSpawnAnimals() { - return this.spawnAnimals; - } - - public void setSpawnAnimals(boolean flag) { - this.spawnAnimals = flag; - } - - public boolean getSpawnNPCs() { - return this.spawnNPCs; - } - - public abstract boolean X(); - - public void setSpawnNPCs(boolean flag) { - this.spawnNPCs = flag; - } - - 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 this.G; - } - - public void b(int i) { - this.G = i; - } - - public boolean isStopped() { - return this.isStopped; - } - - public PlayerList getPlayerList() { - return this.playerList; - } - - public void a(PlayerList playerlist) { - this.playerList = playerlist; - } - - public abstract boolean af(); - - public void setGamemode(EnumGamemode enumgamemode) { - Iterator iterator = this.getWorlds().iterator(); - - while (iterator.hasNext()) { - WorldServer worldserver = (WorldServer) iterator.next(); - - worldserver.getWorldData().setGameType(enumgamemode); - } - - } - - @Nullable - public ServerConnection getServerConnection() { - return this.serverConnection == null ? this.serverConnection = new ServerConnection(this) : this.serverConnection; // Spigot - } - - public boolean ai() { - return false; - } - - public abstract boolean a(EnumGamemode enumgamemode, boolean flag, int i); - - public int aj() { - return this.ticks; - } - - public void ak() { - this.T = true; - } - - public int getSpawnProtection() { - return 16; - } - - public boolean a(World world, BlockPosition blockposition, EntityHuman entityhuman) { - return false; - } - - public void setForceGamemode(boolean flag) { - this.U = flag; - } - - public boolean getForceGamemode() { - return this.U; - } - - public int getIdleTimeout() { - return this.H; - } - - public void setIdleTimeout(int i) { - this.H = i; - } - - public final MinecraftSessionService getSessionService() { return this.getMinecraftSessionService(); } // Paper - OBFHELPER - public MinecraftSessionService getMinecraftSessionService() { - return this.minecraftSessionService; - } - - public GameProfileRepository getGameProfileRepository() { - return this.gameProfileRepository; - } - - public UserCache getUserCache() { - return this.userCache; - } - - public ServerPing getServerPing() { - return this.serverPing; - } - - public void invalidatePingSample() { - this.Z = 0L; - } - - public int aw() { - return 29999984; - } - - @Override - public boolean isNotMainThread() { - return super.isNotMainThread() && !this.isStopped(); - } - - @Override - public Thread getThread() { - return this.serverThread; - } - - public int az() { - return 256; - } - - public long aA() { - return this.nextTick; - } - - public DataFixer aB() { - return this.dataConverterManager; - } - - public int a(@Nullable WorldServer worldserver) { - return worldserver != null ? worldserver.getGameRules().getInt(GameRules.SPAWN_RADIUS) : 10; - } - - public AdvancementDataWorld getAdvancementData() { - return this.an; - } - - public CustomFunctionData getFunctionData() { - return this.ao; - } - - public void reload() { - if (!this.isMainThread()) { - this.execute(this::reload); - } else { - this.getPlayerList().savePlayers(); - this.resourcePackRepository.a(); - this.b(this.getWorldServer(DimensionManager.OVERWORLD).getWorldData()); - this.getPlayerList().reload(); - } - } - - private void b(WorldData worlddata) { - List list = Lists.newArrayList(this.resourcePackRepository.d()); - Iterator iterator = this.resourcePackRepository.b().iterator(); - - while (iterator.hasNext()) { - ResourcePackLoader resourcepackloader = (ResourcePackLoader) iterator.next(); - - if (!worlddata.N().contains(resourcepackloader.e()) && !list.contains(resourcepackloader)) { - MinecraftServer.LOGGER.info("Found new data pack {}, loading it automatically", resourcepackloader.e()); - resourcepackloader.h().a(list, resourcepackloader, (resourcepackloader1) -> { - return resourcepackloader1; - }, false); - } - } - - this.resourcePackRepository.a((Collection) list); - List list1 = Lists.newArrayList(); - - this.resourcePackRepository.d().forEach((resourcepackloader1) -> { - list1.add(resourcepackloader1.d()); - }); - CompletableFuture completablefuture = this.ae.a(this.executorService, this, list1, MinecraftServer.i); - - this.awaitTasks(completablefuture::isDone); - - try { - completablefuture.get(); - } catch (Exception exception) { - MinecraftServer.LOGGER.error("Failed to reload data packs", exception); - } - - worlddata.O().clear(); - worlddata.N().clear(); - this.resourcePackRepository.d().forEach((resourcepackloader1) -> { - worlddata.O().add(resourcepackloader1.e()); - }); - this.resourcePackRepository.b().forEach((resourcepackloader1) -> { - if (!this.resourcePackRepository.d().contains(resourcepackloader1)) { - worlddata.N().add(resourcepackloader1.e()); - } - - }); - } - - public void a(CommandListenerWrapper commandlistenerwrapper) { - if (this.aQ()) { - PlayerList playerlist = commandlistenerwrapper.getServer().getPlayerList(); - WhiteList whitelist = playerlist.getWhitelist(); - - if (whitelist.isEnabled()) { - List list = Lists.newArrayList(playerlist.getPlayers()); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - if (!whitelist.isWhitelisted(entityplayer.getProfile())) { - entityplayer.playerConnection.disconnect(new ChatMessage("multiplayer.disconnect.not_whitelisted", new Object[0])); - } - } - - } - } - } - - public IReloadableResourceManager getResourceManager() { - return this.ae; - } - - public ResourcePackRepository getResourcePackRepository() { - return this.resourcePackRepository; - } - - public CommandDispatcher getCommandDispatcher() { - return this.commandDispatcher; - } - - public CommandListenerWrapper getServerCommandListener() { - return new CommandListenerWrapper(this, this.getWorldServer(DimensionManager.OVERWORLD) == null ? Vec3D.a : new Vec3D(this.getWorldServer(DimensionManager.OVERWORLD).getSpawn()), Vec2F.a, this.getWorldServer(DimensionManager.OVERWORLD), 4, "Server", new ChatComponentText("Server"), this, (Entity) null); - } - - @Override - public boolean shouldSendSuccess() { - return true; - } - - @Override - public boolean shouldSendFailure() { - return true; - } - - public CraftingManager getCraftingManager() { - return this.ai; - } - - public TagRegistry getTagRegistry() { - return this.aj; - } - - public ScoreboardServer getScoreboard() { - return this.ak; - } - - public LootTableRegistry getLootTableRegistry() { - return this.am; - } - - public GameRules getGameRules() { - return this.getWorldServer(DimensionManager.OVERWORLD).getGameRules(); - } - - public BossBattleCustomData getBossBattleCustomData() { - return this.al; - } - - public boolean aQ() { - return this.aq; - } - - public void n(boolean flag) { - this.aq = flag; - } - - public float aR() { - return this.at; - } - - public int a(GameProfile gameprofile) { - if (this.getPlayerList().isOp(gameprofile)) { - OpListEntry oplistentry = (OpListEntry) this.getPlayerList().getOPs().get(gameprofile); - - return oplistentry != null ? oplistentry.a() : (this.b(gameprofile) ? 4 : (this.isEmbeddedServer() ? (this.getPlayerList().v() ? 4 : 0) : this.j())); - } else { - return 0; - } - } - - public GameProfiler getMethodProfiler() { - return this.methodProfiler; - } - - public Executor aU() { - return this.executorService; - } - - public abstract boolean b(GameProfile gameprofile); - - public void a(java.nio.file.Path java_nio_file_path) throws IOException { - java.nio.file.Path java_nio_file_path1 = java_nio_file_path.resolve("levels"); - Iterator iterator = this.worldServer.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - MinecraftKey minecraftkey = DimensionManager.a((DimensionManager) entry.getKey()); - java.nio.file.Path java_nio_file_path2 = java_nio_file_path1.resolve(minecraftkey.getNamespace()).resolve(minecraftkey.getKey()); - - Files.createDirectories(java_nio_file_path2); - ((WorldServer) entry.getValue()).a(java_nio_file_path2); - } - - this.d(java_nio_file_path.resolve("gamerules.txt")); - this.e(java_nio_file_path.resolve("classpath.txt")); - this.c(java_nio_file_path.resolve("example_crash.txt")); - this.b(java_nio_file_path.resolve("stats.txt")); - this.f(java_nio_file_path.resolve("threads.txt")); - } - - private void b(java.nio.file.Path java_nio_file_path) throws IOException { - BufferedWriter bufferedwriter = Files.newBufferedWriter(java_nio_file_path); - Throwable throwable = null; - - try { - bufferedwriter.write(String.format("pending_tasks: %d\n", this.be())); - bufferedwriter.write(String.format("average_tick_time: %f\n", this.aR())); - bufferedwriter.write(String.format("tick_times: %s\n", Arrays.toString(this.f))); - bufferedwriter.write(String.format("queue: %s\n", SystemUtils.e())); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (bufferedwriter != null) { - if (throwable != null) { - try { - bufferedwriter.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - bufferedwriter.close(); - } - } - - } - - } - - private void c(java.nio.file.Path java_nio_file_path) throws IOException { - CrashReport crashreport = new CrashReport("Server dump", new Exception("dummy")); - - this.b(crashreport); - BufferedWriter bufferedwriter = Files.newBufferedWriter(java_nio_file_path); - Throwable throwable = null; - - try { - bufferedwriter.write(crashreport.e()); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (bufferedwriter != null) { - if (throwable != null) { - try { - bufferedwriter.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - bufferedwriter.close(); - } - } - - } - - } - - private void d(java.nio.file.Path java_nio_file_path) throws IOException { - BufferedWriter bufferedwriter = Files.newBufferedWriter(java_nio_file_path); - Throwable throwable = null; - - try { - final List list = Lists.newArrayList(); - final GameRules gamerules = this.getGameRules(); - - GameRules.a(new GameRules.GameRuleVisitor() { - @Override - public > void a(GameRules.GameRuleKey gamerules_gamerulekey, GameRules.GameRuleDefinition gamerules_gameruledefinition) { - list.add(String.format("%s=%s\n", gamerules_gamerulekey.a(), gamerules.get(gamerules_gamerulekey).toString())); - } - }); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - - bufferedwriter.write(s); - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (bufferedwriter != null) { - if (throwable != null) { - try { - bufferedwriter.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - bufferedwriter.close(); - } - } - - } - - } - - private void e(java.nio.file.Path java_nio_file_path) throws IOException { - BufferedWriter bufferedwriter = Files.newBufferedWriter(java_nio_file_path); - Throwable throwable = null; - - try { - String s = System.getProperty("java.class.path"); - String s1 = System.getProperty("path.separator"); - Iterator iterator = Splitter.on(s1).split(s).iterator(); - - while (iterator.hasNext()) { - String s2 = (String) iterator.next(); - - bufferedwriter.write(s2); - bufferedwriter.write("\n"); - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (bufferedwriter != null) { - if (throwable != null) { - try { - bufferedwriter.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - bufferedwriter.close(); - } - } - - } - - } - - private void f(java.nio.file.Path java_nio_file_path) throws IOException { - ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] athreadinfo = threadmxbean.dumpAllThreads(true, true); - - Arrays.sort(athreadinfo, Comparator.comparing(ThreadInfo::getThreadName)); - BufferedWriter bufferedwriter = Files.newBufferedWriter(java_nio_file_path); - Throwable throwable = null; - - try { - ThreadInfo[] athreadinfo1 = athreadinfo; - int i = athreadinfo.length; - - for (int j = 0; j < i; ++j) { - ThreadInfo threadinfo = athreadinfo1[j]; - - bufferedwriter.write(threadinfo.toString()); - bufferedwriter.write(10); - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (bufferedwriter != null) { - if (throwable != null) { - try { - bufferedwriter.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - bufferedwriter.close(); - } - } - - } - - } - - // CraftBukkit start - @Override - public boolean isMainThread() { - return super.isMainThread() /*|| this.isStopped()*/; // CraftBukkit - MC-142590 // Paper - causes issues elsewhere - } - - @Deprecated - public static MinecraftServer getServer() { - return SERVER; // Paper - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/MobEffectList.java b/src/main/java/net/minecraft/server/MobEffectList.java deleted file mode 100644 index 233eaf677..000000000 --- a/src/main/java/net/minecraft/server/MobEffectList.java +++ /dev/null @@ -1,178 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import java.util.Iterator; -import java.util.Map; -import java.util.UUID; -import java.util.Map.Entry; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; -// CraftBukkit end - -public class MobEffectList { - - private final Map a = Maps.newHashMap(); - private final MobEffectInfo b; - private final int c; - @Nullable - private String d; - - @Nullable - public static MobEffectList fromId(int i) { - return (MobEffectList) IRegistry.MOB_EFFECT.fromId(i); - } - - public static int getId(MobEffectList mobeffectlist) { - return IRegistry.MOB_EFFECT.a(mobeffectlist); // CraftBukkit - decompile error - } - - protected MobEffectList(MobEffectInfo mobeffectinfo, int i) { - this.b = mobeffectinfo; - this.c = i; - } - - public void tick(EntityLiving entityliving, int i) { - if (this == MobEffects.REGENERATION) { - if (entityliving.getHealth() < entityliving.getMaxHealth()) { - entityliving.heal(1.0F, RegainReason.MAGIC_REGEN); // CraftBukkit - } - } else if (this == MobEffects.POISON) { - if (entityliving.getHealth() > 1.0F) { - entityliving.damageEntity(CraftEventFactory.POISON, 1.0F); // CraftBukkit - DamageSource.MAGIC -> CraftEventFactory.POISON - } - } else if (this == MobEffects.WITHER) { - entityliving.damageEntity(DamageSource.WITHER, 1.0F); - } else if (this == MobEffects.HUNGER && entityliving instanceof EntityHuman) { - ((EntityHuman) entityliving).applyExhaustion(0.005F * (float) (i + 1)); - } else if (this == MobEffects.SATURATION && entityliving instanceof EntityHuman) { - if (!entityliving.world.isClientSide) { - // CraftBukkit start - EntityHuman entityhuman = (EntityHuman) 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); - } - - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutUpdateHealth(((EntityPlayer) entityhuman).getBukkitEntity().getScaledHealth(), entityhuman.getFoodData().foodLevel, entityhuman.getFoodData().saturationLevel)); - // CraftBukkit end - } - } else if ((this != MobEffects.HEAL || entityliving.cC()) && (this != MobEffects.HARM || !entityliving.cC())) { - if (this == MobEffects.HARM && !entityliving.cC() || this == MobEffects.HEAL && entityliving.cC()) { - entityliving.damageEntity(DamageSource.MAGIC, (float) (6 << i)); - } - } else { - entityliving.heal((float) Math.max(4 << i, 0), RegainReason.MAGIC); // CraftBukkit - } - - } - - public void applyInstantEffect(@Nullable Entity entity, @Nullable Entity entity1, EntityLiving entityliving, int i, double d0) { - int j; - - if ((this != MobEffects.HEAL || entityliving.cC()) && (this != MobEffects.HARM || !entityliving.cC())) { - if ((this != MobEffects.HARM || entityliving.cC()) && (this != MobEffects.HEAL || !entityliving.cC())) { - this.tick(entityliving, i); - } else { - j = (int) (d0 * (double) (6 << i) + 0.5D); - if (entity == null) { - entityliving.damageEntity(DamageSource.MAGIC, (float) j); - } else { - entityliving.damageEntity(DamageSource.c(entity, entity1), (float) j); - } - } - } else { - j = (int) (d0 * (double) (4 << i) + 0.5D); - entityliving.heal((float) j, RegainReason.MAGIC); // CraftBukkit - } - - } - - public boolean a(int i, int j) { - int k; - - if (this == MobEffects.REGENERATION) { - k = 50 >> j; - return k > 0 ? i % k == 0 : true; - } else if (this == MobEffects.POISON) { - k = 25 >> j; - return k > 0 ? i % k == 0 : true; - } else if (this == MobEffects.WITHER) { - k = 40 >> j; - return k > 0 ? i % k == 0 : true; - } else { - return this == MobEffects.HUNGER; - } - } - - public boolean isInstant() { - return false; - } - - protected String b() { - if (this.d == null) { - this.d = SystemUtils.a("effect", IRegistry.MOB_EFFECT.getKey(this)); - } - - return this.d; - } - - public String c() { - return this.b(); - } - - public IChatBaseComponent d() { - return new ChatMessage(this.c(), new Object[0]); - } - - public int getColor() { - return this.c; - } - - public MobEffectList a(IAttribute iattribute, String s, double d0, AttributeModifier.Operation attributemodifier_operation) { - AttributeModifier attributemodifier = new AttributeModifier(UUID.fromString(s), this::c, d0, attributemodifier_operation); - - this.a.put(iattribute, attributemodifier); - return this; - } - - public void a(EntityLiving entityliving, AttributeMapBase attributemapbase, int i) { - Iterator iterator = this.a.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - AttributeInstance attributeinstance = attributemapbase.a((IAttribute) entry.getKey()); - - if (attributeinstance != null) { - attributeinstance.removeModifier((AttributeModifier) entry.getValue()); - } - } - - } - - public void b(EntityLiving entityliving, AttributeMapBase attributemapbase, int i) { - Iterator iterator = this.a.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - AttributeInstance attributeinstance = attributemapbase.a((IAttribute) entry.getKey()); - - if (attributeinstance != null) { - AttributeModifier attributemodifier = (AttributeModifier) entry.getValue(); - - attributeinstance.removeModifier(attributemodifier); - attributeinstance.addModifier(new AttributeModifier(attributemodifier.getUniqueId(), this.c() + " " + i, this.a(i, attributemodifier), attributemodifier.getOperation())); - } - } - - } - - public double a(int i, AttributeModifier attributemodifier) { - return attributemodifier.getAmount() * (double) (i + 1); - } -} diff --git a/src/main/java/net/minecraft/server/MobEffects.java b/src/main/java/net/minecraft/server/MobEffects.java deleted file mode 100644 index f5492b08c..000000000 --- a/src/main/java/net/minecraft/server/MobEffects.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.minecraft.server; - -public class MobEffects { - - public static final MobEffectList FASTER_MOVEMENT = a(1, "speed", (new MobEffectList(MobEffectInfo.BENEFICIAL, 8171462)).a(GenericAttributes.MOVEMENT_SPEED, "91AEAA56-376B-4498-935B-2F7F68070635", 0.20000000298023224D, AttributeModifier.Operation.MULTIPLY_TOTAL)); - public static final MobEffectList SLOWER_MOVEMENT = a(2, "slowness", (new MobEffectList(MobEffectInfo.HARMFUL, 5926017)).a(GenericAttributes.MOVEMENT_SPEED, "7107DE5E-7CE8-4030-940E-514C1F160890", -0.15000000596046448D, AttributeModifier.Operation.MULTIPLY_TOTAL)); - public static final MobEffectList FASTER_DIG = a(3, "haste", (new MobEffectList(MobEffectInfo.BENEFICIAL, 14270531)).a(GenericAttributes.ATTACK_SPEED, "AF8B6E3F-3328-4C0A-AA36-5BA2BB9DBEF3", 0.10000000149011612D, AttributeModifier.Operation.MULTIPLY_TOTAL)); - public static final MobEffectList SLOWER_DIG = a(4, "mining_fatigue", (new MobEffectList(MobEffectInfo.HARMFUL, 4866583)).a(GenericAttributes.ATTACK_SPEED, "55FCED67-E92A-486E-9800-B47F202C4386", -0.10000000149011612D, AttributeModifier.Operation.MULTIPLY_TOTAL)); - public static final MobEffectList INCREASE_DAMAGE = a(5, "strength", (new MobEffectAttackDamage(MobEffectInfo.BENEFICIAL, 9643043, 3.0D)).a(GenericAttributes.ATTACK_DAMAGE, "648D7064-6A60-4F59-8ABE-C2C23A6DD7A9", 0.0D, AttributeModifier.Operation.ADDITION)); - public static final MobEffectList HEAL = a(6, "instant_health", new InstantMobEffect(MobEffectInfo.BENEFICIAL, 16262179)); - public static final MobEffectList HARM = a(7, "instant_damage", new InstantMobEffect(MobEffectInfo.HARMFUL, 4393481)); - public static final MobEffectList JUMP = a(8, "jump_boost", new MobEffectList(MobEffectInfo.BENEFICIAL, 2293580)); - public static final MobEffectList CONFUSION = a(9, "nausea", new MobEffectList(MobEffectInfo.HARMFUL, 5578058)); - public static final MobEffectList REGENERATION = a(10, "regeneration", new MobEffectList(MobEffectInfo.BENEFICIAL, 13458603)); - public static final MobEffectList RESISTANCE = a(11, "resistance", new MobEffectList(MobEffectInfo.BENEFICIAL, 10044730)); - public static final MobEffectList FIRE_RESISTANCE = a(12, "fire_resistance", new MobEffectList(MobEffectInfo.BENEFICIAL, 14981690)); - public static final MobEffectList WATER_BREATHING = a(13, "water_breathing", new MobEffectList(MobEffectInfo.BENEFICIAL, 3035801)); - public static final MobEffectList INVISIBILITY = a(14, "invisibility", new MobEffectList(MobEffectInfo.BENEFICIAL, 8356754)); - public static final MobEffectList BLINDNESS = a(15, "blindness", new MobEffectList(MobEffectInfo.HARMFUL, 2039587)); - public static final MobEffectList NIGHT_VISION = a(16, "night_vision", new MobEffectList(MobEffectInfo.BENEFICIAL, 2039713)); - public static final MobEffectList HUNGER = a(17, "hunger", new MobEffectList(MobEffectInfo.HARMFUL, 5797459)); - public static final MobEffectList WEAKNESS = a(18, "weakness", (new MobEffectAttackDamage(MobEffectInfo.HARMFUL, 4738376, -4.0D)).a(GenericAttributes.ATTACK_DAMAGE, "22653B89-116E-49DC-9B6B-9971489B5BE5", 0.0D, AttributeModifier.Operation.ADDITION)); - public static final MobEffectList POISON = a(19, "poison", new MobEffectList(MobEffectInfo.HARMFUL, 5149489)); - public static final MobEffectList WITHER = a(20, "wither", new MobEffectList(MobEffectInfo.HARMFUL, 3484199)); - public static final MobEffectList HEALTH_BOOST = a(21, "health_boost", (new MobEffectHealthBoost(MobEffectInfo.BENEFICIAL, 16284963)).a(GenericAttributes.MAX_HEALTH, "5D6F0BA2-1186-46AC-B896-C61C5CEE99CC", 4.0D, AttributeModifier.Operation.ADDITION)); - public static final MobEffectList ABSORBTION = a(22, "absorption", new MobEffectAbsorption(MobEffectInfo.BENEFICIAL, 2445989)); - public static final MobEffectList SATURATION = a(23, "saturation", new InstantMobEffect(MobEffectInfo.BENEFICIAL, 16262179)); - public static final MobEffectList GLOWING = a(24, "glowing", new MobEffectList(MobEffectInfo.NEUTRAL, 9740385)); - public static final MobEffectList LEVITATION = a(25, "levitation", new MobEffectList(MobEffectInfo.HARMFUL, 13565951)); - public static final MobEffectList LUCK = a(26, "luck", (new MobEffectList(MobEffectInfo.BENEFICIAL, 3381504)).a(GenericAttributes.LUCK, "03C3C89D-7037-4B42-869F-B146BCB64D2E", 1.0D, AttributeModifier.Operation.ADDITION)); - public static final MobEffectList UNLUCK = a(27, "unluck", (new MobEffectList(MobEffectInfo.HARMFUL, 12624973)).a(GenericAttributes.LUCK, "CC5AF142-2BD2-4215-B636-2605AED11727", -1.0D, AttributeModifier.Operation.ADDITION)); - public static final MobEffectList SLOW_FALLING = a(28, "slow_falling", new MobEffectList(MobEffectInfo.BENEFICIAL, 16773073)); - public static final MobEffectList CONDUIT_POWER = a(29, "conduit_power", new MobEffectList(MobEffectInfo.BENEFICIAL, 1950417)); - public static final MobEffectList DOLPHINS_GRACE = a(30, "dolphins_grace", new MobEffectList(MobEffectInfo.BENEFICIAL, 8954814)); - public static final MobEffectList BAD_OMEN = a(31, "bad_omen", new MobEffectList(MobEffectInfo.NEUTRAL, 745784) { - @Override - public boolean a(int i, int j) { - return true; - } - - @Override - public void tick(EntityLiving entityliving, int i) { - if (entityliving instanceof EntityPlayer && !entityliving.isSpectator()) { - EntityPlayer entityplayer = (EntityPlayer) entityliving; - WorldServer worldserver = entityplayer.getWorldServer(); - - if (worldserver.getDifficulty() == EnumDifficulty.PEACEFUL) { - return; - } - - if (worldserver.b_(new BlockPosition(entityliving))) { - worldserver.C().a(entityplayer); - } - } - - } - }); - public static final MobEffectList HERO_OF_THE_VILLAGE = a(32, "hero_of_the_village", new MobEffectList(MobEffectInfo.BENEFICIAL, 4521796)); - - // CraftBukkit start - static { - for (Object effect : IRegistry.MOB_EFFECT) { - org.bukkit.potion.PotionEffectType.registerPotionEffectType(new org.bukkit.craftbukkit.potion.CraftPotionEffectType((MobEffectList) effect)); - } - } - // CraftBukkit end - - private static MobEffectList a(int i, String s, MobEffectList mobeffectlist) { - return (MobEffectList) IRegistry.a(IRegistry.MOB_EFFECT, i, s, mobeffectlist); - } -} diff --git a/src/main/java/net/minecraft/server/MobSpawnerAbstract.java b/src/main/java/net/minecraft/server/MobSpawnerAbstract.java deleted file mode 100644 index a4e6be549..000000000 --- a/src/main/java/net/minecraft/server/MobSpawnerAbstract.java +++ /dev/null @@ -1,338 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public abstract class MobSpawnerAbstract { - - private static final Logger LOGGER = LogManager.getLogger(); - public int spawnDelay = 20; - public final List mobs = Lists.newArrayList(); - public MobSpawnerData spawnData = new MobSpawnerData(); - private double e; - private double f; - public int minSpawnDelay = 200; - public int maxSpawnDelay = 800; - public int spawnCount = 4; - private Entity j; - public int maxNearbyEntities = 6; - public int requiredPlayerRange = 16; - public int spawnRange = 4; - private int tickDelay = 0; // Paper - - public MobSpawnerAbstract() {} - - @Nullable - public MinecraftKey getMobName() { - String s = this.spawnData.getEntity().getString("id"); - - try { - return UtilColor.b(s) ? null : new MinecraftKey(s); - } catch (ResourceKeyInvalidException resourcekeyinvalidexception) { - BlockPosition blockposition = this.b(); - - MobSpawnerAbstract.LOGGER.warn("Invalid entity id '{}' at spawner {}:[{},{},{}]", s, this.a().worldProvider.getDimensionManager(), blockposition.getX(), blockposition.getY(), blockposition.getZ()); - return null; - } - } - - public void setMobName(EntityTypes entitytypes) { - this.spawnData.getEntity().setString("id", IRegistry.ENTITY_TYPE.getKey(entitytypes).toString()); - this.mobs.clear(); // CraftBukkit - SPIGOT-3496, MC-92282 - } - - public boolean isActivated() { return h(); } // Paper - OBFHELPER - private boolean h() { - BlockPosition blockposition = this.b(); - - return this.a().isPlayerNearby((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, (double) this.requiredPlayerRange); - } - - public void c() { - // Paper start - Configurable mob spawner tick rate - if (spawnDelay > 0 && --tickDelay > 0) return; - tickDelay = this.a().paperConfig.mobSpawnerTickRate; - // Paper end - if (!this.h()) { - this.f = this.e; - } else { - World world = this.a(); - BlockPosition blockposition = this.b(); - - if (world.isClientSide) { - double d0 = (double) ((float) blockposition.getX() + world.random.nextFloat()); - double d1 = (double) ((float) blockposition.getY() + world.random.nextFloat()); - double d2 = (double) ((float) blockposition.getZ() + world.random.nextFloat()); - - world.addParticle(Particles.SMOKE, d0, d1, d2, 0.0D, 0.0D, 0.0D); - world.addParticle(Particles.FLAME, d0, d1, d2, 0.0D, 0.0D, 0.0D); - if (this.spawnDelay > 0) { - this.spawnDelay -= tickDelay; // Paper - } - - this.f = this.e; - this.e = (this.e + (double) (1000.0F / ((float) this.spawnDelay + 200.0F))) % 360.0D; - } else { - if (this.spawnDelay < -tickDelay) { // Paper - this.i(); - } - - if (this.spawnDelay > 0) { - this.spawnDelay -= tickDelay; // Paper - return; - } - - boolean flag = false; - - for (int i = 0; i < this.spawnCount; ++i) { - NBTTagCompound nbttagcompound = this.spawnData.getEntity(); - Optional> optional = EntityTypes.a(nbttagcompound); - - if (!optional.isPresent()) { - this.i(); - return; - } - - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) this.spawnRange + 0.5D; - double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) this.spawnRange + 0.5D; - - if (world.c(((EntityTypes) optional.get()).a(d3, d4, d5)) && EntityPositionTypes.a((EntityTypes) optional.get(), world.getMinecraftWorld(), EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { - // Paper start - EntityTypes entityType = optional.get(); - String key = EntityTypes.getName(entityType).getKey(); - - org.bukkit.entity.EntityType type = org.bukkit.entity.EntityType.fromName(key); - if (type != null) { - com.destroystokyo.paper.event.entity.PreSpawnerSpawnEvent event; - event = new com.destroystokyo.paper.event.entity.PreSpawnerSpawnEvent( - MCUtil.toLocation(world, d3, d4, d5), - type, - MCUtil.toLocation(world, blockposition) - ); - if (!event.callEvent()) { - flag = true; - if (event.shouldAbortSpawn()) { - break; - } - continue; - } - } - // Paper end - - Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { - entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); - return entity1; - }); - - if (entity == null) { - this.i(); - return; - } - - int k = world.a(entity.getClass(), (new AxisAlignedBB((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), (double) (blockposition.getX() + 1), (double) (blockposition.getY() + 1), (double) (blockposition.getZ() + 1))).g((double) this.spawnRange)).size(); - - if (k >= this.maxNearbyEntities) { - this.i(); - return; - } - - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); - if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - - if (!entityinsentient.a((GeneratorAccess) world, EnumMobSpawn.SPAWNER) || !entityinsentient.a((IWorldReader) world)) { - continue; - } - - if (this.spawnData.getEntity().d() == 1 && this.spawnData.getEntity().hasKeyOfType("id", 8)) { - ((EntityInsentient) entity).prepare(world, world.getDamageScaler(new BlockPosition(entity)), EnumMobSpawn.SPAWNER, (GroupDataEntity) null, (NBTTagCompound) null); - } - } - entity.spawnedViaMobSpawner = true; // Paper - // Spigot Start - if ( entity.world.spigotConfig.nerfSpawnerMobs ) - { - entity.fromMobSpawner = true; - } - - flag = true; // Paper - - if (org.bukkit.craftbukkit.event.CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.dead = true; - } - for (Entity passenger : entity.getAllPassengers()) { - passenger.dead = true; - } - continue; - } - // Spigot End - this.a(entity); - world.triggerEffect(2004, blockposition, 0); - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).doSpawnEffect(); - } - - /*flag = true;*/ // Paper - moved up above cancellable event - } - } - - if (flag) { - this.i(); - } - } - - } - } - - private void a(Entity entity) { - if (entity.valid || this.a().addEntity(entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SPAWNER)) { // CraftBukkit // Paper - Iterator iterator = entity.getPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity1 = (Entity) iterator.next(); - - this.a(entity1); - } - - } - } - - public void resetTimer() { i(); } // Paper - OBFHELPER - private void i() { - if (this.maxSpawnDelay <= this.minSpawnDelay) { - this.spawnDelay = this.minSpawnDelay; - } else { - int i = this.maxSpawnDelay - this.minSpawnDelay; - - this.spawnDelay = this.minSpawnDelay + this.a().random.nextInt(i); - } - - if (!this.mobs.isEmpty()) { - this.setSpawnData((MobSpawnerData) WeightedRandom.a(this.a().random, this.mobs)); - } - - this.a(1); - } - - public void a(NBTTagCompound nbttagcompound) { - // Paper start - use larger int if set - if (nbttagcompound.hasKey("Paper.Delay")) { - this.spawnDelay = nbttagcompound.getInt("Paper.Delay"); - } else { - this.spawnDelay = nbttagcompound.getShort("Delay"); - } - // Paper end - this.mobs.clear(); - if (nbttagcompound.hasKeyOfType("SpawnPotentials", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("SpawnPotentials", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - this.mobs.add(new MobSpawnerData(nbttaglist.getCompound(i))); - } - } - - if (nbttagcompound.hasKeyOfType("SpawnData", 10)) { - this.setSpawnData(new MobSpawnerData(1, nbttagcompound.getCompound("SpawnData"))); - } else if (!this.mobs.isEmpty()) { - this.setSpawnData((MobSpawnerData) WeightedRandom.a(this.a().random, this.mobs)); - } - // Paper start - use ints if set - if (nbttagcompound.hasKeyOfType("Paper.MinSpawnDelay", 99)) { - this.minSpawnDelay = nbttagcompound.getInt("Paper.MinSpawnDelay"); - this.maxSpawnDelay = nbttagcompound.getInt("Paper.MaxSpawnDelay"); - this.spawnCount = nbttagcompound.getShort("SpawnCount"); - } else // Paper end - if (nbttagcompound.hasKeyOfType("MinSpawnDelay", 99)) { - this.minSpawnDelay = nbttagcompound.getInt("MinSpawnDelay"); - this.maxSpawnDelay = nbttagcompound.getInt("MaxSpawnDelay"); - this.spawnCount = nbttagcompound.getShort("SpawnCount"); - } - - if (nbttagcompound.hasKeyOfType("MaxNearbyEntities", 99)) { - this.maxNearbyEntities = nbttagcompound.getShort("MaxNearbyEntities"); - this.requiredPlayerRange = nbttagcompound.getShort("RequiredPlayerRange"); - } - - if (nbttagcompound.hasKeyOfType("SpawnRange", 99)) { - this.spawnRange = nbttagcompound.getShort("SpawnRange"); - } - - if (this.a() != null) { - this.j = null; - } - - } - - public NBTTagCompound b(NBTTagCompound nbttagcompound) { - MinecraftKey minecraftkey = this.getMobName(); - - if (minecraftkey == null) { - return nbttagcompound; - } else { - // Paper start - if (spawnDelay > Short.MAX_VALUE) { - nbttagcompound.setInt("Paper.Delay", this.spawnDelay); - } - nbttagcompound.setShort("Delay", (short) Math.min(Short.MAX_VALUE, this.spawnDelay)); - - if (minSpawnDelay > Short.MAX_VALUE || maxSpawnDelay > Short.MAX_VALUE) { - nbttagcompound.setInt("Paper.MinSpawnDelay", this.minSpawnDelay); - nbttagcompound.setInt("Paper.MaxSpawnDelay", this.maxSpawnDelay); - } - - nbttagcompound.setShort("MinSpawnDelay", (short) Math.min(Short.MAX_VALUE, this.minSpawnDelay)); - nbttagcompound.setShort("MaxSpawnDelay", (short) Math.min(Short.MAX_VALUE, this.maxSpawnDelay)); - // Paper end - nbttagcompound.setShort("SpawnCount", (short) this.spawnCount); - nbttagcompound.setShort("MaxNearbyEntities", (short) this.maxNearbyEntities); - nbttagcompound.setShort("RequiredPlayerRange", (short) this.requiredPlayerRange); - nbttagcompound.setShort("SpawnRange", (short) this.spawnRange); - nbttagcompound.set("SpawnData", this.spawnData.getEntity().clone()); - NBTTagList nbttaglist = new NBTTagList(); - - if (this.mobs.isEmpty()) { - nbttaglist.add(this.spawnData.a()); - } else { - Iterator iterator = this.mobs.iterator(); - - while (iterator.hasNext()) { - MobSpawnerData mobspawnerdata = (MobSpawnerData) iterator.next(); - - nbttaglist.add(mobspawnerdata.a()); - } - } - - nbttagcompound.set("SpawnPotentials", nbttaglist); - return nbttagcompound; - } - } - - public boolean b(int i) { - if (i == 1 && this.a().isClientSide) { - this.spawnDelay = this.minSpawnDelay; - return true; - } else { - return false; - } - } - - public void setSpawnData(MobSpawnerData mobspawnerdata) { - this.spawnData = mobspawnerdata; - } - - public abstract void a(int i); - - public abstract World a(); - - public abstract BlockPosition b(); -} diff --git a/src/main/java/net/minecraft/server/MobSpawnerPatrol.java b/src/main/java/net/minecraft/server/MobSpawnerPatrol.java deleted file mode 100644 index a9d32ebdf..000000000 --- a/src/main/java/net/minecraft/server/MobSpawnerPatrol.java +++ /dev/null @@ -1,106 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class MobSpawnerPatrol { - - private int a; - - public MobSpawnerPatrol() {} - - public int a(WorldServer worldserver, boolean flag, boolean flag1) { - if (!flag) { - return 0; - } else { - Random random = worldserver.random; - - --this.a; - if (this.a > 0) { - return 0; - } else { - this.a += 12000 + random.nextInt(1200); - long i = worldserver.getDayTime() / 24000L; - - if (i >= 5L && worldserver.J()) { - if (random.nextInt(5) != 0) { - return 0; - } else { - int j = worldserver.getPlayers().size(); - - if (j < 1) { - return 0; - } else { - EntityHuman entityhuman = (EntityHuman) worldserver.getPlayers().get(random.nextInt(j)); - - if (entityhuman.isSpectator()) { - return 0; - } else if (worldserver.b_(entityhuman.getChunkCoordinates())) { - return 0; - } else { - int k = (24 + random.nextInt(24)) * (random.nextBoolean() ? -1 : 1); - int l = (24 + random.nextInt(24)) * (random.nextBoolean() ? -1 : 1); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - blockposition_mutableblockposition.c(entityhuman.locX, entityhuman.locY, entityhuman.locZ).e(k, 0, l); - if (!worldserver.isAreaLoaded(blockposition_mutableblockposition.getX() - 10, blockposition_mutableblockposition.getY() - 10, blockposition_mutableblockposition.getZ() - 10, blockposition_mutableblockposition.getX() + 10, blockposition_mutableblockposition.getY() + 10, blockposition_mutableblockposition.getZ() + 10)) { - return 0; - } else { - BiomeBase biomebase = worldserver.getBiome(blockposition_mutableblockposition); - BiomeBase.Geography biomebase_geography = biomebase.o(); - - if (biomebase_geography == BiomeBase.Geography.MUSHROOM) { - return 0; - } else { - int i1 = 0; - int j1 = (int) Math.ceil((double) worldserver.getDamageScaler(blockposition_mutableblockposition).b()) + 1; - - for (int k1 = 0; k1 < j1; ++k1) { - ++i1; - blockposition_mutableblockposition.p(worldserver.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, blockposition_mutableblockposition).getY()); - if (k1 == 0) { - if (!this.a(worldserver, blockposition_mutableblockposition, random, true)) { - break; - } - } else { - this.a(worldserver, blockposition_mutableblockposition, random, false); - } - - blockposition_mutableblockposition.o(blockposition_mutableblockposition.getX() + random.nextInt(5) - random.nextInt(5)); - blockposition_mutableblockposition.q(blockposition_mutableblockposition.getZ() + random.nextInt(5) - random.nextInt(5)); - } - - return i1; - } - } - } - } - } - } else { - return 0; - } - } - } - } - - private boolean a(World world, BlockPosition blockposition, Random random, boolean flag) { - if (!EntityMonsterPatrolling.b(EntityTypes.PILLAGER, world, EnumMobSpawn.PATROL, blockposition, random)) { - return false; - } else { - EntityMonsterPatrolling entitymonsterpatrolling = (EntityMonsterPatrolling) EntityTypes.PILLAGER.a(world); - - if (entitymonsterpatrolling != null) { - if (flag) { - entitymonsterpatrolling.setPatrolLeader(true); - entitymonsterpatrolling.ed(); - } - - entitymonsterpatrolling.setPosition((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()); - entitymonsterpatrolling.prepare(world, world.getDamageScaler(blockposition), EnumMobSpawn.PATROL, (GroupDataEntity) null, (NBTTagCompound) null); - world.addEntity(entitymonsterpatrolling, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.PATROL); // CraftBukkit - return true; - } else { - return false; - } - } - } -} diff --git a/src/main/java/net/minecraft/server/MobSpawnerPhantom.java b/src/main/java/net/minecraft/server/MobSpawnerPhantom.java deleted file mode 100644 index 1818e7c38..000000000 --- a/src/main/java/net/minecraft/server/MobSpawnerPhantom.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Random; - -public class MobSpawnerPhantom { - - private int a; - - public MobSpawnerPhantom() {} - - public int a(WorldServer worldserver, boolean flag, boolean flag1) { - if (!flag) { - return 0; - } else { - Random random = worldserver.random; - - --this.a; - if (this.a > 0) { - return 0; - } else { - this.a += (60 + random.nextInt(60)) * 20; - if (worldserver.c() < 5 && worldserver.worldProvider.g()) { - return 0; - } else { - int i = 0; - Iterator iterator = worldserver.getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman = (EntityHuman) iterator.next(); - - if (!entityhuman.isSpectator()) { - BlockPosition blockposition = new BlockPosition(entityhuman); - - if (!worldserver.worldProvider.g() || blockposition.getY() >= worldserver.getSeaLevel() && worldserver.f(blockposition)) { - DifficultyDamageScaler difficultydamagescaler = worldserver.getDamageScaler(blockposition); - - if (difficultydamagescaler.a(random.nextFloat() * 3.0F)) { - ServerStatisticManager serverstatisticmanager = ((EntityPlayer) entityhuman).getStatisticManager(); - int j = MathHelper.clamp(serverstatisticmanager.getStatisticValue(StatisticList.CUSTOM.b(StatisticList.TIME_SINCE_REST)), 1, Integer.MAX_VALUE); - boolean flag2 = true; - - if (random.nextInt(j) >= 72000) { - BlockPosition blockposition1 = blockposition.up(20 + random.nextInt(15)).east(-10 + random.nextInt(21)).south(-10 + random.nextInt(21)); - IBlockData iblockdata = worldserver.getType(blockposition1); - Fluid fluid = worldserver.getFluid(blockposition1); - - if (SpawnerCreature.a((IBlockAccess) worldserver, blockposition1, iblockdata, fluid)) { - GroupDataEntity groupdataentity = null; - int k = 1 + random.nextInt(difficultydamagescaler.a().a() + 1); - - for (int l = 0; l < k; ++l) { - // Paper start - com.destroystokyo.paper.event.entity.PhantomPreSpawnEvent event = new com.destroystokyo.paper.event.entity.PhantomPreSpawnEvent(MCUtil.toLocation(worldserver, blockposition1), ((EntityPlayer) entityhuman).getBukkitEntity(), org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NATURAL); - if (!event.callEvent()) { - if (event.shouldAbortSpawn()) { - break; - } - continue; - } - // Paper end - EntityPhantom entityphantom = (EntityPhantom) EntityTypes.PHANTOM.a((World) worldserver); - entityphantom.spawningEntity = entityhuman.uniqueID; // Paper - entityphantom.setPositionRotation(blockposition1, 0.0F, 0.0F); - groupdataentity = entityphantom.prepare(worldserver, difficultydamagescaler, EnumMobSpawn.NATURAL, groupdataentity, (NBTTagCompound) null); - worldserver.addEntity(entityphantom, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NATURAL); // CraftBukkit - } - - i += k; - } - } - } - } - } - } - - return i; - } - } - } - } -} diff --git a/src/main/java/net/minecraft/server/NBTBase.java b/src/main/java/net/minecraft/server/NBTBase.java deleted file mode 100644 index 7a987c6be..000000000 --- a/src/main/java/net/minecraft/server/NBTBase.java +++ /dev/null @@ -1,102 +0,0 @@ -package net.minecraft.server; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public interface NBTBase { - - String[] a = new String[]{"END", "BYTE", "SHORT", "INT", "LONG", "FLOAT", "DOUBLE", "BYTE[]", "STRING", "LIST", "COMPOUND", "INT[]", "LONG[]"}; - EnumChatFormat b = EnumChatFormat.AQUA; - EnumChatFormat c = EnumChatFormat.GREEN; - EnumChatFormat d = EnumChatFormat.GOLD; - EnumChatFormat e = EnumChatFormat.RED; - - void write(DataOutput dataoutput) throws IOException; - - void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException; - - String toString(); - - byte getTypeId(); - - 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(); - case 12: - return new NBTTagLongArray(); - default: - return null; - } - } - - static String l(int i) { - switch (i) { - case 0: - return "TAG_End"; - case 1: - return "TAG_Byte"; - case 2: - return "TAG_Short"; - case 3: - return "TAG_Int"; - case 4: - return "TAG_Long"; - case 5: - return "TAG_Float"; - case 6: - return "TAG_Double"; - case 7: - return "TAG_Byte_Array"; - case 8: - return "TAG_String"; - case 9: - return "TAG_List"; - case 10: - return "TAG_Compound"; - case 11: - return "TAG_Int_Array"; - case 12: - return "TAG_Long_Array"; - case 99: - return "Any Numeric Tag"; - default: - return "UNKNOWN"; - } - } - - public NBTBase clone(); // Paper - decompile fix - - default String asString() { - return this.toString(); - } - - default IChatBaseComponent k() { - return this.a("", 0); - } - - IChatBaseComponent a(String s, int i); -} diff --git a/src/main/java/net/minecraft/server/NBTCompressedStreamTools.java b/src/main/java/net/minecraft/server/NBTCompressedStreamTools.java deleted file mode 100644 index d49afd622..000000000 --- a/src/main/java/net/minecraft/server/NBTCompressedStreamTools.java +++ /dev/null @@ -1,127 +0,0 @@ -package net.minecraft.server; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -public class NBTCompressedStreamTools { - - public static NBTTagCompound a(InputStream inputstream) throws IOException { - DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(inputstream))); - Throwable throwable = null; - - NBTTagCompound nbttagcompound; - - try { - nbttagcompound = a((DataInput) datainputstream, NBTReadLimiter.a); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (datainputstream != null) { - if (throwable != null) { - try { - datainputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - datainputstream.close(); - } - } - - } - - return nbttagcompound; - } - - public static void a(NBTTagCompound nbttagcompound, OutputStream outputstream) throws IOException { - DataOutputStream dataoutputstream = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(outputstream))); - Throwable throwable = null; - - try { - a(nbttagcompound, (DataOutput) dataoutputstream); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (dataoutputstream != null) { - if (throwable != null) { - try { - dataoutputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - dataoutputstream.close(); - } - } - - } - - } - - public static NBTTagCompound readNBT(DataInputStream datainputstream) throws IOException { return a(datainputstream); } // Paper - OBFHELPER - public static NBTTagCompound a(DataInputStream datainputstream) throws IOException { - return a((DataInput) 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 writeNBT(NBTTagCompound nbttagcompound, DataOutput dataoutput) throws IOException { a(nbttagcompound, dataoutput); } // Paper - OBFHELPER - 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 type", (Object) b0); - throw new ReportedException(crashreport); - } - } - } -} diff --git a/src/main/java/net/minecraft/server/NBTTagByteArray.java b/src/main/java/net/minecraft/server/NBTTagByteArray.java deleted file mode 100644 index 1110b277f..000000000 --- a/src/main/java/net/minecraft/server/NBTTagByteArray.java +++ /dev/null @@ -1,161 +0,0 @@ -package net.minecraft.server; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import org.apache.commons.lang3.ArrayUtils; - -public class NBTTagByteArray extends NBTList { - - private byte[] data; - - NBTTagByteArray() {} - - public NBTTagByteArray(byte[] abyte) { - this.data = abyte; - } - - public NBTTagByteArray(List list) { - this(a(list)); - } - - private static byte[] a(List list) { - byte[] abyte = new byte[list.size()]; - - for (int i = 0; i < list.size(); ++i) { - Byte obyte = (Byte) list.get(i); - - abyte[i] = obyte == null ? 0 : obyte; - } - - return abyte; - } - - @Override - public void write(DataOutput dataoutput) throws IOException { - dataoutput.writeInt(this.data.length); - dataoutput.write(this.data); - } - - @Override - public 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((long) (8 * j)); - this.data = new byte[j]; - datainput.readFully(this.data); - } - - @Override - public byte getTypeId() { - return 7; - } - - @Override - public String toString() { - StringBuilder stringbuilder = new StringBuilder("[B;"); - - for (int i = 0; i < this.data.length; ++i) { - if (i != 0) { - stringbuilder.append(','); - } - - stringbuilder.append(this.data[i]).append('B'); - } - - return stringbuilder.append(']').toString(); - } - - @Override - 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 this == object ? true : object instanceof NBTTagByteArray && Arrays.equals(this.data, ((NBTTagByteArray) object).data); - } - - public int hashCode() { - return Arrays.hashCode(this.data); - } - - @Override - public IChatBaseComponent a(String s, int i) { - IChatBaseComponent ichatbasecomponent = (new ChatComponentText("B")).a(NBTTagByteArray.e); - IChatBaseComponent ichatbasecomponent1 = (new ChatComponentText("[")).addSibling(ichatbasecomponent).a(";"); - - for (int j = 0; j < this.data.length; ++j) { - IChatBaseComponent ichatbasecomponent2 = (new ChatComponentText(String.valueOf(this.data[j]))).a(NBTTagByteArray.d); - - ichatbasecomponent1.a(" ").addSibling(ichatbasecomponent2).addSibling(ichatbasecomponent); - if (j != this.data.length - 1) { - ichatbasecomponent1.a(","); - } - } - - ichatbasecomponent1.a("]"); - return ichatbasecomponent1; - } - - public byte[] getBytes() { - return this.data; - } - - public int size() { - return this.data.length; - } - - public NBTTagByte get(int i) { - return new NBTTagByte(this.data[i]); - } - - public NBTTagByte set(int i, NBTTagByte nbttagbyte) { - byte b0 = this.data[i]; - - this.data[i] = nbttagbyte.asByte(); - return new NBTTagByte(b0); - } - - public void add(int i, NBTTagByte nbttagbyte) { - this.data = ArrayUtils.add(this.data, i, nbttagbyte.asByte()); - } - - @Override - public boolean a(int i, NBTBase nbtbase) { - if (nbtbase instanceof NBTNumber) { - this.data[i] = ((NBTNumber) nbtbase).asByte(); - return true; - } else { - return false; - } - } - - @Override - public boolean b(int i, NBTBase nbtbase) { - if (nbtbase instanceof NBTNumber) { - this.data = ArrayUtils.add(this.data, i, ((NBTNumber) nbtbase).asByte()); - return true; - } else { - return false; - } - } - - @Override - public NBTTagByte remove(int i) { - byte b0 = this.data[i]; - - this.data = ArrayUtils.remove(this.data, i); - return new NBTTagByte(b0); - } - - public void clear() { - this.data = new byte[0]; - } -} diff --git a/src/main/java/net/minecraft/server/NBTTagCompound.java b/src/main/java/net/minecraft/server/NBTTagCompound.java deleted file mode 100644 index b1fd18151..000000000 --- a/src/main/java/net/minecraft/server/NBTTagCompound.java +++ /dev/null @@ -1,507 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Pattern; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class NBTTagCompound implements NBTBase { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final Pattern g = Pattern.compile("[A-Za-z0-9._+-]+"); - public final Map map = Maps.newHashMap(); // Paper - - public NBTTagCompound() {} - - @Override - public void write(DataOutput dataoutput) throws IOException { - Iterator iterator = this.map.keySet().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - NBTBase nbtbase = (NBTBase) this.map.get(s); - - a(s, nbtbase, dataoutput); - } - - dataoutput.writeByte(0); - } - - @Override - public 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((long) (224 + 16 * s.length())); - NBTBase nbtbase = a(b0, s, datainput, i + 1, nbtreadlimiter); - - if (this.map.put(s, nbtbase) != null) { - nbtreadlimiter.a(288L); - } - } - - } - } - - public Set getKeys() { - return this.map.keySet(); - } - - @Override - public byte getTypeId() { - return 10; - } - - public int d() { - return this.map.size(); - } - - @Nullable - public NBTBase set(String s, NBTBase nbtbase) { - return (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 setUUID(String prefix, UUID uuid) { a(prefix, uuid); } // Paper - OBFHELPER - public void a(String s, UUID uuid) { - this.setLong(s + "Most", uuid.getMostSignificantBits()); - this.setLong(s + "Least", uuid.getLeastSignificantBits()); - } - - - @Nullable public UUID getUUID(String prefix) { return a(prefix); } // Paper - OBFHELPER - @Nullable - public UUID a(String s) { - return new UUID(this.getLong(s + "Most"), this.getLong(s + "Least")); - } - - public final boolean hasUUID(String s) { return this.b(s); } public boolean b(String s) { // Paper - OBFHELPER - return this.hasKeyOfType(s + "Most", 99) && this.hasKeyOfType(s + "Least", 99); - } - - 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 b(String s, List list) { - this.map.put(s, new NBTTagIntArray(list)); - } - - public void a(String s, long[] along) { - this.map.put(s, new NBTTagLongArray(along)); - } - - public void c(String s, List list) { - this.map.put(s, new NBTTagLongArray(list)); - } - - public void setBoolean(String s, boolean flag) { - this.setByte(s, (byte) (flag ? 1 : 0)); - } - - @Nullable - public NBTBase get(String s) { - return (NBTBase) this.map.get(s); - } - - public byte d(String s) { - NBTBase nbtbase = (NBTBase) this.map.get(s); - - return nbtbase == null ? 0 : nbtbase.getTypeId(); - } - - public boolean hasKey(String s) { - return this.map.containsKey(s); - } - - public boolean hasKeyOfType(String s, int i) { - byte b0 = this.d(s); - - return b0 == i ? true : (i != 99 ? false : b0 == 1 || b0 == 2 || b0 == 3 || b0 == 4 || b0 == 5 || b0 == 6); - } - - public byte getByte(String s) { - try { - if (this.hasKeyOfType(s, 99)) { - return ((NBTNumber) this.map.get(s)).asByte(); - } - } catch (ClassCastException classcastexception) { - ; - } - - return 0; - } - - public short getShort(String s) { - try { - if (this.hasKeyOfType(s, 99)) { - return ((NBTNumber) this.map.get(s)).asShort(); - } - } catch (ClassCastException classcastexception) { - ; - } - - return 0; - } - - public int getInt(String s) { - try { - if (this.hasKeyOfType(s, 99)) { - return ((NBTNumber) this.map.get(s)).asInt(); - } - } catch (ClassCastException classcastexception) { - ; - } - - return 0; - } - - public long getLong(String s) { - try { - if (this.hasKeyOfType(s, 99)) { - return ((NBTNumber) this.map.get(s)).asLong(); - } - } catch (ClassCastException classcastexception) { - ; - } - - return 0L; - } - - public float getFloat(String s) { - try { - if (this.hasKeyOfType(s, 99)) { - return ((NBTNumber) this.map.get(s)).asFloat(); - } - } catch (ClassCastException classcastexception) { - ; - } - - return 0.0F; - } - - public double getDouble(String s) { - try { - if (this.hasKeyOfType(s, 99)) { - return ((NBTNumber) this.map.get(s)).asDouble(); - } - } catch (ClassCastException classcastexception) { - ; - } - - return 0.0D; - } - - public String getString(String s) { - try { - if (this.hasKeyOfType(s, 8)) { - return ((NBTBase) this.map.get(s)).asString(); - } - } catch (ClassCastException classcastexception) { - ; - } - - return ""; - } - - public byte[] getByteArray(String s) { - try { - if (this.hasKeyOfType(s, 7)) { - return ((NBTTagByteArray) this.map.get(s)).getBytes(); - } - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.a(s, 7, classcastexception)); - } - - return new byte[0]; - } - - public int[] getIntArray(String s) { - try { - if (this.hasKeyOfType(s, 11)) { - return ((NBTTagIntArray) this.map.get(s)).getInts(); - } - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.a(s, 11, classcastexception)); - } - - return new int[0]; - } - - public long[] getLongArray(String s) { - try { - if (this.hasKeyOfType(s, 12)) { - return ((NBTTagLongArray) this.map.get(s)).getLongs(); - } - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.a(s, 12, classcastexception)); - } - - return new long[0]; - } - - public NBTTagCompound getCompound(String s) { - try { - if (this.hasKeyOfType(s, 10)) { - return (NBTTagCompound) this.map.get(s); - } - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.a(s, 10, classcastexception)); - } - - return new NBTTagCompound(); - } - - public NBTTagList getList(String s, int i) { - try { - if (this.d(s) == 9) { - NBTTagList nbttaglist = (NBTTagList) this.map.get(s); - - if (!nbttaglist.isEmpty() && nbttaglist.a_() != i) { - return new NBTTagList(); - } - - return nbttaglist; - } - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.a(s, 9, classcastexception)); - } - - return new NBTTagList(); - } - - public boolean getBoolean(String s) { - return this.getByte(s) != 0; - } - - public void remove(String s) { - this.map.remove(s); - } - - @Override - public String toString() { - StringBuilder stringbuilder = new StringBuilder("{"); - Collection collection = this.map.keySet(); - - if (NBTTagCompound.LOGGER.isDebugEnabled()) { - List list = Lists.newArrayList(this.map.keySet()); - - Collections.sort(list); - collection = list; - } - - String s; - - for (Iterator iterator = ((Collection) collection).iterator(); iterator.hasNext(); stringbuilder.append(s(s)).append(':').append(this.map.get(s))) { - s = (String) iterator.next(); - if (stringbuilder.length() != 1) { - stringbuilder.append(','); - } - } - - return stringbuilder.append('}').toString(); - } - - public boolean isEmpty() { - return this.map.isEmpty(); - } - - private CrashReport a(String s, 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", () -> { - return NBTTagCompound.a[((NBTBase) this.map.get(s)).getTypeId()]; - }); - crashreportsystemdetails.a("Tag type expected", () -> { - return NBTTagCompound.a[i]; - }); - crashreportsystemdetails.a("Tag name", (Object) s); - return crashreport; - } - - @Override - public NBTTagCompound clone() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - Iterator iterator = this.map.keySet().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - - nbttagcompound.set(s, ((NBTBase) this.map.get(s)).clone()); - } - - return nbttagcompound; - } - - public boolean equals(Object object) { - return this == object ? true : object instanceof NBTTagCompound && Objects.equals(this.map, ((NBTTagCompound) object).map); - } - - public int hashCode() { - return 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", (Object) s); - crashreportsystemdetails.a("Tag type", (Object) b0); - throw new ReportedException(crashreport); - } - } - - public NBTTagCompound a(NBTTagCompound nbttagcompound) { - Iterator iterator = nbttagcompound.map.keySet().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - NBTBase 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()); - } - } - - return this; - } - - protected static String s(String s) { - return NBTTagCompound.g.matcher(s).matches() ? s : NBTTagString.a(s); - } - - protected static IChatBaseComponent t(String s) { - if (NBTTagCompound.g.matcher(s).matches()) { - return (new ChatComponentText(s)).a(NBTTagCompound.b); - } else { - String s1 = NBTTagString.a(s); - String s2 = s1.substring(0, 1); - IChatBaseComponent ichatbasecomponent = (new ChatComponentText(s1.substring(1, s1.length() - 1))).a(NBTTagCompound.b); - - return (new ChatComponentText(s2)).addSibling(ichatbasecomponent).a(s2); - } - } - - @Override - public IChatBaseComponent a(String s, int i) { - if (this.map.isEmpty()) { - return new ChatComponentText("{}"); - } else { - ChatComponentText chatcomponenttext = new ChatComponentText("{"); - Collection collection = this.map.keySet(); - - if (NBTTagCompound.LOGGER.isDebugEnabled()) { - List list = Lists.newArrayList(this.map.keySet()); - - Collections.sort(list); - collection = list; - } - - if (!s.isEmpty()) { - chatcomponenttext.a("\n"); - } - - IChatBaseComponent ichatbasecomponent; - - for (Iterator iterator = ((Collection) collection).iterator(); iterator.hasNext(); chatcomponenttext.addSibling(ichatbasecomponent)) { - String s1 = (String) iterator.next(); - - ichatbasecomponent = (new ChatComponentText(Strings.repeat(s, i + 1))).addSibling(t(s1)).a(String.valueOf(':')).a(" ").addSibling(((NBTBase) this.map.get(s1)).a(s, i + 1)); - if (iterator.hasNext()) { - ichatbasecomponent.a(String.valueOf(',')).a(s.isEmpty() ? " " : "\n"); - } - } - - if (!s.isEmpty()) { - chatcomponenttext.a("\n").a(Strings.repeat(s, i)); - } - - chatcomponenttext.a("}"); - return chatcomponenttext; - } - } -} diff --git a/src/main/java/net/minecraft/server/NBTTagIntArray.java b/src/main/java/net/minecraft/server/NBTTagIntArray.java deleted file mode 100644 index e3ed32aa7..000000000 --- a/src/main/java/net/minecraft/server/NBTTagIntArray.java +++ /dev/null @@ -1,171 +0,0 @@ -package net.minecraft.server; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import org.apache.commons.lang3.ArrayUtils; - -public class NBTTagIntArray extends NBTList { - - private int[] data; - - NBTTagIntArray() {} - - public NBTTagIntArray(int[] aint) { - this.data = aint; - } - - public NBTTagIntArray(List list) { - this(a(list)); - } - - private static int[] a(List list) { - int[] aint = new int[list.size()]; - - for (int i = 0; i < list.size(); ++i) { - Integer integer = (Integer) list.get(i); - - aint[i] = integer == null ? 0 : integer; - } - - return aint; - } - - @Override - public void write(DataOutput dataoutput) throws IOException { - dataoutput.writeInt(this.data.length); - int[] aint = this.data; - int i = aint.length; - - for (int j = 0; j < i; ++j) { - int k = aint[j]; - - dataoutput.writeInt(k); - } - - } - - @Override - public 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((long) (32 * j)); - this.data = new int[j]; - - for (int k = 0; k < j; ++k) { - this.data[k] = datainput.readInt(); - } - - } - - @Override - public byte getTypeId() { - return 11; - } - - @Override - public String toString() { - StringBuilder stringbuilder = new StringBuilder("[I;"); - - for (int i = 0; i < this.data.length; ++i) { - if (i != 0) { - stringbuilder.append(','); - } - - stringbuilder.append(this.data[i]); - } - - return stringbuilder.append(']').toString(); - } - - @Override - public NBTTagIntArray 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 this == object ? true : object instanceof NBTTagIntArray && Arrays.equals(this.data, ((NBTTagIntArray) object).data); - } - - public int hashCode() { - return Arrays.hashCode(this.data); - } - - public int[] getInts() { - return this.data; - } - - @Override - public IChatBaseComponent a(String s, int i) { - IChatBaseComponent ichatbasecomponent = (new ChatComponentText("I")).a(NBTTagIntArray.e); - IChatBaseComponent ichatbasecomponent1 = (new ChatComponentText("[")).addSibling(ichatbasecomponent).a(";"); - - for (int j = 0; j < this.data.length; ++j) { - ichatbasecomponent1.a(" ").addSibling((new ChatComponentText(String.valueOf(this.data[j]))).a(NBTTagIntArray.d)); - if (j != this.data.length - 1) { - ichatbasecomponent1.a(","); - } - } - - ichatbasecomponent1.a("]"); - return ichatbasecomponent1; - } - - public int size() { - return this.data.length; - } - - public NBTTagInt get(int i) { - return new NBTTagInt(this.data[i]); - } - - public NBTTagInt set(int i, NBTTagInt nbttagint) { - int j = this.data[i]; - - this.data[i] = nbttagint.asInt(); - return new NBTTagInt(j); - } - - public void add(int i, NBTTagInt nbttagint) { - this.data = ArrayUtils.add(this.data, i, nbttagint.asInt()); - } - - @Override - public boolean a(int i, NBTBase nbtbase) { - if (nbtbase instanceof NBTNumber) { - this.data[i] = ((NBTNumber) nbtbase).asInt(); - return true; - } else { - return false; - } - } - - @Override - public boolean b(int i, NBTBase nbtbase) { - if (nbtbase instanceof NBTNumber) { - this.data = ArrayUtils.add(this.data, i, ((NBTNumber) nbtbase).asInt()); - return true; - } else { - return false; - } - } - - @Override - public NBTTagInt remove(int i) { - int j = this.data[i]; - - this.data = ArrayUtils.remove(this.data, i); - return new NBTTagInt(j); - } - - public void clear() { - this.data = new int[0]; - } -} diff --git a/src/main/java/net/minecraft/server/NBTTagList.java b/src/main/java/net/minecraft/server/NBTTagList.java deleted file mode 100644 index 80eea5dfb..000000000 --- a/src/main/java/net/minecraft/server/NBTTagList.java +++ /dev/null @@ -1,320 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; - -public class NBTTagList extends NBTList { - - List list = Lists.newArrayList(); // Paper - private -> package - private byte type = 0; - - public NBTTagList() {} - - @Override - public void write(DataOutput dataoutput) throws IOException { - if (this.list.isEmpty()) { - this.type = 0; - } else { - this.type = ((NBTBase) this.list.get(0)).getTypeId(); - } - - dataoutput.writeByte(this.type); - dataoutput.writeInt(this.list.size()); - Iterator iterator = this.list.iterator(); - - while (iterator.hasNext()) { - NBTBase nbtbase = (NBTBase) iterator.next(); - - nbtbase.write(dataoutput); - } - - } - - @Override - public 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(); - - 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); - } - - } - } - } - - @Override - public byte getTypeId() { - return 9; - } - - @Override - public String toString() { - StringBuilder stringbuilder = new StringBuilder("["); - - for (int i = 0; i < this.list.size(); ++i) { - if (i != 0) { - stringbuilder.append(','); - } - - stringbuilder.append(this.list.get(i)); - } - - return stringbuilder.append(']').toString(); - } - - private void f() { - if (this.list.isEmpty()) { - this.type = 0; - } - - } - - @Override - public NBTBase remove(int i) { - NBTBase nbtbase = (NBTBase) this.list.remove(i); - - this.f(); - return nbtbase; - } - - public boolean isEmpty() { - return this.list.isEmpty(); - } - - public NBTTagCompound getCompound(int i) { - if (i >= 0 && i < this.list.size()) { - NBTBase nbtbase = (NBTBase) this.list.get(i); - - if (nbtbase.getTypeId() == 10) { - return (NBTTagCompound) nbtbase; - } - } - - return new NBTTagCompound(); - } - - public NBTTagList b(int i) { - if (i >= 0 && i < this.list.size()) { - NBTBase nbtbase = (NBTBase) this.list.get(i); - - if (nbtbase.getTypeId() == 9) { - return (NBTTagList) nbtbase; - } - } - - return new NBTTagList(); - } - - public short d(int i) { - if (i >= 0 && i < this.list.size()) { - NBTBase nbtbase = (NBTBase) this.list.get(i); - - if (nbtbase.getTypeId() == 2) { - return ((NBTTagShort) nbtbase).asShort(); - } - } - - return 0; - } - - public int e(int i) { - if (i >= 0 && i < this.list.size()) { - NBTBase nbtbase = (NBTBase) this.list.get(i); - - if (nbtbase.getTypeId() == 3) { - return ((NBTTagInt) nbtbase).asInt(); - } - } - - return 0; - } - - public int[] f(int i) { - if (i >= 0 && i < this.list.size()) { - NBTBase nbtbase = (NBTBase) this.list.get(i); - - if (nbtbase.getTypeId() == 11) { - return ((NBTTagIntArray) nbtbase).getInts(); - } - } - - return new int[0]; - } - - public final double getDoubleAt(int i) { return this.h(i); } // Paper - OBFHELPER - public double h(int i) { - if (i >= 0 && i < this.list.size()) { - NBTBase nbtbase = (NBTBase) this.list.get(i); - - if (nbtbase.getTypeId() == 6) { - return ((NBTTagDouble) nbtbase).asDouble(); - } - } - - return 0.0D; - } - - public float i(int i) { - if (i >= 0 && i < this.list.size()) { - NBTBase nbtbase = (NBTBase) this.list.get(i); - - if (nbtbase.getTypeId() == 5) { - return ((NBTTagFloat) nbtbase).asFloat(); - } - } - - return 0.0F; - } - - public String getString(int i) { - if (i >= 0 && i < this.list.size()) { - NBTBase nbtbase = (NBTBase) this.list.get(i); - - return nbtbase.getTypeId() == 8 ? nbtbase.asString() : nbtbase.toString(); - } else { - return ""; - } - } - - public int size() { - return this.list.size(); - } - - public NBTBase get(int i) { - return (NBTBase) this.list.get(i); - } - - @Override - public NBTBase set(int i, NBTBase nbtbase) { - NBTBase nbtbase1 = this.get(i); - - if (!this.a(i, nbtbase)) { - throw new UnsupportedOperationException(String.format("Trying to add tag of type %d to list of %d", nbtbase.getTypeId(), this.type)); - } else { - return nbtbase1; - } - } - - @Override - public void add(int i, NBTBase nbtbase) { - if (!this.b(i, nbtbase)) { - throw new UnsupportedOperationException(String.format("Trying to add tag of type %d to list of %d", nbtbase.getTypeId(), this.type)); - } - } - - @Override - public boolean a(int i, NBTBase nbtbase) { - if (this.a(nbtbase)) { - this.list.set(i, nbtbase); - return true; - } else { - return false; - } - } - - @Override - public boolean b(int i, NBTBase nbtbase) { - if (this.a(nbtbase)) { - this.list.add(i, nbtbase); - return true; - } else { - return false; - } - } - - private boolean a(NBTBase nbtbase) { - if (nbtbase.getTypeId() == 0) { - return false; - } else if (this.type == 0) { - this.type = nbtbase.getTypeId(); - return true; - } else { - return this.type == nbtbase.getTypeId(); - } - } - - @Override - public NBTTagList clone() { - NBTTagList nbttaglist = new NBTTagList(); - - nbttaglist.type = this.type; - Iterator iterator = this.list.iterator(); - - while (iterator.hasNext()) { - NBTBase nbtbase = (NBTBase) iterator.next(); - NBTBase nbtbase1 = nbtbase.clone(); - - nbttaglist.list.add(nbtbase1); - } - - return nbttaglist; - } - - public boolean equals(Object object) { - return this == object ? true : object instanceof NBTTagList && Objects.equals(this.list, ((NBTTagList) object).list); - } - - public int hashCode() { - return this.list.hashCode(); - } - - @Override - public IChatBaseComponent a(String s, int i) { - if (this.isEmpty()) { - return new ChatComponentText("[]"); - } else { - ChatComponentText chatcomponenttext = new ChatComponentText("["); - - if (!s.isEmpty()) { - chatcomponenttext.a("\n"); - } - - for (int j = 0; j < this.list.size(); ++j) { - ChatComponentText chatcomponenttext1 = new ChatComponentText(Strings.repeat(s, i + 1)); - - chatcomponenttext1.addSibling(((NBTBase) this.list.get(j)).a(s, i + 1)); - if (j != this.list.size() - 1) { - chatcomponenttext1.a(String.valueOf(',')).a(s.isEmpty() ? " " : "\n"); - } - - chatcomponenttext.addSibling(chatcomponenttext1); - } - - if (!s.isEmpty()) { - chatcomponenttext.a("\n").a(Strings.repeat(s, i)); - } - - chatcomponenttext.a("]"); - return chatcomponenttext; - } - } - - public int a_() { - return this.type; - } - - public void clear() { - this.list.clear(); - this.type = 0; - } -} diff --git a/src/main/java/net/minecraft/server/NameReferencingFileConverter.java b/src/main/java/net/minecraft/server/NameReferencingFileConverter.java deleted file mode 100644 index 0794aff5b..000000000 --- a/src/main/java/net/minecraft/server/NameReferencingFileConverter.java +++ /dev/null @@ -1,532 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.exception.ServerInternalException; -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 java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.UUID; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class NameReferencingFileConverter { - - private static final Logger LOGGER = 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, StandardCharsets.UTF_8); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - - 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 = (String[]) collection.stream().filter((s) -> { - return !UtilColor.b(s); - }).toArray((i) -> { - return new String[i]; - }); - - if (minecraftserver.getOnlineMode() - || (com.destroystokyo.paper.PaperConfig.isProxyOnlineMode())) { // Spigot: bungee = online mode, for now. // Paper - Handle via setting - minecraftserver.getGameProfileRepository().findProfilesByNames(astring, Agent.MINECRAFT, profilelookupcallback); - } else { - String[] astring1 = astring; - int i = astring.length; - - for (int j = 0; j < i; ++j) { - String s = astring1[j]; - UUID uuid = EntityHuman.a(new GameProfile((UUID) 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 stacktrace - } catch (IOException filenotfoundexception) { - NameReferencingFileConverter.LOGGER.warn("Could not load existing file {}", gameprofilebanlist.c().getName()); - } - } - - try { - final Map map = Maps.newHashMap(); - - a(NameReferencingFileConverter.b, (Map) map); - ProfileLookupCallback profilelookupcallback = new ProfileLookupCallback() { - public void onProfileLookupSucceeded(GameProfile gameprofile) { - minecraftserver.getUserCache().a(gameprofile); - String[] astring = (String[]) map.get(gameprofile.getName().toLowerCase(Locale.ROOT)); - - if (astring == null) { - NameReferencingFileConverter.LOGGER.warn("Could not convert user banlist entry for {}", gameprofile.getName()); - throw new NameReferencingFileConverter.FileConversionException("Profile not in the conversionlist"); - } else { - Date date = astring.length > 1 ? NameReferencingFileConverter.b(astring[1], (Date) null) : null; - String s = astring.length > 2 ? astring[2] : null; - Date date1 = astring.length > 3 ? NameReferencingFileConverter.b(astring[3], (Date) 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.LOGGER.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); - } - } - }; - - a(minecraftserver, map.keySet(), profilelookupcallback); - gameprofilebanlist.save(); - c(NameReferencingFileConverter.b); - return true; - } catch (IOException ioexception) { - NameReferencingFileConverter.LOGGER.warn("Could not read old user banlist to convert it!", ioexception); - return false; - } catch (NameReferencingFileConverter.FileConversionException namereferencingfileconverter_fileconversionexception) { - NameReferencingFileConverter.LOGGER.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 stacktrace - } catch (IOException filenotfoundexception) { - NameReferencingFileConverter.LOGGER.warn("Could not load existing file {}", ipbanlist.c().getName()); - } - } - - try { - Map map = Maps.newHashMap(); - - a(NameReferencingFileConverter.a, (Map) map); - Iterator iterator = map.keySet().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - String[] astring = (String[]) map.get(s); - Date date = astring.length > 1 ? b(astring[1], (Date) null) : null; - String s1 = astring.length > 2 ? astring[2] : null; - Date date1 = astring.length > 3 ? b(astring[3], (Date) 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.LOGGER.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 stacktrace - } catch (IOException filenotfoundexception) { - NameReferencingFileConverter.LOGGER.warn("Could not load existing file {}", oplist.c().getName()); - } - } - - try { - List list = Files.readLines(NameReferencingFileConverter.c, StandardCharsets.UTF_8); - ProfileLookupCallback profilelookupcallback = new ProfileLookupCallback() { - public void onProfileLookupSucceeded(GameProfile gameprofile) { - minecraftserver.getUserCache().a(gameprofile); - oplist.add(new OpListEntry(gameprofile, minecraftserver.j(), false)); - } - - public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { - NameReferencingFileConverter.LOGGER.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); - } - } - }; - - a(minecraftserver, list, profilelookupcallback); - oplist.save(); - c(NameReferencingFileConverter.c); - return true; - } catch (IOException ioexception) { - NameReferencingFileConverter.LOGGER.warn("Could not read old oplist to convert it!", ioexception); - return false; - } catch (NameReferencingFileConverter.FileConversionException namereferencingfileconverter_fileconversionexception) { - NameReferencingFileConverter.LOGGER.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 stacktrace - } catch (IOException filenotfoundexception) { - NameReferencingFileConverter.LOGGER.warn("Could not load existing file {}", whitelist.c().getName()); - } - } - - try { - List list = Files.readLines(NameReferencingFileConverter.d, StandardCharsets.UTF_8); - ProfileLookupCallback profilelookupcallback = new ProfileLookupCallback() { - public void onProfileLookupSucceeded(GameProfile gameprofile) { - minecraftserver.getUserCache().a(gameprofile); - whitelist.add(new WhiteListEntry(gameprofile)); - } - - public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { - NameReferencingFileConverter.LOGGER.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); - } - } - }; - - a(minecraftserver, list, profilelookupcallback); - whitelist.save(); - c(NameReferencingFileConverter.d); - return true; - } catch (IOException ioexception) { - NameReferencingFileConverter.LOGGER.warn("Could not read old whitelist to convert it!", ioexception); - return false; - } catch (NameReferencingFileConverter.FileConversionException namereferencingfileconverter_fileconversionexception) { - NameReferencingFileConverter.LOGGER.error("Conversion failed, please try again later", namereferencingfileconverter_fileconversionexception); - return false; - } - } else { - return true; - } - } - - public static String a(final MinecraftServer minecraftserver, String s) { - if (!UtilColor.b(s) && s.length() <= 16) { - GameProfile gameprofile = minecraftserver.getUserCache().getProfile(s); - - if (gameprofile != null && gameprofile.getId() != null) { - return gameprofile.getId().toString(); - } else if (!minecraftserver.isEmbeddedServer() && minecraftserver.getOnlineMode()) { - final List list = Lists.newArrayList(); - ProfileLookupCallback profilelookupcallback = new ProfileLookupCallback() { - public void onProfileLookupSucceeded(GameProfile gameprofile1) { - minecraftserver.getUserCache().a(gameprofile1); - list.add(gameprofile1); - } - - public void onProfileLookupFailed(GameProfile gameprofile1, Exception exception) { - NameReferencingFileConverter.LOGGER.warn("Could not lookup user whitelist entry for {}", gameprofile1.getName(), exception); - } - }; - - a(minecraftserver, Lists.newArrayList(new String[]{s}), profilelookupcallback); - return !list.isEmpty() && ((GameProfile) list.get(0)).getId() != null ? ((GameProfile) list.get(0)).getId().toString() : ""; - } else { - return EntityHuman.a(new GameProfile((UUID) null, s)).toString(); - } - } else { - return s; - } - } - - public static boolean a(final DedicatedServer dedicatedserver) { - final File file = getPlayersFolder(dedicatedserver); - final File file1 = new File(file.getParentFile(), "playerdata"); - final File file2 = new File(file.getParentFile(), "unknownplayers"); - - if (file.exists() && file.isDirectory()) { - File[] afile = file.listFiles(); - List list = Lists.newArrayList(); - File[] afile1 = afile; - int i = afile.length; - - for (int j = 0; j < i; ++j) { - File file3 = afile1[j]; - String s = file3.getName(); - - if (s.toLowerCase(Locale.ROOT).endsWith(".dat")) { - String s1 = s.substring(0, s.length() - ".dat".length()); - - if (!s1.isEmpty()) { - list.add(s1); - } - } - } - - try { - final String[] astring = (String[]) list.toArray(new String[list.size()]); - ProfileLookupCallback profilelookupcallback = 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()); - } else { - this.a(file1, this.a(gameprofile), uuid.toString()); - } - } - - public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { - NameReferencingFileConverter.LOGGER.warn("Could not lookup user uuid for {}", gameprofile.getName(), exception); - if (exception instanceof ProfileNotFoundException) { - String s2 = this.a(gameprofile); - - this.a(file2, s2, s2); - } else { - throw new NameReferencingFileConverter.FileConversionException("Could not request user " + gameprofile.getName() + " from backend systems", exception); - } - } - - private void a(File file4, String s2, String s3) { - File file5 = new File(file, s2 + ".dat"); - File file6 = new File(file4, s3 + ".dat"); - - // CraftBukkit start - Use old file name to seed lastKnownName - NBTTagCompound root = null; - - try { - root = NBTCompressedStreamTools.a(new java.io.FileInputStream(file5)); - } catch (Exception exception) { - exception.printStackTrace(); - ServerInternalException.reportInternalException(exception); // Paper - } - - if (root != null) { - if (!root.hasKey("bukkit")) { - root.set("bukkit", new NBTTagCompound()); - } - NBTTagCompound data = root.getCompound("bukkit"); - data.setString("lastKnownName", s2); - - try { - NBTCompressedStreamTools.a(root, new java.io.FileOutputStream(file2)); - } catch (Exception exception) { - exception.printStackTrace(); - ServerInternalException.reportInternalException(exception); // Paper - } - } - // CraftBukkit end - - NameReferencingFileConverter.b(file4); - if (!file5.renameTo(file6)) { - throw new NameReferencingFileConverter.FileConversionException("Could not convert file for " + s2); - } - } - - private String a(GameProfile gameprofile) { - String s2 = null; - String[] astring1 = astring; - int k = astring1.length; - - for (int l = 0; l < k; ++l) { - String s3 = astring1[l]; - - if (s3 != null && s3.equalsIgnoreCase(gameprofile.getName())) { - s2 = s3; - break; - } - } - - if (s2 == null) { - throw new NameReferencingFileConverter.FileConversionException("Could not find the filename for " + gameprofile.getName() + " anymore"); - } else { - return s2; - } - } - }; - - a(dedicatedserver, Lists.newArrayList(astring), profilelookupcallback); - return true; - } catch (NameReferencingFileConverter.FileConversionException namereferencingfileconverter_fileconversionexception) { - NameReferencingFileConverter.LOGGER.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."); - } - } else if (!file.mkdirs()) { - throw new NameReferencingFileConverter.FileConversionException("Can't create directory " + file.getName() + " in world save directory."); - } - } - - public static boolean e(MinecraftServer minecraftserver) { - boolean flag = b(); - - flag = flag && f(minecraftserver); - return flag; - } - - private static boolean b() { - 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.LOGGER.warn("**** FAILED TO START THE SERVER AFTER ACCOUNT CONVERSION!"); - NameReferencingFileConverter.LOGGER.warn("** please remove the following files and restart the server:"); - if (flag) { - NameReferencingFileConverter.LOGGER.warn("* {}", NameReferencingFileConverter.b.getName()); - } - - if (flag1) { - NameReferencingFileConverter.LOGGER.warn("* {}", NameReferencingFileConverter.a.getName()); - } - - if (flag2) { - NameReferencingFileConverter.LOGGER.warn("* {}", NameReferencingFileConverter.c.getName()); - } - - if (flag3) { - NameReferencingFileConverter.LOGGER.warn("* {}", NameReferencingFileConverter.d.getName()); - } - - return false; - } - } - - private static boolean f(MinecraftServer minecraftserver) { - File file = getPlayersFolder(minecraftserver); - - if (file.exists() && file.isDirectory() && (file.list().length > 0 || !file.delete())) { - NameReferencingFileConverter.LOGGER.warn("**** DETECTED OLD PLAYER DIRECTORY IN THE WORLD SAVE"); - NameReferencingFileConverter.LOGGER.warn("**** THIS USUALLY HAPPENS WHEN THE AUTOMATIC CONVERSION FAILED IN SOME WAY"); - NameReferencingFileConverter.LOGGER.warn("** please restart the server and if the problem persists, remove the directory '{}'", file.getPath()); - return false; - } else { - return true; - } - } - - private static File getPlayersFolder(MinecraftServer minecraftserver) { - String s = minecraftserver.getWorld(); - 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); - } - } -} diff --git a/src/main/java/net/minecraft/server/Navigation.java b/src/main/java/net/minecraft/server/Navigation.java deleted file mode 100644 index fd1dbb108..000000000 --- a/src/main/java/net/minecraft/server/Navigation.java +++ /dev/null @@ -1,249 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; - -public class Navigation extends NavigationAbstract { - - private boolean p; - - public Navigation(EntityInsentient entityinsentient, World world) { - super(entityinsentient, world); - } - - @Override - protected Pathfinder a(int i) { - this.o = new PathfinderNormal(); - this.o.a(true); - return new Pathfinder(this.o, i); - } - - @Override - protected boolean a() { - return this.a.onGround || this.p() || this.a.isPassenger(); - } - - @Override - protected Vec3D b() { - return new Vec3D(this.a.locX, (double) this.t(), this.a.locZ); - } - - @Override - public PathEntity a(BlockPosition blockposition, int i) { - BlockPosition blockposition1; - - if (this.b.getType(blockposition).isAir()) { - for (blockposition1 = blockposition.down(); blockposition1.getY() > 0 && this.b.getType(blockposition1).isAir(); blockposition1 = blockposition1.down()) { - ; - } - - if (blockposition1.getY() > 0) { - return super.a(blockposition1.up(), i); - } - - while (blockposition1.getY() < this.b.getBuildHeight() && this.b.getType(blockposition1).isAir()) { - blockposition1 = blockposition1.up(); - } - - blockposition = blockposition1; - } - - if (!this.b.getType(blockposition).getMaterial().isBuildable()) { - return super.a(blockposition, i); - } else { - for (blockposition1 = blockposition.up(); blockposition1.getY() < this.b.getBuildHeight() && this.b.getType(blockposition1).getMaterial().isBuildable(); blockposition1 = blockposition1.up()) { - ; - } - - return super.a(blockposition1, i); - } - } - - @Override - public PathEntity a(Entity entity, int i) { - return this.a(new BlockPosition(entity), entity, i); // Paper - Forward target entity - } - - private int t() { - if (this.a.isInWater() && this.r()) { - int i = MathHelper.floor(this.a.getBoundingBox().minY); - Block block = this.b.getType(new BlockPosition(this.a.locX, (double) i, this.a.locZ)).getBlock(); - int j = 0; - - do { - if (block != Blocks.WATER) { - return i; - } - - ++i; - block = this.b.getType(new BlockPosition(this.a.locX, (double) i, this.a.locZ)).getBlock(); - ++j; - } while (j <= 16); - - return MathHelper.floor(this.a.getBoundingBox().minY); - } else { - return MathHelper.floor(this.a.getBoundingBox().minY + 0.5D); - } - } - - @Override - protected void D_() { - super.D_(); - if (this.p) { - if (this.b.f(new BlockPosition(this.a.locX, this.a.getBoundingBox().minY + 0.5D, this.a.locZ))) { - return; - } - - for (int i = 0; i < this.c.e(); ++i) { - PathPoint pathpoint = this.c.a(i); - - if (this.b.f(new BlockPosition(pathpoint.a, pathpoint.b, pathpoint.c))) { - this.c.b(i); - return; - } - } - } - - } - - @Override - protected boolean a(Vec3D vec3d, Vec3D vec3d1, int i, int j, int k) { - int l = MathHelper.floor(vec3d.x); - int i1 = MathHelper.floor(vec3d.z); - double d0 = vec3d1.x - vec3d.x; - double d1 = vec3d1.z - vec3d.z; - double d2 = d0 * d0 + d1 * d1; - - if (d2 < 1.0E-8D) { - return false; - } else { - double d3 = 1.0D / Math.sqrt(d2); - - d0 *= d3; - d1 *= d3; - i += 2; - k += 2; - if (!this.a(l, MathHelper.floor(vec3d.y), i1, i, j, k, vec3d, d0, d1)) { - return false; - } else { - i -= 2; - k -= 2; - double d4 = 1.0D / Math.abs(d0); - double d5 = 1.0D / Math.abs(d1); - double d6 = (double) l - vec3d.x; - double d7 = (double) i1 - vec3d.z; - - 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.x); - int i2 = MathHelper.floor(vec3d1.z); - 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, MathHelper.floor(vec3d.y), 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.x; - double d3 = (double) j2 + 0.5D - vec3d.z; - - if (d2 * d0 + d3 * d1 >= 0.0D) { - PathType pathtype = this.o.a(this.b, i2, j - 1, j2, this.a, l, i1, j1, true, true); - - if (pathtype == PathType.WATER) { - return false; - } - - if (pathtype == PathType.LAVA) { - return false; - } - - if (pathtype == PathType.OPEN) { - return false; - } - - pathtype = this.o.a(this.b, i2, j, j2, this.a, l, i1, j1, true, true); - float f = this.a.a(pathtype); - - if (f < 0.0F || f >= 8.0F) { - return false; - } - - if (pathtype == PathType.DAMAGE_FIRE || pathtype == PathType.DANGER_FIRE || pathtype == PathType.DAMAGE_OTHER) { - 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) { - Iterator iterator = BlockPosition.a(new BlockPosition(i, j, k), new BlockPosition(i + l - 1, j + i1 - 1, k + j1 - 1)).iterator(); - - BlockPosition blockposition; - double d2; - double d3; - - do { - if (!iterator.hasNext()) { - return true; - } - - blockposition = (BlockPosition) iterator.next(); - d2 = (double) blockposition.getX() + 0.5D - vec3d.x; - d3 = (double) blockposition.getZ() + 0.5D - vec3d.z; - } while (d2 * d0 + d3 * d1 < 0.0D || this.b.getType(blockposition).a((IBlockAccess) this.b, blockposition, PathMode.LAND)); - - return false; - } - - public void a(boolean flag) { - this.o.b(flag); - } - - public boolean f() { - return this.o.c(); - } - - public void c(boolean flag) { - this.p = flag; - } -} diff --git a/src/main/java/net/minecraft/server/NavigationAbstract.java b/src/main/java/net/minecraft/server/NavigationAbstract.java deleted file mode 100644 index 66e10108d..000000000 --- a/src/main/java/net/minecraft/server/NavigationAbstract.java +++ /dev/null @@ -1,332 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableSet; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.annotation.Nullable; - -public abstract class NavigationAbstract { - - protected final EntityInsentient a; public Entity getEntity() { return a; } // Paper - OBFHELPER - protected final World b; - @Nullable - protected PathEntity c; - protected double d; - private final AttributeInstance p; - protected int e; - protected int f; - protected Vec3D g; - protected Vec3D h; - protected long i; - protected long j; - protected double k; - protected float l; - protected boolean m; - protected long n; - protected PathfinderAbstract o; - private BlockPosition q; - private int r; - private Pathfinder s; public Pathfinder getPathfinder() { return this.s; } // Paper - OBFHELPER - - public NavigationAbstract(EntityInsentient entityinsentient, World world) { - this.g = Vec3D.a; - this.h = Vec3D.a; - this.l = 0.5F; - this.a = entityinsentient; - this.b = world; - this.p = entityinsentient.getAttributeInstance(GenericAttributes.FOLLOW_RANGE); - this.s = this.a(MathHelper.floor(this.p.getValue() * 16.0D)); - } - - public BlockPosition h() { - return this.q; - } - - protected abstract Pathfinder a(int i); - - public void a(double d0) { - this.d = d0; - } - - public float i() { - return (float) this.p.getValue(); - } - - public boolean j() { - return this.m; - } - - public void k() { - if (this.b.getTime() - this.n > 20L) { - if (this.q != null) { - this.c = null; - this.c = this.a(this.q, this.r); - this.n = this.b.getTime(); - this.m = false; - } - } else { - this.m = true; - } - - } - - @Nullable - public final PathEntity calculateDestination(double d0, double d1, double d2) { return a(d0, d1, d2, 0); } public final PathEntity a(double d0, double d1, double d2, int i) { // Paper - OBFHELPER - return this.a(new BlockPosition(d0, d1, d2), i); - } - - @Nullable - public PathEntity a(Stream stream, int i) { - return this.a((Set) stream.collect(Collectors.toSet()), 8, false, i); - } - - @Nullable - public PathEntity a(BlockPosition blockposition, int i) { - // Paper start - add target parameter - return this.a(blockposition, null, i); - } - @Nullable public PathEntity a(BlockPosition blockposition, Entity target, int i) { - return this.a(ImmutableSet.of(blockposition), target, 8, false, i); - // Paper end - } - - @Nullable - public final PathEntity calculateDestination(Entity entity) { return a(entity, 0); } public PathEntity a(Entity entity, int i) { - return this.a(ImmutableSet.of(new BlockPosition(entity)), entity, 16, true, i); // Paper - } - - @Nullable - // Paper start - Add target - protected PathEntity a(Set set, int i, boolean flag, int j) { - return this.a(set, null, i, flag, j); - } - @Nullable protected PathEntity a(Set set, Entity target, int i, boolean flag, int j) { - // Paper end - if (set.isEmpty()) { - return null; - } else if (this.a.locY < 0.0D) { - return null; - } else if (!this.a()) { - return null; - } else if (this.c != null && !this.c.b() && set.contains(this.q)) { - return this.c; - } else { - // Paper start - Pathfind event - boolean copiedSet = false; - for (BlockPosition possibleTarget : set) { - if (!getEntity().getWorld().getWorldBorder().isInBounds(possibleTarget) || !new com.destroystokyo.paper.event.entity.EntityPathfindEvent(getEntity().getBukkitEntity(), // Paper - don't path out of world border - MCUtil.toLocation(getEntity().world, possibleTarget), target == null ? null : target.getBukkitEntity()).callEvent()) { - if (!copiedSet) { - copiedSet = true; - set = new java.util.HashSet<>(set); - } - // note: since we copy the set this remove call is safe, since we're iterating over the old copy - set.remove(possibleTarget); - if (set.isEmpty()) { - return null; - } - } - } - // Paper end - this.b.getMethodProfiler().enter("pathfind"); - float f = this.i(); - BlockPosition blockposition = flag ? (new BlockPosition(this.a)).up() : new BlockPosition(this.a); - int k = (int) (f + (float) i); - ChunkCache chunkcache = new ChunkCache(this.b, blockposition.b(-k, -k, -k), blockposition.b(k, k, k)); - PathEntity pathentity = this.s.a(chunkcache, this.a, set, f, j); - - this.b.getMethodProfiler().exit(); - if (pathentity != null && pathentity.k() != null) { - this.q = pathentity.k(); - this.r = j; - } - - return pathentity; - } - } - - public boolean a(double d0, double d1, double d2, double d3) { - return this.a(this.a(d0, d1, d2, 1), d3); - } - - public boolean a(Entity entity, double d0) { - PathEntity pathentity = this.a(entity, 1); - - return pathentity != null && this.a(pathentity, d0); - } - - public boolean setDestination(@Nullable PathEntity pathentity, double speed) { return a(pathentity, speed); } // Paper - OBFHELPER - public boolean a(@Nullable PathEntity pathentity, double d0) { - if (pathentity == null) { - this.c = null; - return false; - } else { - if (!pathentity.a(this.c)) { - this.c = pathentity; - } - - this.D_(); - if (this.c.e() <= 0) { - return false; - } else { - this.d = d0; - Vec3D vec3d = this.b(); - - this.f = this.e; - this.g = vec3d; - return true; - } - } - } - - @Nullable public PathEntity getPathEntity() { return l(); } @Nullable // Paper - OBFHELPER - public PathEntity l() { - return this.c; - } - - public void c() { - ++this.e; - if (this.m) { - this.k(); - } - - if (!this.n()) { - Vec3D vec3d; - - if (this.a()) { - this.m(); - } else if (this.c != null && this.c.f() < this.c.e()) { - vec3d = this.b(); - Vec3D vec3d1 = this.c.a(this.a, this.c.f()); - - if (vec3d.y > vec3d1.y && !this.a.onGround && MathHelper.floor(vec3d.x) == MathHelper.floor(vec3d1.x) && MathHelper.floor(vec3d.z) == MathHelper.floor(vec3d1.z)) { - this.c.c(this.c.f() + 1); - } - } - - PacketDebug.a(this.b, this.a, this.c, this.l); - if (!this.n()) { - vec3d = this.c.a((Entity) this.a); - BlockPosition blockposition = new BlockPosition(vec3d); - - this.a.getControllerMove().a(vec3d.x, this.b.getType(blockposition.down()).isAir() ? vec3d.y : PathfinderNormal.a((IBlockAccess) this.b, blockposition), vec3d.z, this.d); - } - } - } - - protected void m() { - Vec3D vec3d = this.b(); - - this.l = this.a.getWidth() > 0.75F ? this.a.getWidth() / 2.0F : 0.75F - this.a.getWidth() / 2.0F; - Vec3D vec3d1 = this.c.g(); - - if (Math.abs(this.a.locX - (vec3d1.x + 0.5D)) < (double) this.l && Math.abs(this.a.locZ - (vec3d1.z + 0.5D)) < (double) this.l && Math.abs(this.a.locY - vec3d1.y) < 1.0D) { - this.c.c(this.c.f() + 1); - } - - this.a(vec3d); - } - - protected void a(Vec3D vec3d) { - if (this.e - this.f > 100) { - if (vec3d.distanceSquared(this.g) < 2.25D) { - this.o(); - } - - this.f = this.e; - this.g = vec3d; - } - - if (this.c != null && !this.c.b()) { - Vec3D vec3d1 = this.c.g(); - - if (vec3d1.equals(this.h)) { - this.i += SystemUtils.getMonotonicMillis() - this.j; - } else { - this.h = vec3d1; - double d0 = vec3d.f(this.h); - - this.k = this.a.db() > 0.0F ? d0 / (double) this.a.db() * 1000.0D : 0.0D; - } - - if (this.k > 0.0D && (double) this.i > this.k * 3.0D) { - this.h = Vec3D.a; - this.i = 0L; - this.k = 0.0D; - this.o(); - } - - this.j = SystemUtils.getMonotonicMillis(); - } - - } - - public boolean n() { - return this.c == null || this.c.b(); - } - - public void stopPathfinding() { o(); } // Paper - OBFHELPER - public void o() { - this.c = null; - } - - protected abstract Vec3D b(); - - protected abstract boolean a(); - - protected boolean p() { - return this.a.av() || this.a.aD(); - } - - protected void D_() { - if (this.c != null) { - for (int i = 0; i < this.c.e(); ++i) { - PathPoint pathpoint = this.c.a(i); - PathPoint pathpoint1 = i + 1 < this.c.e() ? this.c.a(i + 1) : null; - IBlockData iblockdata = this.b.getType(new BlockPosition(pathpoint.a, pathpoint.b, pathpoint.c)); - Block block = iblockdata.getBlock(); - - if (block == Blocks.CAULDRON) { - this.c.a(i, pathpoint.a(pathpoint.a, pathpoint.b + 1, pathpoint.c)); - if (pathpoint1 != null && pathpoint.b >= pathpoint1.b) { - this.c.a(i + 1, pathpoint1.a(pathpoint1.a, pathpoint.b + 1, pathpoint1.c)); - } - } - } - - } - } - - protected abstract boolean a(Vec3D vec3d, Vec3D vec3d1, int i, int j, int k); - - public boolean a(BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - - return this.b.getType(blockposition1).g(this.b, blockposition1); - } - - public PathfinderAbstract q() { - return this.o; - } - - public void d(boolean flag) { - this.o.c(flag); - } - - public boolean r() { - return this.o.e(); - } - - public void b(BlockPosition blockposition) { - if (this.c != null && !this.c.b() && this.c.e() != 0) { - PathPoint pathpoint = this.c.c(); - Vec3D vec3d = new Vec3D(((double) pathpoint.a + this.a.locX) / 2.0D, ((double) pathpoint.b + this.a.locY) / 2.0D, ((double) pathpoint.c + this.a.locZ) / 2.0D); - - if (blockposition.a((IPosition) vec3d, (double) (this.c.e() - this.c.f()))) { - this.k(); - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/NavigationFlying.java b/src/main/java/net/minecraft/server/NavigationFlying.java deleted file mode 100644 index fbf5752aa..000000000 --- a/src/main/java/net/minecraft/server/NavigationFlying.java +++ /dev/null @@ -1,140 +0,0 @@ -package net.minecraft.server; - -public class NavigationFlying extends NavigationAbstract { - - public NavigationFlying(EntityInsentient entityinsentient, World world) { - super(entityinsentient, world); - } - - @Override - protected Pathfinder a(int i) { - this.o = new PathfinderFlying(); - this.o.a(true); - return new Pathfinder(this.o, i); - } - - @Override - protected boolean a() { - return this.r() && this.p() || !this.a.isPassenger(); - } - - @Override - protected Vec3D b() { - return new Vec3D(this.a.locX, this.a.locY, this.a.locZ); - } - - @Override - public PathEntity a(Entity entity, int i) { - return this.a(new BlockPosition(entity), entity, i); // Paper - Forward target entity - } - - @Override - public void c() { - ++this.e; - if (this.m) { - this.k(); - } - - if (!this.n()) { - Vec3D vec3d; - - if (this.a()) { - this.m(); - } else if (this.c != null && this.c.f() < this.c.e()) { - vec3d = this.c.a(this.a, this.c.f()); - if (MathHelper.floor(this.a.locX) == MathHelper.floor(vec3d.x) && MathHelper.floor(this.a.locY) == MathHelper.floor(vec3d.y) && MathHelper.floor(this.a.locZ) == MathHelper.floor(vec3d.z)) { - this.c.c(this.c.f() + 1); - } - } - - PacketDebug.a(this.b, this.a, this.c, this.l); - if (!this.n()) { - vec3d = this.c.a((Entity) this.a); - this.a.getControllerMove().a(vec3d.x, vec3d.y, vec3d.z, this.d); - } - } - } - - @Override - protected boolean a(Vec3D vec3d, Vec3D vec3d1, int i, int j, int k) { - int l = MathHelper.floor(vec3d.x); - int i1 = MathHelper.floor(vec3d.y); - int j1 = MathHelper.floor(vec3d.z); - double d0 = vec3d1.x - vec3d.x; - double d1 = vec3d1.y - vec3d.y; - double d2 = vec3d1.z - vec3d.z; - double d3 = d0 * d0 + d1 * d1 + d2 * d2; - - if (d3 < 1.0E-8D) { - return false; - } else { - double d4 = 1.0D / Math.sqrt(d3); - - d0 *= d4; - d1 *= d4; - d2 *= d4; - double d5 = 1.0D / Math.abs(d0); - double d6 = 1.0D / Math.abs(d1); - double d7 = 1.0D / Math.abs(d2); - double d8 = (double) l - vec3d.x; - double d9 = (double) i1 - vec3d.y; - double d10 = (double) j1 - vec3d.z; - - if (d0 >= 0.0D) { - ++d8; - } - - if (d1 >= 0.0D) { - ++d9; - } - - if (d2 >= 0.0D) { - ++d10; - } - - d8 /= d0; - d9 /= d1; - d10 /= d2; - int k1 = d0 < 0.0D ? -1 : 1; - int l1 = d1 < 0.0D ? -1 : 1; - int i2 = d2 < 0.0D ? -1 : 1; - int j2 = MathHelper.floor(vec3d1.x); - int k2 = MathHelper.floor(vec3d1.y); - int l2 = MathHelper.floor(vec3d1.z); - int i3 = j2 - l; - int j3 = k2 - i1; - int k3 = l2 - j1; - - while (i3 * k1 > 0 || j3 * l1 > 0 || k3 * i2 > 0) { - if (d8 < d10 && d8 <= d9) { - d8 += d5; - l += k1; - i3 = j2 - l; - } else if (d9 < d8 && d9 <= d10) { - d9 += d6; - i1 += l1; - j3 = k2 - i1; - } else { - d10 += d7; - j1 += i2; - k3 = l2 - j1; - } - } - - return true; - } - } - - public void a(boolean flag) { - this.o.b(flag); - } - - public void b(boolean flag) { - this.o.a(flag); - } - - @Override - public boolean a(BlockPosition blockposition) { - return this.b.getType(blockposition).a((IBlockAccess) this.b, blockposition, (Entity) this.a); - } -} diff --git a/src/main/java/net/minecraft/server/NetworkManager.java b/src/main/java/net/minecraft/server/NetworkManager.java deleted file mode 100644 index 96a785af2..000000000 --- a/src/main/java/net/minecraft/server/NetworkManager.java +++ /dev/null @@ -1,402 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Queues; -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.DefaultEventLoopGroup; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.channel.epoll.EpollEventLoopGroup; -import io.netty.channel.local.LocalChannel; -import io.netty.channel.local.LocalServerChannel; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.handler.timeout.TimeoutException; -import io.netty.util.AttributeKey; -import io.netty.util.concurrent.Future; -import io.netty.util.concurrent.GenericFutureListener; -import java.net.SocketAddress; -import java.util.Queue; -import javax.annotation.Nullable; -import javax.crypto.SecretKey; -import org.apache.commons.lang3.Validate; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; - -public class NetworkManager extends SimpleChannelInboundHandler> { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final Marker a = MarkerManager.getMarker("NETWORK"); - public static final Marker b = MarkerManager.getMarker("NETWORK_PACKETS", NetworkManager.a); - public static final AttributeKey c = AttributeKey.valueOf("protocol"); - public static final LazyInitVar d = new LazyInitVar<>(() -> { - return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build()); - }); - public static final LazyInitVar e = new LazyInitVar<>(() -> { - return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Client IO #%d").setDaemon(true).build()); - }); - public static final LazyInitVar f = new LazyInitVar<>(() -> { - return new DefaultEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Local Client IO #%d").setDaemon(true).build()); - }); - private final EnumProtocolDirection h; - private final Queue packetQueue = Queues.newConcurrentLinkedQueue(); private final Queue getPacketQueue() { return this.packetQueue; } // Paper - OBFHELPER - public Channel channel; - public SocketAddress socketAddress; public void setSpoofedRemoteAddress(SocketAddress address) { this.socketAddress = address; } // Paper - OBFHELPER - // Spigot Start - public java.util.UUID spoofedUUID; - public com.mojang.authlib.properties.Property[] spoofedProfile; - public boolean preparing = true; - // Spigot End - private PacketListener packetListener; - private IChatBaseComponent m; - private boolean n; - private boolean o; - private int p; - private int q; - private float r; - private float s; - private int t; - private boolean u; - // Paper start - NetworkClient implementation - public int protocolVersion; - public java.net.InetSocketAddress virtualHost; - private static boolean enableExplicitFlush = Boolean.getBoolean("paper.explicit-flush"); - // Paper end - - public NetworkManager(EnumProtocolDirection enumprotocoldirection) { - this.h = enumprotocoldirection; - } - - public void channelActive(ChannelHandlerContext channelhandlercontext) throws Exception { - super.channelActive(channelhandlercontext); - this.channel = channelhandlercontext.channel(); - this.socketAddress = this.channel.remoteAddress(); - // Spigot Start - this.preparing = false; - // Spigot End - - try { - this.setProtocol(EnumProtocol.HANDSHAKING); - } catch (Throwable throwable) { - NetworkManager.LOGGER.fatal(throwable); - } - - } - - public void setProtocol(EnumProtocol enumprotocol) { - this.channel.attr(NetworkManager.c).set(enumprotocol); - this.channel.config().setAutoRead(true); - NetworkManager.LOGGER.debug("Enabled auto read"); - } - - public void channelInactive(ChannelHandlerContext channelhandlercontext) throws Exception { - this.close(new ChatMessage("disconnect.endOfStream", new Object[0])); - } - - public void exceptionCaught(ChannelHandlerContext channelhandlercontext, Throwable throwable) { - // Paper start - if (throwable instanceof io.netty.handler.codec.EncoderException && throwable.getCause() instanceof PacketEncoder.PacketTooLargeException) { - if (((PacketEncoder.PacketTooLargeException) throwable.getCause()).getPacket().packetTooLarge(this)) { - return; - } else { - throwable = throwable.getCause(); - } - } - // Paper end - if (throwable instanceof SkipEncodeException) { - NetworkManager.LOGGER.debug("Skipping packet due to errors", throwable.getCause()); - } else { - boolean flag = !this.u; - - this.u = true; - if (this.channel.isOpen()) { - if (throwable instanceof TimeoutException) { - NetworkManager.LOGGER.debug("Timeout", throwable); - this.close(new ChatMessage("disconnect.timeout", new Object[0])); - } else { - ChatMessage chatmessage = new ChatMessage("disconnect.genericReason", new Object[]{"Internal Exception: " + throwable}); - - if (flag) { - NetworkManager.LOGGER.debug("Failed to sent packet", throwable); - this.sendPacket(new PacketPlayOutKickDisconnect(chatmessage), (future) -> { - this.close(chatmessage); - }); - this.stopReading(); - } else { - NetworkManager.LOGGER.debug("Double fault", throwable); - this.close(chatmessage); - } - } - - } - } - if (MinecraftServer.getServer().isDebugging()) throwable.printStackTrace(); // Spigot - } - - protected void channelRead0(ChannelHandlerContext channelhandlercontext, Packet packet) throws Exception { - if (this.channel.isOpen()) { - try { - a(packet, this.packetListener); - } catch (CancelledPacketHandleException cancelledpackethandleexception) { - ; - } - - ++this.p; - } - - } - - private static void a(Packet packet, PacketListener packetlistener) { - packet.a((T) packetlistener); // CraftBukkit - decompile error - } - - public void setPacketListener(PacketListener packetlistener) { - Validate.notNull(packetlistener, "packetListener", new Object[0]); - NetworkManager.LOGGER.debug("Set listener of {} to {}", this, packetlistener); - this.packetListener = packetlistener; - } - - public void sendPacket(Packet packet) { - this.sendPacket(packet, (GenericFutureListener) null); - } - - public void sendPacket(Packet packet, @Nullable GenericFutureListener> genericfuturelistener) { - if (this.isConnected() && this.sendPacketQueue() && !(packet instanceof PacketPlayOutMapChunk && !((PacketPlayOutMapChunk) packet).isReady())) { // Paper - Async-Anti-Xray - Add chunk packets which are not ready or all packets if the packet queue contains chunk packets which are not ready to the packet queue and send the packets later in the right order - //this.o(); // Paper - Async-Anti-Xray - Move to if statement (this.sendPacketQueue()) - this.b(packet, genericfuturelistener); - } else { - this.packetQueue.add(new NetworkManager.QueuedPacket(packet, genericfuturelistener)); - } - - } - - private void dispatchPacket(Packet packet, @Nullable GenericFutureListener> genericFutureListener) { this.b(packet, genericFutureListener); } // Paper - OBFHELPER - private void b(Packet packet, @Nullable GenericFutureListener> genericfuturelistener) { - EnumProtocol enumprotocol = EnumProtocol.a(packet); - EnumProtocol enumprotocol1 = (EnumProtocol) this.channel.attr(NetworkManager.c).get(); - - ++this.q; - if (enumprotocol1 != enumprotocol) { - NetworkManager.LOGGER.debug("Disabled auto read"); - this.channel.config().setAutoRead(false); - } - - if (this.channel.eventLoop().inEventLoop()) { - if (enumprotocol != enumprotocol1) { - this.setProtocol(enumprotocol); - } - - ChannelFuture channelfuture = this.channel.writeAndFlush(packet); - - if (genericfuturelistener != null) { - channelfuture.addListener(genericfuturelistener); - } - - channelfuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - } else { - this.channel.eventLoop().execute(() -> { - if (enumprotocol != enumprotocol1) { - this.setProtocol(enumprotocol); - } - - ChannelFuture channelfuture1 = this.channel.writeAndFlush(packet); - - if (genericfuturelistener != null) { - channelfuture1.addListener(genericfuturelistener); - } - - channelfuture1.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - }); - } - - // Paper start - java.util.List extraPackets = packet.getExtraPackets(); - if (extraPackets != null && !extraPackets.isEmpty()) { - for (Packet extraPacket : extraPackets) { - this.dispatchPacket(extraPacket, genericfuturelistener); - } - } - // Paper end - - } - - // Paper start - Async-Anti-Xray - Stop dispatching further packets and return false if the peeked packet is a chunk packet which is not ready - private boolean sendPacketQueue() { return this.o(); } // OBFHELPER // void -> boolean - private boolean o() { // void -> boolean - if (this.channel != null && this.channel.isOpen()) { - Queue queue = this.packetQueue; - - synchronized (this.packetQueue) { - while (!this.packetQueue.isEmpty()) { - NetworkManager.QueuedPacket networkmanager_queuedpacket = (NetworkManager.QueuedPacket) this.getPacketQueue().peek(); // poll -> peek - - if (networkmanager_queuedpacket != null) { // Fix NPE (Spigot bug caused by handleDisconnection()) - if (networkmanager_queuedpacket.getPacket() instanceof PacketPlayOutMapChunk && !((PacketPlayOutMapChunk) networkmanager_queuedpacket.getPacket()).isReady()) { // Check if the peeked packet is a chunk packet which is not ready - return false; // Return false if the peeked packet is a chunk packet which is not ready - } else { - this.getPacketQueue().poll(); // poll here - this.dispatchPacket(networkmanager_queuedpacket.getPacket(), networkmanager_queuedpacket.getGenericFutureListener()); // dispatch the packet - } - } - } - - } - } - - return true; // Return true if all packets were dispatched - } - // Paper end - - public void a() { - this.o(); - if (this.packetListener instanceof LoginListener) { - ((LoginListener) this.packetListener).tick(); - } - - if (this.packetListener instanceof PlayerConnection) { - ((PlayerConnection) this.packetListener).tick(); - } - - if (this.channel != null) { - if (enableExplicitFlush) this.channel.eventLoop().execute(() -> this.channel.flush()); // Paper - we don't need to explicit flush here, but allow opt in incase issues are found to a better version - } - - if (this.t++ % 20 == 0) { - this.s = this.s * 0.75F + (float) this.q * 0.25F; - this.r = this.r * 0.75F + (float) this.p * 0.25F; - this.q = 0; - this.p = 0; - } - - } - - public SocketAddress getSocketAddress() { - return this.socketAddress; - } - - public void close(IChatBaseComponent ichatbasecomponent) { - // Spigot Start - this.preparing = false; - // Spigot End - if (this.channel.isOpen()) { - this.channel.close(); // We can't wait as this may be called from an event loop. - this.m = ichatbasecomponent; - } - - } - - public boolean isLocal() { - return this.channel instanceof LocalChannel || this.channel instanceof LocalServerChannel; - } - - public void a(SecretKey secretkey) { - this.n = true; - this.channel.pipeline().addBefore("splitter", "decrypt", new PacketDecrypter(MinecraftEncryption.a(2, secretkey))); - this.channel.pipeline().addBefore("prepender", "encrypt", new PacketEncrypter(MinecraftEncryption.a(1, secretkey))); - } - - public boolean isConnected() { - return this.channel != null && this.channel.isOpen(); - } - - public boolean h() { - return this.channel == null; - } - - public PacketListener i() { - return this.packetListener; - } - - @Nullable - public IChatBaseComponent j() { - return this.m; - } - - public void stopReading() { - this.channel.config().setAutoRead(false); - } - - public void setCompressionLevel(int i) { - if (i >= 0) { - if (this.channel.pipeline().get("decompress") instanceof PacketDecompressor) { - ((PacketDecompressor) this.channel.pipeline().get("decompress")).a(i); - } else { - this.channel.pipeline().addBefore("decoder", "decompress", new PacketDecompressor(i)); - } - - if (this.channel.pipeline().get("compress") instanceof PacketCompressor) { - ((PacketCompressor) this.channel.pipeline().get("compress")).a(i); - } else { - this.channel.pipeline().addBefore("encoder", "compress", new PacketCompressor(i)); - } - } 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 handleDisconnection() { - if (this.channel != null && !this.channel.isOpen()) { - if (this.o) { - NetworkManager.LOGGER.warn("handleDisconnection() called twice"); - } else { - this.o = true; - if (this.j() != null) { - this.i().a(this.j()); - } else if (this.i() != null) { - this.i().a(new ChatMessage("multiplayer.disconnect.generic", new Object[0])); - } - this.packetQueue.clear(); // Free up packet queue. - // Paper start - Add PlayerConnectionCloseEvent - final PacketListener packetListener = this.i(); - if (packetListener instanceof PlayerConnection) { - /* Player was logged in */ - final PlayerConnection playerConnection = (PlayerConnection) packetListener; - new com.destroystokyo.paper.event.player.PlayerConnectionCloseEvent(playerConnection.player.uniqueID, - playerConnection.player.getName(), ((java.net.InetSocketAddress)socketAddress).getAddress(), false).callEvent(); - } else if (packetListener instanceof LoginListener) { - /* Player is login stage */ - final LoginListener loginListener = (LoginListener) packetListener; - switch (loginListener.getLoginState()) { - case READY_TO_ACCEPT: - case DELAY_ACCEPT: - case ACCEPTED: - final com.mojang.authlib.GameProfile profile = loginListener.getGameProfile(); /* Should be non-null at this stage */ - new com.destroystokyo.paper.event.player.PlayerConnectionCloseEvent(profile.getId(), profile.getName(), - ((java.net.InetSocketAddress)socketAddress).getAddress(), false).callEvent(); - } - } - // Paper end - } - - } - } - - static class QueuedPacket { - - private final Packet a; private final Packet getPacket() { return this.a; } // Paper - OBFHELPER - @Nullable - private final GenericFutureListener> b; private final GenericFutureListener> getGenericFutureListener() { return this.b; } // Paper - OBFHELPER - - public QueuedPacket(Packet packet, @Nullable GenericFutureListener> genericfuturelistener) { - this.a = packet; - this.b = genericfuturelistener; - } - } - - // Spigot Start - public SocketAddress getRawAddress() - { - return this.channel.remoteAddress(); - } - // Spigot End -} diff --git a/src/main/java/net/minecraft/server/NextTickListEntry.java b/src/main/java/net/minecraft/server/NextTickListEntry.java deleted file mode 100644 index 53a290e8b..000000000 --- a/src/main/java/net/minecraft/server/NextTickListEntry.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.minecraft.server; - -import java.util.Comparator; - -public class NextTickListEntry { - - private static final java.util.concurrent.atomic.AtomicLong COUNTER = new java.util.concurrent.atomic.AtomicLong(); // Paper - async chunk loading - private final T e; - public final BlockPosition a; - public final long b; - public final TickListPriority c; - private final long f; - - public NextTickListEntry(BlockPosition blockposition, T t0) { - this(blockposition, t0, 0L, TickListPriority.NORMAL); - } - - public NextTickListEntry(BlockPosition blockposition, T t0, long i, TickListPriority ticklistpriority) { - this.f = (long) (NextTickListEntry.COUNTER.getAndIncrement()); // Paper - async chunk loading - this.a = blockposition.immutableCopy(); - this.e = t0; - this.b = i; - this.c = ticklistpriority; - } - - public boolean equals(Object object) { - if (!(object instanceof NextTickListEntry)) { - return false; - } else { - NextTickListEntry nextticklistentry = (NextTickListEntry) object; - - return this.a.equals(nextticklistentry.a) && this.e == nextticklistentry.e; - } - } - - public int hashCode() { - return this.a.hashCode(); - } - - public static Comparator> a() { - return (nextticklistentry, nextticklistentry1) -> { - int i = Long.compare(nextticklistentry.b, nextticklistentry1.b); - - if (i != 0) { - return i; - } else { - i = nextticklistentry.c.compareTo(nextticklistentry1.c); - return i != 0 ? i : Long.compare(nextticklistentry.f, nextticklistentry1.f); - } - }; - } - - public String toString() { - return this.e + ": " + this.a + ", " + this.b + ", " + this.c + ", " + this.f; - } - - public T b() { - return this.e; - } -} diff --git a/src/main/java/net/minecraft/server/NibbleArray.java b/src/main/java/net/minecraft/server/NibbleArray.java deleted file mode 100644 index eb2c06155..000000000 --- a/src/main/java/net/minecraft/server/NibbleArray.java +++ /dev/null @@ -1,99 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class NibbleArray { - - @Nullable - protected byte[] a; - - public NibbleArray() {} - - public NibbleArray(byte[] abyte) { - this.a = abyte; - if (abyte.length != 2048) { - throw new IllegalArgumentException("ChunkNibbleArrays should be 2048 bytes not: " + abyte.length); - } - } - - protected NibbleArray(int i) { - this.a = new byte[i]; - } - - public int a(int i, int j, int k) { - return this.b(this.b(i, j, k)); - } - - public void a(int i, int j, int k, int l) { - this.a(this.b(i, j, k), l); - } - - protected int b(int i, int j, int k) { - return j << 8 | k << 4 | i; - } - - public int b(int i) { // PAIL: private -> public - if (this.a == null) { - return 0; - } else { - int j = this.d(i); - - return this.a[j] >> ((i & 1) << 2) & 15; // Spigot - } - } - - public void a(int i, int j) { // PAIL: private -> public - if (this.a == null) { - this.a = new byte[2048]; - } - - int k = this.d(i); - - // Spigot start - int shift = (i & 1) << 2; - this.a[k] = (byte) (this.a[k] & ~(15 << shift) | (j & 15) << shift); - // Spigot end - } - - private boolean c(int i) { - return (i & 1) == 0; - } - - private int d(int i) { - return i >> 1; - } - - public byte[] asBytes() { - if (this.a == null) { - this.a = new byte[2048]; - } - - return this.a; - } - - public NibbleArray copy() { return this.b(); } // Paper - OBFHELPER - public NibbleArray b() { - return this.a == null ? new NibbleArray() : new NibbleArray((byte[]) this.a.clone()); - } - - public String toString() { - StringBuilder stringbuilder = new StringBuilder(); - - for (int i = 0; i < 4096; ++i) { - stringbuilder.append(Integer.toHexString(this.b(i))); - if ((i & 15) == 15) { - stringbuilder.append("\n"); - } - - if ((i & 255) == 255) { - stringbuilder.append("\n"); - } - } - - return stringbuilder.toString(); - } - - public boolean c() { - return this.a == null; - } -} diff --git a/src/main/java/net/minecraft/server/Packet.java b/src/main/java/net/minecraft/server/Packet.java deleted file mode 100644 index 8d0965a05..000000000 --- a/src/main/java/net/minecraft/server/Packet.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public interface Packet { - - void a(PacketDataSerializer packetdataserializer) throws IOException; - - void b(PacketDataSerializer packetdataserializer) throws IOException; - - void a(T t0); - - // Paper start - default java.util.List getExtraPackets() { return null; } - default boolean packetTooLarge(NetworkManager manager) { - return false; - } - // Paper end - - default boolean a() { - return false; - } -} diff --git a/src/main/java/net/minecraft/server/PacketDataSerializer.java b/src/main/java/net/minecraft/server/PacketDataSerializer.java deleted file mode 100644 index dac560c63..000000000 --- a/src/main/java/net/minecraft/server/PacketDataSerializer.java +++ /dev/null @@ -1,1112 +0,0 @@ -package net.minecraft.server; - -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 java.io.DataInput; -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.Date; -import java.util.UUID; -import javax.annotation.Nullable; - -import org.bukkit.craftbukkit.inventory.CraftItemStack; // CraftBukkit - -public class PacketDataSerializer extends ByteBuf { - - private final ByteBuf a; - - public PacketDataSerializer(ByteBuf bytebuf) { - this.a = bytebuf; - } - - public static int countBytes(int i) { return PacketDataSerializer.a(i); } // Paper - OBFHELPER - public static int a(int i) { - for (int j = 1; j < 5; ++j) { - if ((i & -1 << j * 7) == 0) { - return j; - } - } - - return 5; - } - - public PacketDataSerializer a(byte[] abyte) { - this.d(abyte.length); - this.writeBytes(abyte); - return this; - } - - public byte[] a() { - return this.b(this.readableBytes()); - } - - public byte[] b(int i) { - int j = this.i(); - - if (j > i) { - throw new DecoderException("ByteArray with size " + j + " is bigger than allowed " + i); - } else { - byte[] abyte = new byte[j]; - - this.readBytes(abyte); - return abyte; - } - } - - public PacketDataSerializer a(int[] aint) { - this.d(aint.length); - int[] aint1 = aint; - int i = aint.length; - - for (int j = 0; j < i; ++j) { - int k = aint1[j]; - - this.d(k); - } - - return this; - } - - public int[] b() { - return this.c(this.readableBytes()); - } - - public int[] c(int i) { - int j = this.i(); - - if (j > i) { - throw new DecoderException("VarIntArray with size " + j + " is bigger than allowed " + i); - } else { - int[] aint = new int[j]; - - for (int k = 0; k < aint.length; ++k) { - aint[k] = this.i(); - } - - return aint; - } - } - - public PacketDataSerializer a(long[] along) { - this.d(along.length); - long[] along1 = along; - int i = along.length; - - for (int j = 0; j < i; ++j) { - long k = along1[j]; - - this.writeLong(k); - } - - return this; - } - - public BlockPosition e() { - return BlockPosition.fromLong(this.readLong()); - } - - public PacketDataSerializer a(BlockPosition blockposition) { - this.writeLong(blockposition.asLong()); - return this; - } - - public IChatBaseComponent h() { - return IChatBaseComponent.ChatSerializer.a(this.e(262144)); - } - - public PacketDataSerializer a(IChatBaseComponent ichatbasecomponent) { - return this.a(IChatBaseComponent.ChatSerializer.a(ichatbasecomponent), 262144); - } - - public > T a(Class oclass) { - return ((T[]) oclass.getEnumConstants())[this.i()]; // CraftBukkit - fix decompile error - } - - public PacketDataSerializer a(Enum oenum) { - return this.d(oenum.ordinal()); - } - - public int readVarInt() { return i(); } // Paper - OBFHELPER - public int i() { - int i = 0; - int j = 0; - - byte b0; - - do { - b0 = this.readByte(); - i |= (b0 & 127) << j++ * 7; - if (j > 5) { - throw new RuntimeException("VarInt too big"); - } - } while ((b0 & 128) == 128); - - return i; - } - - public long j() { - long i = 0L; - int j = 0; - - byte b0; - - do { - b0 = this.readByte(); - i |= (long) (b0 & 127) << j++ * 7; - if (j > 10) { - throw new RuntimeException("VarLong too big"); - } - } while ((b0 & 128) == 128); - - return i; - } - - public PacketDataSerializer a(UUID uuid) { - this.writeLong(uuid.getMostSignificantBits()); - this.writeLong(uuid.getLeastSignificantBits()); - return this; - } - - public UUID readUUID() { return k(); } // Paper - OBFHELPER - public UUID k() { - return new UUID(this.readLong(), this.readLong()); - } - - public PacketDataSerializer d(int i) { - while ((i & -128) != 0) { - this.writeByte(i & 127 | 128); - i >>>= 7; - } - - this.writeByte(i); - return this; - } - - public PacketDataSerializer b(long i) { - while ((i & -128L) != 0L) { - this.writeByte((int) (i & 127L) | 128); - i >>>= 7; - } - - this.writeByte((int) i); - return this; - } - - public PacketDataSerializer a(@Nullable 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); - } - } - - return this; - } - - @Nullable - public NBTTagCompound l() { - int i = this.readerIndex(); - byte b0 = this.readByte(); - - if (b0 == 0) { - return null; - } else { - this.readerIndex(i); - - try { - return NBTCompressedStreamTools.a((DataInput) (new ByteBufInputStream(this)), new NBTReadLimiter(2097152L)); - } catch (IOException ioexception) { - throw new EncoderException(ioexception); - } - } - } - - public PacketDataSerializer a(ItemStack itemstack) { - if (itemstack.isEmpty() || itemstack.getItem() == null) { // CraftBukkit - NPE fix itemstack.getItem() - this.writeBoolean(false); - } else { - this.writeBoolean(true); - Item item = itemstack.getItem(); - - this.d(Item.getId(item)); - this.writeByte(itemstack.getCount()); - NBTTagCompound nbttagcompound = null; - - if (item.usesDurability() || item.m()) { - // Spigot start - filter - itemstack = itemstack.cloneItemStack(); - CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); - // Spigot end - nbttagcompound = itemstack.getTag(); - // Paper start - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("SkullOwner", 10)) { - NBTTagCompound owner = nbttagcompound.getCompound("SkullOwner"); - if (owner.hasKey("Id")) { - nbttagcompound.setString("SkullOwnerOrig", owner.getString("Id")); - TileEntitySkull.sanitizeUUID(owner); - } - } - // Paper end - } - - this.a(nbttagcompound); - } - - return this; - } - - public ItemStack m() { - if (!this.readBoolean()) { - return ItemStack.a; - } else { - int i = this.i(); - byte b0 = this.readByte(); - ItemStack itemstack = new ItemStack(Item.getById(i), b0); - - itemstack.setTag(this.l()); - // CraftBukkit start - if (itemstack.getTag() != null) { - // Paper start - Fix skulls of same owner - restore orig ID since we changed it on send to client - if (itemstack.tag.hasKey("SkullOwnerOrig")) { - NBTTagCompound owner = itemstack.tag.getCompound("SkullOwner"); - String ownerOrig = itemstack.tag.getString("SkullOwnerOrig"); - if (!owner.isEmpty() && !ownerOrig.isEmpty()) { - owner.setString("Id", ownerOrig); - } - itemstack.tag.remove("SkullOwnerOrig"); - } - // Paper end - CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); - } - // CraftBukkit end - return itemstack; - } - } - - public String readUTF(int maxLength) { return this.e(maxLength); } // Paper - OBFHELPER - public String e(int i) { - int j = this.i(); - - if (j > i * 4) { - throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + j + " > " + i * 4 + ")"); - } else if (j < 0) { - throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); - } else { - String s = this.toString(this.readerIndex(), j, StandardCharsets.UTF_8); - - this.readerIndex(this.readerIndex() + j); - if (s.length() > i) { - throw new DecoderException("The received string length is longer than maximum allowed (" + j + " > " + i + ")"); - } else { - return s; - } - } - } - - public PacketDataSerializer a(String s) { - return this.a(s, 32767); - } - - public PacketDataSerializer a(String s, int i) { - byte[] abyte = s.getBytes(StandardCharsets.UTF_8); - - if (abyte.length > i) { - throw new EncoderException("String too big (was " + abyte.length + " bytes encoded, max " + i + ")"); - } else { - this.d(abyte.length); - this.writeBytes(abyte); - return this; - } - } - - public MinecraftKey o() { - return new MinecraftKey(this.e(32767)); - } - - public PacketDataSerializer a(MinecraftKey minecraftkey) { - this.a(minecraftkey.toString()); - return this; - } - - public Date p() { - return new Date(this.readLong()); - } - - public PacketDataSerializer a(Date date) { - this.writeLong(date.getTime()); - return this; - } - - public MovingObjectPositionBlock q() { - BlockPosition blockposition = this.e(); - EnumDirection enumdirection = (EnumDirection) this.a(EnumDirection.class); - float f = this.readFloat(); - float f1 = this.readFloat(); - float f2 = this.readFloat(); - boolean flag = this.readBoolean(); - - return new MovingObjectPositionBlock(new Vec3D((double) ((float) blockposition.getX() + f), (double) ((float) blockposition.getY() + f1), (double) ((float) blockposition.getZ() + f2)), enumdirection, blockposition, flag); - } - - public void a(MovingObjectPositionBlock movingobjectpositionblock) { - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition(); - - this.a(blockposition); - this.a((Enum) movingobjectpositionblock.getDirection()); - Vec3D vec3d = movingobjectpositionblock.getPos(); - - this.writeFloat((float) (vec3d.x - (double) blockposition.getX())); - this.writeFloat((float) (vec3d.y - (double) blockposition.getY())); - this.writeFloat((float) (vec3d.z - (double) blockposition.getZ())); - this.writeBoolean(movingobjectpositionblock.d()); - } - - 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 this.a.isReadOnly(); - } - - public ByteBuf asReadOnly() { - return this.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 this.a.getShortLE(i); - } - - public int getUnsignedShort(int i) { - return this.a.getUnsignedShort(i); - } - - public int getUnsignedShortLE(int i) { - return this.a.getUnsignedShortLE(i); - } - - public int getMedium(int i) { - return this.a.getMedium(i); - } - - public int getMediumLE(int i) { - return this.a.getMediumLE(i); - } - - public int getUnsignedMedium(int i) { - return this.a.getUnsignedMedium(i); - } - - public int getUnsignedMediumLE(int i) { - return this.a.getUnsignedMediumLE(i); - } - - public int getInt(int i) { - return this.a.getInt(i); - } - - public int getIntLE(int i) { - return this.a.getIntLE(i); - } - - public long getUnsignedInt(int i) { - return this.a.getUnsignedInt(i); - } - - public long getUnsignedIntLE(int i) { - return this.a.getUnsignedIntLE(i); - } - - public long getLong(int i) { - return this.a.getLong(i); - } - - public long getLongLE(int i) { - return this.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 j, int k) throws IOException { - return this.a.getBytes(i, filechannel, j, k); - } - - public CharSequence getCharSequence(int i, int j, Charset charset) { - return this.a.getCharSequence(i, j, 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 j) { - return this.a.setShortLE(i, j); - } - - public ByteBuf setMedium(int i, int j) { - return this.a.setMedium(i, j); - } - - public ByteBuf setMediumLE(int i, int j) { - return this.a.setMediumLE(i, j); - } - - public ByteBuf setInt(int i, int j) { - return this.a.setInt(i, j); - } - - public ByteBuf setIntLE(int i, int j) { - return this.a.setIntLE(i, j); - } - - public ByteBuf setLong(int i, long j) { - return this.a.setLong(i, j); - } - - public ByteBuf setLongLE(int i, long j) { - return this.a.setLongLE(i, j); - } - - 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 j, int k) throws IOException { - return this.a.setBytes(i, filechannel, j, k); - } - - public ByteBuf setZero(int i, int j) { - return this.a.setZero(i, j); - } - - public int setCharSequence(int i, CharSequence charsequence, Charset charset) { - return this.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 this.a.readShortLE(); - } - - public int readUnsignedShort() { - return this.a.readUnsignedShort(); - } - - public int readUnsignedShortLE() { - return this.a.readUnsignedShortLE(); - } - - public int readMedium() { - return this.a.readMedium(); - } - - public int readMediumLE() { - return this.a.readMediumLE(); - } - - public int readUnsignedMedium() { - return this.a.readUnsignedMedium(); - } - - public int readUnsignedMediumLE() { - return this.a.readUnsignedMediumLE(); - } - - public int readInt() { - return this.a.readInt(); - } - - public int readIntLE() { - return this.a.readIntLE(); - } - - public long readUnsignedInt() { - return this.a.readUnsignedInt(); - } - - public long readUnsignedIntLE() { - return this.a.readUnsignedIntLE(); - } - - public long readLong() { - return this.a.readLong(); - } - - public long readLongLE() { - return this.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 this.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 this.a.readCharSequence(i, charset); - } - - public int readBytes(FileChannel filechannel, long i, int j) throws IOException { - return this.a.readBytes(filechannel, i, j); - } - - 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 this.a.writeShortLE(i); - } - - public ByteBuf writeMedium(int i) { - return this.a.writeMedium(i); - } - - public ByteBuf writeMediumLE(int i) { - return this.a.writeMediumLE(i); - } - - public ByteBuf writeInt(int i) { - return this.a.writeInt(i); - } - - public ByteBuf writeIntLE(int i) { - return this.a.writeIntLE(i); - } - - public ByteBuf writeLong(long i) { - return this.a.writeLong(i); - } - - public ByteBuf writeLongLE(long i) { - return this.a.writeLongLE(i); - } - - 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 i, int j) throws IOException { - return this.a.writeBytes(filechannel, i, j); - } - - public ByteBuf writeZero(int i) { - return this.a.writeZero(i); - } - - public int writeCharSequence(CharSequence charsequence, Charset charset) { - return this.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 this.a.forEachByte(byteprocessor); - } - - public int forEachByte(int i, int j, ByteProcessor byteprocessor) { - return this.a.forEachByte(i, j, byteprocessor); - } - - public int forEachByteDesc(ByteProcessor byteprocessor) { - return this.a.forEachByteDesc(byteprocessor); - } - - public int forEachByteDesc(int i, int j, ByteProcessor byteprocessor) { - return this.a.forEachByteDesc(i, j, 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 this.a.retainedSlice(); - } - - public ByteBuf slice(int i, int j) { - return this.a.slice(i, j); - } - - public ByteBuf retainedSlice(int i, int j) { - return this.a.retainedSlice(i, j); - } - - public ByteBuf duplicate() { - return this.a.duplicate(); - } - - public ByteBuf retainedDuplicate() { - return this.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 this.a.touch(); - } - - public ByteBuf touch(Object object) { - return this.a.touch(object); - } - - public int refCnt() { - return this.a.refCnt(); - } - - public boolean release() { - return this.a.release(); - } - - public boolean release(int i) { - return this.a.release(i); - } -} diff --git a/src/main/java/net/minecraft/server/PacketEncoder.java b/src/main/java/net/minecraft/server/PacketEncoder.java deleted file mode 100644 index b0cfef52c..000000000 --- a/src/main/java/net/minecraft/server/PacketEncoder.java +++ /dev/null @@ -1,79 +0,0 @@ -package net.minecraft.server; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; -import java.io.IOException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; - -public class PacketEncoder extends MessageToByteEncoder> { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final Marker b = MarkerManager.getMarker("PACKET_SENT", NetworkManager.b); - private final EnumProtocolDirection c; - - public PacketEncoder(EnumProtocolDirection enumprotocoldirection) { - this.c = enumprotocoldirection; - } - - protected void encode(ChannelHandlerContext channelhandlercontext, Packet packet, ByteBuf bytebuf) throws Exception { - EnumProtocol enumprotocol = (EnumProtocol) channelhandlercontext.channel().attr(NetworkManager.c).get(); - - if (enumprotocol == null) { - throw new RuntimeException("ConnectionProtocol unknown: " + packet); - } else { - Integer integer = enumprotocol.a(this.c, packet); - - if (PacketEncoder.LOGGER.isDebugEnabled()) { - PacketEncoder.LOGGER.debug(PacketEncoder.b, "OUT: [{}:{}] {}", channelhandlercontext.channel().attr(NetworkManager.c).get(), integer, packet.getClass().getName()); - } - - if (integer == null) { - throw new IOException("Can't serialize unregistered packet"); - } else { - PacketDataSerializer packetdataserializer = new PacketDataSerializer(bytebuf); - - packetdataserializer.d(integer); - - try { - packet.b(packetdataserializer); - } catch (Throwable throwable) { - PacketEncoder.LOGGER.error(throwable); - throwable.printStackTrace(); // Paper - WHAT WAS IT? WHO DID THIS TO YOU? WHAT DID YOU SEE? - if (packet.a()) { - throw new SkipEncodeException(throwable); - } else { - throw throwable; - } - } - - // Paper start - int packetLength = bytebuf.readableBytes(); - if (packetLength > MAX_PACKET_SIZE) { - throw new PacketTooLargeException(packet, packetLength); - } - // Paper end - } - } - } - - // Paper start - private static int MAX_PACKET_SIZE = 2097152; - - public static class PacketTooLargeException extends RuntimeException { - private final Packet packet; - - PacketTooLargeException(Packet packet, int packetLength) { - super("PacketTooLarge - " + packet.getClass().getSimpleName() + " is " + packetLength + ". Max is " + MAX_PACKET_SIZE); - this.packet = packet; - } - - public Packet getPacket() { - return packet; - } - } - // Paper end -} diff --git a/src/main/java/net/minecraft/server/PacketHandshakingInSetProtocol.java b/src/main/java/net/minecraft/server/PacketHandshakingInSetProtocol.java deleted file mode 100644 index 8545146fb..000000000 --- a/src/main/java/net/minecraft/server/PacketHandshakingInSetProtocol.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketHandshakingInSetProtocol implements Packet { - - private int a; - public String hostname; - public int port; - private EnumProtocol d; - - public PacketHandshakingInSetProtocol() {} - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.i(); - this.hostname = packetdataserializer.e(Short.MAX_VALUE); // Spigot - this.port = packetdataserializer.readUnsignedShort(); - this.d = EnumProtocol.a(packetdataserializer.i()); - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.d(this.a); - packetdataserializer.a(this.hostname); - packetdataserializer.writeShort(this.port); - packetdataserializer.d(this.d.a()); - } - - public void a(PacketHandshakingInListener packethandshakinginlistener) { - packethandshakinginlistener.a(this); - } - - public EnumProtocol b() { - return this.d; - } - - public int getProtocolVersion() { return c(); } // Paper - OBFHELPER - public int c() { - return this.a; - } -} diff --git a/src/main/java/net/minecraft/server/PacketLoginInCustomPayload.java b/src/main/java/net/minecraft/server/PacketLoginInCustomPayload.java deleted file mode 100644 index c1ca6f950..000000000 --- a/src/main/java/net/minecraft/server/PacketLoginInCustomPayload.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketLoginInCustomPayload implements Packet { - - private int a; public int getId() { return a; } // Paper - OBFHELPER - private PacketDataSerializer b; public PacketDataSerializer getBuf() { return b; } // Paper - OBFHELPER - - public PacketLoginInCustomPayload() {} - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.i(); - if (packetdataserializer.readBoolean()) { - int i = packetdataserializer.readableBytes(); - - if (i < 0 || i > 1048576) { - throw new IOException("Payload may not be larger than 1048576 bytes"); - } - - this.b = new PacketDataSerializer(packetdataserializer.readBytes(i)); - } else { - this.b = null; - } - - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.d(this.a); - if (this.b != null) { - packetdataserializer.writeBoolean(true); - packetdataserializer.writeBytes(this.b.copy()); - } else { - packetdataserializer.writeBoolean(false); - } - - } - - public void a(PacketLoginInListener packetlogininlistener) { - packetlogininlistener.a(this); - } -} diff --git a/src/main/java/net/minecraft/server/PacketLoginOutCustomPayload.java b/src/main/java/net/minecraft/server/PacketLoginOutCustomPayload.java deleted file mode 100644 index 7eb230f1b..000000000 --- a/src/main/java/net/minecraft/server/PacketLoginOutCustomPayload.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketLoginOutCustomPayload implements Packet { - - private int a; - private MinecraftKey b; - private PacketDataSerializer c; - - public PacketLoginOutCustomPayload() {} - - // Paper start - public PacketLoginOutCustomPayload(int id, MinecraftKey channel, PacketDataSerializer buf) { - this.a = id; - this.b = channel; - this.c = buf; - } - // Paper end - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.i(); - this.b = packetdataserializer.o(); - int i = packetdataserializer.readableBytes(); - - if (i >= 0 && i <= 1048576) { - this.c = new PacketDataSerializer(packetdataserializer.readBytes(i)); - } else { - throw new IOException("Payload may not be larger than 1048576 bytes"); - } - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.d(this.a); - packetdataserializer.a(this.b); - packetdataserializer.writeBytes(this.c.copy()); - } - - public void a(PacketLoginOutListener packetloginoutlistener) { - packetloginoutlistener.a(this); - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java b/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java deleted file mode 100644 index 194576502..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketPlayInBlockPlace implements Packet { - - private EnumHand a; - public long timestamp; // Spigot - - public PacketPlayInBlockPlace() {} - - public PacketPlayInBlockPlace(EnumHand enumhand) { - this.a = enumhand; - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.timestamp = System.currentTimeMillis(); // Spigot - this.a = (EnumHand) packetdataserializer.a(EnumHand.class); - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.a((Enum) this.a); - } - - public void a(PacketListenerPlayIn packetlistenerplayin) { - packetlistenerplayin.a(this); - } - - public EnumHand b() { - return this.a; - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayInChat.java b/src/main/java/net/minecraft/server/PacketPlayInChat.java deleted file mode 100644 index b2ca841b4..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayInChat.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketPlayInChat implements Packet { - - private String a; - - public PacketPlayInChat() {} - - public PacketPlayInChat(String s) { - if (s.length() > 256) { - s = s.substring(0, 256); - } - - this.a = s; - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.e(256); - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.a(this.a); - } - - // Spigot Start - private static final java.util.concurrent.ExecutorService executors = java.util.concurrent.Executors.newCachedThreadPool( - new com.google.common.util.concurrent.ThreadFactoryBuilder().setDaemon( true ).setNameFormat( "Async Chat Thread - #%d" ).build() ); - public void a(final PacketListenerPlayIn packetlistenerplayin) { - if ( !a.startsWith("/") ) - { - executors.submit( new Runnable() - { - - @Override - public void run() - { - packetlistenerplayin.a( PacketPlayInChat.this ); - } - } ); - return; - } - // Spigot End - packetlistenerplayin.a(this); - } - - public String b() { - return this.a; - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayInCloseWindow.java b/src/main/java/net/minecraft/server/PacketPlayInCloseWindow.java deleted file mode 100644 index 03f4e32ed..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayInCloseWindow.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketPlayInCloseWindow implements Packet { - - private int id; - - public PacketPlayInCloseWindow() {} - - // CraftBukkit start - public PacketPlayInCloseWindow(int id) { - this.id = id; - } - // CraftBukkit end - - public void a(PacketListenerPlayIn packetlistenerplayin) { - packetlistenerplayin.a(this); - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.id = packetdataserializer.readByte(); - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.writeByte(this.id); - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java b/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java deleted file mode 100644 index 3f7697b39..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; -import javax.annotation.Nullable; - -public class PacketPlayInUseEntity implements Packet { - - private int a; public int getEntityId() { return this.a; } // Paper - add accessor - private PacketPlayInUseEntity.EnumEntityUseAction action; - private Vec3D c; - private EnumHand d; - - public PacketPlayInUseEntity() {} - - public PacketPlayInUseEntity(Entity entity) { - this.a = entity.getId(); - this.action = PacketPlayInUseEntity.EnumEntityUseAction.ATTACK; - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.i(); - this.action = (PacketPlayInUseEntity.EnumEntityUseAction) packetdataserializer.a(PacketPlayInUseEntity.EnumEntityUseAction.class); - if (this.action == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT_AT) { - this.c = new Vec3D((double) packetdataserializer.readFloat(), (double) packetdataserializer.readFloat(), (double) packetdataserializer.readFloat()); - } - - if (this.action == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT || this.action == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT_AT) { - this.d = (EnumHand) packetdataserializer.a(EnumHand.class); - } - - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.d(this.a); - packetdataserializer.a((Enum) this.action); - if (this.action == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT_AT) { - packetdataserializer.writeFloat((float) this.c.x); - packetdataserializer.writeFloat((float) this.c.y); - packetdataserializer.writeFloat((float) this.c.z); - } - - if (this.action == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT || this.action == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT_AT) { - packetdataserializer.a((Enum) this.d); - } - - } - - public void a(PacketListenerPlayIn packetlistenerplayin) { - packetlistenerplayin.a(this); - } - - @Nullable - public Entity a(World world) { - return world.getEntity(this.a); - } - - public PacketPlayInUseEntity.EnumEntityUseAction b() { - return this.action; - } - - public EnumHand c() { - return this.d; - } - - public Vec3D d() { - return this.c; - } - - public static enum EnumEntityUseAction { - - INTERACT, ATTACK, INTERACT_AT; - - private EnumEntityUseAction() {} - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayInUseItem.java b/src/main/java/net/minecraft/server/PacketPlayInUseItem.java deleted file mode 100644 index 5941c3a5e..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayInUseItem.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketPlayInUseItem implements Packet { - - private MovingObjectPositionBlock a; - private EnumHand b; - public long timestamp; - - public PacketPlayInUseItem() {} - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.timestamp = System.currentTimeMillis(); // Spigot - this.b = (EnumHand) packetdataserializer.a(EnumHand.class); - this.a = packetdataserializer.q(); - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.a((Enum) this.b); - packetdataserializer.a(this.a); - } - - public void a(PacketListenerPlayIn packetlistenerplayin) { - packetlistenerplayin.a(this); - } - - public EnumHand b() { - return this.b; - } - - public MovingObjectPositionBlock c() { - return this.a; - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayOutChat.java b/src/main/java/net/minecraft/server/PacketPlayOutChat.java deleted file mode 100644 index f7b2095bb..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayOutChat.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketPlayOutChat implements Packet { - private static final int MAX_LENGTH = Short.MAX_VALUE * 8 + 8; // Paper - private IChatBaseComponent a; - public net.md_5.bungee.api.chat.BaseComponent[] components; // Spigot - private ChatMessageType b; - - public PacketPlayOutChat() {} - - public PacketPlayOutChat(IChatBaseComponent ichatbasecomponent) { - this(ichatbasecomponent, ChatMessageType.SYSTEM); - } - - public PacketPlayOutChat(IChatBaseComponent ichatbasecomponent, ChatMessageType chatmessagetype) { - this.a = ichatbasecomponent; - this.b = chatmessagetype; - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.h(); - this.b = ChatMessageType.a(packetdataserializer.readByte()); - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - // Spigot start - if (components != null) { - //packetdataserializer.a(net.md_5.bungee.chat.ComponentSerializer.toString(components)); // Paper - comment, replaced with below - // Paper start - don't nest if we don't need to so that we can preserve formatting - if (this.components.length == 1) { - packetdataserializer.a(net.md_5.bungee.chat.ComponentSerializer.toString(this.components[0]), MAX_LENGTH); // Paper - use proper max length - } else { - packetdataserializer.a(net.md_5.bungee.chat.ComponentSerializer.toString(this.components), MAX_LENGTH); // Paper - use proper max length - } - // Paper end - } else { - packetdataserializer.a(this.a); - } - // Spigot end - packetdataserializer.writeByte(this.b.a()); - } - - public void a(PacketListenerPlayOut packetlistenerplayout) { - packetlistenerplayout.a(this); - } - - public boolean c() { - return this.b == ChatMessageType.SYSTEM || this.b == ChatMessageType.GAME_INFO; - } - - public ChatMessageType d() { - return this.b; - } - - @Override - public boolean a() { - return true; - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java b/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java deleted file mode 100644 index 483317608..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java +++ /dev/null @@ -1,218 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.antixray.ChunkPacketInfo; // Paper - Anti-Xray -import com.google.common.collect.Lists; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; - -public class PacketPlayOutMapChunk implements Packet { - - private int a; - private int b; - private int c; - private NBTTagCompound d; - private byte[] e; private byte[] getData() { return this.e; } // Paper - OBFHELPER - private List f; - private boolean g; - private volatile boolean ready; // Paper - Async-Anti-Xray - Ready flag for the network manager - - public PacketPlayOutMapChunk() { - this.ready = true; // Paper - Async-Anti-Xray - Set the ready flag to true - } - - // Paper start - private final java.util.List extraPackets = new java.util.ArrayList<>(); - private static final int SKIP_EXCESSIVE_SIGNS_LIMIT = Integer.getInteger("Paper.excessiveSignsLimit", 500); - - @Override - public java.util.List getExtraPackets() { - return extraPackets; - } - // Paper end - public PacketPlayOutMapChunk(Chunk chunk, int i) { - // Paper start - add forceLoad param - this(chunk, i, false); - } - public PacketPlayOutMapChunk(Chunk chunk, int i, boolean forceLoad) { - // Paper end - ChunkPacketInfo chunkPacketInfo = chunk.world.chunkPacketBlockController.getChunkPacketInfo(this, chunk, i, forceLoad); // Paper - Anti-Xray - Add chunk packet info - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - - this.a = chunkcoordintpair.x; - this.b = chunkcoordintpair.z; - this.g = i == 65535; - this.d = new NBTTagCompound(); - Iterator iterator = chunk.f().iterator(); - - Entry entry; - - while (iterator.hasNext()) { - entry = (Entry) iterator.next(); - if (((HeightMap.Type) entry.getKey()).b()) { - this.d.set(((HeightMap.Type) entry.getKey()).a(), new NBTTagLongArray(((HeightMap) entry.getValue()).a())); - } - } - - this.e = new byte[this.a(chunk, i)]; - // Paper start - Anti-Xray - Add chunk packet info - if (chunkPacketInfo != null) { - chunkPacketInfo.setData(this.getData()); - } - // Paper end - this.c = this.writeChunk(new PacketDataSerializer(this.i()), chunk, i, chunkPacketInfo); // Paper - Anti-Xray - Add chunk packet info - this.f = Lists.newArrayList(); - iterator = chunk.getTileEntities().entrySet().iterator(); - int totalSigns = 0; // Paper - - while (iterator.hasNext()) { - entry = (Entry) iterator.next(); - BlockPosition blockposition = (BlockPosition) entry.getKey(); - TileEntity tileentity = (TileEntity) entry.getValue(); - int j = blockposition.getY() >> 4; - - if (this.f() || (i & 1 << j) != 0) { - // Paper start - send signs separately - if (tileentity instanceof TileEntitySign) { - if (SKIP_EXCESSIVE_SIGNS_LIMIT < 0 || ++totalSigns < SKIP_EXCESSIVE_SIGNS_LIMIT) { - this.extraPackets.add(tileentity.getUpdatePacket()); - } - continue; - } - // Paper end - NBTTagCompound nbttagcompound = tileentity.b(); - if (tileentity instanceof TileEntitySkull) { TileEntitySkull.sanitizeTileEntityUUID(nbttagcompound); } // Paper - - this.f.add(nbttagcompound); - } - } - chunk.world.chunkPacketBlockController.modifyBlocks(this, chunkPacketInfo, forceLoad, null); // Paper - Anti-Xray - Modify blocks - } - - // Paper start - Async-Anti-Xray - Getter and Setter for the ready flag - public boolean isReady() { - return this.ready; - } - - public void setReady(boolean ready) { - this.ready = ready; - } - // Paper end - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.readInt(); - this.b = packetdataserializer.readInt(); - this.g = packetdataserializer.readBoolean(); - this.c = packetdataserializer.i(); - this.d = packetdataserializer.l(); - int i = packetdataserializer.i(); - - if (i > 2097152) { // Paper - if this changes, update PacketEncoder - throw new RuntimeException("Chunk Packet trying to allocate too much memory on read."); - } else { - this.e = new byte[i]; - packetdataserializer.readBytes(this.e); - int j = packetdataserializer.i(); - - this.f = Lists.newArrayList(); - - for (int k = 0; k < j; ++k) { - this.f.add(packetdataserializer.l()); - } - - } - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.writeInt(this.a); - packetdataserializer.writeInt(this.b); - packetdataserializer.writeBoolean(this.g); - packetdataserializer.d(this.c); - packetdataserializer.a(this.d); - packetdataserializer.d(this.e.length); - packetdataserializer.writeBytes(this.e); - packetdataserializer.d(this.f.size()); - Iterator iterator = this.f.iterator(); - - while (iterator.hasNext()) { - NBTTagCompound nbttagcompound = (NBTTagCompound) iterator.next(); - - packetdataserializer.a(nbttagcompound); - } - - } - - public void a(PacketListenerPlayOut packetlistenerplayout) { - packetlistenerplayout.a(this); - } - - private ByteBuf i() { - ByteBuf bytebuf = Unpooled.wrappedBuffer(this.e); - - bytebuf.writerIndex(0); - return bytebuf; - } - - public int writeChunk(PacketDataSerializer packetDataSerializer, Chunk chunk, int chunkSectionSelector) { return this.a(packetDataSerializer, chunk, chunkSectionSelector); } // Paper - OBFHELPER - public int a(PacketDataSerializer packetdataserializer, Chunk chunk, int i) { - // Paper start - Add parameter - return this.writeChunk(packetdataserializer, chunk, i, null); - } - public int writeChunk(PacketDataSerializer packetdataserializer, Chunk chunk, int i, ChunkPacketInfo chunkPacketInfo) { - // Paper end - int j = 0; - ChunkSection[] achunksection = chunk.getSections(); - int k = 0; - - int l; - - for (l = achunksection.length; k < l; ++k) { - ChunkSection chunksection = achunksection[k]; - - if (chunksection != Chunk.a && (!this.f() || !chunksection.c()) && (i & 1 << k) != 0) { - j |= 1 << k; - packetdataserializer.writeShort(chunksection.nonEmptyBlockCount); // Paper - Anti-Xray - Add chunk packet info - chunksection.getBlocks().writeDataPaletteBlock(packetdataserializer, chunkPacketInfo, k); // Paper - Anti-Xray - Add chunk packet info - } - } - - if (this.f()) { - BiomeBase[] abiomebase = chunk.getBiomeIndex(); - - for (l = 0; l < abiomebase.length; ++l) { - packetdataserializer.writeInt(IRegistry.BIOME.a(abiomebase[l])); // Paper - decompile fix - } - } - - return j; - } - - protected int a(Chunk chunk, int i) { - int j = 0; - ChunkSection[] achunksection = chunk.getSections(); - int k = 0; - - for (int l = achunksection.length; k < l; ++k) { - ChunkSection chunksection = achunksection[k]; - - if (chunksection != Chunk.a && (!this.f() || !chunksection.c()) && (i & 1 << k) != 0) { - j += chunksection.j(); - } - } - - if (this.f()) { - j += chunk.getBiomeIndex().length * 4; - } - - return j; - } - - public boolean f() { - return this.g; - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java b/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java deleted file mode 100644 index 6b1a914d2..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java +++ /dev/null @@ -1,121 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.io.IOException; -import java.util.Collection; -import java.util.Iterator; - -public class PacketPlayOutScoreboardTeam implements Packet { - - private String a = ""; - private IChatBaseComponent b = new ChatComponentText(""); - private IChatBaseComponent c = new ChatComponentText(""); - private IChatBaseComponent d = new ChatComponentText(""); - private String e; - private String f; - private EnumChatFormat g; - private final Collection h; - private int i; - private int j; - - public PacketPlayOutScoreboardTeam() { - this.e = ScoreboardTeamBase.EnumNameTagVisibility.ALWAYS.e; - this.f = ScoreboardTeamBase.EnumTeamPush.ALWAYS.e; - this.g = EnumChatFormat.RESET; - this.h = Lists.newArrayList(); - } - - public PacketPlayOutScoreboardTeam(ScoreboardTeam scoreboardteam, int i) { - this.e = ScoreboardTeamBase.EnumNameTagVisibility.ALWAYS.e; - this.f = ScoreboardTeamBase.EnumTeamPush.ALWAYS.e; - this.g = EnumChatFormat.RESET; - this.h = Lists.newArrayList(); - this.a = scoreboardteam.getName(); - this.i = i; - if (i == 0 || i == 2) { - this.b = scoreboardteam.getDisplayName(); - this.j = scoreboardteam.packOptionData(); - this.e = scoreboardteam.getNameTagVisibility().e; - this.f = scoreboardteam.getCollisionRule().e; - this.g = scoreboardteam.getColor(); - this.c = scoreboardteam.getPrefix(); - this.d = scoreboardteam.getSuffix(); - } - - if (i == 0) { - this.h.addAll(scoreboardteam.getPlayerNameSet()); - } - - } - - public PacketPlayOutScoreboardTeam(ScoreboardTeam scoreboardteam, Collection collection, int i) { - this.e = ScoreboardTeamBase.EnumNameTagVisibility.ALWAYS.e; - this.f = ScoreboardTeamBase.EnumTeamPush.ALWAYS.e; - this.g = EnumChatFormat.RESET; - this.h = Lists.newArrayList(); - if (i != 3 && i != 4) { - throw new IllegalArgumentException("Method must be join or leave for player constructor"); - } else if (collection != null && !collection.isEmpty()) { - this.i = i; - this.a = scoreboardteam.getName(); - this.h.addAll(collection); - } else { - throw new IllegalArgumentException("Players cannot be null/empty"); - } - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.e(16); - this.i = packetdataserializer.readByte(); - if (this.i == 0 || this.i == 2) { - this.b = packetdataserializer.h(); - this.j = packetdataserializer.readByte(); - this.e = packetdataserializer.e(40); - this.f = packetdataserializer.e(40); - this.g = (EnumChatFormat) packetdataserializer.a(EnumChatFormat.class); - this.c = packetdataserializer.h(); - this.d = packetdataserializer.h(); - } - - if (this.i == 0 || this.i == 3 || this.i == 4) { - int i = packetdataserializer.i(); - - for (int j = 0; j < i; ++j) { - this.h.add(packetdataserializer.e(40)); - } - } - - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.a(this.a); - packetdataserializer.writeByte(this.i); - if (this.i == 0 || this.i == 2) { - packetdataserializer.a(this.b); - packetdataserializer.writeByte(this.j); - packetdataserializer.a(this.e); - packetdataserializer.a(!com.destroystokyo.paper.PaperConfig.enablePlayerCollisions ? "never" : this.f); // Paper - packetdataserializer.a((Enum) this.g); - packetdataserializer.a(this.c); - packetdataserializer.a(this.d); - } - - if (this.i == 0 || this.i == 3 || this.i == 4) { - packetdataserializer.d(this.h.size()); - Iterator iterator = this.h.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - - packetdataserializer.a(s); - } - } - - } - - public void a(PacketListenerPlayOut packetlistenerplayout) { - packetlistenerplayout.a(this); - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayOutTitle.java b/src/main/java/net/minecraft/server/PacketPlayOutTitle.java deleted file mode 100644 index 535056c64..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayOutTitle.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; -import javax.annotation.Nullable; - -public class PacketPlayOutTitle implements Packet { - - private PacketPlayOutTitle.EnumTitleAction a; - private IChatBaseComponent b; - private int c; - private int d; - private int e; - - public PacketPlayOutTitle() {} - - public PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction packetplayouttitle_enumtitleaction, IChatBaseComponent ichatbasecomponent) { - this(packetplayouttitle_enumtitleaction, ichatbasecomponent, -1, -1, -1); - } - - public PacketPlayOutTitle(int i, int j, int k) { - this(PacketPlayOutTitle.EnumTitleAction.TIMES, (IChatBaseComponent) null, i, j, k); - } - - public PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction packetplayouttitle_enumtitleaction, @Nullable IChatBaseComponent ichatbasecomponent, int i, int j, int k) { - this.a = packetplayouttitle_enumtitleaction; - this.b = ichatbasecomponent; - this.c = i; - this.d = j; - this.e = k; - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = (PacketPlayOutTitle.EnumTitleAction) packetdataserializer.a(PacketPlayOutTitle.EnumTitleAction.class); - if (this.a == PacketPlayOutTitle.EnumTitleAction.TITLE || this.a == PacketPlayOutTitle.EnumTitleAction.SUBTITLE || this.a == PacketPlayOutTitle.EnumTitleAction.ACTIONBAR) { - this.b = packetdataserializer.h(); - } - - if (this.a == PacketPlayOutTitle.EnumTitleAction.TIMES) { - this.c = packetdataserializer.readInt(); - this.d = packetdataserializer.readInt(); - this.e = packetdataserializer.readInt(); - } - - } - // Paper start - public net.md_5.bungee.api.chat.BaseComponent[] components; - - 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; - } - // Paper end - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.a((Enum) this.a); - if (this.a == PacketPlayOutTitle.EnumTitleAction.TITLE || this.a == PacketPlayOutTitle.EnumTitleAction.SUBTITLE || this.a == PacketPlayOutTitle.EnumTitleAction.ACTIONBAR) { - // 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 == PacketPlayOutTitle.EnumTitleAction.TIMES) { - packetdataserializer.writeInt(this.c); - packetdataserializer.writeInt(this.d); - packetdataserializer.writeInt(this.e); - } - - } - - public void a(PacketListenerPlayOut packetlistenerplayout) { - packetlistenerplayout.a(this); - } - - public static enum EnumTitleAction { - - TITLE, SUBTITLE, ACTIONBAR, TIMES, CLEAR, RESET; - - private EnumTitleAction() {} - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayOutUpdateTime.java b/src/main/java/net/minecraft/server/PacketPlayOutUpdateTime.java deleted file mode 100644 index 15af5927f..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayOutUpdateTime.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketPlayOutUpdateTime implements Packet { - - // World Age in ticks - // Not changed by server commands - // World Age must not be negative - private long a; - // Time of Day in ticks - // If negative the sun will stop moving at the Math.abs of the time - // Displayed in the debug screen (F3) - private long b; - - public PacketPlayOutUpdateTime() {} - - public PacketPlayOutUpdateTime(long i, long j, boolean flag) { - this.a = i; - this.b = j; - if (!flag) { - this.b = -this.b; - if (this.b == 0L) { - this.b = -1L; - } - } - - // Paper start - this.a = this.a % 192000; - // Paper end - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.readLong(); - this.b = packetdataserializer.readLong(); - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.writeLong(this.a); - packetdataserializer.writeLong(this.b); - } - - public void a(PacketListenerPlayOut packetlistenerplayout) { - packetlistenerplayout.a(this); - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayOutWindowItems.java b/src/main/java/net/minecraft/server/PacketPlayOutWindowItems.java deleted file mode 100644 index 631234324..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayOutWindowItems.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -public class PacketPlayOutWindowItems implements Packet { - - private int a; - private List b; - - //Paper start - @Override - public boolean packetTooLarge(NetworkManager manager) { - for (int i = 0 ; i < this.b.size() ; i++) { - manager.sendPacket(new PacketPlayOutSetSlot(this.a, i, this.b.get(i))); - } - return true; - } - // Paper end - public PacketPlayOutWindowItems() {} - - public PacketPlayOutWindowItems(int i, NonNullList nonnulllist) { - this.a = i; - this.b = NonNullList.a(nonnulllist.size(), ItemStack.a); - - for (int j = 0; j < this.b.size(); ++j) { - this.b.set(j, ((ItemStack) nonnulllist.get(j)).cloneItemStack()); - } - - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = packetdataserializer.readUnsignedByte(); - short short0 = packetdataserializer.readShort(); - - this.b = NonNullList.a(short0, ItemStack.a); - - for (int i = 0; i < short0; ++i) { - this.b.set(i, packetdataserializer.m()); - } - - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.writeByte(this.a); - packetdataserializer.writeShort(this.b.size()); - Iterator iterator = this.b.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - - packetdataserializer.a(itemstack); - } - - } - - public void a(PacketListenerPlayOut packetlistenerplayout) { - packetlistenerplayout.a(this); - } -} diff --git a/src/main/java/net/minecraft/server/PacketPlayOutWorldBorder.java b/src/main/java/net/minecraft/server/PacketPlayOutWorldBorder.java deleted file mode 100644 index c4310bd6b..000000000 --- a/src/main/java/net/minecraft/server/PacketPlayOutWorldBorder.java +++ /dev/null @@ -1,113 +0,0 @@ -package net.minecraft.server; - -import java.io.IOException; - -public class PacketPlayOutWorldBorder implements Packet { - - private PacketPlayOutWorldBorder.EnumWorldBorderAction a; - private int b; - private double c; - private double d; - private double e; - private double f; - private long g; - private int h; - private int i; - - public PacketPlayOutWorldBorder() {} - - public PacketPlayOutWorldBorder(WorldBorder worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction packetplayoutworldborder_enumworldborderaction) { - this.a = packetplayoutworldborder_enumworldborderaction; - // CraftBukkit start - multiply out nether border - this.c = worldborder.getCenterX() * (worldborder.world.worldProvider instanceof WorldProviderHell ? 8 : 1); - this.d = worldborder.getCenterZ() * (worldborder.world.worldProvider instanceof WorldProviderHell ? 8 : 1); - // CraftBukkit end - this.f = worldborder.getSize(); - this.e = worldborder.k(); - this.g = worldborder.j(); - this.b = worldborder.m(); - this.i = worldborder.getWarningDistance(); - this.h = worldborder.getWarningTime(); - } - - @Override - public void a(PacketDataSerializer packetdataserializer) throws IOException { - this.a = (PacketPlayOutWorldBorder.EnumWorldBorderAction) packetdataserializer.a(PacketPlayOutWorldBorder.EnumWorldBorderAction.class); - switch (this.a) { - case SET_SIZE: - this.e = packetdataserializer.readDouble(); - break; - case LERP_SIZE: - this.f = packetdataserializer.readDouble(); - this.e = packetdataserializer.readDouble(); - this.g = packetdataserializer.j(); - break; - case SET_CENTER: - this.c = packetdataserializer.readDouble(); - this.d = packetdataserializer.readDouble(); - break; - case SET_WARNING_BLOCKS: - this.i = packetdataserializer.i(); - break; - case SET_WARNING_TIME: - this.h = packetdataserializer.i(); - break; - case INITIALIZE: - this.c = packetdataserializer.readDouble(); - this.d = packetdataserializer.readDouble(); - this.f = packetdataserializer.readDouble(); - this.e = packetdataserializer.readDouble(); - this.g = packetdataserializer.j(); - this.b = packetdataserializer.i(); - this.i = packetdataserializer.i(); - this.h = packetdataserializer.i(); - } - - } - - @Override - public void b(PacketDataSerializer packetdataserializer) throws IOException { - packetdataserializer.a((Enum) this.a); - switch (this.a) { - case SET_SIZE: - packetdataserializer.writeDouble(this.e); - break; - case LERP_SIZE: - packetdataserializer.writeDouble(this.f); - packetdataserializer.writeDouble(this.e); - packetdataserializer.b(this.g); - break; - case SET_CENTER: - packetdataserializer.writeDouble(this.c); - packetdataserializer.writeDouble(this.d); - break; - case SET_WARNING_BLOCKS: - packetdataserializer.d(this.i); - break; - case SET_WARNING_TIME: - packetdataserializer.d(this.h); - break; - case INITIALIZE: - packetdataserializer.writeDouble(this.c); - packetdataserializer.writeDouble(this.d); - packetdataserializer.writeDouble(this.f); - packetdataserializer.writeDouble(this.e); - packetdataserializer.b(this.g); - packetdataserializer.d(this.b); - packetdataserializer.d(this.i); - packetdataserializer.d(this.h); - } - - } - - public void a(PacketListenerPlayOut packetlistenerplayout) { - packetlistenerplayout.a(this); - } - - public static enum EnumWorldBorderAction { - - SET_SIZE, LERP_SIZE, SET_CENTER, INITIALIZE, SET_WARNING_TIME, SET_WARNING_BLOCKS; - - private EnumWorldBorderAction() {} - } -} diff --git a/src/main/java/net/minecraft/server/PacketStatusListener.java b/src/main/java/net/minecraft/server/PacketStatusListener.java deleted file mode 100644 index 295c9ac22..000000000 --- a/src/main/java/net/minecraft/server/PacketStatusListener.java +++ /dev/null @@ -1,149 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import com.mojang.authlib.GameProfile; -import io.netty.channel.ChannelFutureListener; -import java.net.InetSocketAddress; -import java.util.Iterator; - -import org.bukkit.craftbukkit.util.CraftIconCache; -import org.bukkit.entity.Player; - -// CraftBukkit end - -public class PacketStatusListener implements PacketStatusInListener { - - private static final IChatBaseComponent a = new ChatMessage("multiplayer.status.request_handled", new Object[0]); - private final MinecraftServer minecraftServer; - private final NetworkManager networkManager; - private boolean d; - - public PacketStatusListener(MinecraftServer minecraftserver, NetworkManager networkmanager) { - this.minecraftServer = minecraftserver; - this.networkManager = networkmanager; - } - - @Override - public void a(IChatBaseComponent ichatbasecomponent) {} - - @Override - public NetworkManager a() { - return this.networkManager; - } - - @Override - public void a(PacketStatusInStart packetstatusinstart) { - if (this.d) { - this.networkManager.close(PacketStatusListener.a); - } else { - this.d = true; - // Paper start - Replace everything - /* - // CraftBukkit start - // this.networkManager.sendPacket(new PacketStatusOutServerInfo(this.minecraftServer.getServerPing())); - final Object[] players = minecraftServer.getPlayerList().players.toArray(); - class ServerListPingEvent extends org.bukkit.event.server.ServerListPingEvent { - - CraftIconCache icon = minecraftServer.server.getServerIcon(); - - ServerListPingEvent() { - super(((InetSocketAddress) networkManager.getSocketAddress()).getAddress(), minecraftServer.getMotd(), minecraftServer.getPlayerList().getMaxPlayers()); - } - - @Override - public void setServerIcon(org.bukkit.util.CachedServerIcon icon) { - if (!(icon instanceof CraftIconCache)) { - throw new IllegalArgumentException(icon + " was not created by " + org.bukkit.craftbukkit.CraftServer.class); - } - this.icon = (CraftIconCache) icon; - } - - @Override - public Iterator iterator() throws UnsupportedOperationException { - return new Iterator() { - int i; - int ret = Integer.MIN_VALUE; - EntityPlayer player; - - @Override - public boolean hasNext() { - if (player != null) { - return true; - } - final Object[] currentPlayers = players; - for (int length = currentPlayers.length, i = this.i; i < length; i++) { - final EntityPlayer player = (EntityPlayer) currentPlayers[i]; - if (player != null) { - this.i = i + 1; - this.player = player; - return true; - } - } - return false; - } - - @Override - public Player next() { - if (!hasNext()) { - throw new java.util.NoSuchElementException(); - } - final EntityPlayer player = this.player; - this.player = null; - this.ret = this.i - 1; - return player.getBukkitEntity(); - } - - @Override - public void remove() { - final Object[] currentPlayers = players; - final int i = this.ret; - if (i < 0 || currentPlayers[i] == null) { - throw new IllegalStateException(); - } - currentPlayers[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[profiles.size()])); - - ServerPing ping = new ServerPing(); - ping.setFavicon(event.icon.value); - ping.setMOTD(new ChatComponentText(event.getMotd())); - ping.setPlayerSample(playerSample); - int version = SharedConstants.a().getProtocolVersion(); - ping.setServerInfo(new ServerPing.ServerData(minecraftServer.getServerModName() + " " + minecraftServer.getVersion(), version)); - - this.networkManager.sendPacket(new PacketStatusOutServerInfo(ping)); - */ - com.destroystokyo.paper.network.StandardPaperServerListPingEventImpl.processRequest(this.minecraftServer, this.networkManager); - // Paper end - } - // CraftBukkit end - } - - @Override - public void a(PacketStatusInPing packetstatusinping) { - this.networkManager.sendPacket(new PacketStatusOutPong(packetstatusinping.b())); - this.networkManager.close(PacketStatusListener.a); - } -} diff --git a/src/main/java/net/minecraft/server/PathEntity.java b/src/main/java/net/minecraft/server/PathEntity.java deleted file mode 100644 index dcb4e2508..000000000 --- a/src/main/java/net/minecraft/server/PathEntity.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import javax.annotation.Nullable; - -public class PathEntity { - - private final List a; public List getPoints() { return a; } // Paper - OBFHELPER - private PathPoint[] b = new PathPoint[0]; - private PathPoint[] c = new PathPoint[0]; - private int e; public int getNextIndex() { return this.e; } // Paper - OBFHELPER - private final BlockPosition f; - private final float g; - private final boolean h; - public boolean hasNext() { return getNextIndex() < getPoints().size(); } // Paper - - public PathEntity(List list, BlockPosition blockposition, boolean flag) { - this.a = list; - this.f = blockposition; - this.g = list.isEmpty() ? Float.MAX_VALUE : ((PathPoint) this.a.get(this.a.size() - 1)).c(this.f); - this.h = flag; - } - - public void a() { - ++this.e; - } - - public boolean b() { - return this.e >= this.a.size(); - } - - public PathPoint getFinalPoint() { return c(); } @Nullable public PathPoint c() { // Paper - OBFHELPER - return !this.a.isEmpty() ? (PathPoint) this.a.get(this.a.size() - 1) : null; - } - - public PathPoint a(int i) { - return (PathPoint) this.a.get(i); - } - - public List d() { - return this.a; - } - - public void b(int i) { - if (this.a.size() > i) { - this.a.subList(i, this.a.size()).clear(); - } - - } - - public void a(int i, PathPoint pathpoint) { - this.a.set(i, pathpoint); - } - - public int e() { - return this.a.size(); - } - - public int f() { - return this.e; - } - - public void c(int i) { - this.e = i; - } - - public Vec3D a(Entity entity, int i) { - PathPoint pathpoint = (PathPoint) this.a.get(i); - double d0 = (double) pathpoint.a + (double) ((int) (entity.getWidth() + 1.0F)) * 0.5D; - double d1 = (double) pathpoint.b; - double d2 = (double) pathpoint.c + (double) ((int) (entity.getWidth() + 1.0F)) * 0.5D; - - return new Vec3D(d0, d1, d2); - } - - public Vec3D a(Entity entity) { - return this.a(entity, this.e); - } - - public Vec3D getNext() { return g(); } public Vec3D g() { // Paper - OBFHELPER - PathPoint pathpoint = (PathPoint) this.a.get(this.e); - - return new Vec3D((double) pathpoint.a, (double) pathpoint.b, (double) pathpoint.c); - } - - public boolean a(@Nullable PathEntity pathentity) { - if (pathentity == null) { - return false; - } else if (pathentity.a.size() != this.a.size()) { - return false; - } else { - for (int i = 0; i < this.a.size(); ++i) { - PathPoint pathpoint = (PathPoint) this.a.get(i); - PathPoint pathpoint1 = (PathPoint) pathentity.a.get(i); - - if (pathpoint.a != pathpoint1.a || pathpoint.b != pathpoint1.b || pathpoint.c != pathpoint1.c) { - return false; - } - } - - return true; - } - } - - public boolean h() { - return this.h; - } - - public String toString() { - return "Path(length=" + this.a.size() + ")"; - } - - public BlockPosition k() { - return this.f; - } - - public float l() { - return this.g; - } -} diff --git a/src/main/java/net/minecraft/server/PathPoint.java b/src/main/java/net/minecraft/server/PathPoint.java deleted file mode 100644 index 18cdd2a6f..000000000 --- a/src/main/java/net/minecraft/server/PathPoint.java +++ /dev/null @@ -1,99 +0,0 @@ -package net.minecraft.server; - -public class PathPoint { - - public final int a; public final int getX() { return a; } // Paper - OBFHELPER - public final int b; public final int getY() { return b; } // Paper - OBFHELPER - public final int c; public final int getZ() { return c; } // Paper - OBFHELPER - private final int m; - public int d = -1; - public float e; - public float f; - public float g; - public PathPoint h; - public boolean i; - public float j; - public float k; - public PathType l; - - public PathPoint(int i, int j, int k) { - this.l = PathType.BLOCKED; - this.a = i; - this.b = j; - this.c = k; - this.m = b(i, j, k); - } - - public PathPoint a(int i, int j, int k) { - PathPoint pathpoint = new PathPoint(i, j, k); - - pathpoint.d = this.d; - pathpoint.e = this.e; - pathpoint.f = this.f; - pathpoint.g = this.g; - pathpoint.h = this.h; - pathpoint.i = this.i; - pathpoint.j = this.j; - pathpoint.k = this.k; - pathpoint.l = this.l; - return pathpoint; - } - - public static int b(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 float c(PathPoint pathpoint) { - float f = (float) Math.abs(pathpoint.a - this.a); - float f1 = (float) Math.abs(pathpoint.b - this.b); - float f2 = (float) Math.abs(pathpoint.c - this.c); - - return f + f1 + f2; - } - - public float c(BlockPosition blockposition) { - float f = (float) Math.abs(blockposition.getX() - this.a); - float f1 = (float) Math.abs(blockposition.getY() - this.b); - float f2 = (float) Math.abs(blockposition.getZ() - this.c); - - return f + f1 + f2; - } - - public boolean equals(Object object) { - if (!(object instanceof PathPoint)) { - return false; - } else { - PathPoint pathpoint = (PathPoint) object; - - return this.m == pathpoint.m && this.a == pathpoint.a && this.b == pathpoint.b && this.c == pathpoint.c; - } - } - - public int hashCode() { - return this.m; - } - - public boolean c() { - return this.d >= 0; - } - - public String toString() { - return "Node{x=" + this.a + ", y=" + this.b + ", z=" + this.c + '}'; - } -} diff --git a/src/main/java/net/minecraft/server/Pathfinder.java b/src/main/java/net/minecraft/server/Pathfinder.java deleted file mode 100644 index 0cec80ec7..000000000 --- a/src/main/java/net/minecraft/server/Pathfinder.java +++ /dev/null @@ -1,147 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.annotation.Nullable; - -public class Pathfinder { - - private final Path a = new Path(); - private final Set b = Sets.newHashSet(); - private final PathPoint[] c = new PathPoint[32]; - private final int d; - private PathfinderAbstract e; public PathfinderAbstract getPathfinder() { return this.e; } // Paper - OBFHELPER - - public Pathfinder(PathfinderAbstract pathfinderabstract, int i) { - this.e = pathfinderabstract; - this.d = i; - } - - @Nullable - public PathEntity a(IWorldReader iworldreader, EntityInsentient entityinsentient, Set set, float f, int i) { - this.a.a(); - this.e.a(iworldreader, entityinsentient); - PathPoint pathpoint = this.e.b(); - Map map = (Map) set.stream().collect(Collectors.toMap((blockposition) -> { - return this.e.a((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()); - }, Function.identity())); - PathEntity pathentity = this.a(pathpoint, map, f, i); - - this.e.a(); - return pathentity; - } - - @Nullable - private PathEntity a(PathPoint pathpoint, Map map, float f, int i) { - Set set = map.keySet(); - - pathpoint.e = 0.0F; - pathpoint.f = this.a(pathpoint, set); - pathpoint.g = pathpoint.f; - this.a.a(); - this.b.clear(); - this.a.a(pathpoint); - int j = 0; - - while (!this.a.e()) { - ++j; - if (j >= this.d) { - break; - } - - PathPoint pathpoint1 = this.a.c(); - - pathpoint1.i = true; - set.stream().filter((pathdestination) -> { - return pathpoint1.c((PathPoint) pathdestination) <= (float) i; - }).forEach(PathDestination::e); - if (set.stream().anyMatch(PathDestination::f)) { - break; - } - - if (pathpoint1.a(pathpoint) < f) { - int k = this.e.a(this.c, pathpoint1); - - for (int l = 0; l < k; ++l) { - PathPoint pathpoint2 = this.c[l]; - float f1 = pathpoint1.a(pathpoint2); - - pathpoint2.j = pathpoint1.j + f1; - float f2 = pathpoint1.e + f1 + pathpoint2.k; - - if (pathpoint2.j < f && (!pathpoint2.c() || f2 < pathpoint2.e)) { - pathpoint2.h = pathpoint1; - pathpoint2.e = f2; - pathpoint2.f = this.a(pathpoint2, set) * 1.5F; - if (pathpoint2.c()) { - this.a.a(pathpoint2, pathpoint2.e + pathpoint2.f); - } else { - pathpoint2.g = pathpoint2.e + pathpoint2.f; - this.a.a(pathpoint2); - } - } - } - } - } - - Stream stream; - - if (set.stream().anyMatch(PathDestination::f)) { - stream = set.stream().filter(PathDestination::f).map((pathdestination) -> { - return this.a(pathdestination.d(), (BlockPosition) map.get(pathdestination), true); - }).sorted(Comparator.comparingInt(PathEntity::e)); - } else { - stream = set.stream().map((pathdestination) -> { - return this.a(pathdestination.d(), (BlockPosition) map.get(pathdestination), false); - }).sorted(Comparator.comparingDouble(PathEntity::l).thenComparingInt(PathEntity::e)); - } - - Optional optional = stream.findFirst(); - - if (!optional.isPresent()) { - return null; - } else { - PathEntity pathentity = (PathEntity) optional.get(); - - return pathentity; - } - } - - private float a(PathPoint pathpoint, Set set) { - float f = Float.MAX_VALUE; - - float f1; - - for (Iterator iterator = set.iterator(); iterator.hasNext(); f = Math.min(f1, f)) { - PathDestination pathdestination = (PathDestination) iterator.next(); - - f1 = pathpoint.a(pathdestination); - pathdestination.a(f1, pathpoint); - } - - return f; - } - - private PathEntity a(PathPoint pathpoint, BlockPosition blockposition, boolean flag) { - List list = Lists.newArrayList(); - PathPoint pathpoint1 = pathpoint; - - list.add(0, pathpoint); - - while (pathpoint1.h != null) { - pathpoint1 = pathpoint1.h; - list.add(0, pathpoint1); - } - - return new PathEntity(list, blockposition, flag); - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalBreakDoor.java b/src/main/java/net/minecraft/server/PathfinderGoalBreakDoor.java deleted file mode 100644 index 584b35e1d..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalBreakDoor.java +++ /dev/null @@ -1,85 +0,0 @@ -package net.minecraft.server; - -import java.util.function.Predicate; - -public class PathfinderGoalBreakDoor extends PathfinderGoalDoorInteract { - - private final Predicate g; - protected int a; - protected int b; - protected int c; - - public PathfinderGoalBreakDoor(EntityInsentient entityinsentient, Predicate predicate) { - super(entityinsentient); - this.b = -1; - this.c = -1; - this.g = predicate; - } - - public PathfinderGoalBreakDoor(EntityInsentient entityinsentient, int i, Predicate predicate) { - this(entityinsentient, predicate); - this.c = i; - } - - protected int f() { - return Math.max(240, this.c); - } - - @Override - public boolean a() { - return !super.a() ? false : (!this.entity.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING) ? false : this.a(this.entity.world.getDifficulty()) && !this.g()); - } - - @Override - public void c() { - super.c(); - this.a = 0; - } - - @Override - public boolean b() { - return this.a <= this.f() && !this.g() && this.door.a((IPosition) this.entity.getPositionVector(), 2.0D) && this.a(this.entity.world.getDifficulty()); - } - - @Override - public void d() { - super.d(); - this.entity.world.a(this.entity.getId(), this.door, -1); - } - - @Override - public void e() { - super.e(); - if (this.entity.getRandom().nextInt(20) == 0) { - this.entity.world.triggerEffect(1019, this.door, 0); - if (!this.entity.at) { - this.entity.a(this.entity.getRaisedHand()); - } - } - - ++this.a; - int i = (int) ((float) this.a / (float) this.f() * 10.0F); - - if (i != this.b) { - this.entity.world.a(this.entity.getId(), this.door, i); - this.b = i; - } - - if (this.a == this.f() && this.a(this.entity.world.getDifficulty())) { - // CraftBukkit start - if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityBreakDoorEvent(this.entity, this.door).isCancelled()) { - this.c(); - return; - } - // CraftBukkit end - this.entity.world.a(this.door, false); - this.entity.world.triggerEffect(1021, this.door, 0); - this.entity.world.triggerEffect(2001, this.door, Block.getCombinedId(this.entity.world.getType(this.door))); - } - - } - - private boolean a(EnumDifficulty enumdifficulty) { - return this.g.test(enumdifficulty); - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalBreed.java b/src/main/java/net/minecraft/server/PathfinderGoalBreed.java deleted file mode 100644 index 0cc34400b..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalBreed.java +++ /dev/null @@ -1,127 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -public class PathfinderGoalBreed extends PathfinderGoal { - - private static final PathfinderTargetCondition d = (new PathfinderTargetCondition()).a(8.0D).a().b().c(); - protected final EntityAnimal animal; - private final Class e; - protected final World b; - protected EntityAnimal partner; - private int f; - private final double g; - - public PathfinderGoalBreed(EntityAnimal entityanimal, double d0) { - this(entityanimal, d0, entityanimal.getClass()); - } - - public PathfinderGoalBreed(EntityAnimal entityanimal, double d0, Class oclass) { - this.animal = entityanimal; - this.b = entityanimal.world; - this.e = oclass; - this.g = d0; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - } - - @Override - public boolean a() { - if (!this.animal.isInLove()) { - return false; - } else { - this.partner = this.h(); - return this.partner != null; - } - } - - @Override - public boolean b() { - return this.partner.isAlive() && this.partner.isInLove() && this.f < 60; - } - - @Override - public void d() { - this.partner = null; - this.f = 0; - } - - @Override - public void e() { - this.animal.getControllerLook().a(this.partner, 10.0F, (float) this.animal.M()); - this.animal.getNavigation().a((Entity) this.partner, this.g); - ++this.f; - if (this.f >= 60 && this.animal.h((Entity) this.partner) < 9.0D) { - this.g(); - } - - } - - @Nullable - private EntityAnimal h() { - List list = this.b.a(this.e, PathfinderGoalBreed.d, this.animal, this.animal.getBoundingBox().g(8.0D)); - double d0 = Double.MAX_VALUE; - EntityAnimal entityanimal = null; - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityAnimal entityanimal1 = (EntityAnimal) iterator.next(); - - if (this.animal.mate(entityanimal1) && this.animal.h((Entity) entityanimal1) < d0) { - entityanimal = entityanimal1; - d0 = this.animal.h((Entity) entityanimal1); - } - } - - return entityanimal; - } - - protected void g() { - EntityAgeable entityageable = this.animal.createChild(this.partner); - - if (entityageable != null) { - // CraftBukkit start - set persistence for tame animals - if (entityageable instanceof EntityTameableAnimal && ((EntityTameableAnimal) entityageable).isTamed()) { - entityageable.persistent = true; - } - // CraftBukkit end - EntityPlayer entityplayer = this.animal.getBreedCause(); - - if (entityplayer == null && this.partner.getBreedCause() != null) { - entityplayer = this.partner.getBreedCause(); - } - // CraftBukkit start - call EntityBreedEvent - int experience = this.animal.getRandom().nextInt(7) + 1; - org.bukkit.event.entity.EntityBreedEvent entityBreedEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityBreedEvent(entityageable, animal, partner, entityplayer, this.animal.breedItem, experience); - if (entityBreedEvent.isCancelled()) { - return; - } - experience = entityBreedEvent.getExperience(); - // CraftBukkit end - - if (entityplayer != null) { - entityplayer.a(StatisticList.ANIMALS_BRED); - CriterionTriggers.o.a(entityplayer, this.animal, this.partner, entityageable); - } - - this.animal.setAgeRaw(6000); - this.partner.setAgeRaw(6000); - this.animal.resetLove(); - this.partner.resetLove(); - entityageable.setAgeRaw(-24000); - entityageable.setPositionRotation(this.animal.locX, this.animal.locY, this.animal.locZ, 0.0F, 0.0F); - this.b.addEntity(entityageable, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.BREEDING); // CraftBukkit - added SpawnReason - this.b.broadcastEntityEffect(this.animal, (byte) 18); - if (this.b.getGameRules().getBoolean(GameRules.DO_MOB_LOOT)) { - // CraftBukkit start - use event experience - if (experience > 0) { - this.b.addEntity(new EntityExperienceOrb(this.b, this.animal.locX, this.animal.locY, this.animal.locZ, experience, org.bukkit.entity.ExperienceOrb.SpawnReason.BREED, entityplayer, entityageable)); // Paper - } - // CraftBukkit end - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalDefendVillage.java b/src/main/java/net/minecraft/server/PathfinderGoalDefendVillage.java deleted file mode 100644 index 9a67f5b55..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalDefendVillage.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; - -public class PathfinderGoalDefendVillage extends PathfinderGoalTarget { - - private final EntityIronGolem a; - private EntityLiving b; - private final PathfinderTargetCondition c = (new PathfinderTargetCondition()).a(64.0D); - - public PathfinderGoalDefendVillage(EntityIronGolem entityirongolem) { - super(entityirongolem, false, true); - this.a = entityirongolem; - this.a(EnumSet.of(PathfinderGoal.Type.TARGET)); - } - - @Override - public boolean a() { - AxisAlignedBB axisalignedbb = this.a.getBoundingBox().grow(10.0D, 8.0D, 10.0D); - List list = this.a.world.a(EntityVillager.class, this.c, this.a, axisalignedbb); - List list1 = this.a.world.a(this.c, (EntityLiving) this.a, axisalignedbb); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityLiving entityliving = (EntityLiving) iterator.next(); - EntityVillager entityvillager = (EntityVillager) entityliving; - Iterator iterator1 = list1.iterator(); - - while (iterator1.hasNext()) { - EntityHuman entityhuman = (EntityHuman) iterator1.next(); - int i = entityvillager.f(entityhuman); - - if (i <= -100) { - this.b = entityhuman; - } - } - } - - return this.b != null; - } - - @Override - public void c() { - this.a.setGoalTarget(this.b, org.bukkit.event.entity.EntityTargetEvent.TargetReason.DEFEND_VILLAGE, true); // CraftBukkit - reason - super.c(); - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalEatTile.java b/src/main/java/net/minecraft/server/PathfinderGoalEatTile.java deleted file mode 100644 index e9679bb46..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalEatTile.java +++ /dev/null @@ -1,84 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.function.Predicate; - -// CraftBukkit start -import org.bukkit.craftbukkit.event.CraftEventFactory; -// CraftBukkit end - -public class PathfinderGoalEatTile extends PathfinderGoal { - - private static final Predicate a = BlockStatePredicate.a(Blocks.GRASS); - private final EntityInsentient b; - private final World c; - private int d; - - public PathfinderGoalEatTile(EntityInsentient entityinsentient) { - this.b = entityinsentient; - this.c = entityinsentient.world; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK, PathfinderGoal.Type.JUMP)); - } - - @Override - public boolean a() { - if (this.b.getRandom().nextInt(this.b.isBaby() ? 50 : 1000) != 0) { - return false; - } else { - BlockPosition blockposition = new BlockPosition(this.b); - - return PathfinderGoalEatTile.a.test(this.c.getType(blockposition)) ? true : this.c.getType(blockposition.down()).getBlock() == Blocks.GRASS_BLOCK; - } - } - - @Override - public void c() { - this.d = 40; - this.c.broadcastEntityEffect(this.b, (byte) 10); - this.b.getNavigation().o(); - } - - @Override - public void d() { - this.d = 0; - } - - @Override - public boolean b() { - return this.d > 0; - } - - public int g() { - return this.d; - } - - @Override - public void e() { - this.d = Math.max(0, this.d - 1); - if (this.d == 4) { - BlockPosition blockposition = new BlockPosition(this.b); - - if (PathfinderGoalEatTile.a.test(this.c.getType(blockposition))) { - // CraftBukkit - if (!CraftEventFactory.callEntityChangeBlockEvent(this.b, blockposition, Blocks.AIR.getBlockData(), !this.c.getGameRules().getBoolean(GameRules.MOB_GRIEFING)).isCancelled()) { - this.c.b(blockposition, false); - } - - this.b.blockEaten(); - } else { - BlockPosition blockposition1 = blockposition.down(); - - if (this.c.getType(blockposition1).getBlock() == Blocks.GRASS_BLOCK) { - // CraftBukkit - if (!CraftEventFactory.callEntityChangeBlockEvent(this.b, blockposition, Blocks.AIR.getBlockData(), !this.c.getGameRules().getBoolean(GameRules.MOB_GRIEFING)).isCancelled()) { - this.c.triggerEffect(2001, blockposition1, Block.getCombinedId(Blocks.GRASS_BLOCK.getBlockData())); - this.c.setTypeAndData(blockposition1, Blocks.DIRT.getBlockData(), 2); - } - - this.b.blockEaten(); - } - } - - } - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalFloat.java b/src/main/java/net/minecraft/server/PathfinderGoalFloat.java deleted file mode 100644 index 2e23b5de5..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalFloat.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; - -public class PathfinderGoalFloat extends PathfinderGoal { - - private final EntityInsentient a; - - public PathfinderGoalFloat(EntityInsentient entityinsentient) { - this.a = entityinsentient; - if (entityinsentient.getWorld().paperConfig.nerfedMobsShouldJump) entityinsentient.goalFloat = this; // Paper - this.a(EnumSet.of(PathfinderGoal.Type.JUMP)); - entityinsentient.getNavigation().d(true); - } - - public final boolean validConditions() { return this.a(); } // Paper - OBFHELPER - @Override - public boolean a() { - double d0 = (double) this.a.getHeadHeight() < 0.4D ? 0.2D : 0.4D; - - return this.a.isInWater() && this.a.cf() > d0 || this.a.aD(); - } - - public void update() { this.e(); } // Paper - OBFHELPER - @Override - public void e() { - if (this.a.getRandom().nextFloat() < 0.8F) { - this.a.getControllerJump().jump(); - } - - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalFollowOwner.java b/src/main/java/net/minecraft/server/PathfinderGoalFollowOwner.java deleted file mode 100644 index 896d2d56a..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalFollowOwner.java +++ /dev/null @@ -1,118 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -// CraftBukkit start -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftEntity; -import org.bukkit.event.entity.EntityTeleportEvent; -// CraftBukkit end - -public class PathfinderGoalFollowOwner extends PathfinderGoal { - - protected final EntityTameableAnimal a; - private EntityLiving c; - protected final IWorldReader b; - private final double d; - private final NavigationAbstract e; - private int f; - private final float g; - private final float h; - private float i; - - public PathfinderGoalFollowOwner(EntityTameableAnimal entitytameableanimal, double d0, float f, float f1) { - this.a = entitytameableanimal; - this.b = entitytameableanimal.world; - this.d = d0; - this.e = entitytameableanimal.getNavigation(); - this.h = f; - this.g = f1; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - if (!(entitytameableanimal.getNavigation() instanceof Navigation) && !(entitytameableanimal.getNavigation() instanceof NavigationFlying)) { - throw new IllegalArgumentException("Unsupported mob type for FollowOwnerGoal"); - } - } - - @Override - public boolean a() { - EntityLiving entityliving = this.a.getOwner(); - - if (entityliving == null) { - return false; - } else if (entityliving instanceof EntityHuman && ((EntityHuman) entityliving).isSpectator()) { - return false; - } else if (this.a.isSitting()) { - return false; - } else if (this.a.h((Entity) entityliving) < (double) (this.h * this.h)) { - return false; - } else { - this.c = entityliving; - return true; - } - } - - @Override - public boolean b() { - return !this.e.n() && this.a.h((Entity) this.c) > (double) (this.g * this.g) && !this.a.isSitting(); - } - - @Override - public void c() { - this.f = 0; - this.i = this.a.a(PathType.WATER); - this.a.a(PathType.WATER, 0.0F); - } - - @Override - public void d() { - this.c = null; - this.e.o(); - this.a.a(PathType.WATER, this.i); - } - - @Override - public void e() { - this.a.getControllerLook().a(this.c, 10.0F, (float) this.a.M()); - if (!this.a.isSitting()) { - if (--this.f <= 0) { - this.f = 10; - if (!this.e.a((Entity) this.c, this.d)) { - if (!this.a.isLeashed() && !this.a.isPassenger()) { - if (this.a.h((Entity) this.c) >= 144.0D) { - int i = MathHelper.floor(this.c.locX) - 2; - int j = MathHelper.floor(this.c.locZ) - 2; - int k = MathHelper.floor(this.c.getBoundingBox().minY); - - for (int l = 0; l <= 4; ++l) { - for (int i1 = 0; i1 <= 4; ++i1) { - if ((l < 1 || i1 < 1 || l > 3 || i1 > 3) && this.a(new BlockPosition(i + l, k - 1, j + i1))) { - // CraftBukkit start - CraftEntity entity = this.a.getBukkitEntity(); - Location to = new Location(entity.getWorld(), (double) ((float) (i + l) + 0.5F), (double) k, (double) ((float) (j + i1) + 0.5F), this.a.yaw, this.a.pitch); - EntityTeleportEvent event = new EntityTeleportEvent(entity, entity.getLocation(), to); - this.a.world.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - to = event.getTo(); - - this.a.setPositionRotation(to.getX(), to.getY(), to.getZ(), to.getYaw(), to.getPitch()); - // CraftBukkit end - this.e.o(); - return; - } - } - } - - } - } - } - } - } - } - - protected boolean a(BlockPosition blockposition) { - IBlockData iblockdata = this.b.getType(blockposition); - - return iblockdata.a((IBlockAccess) this.b, blockposition, this.a.getEntityType()) && this.b.isEmpty(blockposition.up()) && this.b.isEmpty(blockposition.up(2)); - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalHorseTrap.java b/src/main/java/net/minecraft/server/PathfinderGoalHorseTrap.java deleted file mode 100644 index f09374413..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalHorseTrap.java +++ /dev/null @@ -1,69 +0,0 @@ -package net.minecraft.server; - -public class PathfinderGoalHorseTrap extends PathfinderGoal { - - private final EntityHorseSkeleton a; - - public PathfinderGoalHorseTrap(EntityHorseSkeleton entityhorseskeleton) { - this.a = entityhorseskeleton; - } - - @Override - public boolean a() { - return this.a.world.isPlayerNearby(this.a.locX, this.a.locY, this.a.locZ, 10.0D); - } - - @Override - public void e() { - if (!new com.destroystokyo.paper.event.entity.SkeletonHorseTrapEvent((org.bukkit.entity.SkeletonHorse) this.a.getBukkitEntity()).callEvent()) return; // Paper - DifficultyDamageScaler difficultydamagescaler = this.a.world.getDamageScaler(new BlockPosition(this.a)); - - this.a.r(false); - this.a.setTamed(true); - this.a.setAgeRaw(0); - ((WorldServer) this.a.world).strikeLightning(new EntityLightning(this.a.world, this.a.locX, this.a.locY, this.a.locZ, true), org.bukkit.event.weather.LightningStrikeEvent.Cause.TRAP); // CraftBukkit - EntitySkeleton entityskeleton = this.a(difficultydamagescaler, this.a); - - if (entityskeleton != null) entityskeleton.startRiding(this.a); // CraftBukkit - - for (int i = 0; i < 3; ++i) { - EntityHorseAbstract entityhorseabstract = this.a(difficultydamagescaler); - if (entityhorseabstract == null) continue; // CraftBukkit - EntitySkeleton entityskeleton1 = this.a(difficultydamagescaler, entityhorseabstract); - - if (entityskeleton1 != null) entityskeleton1.startRiding(entityhorseabstract); // CraftBukkit - entityhorseabstract.f(this.a.getRandom().nextGaussian() * 0.5D, 0.0D, this.a.getRandom().nextGaussian() * 0.5D); - } - - } - - private EntityHorseAbstract a(DifficultyDamageScaler difficultydamagescaler) { - EntityHorseSkeleton entityhorseskeleton = (EntityHorseSkeleton) EntityTypes.SKELETON_HORSE.a(this.a.world); - - entityhorseskeleton.prepare(this.a.world, difficultydamagescaler, EnumMobSpawn.TRIGGERED, (GroupDataEntity) null, (NBTTagCompound) null); - entityhorseskeleton.setPosition(this.a.locX, this.a.locY, this.a.locZ); - entityhorseskeleton.noDamageTicks = 60; - entityhorseskeleton.setPersistent(); - entityhorseskeleton.setTamed(true); - entityhorseskeleton.setAgeRaw(0); - if (!entityhorseskeleton.world.addEntity(entityhorseskeleton, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.TRAP)) return null; // CraftBukkit - return entityhorseskeleton; - } - - private EntitySkeleton a(DifficultyDamageScaler difficultydamagescaler, EntityHorseAbstract entityhorseabstract) { - EntitySkeleton entityskeleton = (EntitySkeleton) EntityTypes.SKELETON.a(entityhorseabstract.world); - - entityskeleton.prepare(entityhorseabstract.world, difficultydamagescaler, EnumMobSpawn.TRIGGERED, (GroupDataEntity) null, (NBTTagCompound) null); - entityskeleton.setPosition(entityhorseabstract.locX, entityhorseabstract.locY, entityhorseabstract.locZ); - entityskeleton.noDamageTicks = 60; - entityskeleton.setPersistent(); - if (entityskeleton.getEquipment(EnumItemSlot.HEAD).isEmpty()) { - entityskeleton.setSlot(EnumItemSlot.HEAD, new ItemStack(Items.IRON_HELMET)); - } - - entityskeleton.setSlot(EnumItemSlot.MAINHAND, EnchantmentManager.a(entityskeleton.getRandom(), entityskeleton.getItemInMainHand(), (int) (5.0F + difficultydamagescaler.d() * (float) entityskeleton.getRandom().nextInt(18)), false)); - entityskeleton.setSlot(EnumItemSlot.HEAD, EnchantmentManager.a(entityskeleton.getRandom(), entityskeleton.getEquipment(EnumItemSlot.HEAD), (int) (5.0F + difficultydamagescaler.d() * (float) entityskeleton.getRandom().nextInt(18)), false)); - if (!entityskeleton.world.addEntity(entityskeleton, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.JOCKEY)) return null; // CraftBukkit - return entityskeleton; - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalHurtByTarget.java b/src/main/java/net/minecraft/server/PathfinderGoalHurtByTarget.java deleted file mode 100644 index a9bfa5f6a..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalHurtByTarget.java +++ /dev/null @@ -1,100 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; - -public class PathfinderGoalHurtByTarget extends PathfinderGoalTarget { - - private static final PathfinderTargetCondition a = (new PathfinderTargetCondition()).c().e(); - private boolean b; - private int c; - private final Class[] d; - private Class[] i; - - public PathfinderGoalHurtByTarget(EntityCreature entitycreature, Class... aclass) { - super(entitycreature, true); - this.d = aclass; - this.a(EnumSet.of(PathfinderGoal.Type.TARGET)); - } - - @Override - public boolean a() { - int i = this.e.ct(); - EntityLiving entityliving = this.e.getLastDamager(); - - if (i != this.c && entityliving != null) { - Class[] aclass = this.d; - int j = aclass.length; - - for (int k = 0; k < j; ++k) { - Class oclass = aclass[k]; - - if (oclass.isAssignableFrom(entityliving.getClass())) { - return false; - } - } - - return this.a(entityliving, PathfinderGoalHurtByTarget.a); - } else { - return false; - } - } - - public PathfinderGoalHurtByTarget a(Class... aclass) { - this.b = true; - this.i = aclass; - return this; - } - - @Override - public void c() { - this.e.setGoalTarget(this.e.getLastDamager(), org.bukkit.event.entity.EntityTargetEvent.TargetReason.TARGET_ATTACKED_ENTITY, true); // CraftBukkit - reason - this.g = this.e.getGoalTarget(); - this.c = this.e.ct(); - this.h = 300; - if (this.b) { - this.g(); - } - - super.c(); - } - - protected void g() { - double d0 = this.k(); - List list = this.e.world.b(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)); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityInsentient entityinsentient = (EntityInsentient) iterator.next(); - - if (this.e != entityinsentient && entityinsentient.getGoalTarget() == null && (!(this.e instanceof EntityTameableAnimal) || ((EntityTameableAnimal) this.e).getOwner() == ((EntityTameableAnimal) entityinsentient).getOwner()) && !entityinsentient.r(this.e.getLastDamager())) { - if (this.i != null) { - boolean flag = false; - Class[] aclass = this.i; - int i = aclass.length; - - for (int j = 0; j < i; ++j) { - Class oclass = aclass[j]; - - if (entityinsentient.getClass() == oclass) { - flag = true; - break; - } - } - - if (flag) { - continue; - } - } - - this.a(entityinsentient, this.e.getLastDamager()); - } - } - - } - - protected void a(EntityInsentient entityinsentient, EntityLiving entityliving) { - entityinsentient.setGoalTarget(entityliving, org.bukkit.event.entity.EntityTargetEvent.TargetReason.TARGET_ATTACKED_NEARBY_ENTITY, true); // CraftBukkit - reason - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTarget.java b/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTarget.java deleted file mode 100644 index 3295dfa98..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTarget.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import java.util.function.Predicate; -import javax.annotation.Nullable; - -public class PathfinderGoalNearestAttackableTarget extends PathfinderGoalTarget { - - protected final Class a; - protected final int b; - protected EntityLiving c; - protected PathfinderTargetCondition d; - - public PathfinderGoalNearestAttackableTarget(EntityInsentient entityinsentient, Class oclass, boolean flag) { - this(entityinsentient, oclass, flag, false); - } - - public PathfinderGoalNearestAttackableTarget(EntityInsentient entityinsentient, Class oclass, boolean flag, boolean flag1) { - this(entityinsentient, oclass, 10, flag, flag1, (Predicate) null); - } - - public PathfinderGoalNearestAttackableTarget(EntityInsentient entityinsentient, Class oclass, int i, boolean flag, boolean flag1, @Nullable Predicate predicate) { - super(entityinsentient, flag, flag1); - this.a = oclass; - this.b = i; - this.a(EnumSet.of(PathfinderGoal.Type.TARGET)); - this.d = (new PathfinderTargetCondition()).a(this.k()).a(predicate); - } - - @Override - public boolean a() { - if (this.b > 0 && this.e.getRandom().nextInt(this.b) != 0) { - return false; - } else { - this.g(); - return this.c != null; - } - } - - protected AxisAlignedBB a(double d0) { - return this.e.getBoundingBox().grow(d0, 4.0D, d0); - } - - protected void g() { - if (this.a != EntityHuman.class && this.a != EntityPlayer.class) { - this.c = this.e.world.b(this.a, this.d, this.e, this.e.locX, this.e.locY + (double) this.e.getHeadHeight(), this.e.locZ, this.a(this.k())); - } else { - this.c = this.e.world.a(this.d, this.e, this.e.locX, this.e.locY + (double) this.e.getHeadHeight(), this.e.locZ); - } - - } - - @Override - public void c() { - this.e.setGoalTarget(this.c, c instanceof EntityPlayer ? org.bukkit.event.entity.EntityTargetEvent.TargetReason.CLOSEST_PLAYER : org.bukkit.event.entity.EntityTargetEvent.TargetReason.CLOSEST_ENTITY, true); // Craftbukkit - reason - super.c(); - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtByTarget.java b/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtByTarget.java deleted file mode 100644 index 5b99b0ddd..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtByTarget.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; - -public class PathfinderGoalOwnerHurtByTarget extends PathfinderGoalTarget { - - private final EntityTameableAnimal a; - private EntityLiving b; - private int c; - - public PathfinderGoalOwnerHurtByTarget(EntityTameableAnimal entitytameableanimal) { - super(entitytameableanimal, false); - this.a = entitytameableanimal; - this.a(EnumSet.of(PathfinderGoal.Type.TARGET)); - } - - @Override - public boolean a() { - if (this.a.isTamed() && !this.a.isSitting()) { - EntityLiving entityliving = this.a.getOwner(); - - if (entityliving == null) { - return false; - } else { - this.b = entityliving.getLastDamager(); - int i = entityliving.ct(); - - return i != this.c && this.a(this.b, PathfinderTargetCondition.a) && this.a.a(this.b, entityliving); - } - } else { - return false; - } - } - - @Override - 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.ct(); - } - - super.c(); - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtTarget.java b/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtTarget.java deleted file mode 100644 index eb99159c8..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtTarget.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; - -public class PathfinderGoalOwnerHurtTarget extends PathfinderGoalTarget { - - private final EntityTameableAnimal a; - private EntityLiving b; - private int c; - - public PathfinderGoalOwnerHurtTarget(EntityTameableAnimal entitytameableanimal) { - super(entitytameableanimal, false); - this.a = entitytameableanimal; - this.a(EnumSet.of(PathfinderGoal.Type.TARGET)); - } - - @Override - public boolean a() { - if (this.a.isTamed() && !this.a.isSitting()) { - EntityLiving entityliving = this.a.getOwner(); - - if (entityliving == null) { - return false; - } else { - this.b = entityliving.cu(); - int i = entityliving.cv(); - - return i != this.c && this.a(this.b, PathfinderTargetCondition.a) && this.a.a(this.b, entityliving); - } - } else { - return false; - } - } - - @Override - 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.cv(); - } - - super.c(); - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalPanic.java b/src/main/java/net/minecraft/server/PathfinderGoalPanic.java deleted file mode 100644 index f399683b7..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalPanic.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -import javax.annotation.Nullable; - -public class PathfinderGoalPanic extends PathfinderGoal { - - protected final EntityCreature a; - protected final double b; - protected double c; - protected double d; - protected double e; - - public PathfinderGoalPanic(EntityCreature entitycreature, double d0) { - this.a = entitycreature; - this.b = d0; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - if (this.a.getLastDamager() == null && !this.a.isBurning()) { - return false; - } else { - if (this.a.isBurning()) { - BlockPosition blockposition = this.a(this.a.world, this.a, 5, 4); - - if (blockposition != null) { - this.c = (double) blockposition.getX(); - this.d = (double) blockposition.getY(); - this.e = (double) blockposition.getZ(); - return true; - } - } - - return this.g(); - } - } - - protected boolean g() { - Vec3D vec3d = RandomPositionGenerator.a(this.a, 5, 4); - - if (vec3d == null) { - return false; - } else { - this.c = vec3d.x; - this.d = vec3d.y; - this.e = vec3d.z; - return true; - } - } - - @Override - public void c() { - this.a.getNavigation().a(this.c, this.d, this.e, this.b); - } - - @Override - public boolean b() { - // CraftBukkit start - introduce a temporary timeout hack until this is fixed properly - if ((this.a.ticksLived - this.a.hurtTimestamp) > 100) { - this.a.setLastDamager((EntityLiving) null); - return false; - } - // CraftBukkit end - return !this.a.getNavigation().n(); - } - - @Nullable - protected BlockPosition a(IBlockAccess iblockaccess, Entity entity, int i, int j) { - BlockPosition blockposition = new BlockPosition(entity); - int k = blockposition.getX(); - int l = blockposition.getY(); - int i1 = blockposition.getZ(); - float f = (float) (i * i * j * 2); - BlockPosition blockposition1 = null; - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - for (int j1 = k - i; j1 <= k + i; ++j1) { - for (int k1 = l - j; k1 <= l + j; ++k1) { - for (int l1 = i1 - i; l1 <= i1 + i; ++l1) { - blockposition_mutableblockposition.d(j1, k1, l1); - if (iblockaccess.getFluid(blockposition_mutableblockposition).a(TagsFluid.WATER)) { - float f1 = (float) ((j1 - k) * (j1 - k) + (k1 - l) * (k1 - l) + (l1 - i1) * (l1 - i1)); - - if (f1 < f) { - f = f1; - blockposition1 = new BlockPosition(blockposition_mutableblockposition); - } - } - } - } - } - - return blockposition1; - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalRemoveBlock.java b/src/main/java/net/minecraft/server/PathfinderGoalRemoveBlock.java deleted file mode 100644 index 7ccb3d5c0..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalRemoveBlock.java +++ /dev/null @@ -1,146 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.event.entity.EntityInteractEvent; -// CraftBukkit end - -public class PathfinderGoalRemoveBlock extends PathfinderGoalGotoTarget { - - private final Block g; - private final EntityInsentient entity; - private int i; - private World world; // Paper - - public PathfinderGoalRemoveBlock(Block block, EntityCreature entitycreature, double d0, int i) { - super(entitycreature, d0, 24, i); - this.g = block; - this.entity = entitycreature; - this.world = entitycreature.world; // Paper - } - - @Override - public boolean a() { - if (!this.entity.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) { - return false; - } else if (this.c > 0) { - --this.c; - return false; - } else if (this.m()) { - this.c = 20; - return true; - } else { - this.c = this.a(this.a); - return false; - } - } - - private boolean m() { - return this.e != null && this.a((IWorldReader) this.a.world, this.e) ? true : this.l(); - } - - @Override - public void d() { - super.d(); - this.entity.fallDistance = 1.0F; - } - - @Override - public void c() { - super.c(); - this.i = 0; - } - - public void a(GeneratorAccess generatoraccess, BlockPosition blockposition) {} - - public void a(World world, BlockPosition blockposition) {} - - @Override - public void e() { - super.e(); - World world = this.entity.world; - BlockPosition blockposition = new BlockPosition(this.entity); - BlockPosition blockposition1 = this.a(blockposition, (IBlockAccess) world); - Random random = this.entity.getRandom(); - - if (this.k() && blockposition1 != null) { - Vec3D vec3d; - double d0; - - if (this.i > 0) { - vec3d = this.entity.getMot(); - this.entity.setMot(vec3d.x, 0.3D, vec3d.z); - if (!world.isClientSide) { - d0 = 0.08D; - ((WorldServer) world).a(new ParticleParamItem(Particles.ITEM, new ItemStack(Items.EGG)), (double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 0.7D, (double) blockposition1.getZ() + 0.5D, 3, ((double) random.nextFloat() - 0.5D) * 0.08D, ((double) random.nextFloat() - 0.5D) * 0.08D, ((double) random.nextFloat() - 0.5D) * 0.08D, 0.15000000596046448D); - } - } - - if (this.i % 2 == 0) { - vec3d = this.entity.getMot(); - this.entity.setMot(vec3d.x, -0.3D, vec3d.z); - if (this.i % 6 == 0) { - this.a((GeneratorAccess) world, this.e); - } - } - - if (this.i > 60) { - // CraftBukkit start - Step on eggs - EntityInteractEvent event = new EntityInteractEvent(this.entity.getBukkitEntity(), CraftBlock.at(world, blockposition1)); - world.getServer().getPluginManager().callEvent((EntityInteractEvent) event); - - if (event.isCancelled()) { - return; - } - // CraftBukkit end - world.a(blockposition1, false); - if (!world.isClientSide) { - for (int i = 0; i < 20; ++i) { - d0 = random.nextGaussian() * 0.02D; - double d1 = random.nextGaussian() * 0.02D; - double d2 = random.nextGaussian() * 0.02D; - - ((WorldServer) world).a(Particles.POOF, (double) blockposition1.getX() + 0.5D, (double) blockposition1.getY(), (double) blockposition1.getZ() + 0.5D, 1, d0, d1, d2, 0.15000000596046448D); - } - - this.a(world, blockposition1); - } - } - - ++this.i; - } - - } - - @Nullable - private BlockPosition a(BlockPosition blockposition, IBlockAccess iblockaccess) { - Block block = world.getBlockIfLoaded(blockposition); // Paper - if (block == null) return null; // Paper - if (block == this.g) { // Paper - return blockposition; - } else { - BlockPosition[] ablockposition = new BlockPosition[]{blockposition.down(), blockposition.west(), blockposition.east(), blockposition.north(), blockposition.south(), blockposition.down().down()}; - BlockPosition[] ablockposition1 = ablockposition; - int i = ablockposition.length; - - for (int j = 0; j < i; ++j) { - BlockPosition blockposition1 = ablockposition1[j]; - - if (world.getBlockIfLoaded(blockposition1) == this.g) { // Paper - return blockposition1; - } - } - - return null; - } - } - - @Override - protected boolean a(IWorldReader iworldreader, BlockPosition blockposition) { - IChunkAccess ichunkaccess = iworldreader.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4); // Paper - - return ichunkaccess == null ? false : ichunkaccess.getType(blockposition).getBlock() == this.g && ichunkaccess.getType(blockposition.up()).isAir() && ichunkaccess.getType(blockposition.up(2)).isAir(); - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalSit.java b/src/main/java/net/minecraft/server/PathfinderGoalSit.java deleted file mode 100644 index 3bb38030c..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalSit.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; - -public class PathfinderGoalSit extends PathfinderGoal { - - private final EntityTameableAnimal entity; - private boolean willSit; - - public PathfinderGoalSit(EntityTameableAnimal entitytameableanimal) { - this.entity = entitytameableanimal; - this.a(EnumSet.of(PathfinderGoal.Type.JUMP, PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean b() { - return this.willSit; - } - - @Override - public boolean a() { - if (!this.entity.isTamed()) { - return this.willSit && this.entity.getGoalTarget() == null; // CraftBukkit - Allow sitting for wild animals - } else if (this.entity.av()) { - return false; - } else if (!this.entity.onGround) { - return false; - } else { - EntityLiving entityliving = this.entity.getOwner(); - - return entityliving == null ? true : (this.entity.h((Entity) entityliving) < 144.0D && entityliving.getLastDamager() != null ? false : this.willSit); - } - } - - @Override - public void c() { - this.entity.getNavigation().o(); - this.entity.setSitting(true); - } - - @Override - public void d() { - this.entity.setSitting(false); - } - - public void setSitting(boolean flag) { - this.willSit = flag; - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalTame.java b/src/main/java/net/minecraft/server/PathfinderGoalTame.java deleted file mode 100644 index 85fd50b3d..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalTame.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; - -public class PathfinderGoalTame extends PathfinderGoal { - - private final EntityHorseAbstract entity; - private final double b; - private double c; - private double d; - private double e; - - public PathfinderGoalTame(EntityHorseAbstract entityhorseabstract, double d0) { - this.entity = entityhorseabstract; - this.b = d0; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE)); - } - - @Override - public boolean a() { - if (!this.entity.isTamed() && this.entity.isVehicle()) { - Vec3D vec3d = RandomPositionGenerator.a(this.entity, 5, 4); - - if (vec3d == null) { - return false; - } else { - this.c = vec3d.x; - this.d = vec3d.y; - this.e = vec3d.z; - return true; - } - } else { - return false; - } - } - - @Override - public void c() { - this.entity.getNavigation().a(this.c, this.d, this.e, this.b); - } - - @Override - public boolean b() { - return !this.entity.isTamed() && !this.entity.getNavigation().n() && this.entity.isVehicle(); - } - - @Override - public void e() { - if (!this.entity.isTamed() && this.entity.getRandom().nextInt(50) == 0) { - Entity entity = (Entity) this.entity.getPassengers().get(0); - - if (entity == null) { - return; - } - - if (entity instanceof EntityHuman) { - int i = this.entity.getTemper(); - int j = this.entity.getMaxDomestication(); - - // CraftBukkit - fire EntityTameEvent - if (j > 0 && this.entity.getRandom().nextInt(j) < i && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityTameEvent(this.entity, ((org.bukkit.craftbukkit.entity.CraftHumanEntity) this.entity.getBukkitEntity().getPassenger()).getHandle()).isCancelled()) { - this.entity.h((EntityHuman) entity); - return; - } - - this.entity.u(5); - } - - this.entity.ejectPassengers(); - this.entity.eu(); - this.entity.world.broadcastEntityEffect(this.entity, (byte) 6); - } - - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalTarget.java b/src/main/java/net/minecraft/server/PathfinderGoalTarget.java deleted file mode 100644 index f15d8bf83..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalTarget.java +++ /dev/null @@ -1,140 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -import org.bukkit.event.entity.EntityTargetEvent; // CraftBukkit - -public abstract class PathfinderGoalTarget extends PathfinderGoal { - - protected final EntityInsentient e; - protected final boolean f; - private final boolean a; - private int b; - private int c; - private int d; - protected EntityLiving g; - protected int h; - - public PathfinderGoalTarget(EntityInsentient entityinsentient, boolean flag) { - this(entityinsentient, flag, false); - } - - public PathfinderGoalTarget(EntityInsentient entityinsentient, boolean flag, boolean flag1) { - this.h = 60; - this.e = entityinsentient; - this.f = flag; - this.a = flag1; - } - - @Override - public boolean b() { - EntityLiving entityliving = this.e.getGoalTarget(); - - if (entityliving == null) { - entityliving = this.g; - } - - 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.k(); - - if (this.e.h((Entity) entityliving) > d0 * d0) { - return false; - } else { - if (this.f) { - if (this.e.getEntitySenses().a(entityliving)) { - this.d = 0; - } else if (++this.d > this.h) { - return false; - } - } - - if (entityliving instanceof EntityHuman && ((EntityHuman) entityliving).abilities.isInvulnerable) { - return false; - } else { - this.e.setGoalTarget(entityliving, EntityTargetEvent.TargetReason.CLOSEST_ENTITY, true); // CraftBukkit - return true; - } - } - } - } - } - - protected double k() { - AttributeInstance attributeinstance = this.e.getAttributeInstance(GenericAttributes.FOLLOW_RANGE); - - return attributeinstance == null ? 16.0D : attributeinstance.getValue(); - } - - @Override - public void c() { - this.b = 0; - this.c = 0; - this.d = 0; - } - - @Override - public void d() { - this.e.setGoalTarget((EntityLiving) null, EntityTargetEvent.TargetReason.FORGOT_TARGET, true); // CraftBukkit - this.g = null; - } - - protected boolean a(@Nullable EntityLiving entityliving, PathfinderTargetCondition pathfindertargetcondition) { - if (entityliving == null) { - return false; - } else if (!pathfindertargetcondition.a(this.e, entityliving)) { - return false; - } else if (!this.e.a(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; - } - - if (this.b == 2) { - return false; - } - } - - return true; - } - } - - private boolean a(EntityLiving entityliving) { - this.c = 10 + this.e.getRandom().nextInt(5); - PathEntity pathentity = this.e.getNavigation().a((Entity) entityliving, 0); - - 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; - } - } - } - - public PathfinderGoalTarget a(int i) { - this.h = i; - return this; - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderGoalTempt.java b/src/main/java/net/minecraft/server/PathfinderGoalTempt.java deleted file mode 100644 index d1164dd68..000000000 --- a/src/main/java/net/minecraft/server/PathfinderGoalTempt.java +++ /dev/null @@ -1,125 +0,0 @@ -package net.minecraft.server; - -import java.util.EnumSet; -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftLivingEntity; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.EntityTargetEvent; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -// CraftBukkit end - -public class PathfinderGoalTempt extends PathfinderGoal { - - private static final PathfinderTargetCondition c = (new PathfinderTargetCondition()).a(10.0D).a().b().d().c(); - protected final EntityCreature a; - private final double d; - private double e; - private double f; - private double g; - private double h; - private double i; - protected EntityLiving target; // CraftBukkit - private int j; - private boolean k; - private final RecipeItemStack l; - private final boolean m; - - public PathfinderGoalTempt(EntityCreature entitycreature, double d0, RecipeItemStack recipeitemstack, boolean flag) { - this(entitycreature, d0, flag, recipeitemstack); - } - - public PathfinderGoalTempt(EntityCreature entitycreature, double d0, boolean flag, RecipeItemStack recipeitemstack) { - this.a = entitycreature; - this.d = d0; - this.l = recipeitemstack; - this.m = flag; - this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK)); - if (!(entitycreature.getNavigation() instanceof Navigation)) { - throw new IllegalArgumentException("Unsupported mob type for TemptGoal"); - } - } - - @Override - public boolean a() { - if (this.j > 0) { - --this.j; - return false; - } else { - this.target = this.a.world.a(PathfinderGoalTempt.c, (EntityLiving) this.a); - // CraftBukkit start - boolean tempt = this.target == null ? false : this.a(this.target.getItemInMainHand()) || this.a(this.target.getItemInOffHand()); - if (tempt) { - EntityTargetLivingEntityEvent event = CraftEventFactory.callEntityTargetLivingEvent(this.a, this.target, EntityTargetEvent.TargetReason.TEMPT); - if (event.isCancelled()) { - return false; - } - this.target = (event.getTarget() == null) ? null : ((CraftLivingEntity) event.getTarget()).getHandle(); - } - return tempt && this.target != null; // Paper - must have target - plugin might of cancelled - // CraftBukkit end - } - } - - protected boolean a(ItemStack itemstack) { - return this.l.test(itemstack); - } - - @Override - public boolean b() { - if (this.g()) { - if (this.a.h((Entity) this.target) < 36.0D) { - if (this.target.e(this.e, this.f, this.g) > 0.010000000000000002D) { - return false; - } - - if (Math.abs((double) this.target.pitch - this.h) > 5.0D || Math.abs((double) this.target.yaw - this.i) > 5.0D) { - return false; - } - } else { - this.e = this.target.locX; - this.f = this.target.locY; - this.g = this.target.locZ; - } - - this.h = (double) this.target.pitch; - this.i = (double) this.target.yaw; - } - - return this.a(); - } - - protected boolean g() { - return this.m; - } - - @Override - public void c() { - this.e = this.target.locX; - this.f = this.target.locY; - this.g = this.target.locZ; - this.k = true; - } - - @Override - public void d() { - this.target = null; - this.a.getNavigation().o(); - this.j = 100; - this.k = false; - } - - @Override - public void e() { - this.a.getControllerLook().a(this.target, (float) (this.a.dA() + 20), (float) this.a.M()); - if (this.a.h((Entity) this.target) < 6.25D) { - this.a.getNavigation().o(); - } else { - this.a.getNavigation().a((Entity) this.target, this.d); - } - - } - - public boolean h() { - return this.k; - } -} diff --git a/src/main/java/net/minecraft/server/PathfinderNormal.java b/src/main/java/net/minecraft/server/PathfinderNormal.java deleted file mode 100644 index 45fd13503..000000000 --- a/src/main/java/net/minecraft/server/PathfinderNormal.java +++ /dev/null @@ -1,461 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Sets; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Set; -import javax.annotation.Nullable; - -public class PathfinderNormal extends PathfinderAbstract { - - protected float j; - - public PathfinderNormal() {} - - @Override - public void a(IWorldReader iworldreader, EntityInsentient entityinsentient) { - super.a(iworldreader, entityinsentient); - this.j = entityinsentient.a(PathType.WATER); - } - - @Override - public void a() { - this.b.a(PathType.WATER, this.j); - super.a(); - } - - @Override - public PathPoint b() { - int i; - BlockPosition blockposition; - - if (this.e() && this.b.isInWater()) { - i = MathHelper.floor(this.b.getBoundingBox().minY); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(this.b.locX, (double) i, this.b.locZ); - - for (IBlockData iblockdata = this.a.getType(blockposition_mutableblockposition); iblockdata.getBlock() == Blocks.WATER || iblockdata.p() == FluidTypes.WATER.a(false); iblockdata = this.a.getType(blockposition_mutableblockposition)) { - ++i; - blockposition_mutableblockposition.c(this.b.locX, (double) i, this.b.locZ); - } - - --i; - } else if (this.b.onGround) { - i = MathHelper.floor(this.b.getBoundingBox().minY + 0.5D); - } else { - for (blockposition = new BlockPosition(this.b); (this.a.getType(blockposition).isAir() || this.a.getType(blockposition).a((IBlockAccess) this.a, blockposition, PathMode.LAND)) && blockposition.getY() > 0; blockposition = blockposition.down()) { - ; - } - - i = blockposition.up().getY(); - } - - blockposition = new BlockPosition(this.b); - PathType pathtype = this.a(this.b, blockposition.getX(), i, blockposition.getZ()); - - if (this.b.a(pathtype) < 0.0F) { - Set set = Sets.newHashSet(); - - set.add(new BlockPosition(this.b.getBoundingBox().minX, (double) i, this.b.getBoundingBox().minZ)); - set.add(new BlockPosition(this.b.getBoundingBox().minX, (double) i, this.b.getBoundingBox().maxZ)); - set.add(new BlockPosition(this.b.getBoundingBox().maxX, (double) i, this.b.getBoundingBox().minZ)); - set.add(new BlockPosition(this.b.getBoundingBox().maxX, (double) i, this.b.getBoundingBox().maxZ)); - Iterator iterator = set.iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition1 = (BlockPosition) iterator.next(); - PathType pathtype1 = this.a(this.b, blockposition1); - - if (this.b.a(pathtype1) >= 0.0F) { - return this.a(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); - } - } - } - - return this.a(blockposition.getX(), i, blockposition.getZ()); - } - - @Override - public PathDestination a(double d0, double d1, double d2) { - return new PathDestination(this.a(MathHelper.floor(d0), MathHelper.floor(d1), MathHelper.floor(d2))); - } - - @Override - public int a(PathPoint[] apathpoint, PathPoint pathpoint) { - int i = 0; - int j = 0; - PathType pathtype = this.a(this.b, pathpoint.a, pathpoint.b + 1, pathpoint.c); - - if (this.b.a(pathtype) >= 0.0F) { - j = MathHelper.d(Math.max(1.0F, this.b.K)); - } - - double d0 = a((IBlockAccess) this.a, new BlockPosition(pathpoint.a, pathpoint.b, pathpoint.c)); - PathPoint pathpoint1 = this.a(pathpoint.a, pathpoint.b, pathpoint.c + 1, j, d0, EnumDirection.SOUTH); - - if (pathpoint1 != null && !pathpoint1.i && pathpoint1.k >= 0.0F) { - apathpoint[i++] = pathpoint1; - } - - PathPoint pathpoint2 = this.a(pathpoint.a - 1, pathpoint.b, pathpoint.c, j, d0, EnumDirection.WEST); - - if (pathpoint2 != null && !pathpoint2.i && pathpoint2.k >= 0.0F) { - apathpoint[i++] = pathpoint2; - } - - PathPoint pathpoint3 = this.a(pathpoint.a + 1, pathpoint.b, pathpoint.c, j, d0, EnumDirection.EAST); - - if (pathpoint3 != null && !pathpoint3.i && pathpoint3.k >= 0.0F) { - apathpoint[i++] = pathpoint3; - } - - PathPoint pathpoint4 = this.a(pathpoint.a, pathpoint.b, pathpoint.c - 1, j, d0, EnumDirection.NORTH); - - if (pathpoint4 != null && !pathpoint4.i && pathpoint4.k >= 0.0F) { - apathpoint[i++] = pathpoint4; - } - - PathPoint pathpoint5 = this.a(pathpoint.a - 1, pathpoint.b, pathpoint.c - 1, j, d0, EnumDirection.NORTH); - - if (this.a(pathpoint, pathpoint2, pathpoint4, pathpoint5)) { - apathpoint[i++] = pathpoint5; - } - - PathPoint pathpoint6 = this.a(pathpoint.a + 1, pathpoint.b, pathpoint.c - 1, j, d0, EnumDirection.NORTH); - - if (this.a(pathpoint, pathpoint3, pathpoint4, pathpoint6)) { - apathpoint[i++] = pathpoint6; - } - - PathPoint pathpoint7 = this.a(pathpoint.a - 1, pathpoint.b, pathpoint.c + 1, j, d0, EnumDirection.SOUTH); - - if (this.a(pathpoint, pathpoint2, pathpoint1, pathpoint7)) { - apathpoint[i++] = pathpoint7; - } - - PathPoint pathpoint8 = this.a(pathpoint.a + 1, pathpoint.b, pathpoint.c + 1, j, d0, EnumDirection.SOUTH); - - if (this.a(pathpoint, pathpoint3, pathpoint1, pathpoint8)) { - apathpoint[i++] = pathpoint8; - } - - return i; - } - - private boolean a(PathPoint pathpoint, @Nullable PathPoint pathpoint1, @Nullable PathPoint pathpoint2, @Nullable PathPoint pathpoint3) { - return pathpoint3 != null && pathpoint2 != null && pathpoint1 != null ? (pathpoint3.i ? false : (pathpoint2.b <= pathpoint.b && pathpoint1.b <= pathpoint.b ? pathpoint3.k >= 0.0F && (pathpoint2.b < pathpoint.b || pathpoint2.k >= 0.0F) && (pathpoint1.b < pathpoint.b || pathpoint1.k >= 0.0F) : false)) : false; - } - - public static double a(IBlockAccess iblockaccess, BlockPosition blockposition) { - BlockPosition blockposition1 = blockposition.down(); - VoxelShape voxelshape = iblockaccess.getType(blockposition1).getCollisionShape(iblockaccess, blockposition1); - - return (double) blockposition1.getY() + (voxelshape.isEmpty() ? 0.0D : voxelshape.c(EnumDirection.EnumAxis.Y)); - } - - @Nullable - private PathPoint a(int i, int j, int k, int l, double d0, EnumDirection enumdirection) { - PathPoint pathpoint = null; - BlockPosition blockposition = new BlockPosition(i, j, k); - double d1 = a((IBlockAccess) this.a, blockposition); - - if (d1 - d0 > 1.125D) { - return null; - } else { - PathType pathtype = this.a(this.b, i, j, k); - float f = this.b.a(pathtype); - double d2 = (double) this.b.getWidth() / 2.0D; - - if (f >= 0.0F) { - pathpoint = this.a(i, j, k); - pathpoint.l = pathtype; - pathpoint.k = Math.max(pathpoint.k, f); - } - - if (pathtype == PathType.WALKABLE) { - return pathpoint; - } else { - if ((pathpoint == null || pathpoint.k < 0.0F) && l > 0 && pathtype != PathType.FENCE && pathtype != PathType.TRAPDOOR) { - pathpoint = this.a(i, j + 1, k, l - 1, d0, enumdirection); - if (pathpoint != null && (pathpoint.l == PathType.OPEN || pathpoint.l == PathType.WALKABLE) && this.b.getWidth() < 1.0F) { - double d3 = (double) (i - enumdirection.getAdjacentX()) + 0.5D; - double d4 = (double) (k - enumdirection.getAdjacentZ()) + 0.5D; - AxisAlignedBB axisalignedbb = new AxisAlignedBB(d3 - d2, a((IBlockAccess) this.a, new BlockPosition(d3, (double) (j + 1), d4)) + 0.001D, d4 - d2, d3 + d2, (double) this.b.getHeight() + a((IBlockAccess) this.a, new BlockPosition(pathpoint.a, pathpoint.b, pathpoint.c)) - 0.002D, d4 + d2); - - if (!this.a.getCubes(this.b, axisalignedbb)) { - pathpoint = null; - } - } - } - - if (pathtype == PathType.WATER && !this.e()) { - if (this.a(this.b, i, j - 1, k) != PathType.WATER) { - return pathpoint; - } - - while (j > 0) { - --j; - pathtype = this.a(this.b, i, j, k); - if (pathtype != PathType.WATER) { - return pathpoint; - } - - pathpoint = this.a(i, j, k); - pathpoint.l = pathtype; - pathpoint.k = Math.max(pathpoint.k, this.b.a(pathtype)); - } - } - - if (pathtype == PathType.OPEN) { - AxisAlignedBB axisalignedbb1 = new AxisAlignedBB((double) i - d2 + 0.5D, (double) j + 0.001D, (double) k - d2 + 0.5D, (double) i + d2 + 0.5D, (double) ((float) j + this.b.getHeight()), (double) k + d2 + 0.5D); - - if (!this.a.getCubes(this.b, axisalignedbb1)) { - return null; - } - - if (this.b.getWidth() >= 1.0F) { - PathType pathtype1 = this.a(this.b, i, j - 1, k); - - if (pathtype1 == PathType.BLOCKED) { - pathpoint = this.a(i, j, k); - pathpoint.l = PathType.WALKABLE; - pathpoint.k = Math.max(pathpoint.k, f); - return pathpoint; - } - } - - int i1 = 0; - int j1 = j; - - while (pathtype == PathType.OPEN) { - --j; - PathPoint pathpoint1; - - if (j < 0) { - pathpoint1 = this.a(i, j1, k); - pathpoint1.l = PathType.BLOCKED; - pathpoint1.k = -1.0F; - return pathpoint1; - } - - pathpoint1 = this.a(i, j, k); - if (i1++ >= this.b.bv()) { - pathpoint1.l = PathType.BLOCKED; - pathpoint1.k = -1.0F; - return pathpoint1; - } - - pathtype = this.a(this.b, i, j, k); - f = this.b.a(pathtype); - if (pathtype != PathType.OPEN && f >= 0.0F) { - pathpoint = pathpoint1; - pathpoint1.l = pathtype; - pathpoint1.k = Math.max(pathpoint1.k, f); - break; - } - - if (f < 0.0F) { - pathpoint1.l = PathType.BLOCKED; - pathpoint1.k = -1.0F; - return pathpoint1; - } - } - } - - return pathpoint; - } - } - } - - @Override - public PathType a(IBlockAccess iblockaccess, int i, int j, int k, EntityInsentient entityinsentient, int l, int i1, int j1, boolean flag, boolean flag1) { - EnumSet enumset = EnumSet.noneOf(PathType.class); - PathType pathtype = PathType.BLOCKED; - double d0 = (double) entityinsentient.getWidth() / 2.0D; - BlockPosition blockposition = new BlockPosition(entityinsentient); - - pathtype = this.a(iblockaccess, i, j, k, l, i1, j1, flag, flag1, enumset, pathtype, blockposition); - if (enumset.contains(PathType.FENCE)) { - return PathType.FENCE; - } else { - PathType pathtype1 = PathType.BLOCKED; - Iterator iterator = enumset.iterator(); - - while (iterator.hasNext()) { - PathType pathtype2 = (PathType) iterator.next(); - - if (entityinsentient.a(pathtype2) < 0.0F) { - return pathtype2; - } - - if (entityinsentient.a(pathtype2) >= entityinsentient.a(pathtype1)) { - pathtype1 = pathtype2; - } - } - - if (pathtype == PathType.OPEN && entityinsentient.a(pathtype1) == 0.0F) { - return PathType.OPEN; - } else { - return pathtype1; - } - } - } - - public PathType a(IBlockAccess iblockaccess, int i, int j, int k, int l, int i1, int j1, boolean flag, boolean flag1, EnumSet enumset, PathType pathtype, BlockPosition blockposition) { - for (int k1 = 0; k1 < l; ++k1) { - for (int l1 = 0; l1 < i1; ++l1) { - for (int i2 = 0; i2 < j1; ++i2) { - int j2 = k1 + i; - int k2 = l1 + j; - int l2 = i2 + k; - PathType pathtype1 = this.a(iblockaccess, j2, k2, l2); - - pathtype1 = this.a(iblockaccess, flag, flag1, blockposition, pathtype1); - if (k1 == 0 && l1 == 0 && i2 == 0) { - pathtype = pathtype1; - } - - enumset.add(pathtype1); - } - } - } - - return pathtype; - } - - protected PathType a(IBlockAccess iblockaccess, boolean flag, boolean flag1, BlockPosition blockposition, PathType pathtype) { - if (pathtype == PathType.DOOR_WOOD_CLOSED && flag && flag1) { - pathtype = PathType.WALKABLE; - } - - if (pathtype == PathType.DOOR_OPEN && !flag1) { - pathtype = PathType.BLOCKED; - } - - if (pathtype == PathType.RAIL && !(iblockaccess.getType(blockposition).getBlock() instanceof BlockMinecartTrackAbstract) && !(iblockaccess.getType(blockposition.down()).getBlock() instanceof BlockMinecartTrackAbstract)) { - pathtype = PathType.FENCE; - } - - if (pathtype == PathType.LEAVES) { - pathtype = PathType.BLOCKED; - } - - return pathtype; - } - - private PathType a(EntityInsentient entityinsentient, BlockPosition blockposition) { - return this.a(entityinsentient, blockposition.getX(), blockposition.getY(), blockposition.getZ()); - } - - private PathType a(EntityInsentient entityinsentient, int i, int j, int k) { - return this.a(this.a, i, j, k, entityinsentient, this.d, this.e, this.f, this.d(), this.c()); - } - - @Override - public PathType a(IBlockAccess iblockaccess, int i, int j, int k) { - PathType pathtype = this.b(iblockaccess, i, j, k); - - if (pathtype == PathType.OPEN && j >= 1) { - Block block = iblockaccess.getBlockIfLoaded(new BlockPosition(i, j - 1, k)); // Paper - if (block == null) return PathType.BLOCKED; // Paper - PathType pathtype1 = this.b(iblockaccess, i, j - 1, k); - - pathtype = pathtype1 != PathType.WALKABLE && pathtype1 != PathType.OPEN && pathtype1 != PathType.WATER && pathtype1 != PathType.LAVA ? PathType.WALKABLE : PathType.OPEN; - if (pathtype1 == PathType.DAMAGE_FIRE || block == Blocks.MAGMA_BLOCK || block == Blocks.CAMPFIRE) { - pathtype = PathType.DAMAGE_FIRE; - } - - if (pathtype1 == PathType.DAMAGE_CACTUS) { - pathtype = PathType.DAMAGE_CACTUS; - } - - if (pathtype1 == PathType.DAMAGE_OTHER) { - pathtype = PathType.DAMAGE_OTHER; - } - } - - pathtype = this.a(iblockaccess, i, j, k, pathtype); - return pathtype; - } - - public PathType a(IBlockAccess iblockaccess, int i, int j, int k, PathType pathtype) { - if (pathtype == PathType.WALKABLE) { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - for (int l = -1; l <= 1; ++l) { - for (int i1 = -1; i1 <= 1; ++i1) { - if (l != 0 || i1 != 0) { - Block block = iblockaccess.getBlockIfLoaded(blockposition_pooledblockposition.d(l + i, j, i1 + k)); // Paper - - if (block == null) pathtype = PathType.BLOCKED; // Paper - else if (block == Blocks.CACTUS) { // Paper - pathtype = PathType.DANGER_CACTUS; - } else if (block == Blocks.FIRE) { - pathtype = PathType.DANGER_FIRE; - } else if (block == Blocks.SWEET_BERRY_BUSH) { - pathtype = PathType.DANGER_OTHER; - } - } - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - } - - return pathtype; - } - - protected PathType b(IBlockAccess iblockaccess, int i, int j, int k) { - BlockPosition blockposition = new BlockPosition(i, j, k); - IBlockData iblockdata = iblockaccess.getTypeIfLoaded(blockposition); // Paper - if (iblockdata == null) return PathType.BLOCKED; // Paper - Block block = iblockdata.getBlock(); - Material material = iblockdata.getMaterial(); - - if (iblockdata.isAir()) { - return PathType.OPEN; - } else if (!block.a(TagsBlock.TRAPDOORS) && block != Blocks.LILY_PAD) { - if (block == Blocks.FIRE) { - return PathType.DAMAGE_FIRE; - } else if (block == Blocks.CACTUS) { - return PathType.DAMAGE_CACTUS; - } else if (block == Blocks.SWEET_BERRY_BUSH) { - return PathType.DAMAGE_OTHER; - } else if (block instanceof BlockDoor && material == Material.WOOD && !(Boolean) iblockdata.get(BlockDoor.OPEN)) { - return PathType.DOOR_WOOD_CLOSED; - } else if (block instanceof BlockDoor && material == Material.ORE && !(Boolean) iblockdata.get(BlockDoor.OPEN)) { - return PathType.DOOR_IRON_CLOSED; - } else if (block instanceof BlockDoor && (Boolean) iblockdata.get(BlockDoor.OPEN)) { - return PathType.DOOR_OPEN; - } else if (block instanceof BlockMinecartTrackAbstract) { - return PathType.RAIL; - } else if (block instanceof BlockLeaves) { - return PathType.LEAVES; - } else if (!block.a(TagsBlock.FENCES) && !block.a(TagsBlock.WALLS) && (!(block instanceof BlockFenceGate) || (Boolean) iblockdata.get(BlockFenceGate.OPEN))) { - Fluid fluid = iblockaccess.getFluid(blockposition); - - return fluid.a(TagsFluid.WATER) ? PathType.WATER : (fluid.a(TagsFluid.LAVA) ? PathType.LAVA : (iblockdata.a(iblockaccess, blockposition, PathMode.LAND) ? PathType.OPEN : PathType.BLOCKED)); - } else { - return PathType.FENCE; - } - } else { - return PathType.TRAPDOOR; - } - } -} diff --git a/src/main/java/net/minecraft/server/PersistentRaid.java b/src/main/java/net/minecraft/server/PersistentRaid.java deleted file mode 100644 index 79d16eef9..000000000 --- a/src/main/java/net/minecraft/server/PersistentRaid.java +++ /dev/null @@ -1,202 +0,0 @@ -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.stream.Collectors; -import javax.annotation.Nullable; - -public class PersistentRaid extends PersistentBase { - - public final Map a = Maps.newHashMap(); // PAIL rename raids, private -> public - private final WorldServer b; - private int c; - private int d; - - public PersistentRaid(WorldServer worldserver) { - super(a(worldserver.worldProvider)); - this.b = worldserver; - this.c = 1; - this.b(); - } - - public Raid a(int i) { - return (Raid) this.a.get(i); - } - - public void a() { - ++this.d; - Iterator iterator = this.a.values().iterator(); - - while (iterator.hasNext()) { - Raid raid = (Raid) iterator.next(); - - if (this.b.getGameRules().getBoolean(GameRules.x)) { - raid.n(); - } - - if (raid.d()) { - iterator.remove(); - this.b(); - } else { - raid.o(); - } - } - - if (this.d % 200 == 0) { - this.b(); - } - - PacketDebug.a(this.b, this.a.values()); - } - - public static boolean a(EntityRaider entityraider, Raid raid) { - return entityraider != null && raid != null && raid.i() != null ? entityraider.isAlive() && entityraider.ei() && entityraider.cw() <= 2400 && entityraider.world.getWorldProvider().getDimensionManager() == raid.i().getWorldProvider().getDimensionManager() : false; - } - - @Nullable - public Raid a(EntityPlayer entityplayer) { - if (entityplayer.isSpectator()) { - return null; - } else if (this.b.getGameRules().getBoolean(GameRules.x)) { - return null; - } else { - DimensionManager dimensionmanager = entityplayer.world.getWorldProvider().getDimensionManager(); - - if (dimensionmanager == DimensionManager.NETHER) { - return null; - } else { - BlockPosition blockposition = new BlockPosition(entityplayer); - List list = (List) this.b.B().b(VillagePlaceType.a, blockposition, 64, VillagePlace.Occupancy.IS_OCCUPIED).collect(Collectors.toList()); - int i = 0; - Vec3D vec3d = new Vec3D(0.0D, 0.0D, 0.0D); - - for (Iterator iterator = list.iterator(); iterator.hasNext(); ++i) { - VillagePlaceRecord villageplacerecord = (VillagePlaceRecord) iterator.next(); - BlockPosition blockposition1 = villageplacerecord.f(); - - vec3d = vec3d.add((double) blockposition1.getX(), (double) blockposition1.getY(), (double) blockposition1.getZ()); - } - - BlockPosition blockposition2; - - if (i > 0) { - vec3d = vec3d.a(1.0D / (double) i); - blockposition2 = new BlockPosition(vec3d); - } else { - blockposition2 = blockposition; - } - - Raid raid = this.a(entityplayer.getWorldServer(), blockposition2); - boolean flag = false; - - if (!raid.j()) { - /* CraftBukkit - moved down - if (!this.a.containsKey(raid.u())) { - this.a.put(raid.u(), raid); - } - */ - - flag = true; - // CraftBukkit start - fixed a bug with raid: players could add up Bad Omen level even when the raid had finished - } else if (raid.isInProgress() && raid.m() < raid.l()) { - flag = true; - // CraftBukkit end - } else { - entityplayer.removeEffect(MobEffects.BAD_OMEN); - entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, (byte) 43)); - } - - if (flag) { - // CraftBukkit start - if (!org.bukkit.craftbukkit.event.CraftEventFactory.callRaidTriggerEvent(raid, entityplayer)) { - entityplayer.removeEffect(MobEffects.BAD_OMEN); - return null; - } - - if (!this.a.containsKey(raid.u())) { - this.a.put(raid.u(), raid); - } - // CraftBukkit end - raid.a((EntityHuman) entityplayer); - entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, (byte) 43)); - if (!raid.c()) { - entityplayer.a(StatisticList.RAID_TRIGGER); - CriterionTriggers.I.a(entityplayer); - } - } - - this.b(); - return raid; - } - } - } - - private Raid a(WorldServer worldserver, BlockPosition blockposition) { - Raid raid = worldserver.c_(blockposition); - - return raid != null ? raid : new Raid(this.e(), worldserver, blockposition); - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.c = nbttagcompound.getInt("NextAvailableID"); - this.d = nbttagcompound.getInt("Tick"); - NBTTagList nbttaglist = nbttagcompound.getList("Raids", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompound(i); - Raid raid = new Raid(this.b, nbttagcompound1); - - this.a.put(raid.u(), raid); - } - - } - - @Override - public NBTTagCompound b(NBTTagCompound nbttagcompound) { - nbttagcompound.setInt("NextAvailableID", this.c); - nbttagcompound.setInt("Tick", this.d); - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.a.values().iterator(); - - while (iterator.hasNext()) { - Raid raid = (Raid) iterator.next(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - raid.a(nbttagcompound1); - nbttaglist.add(nbttagcompound1); - } - - nbttagcompound.set("Raids", nbttaglist); - return nbttagcompound; - } - - public static String a(WorldProvider worldprovider) { - return "raids" + worldprovider.getDimensionManager().getSuffix(); - } - - private int e() { - return ++this.c; - } - - @Nullable - public Raid a(BlockPosition blockposition, int i) { - Raid raid = null; - double d0 = (double) i; - Iterator iterator = this.a.values().iterator(); - - while (iterator.hasNext()) { - Raid raid1 = (Raid) iterator.next(); - double d1 = raid1.t().m(blockposition); - - if (raid1.v() && d1 < d0) { - raid = raid1; - d0 = d1; - } - } - - return raid; - } -} diff --git a/src/main/java/net/minecraft/server/PersistentScoreboard.java b/src/main/java/net/minecraft/server/PersistentScoreboard.java deleted file mode 100644 index de7ac6c20..000000000 --- a/src/main/java/net/minecraft/server/PersistentScoreboard.java +++ /dev/null @@ -1,249 +0,0 @@ -package net.minecraft.server; - -import java.util.Collection; -import java.util.Iterator; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class PersistentScoreboard extends PersistentBase { - - private static final Logger LOGGER = LogManager.getLogger(); - private Scoreboard b; - private NBTTagCompound c; - - public PersistentScoreboard() { - super("scoreboard"); - } - - public void a(Scoreboard scoreboard) { - this.b = scoreboard; - if (this.c != null) { - this.a(this.c); - } - - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - if (this.b == null) { - this.c = nbttagcompound; - } else { - this.b(nbttagcompound.getList("Objectives", 10)); - this.b.a(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.getCompound(i); - String s = nbttagcompound.getString("Name"); - - if (s.length() > 16) { - s = s.substring(0, 16); - } - - ScoreboardTeam scoreboardteam = this.b.createTeam(s); - IChatBaseComponent ichatbasecomponent = IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("DisplayName")); - - if (ichatbasecomponent != null) { - scoreboardteam.setDisplayName(ichatbasecomponent); - } - - if (nbttagcompound.hasKeyOfType("TeamColor", 8)) { - scoreboardteam.setColor(EnumChatFormat.c(nbttagcompound.getString("TeamColor"))); - } - - if (nbttagcompound.hasKeyOfType("AllowFriendlyFire", 99)) { - scoreboardteam.setAllowFriendlyFire(nbttagcompound.getBoolean("AllowFriendlyFire")); - } - - if (nbttagcompound.hasKeyOfType("SeeFriendlyInvisibles", 99)) { - scoreboardteam.setCanSeeFriendlyInvisibles(nbttagcompound.getBoolean("SeeFriendlyInvisibles")); - } - - IChatBaseComponent ichatbasecomponent1; - - if (nbttagcompound.hasKeyOfType("MemberNamePrefix", 8)) { - ichatbasecomponent1 = IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("MemberNamePrefix")); - if (ichatbasecomponent1 != null) { - scoreboardteam.setPrefix(ichatbasecomponent1); - } - } - - if (nbttagcompound.hasKeyOfType("MemberNameSuffix", 8)) { - ichatbasecomponent1 = IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("MemberNameSuffix")); - if (ichatbasecomponent1 != null) { - scoreboardteam.setSuffix(ichatbasecomponent1); - } - } - - 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.setDeathMessageVisibility(scoreboardteambase_enumnametagvisibility); - } - } - - if (nbttagcompound.hasKeyOfType("CollisionRule", 8)) { - ScoreboardTeamBase.EnumTeamPush scoreboardteambase_enumteampush = ScoreboardTeamBase.EnumTeamPush.a(nbttagcompound.getString("CollisionRule")); - - if (scoreboardteambase_enumteampush != null) { - scoreboardteam.setCollisionRule(scoreboardteambase_enumteampush); - } - } - - this.a(scoreboardteam, nbttagcompound.getList("Players", 8)); - } - - } - - protected void a(ScoreboardTeam scoreboardteam, NBTTagList nbttaglist) { - for (int i = 0; i < nbttaglist.size(); ++i) { - this.b.addPlayerToTeam(nbttaglist.getString(i), scoreboardteam); - } - - } - - protected void c(NBTTagCompound nbttagcompound) { - for (int i = 0; i < 19; ++i) { - if (nbttagcompound.hasKeyOfType("slot_" + i, 8)) { - String s = nbttagcompound.getString("slot_" + i); - ScoreboardObjective scoreboardobjective = this.b.getObjective(s); - - this.b.setDisplaySlot(i, scoreboardobjective); - } - } - - } - - protected void b(NBTTagList nbttaglist) { - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompound(i); - - IScoreboardCriteria.a(nbttagcompound.getString("CriteriaName")).ifPresent((iscoreboardcriteria) -> { - String s = nbttagcompound.getString("Name"); - - if (s.length() > 16) { - s = s.substring(0, 16); - } - - IChatBaseComponent ichatbasecomponent = IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("DisplayName")); - IScoreboardCriteria.EnumScoreboardHealthDisplay iscoreboardcriteria_enumscoreboardhealthdisplay = IScoreboardCriteria.EnumScoreboardHealthDisplay.a(nbttagcompound.getString("RenderType")); - - this.b.registerObjective(s, iscoreboardcriteria, ichatbasecomponent, iscoreboardcriteria_enumscoreboardhealthdisplay); - }); - } - - } - - @Override - public NBTTagCompound b(NBTTagCompound nbttagcompound) { - if (this.b == null) { - PersistentScoreboard.LOGGER.warn("Tried to save scoreboard without having a scoreboard..."); - return nbttagcompound; - } else { - nbttagcompound.set("Objectives", this.e()); - nbttagcompound.set("PlayerScores", this.b.i()); - nbttagcompound.set("Teams", this.a()); - this.d(nbttagcompound); - return nbttagcompound; - } - } - - protected NBTTagList a() { - NBTTagList nbttaglist = new NBTTagList(); - Collection collection = this.b.getTeams(); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - ScoreboardTeam scoreboardteam = (ScoreboardTeam) iterator.next(); - if (!com.destroystokyo.paper.PaperConfig.saveEmptyScoreboardTeams && scoreboardteam.getPlayerNameSet().isEmpty()) continue; // Paper - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setString("Name", scoreboardteam.getName()); - nbttagcompound.setString("DisplayName", IChatBaseComponent.ChatSerializer.a(scoreboardteam.getDisplayName())); - if (scoreboardteam.getColor().b() >= 0) { - nbttagcompound.setString("TeamColor", scoreboardteam.getColor().g()); - } - - nbttagcompound.setBoolean("AllowFriendlyFire", scoreboardteam.allowFriendlyFire()); - nbttagcompound.setBoolean("SeeFriendlyInvisibles", scoreboardteam.canSeeFriendlyInvisibles()); - nbttagcompound.setString("MemberNamePrefix", IChatBaseComponent.ChatSerializer.a(scoreboardteam.getPrefix())); - nbttagcompound.setString("MemberNameSuffix", IChatBaseComponent.ChatSerializer.a(scoreboardteam.getSuffix())); - nbttagcompound.setString("NameTagVisibility", scoreboardteam.getNameTagVisibility().e); - nbttagcompound.setString("DeathMessageVisibility", scoreboardteam.getDeathMessageVisibility().e); - nbttagcompound.setString("CollisionRule", scoreboardteam.getCollisionRule().e); - NBTTagList nbttaglist1 = new NBTTagList(); - Iterator iterator1 = scoreboardteam.getPlayerNameSet().iterator(); - - while (iterator1.hasNext()) { - String s = (String) iterator1.next(); - - 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.b.getObjectiveForSlot(i); - - if (scoreboardobjective != null) { - nbttagcompound1.setString("slot_" + i, scoreboardobjective.getName()); - flag = true; - } - } - - if (flag) { - nbttagcompound.set("DisplaySlots", nbttagcompound1); - } - - } - - protected NBTTagList e() { - NBTTagList nbttaglist = new NBTTagList(); - Collection collection = this.b.getObjectives(); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - ScoreboardObjective scoreboardobjective = (ScoreboardObjective) iterator.next(); - - if (scoreboardobjective.getCriteria() != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setString("Name", scoreboardobjective.getName()); - nbttagcompound.setString("CriteriaName", scoreboardobjective.getCriteria().getName()); - nbttagcompound.setString("DisplayName", IChatBaseComponent.ChatSerializer.a(scoreboardobjective.getDisplayName())); - nbttagcompound.setString("RenderType", scoreboardobjective.getRenderType().a()); - nbttaglist.add(nbttagcompound); - } - } - - return nbttaglist; - } -} diff --git a/src/main/java/net/minecraft/server/PlayerChunk.java b/src/main/java/net/minecraft/server/PlayerChunk.java deleted file mode 100644 index 34d0ab0d5..000000000 --- a/src/main/java/net/minecraft/server/PlayerChunk.java +++ /dev/null @@ -1,486 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.util.Either; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicReferenceArray; -import java.util.function.IntConsumer; -import java.util.function.IntSupplier; -import java.util.stream.Stream; -import javax.annotation.Nullable; - -public class PlayerChunk { - - public static final Either UNLOADED_CHUNK_ACCESS = Either.right(PlayerChunk.Failure.b); - public static final CompletableFuture> UNLOADED_CHUNK_ACCESS_FUTURE = CompletableFuture.completedFuture(PlayerChunk.UNLOADED_CHUNK_ACCESS); - public static final Either UNLOADED_CHUNK = Either.right(PlayerChunk.Failure.b); - private static final CompletableFuture> UNLOADED_CHUNK_FUTURE = CompletableFuture.completedFuture(PlayerChunk.UNLOADED_CHUNK); - private static final List CHUNK_STATUSES = ChunkStatus.a(); - private static final PlayerChunk.State[] CHUNK_STATES = PlayerChunk.State.values(); - private final AtomicReferenceArray>> statusFutures; - private volatile CompletableFuture> fullChunkFuture; - private volatile CompletableFuture> tickingFuture; - private volatile CompletableFuture> entityTickingFuture; - private CompletableFuture chunkSave; - public int oldTicketLevel; - private int ticketLevel; - private int n; - final ChunkCoordIntPair location; // Paper - private -> package - private final short[] dirtyBlocks; - private int dirtyCount; - private int r; - private int s; - private int t; - private int u; - private final LightEngine lightEngine; - private final PlayerChunk.c w; - public final PlayerChunk.d players; - private boolean hasBeenLoaded; - - public PlayerChunk(ChunkCoordIntPair chunkcoordintpair, int i, LightEngine lightengine, PlayerChunk.c playerchunk_c, PlayerChunk.d playerchunk_d) { - this.statusFutures = new AtomicReferenceArray(PlayerChunk.CHUNK_STATUSES.size()); - this.fullChunkFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE; - this.tickingFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE; - this.entityTickingFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE; - this.chunkSave = CompletableFuture.completedFuture(null); // CraftBukkit - decompile error - this.dirtyBlocks = new short[64]; - this.location = chunkcoordintpair; - this.lightEngine = lightengine; - this.w = playerchunk_c; - this.players = playerchunk_d; - this.oldTicketLevel = PlayerChunkMap.GOLDEN_TICKET + 1; - this.ticketLevel = this.oldTicketLevel; - this.n = this.oldTicketLevel; - this.a(i); - } - - // CraftBukkit start - public Chunk getFullChunk() { - if (!getChunkState(this.oldTicketLevel).isAtLeast(PlayerChunk.State.BORDER)) return null; // note: using oldTicketLevel for isLoaded checks - CompletableFuture> statusFuture = this.getStatusFutureUnchecked(ChunkStatus.FULL); - Either either = (Either) statusFuture.getNow(null); - return either == null ? null : (Chunk) either.left().orElse(null); - } - // CraftBukkit end - // Paper start - "real" get full chunk immediately - public Chunk getFullChunkIfCached() { - // Note: Copied from above without ticket level check - CompletableFuture> statusFuture = this.getStatusFutureUnchecked(ChunkStatus.FULL); - Either either = (Either) statusFuture.getNow(null); - return either == null ? null : (Chunk) either.left().orElse(null); - } - - public IChunkAccess getAvailableChunkNow() { - // TODO can we just getStatusFuture(EMPTY)? - for (ChunkStatus curr = ChunkStatus.FULL, next = curr.getPreviousStatus(); curr != next; curr = next, next = next.getPreviousStatus()) { - CompletableFuture> future = this.getStatusFutureUnchecked(curr); - Either either = future.getNow(null); - if (either == null || !either.left().isPresent()) { - continue; - } - return either.left().get(); - } - return null; - } - // Paper end - - public CompletableFuture> getStatusFutureUnchecked(ChunkStatus chunkstatus) { - CompletableFuture> completablefuture = (CompletableFuture) this.statusFutures.get(chunkstatus.c()); - - return completablefuture == null ? PlayerChunk.UNLOADED_CHUNK_ACCESS_FUTURE : completablefuture; - } - - public CompletableFuture> b(ChunkStatus chunkstatus) { - return getChunkStatus(this.ticketLevel).b(chunkstatus) ? this.getStatusFutureUnchecked(chunkstatus) : PlayerChunk.UNLOADED_CHUNK_ACCESS_FUTURE; - } - - public CompletableFuture> a() { - return this.tickingFuture; - } - - public CompletableFuture> b() { - return this.entityTickingFuture; - } - - public CompletableFuture> c() { - return this.fullChunkFuture; - } - - @Nullable - public Chunk getChunk() { - CompletableFuture> completablefuture = this.a(); - Either either = (Either) completablefuture.getNow(null); // CraftBukkit - decompile error - - return either == null ? null : (Chunk) either.left().orElse(null); // CraftBukkit - decompile error - } - - @Nullable - public IChunkAccess f() { - for (int i = PlayerChunk.CHUNK_STATUSES.size() - 1; i >= 0; --i) { - ChunkStatus chunkstatus = (ChunkStatus) PlayerChunk.CHUNK_STATUSES.get(i); - CompletableFuture> completablefuture = this.getStatusFutureUnchecked(chunkstatus); - - if (!completablefuture.isCompletedExceptionally()) { - Optional optional = ((Either) completablefuture.getNow(PlayerChunk.UNLOADED_CHUNK_ACCESS)).left(); - - if (optional.isPresent()) { - return (IChunkAccess) optional.get(); - } - } - } - - return null; - } - - public CompletableFuture getChunkSave() { - return this.chunkSave; - } - - public void a(int i, int j, int k) { - Chunk chunk = this.getChunk(); - - if (chunk != null) { - this.r |= 1 << (j >> 4); - if (this.dirtyCount < 64) { - short short0 = (short) (i << 12 | k << 8 | j); - - for (int l = 0; l < this.dirtyCount; ++l) { - if (this.dirtyBlocks[l] == short0) { - return; - } - } - - this.dirtyBlocks[this.dirtyCount++] = short0; - } - - } - } - - public void a(EnumSkyBlock enumskyblock, int i) { - Chunk chunk = this.getChunk(); - - if (chunk != null) { - chunk.setNeedsSaving(true); - if (enumskyblock == EnumSkyBlock.SKY) { - this.u |= 1 << i - -1; - } else { - this.t |= 1 << i - -1; - } - - } - } - - public void a(Chunk chunk) { - if (this.dirtyCount != 0 || this.u != 0 || this.t != 0) { - World world = chunk.getWorld(); - - if (this.dirtyCount == 64) { - // Paper start - Anti-Xray - Load nearby chunks if necessary - if (!chunk.world.chunkPacketBlockController.onChunkPacketCreate(chunk, '\uffff', false)) { - return; - } - // Paper end - this.s = -1; - } - - int i; - int j; - - if (this.u != 0 || this.t != 0) { - this.a(new PacketPlayOutLightUpdate(chunk.getPos(), this.lightEngine, this.u & ~this.s, this.t & ~this.s), true); - i = this.u & this.s; - j = this.t & this.s; - if (i != 0 || j != 0) { - this.a(new PacketPlayOutLightUpdate(chunk.getPos(), this.lightEngine, i, j), false); - } - - this.u = 0; - this.t = 0; - this.s &= ~(this.u & this.t); - } - - int k; - - if (this.dirtyCount == 1) { - i = (this.dirtyBlocks[0] >> 12 & 15) + this.location.x * 16; - j = this.dirtyBlocks[0] & 255; - k = (this.dirtyBlocks[0] >> 8 & 15) + this.location.z * 16; - BlockPosition blockposition = new BlockPosition(i, j, k); - - this.a(new PacketPlayOutBlockChange(world, blockposition), false); - if (world.getType(blockposition).getBlock().isTileEntity()) { - this.a(world, blockposition); - } - } else if (this.dirtyCount == 64) { - this.a(new PacketPlayOutMapChunk(chunk, this.r, true), false); // Paper - Anti-Xray - } else if (this.dirtyCount != 0) { - this.a(new PacketPlayOutMultiBlockChange(this.dirtyCount, this.dirtyBlocks, chunk), false); - - for (i = 0; i < this.dirtyCount; ++i) { - j = (this.dirtyBlocks[i] >> 12 & 15) + this.location.x * 16; - k = this.dirtyBlocks[i] & 255; - int l = (this.dirtyBlocks[i] >> 8 & 15) + this.location.z * 16; - BlockPosition blockposition1 = new BlockPosition(j, k, l); - - if (world.getType(blockposition1).getBlock().isTileEntity()) { - this.a(world, blockposition1); - } - } - } - - this.dirtyCount = 0; - this.r = 0; - } - } - - private void a(World world, BlockPosition blockposition) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity != null) { - PacketPlayOutTileEntityData packetplayouttileentitydata = tileentity.getUpdatePacket(); - - if (packetplayouttileentitydata != null) { - this.a(packetplayouttileentitydata, false); - } - } - - } - - private void a(Packet packet, boolean flag) { - this.players.a(this.location, flag).forEach((entityplayer) -> { - entityplayer.playerConnection.sendPacket(packet); - }); - } - - public CompletableFuture> a(ChunkStatus chunkstatus, PlayerChunkMap playerchunkmap) { - int i = chunkstatus.c(); - CompletableFuture> completablefuture = (CompletableFuture) this.statusFutures.get(i); - - if (completablefuture != null) { - Either either = (Either) completablefuture.getNow(null); // CraftBukkit - decompile error - - if (either == null || either.left().isPresent()) { - return completablefuture; - } - } - - if (getChunkStatus(this.ticketLevel).b(chunkstatus)) { - CompletableFuture> completablefuture1 = playerchunkmap.a(this, chunkstatus); - - this.a(completablefuture1); - this.statusFutures.set(i, completablefuture1); - return completablefuture1; - } else { - return completablefuture == null ? PlayerChunk.UNLOADED_CHUNK_ACCESS_FUTURE : completablefuture; - } - } - - private void a(CompletableFuture> completablefuture) { - this.chunkSave = this.chunkSave.thenCombine(completablefuture, (ichunkaccess, either) -> { - return (IChunkAccess) either.map((ichunkaccess1) -> { - return ichunkaccess1; - }, (playerchunk_failure) -> { - return ichunkaccess; - }); - }); - } - - public ChunkCoordIntPair i() { - return this.location; - } - - public int getTicketLevel() { - return this.ticketLevel; - } - - public int k() { - return this.n; - } - - private void d(int i) { - this.n = i; - } - - public void a(int i) { - this.ticketLevel = i; - } - - protected void a(PlayerChunkMap playerchunkmap) { - ChunkStatus chunkstatus = getChunkStatus(this.oldTicketLevel); - ChunkStatus chunkstatus1 = getChunkStatus(this.ticketLevel); - boolean flag = this.oldTicketLevel <= PlayerChunkMap.GOLDEN_TICKET; - boolean flag1 = this.ticketLevel <= PlayerChunkMap.GOLDEN_TICKET; // Paper - diff on change: (flag1 = new ticket level is in loadable range) - PlayerChunk.State playerchunk_state = getChunkState(this.oldTicketLevel); - PlayerChunk.State playerchunk_state1 = getChunkState(this.ticketLevel); - // CraftBukkit start - // ChunkUnloadEvent: Called before the chunk is unloaded: isChunkLoaded is still true and chunk can still be modified by plugins. - if (playerchunk_state.isAtLeast(PlayerChunk.State.BORDER) && !playerchunk_state1.isAtLeast(PlayerChunk.State.BORDER)) { - this.getStatusFutureUnchecked(ChunkStatus.FULL).thenAcceptAsync((either) -> { - either.ifLeft((chunkAccess) -> { - Chunk chunk = (Chunk) chunkAccess; - // Minecraft will apply the chunks tick lists to the world once the chunk got loaded, and then store the tick - // lists again inside the chunk once the chunk becomes inaccessible and set the chunk's needsSaving flag. - // These actions may however happen deferred, so we manually set the needsSaving flag already here. - chunk.setNeedsSaving(true); - chunk.unloadCallback(); - }); - }, playerchunkmap.callbackExecutor); - - // Run callback right away if the future was already done - playerchunkmap.callbackExecutor.run(); - } - // CraftBukkit end - CompletableFuture completablefuture; - - if (flag) { - Either either = Either.right(new PlayerChunk.Failure() { - public String toString() { - return "Unloaded ticket level " + PlayerChunk.this.location.toString(); - } - }); - - // Paper start - if (!flag1) { - playerchunkmap.world.asyncChunkTaskManager.cancelChunkLoad(this.location.x, this.location.z); - } - // Paper end - - for (int i = flag1 ? chunkstatus1.c() + 1 : 0; i <= chunkstatus.c(); ++i) { - completablefuture = (CompletableFuture) this.statusFutures.get(i); - if (completablefuture != null) { - completablefuture.complete(either); - } else { - this.statusFutures.set(i, CompletableFuture.completedFuture(either)); - } - } - } - - boolean flag2 = playerchunk_state.isAtLeast(PlayerChunk.State.BORDER); - boolean flag3 = playerchunk_state1.isAtLeast(PlayerChunk.State.BORDER); - - this.hasBeenLoaded |= flag3; - if (!flag2 && flag3) { - this.fullChunkFuture = playerchunkmap.b(this); - this.a(this.fullChunkFuture); - } - - if (flag2 && !flag3) { - completablefuture = this.fullChunkFuture; - this.fullChunkFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE; - this.a(((CompletableFuture>) completablefuture).thenApply((either1) -> { // CraftBukkit - decompile error - playerchunkmap.getClass(); - return either1.ifLeft(playerchunkmap::a); - })); - } - - boolean flag4 = playerchunk_state.isAtLeast(PlayerChunk.State.TICKING); - boolean flag5 = playerchunk_state1.isAtLeast(PlayerChunk.State.TICKING); - - if (!flag4 && flag5) { - this.tickingFuture = playerchunkmap.a(this); - this.a(this.tickingFuture); - } - - if (flag4 && !flag5) { - this.tickingFuture.complete(PlayerChunk.UNLOADED_CHUNK); - this.tickingFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE; - } - - boolean flag6 = playerchunk_state.isAtLeast(PlayerChunk.State.ENTITY_TICKING); - boolean flag7 = playerchunk_state1.isAtLeast(PlayerChunk.State.ENTITY_TICKING); - - if (!flag6 && flag7) { - if (this.entityTickingFuture != PlayerChunk.UNLOADED_CHUNK_FUTURE) { - throw new IllegalStateException(); - } - - this.entityTickingFuture = playerchunkmap.b(this.location); - this.a(this.entityTickingFuture); - } - - if (flag6 && !flag7) { - this.entityTickingFuture.complete(PlayerChunk.UNLOADED_CHUNK); - this.entityTickingFuture = PlayerChunk.UNLOADED_CHUNK_FUTURE; - } - - this.w.a(this.location, this::k, this.ticketLevel, this::d); - this.oldTicketLevel = this.ticketLevel; - // CraftBukkit start - // ChunkLoadEvent: Called after the chunk is loaded: isChunkLoaded returns true and chunk is ready to be modified by plugins. - if (!playerchunk_state.isAtLeast(PlayerChunk.State.BORDER) && playerchunk_state1.isAtLeast(PlayerChunk.State.BORDER)) { - this.getStatusFutureUnchecked(ChunkStatus.FULL).thenAcceptAsync((either) -> { - either.ifLeft((chunkAccess) -> { - Chunk chunk = (Chunk) chunkAccess; - chunk.loadCallback(); - }); - }, playerchunkmap.callbackExecutor); - - // Run callback right away if the future was already done - playerchunkmap.callbackExecutor.run(); - } - // CraftBukkit end - } - - public static ChunkStatus getChunkStatus(int i) { - return i < 33 ? ChunkStatus.FULL : ChunkStatus.a(i - 33); - } - - public static PlayerChunk.State getChunkState(int i) { - return PlayerChunk.CHUNK_STATES[MathHelper.clamp(33 - i + 1, 0, PlayerChunk.CHUNK_STATES.length - 1)]; - } - - public boolean hasBeenLoaded() { - return this.hasBeenLoaded; - } - - public void m() { - this.hasBeenLoaded = getChunkState(this.ticketLevel).isAtLeast(PlayerChunk.State.BORDER); - } - - public void a(ProtoChunkExtension protochunkextension) { - for (int i = 0; i < this.statusFutures.length(); ++i) { - CompletableFuture> completablefuture = (CompletableFuture) this.statusFutures.get(i); - - if (completablefuture != null) { - Optional optional = ((Either) completablefuture.getNow(PlayerChunk.UNLOADED_CHUNK_ACCESS)).left(); - - if (optional.isPresent() && optional.get() instanceof ProtoChunk) { - this.statusFutures.set(i, CompletableFuture.completedFuture(Either.left(protochunkextension))); - } - } - } - - this.a(CompletableFuture.completedFuture(Either.left(protochunkextension.u()))); - } - - public interface d { - - Stream a(ChunkCoordIntPair chunkcoordintpair, boolean flag); - } - - public interface c { - - void a(ChunkCoordIntPair chunkcoordintpair, IntSupplier intsupplier, int i, IntConsumer intconsumer); - } - - public interface Failure { - - PlayerChunk.Failure b = new PlayerChunk.Failure() { - public String toString() { - return "UNLOADED"; - } - }; - } - - public static enum State { - - INACCESSIBLE, BORDER, TICKING, ENTITY_TICKING; - - private State() {} - - public boolean isAtLeast(PlayerChunk.State playerchunk_state) { - return this.ordinal() >= playerchunk_state.ordinal(); - } - } -} diff --git a/src/main/java/net/minecraft/server/PlayerChunkMap.java b/src/main/java/net/minecraft/server/PlayerChunkMap.java deleted file mode 100644 index 59e74900f..000000000 --- a/src/main/java/net/minecraft/server/PlayerChunkMap.java +++ /dev/null @@ -1,1690 +0,0 @@ -package net.minecraft.server; - -import co.aikar.timings.Timing; // Paper -import com.destroystokyo.paper.PaperWorldConfig; // Paper -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.ComparisonChain; // Paper -import com.google.common.collect.Lists; -import com.google.common.collect.Queues; -import com.google.common.collect.Sets; -import com.mojang.datafixers.DataFixer; -import com.mojang.datafixers.util.Either; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.longs.LongIterator; -import it.unimi.dsi.fastutil.longs.LongOpenHashSet; -import it.unimi.dsi.fastutil.longs.LongSet; -import it.unimi.dsi.fastutil.longs.Long2ObjectMap.Entry; -import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.HashMap; // Paper -import java.util.Iterator; -import java.util.List; -import java.util.Map; // Paper -import java.util.Objects; -import java.util.Optional; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.CancellationException; -import java.util.UUID; // Paper -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.BooleanSupplier; -import java.util.function.Consumer; -import java.util.function.IntFunction; -import java.util.function.IntSupplier; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.apache.commons.lang3.mutable.MutableBoolean; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.bukkit.entity.Player; // CraftBukkit - -public class PlayerChunkMap extends IChunkLoader implements PlayerChunk.d { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final int GOLDEN_TICKET = 33 + ChunkStatus.b(); - public final Long2ObjectLinkedOpenHashMap updatingChunks = new Long2ObjectLinkedOpenHashMap(); - public volatile Long2ObjectLinkedOpenHashMap visibleChunks; - private final Long2ObjectLinkedOpenHashMap pendingUnload; - final LongSet loadedChunks; // Paper - private -> package - public final WorldServer world; - private final LightEngineThreaded lightEngine; - private final IAsyncTaskHandler executor; - public final ChunkGenerator chunkGenerator; - private final Supplier m; public final Supplier getWorldPersistentDataSupplier() { return this.m; } // Paper - OBFHELPER - private final VillagePlace n; - public final LongSet unloadQueue; - private boolean updatingChunksModified; - private final ChunkTaskQueueSorter q; - private final Mailbox> mailboxWorldGen; - private final Mailbox> mailboxMain; - public final WorldLoadListener worldLoadListener; - public final PlayerChunkMap.a chunkDistanceManager; public final PlayerChunkMap.a getChunkMapDistanceManager() { return this.chunkDistanceManager; } // Paper - OBFHELPER - private final AtomicInteger v; - public final DefinedStructureManager definedStructureManager; // Paper - private -> public - private final File x; - private final PlayerMap playerMap; - public final Int2ObjectMap trackedEntities; - private final Queue A; - int viewDistance; // Paper - private -> package private - public final com.destroystokyo.paper.util.PlayerMobDistanceMap playerMobDistanceMap; // Paper - - // CraftBukkit start - recursion-safe executor for Chunk loadCallback() and unloadCallback() - public final CallbackExecutor callbackExecutor = new CallbackExecutor(); - public static final class CallbackExecutor implements java.util.concurrent.Executor, Runnable { - - private Runnable queued; - - @Override - public void execute(Runnable runnable) { - if (queued != null) { - throw new IllegalStateException("Already queued"); - } - queued = runnable; - } - - @Override - public void run() { - Runnable task = queued; - queued = null; - if (task != null) { - task.run(); - } - } - }; - // CraftBukkit end - - public PlayerChunkMap(WorldServer worldserver, File file, DataFixer datafixer, DefinedStructureManager definedstructuremanager, Executor executor, IAsyncTaskHandler iasynctaskhandler, ILightAccess ilightaccess, ChunkGenerator chunkgenerator, WorldLoadListener worldloadlistener, Supplier supplier, int i) { - super(new File(worldserver.getWorldProvider().getDimensionManager().a(file), "region"), datafixer); - this.visibleChunks = this.updatingChunks.clone(); - this.pendingUnload = new Long2ObjectLinkedOpenHashMap(); - this.loadedChunks = new LongOpenHashSet(); - this.unloadQueue = new LongOpenHashSet(); - this.v = new AtomicInteger(); - this.playerMap = new PlayerMap(); - this.trackedEntities = new Int2ObjectOpenHashMap(); - this.A = new com.destroystokyo.paper.utils.CachedSizeConcurrentLinkedQueue<>(); // Paper - this.definedStructureManager = definedstructuremanager; - this.x = worldserver.getWorldProvider().getDimensionManager().a(file); - this.world = worldserver; - this.chunkGenerator = chunkgenerator; - this.executor = iasynctaskhandler; - ThreadedMailbox threadedmailbox = ThreadedMailbox.a(executor, "worldgen"); - - iasynctaskhandler.getClass(); - Mailbox mailbox = Mailbox.a("main", iasynctaskhandler::a); - - this.worldLoadListener = worldloadlistener; - ThreadedMailbox threadedmailbox1 = ThreadedMailbox.a(executor, "light"); - - this.q = new ChunkTaskQueueSorter(ImmutableList.of(threadedmailbox, mailbox, threadedmailbox1), executor, Integer.MAX_VALUE); - this.mailboxWorldGen = this.q.a(threadedmailbox, false); - this.mailboxMain = this.q.a(mailbox, false); - this.lightEngine = new LightEngineThreaded(ilightaccess, this, this.world.getWorldProvider().g(), threadedmailbox1, this.q.a(threadedmailbox1, false)); - this.chunkDistanceManager = new PlayerChunkMap.a(executor, iasynctaskhandler); - this.m = supplier; - this.n = new VillagePlace(new File(this.x, "poi"), datafixer, this.world); // Paper - this.setViewDistance(i); - this.playerMobDistanceMap = this.world.paperConfig.perPlayerMobSpawns ? new com.destroystokyo.paper.util.PlayerMobDistanceMap() : null; // Paper - } - - public void updatePlayerMobTypeMap(Entity entity) { - if (!this.world.paperConfig.perPlayerMobSpawns) { - return; - } - int chunkX = (int)Math.floor(entity.locX) >> 4; - int chunkZ = (int)Math.floor(entity.locZ) >> 4; - int index = entity.getEntityType().getEnumCreatureType().ordinal(); - - for (EntityPlayer player : this.playerMobDistanceMap.getPlayersInRange(chunkX, chunkZ)) { - ++player.mobCounts[index]; - } - } - - public int getMobCountNear(EntityPlayer entityPlayer, EnumCreatureType enumCreatureType) { - return entityPlayer.mobCounts[enumCreatureType.ordinal()]; - } - - private static double a(ChunkCoordIntPair chunkcoordintpair, Entity entity) { - double d0 = (double) (chunkcoordintpair.x * 16 + 8); - double d1 = (double) (chunkcoordintpair.z * 16 + 8); - double d2 = d0 - entity.locX; - double d3 = d1 - entity.locZ; - - return d2 * d2 + d3 * d3; - } - - private static int b(ChunkCoordIntPair chunkcoordintpair, EntityPlayer entityplayer, boolean flag) { - int i; - int j; - - if (flag) { - SectionPosition sectionposition = entityplayer.M(); - - i = sectionposition.a(); - j = sectionposition.c(); - } else { - i = MathHelper.floor(entityplayer.locX / 16.0D); - j = MathHelper.floor(entityplayer.locZ / 16.0D); - } - - return a(chunkcoordintpair, i, j); - } - - private static int a(ChunkCoordIntPair chunkcoordintpair, int i, int j) { - int k = chunkcoordintpair.x - i; - int l = chunkcoordintpair.z - j; - - return Math.max(Math.abs(k), Math.abs(l)); - } - - protected LightEngineThreaded a() { - return this.lightEngine; - } - - @Nullable - protected PlayerChunk getUpdatingChunk(long i) { - return (PlayerChunk) this.updatingChunks.get(i); - } - - @Nullable - public PlayerChunk getVisibleChunk(long i) { // Paper - protected -> public - return (PlayerChunk) this.visibleChunks.get(i); - } - - protected IntSupplier c(long i) { - return () -> { - PlayerChunk playerchunk = this.getVisibleChunk(i); - - return playerchunk == null ? ChunkTaskQueue.a - 1 : Math.min(playerchunk.k(), ChunkTaskQueue.a - 1); - }; - } - - private CompletableFuture, PlayerChunk.Failure>> a(ChunkCoordIntPair chunkcoordintpair, int i, IntFunction intfunction) { - List>> list = Lists.newArrayList(); - int j = chunkcoordintpair.x; - int k = chunkcoordintpair.z; - - for (int l = -i; l <= i; ++l) { - for (int i1 = -i; i1 <= i; ++i1) { - int j1 = Math.max(Math.abs(i1), Math.abs(l)); - final ChunkCoordIntPair chunkcoordintpair1 = new ChunkCoordIntPair(j + i1, k + l); - long k1 = chunkcoordintpair1.pair(); - PlayerChunk playerchunk = this.getUpdatingChunk(k1); - - if (playerchunk == null) { - return CompletableFuture.completedFuture(Either.right(new PlayerChunk.Failure() { - public String toString() { - return "Unloaded " + chunkcoordintpair1.toString(); - } - })); - } - - ChunkStatus chunkstatus = (ChunkStatus) intfunction.apply(j1); - CompletableFuture> completablefuture = playerchunk.a(chunkstatus, this); - - list.add(completablefuture); - } - } - - CompletableFuture>> completablefuture1 = SystemUtils.b(list); - - return completablefuture1.thenApply((list1) -> { - List list2 = Lists.newArrayList(); - // CraftBukkit start - decompile error - int cnt = 0; - - for (Iterator iterator = list1.iterator(); iterator.hasNext(); ++cnt) { - final int l1 = cnt; - // CraftBukkit end - final Either either = (Either) iterator.next(); - Optional optional = either.left(); - - if (!optional.isPresent()) { - return Either.right(new PlayerChunk.Failure() { - public String toString() { - return "Unloaded " + new ChunkCoordIntPair(j + l1 % (i * 2 + 1), k + l1 / (i * 2 + 1)) + " " + ((PlayerChunk.Failure) either.right().get()).toString(); - } - }); - } - - list2.add(optional.get()); - } - - return Either.left(list2); - }); - } - - public CompletableFuture> b(ChunkCoordIntPair chunkcoordintpair) { - return this.a(chunkcoordintpair, 2, (i) -> { - return ChunkStatus.FULL; - }).thenApplyAsync((either) -> { - return either.mapLeft((list) -> { - return (Chunk) list.get(list.size() / 2); - }); - }, this.executor); - } - - @Nullable - private PlayerChunk a(long i, int j, @Nullable PlayerChunk playerchunk, int k) { - if (k > PlayerChunkMap.GOLDEN_TICKET && j > PlayerChunkMap.GOLDEN_TICKET) { - return playerchunk; - } else { - if (playerchunk != null) { - playerchunk.a(j); - } - - if (playerchunk != null) { - if (j > PlayerChunkMap.GOLDEN_TICKET) { - this.unloadQueue.add(i); - } else { - this.unloadQueue.remove(i); - } - } - - if (j <= PlayerChunkMap.GOLDEN_TICKET && playerchunk == null) { - playerchunk = (PlayerChunk) this.pendingUnload.remove(i); - if (playerchunk != null) { - playerchunk.a(j); - } else { - playerchunk = new PlayerChunk(new ChunkCoordIntPair(i), j, this.lightEngine, this.q, this); - } - - this.updatingChunks.put(i, playerchunk); - this.updatingChunksModified = true; - } - - return playerchunk; - } - } - - @Override - public void close() throws IOException { - this.q.close(); - this.world.asyncChunkTaskManager.close(true); // Paper - Required since we're closing regionfiles in the next line - this.n.close(); - super.close(); - } - - // Paper start - derived from below - protected void saveIncrementally() { - int savedThisTick = 0; - for (PlayerChunk playerchunk : visibleChunks.values()) { - if (playerchunk.hasBeenLoaded()) { - - IChunkAccess ichunkaccess = (IChunkAccess) playerchunk.getChunkSave().getNow(null); // CraftBukkit - decompile error - - - if (ichunkaccess instanceof ProtoChunkExtension || ichunkaccess instanceof Chunk) { - boolean shouldSave = true; - - if (ichunkaccess instanceof Chunk) { - shouldSave = ((Chunk) ichunkaccess).lastSaved + world.paperConfig.autoSavePeriod <= world.getTime(); - } - - if (shouldSave && this.saveChunk(ichunkaccess, true)) { // Paper - async chunk io - ++savedThisTick; - playerchunk.m(); - } - } - - if (savedThisTick >= world.paperConfig.maxAutoSaveChunksPerTick) { - return; - } - } - } - } - // paper end - - protected void save(boolean flag) { - if (flag) { - List list = (List) this.visibleChunks.values().stream().filter(PlayerChunk::hasBeenLoaded).peek(PlayerChunk::m).collect(Collectors.toList()); - MutableBoolean mutableboolean = new MutableBoolean(); - - do { - mutableboolean.setFalse(); - list.stream().map((playerchunk) -> { - CompletableFuture completablefuture; - - do { - completablefuture = playerchunk.getChunkSave(); - this.executor.awaitTasks(completablefuture::isDone); - } while (completablefuture != playerchunk.getChunkSave()); - - return (IChunkAccess) completablefuture.join(); - }).filter((ichunkaccess) -> { - return ichunkaccess instanceof ProtoChunkExtension || ichunkaccess instanceof Chunk; - }).filter((chunk) -> this.saveChunk(chunk, true)).forEach((ichunkaccess) -> { // Paper - async io for chunk save - mutableboolean.setTrue(); - }); - } while (mutableboolean.isTrue()); - - this.b(() -> { - return true; - }); - this.world.asyncChunkTaskManager.flush(); // Paper - flush to preserve behavior compat with pre-async behaviour - PlayerChunkMap.LOGGER.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", this.x.getName()); - } else { - this.visibleChunks.values().stream().filter(PlayerChunk::hasBeenLoaded).forEach((playerchunk) -> { - IChunkAccess ichunkaccess = (IChunkAccess) playerchunk.getChunkSave().getNow(null); // CraftBukkit - decompile error - - if (ichunkaccess instanceof ProtoChunkExtension || ichunkaccess instanceof Chunk) { - this.saveChunk(ichunkaccess, true); // Paper - playerchunk.m(); - } - - }); - com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.flush(); // Paper - flush to preserve behavior compat with pre-async behaviour - } - - } - - private static final double UNLOAD_QUEUE_RESIZE_FACTOR = 0.96; // Spigot - - protected void unloadChunks(BooleanSupplier booleansupplier) { - GameProfilerFiller gameprofilerfiller = this.world.getMethodProfiler(); - - try (Timing ignored = this.world.timings.poiUnload.startTiming()) { // Paper - gameprofilerfiller.enter("poi"); - this.n.a(booleansupplier); - } // Paper - gameprofilerfiller.exitEnter("chunk_unload"); - if (!this.world.isSavingDisabled()) { - try (Timing ignored = this.world.timings.chunkUnload.startTiming()) { // Paper - this.b(booleansupplier); - }// Paper - } - - gameprofilerfiller.exit(); - } - - private void b(BooleanSupplier booleansupplier) { - LongIterator longiterator = this.unloadQueue.iterator(); - // Spigot start - org.spigotmc.SlackActivityAccountant activityAccountant = this.world.getMinecraftServer().slackActivityAccountant; - activityAccountant.startActivity(0.5); - int targetSize = Math.min(this.unloadQueue.size() - 100, (int) (this.unloadQueue.size() * UNLOAD_QUEUE_RESIZE_FACTOR)); // Paper - Make more aggressive - // Spigot end - while (longiterator.hasNext()) { // Spigot - long j = longiterator.nextLong(); - longiterator.remove(); // Spigot - PlayerChunk playerchunk = (PlayerChunk) this.updatingChunks.remove(j); - - if (playerchunk != null) { - this.pendingUnload.put(j, playerchunk); - this.updatingChunksModified = true; - // Spigot start - if (!booleansupplier.getAsBoolean() && this.unloadQueue.size() <= targetSize && activityAccountant.activityTimeIsExhausted()) { - break; - } - // Spigot end - this.a(j, playerchunk); - } - } - activityAccountant.endActivity(); // Spigot - - Runnable runnable; - - int queueTarget = Math.min(this.A.size() - 100, (int) (this.A.size() * UNLOAD_QUEUE_RESIZE_FACTOR)); // Paper - Target this queue as well - - while ((booleansupplier.getAsBoolean() || this.A.size() > queueTarget) && (runnable = (Runnable) this.A.poll()) != null) { // Paper - Target this queue as well - runnable.run(); - } - - } - - // Paper start - async chunk save for unload - // Note: This is very unsafe to call if the chunk is still in use. - // This is also modeled after PlayerChunkMap#saveChunk(IChunkAccess, boolean), with the intentional difference being - // serializing the chunk is left to a worker thread. - private void asyncSave(IChunkAccess chunk) { - ChunkCoordIntPair chunkPos = chunk.getPos(); - NBTTagCompound poiData; - try (Timing ignored = this.world.timings.chunkUnloadPOISerialization.startTiming()) { - poiData = this.getVillagePlace().getData(chunk.getPos()); - } - - com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.scheduleSave(this.world, chunkPos.x, chunkPos.z, - poiData, null, com.destroystokyo.paper.io.PrioritizedTaskQueue.LOW_PRIORITY); - - if (!chunk.isNeedsSaving()) { - return; - } - - ChunkStatus chunkstatus = chunk.getChunkStatus(); - - // Copied from PlayerChunkMap#saveChunk(IChunkAccess, boolean) - if (chunkstatus.getType() != ChunkStatus.Type.LEVELCHUNK) { - try (co.aikar.timings.Timing ignored1 = this.world.timings.chunkSaveOverwriteCheck.startTiming()) { // Paper - // Paper start - Optimize save by using status cache - try { - ChunkStatus statusOnDisk = this.getChunkStatusOnDisk(chunkPos); - if (statusOnDisk != null && statusOnDisk.getType() == ChunkStatus.Type.LEVELCHUNK) { - // Paper end - return; - } - - if (chunkstatus == ChunkStatus.EMPTY && chunk.h().values().stream().noneMatch(StructureStart::e)) { - return; - } - } catch (IOException ex) { - ex.printStackTrace(); - return; - } - } - } - - ChunkRegionLoader.AsyncSaveData asyncSaveData; - try (Timing ignored = this.world.timings.chunkUnloadPrepareSave.startTiming()) { - asyncSaveData = ChunkRegionLoader.getAsyncSaveData(this.world, chunk); - } - - this.world.asyncChunkTaskManager.scheduleChunkSave(chunkPos.x, chunkPos.z, com.destroystokyo.paper.io.PrioritizedTaskQueue.LOW_PRIORITY, - asyncSaveData, chunk); - - chunk.setLastSaved(this.world.getTime()); - chunk.setNeedsSaving(false); - } - // Paper end - - private void a(long i, PlayerChunk playerchunk) { - CompletableFuture completablefuture = playerchunk.getChunkSave(); - Consumer consumer = (ichunkaccess) -> { // CraftBukkit - decompile error - CompletableFuture completablefuture1 = playerchunk.getChunkSave(); - - if (completablefuture1 != completablefuture) { - this.a(i, playerchunk); - } else { - if (this.pendingUnload.remove(i, playerchunk) && ichunkaccess != null) { - if (ichunkaccess instanceof Chunk) { - ((Chunk) ichunkaccess).setLoaded(false); - } - - //this.saveChunk(ichunkaccess);// Paper - delay - if (this.loadedChunks.remove(i) && ichunkaccess instanceof Chunk) { - Chunk chunk = (Chunk) ichunkaccess; - - this.world.unloadChunk(chunk); - } - - try { - this.asyncSave(ichunkaccess); // Paper - async chunk saving - } catch (Throwable ex) { - LOGGER.fatal("Failed to prepare async save, attempting synchronous save", ex); - this.saveChunk(ichunkaccess, true); - } - - this.lightEngine.a(ichunkaccess.getPos()); - this.lightEngine.queueUpdate(); - this.worldLoadListener.a(ichunkaccess.getPos(), (ChunkStatus) null); - } - - } - }; - Queue queue = this.A; - - this.A.getClass(); - completablefuture.thenAcceptAsync(consumer, queue::add).whenComplete((ovoid, throwable) -> { - if (throwable != null) { - PlayerChunkMap.LOGGER.error("Failed to save chunk " + playerchunk.i(), throwable); - } - - }); - } - - protected boolean b() { - if (!this.updatingChunksModified) { - return false; - } else { - this.visibleChunks = this.updatingChunks.clone(); - this.updatingChunksModified = false; - return true; - } - } - - public CompletableFuture> a(PlayerChunk playerchunk, ChunkStatus chunkstatus) { - ChunkCoordIntPair chunkcoordintpair = playerchunk.i(); - - if (chunkstatus == ChunkStatus.EMPTY) { - return this.f(chunkcoordintpair); - } else { - CompletableFuture> completablefuture = playerchunk.a(chunkstatus.e(), this); - - return completablefuture.thenComposeAsync((either) -> { - Optional optional = either.left(); - - if (!optional.isPresent()) { - return CompletableFuture.completedFuture(either); - } else { - if (chunkstatus == ChunkStatus.LIGHT) { - this.chunkDistanceManager.a(TicketType.LIGHT, chunkcoordintpair, 33 + ChunkStatus.a(ChunkStatus.FEATURES), chunkcoordintpair); - } - - IChunkAccess ichunkaccess = (IChunkAccess) optional.get(); - - if (ichunkaccess.getChunkStatus().b(chunkstatus)) { - CompletableFuture completablefuture1; - - if (chunkstatus == ChunkStatus.LIGHT) { - completablefuture1 = this.b(playerchunk, chunkstatus); - } else { - completablefuture1 = chunkstatus.a(this.world, this.definedStructureManager, this.lightEngine, (ichunkaccess1) -> { - return this.c(playerchunk); - }, ichunkaccess); - } - - this.worldLoadListener.a(chunkcoordintpair, chunkstatus); - return completablefuture1; - } else { - return this.b(playerchunk, chunkstatus); - } - } - }, this.executor); - } - } - - // Paper start - Async chunk io - public NBTTagCompound completeChunkData(NBTTagCompound compound, ChunkCoordIntPair chunkcoordintpair) throws IOException { - return compound == null ? null : this.getChunkData(this.world.getWorldProvider().getDimensionManager(), this.getWorldPersistentDataSupplier(), compound, chunkcoordintpair, this.world); - } - // Paper end - - private CompletableFuture> f(ChunkCoordIntPair chunkcoordintpair) { - // Paper start - Async chunk io - final java.util.function.BiFunction> syncLoadComplete = (chunkHolder, ioThrowable) -> { - try (Timing ignored = this.world.timings.syncChunkLoadTimer.startTimingIfSync()) { // Paper - if (ioThrowable != null) { - com.destroystokyo.paper.io.IOUtil.rethrow(ioThrowable); - } - this.getVillagePlace().loadInData(chunkcoordintpair, chunkHolder.poiData); - chunkHolder.tasks.forEach(Runnable::run); - // Paper - async load completes this - // Paper end - - // Paper start - This is done async - if (chunkHolder.protoChunk != null) { - chunkHolder.protoChunk.setLastSaved(this.world.getTime()); - return Either.left(chunkHolder.protoChunk); - } - // Paper end - } catch (ReportedException reportedexception) { - Throwable throwable = reportedexception.getCause(); - - if (!(throwable instanceof IOException)) { - throw reportedexception; - } - - PlayerChunkMap.LOGGER.error("Couldn't load chunk {}", chunkcoordintpair, throwable); - } catch (Exception exception) { - PlayerChunkMap.LOGGER.error("Couldn't load chunk {}", chunkcoordintpair, exception); - } - - return Either.left(new ProtoChunk(chunkcoordintpair, ChunkConverter.a, this.world)); // Paper - Anti-Xray - // Paper start - Async chunk io - }; - CompletableFuture> ret = new CompletableFuture<>(); - - Consumer chunkHolderConsumer = (ChunkRegionLoader.InProgressChunkHolder holder) -> { - PlayerChunkMap.this.executor.addTask(() -> { - ret.complete(syncLoadComplete.apply(holder, null)); - }); - }; - - CompletableFuture chunkSaveFuture = this.world.asyncChunkTaskManager.getChunkSaveFuture(chunkcoordintpair.x, chunkcoordintpair.z); - if (chunkSaveFuture != null) { - this.world.asyncChunkTaskManager.scheduleChunkLoad(chunkcoordintpair.x, chunkcoordintpair.z, - com.destroystokyo.paper.io.PrioritizedTaskQueue.HIGH_PRIORITY, chunkHolderConsumer, false, chunkSaveFuture); - this.world.asyncChunkTaskManager.raisePriority(chunkcoordintpair.x, chunkcoordintpair.z, com.destroystokyo.paper.io.PrioritizedTaskQueue.HIGH_PRIORITY); - } else { - this.world.asyncChunkTaskManager.scheduleChunkLoad(chunkcoordintpair.x, chunkcoordintpair.z, - com.destroystokyo.paper.io.PrioritizedTaskQueue.NORMAL_PRIORITY, chunkHolderConsumer, false); - } - return ret; - // Paper end - } - - private CompletableFuture> b(PlayerChunk playerchunk, ChunkStatus chunkstatus) { - ChunkCoordIntPair chunkcoordintpair = playerchunk.i(); - CompletableFuture, PlayerChunk.Failure>> completablefuture = this.a(chunkcoordintpair, chunkstatus.f(), (i) -> { - return this.a(chunkstatus, i); - }); - - return completablefuture.thenComposeAsync((either) -> { - return either.map((list) -> { // Paper - Shut up. - try { - CompletableFuture> completablefuture1 = chunkstatus.a(this.world, this.chunkGenerator, this.definedStructureManager, this.lightEngine, (ichunkaccess) -> { - return this.c(playerchunk); - }, list); - - this.worldLoadListener.a(chunkcoordintpair, chunkstatus); - return completablefuture1; - } catch (Exception exception) { - CrashReport crashreport = CrashReport.a(exception, "Exception generating new chunk"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Chunk to be generated"); - - crashreportsystemdetails.a("Location", (Object) String.format("%d,%d", chunkcoordintpair.x, chunkcoordintpair.z)); - crashreportsystemdetails.a("Position hash", (Object) ChunkCoordIntPair.pair(chunkcoordintpair.x, chunkcoordintpair.z)); - crashreportsystemdetails.a("Generator", (Object) this.chunkGenerator); - throw new ReportedException(crashreport); - } - }, (playerchunk_failure) -> { - this.c(chunkcoordintpair); - return CompletableFuture.completedFuture(Either.right(playerchunk_failure)); - }); - }, (runnable) -> { - this.mailboxWorldGen.a(ChunkTaskQueueSorter.a(playerchunk, runnable)); // CraftBukkit - decompile error - }); - } - - protected void c(ChunkCoordIntPair chunkcoordintpair) { - this.executor.a(SystemUtils.a(() -> { - this.chunkDistanceManager.b(TicketType.LIGHT, chunkcoordintpair, 33 + ChunkStatus.a(ChunkStatus.FEATURES), chunkcoordintpair); - }, () -> { - return "release light ticket " + chunkcoordintpair; - })); - } - - private ChunkStatus a(ChunkStatus chunkstatus, int i) { - ChunkStatus chunkstatus1; - - if (i == 0) { - chunkstatus1 = chunkstatus.e(); - } else { - chunkstatus1 = ChunkStatus.a(ChunkStatus.a(chunkstatus) + i); - } - - return chunkstatus1; - } - - private CompletableFuture> c(PlayerChunk playerchunk) { - CompletableFuture> completablefuture = playerchunk.getStatusFutureUnchecked(ChunkStatus.FULL.e()); - - return completablefuture.thenApplyAsync((either) -> { - ChunkStatus chunkstatus = PlayerChunk.getChunkStatus(playerchunk.getTicketLevel()); - - return !chunkstatus.b(ChunkStatus.FULL) ? PlayerChunk.UNLOADED_CHUNK_ACCESS : either.mapLeft((ichunkaccess) -> { - try (Timing ignored = world.timings.chunkIOStage2.startTimingIfSync()) { // Paper - ChunkCoordIntPair chunkcoordintpair = playerchunk.i(); - Chunk chunk; - - if (ichunkaccess instanceof ProtoChunkExtension) { - chunk = ((ProtoChunkExtension) ichunkaccess).u(); - } else { - chunk = new Chunk(this.world, (ProtoChunk) ichunkaccess); - playerchunk.a(new ProtoChunkExtension(chunk)); - } - - chunk.a(() -> { - return PlayerChunk.getChunkState(playerchunk.getTicketLevel()); - }); - chunk.addEntities(); - if (this.loadedChunks.add(chunkcoordintpair.pair())) { - chunk.setLoaded(true); - this.world.a(chunk.getTileEntities().values()); - List list = null; - List[] aentityslice = chunk.getEntitySlices(); // Spigot - int i = aentityslice.length; - - for (int j = 0; j < i; ++j) { - List entityslice = aentityslice[j]; // Spigot - - // Paper start - PaperWorldConfig.DuplicateUUIDMode mode = world.paperConfig.duplicateUUIDMode; - if (mode == PaperWorldConfig.DuplicateUUIDMode.WARN || mode == PaperWorldConfig.DuplicateUUIDMode.DELETE || mode == PaperWorldConfig.DuplicateUUIDMode.SAFE_REGEN) { - Map thisChunk = new HashMap<>(); - for (Iterator iterator = ((List) entityslice).iterator(); iterator.hasNext(); ) { - Entity entity = iterator.next(); - if (entity.dead || entity.valid) continue; - Entity other = ((WorldServer) world).getEntity(entity.uniqueID); - if (other == null || other.dead) { - other = thisChunk.get(entity.uniqueID); - } - - if (mode == PaperWorldConfig.DuplicateUUIDMode.SAFE_REGEN && other != null && !other.dead - && java.util.Objects.equals(other.getSaveID(), entity.getSaveID()) - && entity.getBukkitEntity().getLocation().distance(other.getBukkitEntity().getLocation()) < world.paperConfig.duplicateUUIDDeleteRange - ) { - if (World.DEBUG_ENTITIES) LOGGER.warn("[DUPE-UUID] Duplicate UUID found used by " + other + ", deleted entity " + entity + " because it was near the duplicate and likely an actual duplicate. See https://github.com/PaperMC/Paper/issues/1223 for discussion on what this is about."); - entity.dead = true; - iterator.remove(); - continue; - } - if (other != null && !other.dead) { - switch (mode) { - case SAFE_REGEN: { - entity.setUUID(UUID.randomUUID()); - if (World.DEBUG_ENTITIES) LOGGER.warn("[DUPE-UUID] Duplicate UUID found used by " + other + ", regenerated UUID for " + entity + ". See https://github.com/PaperMC/Paper/issues/1223 for discussion on what this is about."); - break; - } - case DELETE: { - if (World.DEBUG_ENTITIES) LOGGER.warn("[DUPE-UUID] Duplicate UUID found used by " + other + ", deleted entity " + entity + ". See https://github.com/PaperMC/Paper/issues/1223 for discussion on what this is about."); - entity.dead = true; - iterator.remove(); - break; - } - default: - if (World.DEBUG_ENTITIES) LOGGER.warn("[DUPE-UUID] Duplicate UUID found used by " + other + ", doing nothing to " + entity + ". See https://github.com/PaperMC/Paper/issues/1223 for discussion on what this is about."); - break; - } - } - - - if (!(entity instanceof EntityHuman) && (entity.dead || !this.world.addEntityChunk(entity))) { // Paper - if (list == null) { - list = Lists.newArrayList(new Entity[]{entity}); - } else { - list.add(entity); - } - } - } - } // Paper - } - - if (list != null) { - list.forEach(chunk::b); - } - } - - return chunk; - } // Paper - }); - }, (runnable) -> { - Mailbox mailbox = this.mailboxMain; - long i = playerchunk.i().pair(); - - playerchunk.getClass(); - mailbox.a(ChunkTaskQueueSorter.a(runnable, i, playerchunk::getTicketLevel)); // CraftBukkit - decompile error - }); - } - - public CompletableFuture> a(PlayerChunk playerchunk) { - ChunkCoordIntPair chunkcoordintpair = playerchunk.i(); - CompletableFuture, PlayerChunk.Failure>> completablefuture = this.a(chunkcoordintpair, 1, (i) -> { - return ChunkStatus.FULL; - }); - CompletableFuture> completablefuture1 = completablefuture.thenApplyAsync((either) -> { - return either.flatMap((list) -> { - Chunk chunk = (Chunk) list.get(list.size() / 2); - - chunk.A(); - return Either.left(chunk); - }); - }, (runnable) -> { - this.mailboxMain.a(ChunkTaskQueueSorter.a(playerchunk, runnable)); // CraftBukkit - decompile error - }); - - completablefuture1.thenAcceptAsync((either) -> { - either.mapLeft((chunk) -> { - this.v.getAndIncrement(); - Packet[] apacket = new Packet[2]; - - this.a(chunkcoordintpair, false).forEach((entityplayer) -> { - this.a(entityplayer, apacket, chunk); - }); - return Either.left(chunk); - }); - }, (runnable) -> { - this.mailboxMain.a(ChunkTaskQueueSorter.a(playerchunk, runnable)); // CraftBukkit - decompile error - }); - return completablefuture1; - } - - public CompletableFuture> b(PlayerChunk playerchunk) { - return playerchunk.a(ChunkStatus.FULL, this).thenApplyAsync((either) -> { - return either.mapLeft((ichunkaccess) -> { - Chunk chunk = (Chunk) ichunkaccess; - - chunk.B(); - return chunk; - }); - }, (runnable) -> { - this.mailboxMain.a(ChunkTaskQueueSorter.a(playerchunk, runnable)); // CraftBukkit - decompile error - }); - } - - public int c() { - return this.v.get(); - } - - // Paper start - async chunk io - private boolean writeDataAsync(ChunkCoordIntPair chunkPos, NBTTagCompound poiData, NBTTagCompound chunkData, boolean async) { - com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.scheduleSave(this.world, chunkPos.x, chunkPos.z, - poiData, chunkData, !async ? com.destroystokyo.paper.io.PrioritizedTaskQueue.HIGHEST_PRIORITY : com.destroystokyo.paper.io.PrioritizedTaskQueue.LOW_PRIORITY); - - if (async) { - return true; - } - - try (co.aikar.timings.Timing ignored = this.world.timings.chunkSaveIOWait.startTiming()) { // Paper - Boolean successPoi = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.waitForIOToComplete(this.world, chunkPos.x, chunkPos.z, true, true); - Boolean successChunk = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.waitForIOToComplete(this.world, chunkPos.x, chunkPos.z, true, false); - - if (successPoi == Boolean.FALSE || successChunk == Boolean.FALSE) { - return false; - } - - // null indicates no task existed, which means our write completed before we waited on it - - return true; - } // Paper - } - // Paper end - - public boolean saveChunk(IChunkAccess ichunkaccess) { - // Paper start - async param - return this.saveChunk(ichunkaccess, false); - } - public boolean saveChunk(IChunkAccess ichunkaccess, boolean async) { - try (co.aikar.timings.Timing ignored = this.world.timings.chunkSave.startTiming()) { - NBTTagCompound poiData = this.getVillagePlace().getData(ichunkaccess.getPos()); // Paper - //this.n.a(ichunkaccess.getPos()); // Delay - // Paper end - if (!ichunkaccess.isNeedsSaving()) { - return false; - } else { - // Paper - The save session check is performed on the IO thread - - ichunkaccess.setLastSaved(this.world.getTime()); - ichunkaccess.setNeedsSaving(false); - ChunkCoordIntPair chunkcoordintpair = ichunkaccess.getPos(); - - try { - ChunkStatus chunkstatus = ichunkaccess.getChunkStatus(); - NBTTagCompound nbttagcompound; - - if (chunkstatus.getType() != ChunkStatus.Type.LEVELCHUNK) { - try (co.aikar.timings.Timing ignored1 = this.world.timings.chunkSaveOverwriteCheck.startTiming()) { // Paper - // Paper start - Optimize save by using status cache - ChunkStatus statusOnDisk = this.getChunkStatusOnDisk(chunkcoordintpair); - if (statusOnDisk != null && statusOnDisk.getType() == ChunkStatus.Type.LEVELCHUNK) { - // Paper end - this.writeDataAsync(ichunkaccess.getPos(), poiData, null, async); // Paper - Async chunk io - return false; - } - - if (chunkstatus == ChunkStatus.EMPTY && ichunkaccess.h().values().stream().noneMatch(StructureStart::e)) { - this.writeDataAsync(ichunkaccess.getPos(), poiData, null, async); // Paper - Async chunk io - return false; - } - } - } // Paper - try (co.aikar.timings.Timing ignored1 = this.world.timings.chunkSaveDataSerialization.startTiming()) { // Paper - nbttagcompound = ChunkRegionLoader.saveChunk(this.world, ichunkaccess); - } // Paper - return this.writeDataAsync(ichunkaccess.getPos(), poiData, nbttagcompound, async); // Paper - Async chunk io - //return true; // Paper - } catch (Exception exception) { - PlayerChunkMap.LOGGER.error("Failed to save chunk {},{}", chunkcoordintpair.x, chunkcoordintpair.z, exception); - com.destroystokyo.paper.exception.ServerInternalException.reportInternalException(exception); // Paper - return false; - } - } - } // Paper - } - - protected void setViewDistance(int i) { - int j = MathHelper.clamp(i + 1, 3, 33); - - if (j != this.viewDistance) { - int k = this.viewDistance; - - this.viewDistance = j; - this.chunkDistanceManager.a(this.viewDistance); - ObjectIterator objectiterator = this.updatingChunks.values().iterator(); - - while (objectiterator.hasNext()) { - PlayerChunk playerchunk = (PlayerChunk) objectiterator.next(); - ChunkCoordIntPair chunkcoordintpair = playerchunk.i(); - Packet[] apacket = new Packet[2]; - - this.a(chunkcoordintpair, false).forEach((entityplayer) -> { - int l = b(chunkcoordintpair, entityplayer, true); - boolean flag = l <= k; - boolean flag1 = l <= this.viewDistance; - - this.sendChunk(entityplayer, chunkcoordintpair, apacket, flag, flag1); - }); - } - } - - } - - protected void sendChunk(EntityPlayer entityplayer, ChunkCoordIntPair chunkcoordintpair, Packet[] apacket, boolean flag, boolean flag1) { - if (entityplayer.world == this.world) { - if (flag1 && !flag) { - PlayerChunk playerchunk = this.getVisibleChunk(chunkcoordintpair.pair()); - - if (playerchunk != null) { - Chunk chunk = playerchunk.getChunk(); - - if (chunk != null) { - this.a(entityplayer, apacket, chunk); - } - - PacketDebug.a(this.world, chunkcoordintpair); - } - } - - if (!flag1 && flag) { - entityplayer.a(chunkcoordintpair); - } - - } - } - - public int d() { - return this.visibleChunks.size(); - } - - protected PlayerChunkMap.a e() { - return this.chunkDistanceManager; - } - - protected Iterable f() { - return Iterables.unmodifiableIterable(this.visibleChunks.values()); - } - - void a(Writer writer) throws IOException { - CSVWriter csvwriter = CSVWriter.a().a("x").a("z").a("level").a("in_memory").a("status").a("full_status").a("accessible_ready").a("ticking_ready").a("entity_ticking_ready").a("ticket").a("spawning").a("entity_count").a("block_entity_count").a(writer); - ObjectBidirectionalIterator objectbidirectionaliterator = this.visibleChunks.long2ObjectEntrySet().iterator(); - - while (objectbidirectionaliterator.hasNext()) { - Entry entry = (Entry) objectbidirectionaliterator.next(); - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(entry.getLongKey()); - PlayerChunk playerchunk = (PlayerChunk) entry.getValue(); - Optional optional = Optional.ofNullable(playerchunk.f()); - Optional optional1 = optional.flatMap((ichunkaccess) -> { - return ichunkaccess instanceof Chunk ? Optional.of((Chunk) ichunkaccess) : Optional.empty(); - }); - - // Craftbukkit - decompile error - csvwriter.a(chunkcoordintpair.x, chunkcoordintpair.z, playerchunk.getTicketLevel(), optional.isPresent(), optional.map(IChunkAccess::getChunkStatus).orElse(null), optional1.map(Chunk::getState).orElse(null), a(playerchunk.c()), a(playerchunk.a()), a(playerchunk.b()), this.chunkDistanceManager.c(entry.getLongKey()), !this.isOutsideOfRange(chunkcoordintpair), optional1.map((chunk) -> { - return Stream.of(chunk.getEntitySlices()).mapToInt(List::size).sum(); // Spigot - }).orElse(0), optional1.map((chunk) -> { - return chunk.getTileEntities().size(); - }).orElse(0)); - } - - } - - private static String a(CompletableFuture> completablefuture) { - try { - Either either = (Either) completablefuture.getNow(null); // Craftbukkit - decompile error - - return either != null ? (String) either.map((chunk) -> { - return "done"; - }, (playerchunk_failure) -> { - return "unloaded"; - }) : "not completed"; - } catch (CompletionException completionexception) { - return "failed " + completionexception.getCause().getMessage(); - } catch (CancellationException cancellationexception) { - return "cancelled"; - } - } - - // Paper start - Asynchronous chunk io - @Nullable - @Override - public NBTTagCompound read(ChunkCoordIntPair chunkcoordintpair) throws IOException { - if (Thread.currentThread() != com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE) { - NBTTagCompound ret = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE - .loadChunkDataAsyncFuture(this.world, chunkcoordintpair.x, chunkcoordintpair.z, com.destroystokyo.paper.io.IOUtil.getPriorityForCurrentThread(), - false, true, true).join().chunkData; - - if (ret == com.destroystokyo.paper.io.PaperFileIOThread.FAILURE_VALUE) { - throw new IOException("See logs for further detail"); - } - return ret; - } - return super.read(chunkcoordintpair); - } - - @Override - public void write(ChunkCoordIntPair chunkcoordintpair, NBTTagCompound nbttagcompound) throws IOException { - if (Thread.currentThread() != com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE) { - com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.scheduleSave( - this.world, chunkcoordintpair.x, chunkcoordintpair.z, null, nbttagcompound, - com.destroystokyo.paper.io.IOUtil.getPriorityForCurrentThread()); - - Boolean ret = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.waitForIOToComplete(this.world, - chunkcoordintpair.x, chunkcoordintpair.z, true, false); - - if (ret == Boolean.FALSE) { - throw new IOException("See logs for further detail"); - } - return; - } - super.write(chunkcoordintpair, nbttagcompound); - } - // Paper end - - @Nullable - public NBTTagCompound readChunkData(ChunkCoordIntPair chunkcoordintpair) throws IOException { // Paper - private -> public - NBTTagCompound nbttagcompound = this.read(chunkcoordintpair); - - // Paper start - Cache chunk status on disk - if (nbttagcompound == null) { - return null; - } - - nbttagcompound = this.getChunkData(this.world.getWorldProvider().getDimensionManager(), this.m, nbttagcompound, chunkcoordintpair, world); // CraftBukkit - if (nbttagcompound == null) { - return null; - } - - this.updateChunkStatusOnDisk(chunkcoordintpair, nbttagcompound); - - return nbttagcompound; - // Paper end - } - - // Paper start - chunk status cache "api" - public ChunkStatus getChunkStatusOnDiskIfCached(ChunkCoordIntPair chunkPos) { - // Paper start - async chunk save for unload - IChunkAccess unloadingChunk = this.world.asyncChunkTaskManager.getChunkInSaveProgress(chunkPos.x, chunkPos.z); - if (unloadingChunk != null) { - return unloadingChunk.getChunkStatus(); - } - // Paper end - // Paper start - async io - NBTTagCompound inProgressWrite = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE - .getPendingWrite(this.world, chunkPos.x, chunkPos.z, false); - - if (inProgressWrite != null) { - return ChunkRegionLoader.getStatus(inProgressWrite); - } - // Paper end - - RegionFile regionFile = this.getRegionFileIfLoaded(chunkPos); - - return regionFile == null ? null : regionFile.getStatusIfCached(chunkPos.x, chunkPos.z); - } - - public ChunkStatus getChunkStatusOnDisk(ChunkCoordIntPair chunkPos) throws IOException { - // Paper start - async chunk save for unload - IChunkAccess unloadingChunk = this.world.asyncChunkTaskManager.getChunkInSaveProgress(chunkPos.x, chunkPos.z); - if (unloadingChunk != null) { - return unloadingChunk.getChunkStatus(); - } - // Paper end - // Paper start - async io - NBTTagCompound inProgressWrite = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE - .getPendingWrite(this.world, chunkPos.x, chunkPos.z, false); - - if (inProgressWrite != null) { - return ChunkRegionLoader.getStatus(inProgressWrite); - } - // Paper end - synchronized (this) { // Paper - async io - RegionFile regionFile = this.getRegionFile(chunkPos, false); - - if (!regionFile.chunkExists(chunkPos)) { - return null; - } - - ChunkStatus status = regionFile.getStatusIfCached(chunkPos.x, chunkPos.z); - - if (status != null) { - return status; - } - // Paper start - async io - } - - NBTTagCompound compound = this.readChunkData(chunkPos); - - return ChunkRegionLoader.getStatus(compound); - // Paper end - } - - public void updateChunkStatusOnDisk(ChunkCoordIntPair chunkPos, @Nullable NBTTagCompound compound) throws IOException { - synchronized (this) { // Paper - async io - RegionFile regionFile = this.getRegionFile(chunkPos, false); - - regionFile.setStatus(chunkPos.x, chunkPos.z, ChunkRegionLoader.getStatus(compound)); - } // Paper - async io - } - - // Paper start - async io - // this function will not load chunk data off disk to check for status - // ret null for unknown, empty for empty status on disk or absent from disk - public ChunkStatus getStatusOnDiskNoLoad(int x, int z) { - // Paper start - async chunk save for unload - IChunkAccess unloadingChunk = this.world.asyncChunkTaskManager.getChunkInSaveProgress(x, z); - if (unloadingChunk != null) { - return unloadingChunk.getChunkStatus(); - } - // Paper end - // Paper start - async io - net.minecraft.server.NBTTagCompound inProgressWrite = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE - .getPendingWrite(this.world, x, z, false); - - if (inProgressWrite != null) { - return net.minecraft.server.ChunkRegionLoader.getStatus(inProgressWrite); - } - // Paper end - // variant of PlayerChunkMap#getChunkStatusOnDisk that does not load data off disk, but loads the region file - ChunkCoordIntPair chunkPos = new ChunkCoordIntPair(x, z); - synchronized (world.getChunkProvider().playerChunkMap) { - net.minecraft.server.RegionFile file; - try { - file = world.getChunkProvider().playerChunkMap.getRegionFile(chunkPos, false); - } catch (IOException ex) { - throw new RuntimeException(ex); - } - - return !file.chunkExists(chunkPos) ? ChunkStatus.EMPTY : file.getStatusIfCached(x, z); - } - } - // Paper end - - public IChunkAccess getUnloadingChunk(int chunkX, int chunkZ) { - PlayerChunk chunkHolder = this.pendingUnload.get(ChunkCoordIntPair.pair(chunkX, chunkZ)); - return chunkHolder == null ? null : chunkHolder.getAvailableChunkNow(); - } - // Paper end - - boolean isOutsideOfRange(ChunkCoordIntPair chunkcoordintpair) { - // Spigot start - return isOutsideOfRange(chunkcoordintpair, false); - } - - boolean isOutsideOfRange(ChunkCoordIntPair chunkcoordintpair, boolean reducedRange) { - int chunkRange = world.spigotConfig.mobSpawnRange; - chunkRange = (chunkRange > world.spigotConfig.viewDistance) ? (byte) world.spigotConfig.viewDistance : chunkRange; - chunkRange = (chunkRange > 8) ? 8 : chunkRange; - - final int finalChunkRange = chunkRange; // Paper for lambda below - //double blockRange = (reducedRange) ? Math.pow(chunkRange << 4, 2) : 16384.0D; // Paper - use from event - // Spigot end - long i = chunkcoordintpair.pair(); - - return !this.chunkDistanceManager.d(i) ? true : this.playerMap.a(i).noneMatch((entityplayer) -> { - // Paper start - - com.destroystokyo.paper.event.entity.PlayerNaturallySpawnCreaturesEvent event; - double blockRange = 16384.0D; - if (reducedRange) { - event = new com.destroystokyo.paper.event.entity.PlayerNaturallySpawnCreaturesEvent(entityplayer.getBukkitEntity(), (byte) finalChunkRange); - event.callEvent(); - blockRange = (double) ((event.getSpawnRadius() << 4) * (event.getSpawnRadius() << 4)); - if (event.isCancelled()) return true; - } - - return (!entityplayer.isSpectator() && a(chunkcoordintpair, (Entity) entityplayer) < blockRange); // Spigot - // Paper end - }); - } - - private boolean b(EntityPlayer entityplayer) { - return entityplayer.isSpectator() && !this.world.getGameRules().getBoolean(GameRules.SPECTATORS_GENERATE_CHUNKS); - } - - void a(EntityPlayer entityplayer, boolean flag) { - boolean flag1 = this.b(entityplayer); - boolean flag2 = this.playerMap.c(entityplayer); - int i = MathHelper.floor(entityplayer.locX) >> 4; - int j = MathHelper.floor(entityplayer.locZ) >> 4; - - if (flag) { - this.playerMap.a(ChunkCoordIntPair.pair(i, j), entityplayer, flag1); - this.c(entityplayer); - if (!flag1) { - this.chunkDistanceManager.a(SectionPosition.a((Entity) entityplayer), entityplayer); - } - } else { - SectionPosition sectionposition = entityplayer.M(); - - this.playerMap.a(sectionposition.u().pair(), entityplayer); - if (!flag2) { - this.chunkDistanceManager.b(sectionposition, entityplayer); - } - } - - for (int k = i - this.viewDistance; k <= i + this.viewDistance; ++k) { - for (int l = j - this.viewDistance; l <= j + this.viewDistance; ++l) { - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(k, l); - - this.sendChunk(entityplayer, chunkcoordintpair, new Packet[2], !flag, flag); - } - } - - } - - private SectionPosition c(EntityPlayer entityplayer) { - SectionPosition sectionposition = SectionPosition.a((Entity) entityplayer); - - entityplayer.a(sectionposition); - entityplayer.playerConnection.sendPacket(new PacketPlayOutViewCentre(sectionposition.a(), sectionposition.c())); - return sectionposition; - } - - public void movePlayer(EntityPlayer entityplayer) { - ObjectIterator objectiterator = this.trackedEntities.values().iterator(); - - while (objectiterator.hasNext()) { - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker = (PlayerChunkMap.EntityTracker) objectiterator.next(); - - if (playerchunkmap_entitytracker.tracker == entityplayer) { - playerchunkmap_entitytracker.track(this.world.getPlayers()); - } else { - playerchunkmap_entitytracker.updatePlayer(entityplayer); - } - } - - int i = MathHelper.floor(entityplayer.locX) >> 4; - int j = MathHelper.floor(entityplayer.locZ) >> 4; - SectionPosition sectionposition = entityplayer.M(); - SectionPosition sectionposition1 = SectionPosition.a((Entity) entityplayer); - long k = sectionposition.u().pair(); - long l = sectionposition1.u().pair(); - boolean flag = this.playerMap.d(entityplayer); - boolean flag1 = this.b(entityplayer); - boolean flag2 = sectionposition.v() != sectionposition1.v(); - - if (flag2 || flag != flag1) { - this.c(entityplayer); - if (!flag) { - this.chunkDistanceManager.b(sectionposition, entityplayer); - } - - if (!flag1) { - this.chunkDistanceManager.a(sectionposition1, entityplayer); - } - - if (!flag && flag1) { - this.playerMap.a(entityplayer); - } - - if (flag && !flag1) { - this.playerMap.b(entityplayer); - } - - if (k != l) { - this.playerMap.a(k, l, entityplayer); - } - } - - int i1 = sectionposition.a(); - int j1 = sectionposition.c(); - int k1; - int l1; - - if (Math.abs(i1 - i) <= this.viewDistance * 2 && Math.abs(j1 - j) <= this.viewDistance * 2) { - k1 = Math.min(i, i1) - this.viewDistance; - l1 = Math.min(j, j1) - this.viewDistance; - int i2 = Math.max(i, i1) + this.viewDistance; - int j2 = Math.max(j, j1) + this.viewDistance; - - for (int k2 = k1; k2 <= i2; ++k2) { - for (int l2 = l1; l2 <= j2; ++l2) { - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(k2, l2); - boolean flag3 = a(chunkcoordintpair, i1, j1) <= this.viewDistance; - boolean flag4 = a(chunkcoordintpair, i, j) <= this.viewDistance; - - this.sendChunk(entityplayer, chunkcoordintpair, new Packet[2], flag3, flag4); - } - } - } else { - ChunkCoordIntPair chunkcoordintpair1; - boolean flag5; - boolean flag6; - - for (k1 = i1 - this.viewDistance; k1 <= i1 + this.viewDistance; ++k1) { - for (l1 = j1 - this.viewDistance; l1 <= j1 + this.viewDistance; ++l1) { - chunkcoordintpair1 = new ChunkCoordIntPair(k1, l1); - flag5 = true; - flag6 = false; - this.sendChunk(entityplayer, chunkcoordintpair1, new Packet[2], true, false); - } - } - - for (k1 = i - this.viewDistance; k1 <= i + this.viewDistance; ++k1) { - for (l1 = j - this.viewDistance; l1 <= j + this.viewDistance; ++l1) { - chunkcoordintpair1 = new ChunkCoordIntPair(k1, l1); - flag5 = false; - flag6 = true; - this.sendChunk(entityplayer, chunkcoordintpair1, new Packet[2], false, true); - } - } - } - - } - - @Override - public Stream a(ChunkCoordIntPair chunkcoordintpair, boolean flag) { - return this.playerMap.a(chunkcoordintpair.pair()).filter((entityplayer) -> { - int i = b(chunkcoordintpair, entityplayer, true); - - return i > this.viewDistance ? false : !flag || i == this.viewDistance; - }); - } - - protected void addEntity(Entity entity) { - org.spigotmc.AsyncCatcher.catchOp("entity track"); // Spigot - if (!(entity instanceof EntityComplexPart)) { - if (!(entity instanceof EntityLightning)) { - EntityTypes entitytypes = entity.getEntityType(); - int i = entitytypes.getChunkRange() * 16; - i = org.spigotmc.TrackingRange.getEntityTrackingRange(entity, i); // Spigot - int j = entitytypes.getUpdateInterval(); - - if (this.trackedEntities.containsKey(entity.getId())) { - throw new IllegalStateException("Entity is already tracked!"); - } else { - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker = new PlayerChunkMap.EntityTracker(entity, i, j, entitytypes.isDeltaTracking()); - - entity.tracker = playerchunkmap_entitytracker; // Paper - Fast access to tracker - this.trackedEntities.put(entity.getId(), playerchunkmap_entitytracker); - playerchunkmap_entitytracker.track(this.world.getPlayers()); - if (entity instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entity; - - this.a(entityplayer, true); - ObjectIterator objectiterator = this.trackedEntities.values().iterator(); - - while (objectiterator.hasNext()) { - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker1 = (PlayerChunkMap.EntityTracker) objectiterator.next(); - - if (playerchunkmap_entitytracker1.tracker != entityplayer) { - playerchunkmap_entitytracker1.updatePlayer(entityplayer); - } - } - } - - } - } - } - } - - protected void removeEntity(Entity entity) { - org.spigotmc.AsyncCatcher.catchOp("entity untrack"); // Spigot - if (entity instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entity; - - this.a(entityplayer, false); - ObjectIterator objectiterator = this.trackedEntities.values().iterator(); - - while (objectiterator.hasNext()) { - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker = (PlayerChunkMap.EntityTracker) objectiterator.next(); - - playerchunkmap_entitytracker.clear(entityplayer); - } - } - - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker1 = (PlayerChunkMap.EntityTracker) this.trackedEntities.remove(entity.getId()); - - if (playerchunkmap_entitytracker1 != null) { - playerchunkmap_entitytracker1.a(); - } - entity.tracker = null; // Paper - We're no longer tracked - } - - protected void g() { - List list = Lists.newArrayList(); - List list1 = this.world.getPlayers(); - - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker; - ObjectIterator objectiterator; - world.timings.tracker1.startTiming(); // Paper - - for (objectiterator = this.trackedEntities.values().iterator(); objectiterator.hasNext(); playerchunkmap_entitytracker.trackerEntry.a()) { - playerchunkmap_entitytracker = (PlayerChunkMap.EntityTracker) objectiterator.next(); - SectionPosition sectionposition = playerchunkmap_entitytracker.e; - SectionPosition sectionposition1 = SectionPosition.a(playerchunkmap_entitytracker.tracker); - - if (!Objects.equals(sectionposition, sectionposition1)) { - playerchunkmap_entitytracker.track(list1); - Entity entity = playerchunkmap_entitytracker.tracker; - - if (entity instanceof EntityPlayer) { - list.add((EntityPlayer) entity); - } - - playerchunkmap_entitytracker.e = sectionposition1; - } - } - world.timings.tracker1.stopTiming(); // Paper - - objectiterator = this.trackedEntities.values().iterator(); - - world.timings.tracker2.startTiming(); // Paper - while (objectiterator.hasNext()) { - playerchunkmap_entitytracker = (PlayerChunkMap.EntityTracker) objectiterator.next(); - playerchunkmap_entitytracker.track(list); - } - world.timings.tracker2.stopTiming(); // Paper - - } - - protected void broadcast(Entity entity, Packet packet) { - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker = (PlayerChunkMap.EntityTracker) this.trackedEntities.get(entity.getId()); - - if (playerchunkmap_entitytracker != null) { - playerchunkmap_entitytracker.broadcast(packet); - } - - } - - protected void broadcastIncludingSelf(Entity entity, Packet packet) { - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker = (PlayerChunkMap.EntityTracker) this.trackedEntities.get(entity.getId()); - - if (playerchunkmap_entitytracker != null) { - playerchunkmap_entitytracker.broadcastIncludingSelf(packet); - } - - } - - private void a(EntityPlayer entityplayer, Packet[] apacket, Chunk chunk) { - if (apacket[0] == null) { - apacket[0] = new PacketPlayOutMapChunk(chunk, 65535, true); // Paper - Anti-Xray - apacket[1] = new PacketPlayOutLightUpdate(chunk.getPos(), this.lightEngine); - } - - entityplayer.a(chunk.getPos(), apacket[0], apacket[1]); - PacketDebug.a(this.world, chunk.getPos()); - List list = Lists.newArrayList(); - List list1 = Lists.newArrayList(); - ObjectIterator objectiterator = this.trackedEntities.values().iterator(); - - while (objectiterator.hasNext()) { - PlayerChunkMap.EntityTracker playerchunkmap_entitytracker = (PlayerChunkMap.EntityTracker) objectiterator.next(); - Entity entity = playerchunkmap_entitytracker.tracker; - - if (entity != entityplayer && entity.chunkX == chunk.getPos().x && entity.chunkZ == chunk.getPos().z) { - playerchunkmap_entitytracker.updatePlayer(entityplayer); - if (entity instanceof EntityInsentient && ((EntityInsentient) entity).getLeashHolder() != null) { - list.add(entity); - } - - if (!entity.getPassengers().isEmpty()) { - list1.add(entity); - } - } - } - - Iterator iterator; - Entity entity1; - - if (!list.isEmpty()) { - iterator = list.iterator(); - - while (iterator.hasNext()) { - entity1 = (Entity) iterator.next(); - entityplayer.playerConnection.sendPacket(new PacketPlayOutAttachEntity(entity1, ((EntityInsentient) entity1).getLeashHolder())); - } - } - - if (!list1.isEmpty()) { - iterator = list1.iterator(); - - while (iterator.hasNext()) { - entity1 = (Entity) iterator.next(); - entityplayer.playerConnection.sendPacket(new PacketPlayOutMount(entity1)); - } - } - - } - - public VillagePlace getVillagePlace() { return this.h(); } // Paper - OBFHELPER - protected VillagePlace h() { - return this.n; - } - - public CompletableFuture a(Chunk chunk) { - return this.executor.e(() -> { - chunk.a(this.world); - }); - } - - public class EntityTracker { - - private final EntityTrackerEntry trackerEntry; - private final Entity tracker; - private final int trackingDistance; - private SectionPosition e; - // Paper start - // Replace trackedPlayers Set with a Map. The value is true until the player receives - // their first update (which is forced to have absolute coordinates), false afterward. - public java.util.Map trackedPlayerMap = new java.util.HashMap<>(); - public Set trackedPlayers = trackedPlayerMap.keySet(); - - public EntityTracker(Entity entity, int i, int j, boolean flag) { - this.trackerEntry = new EntityTrackerEntry(PlayerChunkMap.this.world, entity, j, flag, this::broadcast, trackedPlayerMap); // CraftBukkit // Paper - this.tracker = entity; - this.trackingDistance = i; - this.e = SectionPosition.a(entity); - } - - public boolean equals(Object object) { - return object instanceof PlayerChunkMap.EntityTracker ? ((PlayerChunkMap.EntityTracker) object).tracker.getId() == this.tracker.getId() : false; - } - - public int hashCode() { - return this.tracker.getId(); - } - - public void broadcast(Packet packet) { - Iterator iterator = this.trackedPlayers.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - entityplayer.playerConnection.sendPacket(packet); - } - - } - - public void broadcastIncludingSelf(Packet packet) { - this.broadcast(packet); - if (this.tracker instanceof EntityPlayer) { - ((EntityPlayer) this.tracker).playerConnection.sendPacket(packet); - } - - } - - public void a() { - Iterator iterator = this.trackedPlayers.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - this.trackerEntry.a(entityplayer); - } - - } - - public void clear(EntityPlayer entityplayer) { - org.spigotmc.AsyncCatcher.catchOp("player tracker clear"); // Spigot - if (this.trackedPlayers.remove(entityplayer)) { - this.trackerEntry.a(entityplayer); - } - - } - - public void updatePlayer(EntityPlayer entityplayer) { - org.spigotmc.AsyncCatcher.catchOp("player tracker update"); // Spigot - if (entityplayer != this.tracker) { - Vec3D vec3d = (new Vec3D(entityplayer.locX, entityplayer.locY, entityplayer.locZ)).d(this.tracker.getPositionVector()); // MC-155077, SPIGOT-5113 - int i = Math.min(this.trackingDistance, (PlayerChunkMap.this.viewDistance - 1) * 16); - boolean flag = vec3d.x >= (double) (-i) && vec3d.x <= (double) i && vec3d.z >= (double) (-i) && vec3d.z <= (double) i && this.tracker.a(entityplayer); - - if (flag) { - boolean flag1 = this.tracker.attachedToPlayer; - - if (!flag1) { - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(this.tracker.chunkX, this.tracker.chunkZ); - PlayerChunk playerchunk = PlayerChunkMap.this.getVisibleChunk(chunkcoordintpair.pair()); - - if (playerchunk != null && playerchunk.getChunk() != null) { - flag1 = PlayerChunkMap.b(chunkcoordintpair, entityplayer, false) <= PlayerChunkMap.this.viewDistance; - } - } - - // CraftBukkit start - respect vanish API - if (this.tracker instanceof EntityPlayer) { - Player player = ((EntityPlayer) this.tracker).getBukkitEntity(); - if (!entityplayer.getBukkitEntity().canSee(player)) { - flag1 = false; - } - } - - entityplayer.removeQueue.remove(Integer.valueOf(this.tracker.getId())); - // CraftBukkit end - - if (flag1 && this.trackedPlayerMap.putIfAbsent(entityplayer, true) == null) { // Paper - this.trackerEntry.b(entityplayer); - } - } else if (this.trackedPlayers.remove(entityplayer)) { - this.trackerEntry.a(entityplayer); - } - - } - } - - public void track(List list) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - this.updatePlayer(entityplayer); - } - - } - } - - class a extends ChunkMapDistance { - - protected a(Executor executor, Executor executor1) { - super(executor, executor1); - } - - @Override - protected boolean a(long i) { - return PlayerChunkMap.this.unloadQueue.contains(i); - } - - @Nullable - @Override - protected PlayerChunk b(long i) { - return PlayerChunkMap.this.getUpdatingChunk(i); - } - - @Nullable - @Override - protected PlayerChunk a(long i, int j, @Nullable PlayerChunk playerchunk, int k) { - return PlayerChunkMap.this.a(i, j, playerchunk, k); - } - } -} diff --git a/src/main/java/net/minecraft/server/PlayerConnection.java b/src/main/java/net/minecraft/server/PlayerConnection.java deleted file mode 100644 index ae17cdf23..000000000 --- a/src/main/java/net/minecraft/server/PlayerConnection.java +++ /dev/null @@ -1,2681 +0,0 @@ -package net.minecraft.server; - -import com.google.common.primitives.Doubles; -import com.google.common.primitives.Floats; -import com.mojang.brigadier.ParseResults; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.suggestion.Suggestions; -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 java.util.Collections; -import java.util.Iterator; -import java.util.Optional; -import java.util.Set; -import javax.annotation.Nullable; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -import org.bukkit.Location; -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.craftbukkit.util.CraftMagicNumbers; -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.ClickType; -import org.bukkit.event.inventory.CraftItemEvent; -import org.bukkit.event.inventory.InventoryAction; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCreativeEvent; -import org.bukkit.event.inventory.InventoryType.SlotType; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerAnimationEvent; -import org.bukkit.event.player.PlayerChatEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerInteractAtEntityEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerItemHeldEvent; -import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerResourcePackStatusEvent; -import org.bukkit.event.player.PlayerSwapHandItemsEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.player.PlayerToggleFlightEvent; -import org.bukkit.event.player.PlayerToggleSneakEvent; -import org.bukkit.event.player.PlayerToggleSprintEvent; -import org.bukkit.inventory.CraftingInventory; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.InventoryView; -import org.bukkit.util.NumberConversions; -import com.destroystokyo.paper.event.player.IllegalPacketEvent; // Paper -import com.destroystokyo.paper.event.player.PlayerJumpEvent; // Paper -import co.aikar.timings.MinecraftTimings; // Paper -// CraftBukkit end - -public class PlayerConnection implements PacketListenerPlayIn { - - private static final Logger LOGGER = LogManager.getLogger(); - public final NetworkManager networkManager; - private final MinecraftServer minecraftServer; - public EntityPlayer player; - private int e; - private long lastKeepAlive = SystemUtils.getMonotonicMillis(); private void setLastPing(long lastPing) { this.lastKeepAlive = lastPing;}; private long getLastPing() { return this.lastKeepAlive;}; // Paper - OBFHELPER - private boolean awaitingKeepAlive; private void setPendingPing(boolean isPending) { this.awaitingKeepAlive = isPending;}; private boolean isPendingPing() { return this.awaitingKeepAlive;}; // Paper - OBFHELPER - private long h; private void setKeepAliveID(long keepAliveID) { this.h = keepAliveID;}; private long getKeepAliveID() {return this.h; }; // Paper - OBFHELPER - // CraftBukkit start - multithreaded fields - private volatile int chatThrottle; - private static final AtomicIntegerFieldUpdater chatSpamField = AtomicIntegerFieldUpdater.newUpdater(PlayerConnection.class, "chatThrottle"); - private final java.util.concurrent.atomic.AtomicInteger tabSpamLimiter = new java.util.concurrent.atomic.AtomicInteger(); // Paper - configurable tab spam limits - // CraftBukkit end - private int j; - private final Int2ShortMap k = new Int2ShortOpenHashMap(); - private double l; - private double m; - private double n; - private double o; - private double p; - private double q; - private Entity r; - private double s; - private double t; - private double u; - private double v; - private double w; - private double x; - private Vec3D teleportPos; - private int teleportAwait; - private int A; - private boolean B; - private int C; - private boolean D; - private int E; - private int receivedMovePackets; - private int processedMovePackets; - private static final int MAX_SIGN_LINE_LENGTH = Integer.getInteger("Paper.maxSignLength", 80); - private static final long KEEPALIVE_LIMIT = Long.getLong("paper.playerconnection.keepalive", 30) * 1000; // Paper - provide property to set keepalive limit - - public PlayerConnection(MinecraftServer minecraftserver, NetworkManager networkmanager, EntityPlayer entityplayer) { - this.minecraftServer = minecraftserver; - this.networkManager = networkmanager; - networkmanager.setPacketListener(this); - this.player = entityplayer; - entityplayer.playerConnection = this; - - // CraftBukkit start - add fields and methods - this.server = minecraftserver.server; - } - - private final org.bukkit.craftbukkit.CraftServer server; - public boolean processedDisconnect; - private int lastTick = MinecraftServer.currentTick; - private int allowedPlayerTicks = 1; - private int lastDropTick = MinecraftServer.currentTick; - private int lastBookTick = MinecraftServer.currentTick; - private int dropCount = 0; - private static final int SURVIVAL_PLACE_DISTANCE_SQUARED = 6 * 6; - private static final int CREATIVE_PLACE_DISTANCE_SQUARED = 7 * 7; - - // 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 = false; - private boolean hasMoved; // Spigot - - public CraftPlayer getPlayer() { - return (this.player == null) ? null : (CraftPlayer) this.player.getBukkitEntity(); - } - // CraftBukkit end - - public void tick() { - this.syncPosition(); - this.player.playerTick(); - this.player.setLocation(this.l, this.m, this.n, this.player.yaw, this.player.pitch); - ++this.e; - this.processedMovePackets = this.receivedMovePackets; - if (this.B) { - if (++this.C > 80) { - PlayerConnection.LOGGER.warn("{} was kicked for floating too long!", this.player.getDisplayName().getString()); - this.disconnect(com.destroystokyo.paper.PaperConfig.flyingKickPlayerMessage); // Paper - use configurable kick message - return; - } - } else { - this.B = false; - this.C = 0; - } - - this.r = this.player.getRootVehicle(); - if (this.r != this.player && this.r.getRidingPassenger() == this.player) { - this.s = this.r.locX; - this.t = this.r.locY; - this.u = this.r.locZ; - this.v = this.r.locX; - this.w = this.r.locY; - this.x = this.r.locZ; - if (this.D && this.player.getRootVehicle().getRidingPassenger() == this.player) { - if (++this.E > 80) { - PlayerConnection.LOGGER.warn("{} was kicked for floating a vehicle too long!", this.player.getDisplayName().getString()); - this.disconnect(com.destroystokyo.paper.PaperConfig.flyingKickVehicleMessage); // Paper - use configurable kick message - return; - } - } else { - this.D = false; - this.E = 0; - } - } else { - this.r = null; - this.D = false; - this.E = 0; - } - - this.minecraftServer.getMethodProfiler().enter("keepAlive"); - // Paper Start - give clients a longer time to respond to pings as per pre 1.12.2 timings - // This should effectively place the keepalive handling back to "as it was" before 1.12.2 - long currentTime = SystemUtils.getMonotonicMillis(); - long elapsedTime = currentTime - this.getLastPing(); - - if (this.isPendingPing()) { - if (!this.processedDisconnect && elapsedTime >= KEEPALIVE_LIMIT) { // check keepalive limit, don't fire if already disconnected - PlayerConnection.LOGGER.warn("{} was kicked due to keepalive timeout!", this.player.getName()); // more info - this.disconnect(new ChatMessage("disconnect.timeout", new Object[0])); - } - } else { - if (elapsedTime >= 15000L) { // 15 seconds - this.setPendingPing(true); - this.setLastPing(currentTime); - this.setKeepAliveID(currentTime); - this.sendPacket(new PacketPlayOutKeepAlive(this.getKeepAliveID())); - - } - } - // Paper end - - this.minecraftServer.getMethodProfiler().exit(); - // CraftBukkit start - for (int spam; (spam = this.chatThrottle) > 0 && !chatSpamField.compareAndSet(this, spam, spam - 1); ) ; - if (tabSpamLimiter.get() > 0) tabSpamLimiter.getAndDecrement(); // Paper - split to seperate variable - /* Use thread-safe field access instead - if (this.chatThrottle > 0) { - --this.chatThrottle; - } - */ - // CraftBukkit end - - if (this.j > 0) { - --this.j; - } - - if (this.player.F() > 0L && this.minecraftServer.getIdleTimeout() > 0 && SystemUtils.getMonotonicMillis() - this.player.F() > (long) (this.minecraftServer.getIdleTimeout() * 1000 * 60)) { - this.player.resetIdleTimer(); // CraftBukkit - SPIGOT-854 - this.disconnect(new ChatMessage("multiplayer.disconnect.idling", new Object[0])); - } - - } - - public void syncPosition() { - this.l = this.player.locX; - this.m = this.player.locY; - this.n = this.player.locZ; - this.o = this.player.locX; - this.p = this.player.locY; - this.q = this.player.locZ; - } - - @Override - public NetworkManager a() { - return this.networkManager; - } - - private boolean isExemptPlayer() { - return this.minecraftServer.b(this.player.getProfile()); - } - - // CraftBukkit start - @Deprecated - public void disconnect(IChatBaseComponent ichatbasecomponent) { - disconnect(CraftChatMessage.fromComponent(ichatbasecomponent, EnumChatFormat.WHITE)); - } - // CraftBukkit end - - public void disconnect(String s) { - // CraftBukkit start - fire PlayerKickEvent - if (this.processedDisconnect) { - return; - } - String leaveMessage = EnumChatFormat.YELLOW + this.player.getName() + " left the game."; - - PlayerKickEvent event = new PlayerKickEvent(this.server.getPlayer(this.player), s, leaveMessage); - - if (this.server.getServer().isRunning()) { - this.server.getPluginManager().callEvent(event); - } - - if (event.isCancelled()) { - // Do not kick the player - return; - } - // Send the possibly modified leave message - s = event.getReason(); - // CraftBukkit end - final ChatComponentText ichatbasecomponent = new ChatComponentText(s); - - this.networkManager.sendPacket(new PacketPlayOutKickDisconnect(ichatbasecomponent), (future) -> { - this.networkManager.close(ichatbasecomponent); - }); - this.a(ichatbasecomponent); // CraftBukkit - fire quit instantly - this.networkManager.stopReading(); - MinecraftServer minecraftserver = this.minecraftServer; - NetworkManager networkmanager = this.networkManager; - - this.networkManager.getClass(); - // CraftBukkit - Don't wait - minecraftserver.scheduleOnMain(networkmanager::handleDisconnection); // Paper - } - - @Override - public void a(PacketPlayInSteerVehicle packetplayinsteervehicle) { - PlayerConnectionUtils.ensureMainThread(packetplayinsteervehicle, this, this.player.getWorldServer()); - this.player.a(packetplayinsteervehicle.b(), packetplayinsteervehicle.c(), packetplayinsteervehicle.d(), packetplayinsteervehicle.e()); - } - - private static boolean b(PacketPlayInFlying packetplayinflying) { - return Doubles.isFinite(packetplayinflying.a(0.0D)) && Doubles.isFinite(packetplayinflying.b(0.0D)) && Doubles.isFinite(packetplayinflying.c(0.0D)) && Floats.isFinite(packetplayinflying.b(0.0F)) && Floats.isFinite(packetplayinflying.a(0.0F)) ? Math.abs(packetplayinflying.a(0.0D)) > 3.0E7D || Math.abs(packetplayinflying.b(0.0D)) > 3.0E7D || Math.abs(packetplayinflying.c(0.0D)) > 3.0E7D : true; - } - - private static boolean b(PacketPlayInVehicleMove packetplayinvehiclemove) { - return !Doubles.isFinite(packetplayinvehiclemove.getX()) || !Doubles.isFinite(packetplayinvehiclemove.getY()) || !Doubles.isFinite(packetplayinvehiclemove.getZ()) || !Floats.isFinite(packetplayinvehiclemove.getPitch()) || !Floats.isFinite(packetplayinvehiclemove.getYaw()); - } - - @Override - public void a(PacketPlayInVehicleMove packetplayinvehiclemove) { - PlayerConnectionUtils.ensureMainThread(packetplayinvehiclemove, this, this.player.getWorldServer()); - if (b(packetplayinvehiclemove)) { - this.disconnect(new ChatMessage("multiplayer.disconnect.invalid_vehicle_movement", new Object[0])); - } else { - Entity entity = this.player.getRootVehicle(); - - if (entity != this.player && entity.getRidingPassenger() == this.player && entity == this.r) { - WorldServer worldserver = this.player.getWorldServer(); - double d0 = entity.locX; - double d1 = entity.locY; - double d2 = entity.locZ; - double d3 = packetplayinvehiclemove.getX(); - double d4 = packetplayinvehiclemove.getY(); - double d5 = packetplayinvehiclemove.getZ(); - float f = packetplayinvehiclemove.getYaw(); - float f1 = packetplayinvehiclemove.getPitch(); - double d6 = d3 - this.s; - double d7 = d4 - this.t; - double d8 = d5 - this.u; - double d9 = entity.getMot().g(); - double d10 = d6 * d6 + d7 * d7 + d8 * d8; - - - // CraftBukkit start - handle custom speeds and skipped ticks - this.allowedPlayerTicks += (System.currentTimeMillis() / 50) - this.lastTick; - this.allowedPlayerTicks = Math.max(this.allowedPlayerTicks, 1); - this.lastTick = (int) (System.currentTimeMillis() / 50); - - ++this.receivedMovePackets; - int i = this.receivedMovePackets - this.processedMovePackets; - if (i > Math.max(this.allowedPlayerTicks, 5)) { - PlayerConnection.LOGGER.debug(this.player.getName() + " is sending move packets too frequently (" + i + " packets since last tick)"); - i = 1; - } - - if (d10 > 0) { - allowedPlayerTicks -= 1; - } else { - allowedPlayerTicks = 20; - } - double speed; - if (player.abilities.isFlying) { - speed = player.abilities.flySpeed * 20f; - } else { - speed = player.abilities.walkSpeed * 10f; - } - speed *= 2f; // TODO: Get the speed of the vehicle instead of the player - - // Paper start - Prevent moving into unloaded chunks - if (player.world.paperConfig.preventMovingIntoUnloadedChunks && worldserver.getChunkIfLoadedImmediately((int) Math.floor(packetplayinvehiclemove.getX()) >> 4, (int) Math.floor(packetplayinvehiclemove.getZ()) >> 4) == null) { - this.networkManager.sendPacket(new PacketPlayOutVehicleMove(entity)); - return; - } - // Paper end - - if (d10 - d9 > Math.max(100.0D, Math.pow((double) (org.spigotmc.SpigotConfig.movedTooQuicklyMultiplier * (float) i * speed), 2)) && !this.isExemptPlayer()) { - // CraftBukkit end - PlayerConnection.LOGGER.warn("{} (vehicle of {}) moved too quickly! {},{},{}", entity.getDisplayName().getString(), this.player.getDisplayName().getString(), d6, d7, d8); - this.networkManager.sendPacket(new PacketPlayOutVehicleMove(entity)); - return; - } - - boolean flag = worldserver.getCubes(entity, entity.getBoundingBox().shrink(0.0625D)); - - d6 = d3 - this.v; - d7 = d4 - this.w - 1.0E-6D; - d8 = d5 - this.x; - entity.move(EnumMoveType.PLAYER, new Vec3D(d6, d7, d8)); - double d11 = d7; - - d6 = d3 - entity.locX; - d7 = d4 - entity.locY; - if (d7 > -0.5D || d7 < 0.5D) { - d7 = 0.0D; - } - - d8 = d5 - entity.locZ; - d10 = d6 * d6 + d7 * d7 + d8 * d8; - boolean flag1 = false; - - if (d10 > org.spigotmc.SpigotConfig.movedWronglyThreshold) { // Spigot - flag1 = true; - PlayerConnection.LOGGER.warn(entity.getName() + " (vehicle of " + this.player.getName() + ") moved wrongly!"); // Paper - More informative - } - Location curPos = this.getPlayer().getLocation(); // Spigot - - entity.setLocation(d3, d4, d5, f, f1); - player.setLocation(d3, d4, d5, this.player.yaw, this.player.pitch); // CraftBukkit - boolean flag2 = worldserver.getCubes(entity, entity.getBoundingBox().shrink(0.0625D)); - - if (flag && (flag1 || !flag2)) { - entity.setLocation(d0, d1, d2, f, f1); - player.setLocation(d0, d1, d2, this.player.yaw, this.player.pitch); // CraftBukkit - this.networkManager.sendPacket(new PacketPlayOutVehicleMove(entity)); - return; - } - - // CraftBukkit start - fire PlayerMoveEvent - Player player = this.getPlayer(); - // Spigot Start - if ( !hasMoved ) - { - lastPosX = curPos.getX(); - lastPosY = curPos.getY(); - lastPosZ = curPos.getZ(); - lastYaw = curPos.getYaw(); - lastPitch = curPos.getPitch(); - hasMoved = true; - } - // Spigot End - Location from = new Location(player.getWorld(), lastPosX, lastPosY, lastPosZ, lastYaw, lastPitch); // Get the Players previous Event location. - Location to = player.getLocation().clone(); // Start off the To location as the Players current location. - - // If the packet contains movement information then we update the To location with the correct XYZ. - to.setX(packetplayinvehiclemove.getX()); - to.setY(packetplayinvehiclemove.getY()); - to.setZ(packetplayinvehiclemove.getZ()); - - - // If the packet contains look information then we update the To location with the correct Yaw & Pitch. - to.setYaw(packetplayinvehiclemove.getYaw()); - to.setPitch(packetplayinvehiclemove.getPitch()); - - // 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.player.isFrozen()) { - this.lastPosX = to.getX(); - this.lastPosY = to.getY(); - this.lastPosZ = to.getZ(); - this.lastYaw = to.getYaw(); - this.lastPitch = to.getPitch(); - - // Skip the first time we do this - if (true) { // Spigot - don't skip any move events - Location oldTo = to.clone(); - PlayerMoveEvent event = new PlayerMoveEvent(player, from, to); - this.server.getPluginManager().callEvent(event); - - // If the event is cancelled we move the player back to their old location. - if (event.isCancelled()) { - teleport(from); - return; - } - - // If a Plugin has changed the To destination then we teleport the Player - // there to avoid any 'Moved wrongly' or 'Moved too quickly' errors. - // We only do this if the Event was not cancelled. - if (!oldTo.equals(event.getTo()) && !event.isCancelled()) { - this.player.getBukkitEntity().teleport(event.getTo(), PlayerTeleportEvent.TeleportCause.PLUGIN); - return; - } - - // Check to see if the Players Location has some how changed during the call of the event. - // This can happen due to a plugin teleporting the player instead of using .setTo() - if (!from.equals(this.getPlayer().getLocation()) && this.justTeleported) { - this.justTeleported = false; - return; - } - } - } - // CraftBukkit end - - this.player.getWorldServer().getChunkProvider().movePlayer(this.player); - this.player.checkMovement(this.player.locX - d0, this.player.locY - d1, this.player.locZ - d2); - this.D = d11 >= -0.03125D && !this.minecraftServer.getAllowFlight() && !worldserver.a(entity.getBoundingBox().g(0.0625D).b(0.0D, -0.55D, 0.0D)); - this.v = entity.locX; - this.w = entity.locY; - this.x = entity.locZ; - } - - } - } - - @Override - public void a(PacketPlayInTeleportAccept packetplayinteleportaccept) { - PlayerConnectionUtils.ensureMainThread(packetplayinteleportaccept, this, this.player.getWorldServer()); - if (packetplayinteleportaccept.b() == this.teleportAwait && this.teleportPos != null) { // CraftBukkit - this.player.setLocation(this.teleportPos.x, this.teleportPos.y, this.teleportPos.z, this.player.yaw, this.player.pitch); - this.o = this.teleportPos.x; - this.p = this.teleportPos.y; - this.q = this.teleportPos.z; - if (this.player.H()) { - this.player.I(); - } - - this.teleportPos = null; - this.player.getWorldServer().getChunkProvider().movePlayer(this.player); // CraftBukkit - } - - } - - @Override - public void a(PacketPlayInRecipeDisplayed packetplayinrecipedisplayed) { - PlayerConnectionUtils.ensureMainThread(packetplayinrecipedisplayed, this, this.player.getWorldServer()); - if (packetplayinrecipedisplayed.b() == PacketPlayInRecipeDisplayed.Status.SHOWN) { - Optional> optional = this.minecraftServer.getCraftingManager().a(packetplayinrecipedisplayed.c()); // CraftBukkit - decompile error - RecipeBookServer recipebookserver = this.player.B(); - - optional.ifPresent(recipebookserver::e); - } else if (packetplayinrecipedisplayed.b() == PacketPlayInRecipeDisplayed.Status.SETTINGS) { - this.player.B().a(packetplayinrecipedisplayed.d()); - this.player.B().b(packetplayinrecipedisplayed.e()); - this.player.B().c(packetplayinrecipedisplayed.f()); - this.player.B().d(packetplayinrecipedisplayed.g()); - this.player.B().e(packetplayinrecipedisplayed.h()); - this.player.B().f(packetplayinrecipedisplayed.i()); - this.player.B().g(packetplayinrecipedisplayed.j()); - this.player.B().h(packetplayinrecipedisplayed.k()); - } - - } - - @Override - public void a(PacketPlayInAdvancements packetplayinadvancements) { - PlayerConnectionUtils.ensureMainThread(packetplayinadvancements, this, this.player.getWorldServer()); - if (packetplayinadvancements.c() == PacketPlayInAdvancements.Status.OPENED_TAB) { - MinecraftKey minecraftkey = packetplayinadvancements.d(); - Advancement advancement = this.minecraftServer.getAdvancementData().a(minecraftkey); - - if (advancement != null) { - this.player.getAdvancementData().a(advancement); - } - } - - } - - @Override - public void a(PacketPlayInTabComplete packetplayintabcomplete) { - // PlayerConnectionUtils.ensureMainThread(packetplayintabcomplete, this, this.player.getWorldServer()); // Paper - run this async - // CraftBukkit start - if (tabSpamLimiter.addAndGet(com.destroystokyo.paper.PaperConfig.tabSpamIncrement) > com.destroystokyo.paper.PaperConfig.tabSpamLimit && !this.minecraftServer.getPlayerList().isOp(this.player.getProfile())) { // Paper start - split and make configurable - minecraftServer.scheduleOnMain(() -> this.disconnect(new ChatMessage("disconnect.spam", new Object[0]))); // Paper - return; - } - // CraftBukkit end - StringReader stringreader = new StringReader(packetplayintabcomplete.c()); - - if (stringreader.canRead() && stringreader.peek() == '/') { - stringreader.skip(); - } - - // Paper start - async tab completion - com.destroystokyo.paper.event.server.AsyncTabCompleteEvent event; - java.util.List completions = new java.util.ArrayList<>(); - String buffer = packetplayintabcomplete.c(); - event = new com.destroystokyo.paper.event.server.AsyncTabCompleteEvent(this.getPlayer(), completions, - buffer, true, null); - event.callEvent(); - completions = event.isCancelled() ? com.google.common.collect.ImmutableList.of() : event.getCompletions(); - // If the event isn't handled, we can assume that we have no completions, and so we'll ask the server - if (!event.isHandled()) { - if (!event.isCancelled()) { - // Paper end - async tab completion - this.minecraftServer.scheduleOnMain(() -> { // Paper - This needs to be on main - ParseResults parseresults = this.minecraftServer.getCommandDispatcher().a().parse(stringreader, this.player.getCommandListener()); - - this.minecraftServer.getCommandDispatcher().a().getCompletionSuggestions(parseresults).thenAccept((suggestions) -> { - if (((Suggestions) suggestions).isEmpty()) return; // CraftBukkit - don't send through empty suggestions - prevents [] from showing for plugins with nothing more to offer - this.networkManager.sendPacket(new PacketPlayOutTabComplete(packetplayintabcomplete.b(), (Suggestions) suggestions)); // CraftBukkit - decompile error - }); - }); // Paper - This needs to be on main - } - // Paper start - async tab completion - } else if (!completions.isEmpty()) { - com.mojang.brigadier.suggestion.SuggestionsBuilder builder = new com.mojang.brigadier.suggestion.SuggestionsBuilder(packetplayintabcomplete.c(), stringreader.getTotalLength()); - - builder = builder.createOffset(builder.getInput().lastIndexOf(' ') + 1); - completions.forEach(builder::suggest); - player.playerConnection.sendPacket(new PacketPlayOutTabComplete(packetplayintabcomplete.b(), builder.buildFuture().join())); - } - // Paper end - async tab completion - - } - - @Override - public void a(PacketPlayInSetCommandBlock packetplayinsetcommandblock) { - PlayerConnectionUtils.ensureMainThread(packetplayinsetcommandblock, this, this.player.getWorldServer()); - if (!this.minecraftServer.getEnableCommandBlock()) { - this.player.sendMessage(new ChatMessage("advMode.notEnabled", new Object[0])); - } else if (!this.player.isCreativeAndOp()) { - this.player.sendMessage(new ChatMessage("advMode.notAllowed", new Object[0])); - } else { - CommandBlockListenerAbstract commandblocklistenerabstract = null; - TileEntityCommand tileentitycommand = null; - BlockPosition blockposition = packetplayinsetcommandblock.b(); - TileEntity tileentity = this.player.world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityCommand) { - tileentitycommand = (TileEntityCommand) tileentity; - commandblocklistenerabstract = tileentitycommand.getCommandBlock(); - } - - String s = packetplayinsetcommandblock.c(); - boolean flag = packetplayinsetcommandblock.d(); - - if (commandblocklistenerabstract != null) { - EnumDirection enumdirection = (EnumDirection) this.player.world.getType(blockposition).get(BlockCommand.a); - IBlockData iblockdata; - - switch (packetplayinsetcommandblock.g()) { - case SEQUENCE: - iblockdata = Blocks.CHAIN_COMMAND_BLOCK.getBlockData(); - this.player.world.setTypeAndData(blockposition, (IBlockData) ((IBlockData) iblockdata.set(BlockCommand.a, enumdirection)).set(BlockCommand.b, packetplayinsetcommandblock.e()), 2); - break; - case AUTO: - iblockdata = Blocks.REPEATING_COMMAND_BLOCK.getBlockData(); - this.player.world.setTypeAndData(blockposition, (IBlockData) ((IBlockData) iblockdata.set(BlockCommand.a, enumdirection)).set(BlockCommand.b, packetplayinsetcommandblock.e()), 2); - break; - case REDSTONE: - default: - iblockdata = Blocks.COMMAND_BLOCK.getBlockData(); - this.player.world.setTypeAndData(blockposition, (IBlockData) ((IBlockData) iblockdata.set(BlockCommand.a, enumdirection)).set(BlockCommand.b, packetplayinsetcommandblock.e()), 2); - } - - tileentity.n(); - this.player.world.setTileEntity(blockposition, tileentity); - commandblocklistenerabstract.setCommand(s); - commandblocklistenerabstract.a(flag); - if (!flag) { - commandblocklistenerabstract.c((IChatBaseComponent) null); - } - - tileentitycommand.b(packetplayinsetcommandblock.f()); - commandblocklistenerabstract.e(); - if (!UtilColor.b(s)) { - this.player.sendMessage(new ChatMessage("advMode.setCommand.success", new Object[]{s})); - } - } - - } - } - - @Override - public void a(PacketPlayInSetCommandMinecart packetplayinsetcommandminecart) { - PlayerConnectionUtils.ensureMainThread(packetplayinsetcommandminecart, this, this.player.getWorldServer()); - if (!this.minecraftServer.getEnableCommandBlock()) { - this.player.sendMessage(new ChatMessage("advMode.notEnabled", new Object[0])); - } else if (!this.player.isCreativeAndOp()) { - this.player.sendMessage(new ChatMessage("advMode.notAllowed", new Object[0])); - } else { - CommandBlockListenerAbstract commandblocklistenerabstract = packetplayinsetcommandminecart.a(this.player.world); - - if (commandblocklistenerabstract != null) { - commandblocklistenerabstract.setCommand(packetplayinsetcommandminecart.b()); - commandblocklistenerabstract.a(packetplayinsetcommandminecart.c()); - if (!packetplayinsetcommandminecart.c()) { - commandblocklistenerabstract.c((IChatBaseComponent) null); - } - - commandblocklistenerabstract.e(); - this.player.sendMessage(new ChatMessage("advMode.setCommand.success", new Object[]{packetplayinsetcommandminecart.b()})); - } - - } - } - - @Override - public void a(PacketPlayInPickItem packetplayinpickitem) { - PlayerConnectionUtils.ensureMainThread(packetplayinpickitem, this, this.player.getWorldServer()); - this.player.inventory.c(packetplayinpickitem.b()); - this.player.playerConnection.sendPacket(new PacketPlayOutSetSlot(-2, this.player.inventory.itemInHandIndex, this.player.inventory.getItem(this.player.inventory.itemInHandIndex))); - this.player.playerConnection.sendPacket(new PacketPlayOutSetSlot(-2, packetplayinpickitem.b(), this.player.inventory.getItem(packetplayinpickitem.b()))); - this.player.playerConnection.sendPacket(new PacketPlayOutHeldItemSlot(this.player.inventory.itemInHandIndex)); - } - - @Override - public void a(PacketPlayInItemName packetplayinitemname) { - PlayerConnectionUtils.ensureMainThread(packetplayinitemname, this, this.player.getWorldServer()); - if (this.player.activeContainer instanceof ContainerAnvil) { - ContainerAnvil containeranvil = (ContainerAnvil) this.player.activeContainer; - String s = SharedConstants.a(packetplayinitemname.b()); - - if (s.length() <= 35) { - containeranvil.a(s); - } - } - - } - - @Override - public void a(PacketPlayInBeacon packetplayinbeacon) { - PlayerConnectionUtils.ensureMainThread(packetplayinbeacon, this, this.player.getWorldServer()); - if (this.player.activeContainer instanceof ContainerBeacon) { - ((ContainerBeacon) this.player.activeContainer).c(packetplayinbeacon.b(), packetplayinbeacon.c()); - } - - } - - @Override - public void a(PacketPlayInStruct packetplayinstruct) { - PlayerConnectionUtils.ensureMainThread(packetplayinstruct, this, this.player.getWorldServer()); - if (this.player.isCreativeAndOp()) { - BlockPosition blockposition = packetplayinstruct.b(); - IBlockData iblockdata = this.player.world.getType(blockposition); - TileEntity tileentity = this.player.world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityStructure) { - TileEntityStructure tileentitystructure = (TileEntityStructure) tileentity; - - tileentitystructure.setUsageMode(packetplayinstruct.d()); - tileentitystructure.setStructureName(packetplayinstruct.e()); - tileentitystructure.b(packetplayinstruct.f()); - tileentitystructure.c(packetplayinstruct.g()); - tileentitystructure.b(packetplayinstruct.h()); - tileentitystructure.b(packetplayinstruct.i()); - tileentitystructure.b(packetplayinstruct.j()); - tileentitystructure.a(packetplayinstruct.k()); - tileentitystructure.e(packetplayinstruct.l()); - tileentitystructure.f(packetplayinstruct.m()); - tileentitystructure.a(packetplayinstruct.n()); - tileentitystructure.a(packetplayinstruct.o()); - if (tileentitystructure.f()) { - String s = tileentitystructure.getStructureName(); - - if (packetplayinstruct.c() == TileEntityStructure.UpdateType.SAVE_AREA) { - if (tileentitystructure.C()) { - this.player.a((IChatBaseComponent) (new ChatMessage("structure_block.save_success", new Object[]{s})), false); - } else { - this.player.a((IChatBaseComponent) (new ChatMessage("structure_block.save_failure", new Object[]{s})), false); - } - } else if (packetplayinstruct.c() == TileEntityStructure.UpdateType.LOAD_AREA) { - if (!tileentitystructure.F()) { - this.player.a((IChatBaseComponent) (new ChatMessage("structure_block.load_not_found", new Object[]{s})), false); - } else if (tileentitystructure.D()) { - this.player.a((IChatBaseComponent) (new ChatMessage("structure_block.load_success", new Object[]{s})), false); - } else { - this.player.a((IChatBaseComponent) (new ChatMessage("structure_block.load_prepare", new Object[]{s})), false); - } - } else if (packetplayinstruct.c() == TileEntityStructure.UpdateType.SCAN_AREA) { - if (tileentitystructure.B()) { - this.player.a((IChatBaseComponent) (new ChatMessage("structure_block.size_success", new Object[]{s})), false); - } else { - this.player.a((IChatBaseComponent) (new ChatMessage("structure_block.size_failure", new Object[0])), false); - } - } - } else { - this.player.a((IChatBaseComponent) (new ChatMessage("structure_block.invalid_structure_name", new Object[]{packetplayinstruct.e()})), false); - } - - tileentitystructure.update(); - this.player.world.notify(blockposition, iblockdata, iblockdata, 3); - } - - } - } - - @Override - public void a(PacketPlayInSetJigsaw packetplayinsetjigsaw) { - PlayerConnectionUtils.ensureMainThread(packetplayinsetjigsaw, this, this.player.getWorldServer()); - if (this.player.isCreativeAndOp()) { - BlockPosition blockposition = packetplayinsetjigsaw.b(); - IBlockData iblockdata = this.player.world.getType(blockposition); - TileEntity tileentity = this.player.world.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityJigsaw) { - TileEntityJigsaw tileentityjigsaw = (TileEntityJigsaw) tileentity; - - tileentityjigsaw.a(packetplayinsetjigsaw.d()); - tileentityjigsaw.b(packetplayinsetjigsaw.c()); - tileentityjigsaw.a(packetplayinsetjigsaw.e()); - tileentityjigsaw.update(); - this.player.world.notify(blockposition, iblockdata, iblockdata, 3); - } - - } - } - - @Override - public void a(PacketPlayInTrSel packetplayintrsel) { - PlayerConnectionUtils.ensureMainThread(packetplayintrsel, this, this.player.getWorldServer()); - int i = packetplayintrsel.b(); - Container container = this.player.activeContainer; - - if (container instanceof ContainerMerchant) { - ContainerMerchant containermerchant = (ContainerMerchant) container; - CraftEventFactory.callTradeSelectEvent(this.player, i, containermerchant); // CraftBukkit - - containermerchant.d(i); - containermerchant.g(i); - } - - } - - @Override - public void a(PacketPlayInBEdit packetplayinbedit) { - // Paper start - ItemStack testStack = packetplayinbedit.b(); - if (!server.isPrimaryThread() && !testStack.isEmpty() && testStack.getTag() != null) { - NBTTagList pageList = testStack.getTag().getList("pages", 8); - long byteTotal = 0; - int maxBookPageSize = com.destroystokyo.paper.PaperConfig.maxBookPageSize; - double multiplier = Math.max(0.3D, Math.min(1D, com.destroystokyo.paper.PaperConfig.maxBookTotalSizeMultiplier)); - long byteAllowed = maxBookPageSize; - for (int i = 0; i < pageList.size(); ++i) { - String testString = pageList.getString(i); - int byteLength = testString.getBytes(java.nio.charset.StandardCharsets.UTF_8).length; - byteTotal += byteLength; - int length = testString.length(); - int multibytes = 0; - if (byteLength != length) { - for (char c : testString.toCharArray()) { - if (c > 127) { - multibytes++; - } - } - } - byteAllowed += (maxBookPageSize * Math.min(1, Math.max(0.1D, (double) length / 255D))) * multiplier; - - if (multibytes > 1) { - // penalize MB - byteAllowed -= multibytes; - } - } - - if (byteTotal > byteAllowed) { - PlayerConnection.LOGGER.warn(this.player.getName() + " tried to send too large of a book. Book Size: " + byteTotal + " - Allowed: "+ byteAllowed + " - Pages: " + pageList.size()); - minecraftServer.scheduleOnMain(() -> this.disconnect("Book too large!")); - return; - } - } - // Paper end - // CraftBukkit start - PlayerConnectionUtils.ensureMainThread(packetplayinbedit, this, this.player.getWorldServer()); - if (this.lastBookTick + 20 > MinecraftServer.currentTick) { - this.disconnect("Book edited too quickly!"); - return; - } - this.lastBookTick = MinecraftServer.currentTick; - EnumItemSlot enumitemslot = packetplayinbedit.d() == EnumHand.MAIN_HAND ? EnumItemSlot.MAINHAND : EnumItemSlot.OFFHAND; - // CraftBukkit end - ItemStack itemstack = packetplayinbedit.b(); - - if (!itemstack.isEmpty()) { - if (ItemBookAndQuill.b(itemstack.getTag())) { - ItemStack itemstack1 = this.player.b(packetplayinbedit.d()); - - if (itemstack.getItem() == Items.WRITABLE_BOOK && itemstack1.getItem() == Items.WRITABLE_BOOK) { - if (packetplayinbedit.c()) { - ItemStack itemstack2 = new ItemStack(Items.WRITTEN_BOOK); - NBTTagCompound nbttagcompound = itemstack1.getTag(); - - if (nbttagcompound != null) { - itemstack2.setTag(nbttagcompound.clone()); - } - - itemstack2.a("author", (NBTBase) (new NBTTagString(this.player.getDisplayName().getString()))); - itemstack2.a("title", (NBTBase) (new NBTTagString(itemstack.getTag().getString("title")))); - NBTTagList nbttaglist = itemstack.getTag().getList("pages", 8); - - for (int i = 0; i < nbttaglist.size(); ++i) { - String s = nbttaglist.getString(i); - ChatComponentText chatcomponenttext = new ChatComponentText(s); - - s = IChatBaseComponent.ChatSerializer.a((IChatBaseComponent) chatcomponenttext); - nbttaglist.set(i, (NBTBase) (new NBTTagString(s))); - } - - itemstack2.a("pages", (NBTBase) nbttaglist); - this.player.a(packetplayinbedit.d(), CraftEventFactory.handleEditBookEvent(player, enumitemslot, itemstack1, itemstack2)); // CraftBukkit - } else { - // Paper start - dont mutate players current item, set it from the event - ItemStack newBook = itemstack1.cloneItemStack(); - newBook.getOrCreateTagAndSet("pages", (NBTBase)itemstack.getTag().getList("pages", 8)); - this.player.setSlot(enumitemslot, CraftEventFactory.handleEditBookEvent(player, enumitemslot, itemstack1, newBook)); - // Paper end - } - } - - } - } - } - - @Override - public void a(PacketPlayInEntityNBTQuery packetplayinentitynbtquery) { - PlayerConnectionUtils.ensureMainThread(packetplayinentitynbtquery, this, this.player.getWorldServer()); - if (this.player.k(2)) { - Entity entity = this.player.getWorldServer().getEntity(packetplayinentitynbtquery.c()); - - if (entity != null) { - NBTTagCompound nbttagcompound = entity.save(new NBTTagCompound()); - - this.player.playerConnection.sendPacket(new PacketPlayOutNBTQuery(packetplayinentitynbtquery.b(), nbttagcompound)); - } - - } - } - - @Override - public void a(PacketPlayInTileNBTQuery packetplayintilenbtquery) { - PlayerConnectionUtils.ensureMainThread(packetplayintilenbtquery, this, this.player.getWorldServer()); - if (this.player.k(2)) { - TileEntity tileentity = this.player.getWorldServer().getTileEntity(packetplayintilenbtquery.c()); - NBTTagCompound nbttagcompound = tileentity != null ? tileentity.save(new NBTTagCompound()) : null; - - this.player.playerConnection.sendPacket(new PacketPlayOutNBTQuery(packetplayintilenbtquery.b(), nbttagcompound)); - } - } - - @Override - public void a(PacketPlayInFlying packetplayinflying) { - PlayerConnectionUtils.ensureMainThread(packetplayinflying, this, this.player.getWorldServer()); - if (b(packetplayinflying)) { - this.disconnect(new ChatMessage("multiplayer.disconnect.invalid_player_movement", new Object[0])); - } else { - WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); - - if (!this.player.viewingCredits && !this.player.isFrozen()) { // CraftBukkit - if (this.e == 0) { - this.syncPosition(); - } - - if (this.teleportPos != null) { - if (this.e - this.A > 20) { - this.A = this.e; - this.a(this.teleportPos.x, this.teleportPos.y, this.teleportPos.z, this.player.yaw, this.player.pitch); - } - this.allowedPlayerTicks = 20; // CraftBukkit - } else { - this.A = this.e; - if (this.player.isPassenger()) { - this.player.setLocation(this.player.locX, this.player.locY, this.player.locZ, packetplayinflying.a(this.player.yaw), packetplayinflying.b(this.player.pitch)); - this.player.getWorldServer().getChunkProvider().movePlayer(this.player); - this.allowedPlayerTicks = 20; // CraftBukkit - } else { - // CraftBukkit - Make sure the move is valid but then reset it for plugins to modify - double prevX = player.locX; - double prevY = player.locY; - double prevZ = player.locZ; - float prevYaw = player.yaw; - float prevPitch = player.pitch; - // CraftBukkit end - double d0 = this.player.locX; - double d1 = this.player.locY; - double d2 = this.player.locZ; - double d3 = this.player.locY; - double d4 = packetplayinflying.a(this.player.locX);double toX = d4; // Paper - OBFHELPER - double d5 = packetplayinflying.b(this.player.locY); - double d6 = packetplayinflying.c(this.player.locZ);double toZ = d6; // Paper - OBFHELPER - float f = packetplayinflying.a(this.player.yaw); - float f1 = packetplayinflying.b(this.player.pitch); - double d7 = d4 - this.l; - double d8 = d5 - this.m; - double d9 = d6 - this.n; - double d10 = this.player.getMot().g(); - double d11 = d7 * d7 + d8 * d8 + d9 * d9; - - if (this.player.isSleeping()) { - if (d11 > 1.0D) { - this.a(this.player.locX, this.player.locY, this.player.locZ, packetplayinflying.a(this.player.yaw), packetplayinflying.b(this.player.pitch)); - } - - } else { - ++this.receivedMovePackets; - int i = this.receivedMovePackets - this.processedMovePackets; - - // CraftBukkit start - handle custom speeds and skipped ticks - this.allowedPlayerTicks += (System.currentTimeMillis() / 50) - this.lastTick; - this.allowedPlayerTicks = Math.max(this.allowedPlayerTicks, 1); - this.lastTick = (int) (System.currentTimeMillis() / 50); - - if (i > Math.max(this.allowedPlayerTicks, 5)) { - PlayerConnection.LOGGER.debug("{} is sending move packets too frequently ({} packets since last tick)", this.player.getDisplayName().getString(), i); - i = 1; - } - - if (packetplayinflying.hasLook || d11 > 0) { - allowedPlayerTicks -= 1; - } else { - allowedPlayerTicks = 20; - } - double speed; - if (player.abilities.isFlying) { - speed = player.abilities.flySpeed * 20f; - } else { - speed = player.abilities.walkSpeed * 10f; - } - // Paper start - Prevent moving into unloaded chunks - if (player.world.paperConfig.preventMovingIntoUnloadedChunks && (this.player.locX != toX || this.player.locZ != toZ) && worldserver.getChunkIfLoadedImmediately((int) Math.floor(toX) >> 4, (int) Math.floor(toZ) >> 4) == null) { // Paper - use getIfLoadedImmediately - this.internalTeleport(this.player.locX, this.player.locY, this.player.locZ, this.player.yaw, this.player.pitch, Collections.emptySet()); - return; - } - // Paper end - - if (!this.player.H() && (!this.player.getWorldServer().getGameRules().getBoolean(GameRules.DISABLE_ELYTRA_MOVEMENT_CHECK) || !this.player.isGliding())) { - float f2 = this.player.isGliding() ? 300.0F : 100.0F; - - if (d11 - d10 > Math.max(f2, Math.pow((double) (org.spigotmc.SpigotConfig.movedTooQuicklyMultiplier * (float) i * speed), 2)) && !this.isExemptPlayer()) { - // CraftBukkit end - PlayerConnection.LOGGER.warn("{} moved too quickly! {},{},{}", this.player.getDisplayName().getString(), d7, d8, d9); - this.a(this.player.locX, this.player.locY, this.player.locZ, this.player.yaw, this.player.pitch); - return; - } - } - - boolean flag = this.a((IWorldReader) worldserver); - - d7 = d4 - this.o; - d8 = d5 - this.p; - d9 = d6 - this.q; - if (this.player.onGround && !packetplayinflying.b() && d8 > 0.0D) { - // Paper start - Add player jump event - Player player = this.getPlayer(); - Location from = new Location(player.getWorld(), lastPosX, lastPosY, lastPosZ, lastYaw, lastPitch); // Get the Players previous Event location. - Location to = player.getLocation().clone(); // Start off the To location as the Players current location. - - // If the packet contains movement information then we update the To location with the correct XYZ. - if (packetplayinflying.hasPos) { - to.setX(packetplayinflying.x); - to.setY(packetplayinflying.y); - to.setZ(packetplayinflying.z); - } - - // If the packet contains look information then we update the To location with the correct Yaw & Pitch. - if (packetplayinflying.hasLook) { - to.setYaw(packetplayinflying.yaw); - to.setPitch(packetplayinflying.pitch); - } - - PlayerJumpEvent event = new PlayerJumpEvent(player, from, to); - - if (event.callEvent()) { - this.player.jump(); - } else { - from = event.getFrom(); - this.internalTeleport(from.getX(), from.getY(), from.getZ(), from.getYaw(), from.getPitch(), Collections.emptySet()); - return; - } - // Paper end - } - - this.player.move(EnumMoveType.PLAYER, new Vec3D(d7, d8, d9)); - this.player.onGround = packetplayinflying.b(); - double d12 = d8; - - d7 = d4 - this.player.locX; - d8 = d5 - this.player.locY; - if (d8 > -0.5D || d8 < 0.5D) { - d8 = 0.0D; - } - - d9 = d6 - this.player.locZ; - d11 = d7 * d7 + d8 * d8 + d9 * d9; - boolean flag1 = false; - - if (!this.player.H() && d11 > org.spigotmc.SpigotConfig.movedWronglyThreshold && !this.player.isSleeping() && !this.player.playerInteractManager.isCreative() && this.player.playerInteractManager.getGameMode() != EnumGamemode.SPECTATOR) { // Spigot - flag1 = true; - PlayerConnection.LOGGER.warn("{} moved wrongly!", this.player.getDisplayName().getString()); - } - - this.player.setLocation(d4, d5, d6, f, f1); - this.player.checkMovement(this.player.locX - d0, this.player.locY - d1, this.player.locZ - d2); - if (!this.player.noclip && !this.player.isSleeping()) { - boolean flag2 = this.a((IWorldReader) worldserver); - - if (flag && (flag1 || !flag2)) { - this.a(d0, d1, d2, f, f1); - return; - } - } - - // CraftBukkit start - fire PlayerMoveEvent - // Rest to old location first - this.player.setLocation(prevX, prevY, prevZ, prevYaw, prevPitch); - - Player player = this.getPlayer(); - Location from = new Location(player.getWorld(), lastPosX, lastPosY, lastPosZ, lastYaw, lastPitch); // Get the Players previous Event location. - Location to = player.getLocation().clone(); // Start off the To location as the Players current location. - - // If the packet contains movement information then we update the To location with the correct XYZ. - if (packetplayinflying.hasPos) { - to.setX(packetplayinflying.x); - to.setY(packetplayinflying.y); - to.setZ(packetplayinflying.z); - } - - // If the packet contains look information then we update the To location with the correct Yaw & Pitch. - if (packetplayinflying.hasLook) { - to.setYaw(packetplayinflying.yaw); - to.setPitch(packetplayinflying.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.player.isFrozen()) { - this.lastPosX = to.getX(); - this.lastPosY = to.getY(); - this.lastPosZ = to.getZ(); - this.lastYaw = to.getYaw(); - this.lastPitch = to.getPitch(); - - // Skip the first time we do this - if (from.getX() != Double.MAX_VALUE) { - Location oldTo = to.clone(); - PlayerMoveEvent event = new PlayerMoveEvent(player, from, to); - this.server.getPluginManager().callEvent(event); - - // If the event is cancelled we move the player back to their old location. - if (event.isCancelled()) { - teleport(from); - return; - } - - // If a Plugin has changed the To destination then we teleport the Player - // there to avoid any 'Moved wrongly' or 'Moved too quickly' errors. - // We only do this if the Event was not cancelled. - if (!oldTo.equals(event.getTo()) && !event.isCancelled()) { - this.player.getBukkitEntity().teleport(event.getTo(), PlayerTeleportEvent.TeleportCause.PLUGIN); - return; - } - - // Check to see if the Players Location has some how changed during the call of the event. - // This can happen due to a plugin teleporting the player instead of using .setTo() - if (!from.equals(this.getPlayer().getLocation()) && this.justTeleported) { - this.justTeleported = false; - return; - } - } - } - this.player.setLocation(d4, d5, d6, f, f1); // Copied from above - // CraftBukkit end - - this.B = d12 >= -0.03125D && this.player.playerInteractManager.getGameMode() != EnumGamemode.SPECTATOR && !this.minecraftServer.getAllowFlight() && !this.player.abilities.canFly && !this.player.hasEffect(MobEffects.LEVITATION) && !this.player.isGliding() && !worldserver.a(this.player.getBoundingBox().g(0.0625D).b(0.0D, -0.55D, 0.0D)); - this.player.onGround = packetplayinflying.b(); - this.player.getWorldServer().getChunkProvider().movePlayer(this.player); - this.player.a(this.player.locY - d3, packetplayinflying.b()); - this.o = this.player.locX; - this.p = this.player.locY; - this.q = this.player.locZ; - } - } - } - } - } - } - - private boolean a(IWorldReader iworldreader) { - return iworldreader.getCubes(this.player, this.player.getBoundingBox().shrink(9.999999747378752E-6D)); - } - - public void a(double d0, double d1, double d2, float f, float f1) { - this.a(d0, d1, d2, f, f1, Collections.emptySet()); - } - - // CraftBukkit start - Delegate to teleport(Location) - public void a(double d0, double d1, double d2, float f, float f1, PlayerTeleportEvent.TeleportCause cause) { - this.a(d0, d1, d2, f, f1, Collections.emptySet(), cause); - } - - public void a(double d0, double d1, double d2, float f, float f1, Set set) { - this.a(d0, d1, d2, f, f1, set, PlayerTeleportEvent.TeleportCause.UNKNOWN); - } - - public void a(double d0, double d1, double d2, float f, float f1, Set set, PlayerTeleportEvent.TeleportCause cause) { - Player player = this.getPlayer(); - Location from = player.getLocation(); - - double x = d0; - double y = d1; - double z = d2; - float yaw = f; - float pitch = f1; - - Location to = new Location(this.getPlayer().getWorld(), x, y, z, yaw, pitch); - // SPIGOT-5171: Triggered on join - if (from.equals(to)) { - this.internalTeleport(d0, d1, d2, f, f1, set); - return; - } - - PlayerTeleportEvent event = new PlayerTeleportEvent(player, from.clone(), to.clone(), cause); - 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) { - internalTeleport(dest.getX(), dest.getY(), dest.getZ(), dest.getYaw(), dest.getPitch(), Collections.emptySet()); - } - - private void internalTeleport(double d0, double d1, double d2, float f, float f1, Set set) { - // CraftBukkit start - if (Float.isNaN(f)) { - f = 0; - } - if (Float.isNaN(f1)) { - f1 = 0; - } - - this.justTeleported = true; - // CraftBukkit end - double d3 = set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.X) ? this.player.locX : 0.0D; - double d4 = set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y) ? this.player.locY : 0.0D; - double d5 = set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Z) ? this.player.locZ : 0.0D; - float f2 = set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y_ROT) ? this.player.yaw : 0.0F; - float f3 = set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.X_ROT) ? this.player.pitch : 0.0F; - - this.teleportPos = new Vec3D(d0, d1, d2); - if (++this.teleportAwait == Integer.MAX_VALUE) { - this.teleportAwait = 0; - } - - // CraftBukkit start - update last location - this.lastPosX = this.teleportPos.x; - this.lastPosY = this.teleportPos.y; - this.lastPosZ = this.teleportPos.z; - this.lastYaw = f; - this.lastPitch = f1; - // CraftBukkit end - - this.A = this.e; - this.player.setLocation(d0, d1, d2, f, f1); - this.player.playerConnection.sendPacket(new PacketPlayOutPosition(d0 - d3, d1 - d4, d2 - d5, f - f2, f1 - f3, set, this.teleportAwait)); - } - - @Override - public void a(PacketPlayInBlockDig packetplayinblockdig) { - PlayerConnectionUtils.ensureMainThread(packetplayinblockdig, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - BlockPosition blockposition = packetplayinblockdig.b(); - - this.player.resetIdleTimer(); - PacketPlayInBlockDig.EnumPlayerDigType packetplayinblockdig_enumplayerdigtype = packetplayinblockdig.d(); - - switch (packetplayinblockdig_enumplayerdigtype) { - case SWAP_HELD_ITEMS: - if (!this.player.isSpectator()) { - ItemStack itemstack = this.player.b(EnumHand.OFF_HAND); - - // CraftBukkit start - inspiration taken from DispenserRegistry (See SpigotCraft#394) - CraftItemStack mainHand = CraftItemStack.asCraftMirror(itemstack); - CraftItemStack offHand = CraftItemStack.asCraftMirror(this.player.b(EnumHand.MAIN_HAND)); - PlayerSwapHandItemsEvent swapItemsEvent = new PlayerSwapHandItemsEvent(getPlayer(), mainHand.clone(), offHand.clone()); - this.server.getPluginManager().callEvent(swapItemsEvent); - if (swapItemsEvent.isCancelled()) { - return; - } - if (swapItemsEvent.getOffHandItem().equals(offHand)) { - this.player.a(EnumHand.OFF_HAND, this.player.b(EnumHand.MAIN_HAND)); - } else { - this.player.a(EnumHand.OFF_HAND, CraftItemStack.asNMSCopy(swapItemsEvent.getOffHandItem())); - } - if (swapItemsEvent.getMainHandItem().equals(mainHand)) { - this.player.a(EnumHand.MAIN_HAND, itemstack); - } else { - this.player.a(EnumHand.MAIN_HAND, CraftItemStack.asNMSCopy(swapItemsEvent.getMainHandItem())); - } - // CraftBukkit end - } - - return; - case 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 (this.lastDropTick != MinecraftServer.currentTick) { - this.dropCount = 0; - this.lastDropTick = MinecraftServer.currentTick; - } else { - // Else we increment the drop count and check the amount. - this.dropCount++; - if (this.dropCount >= 20) { - LOGGER.warn(this.player.getName() + " dropped their items too quickly!"); - this.disconnect("You dropped your items too quickly (Hacking?)"); - return; - } - } - // CraftBukkit end - this.player.n(false); - } - - return; - case DROP_ALL_ITEMS: - if (!this.player.isSpectator()) { - this.player.n(true); - } - - return; - case RELEASE_USE_ITEM: - this.player.clearActiveItem(); - return; - case START_DESTROY_BLOCK: - case ABORT_DESTROY_BLOCK: - case STOP_DESTROY_BLOCK: - // Paper start - Don't allow digging in unloaded chunks - if (this.player.world.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4) == null) { - return; - } - // Paper end - Don't allow digging in unloaded chunks - this.player.playerInteractManager.a(blockposition, packetplayinblockdig_enumplayerdigtype, packetplayinblockdig.c(), this.minecraftServer.getMaxBuildHeight()); - return; - default: - throw new IllegalArgumentException("Invalid player action"); - } - } - - // Spigot start - limit place/interactions - private int limitedPackets; - private long lastLimitedPacket = -1; - private static final int THRESHOLD = com.destroystokyo.paper.PaperConfig.packetInSpamThreshold; // Paper - Configurable threshold - - private boolean checkLimit(long timestamp) { - if (lastLimitedPacket != -1 && timestamp - lastLimitedPacket < THRESHOLD && limitedPackets++ >= 8) { // Paper - Use threshold, raise packet limit to 8 - return false; - } - - if (lastLimitedPacket == -1 || timestamp - lastLimitedPacket >= THRESHOLD) { // Paper - lastLimitedPacket = timestamp; - limitedPackets = 0; - return true; - } - - return true; - } - // Spigot end - - @Override - public void a(PacketPlayInUseItem packetplayinuseitem) { - PlayerConnectionUtils.ensureMainThread(packetplayinuseitem, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - if (!checkLimit(packetplayinuseitem.timestamp)) return; // Spigot - check limit - WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); - EnumHand enumhand = packetplayinuseitem.b(); - ItemStack itemstack = this.player.b(enumhand); - MovingObjectPositionBlock movingobjectpositionblock = packetplayinuseitem.c(); - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition(); - EnumDirection enumdirection = movingobjectpositionblock.getDirection(); - IBlockData clickedBlock = worldserver.getType(blockposition); // Spigot - - this.player.resetIdleTimer(); - if (blockposition.getY() >= this.minecraftServer.getMaxBuildHeight() - 1 && ((enumdirection == EnumDirection.UP && !(clickedBlock.getBlock() instanceof BlockStepAbstract && clickedBlock.get(BlockStepAbstract.a) == BlockPropertySlabType.BOTTOM)) || blockposition.getY() >= this.minecraftServer.getMaxBuildHeight())) { // Spigot - IChatBaseComponent ichatbasecomponent = (new ChatMessage("build.tooHigh", new Object[]{this.minecraftServer.getMaxBuildHeight()})).a(EnumChatFormat.RED); - - this.player.playerConnection.sendPacket(new PacketPlayOutChat(ichatbasecomponent, ChatMessageType.GAME_INFO)); - } else if (this.teleportPos == null && this.player.e((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D) < 64.0D && worldserver.a((EntityHuman) this.player, blockposition)) { - // 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; - } - this.player.clearActiveItem(); // SPIGOT-4706 - // CraftBukkit end - this.player.playerInteractManager.a(this.player, worldserver, itemstack, enumhand, movingobjectpositionblock); - } - - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(worldserver, blockposition)); - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(worldserver, blockposition.shift(enumdirection))); - } - - @Override - public void a(PacketPlayInBlockPlace packetplayinblockplace) { - PlayerConnectionUtils.ensureMainThread(packetplayinblockplace, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - if (!checkLimit(packetplayinblockplace.timestamp)) return; // Spigot - check limit - WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); - EnumHand enumhand = packetplayinblockplace.b(); - ItemStack itemstack = this.player.b(enumhand); - - this.player.resetIdleTimer(); - if (!itemstack.isEmpty()) { - // CraftBukkit start - // Raytrace to look for 'rogue armswings' - float f1 = this.player.pitch; - float f2 = this.player.yaw; - double d0 = this.player.locX; - double d1 = this.player.locY + (double) this.player.getHeadHeight(); - double d2 = this.player.locZ; - 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 = player.playerInteractManager.getGameMode()== EnumGamemode.CREATIVE ? 5.0D : 4.5D; - Vec3D vec3d1 = vec3d.add((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); - MovingObjectPosition movingobjectposition = this.player.world.rayTrace(new RayTrace(vec3d, vec3d1, RayTrace.BlockCollisionOption.OUTLINE, RayTrace.FluidCollisionOption.NONE, player)); - - boolean cancelled; - if (movingobjectposition == null || movingobjectposition.getType() != MovingObjectPosition.EnumMovingObjectType.BLOCK) { - org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(this.player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); - cancelled = event.useItemInHand() == Event.Result.DENY; - } else { - if (player.playerInteractManager.firedInteract) { - player.playerInteractManager.firedInteract = false; - cancelled = player.playerInteractManager.interactResult; - } else { - MovingObjectPositionBlock movingobjectpositionblock = (MovingObjectPositionBlock) movingobjectposition; - org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_BLOCK, movingobjectpositionblock.getBlockPosition(), movingobjectpositionblock.getDirection(), itemstack, true, enumhand); - cancelled = event.useItemInHand() == Event.Result.DENY; - } - } - - if (cancelled) { - this.player.getBukkitEntity().updateInventory(); // SPIGOT-2524 - } else { - this.player.playerInteractManager.a(this.player, worldserver, itemstack, enumhand); - } - // CraftBukkit end - } - } - - @Override - public void a(PacketPlayInSpectate packetplayinspectate) { - PlayerConnectionUtils.ensureMainThread(packetplayinspectate, this, this.player.getWorldServer()); - if (this.player.isSpectator()) { - Iterator iterator = this.minecraftServer.getWorlds().iterator(); - - while (iterator.hasNext()) { - WorldServer worldserver = (WorldServer) iterator.next(); - Entity entity = packetplayinspectate.a(worldserver); - - if (entity != null) { - this.player.a(worldserver, entity.locX, entity.locY, entity.locZ, entity.yaw, entity.pitch, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.SPECTATE); // CraftBukkit - return; - } - } - } - - } - - @Override - // CraftBukkit start - public void a(PacketPlayInResourcePackStatus packetplayinresourcepackstatus) { - PlayerConnectionUtils.ensureMainThread(packetplayinresourcepackstatus, this, this.player.getWorldServer()); - // Paper start - PlayerResourcePackStatusEvent.Status packStatus = PlayerResourcePackStatusEvent.Status.values()[packetplayinresourcepackstatus.status.ordinal()]; - player.getBukkitEntity().setResourcePackStatus(packStatus); - this.server.getPluginManager().callEvent(new PlayerResourcePackStatusEvent(getPlayer(), packStatus)); - // Paper end - } - // CraftBukkit end - - @Override - public void a(PacketPlayInBoatMove packetplayinboatmove) { - PlayerConnectionUtils.ensureMainThread(packetplayinboatmove, this, this.player.getWorldServer()); - Entity entity = this.player.getVehicle(); - - if (entity instanceof EntityBoat) { - ((EntityBoat) entity).a(packetplayinboatmove.b(), packetplayinboatmove.c()); - } - - } - - @Override - public void a(IChatBaseComponent ichatbasecomponent) { - // CraftBukkit start - Rarely it would send a disconnect line twice - if (this.processedDisconnect) { - return; - } else { - this.processedDisconnect = true; - } - // CraftBukkit end - PlayerConnection.LOGGER.info("{} lost connection: {}", this.player.getDisplayName().getString(), ichatbasecomponent.getString()); - // CraftBukkit start - Replace vanilla quit message handling with our own. - /* - this.minecraftServer.invalidatePingSample(); - this.minecraftServer.getPlayerList().sendMessage((new ChatMessage("multiplayer.player.left", new Object[]{this.player.getScoreboardDisplayName()})).a(EnumChatFormat.YELLOW)); - */ - - this.player.n(); - String quitMessage = this.minecraftServer.getPlayerList().disconnect(this.player); - if ((quitMessage != null) && (quitMessage.length() > 0)) { - this.minecraftServer.getPlayerList().sendMessage(CraftChatMessage.fromString(quitMessage)); - } - // CraftBukkit end - if (this.isExemptPlayer()) { - PlayerConnection.LOGGER.info("Stopping singleplayer server as player logged out"); - this.minecraftServer.safeShutdown(false); - } - - } - - public void sendPacket(Packet packet) { - this.a(packet, (GenericFutureListener) null); - } - - public void a(Packet packet, @Nullable GenericFutureListener> genericfuturelistener) { - if (packet instanceof PacketPlayOutChat) { - PacketPlayOutChat packetplayoutchat = (PacketPlayOutChat) packet; - EnumChatVisibility enumchatvisibility = this.player.getChatFlags(); - - if (enumchatvisibility == EnumChatVisibility.HIDDEN && packetplayoutchat.d() != ChatMessageType.GAME_INFO) { - return; - } - - if (enumchatvisibility == EnumChatVisibility.SYSTEM && !packetplayoutchat.c()) { - return; - } - } - - // CraftBukkit start - if (packet == null || this.processedDisconnect) { // Spigot - return; - } else if (packet instanceof PacketPlayOutSpawnPosition) { - PacketPlayOutSpawnPosition packet6 = (PacketPlayOutSpawnPosition) packet; - this.player.compassTarget = new Location(this.getPlayer().getWorld(), packet6.position.getX(), packet6.position.getY(), packet6.position.getZ()); - } - // CraftBukkit end - - try { - this.networkManager.sendPacket(packet, genericfuturelistener); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Sending packet"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Packet being sent"); - - crashreportsystemdetails.a("Packet class", () -> { - return packet.getClass().getCanonicalName(); - }); - throw new ReportedException(crashreport); - } - } - - @Override - public void a(PacketPlayInHeldItemSlot packetplayinhelditemslot) { - PlayerConnectionUtils.ensureMainThread(packetplayinhelditemslot, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - if (packetplayinhelditemslot.b() >= 0 && packetplayinhelditemslot.b() < PlayerInventory.getHotbarSize()) { - PlayerItemHeldEvent event = new PlayerItemHeldEvent(this.getPlayer(), this.player.inventory.itemInHandIndex, packetplayinhelditemslot.b()); - this.server.getPluginManager().callEvent(event); - if (event.isCancelled()) { - this.sendPacket(new PacketPlayOutHeldItemSlot(this.player.inventory.itemInHandIndex)); - this.player.resetIdleTimer(); - return; - } - // CraftBukkit end - this.player.inventory.itemInHandIndex = packetplayinhelditemslot.b(); - this.player.resetIdleTimer(); - } else { - PlayerConnection.LOGGER.warn("{} tried to set an invalid carried item", this.player.getDisplayName().getString()); - this.disconnect("Invalid hotbar selection (Hacking?)"); // CraftBukkit - } - } - - @Override - public void a(PacketPlayInChat packetplayinchat) { - // CraftBukkit start - async chat - // SPIGOT-3638 - if (this.minecraftServer.isStopped()) { - return; - } - - boolean isSync = packetplayinchat.b().startsWith("/"); - if (packetplayinchat.b().startsWith("/")) { - PlayerConnectionUtils.ensureMainThread(packetplayinchat, this, this.player.getWorldServer()); - } - // CraftBukkit end - if (this.player.dead || this.player.getChatFlags() == EnumChatVisibility.HIDDEN) { // CraftBukkit - dead men tell no tales - this.sendPacket(new PacketPlayOutChat((new ChatMessage("chat.cannotSend", new Object[0])).a(EnumChatFormat.RED))); - } else { - this.player.resetIdleTimer(); - String s = packetplayinchat.b(); - - s = StringUtils.normalizeSpace(s); - - 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(new ChatMessage("multiplayer.disconnect.illegal_characters", new Object[0])); - return null; - } - }; - - this.minecraftServer.processQueue.add(waitable); - - try { - waitable.get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (ExecutionException e) { - throw new RuntimeException(e); - } - } else { - this.disconnect(new ChatMessage("multiplayer.disconnect.illegal_characters", new Object[0])); - } - // 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()) { - LOGGER.warn(this.player.getName() + " tried to send an empty message"); - } else if (getPlayer().isConversing()) { - final String conversationInput = s; - this.minecraftServer.processQueue.add(new Runnable() { - @Override - public void run() { - getPlayer().acceptConversationInput(conversationInput); - } - }); - } else if (this.player.getChatFlags() == EnumChatVisibility.SYSTEM) { // Re-add "Command Only" flag check - ChatMessage chatmessage = new ChatMessage("chat.cannotSend", new Object[0]); - - chatmessage.getChatModifier().setColor(EnumChatFormat.RED); - this.sendPacket(new PacketPlayOutChat(chatmessage)); - } else if (true) { - this.chat(s, true); - // CraftBukkit end - the below is for reference. :) - } else { - ChatMessage chatmessage = new ChatMessage("chat.type.text", new Object[]{this.player.getScoreboardDisplayName(), s}); - - this.minecraftServer.getPlayerList().sendMessage(chatmessage, false); - } - - // 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(new ChatMessage("disconnect.spam", new Object[0])); - return null; - } - }; - - this.minecraftServer.processQueue.add(waitable); - - try { - waitable.get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (ExecutionException e) { - throw new RuntimeException(e); - } - } else { - this.disconnect(new ChatMessage("disconnect.spam", new Object[0])); - } - // CraftBukkit end - } - - } - } - - // CraftBukkit start - add method - public void chat(String s, boolean async) { - if (s.isEmpty() || this.player.getChatFlags() == EnumChatVisibility.HIDDEN) { - return; - } - - if (!async && s.startsWith("/")) { - // Paper Start - if (!org.spigotmc.AsyncCatcher.shuttingDown && !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.processQueue.add(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()); - } - } - // Paper End - this.handleCommand(s); - } else if (this.player.getChatFlags() == EnumChatVisibility.SYSTEM) { - // Do nothing, this is coming from a plugin - } else { - Player player = this.getPlayer(); - AsyncPlayerChatEvent event = new AsyncPlayerChatEvent(async, player, s, new LazyPlayerSet(minecraftServer)); - 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 (Object player : PlayerConnection.this.minecraftServer.getPlayerList().players) { - ((EntityPlayer) player).sendMessage(CraftChatMessage.fromString(message)); - } - } else { - for (Player player : queueEvent.getRecipients()) { - player.sendMessage(message); - } - } - return null; - }}; - if (async) { - minecraftServer.processQueue.add(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; - } - - // Paper Start - (Meh) Support for vanilla world scoreboard name coloring - String displayName = event.getPlayer().getDisplayName(); - if (this.player.getWorld().paperConfig.useVanillaScoreboardColoring) { - IChatBaseComponent nameFromTeam = ScoreboardTeam.a(this.player.getScoreboardTeam(),((CraftPlayer) player).getHandle().getDisplayName()); - // Explicitly add a RESET here, vanilla uses components for this now... - displayName = CraftChatMessage.fromComponent(nameFromTeam, EnumChatFormat.WHITE) + org.bukkit.ChatColor.RESET; - } - - s = String.format(event.getFormat(), displayName, event.getMessage()); - // Paper end - minecraftServer.console.sendMessage(s); - if (((LazyPlayerSet) event.getRecipients()).isLazy()) { - for (Object recipient : minecraftServer.getPlayerList().players) { - ((EntityPlayer) recipient).sendMessage(CraftChatMessage.fromString(s)); - } - } else { - for (Player recipient : event.getRecipients()) { - recipient.sendMessage(s); - } - } - } - } - } - // CraftBukkit end - - private void handleCommand(String s) { - MinecraftTimings.playerCommandTimer.startTiming(); // Paper - // CraftBukkit start - whole method - if ( org.spigotmc.SpigotConfig.logCommands ) // Spigot - this.LOGGER.info(this.player.getName() + " issued server command: " + s); - - CraftPlayer player = this.getPlayer(); - - PlayerCommandPreprocessEvent event = new PlayerCommandPreprocessEvent(player, s, new LazyPlayerSet(minecraftServer)); - this.server.getPluginManager().callEvent(event); - - if (event.isCancelled()) { - MinecraftTimings.playerCommandTimer.stopTiming(); // Paper - return; - } - - try { - if (this.server.dispatchCommand(event.getPlayer(), event.getMessage().substring(1))) { - return; - } - } 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); - return; - } finally { - MinecraftTimings.playerCommandTimer.stopTiming(); // Paper - } - // this.minecraftServer.getCommandDispatcher().a(this.player.getCommandListener(), s); - // CraftBukkit end - } - - @Override - public void a(PacketPlayInArmAnimation packetplayinarmanimation) { - PlayerConnectionUtils.ensureMainThread(packetplayinarmanimation, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - this.player.resetIdleTimer(); - // CraftBukkit start - Raytrace to look for 'rogue armswings' - float f1 = this.player.pitch; - float f2 = this.player.yaw; - double d0 = this.player.locX; - double d1 = this.player.locY + (double) this.player.getHeadHeight(); - double d2 = this.player.locZ; - 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 = player.playerInteractManager.getGameMode()== EnumGamemode.CREATIVE ? 5.0D : 4.5D; - Vec3D vec3d1 = vec3d.add((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); - MovingObjectPosition movingobjectposition = this.player.world.rayTrace(new RayTrace(vec3d, vec3d1, RayTrace.BlockCollisionOption.OUTLINE, RayTrace.FluidCollisionOption.NONE, player)); - - if (movingobjectposition == null || movingobjectposition.getType() != MovingObjectPosition.EnumMovingObjectType.BLOCK) { - CraftEventFactory.callPlayerInteractEvent(this.player, Action.LEFT_CLICK_AIR, this.player.inventory.getItemInHand(), EnumHand.MAIN_HAND); - } - - // Arm swing animation - PlayerAnimationEvent event = new PlayerAnimationEvent(this.getPlayer()); - this.server.getPluginManager().callEvent(event); - - if (event.isCancelled()) return; - // CraftBukkit end - this.player.a(packetplayinarmanimation.b()); - } - - @Override - public void a(PacketPlayInEntityAction packetplayinentityaction) { - PlayerConnectionUtils.ensureMainThread(packetplayinentityaction, this, this.player.getWorldServer()); - // CraftBukkit start - if (this.player.dead) return; - switch (packetplayinentityaction.c()) { - case START_SNEAKING: - case STOP_SNEAKING: - PlayerToggleSneakEvent event = new PlayerToggleSneakEvent(this.getPlayer(), packetplayinentityaction.c() == 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.c() == PacketPlayInEntityAction.EnumPlayerAction.START_SPRINTING); - this.server.getPluginManager().callEvent(e2); - - if (e2.isCancelled()) { - return; - } - break; - } - // CraftBukkit end - this.player.resetIdleTimer(); - IJumpable ijumpable; - - switch (packetplayinentityaction.c()) { - case START_SNEAKING: - this.player.setSneaking(true); - - // Paper start - Hang on! - if (this.player.world.paperConfig.parrotsHangOnBetter) { - this.player.releaseShoulderEntities(); - } - // Paper end - - break; - case STOP_SNEAKING: - this.player.setSneaking(false); - break; - case START_SPRINTING: - this.player.setSprinting(true); - break; - case STOP_SPRINTING: - this.player.setSprinting(false); - break; - case STOP_SLEEPING: - if (this.player.isSleeping()) { - this.player.wakeup(false, true, true); - this.teleportPos = new Vec3D(this.player.locX, this.player.locY, this.player.locZ); - } - break; - case START_RIDING_JUMP: - if (this.player.getVehicle() instanceof IJumpable) { - ijumpable = (IJumpable) this.player.getVehicle(); - int i = packetplayinentityaction.d(); - - if (ijumpable.F_() && i > 0) { - ijumpable.b(i); - } - } - break; - case STOP_RIDING_JUMP: - if (this.player.getVehicle() instanceof IJumpable) { - ijumpable = (IJumpable) this.player.getVehicle(); - ijumpable.c(); - } - break; - case OPEN_INVENTORY: - if (this.player.getVehicle() instanceof EntityHorseAbstract) { - ((EntityHorseAbstract) this.player.getVehicle()).e((EntityHuman) this.player); - } - break; - case START_FALL_FLYING: - if (!this.player.onGround && this.player.getMot().y < 0.0D && !this.player.isGliding() && !this.player.isInWater()) { - ItemStack itemstack = this.player.getEquipment(EnumItemSlot.CHEST); - - if (itemstack.getItem() == Items.ELYTRA && ItemElytra.e(itemstack)) { - this.player.J(); - } - } else { - this.player.K(); - } - break; - default: - throw new IllegalArgumentException("Invalid client command!"); - } - - } - - @Override - public void a(PacketPlayInUseEntity packetplayinuseentity) { - PlayerConnectionUtils.ensureMainThread(packetplayinuseentity, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); - Entity entity = packetplayinuseentity.a((World) worldserver); - // Spigot Start - if ( entity == player && !player.isSpectator() ) - { - disconnect( "Cannot interact with self!" ); - return; - } - // Spigot End - - this.player.resetIdleTimer(); - if (entity != null) { - boolean flag = this.player.hasLineOfSight(entity); - double d0 = 36.0D; - - if (!flag) { - d0 = 9.0D; - } - - if (this.player.h(entity) < d0) { - EnumHand enumhand; - - ItemStack itemInHand = this.player.b(packetplayinuseentity.c() == null ? EnumHand.MAIN_HAND : packetplayinuseentity.c()); // CraftBukkit - - if (packetplayinuseentity.b() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT - || packetplayinuseentity.b() == 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.b() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT) { - event = new PlayerInteractEntityEvent((Player) this.getPlayer(), entity.getBukkitEntity(), (packetplayinuseentity.c() == EnumHand.OFF_HAND) ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND); - } else { - Vec3D target = packetplayinuseentity.d(); - event = new PlayerInteractAtEntityEvent((Player) this.getPlayer(), entity.getBukkitEntity(), new org.bukkit.util.Vector(target.x, target.y, target.z), (packetplayinuseentity.c() == EnumHand.OFF_HAND) ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND); - } - this.server.getPluginManager().callEvent(event); - - // Fish bucket - SPIGOT-4048 - if ((entity instanceof EntityFish && origItem != null && origItem.getItem() == Items.WATER_BUCKET) && (event.isCancelled() || this.player.inventory.getItemInHand() == null || this.player.inventory.getItemInHand().getItem() != origItem)) { - this.sendPacket(new PacketPlayOutSpawnEntityLiving((EntityFish) entity)); - this.player.updateInventory(this.player.activeContainer); - } - - if (triggerLeashUpdate && (event.isCancelled() || this.player.inventory.getItemInHand() == null || this.player.inventory.getItemInHand().getItem() != origItem)) { - // Refresh the current leash state - this.sendPacket(new PacketPlayOutAttachEntity(entity, ((EntityInsentient) entity).getLeashHolder())); - } - - if (event.isCancelled() || this.player.inventory.getItemInHand() == null || this.player.inventory.getItemInHand().getItem() != origItem) { - // Refresh the current entity metadata - entity.tracker.broadcast(new PacketPlayOutEntityMetadata(entity.getId(), entity.datawatcher, true)); // Paper - update entity for all players - } - - if (event.isCancelled()) { - this.player.updateInventory(this.player.activeContainer); // Paper - Refresh player inventory - return; - } - // CraftBukkit end - } - - if (packetplayinuseentity.b() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT) { - enumhand = packetplayinuseentity.c(); - this.player.a(entity, enumhand); - // CraftBukkit start - if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { - this.player.updateInventory(this.player.activeContainer); - } - // CraftBukkit end - } else if (packetplayinuseentity.b() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT_AT) { - enumhand = packetplayinuseentity.c(); - entity.a((EntityHuman) this.player, packetplayinuseentity.d(), enumhand); - // CraftBukkit start - if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { - this.player.updateInventory(this.player.activeContainer); - } - // CraftBukkit end - } else if (packetplayinuseentity.b() == PacketPlayInUseEntity.EnumEntityUseAction.ATTACK) { - if (entity instanceof EntityItem || entity instanceof EntityExperienceOrb || entity instanceof EntityArrow || (entity == this.player && !player.isSpectator())) { // CraftBukkit - this.disconnect(new ChatMessage("multiplayer.disconnect.invalid_entity_attacked", new Object[0])); - this.minecraftServer.warning("Player " + this.player.getDisplayName().getString() + " tried to attack an invalid entity"); - return; - } - - this.player.attack(entity); - - // CraftBukkit start - if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { - this.player.updateInventory(this.player.activeContainer); - } - // CraftBukkit end - } - } - } - // Paper start - fire event - else { - this.server.getPluginManager().callEvent(new com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent( - this.getPlayer(), - packetplayinuseentity.getEntityId(), - packetplayinuseentity.b() == PacketPlayInUseEntity.EnumEntityUseAction.ATTACK, - packetplayinuseentity.c() == EnumHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND - )); - } - // Paper end - - } - - @Override - public void a(PacketPlayInClientCommand packetplayinclientcommand) { - PlayerConnectionUtils.ensureMainThread(packetplayinclientcommand, this, this.player.getWorldServer()); - this.player.resetIdleTimer(); - PacketPlayInClientCommand.EnumClientCommand packetplayinclientcommand_enumclientcommand = packetplayinclientcommand.b(); - - switch (packetplayinclientcommand_enumclientcommand) { - case PERFORM_RESPAWN: - if (this.player.viewingCredits) { - this.player.viewingCredits = false; - this.player = this.minecraftServer.getPlayerList().moveToWorld(this.player, DimensionManager.OVERWORLD, true); - CriterionTriggers.v.a(this.player, DimensionManager.THE_END, DimensionManager.OVERWORLD); - } else { - if (this.player.getHealth() > 0.0F) { - return; - } - - this.player = this.minecraftServer.getPlayerList().moveToWorld(this.player, DimensionManager.OVERWORLD, false); - if (this.minecraftServer.isHardcore()) { - this.player.a(EnumGamemode.SPECTATOR); - ((GameRules.GameRuleBoolean) this.player.getWorldServer().getGameRules().get(GameRules.SPECTATORS_GENERATE_CHUNKS)).a(false, this.minecraftServer); - } - } - break; - case REQUEST_STATS: - this.player.getStatisticManager().a(this.player); - } - - } - - @Override - public void a(PacketPlayInCloseWindow packetplayinclosewindow) { - PlayerConnectionUtils.ensureMainThread(packetplayinclosewindow, this, this.player.getWorldServer()); - - if (this.player.isFrozen()) return; // CraftBukkit - CraftEventFactory.handleInventoryCloseEvent(this.player, org.bukkit.event.inventory.InventoryCloseEvent.Reason.PLAYER); // CraftBukkit // Paper - - this.player.m(); - } - - @Override - public void a(PacketPlayInWindowClick packetplayinwindowclick) { - PlayerConnectionUtils.ensureMainThread(packetplayinwindowclick, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - this.player.resetIdleTimer(); - if (this.player.activeContainer.windowId == packetplayinwindowclick.b() && this.player.activeContainer.c(this.player) && this.player.activeContainer.canUse(this.player)) { // CraftBukkit - boolean cancelled = this.player.isSpectator(); // CraftBukkit - see below if - if (false/*this.player.isSpectator()*/) { // CraftBukkit - NonNullList nonnulllist = NonNullList.a(); - - for (int i = 0; i < this.player.activeContainer.slots.size(); ++i) { - nonnulllist.add(((Slot) this.player.activeContainer.slots.get(i)).getItem()); - } - - this.player.a(this.player.activeContainer, nonnulllist); - } else { - // CraftBukkit start - Call InventoryClickEvent - if (packetplayinwindowclick.c() < -1 && packetplayinwindowclick.c() != -999) { - return; - } - - InventoryView inventory = this.player.activeContainer.getBukkitView(); - SlotType type = inventory.getSlotType(packetplayinwindowclick.c()); - - InventoryClickEvent event; - ClickType click = ClickType.UNKNOWN; - InventoryAction action = InventoryAction.UNKNOWN; - - ItemStack itemstack = ItemStack.a; - - switch (packetplayinwindowclick.g()) { - case PICKUP: - if (packetplayinwindowclick.d() == 0) { - click = ClickType.LEFT; - } else if (packetplayinwindowclick.d() == 1) { - click = ClickType.RIGHT; - } - if (packetplayinwindowclick.d() == 0 || packetplayinwindowclick.d() == 1) { - action = InventoryAction.NOTHING; // Don't want to repeat ourselves - if (packetplayinwindowclick.c() == -999) { - if (!player.inventory.getCarried().isEmpty()) { - action = packetplayinwindowclick.d() == 0 ? InventoryAction.DROP_ALL_CURSOR : InventoryAction.DROP_ONE_CURSOR; - } - } else if (packetplayinwindowclick.c() < 0) { - action = InventoryAction.NOTHING; - } else { - Slot slot = this.player.activeContainer.getSlot(packetplayinwindowclick.c()); - if (slot != null) { - ItemStack clickedItem = slot.getItem(); - ItemStack cursor = player.inventory.getCarried(); - if (clickedItem.isEmpty()) { - if (!cursor.isEmpty()) { - action = packetplayinwindowclick.d() == 0 ? InventoryAction.PLACE_ALL : InventoryAction.PLACE_ONE; - } - } else if (slot.isAllowed(player)) { - if (cursor.isEmpty()) { - action = packetplayinwindowclick.d() == 0 ? InventoryAction.PICKUP_ALL : InventoryAction.PICKUP_HALF; - } else if (slot.isAllowed(cursor)) { - if (clickedItem.doMaterialsMatch(cursor) && ItemStack.equals(clickedItem, cursor)) { - int toPlace = packetplayinwindowclick.d() == 0 ? cursor.getCount() : 1; - toPlace = Math.min(toPlace, clickedItem.getMaxStackSize() - clickedItem.getCount()); - toPlace = Math.min(toPlace, slot.inventory.getMaxStackSize() - clickedItem.getCount()); - if (toPlace == 1) { - action = InventoryAction.PLACE_ONE; - } else if (toPlace == cursor.getCount()) { - 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.getCount() <= slot.getMaxStackSize()) { - action = InventoryAction.SWAP_WITH_CURSOR; - } - } else if (cursor.getItem() == clickedItem.getItem() && ItemStack.equals(cursor, clickedItem)) { - if (clickedItem.getCount() >= 0) { - if (clickedItem.getCount() + cursor.getCount() <= cursor.getMaxStackSize()) { - // As of 1.5, this is result slots only - action = InventoryAction.PICKUP_ALL; - } - } - } - } - } - } - } - break; - // TODO check on updates - case QUICK_MOVE: - if (packetplayinwindowclick.d() == 0) { - click = ClickType.SHIFT_LEFT; - } else if (packetplayinwindowclick.d() == 1) { - click = ClickType.SHIFT_RIGHT; - } - if (packetplayinwindowclick.d() == 0 || packetplayinwindowclick.d() == 1) { - if (packetplayinwindowclick.c() < 0) { - action = InventoryAction.NOTHING; - } else { - Slot slot = this.player.activeContainer.getSlot(packetplayinwindowclick.c()); - if (slot != null && slot.isAllowed(this.player) && slot.hasItem()) { - action = InventoryAction.MOVE_TO_OTHER_INVENTORY; - } else { - action = InventoryAction.NOTHING; - } - } - } - break; - case SWAP: - if (packetplayinwindowclick.d() >= 0 && packetplayinwindowclick.d() < 9) { - click = ClickType.NUMBER_KEY; - Slot clickedSlot = this.player.activeContainer.getSlot(packetplayinwindowclick.c()); - if (clickedSlot.isAllowed(player)) { - ItemStack hotbar = this.player.inventory.getItem(packetplayinwindowclick.d()); - boolean canCleanSwap = hotbar.isEmpty() || (clickedSlot.inventory == player.inventory && clickedSlot.isAllowed(hotbar)); // the slot will accept the hotbar item - if (clickedSlot.hasItem()) { - if (canCleanSwap) { - action = InventoryAction.HOTBAR_SWAP; - } else { - action = InventoryAction.HOTBAR_MOVE_AND_READD; - } - } else if (!clickedSlot.hasItem() && !hotbar.isEmpty() && clickedSlot.isAllowed(hotbar)) { - action = InventoryAction.HOTBAR_SWAP; - } else { - action = InventoryAction.NOTHING; - } - } else { - action = InventoryAction.NOTHING; - } - } - break; - case CLONE: - if (packetplayinwindowclick.d() == 2) { - click = ClickType.MIDDLE; - if (packetplayinwindowclick.c() < 0) { - action = InventoryAction.NOTHING; - } else { - Slot slot = this.player.activeContainer.getSlot(packetplayinwindowclick.c()); - if (slot != null && slot.hasItem() && player.abilities.canInstantlyBuild && player.inventory.getCarried().isEmpty()) { - action = InventoryAction.CLONE_STACK; - } else { - action = InventoryAction.NOTHING; - } - } - } else { - click = ClickType.UNKNOWN; - action = InventoryAction.UNKNOWN; - } - break; - case THROW: - if (packetplayinwindowclick.c() >= 0) { - if (packetplayinwindowclick.d() == 0) { - click = ClickType.DROP; - Slot slot = this.player.activeContainer.getSlot(packetplayinwindowclick.c()); - if (slot != null && slot.hasItem() && slot.isAllowed(player) && !slot.getItem().isEmpty() && slot.getItem().getItem() != Item.getItemOf(Blocks.AIR)) { - action = InventoryAction.DROP_ONE_SLOT; - } else { - action = InventoryAction.NOTHING; - } - } else if (packetplayinwindowclick.d() == 1) { - click = ClickType.CONTROL_DROP; - Slot slot = this.player.activeContainer.getSlot(packetplayinwindowclick.c()); - if (slot != null && slot.hasItem() && slot.isAllowed(player) && !slot.getItem().isEmpty() && 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 (packetplayinwindowclick.d() == 1) { - click = ClickType.RIGHT; - } - action = InventoryAction.NOTHING; - } - break; - case QUICK_CRAFT: - itemstack = this.player.activeContainer.a(packetplayinwindowclick.c(), packetplayinwindowclick.d(), packetplayinwindowclick.g(), this.player); - break; - case PICKUP_ALL: - click = ClickType.DOUBLE_CLICK; - action = InventoryAction.NOTHING; - if (packetplayinwindowclick.c() >= 0 && !this.player.inventory.getCarried().isEmpty()) { - ItemStack cursor = this.player.inventory.getCarried(); - action = InventoryAction.NOTHING; - // Quick check for if we have any of the item - if (inventory.getTopInventory().contains(CraftMagicNumbers.getMaterial(cursor.getItem())) || inventory.getBottomInventory().contains(CraftMagicNumbers.getMaterial(cursor.getItem()))) { - action = InventoryAction.COLLECT_TO_CURSOR; - } - } - break; - default: - break; - } - - if (packetplayinwindowclick.g() != InventoryClickType.QUICK_CRAFT) { - if (click == ClickType.NUMBER_KEY) { - event = new InventoryClickEvent(inventory, type, packetplayinwindowclick.c(), click, action, packetplayinwindowclick.d()); - } else { - event = new InventoryClickEvent(inventory, type, packetplayinwindowclick.c(), click, action); - } - - org.bukkit.inventory.Inventory top = inventory.getTopInventory(); - if (packetplayinwindowclick.c() == 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, packetplayinwindowclick.c(), click, action, packetplayinwindowclick.d()); - } else { - event = new CraftItemEvent(recipe, inventory, type, packetplayinwindowclick.c(), click, action); - } - } - } - - event.setCancelled(cancelled); - Container oldContainer = this.player.activeContainer; // SPIGOT-1224 - server.getPluginManager().callEvent(event); - if (this.player.activeContainer != oldContainer) { - return; - } - - switch (event.getResult()) { - case ALLOW: - case DEFAULT: - itemstack = this.player.activeContainer.a(packetplayinwindowclick.c(), packetplayinwindowclick.d(), packetplayinwindowclick.g(), this.player); - break; - case DENY: - /* Needs enum constructor in InventoryAction - if (action.modifiesOtherSlots()) { - - } else { - if (action.modifiesCursor()) { - this.player.playerConnection.sendPacket(new Packet103SetSlot(-1, -1, this.player.inventory.getCarried())); - } - if (action.modifiesClicked()) { - this.player.playerConnection.sendPacket(new Packet103SetSlot(this.player.activeContainer.windowId, packet102windowclick.slot, this.player.activeContainer.getSlot(packet102windowclick.slot).getItem())); - } - }*/ - 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: - this.player.playerConnection.sendPacket(new PacketPlayOutSetSlot(-1, -1, this.player.inventory.getCarried())); - this.player.playerConnection.sendPacket(new PacketPlayOutSetSlot(this.player.activeContainer.windowId, packetplayinwindowclick.c(), this.player.activeContainer.getSlot(packetplayinwindowclick.c()).getItem())); - break; - // Modified clicked only - case DROP_ALL_SLOT: - case DROP_ONE_SLOT: - this.player.playerConnection.sendPacket(new PacketPlayOutSetSlot(this.player.activeContainer.windowId, packetplayinwindowclick.c(), this.player.activeContainer.getSlot(packetplayinwindowclick.c()).getItem())); - break; - // Modified cursor only - case DROP_ALL_CURSOR: - case DROP_ONE_CURSOR: - case CLONE_STACK: - this.player.playerConnection.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.f(), itemstack)) { - this.player.playerConnection.sendPacket(new PacketPlayOutTransaction(packetplayinwindowclick.b(), packetplayinwindowclick.e(), true)); - this.player.e = true; - this.player.activeContainer.c(); - this.player.broadcastCarriedItem(); - this.player.e = false; - } else { - this.k.put(this.player.activeContainer.windowId, packetplayinwindowclick.e()); - this.player.playerConnection.sendPacket(new PacketPlayOutTransaction(packetplayinwindowclick.b(), packetplayinwindowclick.e(), false)); - this.player.activeContainer.a(this.player, false); - NonNullList nonnulllist1 = NonNullList.a(); - - for (int j = 0; j < this.player.activeContainer.slots.size(); ++j) { - ItemStack itemstack1 = ((Slot) this.player.activeContainer.slots.get(j)).getItem(); - - nonnulllist1.add(itemstack1.isEmpty() ? ItemStack.a : itemstack1); - } - - this.player.a(this.player.activeContainer, nonnulllist1); - } - } - } - - } - - @Override - public void a(PacketPlayInAutoRecipe packetplayinautorecipe) { - PlayerConnectionUtils.ensureMainThread(packetplayinautorecipe, this, this.player.getWorldServer()); - this.player.resetIdleTimer(); - if (!this.player.isSpectator() && this.player.activeContainer.windowId == packetplayinautorecipe.b() && this.player.activeContainer.c(this.player) && this.player.activeContainer instanceof ContainerRecipeBook) { - this.minecraftServer.getCraftingManager().a(packetplayinautorecipe.c()).ifPresent((irecipe) -> { - ((ContainerRecipeBook) this.player.activeContainer).a(packetplayinautorecipe.d(), irecipe, this.player); - }); - } - } - - @Override - public void a(PacketPlayInEnchantItem packetplayinenchantitem) { - PlayerConnectionUtils.ensureMainThread(packetplayinenchantitem, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - this.player.resetIdleTimer(); - if (this.player.activeContainer.windowId == packetplayinenchantitem.b() && this.player.activeContainer.c(this.player) && !this.player.isSpectator()) { - this.player.activeContainer.a((EntityHuman) this.player, packetplayinenchantitem.c()); - this.player.activeContainer.c(); - } - - } - - @Override - public void a(PacketPlayInSetCreativeSlot packetplayinsetcreativeslot) { - PlayerConnectionUtils.ensureMainThread(packetplayinsetcreativeslot, this, this.player.getWorldServer()); - if (this.player.playerInteractManager.isCreative()) { - boolean flag = packetplayinsetcreativeslot.b() < 0; - ItemStack itemstack = packetplayinsetcreativeslot.getItemStack(); - NBTTagCompound nbttagcompound = itemstack.b("BlockEntityTag"); - - if (!itemstack.isEmpty() && nbttagcompound != null && nbttagcompound.hasKey("x") && nbttagcompound.hasKey("y") && nbttagcompound.hasKey("z") && this.player.getBukkitEntity().hasPermission("minecraft.nbt.copy")) { // Spigot - 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 = tileentity.save(new NBTTagCompound()); - - nbttagcompound1.remove("x"); - nbttagcompound1.remove("y"); - nbttagcompound1.remove("z"); - itemstack.a("BlockEntityTag", (NBTBase) nbttagcompound1); - } - } - - boolean flag1 = packetplayinsetcreativeslot.b() >= 1 && packetplayinsetcreativeslot.b() <= 45; - boolean flag2 = itemstack.isEmpty() || itemstack.getDamage() >= 0 && itemstack.getCount() <= 64 && !itemstack.isEmpty(); - if (flag || (flag1 && !ItemStack.matches(this.player.defaultContainer.getSlot(packetplayinsetcreativeslot.b()).getItem(), packetplayinsetcreativeslot.getItemStack()))) { // Insist on valid slot - // CraftBukkit start - Call click event - InventoryView inventory = this.player.defaultContainer.getBukkitView(); - org.bukkit.inventory.ItemStack item = CraftItemStack.asBukkitCopy(packetplayinsetcreativeslot.getItemStack()); - - SlotType type = SlotType.QUICKBAR; - if (flag) { - type = SlotType.OUTSIDE; - } else if (packetplayinsetcreativeslot.b() < 36) { - if (packetplayinsetcreativeslot.b() >= 5 && packetplayinsetcreativeslot.b() < 9) { - type = SlotType.ARMOR; - } else { - type = SlotType.CONTAINER; - } - } - InventoryCreativeEvent event = new InventoryCreativeEvent(inventory, type, flag ? -999 : packetplayinsetcreativeslot.b(), item); - server.getPluginManager().callEvent(event); - - itemstack = CraftItemStack.asNMSCopy(event.getCursor()); - - switch (event.getResult()) { - case ALLOW: - // Plugin cleared the id / stacksize checks - flag2 = true; - break; - case DEFAULT: - break; - case DENY: - // Reset the slot - if (packetplayinsetcreativeslot.b() >= 0) { - this.player.playerConnection.sendPacket(new PacketPlayOutSetSlot(this.player.defaultContainer.windowId, packetplayinsetcreativeslot.b(), this.player.defaultContainer.getSlot(packetplayinsetcreativeslot.b()).getItem())); - this.player.playerConnection.sendPacket(new PacketPlayOutSetSlot(-1, -1, ItemStack.a)); - } - return; - } - } - // CraftBukkit end - - if (flag1 && flag2) { - if (itemstack.isEmpty()) { - this.player.defaultContainer.setItem(packetplayinsetcreativeslot.b(), ItemStack.a); - } else { - this.player.defaultContainer.setItem(packetplayinsetcreativeslot.b(), itemstack); - } - - this.player.defaultContainer.a(this.player, true); - this.player.defaultContainer.c(); - } else if (flag && flag2 && this.j < 200) { - this.j += 20; - EntityItem entityitem = this.player.drop(itemstack, true); - - if (entityitem != null) { - entityitem.f(); - } - } - } - - } - - @Override - public void a(PacketPlayInTransaction packetplayintransaction) { - PlayerConnectionUtils.ensureMainThread(packetplayintransaction, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - int i = this.player.activeContainer.windowId; - - if (i == packetplayintransaction.b() && this.k.getOrDefault(i, (short) (packetplayintransaction.c() + 1)) == packetplayintransaction.c() && !this.player.activeContainer.c(this.player) && !this.player.isSpectator()) { - this.player.activeContainer.a(this.player, true); - } - - } - - @Override - public void a(PacketPlayInUpdateSign packetplayinupdatesign) { - PlayerConnectionUtils.ensureMainThread(packetplayinupdatesign, this, this.player.getWorldServer()); - if (this.player.isFrozen()) return; // CraftBukkit - this.player.resetIdleTimer(); - WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); - BlockPosition blockposition = packetplayinupdatesign.b(); - - if (worldserver.isLoaded(blockposition)) { - IBlockData iblockdata = worldserver.getType(blockposition); - TileEntity tileentity = worldserver.getTileEntity(blockposition); - - if (!(tileentity instanceof TileEntitySign)) { - return; - } - - TileEntitySign tileentitysign = (TileEntitySign) tileentity; - - if (!tileentitysign.d() || tileentitysign.signEditor == null || !tileentitysign.signEditor.equals(this.player.getUniqueID())) { - this.minecraftServer.warning("Player " + this.player.getDisplayName().getString() + " just tried to change non-editable sign"); - this.sendPacket(tileentity.getUpdatePacket()); // CraftBukkit - return; - } - - String[] astring = packetplayinupdatesign.c(); - - // CraftBukkit start - Player player = this.server.getPlayer(this.player); - int x = packetplayinupdatesign.b().getX(); - int y = packetplayinupdatesign.b().getY(); - int z = packetplayinupdatesign.b().getZ(); - String[] lines = new String[4]; - - for (int i = 0; i < astring.length; ++i) { - // Paper start - cap line length - modified clients can send longer data than normal - if (MAX_SIGN_LINE_LENGTH > 0 && astring[i].length() > MAX_SIGN_LINE_LENGTH) { - // This handles multibyte characters as 1 - int offset = astring[i].codePoints().limit(MAX_SIGN_LINE_LENGTH).map(Character::charCount).sum(); - if (offset < astring[i].length()) { - astring[i] = astring[i].substring(0, offset); - } - } - // Paper end - lines[i] = SharedConstants.a(astring[i]); //Paper - Replaced with anvil color stripping method to stop exploits that allow colored signs to be created. - } - SignChangeEvent event = new SignChangeEvent((org.bukkit.craftbukkit.block.CraftBlock) player.getWorld().getBlockAt(x, y, z), 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, iblockdata, iblockdata, 3); - } - - } - - @Override - public void a(PacketPlayInKeepAlive packetplayinkeepalive) { - //PlayerConnectionUtils.ensureMainThread(packetplayinkeepalive, this, this.player.getWorldServer()); // CraftBukkit // Paper - This shouldn't be on the main thread - if (this.awaitingKeepAlive && packetplayinkeepalive.b() == this.h) { - int i = (int) (SystemUtils.getMonotonicMillis() - this.lastKeepAlive); - - this.player.ping = (this.player.ping * 3 + i) / 4; - this.awaitingKeepAlive = false; - } else if (!this.isExemptPlayer()) { - // Paper start - This needs to be handled on the main thread for plugins - minecraftServer.scheduleOnMain(() -> { - this.disconnect(new ChatMessage("disconnect.timeout")); - }); - // Paper end - } - - } - - @Override - public void a(PacketPlayInAbilities packetplayinabilities) { - PlayerConnectionUtils.ensureMainThread(packetplayinabilities, this, this.player.getWorldServer()); - // 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 - } - - @Override - public void a(PacketPlayInSettings packetplayinsettings) { - PlayerConnectionUtils.ensureMainThread(packetplayinsettings, this, this.player.getWorldServer()); - this.player.a(packetplayinsettings); - } - - // CraftBukkit start - private static final MinecraftKey CUSTOM_REGISTER = new MinecraftKey("register"); - private static final MinecraftKey CUSTOM_UNREGISTER = new MinecraftKey("unregister"); - - @Override - public void a(PacketPlayInCustomPayload packetplayincustompayload) { - PlayerConnectionUtils.ensureMainThread(packetplayincustompayload, this, this.player.getWorldServer()); - if (packetplayincustompayload.tag.equals(CUSTOM_REGISTER)) { - try { - String channels = packetplayincustompayload.data.toString(com.google.common.base.Charsets.UTF_8); - for (String channel : channels.split("\0")) { - getPlayer().addChannel(channel); - } - } catch (Exception ex) { - PlayerConnection.LOGGER.error("Couldn\'t register custom payload", ex); - this.disconnect("Invalid payload REGISTER!"); - } - } else if (packetplayincustompayload.tag.equals(CUSTOM_UNREGISTER)) { - try { - String channels = packetplayincustompayload.data.toString(com.google.common.base.Charsets.UTF_8); - for (String channel : channels.split("\0")) { - getPlayer().removeChannel(channel); - } - } catch (Exception ex) { - PlayerConnection.LOGGER.error("Couldn\'t unregister custom payload", ex); - this.disconnect("Invalid payload UNREGISTER!"); - } - } else { - try { - byte[] data = new byte[packetplayincustompayload.data.readableBytes()]; - packetplayincustompayload.data.readBytes(data); - server.getMessenger().dispatchIncomingMessage(player.getBukkitEntity(), packetplayincustompayload.tag.toString(), data); - } catch (Exception ex) { - PlayerConnection.LOGGER.error("Couldn\'t dispatch custom payload", ex); - this.disconnect("Invalid custom payload!"); - } - } - - } - - public final boolean isDisconnected() { - return (!this.player.joining && !this.networkManager.isConnected()) || this.processedDisconnect; // Paper - } - // CraftBukkit end - - @Override - public void a(PacketPlayInDifficultyChange packetplayindifficultychange) { - PlayerConnectionUtils.ensureMainThread(packetplayindifficultychange, this, this.player.getWorldServer()); - if (this.player.k(2) || this.isExemptPlayer()) { - this.minecraftServer.a(packetplayindifficultychange.b(), false); - } - } - - @Override - public void a(PacketPlayInDifficultyLock packetplayindifficultylock) { - PlayerConnectionUtils.ensureMainThread(packetplayindifficultylock, this, this.player.getWorldServer()); - if (this.player.k(2) || this.isExemptPlayer()) { - this.minecraftServer.d(packetplayindifficultylock.b()); - } - } -} diff --git a/src/main/java/net/minecraft/server/PlayerConnectionUtils.java b/src/main/java/net/minecraft/server/PlayerConnectionUtils.java deleted file mode 100644 index e928525b8..000000000 --- a/src/main/java/net/minecraft/server/PlayerConnectionUtils.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.minecraft.server; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import co.aikar.timings.MinecraftTimings; // Paper -import co.aikar.timings.Timing; // Paper - -public class PlayerConnectionUtils { - - private static final Logger LOGGER = LogManager.getLogger(); - - public static void ensureMainThread(Packet packet, T t0, WorldServer worldserver) throws CancelledPacketHandleException { - ensureMainThread(packet, t0, (IAsyncTaskHandler) worldserver.getMinecraftServer()); - } - - public static void ensureMainThread(Packet packet, T t0, IAsyncTaskHandler iasynctaskhandler) throws CancelledPacketHandleException { - if (!iasynctaskhandler.isMainThread()) { - Timing timing = MinecraftTimings.getPacketTiming(packet); // Paper - timings - iasynctaskhandler.execute(() -> { - if (MinecraftServer.getServer().hasStopped() || (t0 instanceof PlayerConnection && ((PlayerConnection) t0).processedDisconnect)) return; // CraftBukkit, MC-142590 - if (t0.a().isConnected()) { - try (Timing ignored = timing.startTiming()) { // Paper - timings - packet.a(t0); - } // Paper - timings - } else { - PlayerConnectionUtils.LOGGER.debug("Ignoring packet due to disconnection: " + packet); - } - - }); - throw CancelledPacketHandleException.INSTANCE; - } - } -} diff --git a/src/main/java/net/minecraft/server/PlayerInteractManager.java b/src/main/java/net/minecraft/server/PlayerInteractManager.java deleted file mode 100644 index bc03a82b7..000000000 --- a/src/main/java/net/minecraft/server/PlayerInteractManager.java +++ /dev/null @@ -1,510 +0,0 @@ -package net.minecraft.server; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -// CraftBukkit start -import java.util.ArrayList; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.Event; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -// CraftBukkit end - -public class PlayerInteractManager { - - private static final Logger LOGGER = LogManager.getLogger(); - public WorldServer world; - public EntityPlayer player; - private EnumGamemode gamemode; - private boolean e; - private int lastDigTick; - private BlockPosition g; - private int currentTick; - private boolean i; - private BlockPosition j; - private int k; - private int l; - - public PlayerInteractManager(WorldServer worldserver) { - this.gamemode = EnumGamemode.NOT_SET; - this.g = BlockPosition.ZERO; - this.j = BlockPosition.ZERO; - this.l = -1; - this.world = worldserver; - } - - public void setGameMode(EnumGamemode enumgamemode) { - this.gamemode = enumgamemode; - enumgamemode.a(this.player.abilities); - this.player.updateAbilities(); - this.player.server.getPlayerList().sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_GAME_MODE, new EntityPlayer[]{this.player}), this.player); // CraftBukkit - this.world.everyoneSleeping(); - } - - public EnumGamemode getGameMode() { - return this.gamemode; - } - - public boolean c() { - return this.gamemode.f(); - } - - public boolean isCreative() { - return this.gamemode.isCreative(); - } - - public void b(EnumGamemode enumgamemode) { - if (this.gamemode == EnumGamemode.NOT_SET) { - this.gamemode = enumgamemode; - } - - this.setGameMode(this.gamemode); - } - - public void a() { - this.currentTick = MinecraftServer.currentTick; // CraftBukkit; - IBlockData iblockdata; - - if (this.i) { - iblockdata = this.world.getType(this.j); - if (iblockdata.isAir()) { - this.i = false; - } else { - float f = this.a(iblockdata, this.j); - - if (f >= 1.0F) { - this.i = false; - this.breakBlock(this.j); - } - } - } else if (this.e) { - iblockdata = this.world.getType(this.g); - if (iblockdata.isAir()) { - this.world.a(this.player.getId(), this.g, -1); - this.l = -1; - this.e = false; - } else { - this.a(iblockdata, this.g); - } - } - - } - - private float a(IBlockData iblockdata, BlockPosition blockposition) { - int i = this.currentTick - this.k; - float f = iblockdata.getDamage(this.player, this.player.world, blockposition) * (float) (i + 1); - int j = (int) (f * 10.0F); - - if (j != this.l) { - this.world.a(this.player.getId(), blockposition, j); - this.l = j; - } - - return f; - } - - public void a(BlockPosition blockposition, PacketPlayInBlockDig.EnumPlayerDigType packetplayinblockdig_enumplayerdigtype, EnumDirection enumdirection, int i) { - double d0 = this.player.locX - ((double) blockposition.getX() + 0.5D); - double d1 = this.player.locY - ((double) blockposition.getY() + 0.5D) + 1.5D; - double d2 = this.player.locZ - ((double) blockposition.getZ() + 0.5D); - double d3 = d0 * d0 + d1 * d1 + d2 * d2; - - if (d3 > 36.0D) { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, false)); - } else if (blockposition.getY() >= i) { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, false)); - } else { - IBlockData iblockdata; - - if (packetplayinblockdig_enumplayerdigtype == PacketPlayInBlockDig.EnumPlayerDigType.START_DESTROY_BLOCK) { - if (!this.world.a((EntityHuman) this.player, blockposition)) { - // CraftBukkit start - fire PlayerInteractEvent - CraftEventFactory.callPlayerInteractEvent(this.player, Action.LEFT_CLICK_BLOCK, blockposition, enumdirection, this.player.inventory.getItemInHand(), EnumHand.MAIN_HAND); - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, false)); - // Update any tile entity data for this block - TileEntity tileentity = world.getTileEntity(blockposition); - if (tileentity != null) { - this.player.playerConnection.sendPacket(tileentity.getUpdatePacket()); - } - // CraftBukkit end - return; - } - - // CraftBukkit start - PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(this.player, Action.LEFT_CLICK_BLOCK, blockposition, enumdirection, this.player.inventory.getItemInHand(), EnumHand.MAIN_HAND); - if (event.isCancelled()) { - // Let the client know the block still exists - // Paper start - brute force neighbor blocks for any attached blocks - for (EnumDirection dir : EnumDirection.values()) { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(world, blockposition.shift(dir))); - } - // Paper end - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); - // Update any tile entity data for this block - TileEntity tileentity = this.world.getTileEntity(blockposition); - if (tileentity != null) { - this.player.playerConnection.sendPacket(tileentity.getUpdatePacket()); - } - return; - } - // CraftBukkit end - - if (this.isCreative()) { - if (!this.world.douseFire((EntityHuman) null, blockposition, enumdirection)) { - this.a(blockposition, packetplayinblockdig_enumplayerdigtype); - } else { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, true)); - } - - return; - } - - if (this.player.a((World) this.world, blockposition, this.gamemode)) { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, false)); - return; - } - - // this.world.douseFire((EntityHuman) null, blockposition, enumdirection); // CraftBukkit - Moved down - this.lastDigTick = this.currentTick; - float f = 1.0F; - - iblockdata = this.world.getType(blockposition); - // 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. - IBlockData data = this.world.getType(blockposition); - if (data.getBlock() instanceof BlockDoor) { - // For some reason *BOTH* the bottom/top part have to be marked updated. - boolean bottom = data.get(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER; - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, bottom ? blockposition.up() : blockposition.down())); - } else if (data.getBlock() instanceof BlockTrapdoor) { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); - } - } else if (!iblockdata.isAir()) { - iblockdata.attack(this.world, blockposition, this.player); - f = iblockdata.getDamage(this.player, this.player.world, blockposition); - // Allow fire punching to be blocked - this.world.douseFire((EntityHuman) null, blockposition, enumdirection); - } - - if (event.useItemInHand() == Event.Result.DENY) { - // If we 'insta destroyed' then the client needs to be informed. - if (f > 1.0f) { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); - } - return; - } - org.bukkit.event.block.BlockDamageEvent blockEvent = CraftEventFactory.callBlockDamageEvent(this.player, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this.player.inventory.getItemInHand(), f >= 1.0f); - - if (blockEvent.isCancelled()) { - // Let the client know the block still exists - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); - return; - } - - if (blockEvent.getInstaBreak()) { - f = 2.0f; - } - // CraftBukkit end - - if (!iblockdata.isAir() && f >= 1.0F) { - this.a(blockposition, packetplayinblockdig_enumplayerdigtype); - } else { - this.e = true; - this.g = blockposition; - int j = (int) (f * 10.0F); - - this.world.a(this.player.getId(), blockposition, j); - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); // Paper - fixes MC-156852 - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, true)); - this.l = j; - } - } else if (packetplayinblockdig_enumplayerdigtype == PacketPlayInBlockDig.EnumPlayerDigType.STOP_DESTROY_BLOCK) { - if (blockposition.equals(this.g)) { - int k = this.currentTick - this.lastDigTick; - - iblockdata = this.world.getType(blockposition); - if (!iblockdata.isAir()) { - float f1 = iblockdata.getDamage(this.player, this.player.world, blockposition) * (float) (k + 1); - - if (f1 >= 0.7F) { - this.e = false; - this.world.a(this.player.getId(), blockposition, -1); - this.a(blockposition, packetplayinblockdig_enumplayerdigtype); - return; - } - - if (!this.i) { - this.e = false; - this.i = true; - this.j = blockposition; - this.k = this.lastDigTick; - } - } - } - - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, true)); - } else if (packetplayinblockdig_enumplayerdigtype == PacketPlayInBlockDig.EnumPlayerDigType.ABORT_DESTROY_BLOCK) { - this.e = false; - this.world.a(this.player.getId(), this.g, -1); - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, true)); - } - - } - - this.world.chunkPacketBlockController.onPlayerLeftClickBlock(this, blockposition, enumdirection); // Paper - Anti-Xray - } - - public void a(BlockPosition blockposition, PacketPlayInBlockDig.EnumPlayerDigType packetplayinblockdig_enumplayerdigtype) { - if (this.breakBlock(blockposition)) { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockBreak(blockposition, this.world.getType(blockposition), packetplayinblockdig_enumplayerdigtype, true)); - } else { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); // CraftBukkit - SPIGOT-5196 - } - - } - - public boolean breakBlock(BlockPosition blockposition) { - IBlockData iblockdata = this.world.getType(blockposition); - // CraftBukkit start - fire BlockBreakEvent - org.bukkit.block.Block bblock = CraftBlock.at(world, blockposition); - BlockBreakEvent event = null; - - if (this.player instanceof EntityPlayer) { - // Sword + Creative mode pre-cancel - boolean isSwordNoBreak = !this.player.getItemInMainHand().getItem().a(iblockdata, this.world, blockposition, (EntityHuman) this.player); - - // Tell client the block is gone immediately then process events - // Don't tell the client if its a creative sword break because its not broken! - if (world.getTileEntity(blockposition) == null && !isSwordNoBreak) { - PacketPlayOutBlockChange packet = new PacketPlayOutBlockChange(this.world, blockposition); - packet.block = Blocks.AIR.getBlockData(); - this.player.playerConnection.sendPacket(packet); - } - - event = new BlockBreakEvent(bblock, this.player.getBukkitEntity()); - - // Sword + Creative mode pre-cancel - event.setCancelled(isSwordNoBreak); - - // Calculate default block experience - IBlockData nmsData = this.world.getType(blockposition); - Block nmsBlock = nmsData.getBlock(); - - ItemStack itemstack = this.player.getEquipment(EnumItemSlot.MAINHAND); - - if (nmsBlock != null && !event.isCancelled() && !this.isCreative() && this.player.hasBlock(nmsBlock.getBlockData())) { - event.setExpToDrop(nmsBlock.getExpDrop(nmsData, this.world, blockposition, itemstack)); - } - - this.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - if (isSwordNoBreak) { - return false; - } - // Let the client know the block still exists - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); - - // Brute force all possible updates - for (EnumDirection dir : EnumDirection.values()) { - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(world, blockposition.shift(dir))); - } - - // Update any tile entity data for this block - TileEntity tileentity = this.world.getTileEntity(blockposition); - if (tileentity != null) { - this.player.playerConnection.sendPacket(tileentity.getUpdatePacket()); - } - return false; - } - } - // CraftBukkit end - - if (false && !this.player.getItemInMainHand().getItem().a(iblockdata, (World) this.world, blockposition, (EntityHuman) this.player)) { // CraftBukkit - false - return false; - } else { - iblockdata = this.world.getType(blockposition); // CraftBukkit - update state from plugins - if (iblockdata.isAir()) return false; // CraftBukkit - A plugin set block to air without cancelling - TileEntity tileentity = this.world.getTileEntity(blockposition); - Block block = iblockdata.getBlock(); - - if ((block instanceof BlockCommand || block instanceof BlockStructure || block instanceof BlockJigsaw) && !this.player.isCreativeAndOp()) { - this.world.notify(blockposition, iblockdata, iblockdata, 3); - return false; - } else if (this.player.a((World) this.world, blockposition, this.gamemode)) { - return false; - } else { - // CraftBukkit start - org.bukkit.block.BlockState state = bblock.getState(); - world.captureDrops = new ArrayList<>(); - // CraftBukkit end - block.a((World) this.world, blockposition, iblockdata, (EntityHuman) this.player); - boolean flag = this.world.a(blockposition, false); - - if (flag) { - block.postBreak(this.world, blockposition, iblockdata); - } - - if (this.isCreative()) { - // return true; // CraftBukkit - } else { - ItemStack itemstack = this.player.getItemInMainHand(); - boolean flag1 = this.player.hasBlock(iblockdata); - - ItemStack itemstack1 = flag && flag1 && event.isDropItems() && !itemstack.isEmpty() ? itemstack.cloneItemStack() : ItemStack.a; // Paper - MC-136865 - clone before use - itemstack.a(this.world, iblockdata, blockposition, this.player); - if (flag && flag1 && event.isDropItems()) { // CraftBukkit - Check if block should drop items - //ItemStack itemstack1 = itemstack.isEmpty() ? ItemStack.a : itemstack.cloneItemStack(); // Paper - MC-136865 - move up - - block.a(this.world, this.player, blockposition, iblockdata, tileentity, itemstack1); - } - - // return true; // CraftBukkit - } - // CraftBukkit start - if (event.isDropItems()) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockDropItemEvent(bblock, state, this.player, world.captureDrops); - } - world.captureDrops = null; - - // Drop event experience - if (flag && event != null) { - iblockdata.getBlock().dropExperience(this.world, blockposition, event.getExpToDrop(), this.player); // Paper - } - - return true; - // CraftBukkit end - } - } - } - - public EnumInteractionResult a(EntityHuman entityhuman, World world, ItemStack itemstack, EnumHand enumhand) { - if (this.gamemode == EnumGamemode.SPECTATOR) { - return EnumInteractionResult.PASS; - } else if (entityhuman.getCooldownTracker().hasCooldown(itemstack.getItem())) { - return EnumInteractionResult.PASS; - } else { - int i = itemstack.getCount(); - int j = itemstack.getDamage(); - InteractionResultWrapper interactionresultwrapper = itemstack.a(world, entityhuman, enumhand); - ItemStack itemstack1 = (ItemStack) interactionresultwrapper.b(); - - if (itemstack1 == itemstack && itemstack1.getCount() == i && itemstack1.k() <= 0 && itemstack1.getDamage() == j) { - return interactionresultwrapper.a(); - } else if (interactionresultwrapper.a() == EnumInteractionResult.FAIL && itemstack1.k() > 0 && !entityhuman.isHandRaised()) { - return interactionresultwrapper.a(); - } else { - entityhuman.a(enumhand, itemstack1); - if (this.isCreative()) { - itemstack1.setCount(i); - if (itemstack1.e()) { - itemstack1.setDamage(j); - } - } - - if (itemstack1.isEmpty()) { - entityhuman.a(enumhand, ItemStack.a); - } - - if (!entityhuman.isHandRaised()) { - ((EntityPlayer) entityhuman).updateInventory(entityhuman.defaultContainer); - } - - return interactionresultwrapper.a(); - } - } - } - - // CraftBukkit start - whole method - public boolean interactResult = false; - public boolean firedInteract = false; - public EnumInteractionResult a(EntityHuman entityhuman, World world, ItemStack itemstack, EnumHand enumhand, MovingObjectPositionBlock movingobjectpositionblock) { - BlockPosition blockposition = movingobjectpositionblock.getBlockPosition(); - IBlockData iblockdata = world.getType(blockposition); - EnumInteractionResult enuminteractionresult = EnumInteractionResult.PASS; - boolean cancelledBlock = false; - - if (this.gamemode == EnumGamemode.SPECTATOR) { - ITileInventory itileinventory = iblockdata.b(world, blockposition); - cancelledBlock = !(itileinventory instanceof ITileInventory); - } - - if (entityhuman.getCooldownTracker().hasCooldown(itemstack.getItem())) { - cancelledBlock = true; - } - - PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(entityhuman, Action.RIGHT_CLICK_BLOCK, blockposition, movingobjectpositionblock.getDirection(), itemstack, cancelledBlock, enumhand); - 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 (iblockdata.getBlock() instanceof BlockDoor) { - boolean bottom = iblockdata.get(BlockDoor.HALF) == BlockPropertyDoubleBlockHalf.LOWER; - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutBlockChange(world, bottom ? blockposition.up() : blockposition.down())); - } else if (iblockdata.getBlock() instanceof BlockCake) { - ((EntityPlayer) entityhuman).getBukkitEntity().sendHealthUpdate(); // SPIGOT-1341 - reset health for cake - // Paper start - extend Player Interact cancellation // TODO: consider merging this into the extracted method - } else if (iblockdata.getBlock() instanceof BlockStructure) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutCloseWindow()); - } else if (iblockdata.getBlock() instanceof BlockCommand) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutCloseWindow()); - } else if (iblockdata.getBlock() instanceof BlockFlowerPot) { - // Send a block change to air and then send back the correct block, just to make the client happy - PacketPlayOutBlockChange packet = new PacketPlayOutBlockChange(this.world, blockposition); - packet.block = Blocks.AIR.getBlockData(); - this.player.playerConnection.sendPacket(packet); - - this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); - - TileEntity tileentity = this.world.getTileEntity(blockposition); - if (tileentity != null) { - player.playerConnection.sendPacket(tileentity.getUpdatePacket()); - } - } - // Paper end - extend Player Interact cancellation - ((EntityPlayer) entityhuman).getBukkitEntity().updateInventory(); // SPIGOT-2867 - enuminteractionresult = (event.useItemInHand() != Event.Result.ALLOW) ? EnumInteractionResult.SUCCESS : EnumInteractionResult.PASS; - } else if (this.gamemode == EnumGamemode.SPECTATOR) { - ITileInventory itileinventory = iblockdata.b(world, blockposition); - - if (itileinventory != null) { - entityhuman.openContainer(itileinventory); - return EnumInteractionResult.SUCCESS; - } else { - return EnumInteractionResult.PASS; - } - } else { - boolean flag = !entityhuman.getItemInMainHand().isEmpty() || !entityhuman.getItemInOffHand().isEmpty(); - boolean flag1 = entityhuman.isSneaking() && flag; - - if (!flag1) { - enuminteractionresult = iblockdata.interact(world, entityhuman, enumhand, movingobjectpositionblock) ? EnumInteractionResult.SUCCESS : EnumInteractionResult.FAIL; - } - - if (!itemstack.isEmpty() && enuminteractionresult != EnumInteractionResult.SUCCESS && !interactResult) { // add !interactResult SPIGOT-764 - ItemActionContext itemactioncontext = new ItemActionContext(entityhuman, enumhand, movingobjectpositionblock); - - if (this.isCreative()) { - int i = itemstack.getCount(); - enuminteractionresult = itemstack.placeItem(itemactioncontext, enumhand); - - itemstack.setCount(i); - return enuminteractionresult; - } else { - return itemstack.placeItem(itemactioncontext, enumhand); - } - } - } - return enuminteractionresult; - // CraftBukkit end - } - - public void a(WorldServer worldserver) { - this.world = worldserver; - } -} diff --git a/src/main/java/net/minecraft/server/PlayerInventory.java b/src/main/java/net/minecraft/server/PlayerInventory.java deleted file mode 100644 index 4aee712a6..000000000 --- a/src/main/java/net/minecraft/server/PlayerInventory.java +++ /dev/null @@ -1,693 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableList; -import java.util.Iterator; -import java.util.List; -import java.util.function.Predicate; - -// CraftBukkit start -import java.util.ArrayList; -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -// CraftBukkit end - -public class PlayerInventory implements IInventory, INamableTileEntity { - - public final NonNullList items; - public final NonNullList armor; - public final NonNullList extraSlots; - private final List> f;List> getComponents() { return f; } // Paper - OBFHELPER - public int itemInHandIndex; - public final EntityHuman player; - private ItemStack carried; - private int h; - - // CraftBukkit start - add fields and methods - public List transaction = new java.util.ArrayList(); - private int maxStack = MAX_STACK; - - public List getContents() { - List combined = new ArrayList(items.size() + armor.size() + extraSlots.size()); - for (List sub : this.f) { - combined.addAll(sub); - } - - return combined; - } - - public List getArmorContents() { - return this.armor; - } - - 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.getBukkitEntity(); - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - - @Override - public Location getLocation() { - return player.getBukkitEntity().getLocation(); - } - // CraftBukkit end - - public PlayerInventory(EntityHuman entityhuman) { - this.items = NonNullList.a(36, ItemStack.a); - this.armor = NonNullList.a(4, ItemStack.a); - this.extraSlots = NonNullList.a(1, ItemStack.a); - this.f = ImmutableList.of(this.items, this.armor, this.extraSlots); - this.carried = ItemStack.a; - this.player = entityhuman; - } - - public ItemStack getItemInHand() { - return d(this.itemInHandIndex) ? (ItemStack) this.items.get(this.itemInHandIndex) : ItemStack.a; - } - - public static int getHotbarSize() { - return 9; - } - - private boolean a(ItemStack itemstack, ItemStack itemstack1) { - return !itemstack.isEmpty() && this.b(itemstack, itemstack1) && itemstack.isStackable() && itemstack.getCount() < itemstack.getMaxStackSize() && itemstack.getCount() < this.getMaxStackSize(); - } - - private boolean b(ItemStack itemstack, ItemStack itemstack1) { - return itemstack.getItem() == itemstack1.getItem() && ItemStack.equals(itemstack, itemstack1); - } - - // CraftBukkit start - Watch method above! :D - public int canHold(ItemStack itemstack) { - int remains = itemstack.getCount(); - for (int i = 0; i < this.items.size(); ++i) { - ItemStack itemstack1 = this.getItem(i); - if (itemstack1.isEmpty()) return itemstack.getCount(); - - if (this.a(itemstack1, itemstack)) { // PAIL rename isSimilarAndNotFull - remains -= (itemstack1.getMaxStackSize() < this.getMaxStackSize() ? itemstack1.getMaxStackSize() : this.getMaxStackSize()) - itemstack1.getCount(); - } - if (remains <= 0) return itemstack.getCount(); - } - ItemStack offhandItemStack = this.getItem(this.items.size() + this.armor.size()); - if (this.a(offhandItemStack, itemstack)) { - remains -= (offhandItemStack.getMaxStackSize() < this.getMaxStackSize() ? offhandItemStack.getMaxStackSize() : this.getMaxStackSize()) - offhandItemStack.getCount(); - } - if (remains <= 0) return itemstack.getCount(); - - return itemstack.getCount() - remains; - } - // CraftBukkit end - - public int getFirstEmptySlotIndex() { - for (int i = 0; i < this.items.size(); ++i) { - if (((ItemStack) this.items.get(i)).isEmpty()) { - return i; - } - } - - return -1; - } - - public void c(int i) { - this.itemInHandIndex = this.i(); - ItemStack itemstack = (ItemStack) this.items.get(this.itemInHandIndex); - - this.items.set(this.itemInHandIndex, this.items.get(i)); - this.items.set(i, itemstack); - } - - public static boolean d(int i) { - return i >= 0 && i < 9; - } - - public int c(ItemStack itemstack) { - for (int i = 0; i < this.items.size(); ++i) { - ItemStack itemstack1 = (ItemStack) this.items.get(i); - - if (!((ItemStack) this.items.get(i)).isEmpty() && this.b(itemstack, (ItemStack) this.items.get(i)) && !((ItemStack) this.items.get(i)).f() && !itemstack1.hasEnchantments() && !itemstack1.hasName()) { - return i; - } - } - - return -1; - } - - public int i() { - int i; - int j; - - for (j = 0; j < 9; ++j) { - i = (this.itemInHandIndex + j) % 9; - if (((ItemStack) this.items.get(i)).isEmpty()) { - return i; - } - } - - for (j = 0; j < 9; ++j) { - i = (this.itemInHandIndex + j) % 9; - if (!((ItemStack) this.items.get(i)).hasEnchantments()) { - return i; - } - } - - return this.itemInHandIndex; - } - - public int a(Predicate predicate, int i) { - int j = 0; - - int k; - - for (k = 0; k < this.getSize(); ++k) { - ItemStack itemstack = this.getItem(k); - - if (!itemstack.isEmpty() && predicate.test(itemstack)) { - int l = i <= 0 ? itemstack.getCount() : Math.min(i - j, itemstack.getCount()); - - j += l; - if (i != 0) { - itemstack.subtract(l); - if (itemstack.isEmpty()) { - this.setItem(k, ItemStack.a); - } - - if (i > 0 && j >= i) { - return j; - } - } - } - } - - if (!this.carried.isEmpty() && predicate.test(this.carried)) { - k = i <= 0 ? this.carried.getCount() : Math.min(i - j, this.carried.getCount()); - j += k; - if (i != 0) { - this.carried.subtract(k); - if (this.carried.isEmpty()) { - this.carried = ItemStack.a; - } - - if (i > 0 && j >= i) { - return j; - } - } - } - - return j; - } - - private int i(ItemStack itemstack) { - int i = this.firstPartial(itemstack); - - if (i == -1) { - i = this.getFirstEmptySlotIndex(); - } - - return i == -1 ? itemstack.getCount() : this.d(i, itemstack); - } - - private int d(int i, ItemStack itemstack) { - Item item = itemstack.getItem(); - int j = itemstack.getCount(); - ItemStack itemstack1 = this.getItem(i); - - if (itemstack1.isEmpty()) { - itemstack1 = new ItemStack(item, 0); - if (itemstack.hasTag()) { - itemstack1.setTag(itemstack.getTag().clone()); - } - - this.setItem(i, itemstack1); - } - - int k = j; - - if (j > itemstack1.getMaxStackSize() - itemstack1.getCount()) { - k = itemstack1.getMaxStackSize() - itemstack1.getCount(); - } - - if (k > this.getMaxStackSize() - itemstack1.getCount()) { - k = this.getMaxStackSize() - itemstack1.getCount(); - } - - if (k == 0) { - return j; - } else { - j -= k; - itemstack1.add(k); - itemstack1.d(5); - return j; - } - } - - public int firstPartial(ItemStack itemstack) { - if (this.a(this.getItem(this.itemInHandIndex), itemstack)) { - return this.itemInHandIndex; - } else if (this.a(this.getItem(40), itemstack)) { - return 40; - } else { - for (int i = 0; i < this.items.size(); ++i) { - if (this.a((ItemStack) this.items.get(i), itemstack)) { - return i; - } - } - - return -1; - } - } - - public void j() { - Iterator iterator = this.f.iterator(); - - while (iterator.hasNext()) { - NonNullList nonnulllist = (NonNullList) iterator.next(); - - for (int i = 0; i < nonnulllist.size(); ++i) { - if (!((ItemStack) nonnulllist.get(i)).isEmpty()) { - ((ItemStack) nonnulllist.get(i)).a(this.player.world, this.player, i, this.itemInHandIndex == i); - } - } - } - - } - - public boolean pickup(ItemStack itemstack) { - return this.c(-1, itemstack); - } - - public boolean c(int i, ItemStack itemstack) { - if (itemstack.isEmpty()) { - return false; - } else { - try { - if (itemstack.f()) { - if (i == -1) { - i = this.getFirstEmptySlotIndex(); - } - - if (i >= 0) { - this.items.set(i, itemstack.cloneItemStack()); - ((ItemStack) this.items.get(i)).d(5); - itemstack.setCount(0); - return true; - } else if (this.player.abilities.canInstantlyBuild) { - itemstack.setCount(0); - return true; - } else { - return false; - } - } else { - int j; - - do { - j = itemstack.getCount(); - if (i == -1) { - itemstack.setCount(this.i(itemstack)); - } else { - itemstack.setCount(this.d(i, itemstack)); - } - } while (!itemstack.isEmpty() && itemstack.getCount() < j); - - if (itemstack.getCount() == j && this.player.abilities.canInstantlyBuild) { - itemstack.setCount(0); - return true; - } else { - return itemstack.getCount() < j; - } - } - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Adding item to inventory"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Item being added"); - - crashreportsystemdetails.a("Item ID", (Object) Item.getId(itemstack.getItem())); - crashreportsystemdetails.a("Item data", (Object) itemstack.getDamage()); - crashreportsystemdetails.a("Item name", () -> { - return itemstack.getName().getString(); - }); - throw new ReportedException(crashreport); - } - } - } - - public void a(World world, ItemStack itemstack) { - if (!world.isClientSide) { - while (!itemstack.isEmpty()) { - int i = this.firstPartial(itemstack); - - if (i == -1) { - i = this.getFirstEmptySlotIndex(); - } - - if (i == -1) { - this.player.drop(itemstack, false); - break; - } - - int j = itemstack.getMaxStackSize() - this.getItem(i).getCount(); - - if (this.c(i, itemstack.cloneAndSubtract(j))) { - ((EntityPlayer) this.player).playerConnection.sendPacket(new PacketPlayOutSetSlot(-2, i, this.getItem(i))); - } - } - - } - } - - @Override - public ItemStack splitStack(int i, int j) { - List list = null; - - NonNullList nonnulllist; - - for (Iterator iterator = this.f.iterator(); iterator.hasNext(); i -= nonnulllist.size()) { - nonnulllist = (NonNullList) iterator.next(); - if (i < nonnulllist.size()) { - list = nonnulllist; - break; - } - } - - return list != null && !((ItemStack) list.get(i)).isEmpty() ? ContainerUtil.a(list, i, j) : ItemStack.a; - } - - public void f(ItemStack itemstack) { - Iterator iterator = this.f.iterator(); - - while (iterator.hasNext()) { - NonNullList nonnulllist = (NonNullList) iterator.next(); - - for (int i = 0; i < nonnulllist.size(); ++i) { - if (nonnulllist.get(i) == itemstack) { - nonnulllist.set(i, ItemStack.a); - break; - } - } - } - - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - NonNullList nonnulllist = null; - - NonNullList nonnulllist1; - - for (Iterator iterator = this.f.iterator(); iterator.hasNext(); i -= nonnulllist1.size()) { - nonnulllist1 = (NonNullList) iterator.next(); - if (i < nonnulllist1.size()) { - nonnulllist = nonnulllist1; - break; - } - } - - if (nonnulllist != null && !((ItemStack) nonnulllist.get(i)).isEmpty()) { - ItemStack itemstack = (ItemStack) nonnulllist.get(i); - - nonnulllist.set(i, ItemStack.a); - return itemstack; - } else { - return ItemStack.a; - } - } - - @Override - public void setItem(int i, ItemStack itemstack) { - NonNullList nonnulllist = null; - - NonNullList nonnulllist1; - - for (Iterator iterator = this.f.iterator(); iterator.hasNext(); i -= nonnulllist1.size()) { - nonnulllist1 = (NonNullList) iterator.next(); - if (i < nonnulllist1.size()) { - nonnulllist = nonnulllist1; - break; - } - } - - if (nonnulllist != null) { - nonnulllist.set(i, itemstack); - } - - } - - public float a(IBlockData iblockdata) { - return ((ItemStack) this.items.get(this.itemInHandIndex)).a(iblockdata); - } - - public NBTTagList a(NBTTagList nbttaglist) { - NBTTagCompound nbttagcompound; - int i; - - for (i = 0; i < this.items.size(); ++i) { - if (!((ItemStack) this.items.get(i)).isEmpty()) { - nbttagcompound = new NBTTagCompound(); - nbttagcompound.setByte("Slot", (byte) i); - ((ItemStack) this.items.get(i)).save(nbttagcompound); - nbttaglist.add(nbttagcompound); - } - } - - for (i = 0; i < this.armor.size(); ++i) { - if (!((ItemStack) this.armor.get(i)).isEmpty()) { - nbttagcompound = new NBTTagCompound(); - nbttagcompound.setByte("Slot", (byte) (i + 100)); - ((ItemStack) this.armor.get(i)).save(nbttagcompound); - nbttaglist.add(nbttagcompound); - } - } - - for (i = 0; i < this.extraSlots.size(); ++i) { - if (!((ItemStack) this.extraSlots.get(i)).isEmpty()) { - nbttagcompound = new NBTTagCompound(); - nbttagcompound.setByte("Slot", (byte) (i + 150)); - ((ItemStack) this.extraSlots.get(i)).save(nbttagcompound); - nbttaglist.add(nbttagcompound); - } - } - - return nbttaglist; - } - - public void b(NBTTagList nbttaglist) { - this.items.clear(); - this.armor.clear(); - this.extraSlots.clear(); - - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompound(i); - int j = nbttagcompound.getByte("Slot") & 255; - ItemStack itemstack = ItemStack.a(nbttagcompound); - - if (!itemstack.isEmpty()) { - if (j >= 0 && j < this.items.size()) { - this.items.set(j, itemstack); - } else if (j >= 100 && j < this.armor.size() + 100) { - this.armor.set(j - 100, itemstack); - } else if (j >= 150 && j < this.extraSlots.size() + 150) { - this.extraSlots.set(j - 150, itemstack); - } - } - } - - } - - @Override - public int getSize() { - return this.items.size() + this.armor.size() + this.extraSlots.size(); - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - iterator = this.armor.iterator(); - - do { - if (!iterator.hasNext()) { - iterator = this.extraSlots.iterator(); - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public ItemStack getItem(int i) { - List list = null; - - NonNullList nonnulllist; - - for (Iterator iterator = this.f.iterator(); iterator.hasNext(); i -= nonnulllist.size()) { - nonnulllist = (NonNullList) iterator.next(); - if (i < nonnulllist.size()) { - list = nonnulllist; - break; - } - } - - return list == null ? ItemStack.a : (ItemStack) list.get(i); - } - - @Override - public IChatBaseComponent getDisplayName() { - return new ChatMessage("container.inventory", new Object[0]); - } - - public boolean b(IBlockData iblockdata) { - return this.getItem(this.itemInHandIndex).b(iblockdata); - } - - public void a(float f) { - if (f > 0.0F) { - f /= 4.0F; - if (f < 1.0F) { - f = 1.0F; - } - - for (int i = 0; i < this.armor.size(); ++i) { - ItemStack itemstack = (ItemStack) this.armor.get(i); - - if (itemstack.getItem() instanceof ItemArmor) { - int finalI = i; // CraftBukkit - decompile error - itemstack.damage((int) f, this.player, (entityhuman) -> { - entityhuman.c(EnumItemSlot.a(EnumItemSlot.Function.ARMOR, finalI)); // CraftBukkit - decompile error - }); - } - } - - } - } - - public void dropContents() { - Iterator iterator = this.f.iterator(); - - while (iterator.hasNext()) { - List list = (List) iterator.next(); - - for (int i = 0; i < list.size(); ++i) { - ItemStack itemstack = (ItemStack) list.get(i); - - if (!itemstack.isEmpty()) { - this.player.a(itemstack, true, false); - list.set(i, ItemStack.a); - } - } - } - - } - - @Override - public void update() { - ++this.h; - } - - public void setCarried(ItemStack itemstack) { - this.carried = itemstack; - } - - public ItemStack getCarried() { - // CraftBukkit start - if (this.carried.isEmpty()) { - this.setCarried(ItemStack.a); - } - // CraftBukkit end - return this.carried; - } - - @Override - public boolean a(EntityHuman entityhuman) { - return this.player.dead ? false : entityhuman.h((Entity) this.player) <= 64.0D; - } - - public boolean h(ItemStack itemstack) { - Iterator iterator = this.f.iterator(); - - while (iterator.hasNext()) { - List list = (List) iterator.next(); - Iterator iterator1 = list.iterator(); - - while (iterator1.hasNext()) { - ItemStack itemstack1 = (ItemStack) iterator1.next(); - - if (!itemstack1.isEmpty() && itemstack1.doMaterialsMatch(itemstack)) { - return true; - } - } - } - - return false; - } - - public void a(PlayerInventory playerinventory) { - for (int i = 0; i < this.getSize(); ++i) { - this.setItem(i, playerinventory.getItem(i)); - } - - this.itemInHandIndex = playerinventory.itemInHandIndex; - } - - @Override - public void clear() { - Iterator iterator = this.f.iterator(); - - while (iterator.hasNext()) { - List list = (List) iterator.next(); - - list.clear(); - } - - } - - public void a(AutoRecipeStackManager autorecipestackmanager) { - Iterator iterator = this.items.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - - autorecipestackmanager.a(itemstack); - } - - } -} diff --git a/src/main/java/net/minecraft/server/PlayerList.java b/src/main/java/net/minecraft/server/PlayerList.java deleted file mode 100644 index 3cb443c4f..000000000 --- a/src/main/java/net/minecraft/server/PlayerList.java +++ /dev/null @@ -1,1235 +0,0 @@ -package net.minecraft.server; - -import co.aikar.timings.MinecraftTimings; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.mojang.authlib.GameProfile; -import io.netty.buffer.Unpooled; -import java.io.File; -import java.net.SocketAddress; -import java.text.SimpleDateFormat; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; - -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerPortalEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerLoginEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.util.Vector; -import org.spigotmc.event.player.PlayerSpawnLocationEvent; -// CraftBukkit end - -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 LOGGER = LogManager.getLogger(); - private static final SimpleDateFormat g = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); - private final MinecraftServer server; - public final List players = new java.util.concurrent.CopyOnWriteArrayList(); // CraftBukkit - ArrayList -> CopyOnWriteArrayList: Iterator safety - private final Map j = Maps.newHashMap(); - private final GameProfileBanList k; - private final IpBanList l; - private final OpList operators; - private final WhiteList whitelist; - // CraftBukkit start - // private final Map o; - // private final Map p; - // CraftBukkit end - public IPlayerFileData playerFileData; - //private boolean hasWhitelist; - protected final int maxPlayers; - private int viewDistance; - private EnumGamemode t; - private boolean u; - private int v; - - // CraftBukkit start - private CraftServer cserver; - private final Map playersByName = new java.util.HashMap<>(); - @Nullable String collideRuleTeamName; // Paper - Team name used for collideRule - - public PlayerList(MinecraftServer minecraftserver, int i) { - this.cserver = minecraftserver.server = new CraftServer((DedicatedServer) minecraftserver, this); - minecraftserver.console = new com.destroystokyo.paper.console.TerminalConsoleCommandSender(); // Paper - // CraftBukkit end - - this.k = new GameProfileBanList(PlayerList.a); - this.l = new IpBanList(PlayerList.b); - this.operators = new OpList(PlayerList.c); - this.whitelist = new WhiteList(PlayerList.d); - // CraftBukkit start - // this.o = Maps.newHashMap(); - // this.p = Maps.newHashMap(); - // CraftBukkit end - this.server = minecraftserver; - this.maxPlayers = i; - this.getProfileBans().a(true); - this.getIPBans().a(true); - } - - public void a(NetworkManager networkmanager, EntityPlayer entityplayer) { - entityplayer.loginTime = System.currentTimeMillis(); // Paper - GameProfile gameprofile = entityplayer.getProfile(); - UserCache usercache = this.server.getUserCache(); - GameProfile gameprofile1 = usercache.a(gameprofile.getId()); - String s = gameprofile1 == null ? gameprofile.getName() : gameprofile1.getName(); - - usercache.a(gameprofile); - NBTTagCompound nbttagcompound = this.a(entityplayer); - WorldServer worldserver = this.server.getWorldServer(entityplayer.dimension); - // 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 - - // Paper start - support PlayerInitialSpawnEvent - Location originalLoc = new Location(entityplayer.world.getWorld(), entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); - com.destroystokyo.paper.event.player.PlayerInitialSpawnEvent event = new com.destroystokyo.paper.event.player.PlayerInitialSpawnEvent(entityplayer.getBukkitEntity(), originalLoc); - this.server.server.getPluginManager().callEvent(event); - - Location newLoc = event.getSpawnLocation(); - entityplayer.world = ((CraftWorld) newLoc.getWorld()).getHandle(); - entityplayer.locX = newLoc.getX(); - entityplayer.locY = newLoc.getY(); - entityplayer.locZ = newLoc.getZ(); - entityplayer.yaw = newLoc.getYaw(); - entityplayer.pitch = newLoc.getPitch(); - entityplayer.dimension = ((CraftWorld) newLoc.getWorld()).getHandle().worldProvider.getDimensionManager(); - // Paper end - - entityplayer.spawnIn(((CraftWorld) newLoc.getWorld()).getHandle()); - entityplayer.playerInteractManager.a((WorldServer) entityplayer.world); - 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 - - // CraftBukkit - Moved message to after join - // PlayerList.LOGGER.info("{}[{}] logged in with entity id {} at ({}, {}, {})", entityplayer.getDisplayName().getString(), s1, entityplayer.getId(), entityplayer.locX, entityplayer.locY, entityplayer.locZ); - WorldData worlddata = worldserver.getWorldData(); - - this.a(entityplayer, (EntityPlayer) null, worldserver); - PlayerConnection playerconnection = new PlayerConnection(this.server, networkmanager, entityplayer); - - // CraftBukkit - getType() - // Spigot - view distance - playerconnection.sendPacket(new PacketPlayOutLogin(entityplayer.getId(), entityplayer.playerInteractManager.getGameMode(), worlddata.isHardcore(), worldserver.worldProvider.getDimensionManager().getType(), this.getMaxPlayers(), worlddata.getType(), worldserver.spigotConfig.viewDistance, worldserver.getGameRules().getBoolean(GameRules.REDUCED_DEBUG_INFO))); - entityplayer.getBukkitEntity().sendSupportedChannels(); // CraftBukkit - playerconnection.sendPacket(new PacketPlayOutCustomPayload(PacketPlayOutCustomPayload.a, (new PacketDataSerializer(Unpooled.buffer())).a(this.getServer().getServerModName()))); - playerconnection.sendPacket(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); - playerconnection.sendPacket(new PacketPlayOutAbilities(entityplayer.abilities)); - playerconnection.sendPacket(new PacketPlayOutHeldItemSlot(entityplayer.inventory.itemInHandIndex)); - playerconnection.sendPacket(new PacketPlayOutRecipeUpdate(this.server.getCraftingManager().b())); - playerconnection.sendPacket(new PacketPlayOutTags(this.server.getTagRegistry())); - playerconnection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, (byte) (worldserver.getGameRules().getBoolean(GameRules.REDUCED_DEBUG_INFO) ? 22 : 23))); // Paper - fix this rule not being initialized on the client - this.d(entityplayer); - entityplayer.getStatisticManager().c(); - entityplayer.B().a(entityplayer); - this.sendScoreboard(worldserver.getScoreboard(), entityplayer); - this.server.invalidatePingSample(); - ChatMessage chatmessage; - - if (entityplayer.getProfile().getName().equalsIgnoreCase(s)) { - chatmessage = new ChatMessage("multiplayer.player.joined", new Object[]{entityplayer.getScoreboardDisplayName()}); - } else { - chatmessage = new ChatMessage("multiplayer.player.joined.renamed", new Object[]{entityplayer.getScoreboardDisplayName(), s}); - } - // CraftBukkit start - chatmessage.a(EnumChatFormat.YELLOW); - String joinMessage = CraftChatMessage.fromComponent(chatmessage, EnumChatFormat.WHITE); - - playerconnection.a(entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); - this.players.add(entityplayer); - this.playersByName.put(entityplayer.getName().toLowerCase(java.util.Locale.ROOT), entityplayer); // Spigot - this.j.put(entityplayer.getUniqueID(), entityplayer); - // this.sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, new EntityPlayer[]{entityplayer})); // CraftBukkit - replaced with loop below - - // CraftBukkit start - PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(cserver.getPlayer(entityplayer), joinMessage); - cserver.getPluginManager().callEvent(playerJoinEvent); - - if (!entityplayer.playerConnection.networkManager.isConnected()) { - return; - } - - joinMessage = playerJoinEvent.getJoinMessage(); - - if (joinMessage != null && joinMessage.length() > 0) { - for (IChatBaseComponent line : org.bukkit.craftbukkit.util.CraftChatMessage.fromString(joinMessage)) { - server.getPlayerList().sendAll(new PacketPlayOutChat(line)); - } - } - // CraftBukkit end - - // CraftBukkit start - sendAll above replaced with this loop - PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, entityplayer); - - for (int i = 0; i < this.players.size(); ++i) { - EntityPlayer entityplayer1 = (EntityPlayer) this.players.get(i); - - if (entityplayer1.getBukkitEntity().canSee(entityplayer.getBukkitEntity())) { - entityplayer1.playerConnection.sendPacket(packet); - } - - if (!entityplayer.getBukkitEntity().canSee(entityplayer1.getBukkitEntity())) { - continue; - } - - entityplayer.playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, new EntityPlayer[] { entityplayer1})); - } - entityplayer.sentListPacket = true; - // CraftBukkit end - - entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityMetadata(entityplayer.getId(), entityplayer.datawatcher, true)); // CraftBukkit - BungeeCord#2321, send complete data to self on spawn - - // CraftBukkit start - Only add if the player wasn't moved in the event - if (entityplayer.world == worldserver && !worldserver.getPlayers().contains(entityplayer)) { - worldserver.addPlayerJoin(entityplayer); - this.server.getBossBattleCustomData().a(entityplayer); - } - - worldserver = server.getWorldServer(entityplayer.dimension); // CraftBukkit - Update in case join event changed it - // CraftBukkit end - this.a(entityplayer, worldserver); - if (!this.server.getResourcePack().isEmpty()) { - entityplayer.setResourcePack(this.server.getResourcePack(), this.server.getResourcePackHash()); - } - - Iterator iterator = entityplayer.getEffects().iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - playerconnection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), mobeffect)); - } - - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("RootVehicle", 10)) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("RootVehicle"); - // CraftBukkit start - WorldServer finalWorldServer = worldserver; - Entity entity = EntityTypes.a(nbttagcompound1.getCompound("Entity"), finalWorldServer, (entity1) -> { - return !finalWorldServer.addEntitySerialized(entity1, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.MOUNT) ? null : entity1; // Paper - // CraftBukkit end - }); - - if (entity != null) { - UUID uuid = nbttagcompound1.a("Attach"); - Iterator iterator1; - Entity entity1; - - if (entity.getUniqueID().equals(uuid)) { - entityplayer.a(entity, true); - } else { - iterator1 = entity.getAllPassengers().iterator(); - - while (iterator1.hasNext()) { - entity1 = (Entity) iterator1.next(); - if (entity1.getUniqueID().equals(uuid)) { - entityplayer.a(entity1, true); - break; - } - } - } - - if (!entityplayer.isPassenger()) { - PlayerList.LOGGER.warn("Couldn't reattach entity to player"); - worldserver.removeEntity(entity); - iterator1 = entity.getAllPassengers().iterator(); - - while (iterator1.hasNext()) { - entity1 = (Entity) iterator1.next(); - worldserver.removeEntity(entity1); - } - } - } - } - - entityplayer.syncInventory(); - // Paper start - Add to collideRule team if needed - final Scoreboard scoreboard = this.getServer().getWorldServer(DimensionManager.OVERWORLD).getScoreboard(); - final ScoreboardTeam collideRuleTeam = scoreboard.getTeam(collideRuleTeamName); - if (this.collideRuleTeamName != null && collideRuleTeam != null && entityplayer.getScoreboardTeam() == null) { - scoreboard.addPlayerToTeam(entityplayer.getName(), collideRuleTeam); - } - // Paper end - // CraftBukkit - Moved from above, added world - PlayerList.LOGGER.info("{}[{}] logged in with entity id {} at ([{}]{}, {}, {})", entityplayer.getDisplayName().getString(), s1, entityplayer.getId(), entityplayer.world.worldData.getName(), entityplayer.locX, entityplayer.locY, entityplayer.locZ); - } - - public void sendScoreboard(ScoreboardServer scoreboardserver, EntityPlayer entityplayer) { - Set set = Sets.newHashSet(); - Iterator iterator = scoreboardserver.getTeams().iterator(); - - while (iterator.hasNext()) { - ScoreboardTeam scoreboardteam = (ScoreboardTeam) iterator.next(); - - entityplayer.playerConnection.sendPacket(new PacketPlayOutScoreboardTeam(scoreboardteam, 0)); - } - - for (int i = 0; i < 19; ++i) { - ScoreboardObjective scoreboardobjective = scoreboardserver.getObjectiveForSlot(i); - - if (scoreboardobjective != null && !set.contains(scoreboardobjective)) { - List> list = scoreboardserver.getScoreboardScorePacketsForObjective(scoreboardobjective); - Iterator iterator1 = list.iterator(); - - while (iterator1.hasNext()) { - Packet packet = (Packet) iterator1.next(); - - entityplayer.playerConnection.sendPacket(packet); - } - - set.add(scoreboardobjective); - } - } - - } - - public void setPlayerFileData(WorldServer worldserver) { - if (playerFileData != null) return; // CraftBukkit - this.playerFileData = worldserver.getDataManager(); - worldserver.getWorldBorder().a(new IWorldBorderListener() { - @Override - public void a(WorldBorder worldborder, double d0) { - PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_SIZE), worldborder.world); - } - - @Override - public void a(WorldBorder worldborder, double d0, double d1, long i) { - PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.LERP_SIZE), worldborder.world); - } - - @Override - public void a(WorldBorder worldborder, double d0, double d1) { - PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_CENTER), worldborder.world); - } - - @Override - public void a(WorldBorder worldborder, int i) { - PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_WARNING_TIME), worldborder.world); - } - - @Override - public void b(WorldBorder worldborder, int i) { - PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_WARNING_BLOCKS), worldborder.world); - } - - @Override - public void b(WorldBorder worldborder, double d0) {} - - @Override - public void c(WorldBorder worldborder, double d0) {} - }); - } - - @Nullable - public NBTTagCompound a(EntityPlayer entityplayer) { - NBTTagCompound nbttagcompound = this.server.getWorldServer(DimensionManager.OVERWORLD).getWorldData().h(); - NBTTagCompound nbttagcompound1; - - if (entityplayer.getDisplayName().getString().equals(this.server.getSinglePlayerName()) && nbttagcompound != null) { - nbttagcompound1 = nbttagcompound; - entityplayer.f(nbttagcompound); - PlayerList.LOGGER.debug("loading single player"); - } else { - nbttagcompound1 = this.playerFileData.load(entityplayer); - } - - return nbttagcompound1; - } - - protected void savePlayerFile(EntityPlayer entityplayer) { - if (!entityplayer.getBukkitEntity().isPersistent()) return; // CraftBukkit - this.playerFileData.save(entityplayer); - ServerStatisticManager serverstatisticmanager = (ServerStatisticManager) entityplayer.getStatisticManager(); // CraftBukkit - - if (serverstatisticmanager != null) { - serverstatisticmanager.a(); - } - - AdvancementDataPlayer advancementdataplayer = (AdvancementDataPlayer) entityplayer.getAdvancementData(); // CraftBukkit - - if (advancementdataplayer != null) { - advancementdataplayer.c(); - } - - } - - public String disconnect(EntityPlayer entityplayer) { // CraftBukkit - return string - WorldServer worldserver = entityplayer.getWorldServer(); - - entityplayer.a(StatisticList.LEAVE_GAME); - - // 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, org.bukkit.event.inventory.InventoryCloseEvent.Reason.DISCONNECT); // Paper - - PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(cserver.getPlayer(entityplayer), "\u00A7e" + entityplayer.getName() + " left the game"); - cserver.getPluginManager().callEvent(playerQuitEvent); - entityplayer.getBukkitEntity().disconnect(playerQuitEvent.getQuitMessage()); - - entityplayer.playerTick();// SPIGOT-924 - // CraftBukkit end - - // Paper start - Remove from collideRule team if needed - if (this.collideRuleTeamName != null) { - final Scoreboard scoreBoard = this.server.getWorldServer(DimensionManager.OVERWORLD).getScoreboard(); - final ScoreboardTeam team = scoreBoard.getTeam(this.collideRuleTeamName); - if (entityplayer.getScoreboardTeam() == team && team != null) { - scoreBoard.removePlayerFromTeam(entityplayer.getName(), team); - } - } - // Paper end - - this.savePlayerFile(entityplayer); - if (entityplayer.isPassenger()) { - Entity entity = entityplayer.getRootVehicle(); - - if (entity.hasSinglePlayerPassenger()) { - PlayerList.LOGGER.debug("Removing player mount"); - entityplayer.stopRiding(); - worldserver.removeEntity(entity); - Iterator iterator = entity.getAllPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity1 = (Entity) iterator.next(); - - worldserver.removeEntity(entity1); - } - - worldserver.getChunkAt(entityplayer.chunkX, entityplayer.chunkZ).markDirty(); - } - } - - entityplayer.decouple(); - worldserver.removePlayer(entityplayer); - entityplayer.getAdvancementData().a(); - this.players.remove(entityplayer); - this.playersByName.remove(entityplayer.getName().toLowerCase(java.util.Locale.ROOT)); // Spigot - this.server.getBossBattleCustomData().b(entityplayer); - UUID uuid = entityplayer.getUniqueID(); - EntityPlayer entityplayer1 = (EntityPlayer) this.j.get(uuid); - - if (entityplayer1 == entityplayer) { - this.j.remove(uuid); - // CraftBukkit start - // this.o.remove(uuid); - // this.p.remove(uuid); - // CraftBukkit end - } - - // CraftBukkit start - // this.sendAll(new PacketPlayOutPlayerInfo(EnumPlayerInfoAction.REMOVE_PLAYER, new EntityPlayer[]{entityplayer})); - PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, entityplayer); - for (int i = 0; i < players.size(); i++) { - EntityPlayer entityplayer2 = (EntityPlayer) this.players.get(i); - - if (entityplayer2.getBukkitEntity().canSee(entityplayer.getBukkitEntity())) { - entityplayer2.playerConnection.sendPacket(packet); - } else { - entityplayer2.getBukkitEntity().removeDisconnectingPlayer(entityplayer.getBukkitEntity()); - } - } - // This removes the scoreboard (and player reference) for the specific player in the manager - cserver.getScoreboardManager().removePlayer(entityplayer.getBukkitEntity()); - // CraftBukkit end - - return playerQuitEvent.getQuitMessage(); // CraftBukkit - } - - // CraftBukkit start - Whole method, SocketAddress to LoginListener, added hostname to signature, return EntityPlayer - public EntityPlayer attemptLogin(LoginListener loginlistener, GameProfile gameprofile, String hostname) { - ChatMessage chatmessage; - - // Moved from processLogin - UUID uuid = EntityHuman.a(gameprofile); - List list = Lists.newArrayList(); - - EntityPlayer entityplayer; - - for (int i = 0; i < this.players.size(); ++i) { - entityplayer = (EntityPlayer) this.players.get(i); - if (entityplayer.getUniqueID().equals(uuid)) { - list.add(entityplayer); - } - } - - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - entityplayer = (EntityPlayer) iterator.next(); - savePlayerFile(entityplayer); // CraftBukkit - Force the player's inventory to be saved - entityplayer.playerConnection.disconnect(new ChatMessage("multiplayer.disconnect.duplicate_login", new Object[0])); - } - - // Instead of kicking then returning, we need to store the kick reason - // in the event, check with plugins to see if it's ok, and THEN kick - // depending on the outcome. - SocketAddress socketaddress = loginlistener.networkManager.getSocketAddress(); - - EntityPlayer entity = new EntityPlayer(this.server, this.server.getWorldServer(DimensionManager.OVERWORLD), gameprofile, new PlayerInteractManager(this.server.getWorldServer(DimensionManager.OVERWORLD))); - Player player = entity.getBukkitEntity(); - PlayerLoginEvent event = new PlayerLoginEvent(player, hostname, ((java.net.InetSocketAddress) socketaddress).getAddress(), ((java.net.InetSocketAddress) loginlistener.networkManager.getRawAddress()).getAddress()); - - // Paper start - Fix MC-158900 - GameProfileBanEntry gameprofilebanentry; - if (getProfileBans().isBanned(gameprofile) && (gameprofilebanentry = getProfileBans().get(gameprofile)) != null) { - // Paper end - - chatmessage = new ChatMessage("multiplayer.disconnect.banned.reason", new Object[]{gameprofilebanentry.getReason()}); - if (gameprofilebanentry.getExpires() != null) { - chatmessage.addSibling(new ChatMessage("multiplayer.disconnect.banned.expiration", new Object[]{PlayerList.g.format(gameprofilebanentry.getExpires())})); - } - - // return chatmessage; - if (!gameprofilebanentry.hasExpired()) event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(chatmessage)); // Spigot - } else if (!this.isWhitelisted(gameprofile, event)) { // Paper - chatmessage = new ChatMessage("multiplayer.disconnect.not_whitelisted", new Object[0]); - //event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, org.spigotmc.SpigotConfig.whitelistMessage); // Spigot // Paper - moved to isWhitelisted - } else if (getIPBans().isBanned(socketaddress) && !getIPBans().get(socketaddress).hasExpired()) { - IpBanEntry ipbanentry = this.l.get(socketaddress); - - chatmessage = new ChatMessage("multiplayer.disconnect.banned_ip.reason", new Object[]{ipbanentry.getReason()}); - if (ipbanentry.getExpires() != null) { - chatmessage.addSibling(new ChatMessage("multiplayer.disconnect.banned_ip.expiration", new Object[]{PlayerList.g.format(ipbanentry.getExpires())})); - } - - // return chatmessage; - event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(chatmessage)); - } else { - // return this.players.size() >= this.maxPlayers && !this.f(gameprofile) ? new ChatMessage("multiplayer.disconnect.server_full", new Object[0]) : null; - if (this.players.size() >= this.maxPlayers && !this.f(gameprofile)) { - event.disallow(PlayerLoginEvent.Result.KICK_FULL, org.spigotmc.SpigotConfig.serverFullMessage); // Spigot - } - } - - cserver.getPluginManager().callEvent(event); - if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) { - loginlistener.disconnect(event.getKickMessage()); - return null; - } - return entity; - } - - public EntityPlayer processLogin(GameProfile gameprofile, EntityPlayer player) { // CraftBukkit - added EntityPlayer - /* CraftBukkit startMoved up - UUID uuid = EntityHuman.a(gameprofile); - List list = Lists.newArrayList(); - - for (int i = 0; i < this.players.size(); ++i) { - EntityPlayer entityplayer = (EntityPlayer) this.players.get(i); - - if (entityplayer.getUniqueID().equals(uuid)) { - list.add(entityplayer); - } - } - - EntityPlayer entityplayer1 = (EntityPlayer) this.j.get(gameprofile.getId()); - - if (entityplayer1 != null && !list.contains(entityplayer1)) { - list.add(entityplayer1); - } - - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer2 = (EntityPlayer) iterator.next(); - - entityplayer2.playerConnection.disconnect(new ChatMessage("multiplayer.disconnect.duplicate_login", new Object[0])); - } - - Object object; - - if (this.server.isDemoMode()) { - object = new DemoPlayerInteractManager(this.server.getWorldServer(DimensionManager.OVERWORLD)); - } else { - object = new PlayerInteractManager(this.server.getWorldServer(DimensionManager.OVERWORLD)); - } - - return new EntityPlayer(this.server, this.server.getWorldServer(DimensionManager.OVERWORLD), gameprofile, (PlayerInteractManager) object); - */ - return player; - // CraftBukkit end - } - - // CraftBukkit start - public EntityPlayer moveToWorld(EntityPlayer entityplayer, DimensionManager dimensionmanager, boolean flag) { - return this.moveToWorld(entityplayer, dimensionmanager, flag, null, true); - } - - public EntityPlayer moveToWorld(EntityPlayer entityplayer, DimensionManager dimensionmanager, boolean flag, Location location, boolean avoidSuffocation) { - entityplayer.stopRiding(); // CraftBukkit - this.players.remove(entityplayer); - this.playersByName.remove(entityplayer.getName().toLowerCase(java.util.Locale.ROOT)); // Spigot - entityplayer.getWorldServer().removePlayer(entityplayer); - BlockPosition blockposition = entityplayer.getBed(); - boolean flag1 = entityplayer.isRespawnForced(); - - /* CraftBukkit start - entityplayer.dimension = dimensionmanager; - Object object; - - if (this.server.isDemoMode()) { - object = new DemoPlayerInteractManager(this.server.getWorldServer(entityplayer.dimension)); - } else { - object = new PlayerInteractManager(this.server.getWorldServer(entityplayer.dimension)); - } - - EntityPlayer entityplayer1 = new EntityPlayer(this.server, this.server.getWorldServer(entityplayer.dimension), entityplayer.getProfile(), (PlayerInteractManager) object); - // */ - EntityPlayer entityplayer1 = entityplayer; - org.bukkit.World fromWorld = entityplayer.getBukkitEntity().getWorld(); - entityplayer.viewingCredits = false; - // CraftBukkit end - - entityplayer1.playerConnection = entityplayer.playerConnection; - entityplayer1.copyFrom(entityplayer, flag); - entityplayer1.e(entityplayer.getId()); - entityplayer1.a(entityplayer.getMainHand()); - Iterator iterator = entityplayer.getScoreboardTags().iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - - entityplayer1.addScoreboardTag(s); - } - - // WorldServer worldserver = this.server.getWorldServer(entityplayer.dimension); // CraftBukkit - handled later - - // this.a(entityplayer1, entityplayer, worldserver); // CraftBukkit - removed - - // Paper start - boolean isBedSpawn = false; - boolean isRespawn = false; - // Paper end - - // CraftBukkit start - fire PlayerRespawnEvent - if (location == null) { - //boolean isBedSpawn = false; Paper - moved up - CraftWorld cworld = (CraftWorld) this.server.server.getWorld(entityplayer.spawnWorld); - if (cworld != null && blockposition != null) { - Optional optional = EntityHuman.getBed(cworld.getHandle(), blockposition, flag1); - - if (optional.isPresent()) { - Vec3D vec3d = (Vec3D) optional.get(); - - isBedSpawn = true; - location = new Location(cworld, vec3d.x, vec3d.y, vec3d.z); - } else { - entityplayer1.setRespawnPosition(null, true); - entityplayer1.playerConnection.sendPacket(new PacketPlayOutGameStateChange(0, 0.0F)); - } - } - - if (location == null) { - cworld = (CraftWorld) this.server.server.getWorlds().get(0); - blockposition = entityplayer1.getSpawnPoint(cworld.getHandle()); - location = new Location(cworld, (double) ((float) blockposition.getX() + 0.5F), (double) ((float) blockposition.getY() + 0.1F), (double) ((float) blockposition.getZ() + 0.5F)); - } - - Player respawnPlayer = cserver.getPlayer(entityplayer1); - PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(respawnPlayer, location, isBedSpawn); - cserver.getPluginManager().callEvent(respawnEvent); - // Spigot Start - if (entityplayer.playerConnection.isDisconnected()) { - return entityplayer; - } - // Spigot End - - location = respawnEvent.getRespawnLocation(); - if (!flag) entityplayer.reset(); // SPIGOT-4785 - isRespawn = true; // Paper - } else { - location.setWorld(server.getWorldServer(dimensionmanager).getWorld()); - } - WorldServer worldserver = ((CraftWorld) location.getWorld()).getHandle(); - entityplayer1.forceSetPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); - // CraftBukkit end - - while (avoidSuffocation && !worldserver.getCubes(entityplayer1) && entityplayer1.locY < 256.0D) { - entityplayer1.setPosition(entityplayer1.locX, entityplayer1.locY + 1.0D, entityplayer1.locZ); - } - // CraftBukkit start - // Force the client to refresh their chunk cache - if (fromWorld.getEnvironment() == worldserver.getWorld().getEnvironment()) { - entityplayer1.playerConnection.sendPacket(new PacketPlayOutRespawn(worldserver.worldProvider.getDimensionManager().getDimensionID() >= 0 ? DimensionManager.NETHER : DimensionManager.OVERWORLD, worldserver.getWorldData().getType(), entityplayer.playerInteractManager.getGameMode())); - } - - WorldData worlddata = worldserver.getWorldData(); - - entityplayer1.playerConnection.sendPacket(new PacketPlayOutRespawn(worldserver.worldProvider.getDimensionManager().getType(), worldserver.getWorldData().getType(), entityplayer1.playerInteractManager.getGameMode())); - entityplayer1.playerConnection.sendPacket(new PacketPlayOutViewDistance(worldserver.spigotConfig.viewDistance)); // Spigot - entityplayer1.spawnIn(worldserver); - entityplayer1.dead = false; - entityplayer1.playerConnection.teleport(new Location(worldserver.getWorld(), entityplayer1.locX, entityplayer1.locY, entityplayer1.locZ, entityplayer1.yaw, entityplayer1.pitch)); - entityplayer1.setSneaking(false); - BlockPosition blockposition1 = worldserver.getSpawn(); - - // entityplayer1.playerConnection.a(entityplayer1.locX, entityplayer1.locY, entityplayer1.locZ, entityplayer1.yaw, entityplayer1.pitch); - entityplayer1.playerConnection.sendPacket(new PacketPlayOutSpawnPosition(blockposition1)); - entityplayer1.playerConnection.sendPacket(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), worlddata.isDifficultyLocked())); - entityplayer1.playerConnection.sendPacket(new PacketPlayOutExperience(entityplayer1.exp, entityplayer1.expTotal, entityplayer1.expLevel)); - this.a(entityplayer1, worldserver); - this.d(entityplayer1); - if (!entityplayer.playerConnection.isDisconnected()) { - worldserver.addPlayerRespawn(entityplayer1); - this.players.add(entityplayer1); - this.playersByName.put(entityplayer1.getName().toLowerCase(java.util.Locale.ROOT), entityplayer1); // Spigot - this.j.put(entityplayer1.getUniqueID(), entityplayer1); - } - // entityplayer1.syncInventory(); - entityplayer1.setHealth(entityplayer1.getHealth()); - // Added from changeDimension - updateClient(entityplayer); // Update health, etc... - entityplayer.updateAbilities(); - for (Object o1 : entityplayer.getEffects()) { - MobEffect mobEffect = (MobEffect) o1; - entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), mobEffect)); - } - - // Fire advancement trigger - entityplayer.b(((CraftWorld) fromWorld).getHandle()); - - // Don't fire on respawn - if (fromWorld != location.getWorld()) { - PlayerChangedWorldEvent event = new PlayerChangedWorldEvent(entityplayer.getBukkitEntity(), fromWorld); - server.server.getPluginManager().callEvent(event); - } - - // Save player file again if they were disconnected - if (entityplayer.playerConnection.isDisconnected()) { - this.savePlayerFile(entityplayer); - } - - // Paper start - if (isRespawn) { - cserver.getPluginManager().callEvent(new com.destroystokyo.paper.event.player.PlayerPostRespawnEvent(entityplayer.getBukkitEntity(), location, isBedSpawn)); - } - // Paper end - - // CraftBukkit end - return entityplayer1; - } - - public void d(EntityPlayer entityplayer) { - GameProfile gameprofile = entityplayer.getProfile(); - int i = this.server.a(gameprofile); - - this.a(entityplayer, i); - } - - public void tick() { - if (++this.v > 600) { - // CraftBukkit start - for (int i = 0; i < this.players.size(); ++i) { - final EntityPlayer target = (EntityPlayer) this.players.get(i); - - target.playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_LATENCY, Iterables.filter(this.players, new Predicate() { - @Override - public boolean apply(EntityPlayer input) { - return target.getBukkitEntity().canSee(input.getBukkitEntity()); - } - }))); - } - // CraftBukkit end - this.v = 0; - } - - } - - public void sendAll(Packet packet) { - for (int i = 0; i < this.players.size(); ++i) { - ((EntityPlayer) this.players.get(i)).playerConnection.sendPacket(packet); - } - - } - - // CraftBukkit start - add a world/entity limited version - public void sendAll(Packet packet, EntityHuman entityhuman) { - for (int i = 0; i < this.players.size(); ++i) { - EntityPlayer entityplayer = this.players.get(i); - if (entityhuman != null && entityhuman instanceof EntityPlayer && !entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) { - continue; - } - ((EntityPlayer) this.players.get(i)).playerConnection.sendPacket(packet); - } - } - - public void sendAll(Packet packet, World world) { - for (int i = 0; i < world.getPlayers().size(); ++i) { - ((EntityPlayer) world.getPlayers().get(i)).playerConnection.sendPacket(packet); - } - - } - // CraftBukkit end - - public void a(Packet packet, DimensionManager dimensionmanager) { - for (int i = 0; i < this.players.size(); ++i) { - EntityPlayer entityplayer = (EntityPlayer) this.players.get(i); - - if (entityplayer.dimension == dimensionmanager) { - entityplayer.playerConnection.sendPacket(packet); - } - } - - } - - public void a(EntityHuman entityhuman, IChatBaseComponent ichatbasecomponent) { - ScoreboardTeamBase scoreboardteambase = entityhuman.getScoreboardTeam(); - - if (scoreboardteambase != null) { - Collection collection = scoreboardteambase.getPlayerNameSet(); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - 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 (int i = 0; i < this.players.size(); ++i) { - EntityPlayer entityplayer = (EntityPlayer) this.players.get(i); - - if (entityplayer.getScoreboardTeam() != scoreboardteambase) { - entityplayer.sendMessage(ichatbasecomponent); - } - } - - } - } - - public String[] e() { - String[] astring = new String[this.players.size()]; - - for (int i = 0; i < this.players.size(); ++i) { - astring[i] = ((EntityPlayer) this.players.get(i)).getProfile().getName(); - } - - return astring; - } - - 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.j(), this.operators.b(gameprofile))); - EntityPlayer entityplayer = this.a(gameprofile.getId()); - - if (entityplayer != null) { - this.d(entityplayer); - } - - } - - public void removeOp(GameProfile gameprofile) { - this.operators.remove(gameprofile); - EntityPlayer entityplayer = this.a(gameprofile.getId()); - - if (entityplayer != null) { - this.d(entityplayer); - } - - } - - private void a(EntityPlayer entityplayer, int i) { - if (entityplayer.playerConnection != null) { - byte b0; - - if (i <= 0) { - b0 = 24; - } else if (i >= 4) { - b0 = 28; - } else { - b0 = (byte) (24 + i); - } - - entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, b0)); - } - - entityplayer.getBukkitEntity().recalculatePermissions(); // CraftBukkit - this.server.getCommandDispatcher().a(entityplayer); - } - - // Paper start - public boolean isWhitelisted(GameProfile gameprofile) { - return isWhitelisted(gameprofile, null); - } - public boolean isWhitelisted(GameProfile gameprofile, org.bukkit.event.player.PlayerLoginEvent loginEvent) { - boolean isOp = this.operators.d(gameprofile); - boolean isWhitelisted = !this.getHasWhitelist() || isOp || this.whitelist.d(gameprofile); - final com.destroystokyo.paper.event.profile.ProfileWhitelistVerifyEvent event; - event = new com.destroystokyo.paper.event.profile.ProfileWhitelistVerifyEvent(MCUtil.toBukkit(gameprofile), this.getHasWhitelist(), isWhitelisted, isOp, org.spigotmc.SpigotConfig.whitelistMessage); - event.callEvent(); - if (!event.isWhitelisted()) { - if (loginEvent != null) { - loginEvent.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, event.getKickMessage() == null ? org.spigotmc.SpigotConfig.whitelistMessage : event.getKickMessage()); - } - return false; - } - return true; - } - // Paper end - - public boolean isOp(GameProfile gameprofile) { - return this.operators.d(gameprofile) || this.server.b(gameprofile) && this.server.getWorldServer(DimensionManager.OVERWORLD).getWorldData().t() || this.u; - } - - @Nullable - public EntityPlayer getPlayer(String s) { - return this.playersByName.get(s.toLowerCase(java.util.Locale.ROOT)); // Spigot - } - - public void sendPacketNearby(@Nullable EntityHuman entityhuman, double d0, double d1, double d2, double d3, DimensionManager dimensionmanager, Packet packet) { - // Paper start - Use world list instead of server list where preferable - sendPacketNearby(entityhuman, d0, d1, d2, d3, dimensionmanager, null, packet); // Retained for compatibility - } - - public void sendPacketNearby(@Nullable EntityHuman entityhuman, double d0, double d1, double d2, double d3, WorldServer world, Packet packet) { - sendPacketNearby(entityhuman, d0, d1, d2, d3, world.worldProvider.getDimensionManager(), world, packet); - } - - public void sendPacketNearby(@Nullable EntityHuman entityhuman, double d0, double d1, double d2, double d3, DimensionManager dimensionmanager, @Nullable WorldServer world, Packet packet) { - if (world == null && entityhuman != null && entityhuman.world instanceof WorldServer) { - world = (WorldServer) entityhuman.world; - } - - List players1 = world == null ? players : world.players; - for (int j = 0; j < players1.size(); ++j) { - EntityHuman entity = players1.get(j); - if (!(entity instanceof EntityPlayer)) continue; - EntityPlayer entityplayer = (EntityPlayer) entity; - // Paper end - - // CraftBukkit start - Test if player receiving packet can see the source of the packet - if (entityhuman != null && entityhuman instanceof EntityPlayer && !entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) { - continue; - } - // CraftBukkit end - - if (entityplayer != entityhuman && (world != null || entityplayer.dimension == dimensionmanager)) { // Paper - double d4 = d0 - entityplayer.locX; - double d5 = d1 - entityplayer.locY; - double d6 = d2 - entityplayer.locZ; - - if (d4 * d4 + d5 * d5 + d6 * d6 < d3 * d3) { - entityplayer.playerConnection.sendPacket(packet); - } - } - } - - } - - public void savePlayers() { - MCUtil.ensureMain("Save Players" , () -> { // Paper - Ensure main - MinecraftTimings.savePlayers.startTiming(); // Paper - for (int i = 0; i < this.players.size(); ++i) { - this.savePlayerFile((EntityPlayer) this.players.get(i)); - } - MinecraftTimings.savePlayers.stopTiming(); // Paper - return null; }); // Paper - ensure main - } - - public WhiteList getWhitelist() { - return this.whitelist; - } - - public String[] getWhitelisted() { - return this.whitelist.getEntries(); - } - - public OpList getOPs() { - return this.operators; - } - - public String[] m() { - return this.operators.getEntries(); - } - - public void reloadWhitelist() {} - - public void a(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(GameRules.DO_DAYLIGHT_CYCLE))); - BlockPosition blockposition = worldserver.getSpawn(); - - entityplayer.playerConnection.sendPacket(new PacketPlayOutSpawnPosition(blockposition)); - if (worldserver.isRaining()) { - // CraftBukkit start - handle player weather - // entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(1, 0.0F)); - // entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(7, worldserver.h(1.0F))); - // entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(8, worldserver.f(1.0F))); - entityplayer.setPlayerWeather(org.bukkit.WeatherType.DOWNFALL, false); - entityplayer.updateWeather(-worldserver.rainLevel, worldserver.rainLevel, -worldserver.thunderLevel, worldserver.thunderLevel); - // 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)); - // CraftBukkit start - from GameRules - int i = entityplayer.world.getGameRules().getBoolean(GameRules.REDUCED_DEBUG_INFO) ? 22 : 23; - entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, (byte) i)); - // CraftBukkit end - } - - public int getPlayerCount() { - return this.players.size(); - } - - public int getMaxPlayers() { - return this.maxPlayers; - } - - public boolean getHasWhitelist() { - return this.whitelist.isEnabled(); // Paper - } - - public void setHasWhitelist(boolean flag) { - new com.destroystokyo.paper.event.server.WhitelistToggleEvent(flag).callEvent(); - this.whitelist.setEnabled(flag); // Paper - } - - public List b(String s) { - List list = Lists.newArrayList(); - Iterator iterator = this.players.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - if (entityplayer.v().equals(s)) { - list.add(entityplayer); - } - } - - return list; - } - - public int getViewDistance() { - return this.viewDistance; - } - - public MinecraftServer getServer() { - return this.server; - } - - public NBTTagCompound r() { - return null; - } - - private void a(EntityPlayer entityplayer, EntityPlayer entityplayer1, GeneratorAccess generatoraccess) { - if (entityplayer1 != null) { - entityplayer.playerInteractManager.setGameMode(entityplayer1.playerInteractManager.getGameMode()); - } else if (this.t != null) { - entityplayer.playerInteractManager.setGameMode(this.t); - } - - entityplayer.playerInteractManager.b(generatoraccess.getWorldData().getGameType()); - } - - // Paper start - Extract method to allow for restarting flag - public void shutdown() { - this.shutdown(false); - } - - public void shutdown(boolean isRestarting) { - // CraftBukkit start - disconnect safely - for (EntityPlayer player : this.players) { - player.playerConnection.disconnect(!isRestarting ? this.server.server.getShutdownMessage() : org.spigotmc.SpigotConfig.restartMessage); // CraftBukkit - add custom shutdown message // Paper - add isRestarting flag - } - // CraftBukkit end - // Paper start - Remove collideRule team if it exists - if (this.collideRuleTeamName != null) { - final Scoreboard scoreboard = this.getServer().getWorldServer(DimensionManager.OVERWORLD).getScoreboard(); - final ScoreboardTeam team = scoreboard.getTeam(this.collideRuleTeamName); - if (team != null) scoreboard.removeTeam(team); - } - // Paper end - } - // Paper end - - // CraftBukkit start - public void sendMessage(IChatBaseComponent[] iChatBaseComponents) { - for (IChatBaseComponent component : iChatBaseComponents) { - sendMessage(component, true); - } - } - // CraftBukkit end - - public void sendMessage(IChatBaseComponent ichatbasecomponent, boolean flag) { - this.server.sendMessage(ichatbasecomponent); - ChatMessageType chatmessagetype = flag ? ChatMessageType.SYSTEM : ChatMessageType.CHAT; - - // CraftBukkit start - we run this through our processor first so we can get web links etc - this.sendAll(new PacketPlayOutChat(CraftChatMessage.fixComponent(ichatbasecomponent), chatmessagetype)); - // CraftBukkit end - } - - public void sendMessage(IChatBaseComponent ichatbasecomponent) { - this.sendMessage(ichatbasecomponent, true); - } - - public ServerStatisticManager getStatisticManager(EntityPlayer entityhuman) { - UUID uuid = entityhuman.getUniqueID(); - ServerStatisticManager serverstatisticmanager = uuid == null ? null : (ServerStatisticManager) entityhuman.getStatisticManager(); - // CraftBukkit end - - if (serverstatisticmanager == null) { - File file = new File(this.server.getWorldServer(DimensionManager.OVERWORLD).getDataManager().getDirectory(), "stats"); - File file1 = new File(file, uuid + ".json"); - - if (!file1.exists()) { - File file2 = new File(file, entityhuman.getDisplayName().getString() + ".json"); - - if (file2.exists() && file2.isFile()) { - file2.renameTo(file1); - } - } - - serverstatisticmanager = new ServerStatisticManager(this.server, file1); - // this.o.put(uuid, serverstatisticmanager); // CraftBukkit - } - - return serverstatisticmanager; - } - - public AdvancementDataPlayer f(EntityPlayer entityplayer) { - UUID uuid = entityplayer.getUniqueID(); - AdvancementDataPlayer advancementdataplayer = (AdvancementDataPlayer) entityplayer.getAdvancementData(); // CraftBukkit - - if (advancementdataplayer == null) { - File file = new File(this.server.getWorldServer(DimensionManager.OVERWORLD).getDataManager().getDirectory(), "advancements"); - File file1 = new File(file, uuid + ".json"); - - advancementdataplayer = new AdvancementDataPlayer(this.server, file1, entityplayer); - // this.p.put(uuid, advancementdataplayer); // CraftBukkit - } - - advancementdataplayer.a(entityplayer); - return advancementdataplayer; - } - - public void a(int i) { - this.viewDistance = i; - this.sendAll(new PacketPlayOutViewDistance(i)); - Iterator iterator = this.server.getWorlds().iterator(); - - while (iterator.hasNext()) { - WorldServer worldserver = (WorldServer) iterator.next(); - - if (worldserver != null) { - worldserver.getChunkProvider().setViewDistance(i); - } - } - - } - - public List getPlayers() { - return this.players; - } - - @Nullable - public EntityPlayer a(UUID uuid) { - return (EntityPlayer) this.j.get(uuid); - } - - public boolean f(GameProfile gameprofile) { - return false; - } - - public void reload() { - // CraftBukkit start - /*Iterator iterator = this.p.values().iterator(); - - while (iterator.hasNext()) { - AdvancementDataPlayer advancementdataplayer = (AdvancementDataPlayer) iterator.next(); - - advancementdataplayer.b(); - }*/ - - for (EntityPlayer player : players) { - player.getAdvancementData().b(); - player.getAdvancementData().b(player); // CraftBukkit - trigger immediate flush of advancements - } - // CraftBukkit end - - this.sendAll(new PacketPlayOutTags(this.server.getTagRegistry())); - PacketPlayOutRecipeUpdate packetplayoutrecipeupdate = new PacketPlayOutRecipeUpdate(this.server.getCraftingManager().b()); - Iterator iterator1 = this.players.iterator(); - - while (iterator1.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator1.next(); - - entityplayer.playerConnection.sendPacket(packetplayoutrecipeupdate); - entityplayer.B().a(entityplayer); - } - - } - - public boolean v() { - return this.u; - } -} diff --git a/src/main/java/net/minecraft/server/PortalTravelAgent.java b/src/main/java/net/minecraft/server/PortalTravelAgent.java deleted file mode 100644 index 2f0a8e4bb..000000000 --- a/src/main/java/net/minecraft/server/PortalTravelAgent.java +++ /dev/null @@ -1,369 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import it.unimi.dsi.fastutil.longs.LongIterator; -import it.unimi.dsi.fastutil.objects.Object2LongMap; -import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Random; -import java.util.Map.Entry; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.util.Supplier; - -public class PortalTravelAgent { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final BlockPortal b = (BlockPortal) Blocks.NETHER_PORTAL; - private final WorldServer world; - private final Random d; - private final Map e = Maps.newHashMapWithExpectedSize(4096); - private final Object2LongMap f = new Object2LongOpenHashMap(); - - public PortalTravelAgent(WorldServer worldserver) { - this.world = worldserver; - this.d = new Random(worldserver.getSeed()); - } - - public boolean a(Entity entity, float f) { - Vec3D vec3d = entity.getPortalOffset(); - EnumDirection enumdirection = entity.getPortalDirection(); - ShapeDetector.Shape shapedetector_shape = this.a(new BlockPosition(entity), entity.getMot(), enumdirection, vec3d.x, vec3d.y, entity instanceof EntityHuman); - - if (shapedetector_shape == null) { - return false; - } else { - Vec3D vec3d1 = shapedetector_shape.position; - Vec3D vec3d2 = shapedetector_shape.velocity; - - entity.setMot(vec3d2); - entity.yaw = f + (float) shapedetector_shape.yaw; - if (entity instanceof EntityPlayer) { - ((EntityPlayer) entity).playerConnection.a(vec3d1.x, vec3d1.y, vec3d1.z, entity.yaw, entity.pitch); - ((EntityPlayer) entity).playerConnection.syncPosition(); - } else { - entity.setPositionRotation(vec3d1.x, vec3d1.y, vec3d1.z, entity.yaw, entity.pitch); - } - - return true; - } - } - - @Nullable - public ShapeDetector.Shape a(BlockPosition blockposition, Vec3D vec3d, EnumDirection enumdirection, double d0, double d1, boolean flag) { - boolean flag1 = true; - boolean flag2 = true; - BlockPosition blockposition1 = null; - BlockPosition2D blockposition2d = new BlockPosition2D(blockposition); - - if (!flag && this.f.containsKey(blockposition2d)) { - return null; - } else { - PortalTravelAgent.ChunkCoordinatesPortal portaltravelagent_chunkcoordinatesportal = (PortalTravelAgent.ChunkCoordinatesPortal) this.e.get(blockposition2d); - - if (portaltravelagent_chunkcoordinatesportal != null) { - blockposition1 = portaltravelagent_chunkcoordinatesportal.a; - portaltravelagent_chunkcoordinatesportal.b = this.world.getTime(); - flag2 = false; - } else { - double d2 = Double.MAX_VALUE; - - int portalSearchRadius = world.paperConfig.portalSearchRadius; // Paper - for (int i = -portalSearchRadius; i <= portalSearchRadius; ++i) { // Paper - BlockPosition blockposition2; - - for (int j = -world.paperConfig.portalSearchRadius; j <= world.paperConfig.portalSearchRadius; ++j) { // Paper - for (BlockPosition blockposition3 = blockposition.b(i, this.world.getHeight() - 1 - blockposition.getY(), j); blockposition3.getY() >= 0; blockposition3 = blockposition2) { - blockposition2 = blockposition3.down(); - if (this.world.getType(blockposition3).getBlock() == PortalTravelAgent.b) { - for (blockposition2 = blockposition3.down(); this.world.getType(blockposition2).getBlock() == PortalTravelAgent.b; blockposition2 = blockposition2.down()) { - blockposition3 = blockposition2; - } - - double d3 = blockposition3.m(blockposition); - - if (d2 < 0.0D || d3 < d2) { - d2 = d3; - blockposition1 = blockposition3; - } - } - } - } - } - } - - if (blockposition1 == null) { - long k = this.world.getTime() + 300L; - - this.f.put(blockposition2d, k); - return null; - } else { - if (flag2) { - this.e.put(blockposition2d, new PortalTravelAgent.ChunkCoordinatesPortal(blockposition1, this.world.getTime())); - Logger logger = PortalTravelAgent.LOGGER; - Supplier[] asupplier = new Supplier[2]; - WorldProvider worldprovider = this.world.getWorldProvider(); - - asupplier[0] = worldprovider::getDimensionManager; - asupplier[1] = () -> { - return blockposition2d; - }; - logger.debug("Adding nether portal ticket for {}:{}", asupplier); - this.world.getChunkProvider().addTicket(TicketType.PORTAL, new ChunkCoordIntPair(blockposition1), 3, blockposition2d); - } - - ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = PortalTravelAgent.b.c((GeneratorAccess) this.world, blockposition1); - - return shapedetector_shapedetectorcollection.a(enumdirection, blockposition1, d1, vec3d, d0); - } - } - } - - public boolean a(Entity entity) { - boolean flag = true; - double d0 = -1.0D; - int i = MathHelper.floor(entity.locX); - int j = MathHelper.floor(entity.locY); - int k = MathHelper.floor(entity.locZ); - int l = i; - int i1 = j; - int j1 = k; - int k1 = 0; - int l1 = this.d.nextInt(4); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - double d1; - int i2; - double d2; - int j2; - 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 - 16; i2 <= i + 16; ++i2) { - d1 = (double) i2 + 0.5D - entity.locX; - - for (j2 = k - 16; j2 <= k + 16; ++j2) { - d2 = (double) j2 + 0.5D - entity.locZ; - - label257: - for (k2 = this.world.getHeight() - 1; k2 >= 0; --k2) { - if (this.world.isEmpty(blockposition_mutableblockposition.d(i2, k2, j2))) { - while (k2 > 0 && this.world.isEmpty(blockposition_mutableblockposition.d(i2, k2 - 1, j2))) { - --k2; - } - - for (i3 = l1; i3 < l1 + 4; ++i3) { - l2 = i3 % 2; - j3 = 1 - l2; - if (i3 % 4 >= 2) { - l2 = -l2; - j3 = -j3; - } - - for (l3 = 0; l3 < 3; ++l3) { - for (i4 = 0; i4 < 4; ++i4) { - for (k4 = -1; k4 < 4; ++k4) { - k3 = i2 + (i4 - 1) * l2 + l3 * j3; - j4 = k2 + k4; - int l4 = j2 + (i4 - 1) * j3 - l3 * l2; - - blockposition_mutableblockposition.d(k3, j4, l4); - if (k4 < 0 && !this.world.getType(blockposition_mutableblockposition).getMaterial().isBuildable() || k4 >= 0 && !this.world.isEmpty(blockposition_mutableblockposition)) { - continue label257; - } - } - } - } - - d3 = (double) k2 + 0.5D - entity.locY; - d4 = d1 * d1 + d3 * d3 + d2 * d2; - if (d0 < 0.0D || d4 < d0) { - d0 = d4; - l = i2; - i1 = k2; - j1 = j2; - k1 = i3 % 4; - } - } - } - } - } - } - - if (d0 < 0.0D) { - for (i2 = i - 16; i2 <= i + 16; ++i2) { - d1 = (double) i2 + 0.5D - entity.locX; - - for (j2 = k - 16; j2 <= k + 16; ++j2) { - d2 = (double) j2 + 0.5D - entity.locZ; - - label205: - for (k2 = this.world.getHeight() - 1; k2 >= 0; --k2) { - if (this.world.isEmpty(blockposition_mutableblockposition.d(i2, k2, j2))) { - while (k2 > 0 && this.world.isEmpty(blockposition_mutableblockposition.d(i2, k2 - 1, j2))) { - --k2; - } - - for (i3 = l1; i3 < l1 + 2; ++i3) { - l2 = i3 % 2; - j3 = 1 - l2; - - for (l3 = 0; l3 < 4; ++l3) { - for (i4 = -1; i4 < 4; ++i4) { - k4 = i2 + (l3 - 1) * l2; - k3 = k2 + i4; - j4 = j2 + (l3 - 1) * j3; - blockposition_mutableblockposition.d(k4, k3, j4); - if (i4 < 0 && !this.world.getType(blockposition_mutableblockposition).getMaterial().isBuildable() || i4 >= 0 && !this.world.isEmpty(blockposition_mutableblockposition)) { - continue label205; - } - } - } - - d3 = (double) k2 + 0.5D - entity.locY; - d4 = d1 * d1 + d3 * d3 + d2 * d2; - if (d0 < 0.0D || d4 < d0) { - d0 = d4; - l = i2; - i1 = k2; - j1 = j2; - k1 = i3 % 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; - } - - org.bukkit.craftbukkit.util.BlockStateListPopulator blockList = new org.bukkit.craftbukkit.util.BlockStateListPopulator(this.world); // CraftBukkit - Use BlockStateListPopulator - if (d0 < 0.0D) { - i1 = MathHelper.clamp(i1, 70, this.world.getHeight() - 10); - j5 = i1; - - for (k2 = -1; k2 <= 1; ++k2) { - for (i3 = 1; i3 < 3; ++i3) { - for (l2 = -1; l2 < 3; ++l2) { - j3 = i5 + (i3 - 1) * k5 + k2 * l5; - l3 = j5 + l2; - i4 = j2 + (i3 - 1) * l5 - k2 * k5; - boolean flag1 = l2 < 0; - - blockposition_mutableblockposition.d(j3, l3, i4); - blockList.setTypeAndData(blockposition_mutableblockposition, flag1 ? Blocks.OBSIDIAN.getBlockData() : Blocks.AIR.getBlockData(), 3); // CraftBukkit - } - } - } - } - - for (k2 = -1; k2 < 3; ++k2) { - for (i3 = -1; i3 < 4; ++i3) { - if (k2 == -1 || k2 == 2 || i3 == -1 || i3 == 3) { - blockposition_mutableblockposition.d(i5 + k2 * k5, j5 + i3, j2 + k2 * l5); - blockList.setTypeAndData(blockposition_mutableblockposition, Blocks.OBSIDIAN.getBlockData(), 3); // CraftBukkit - } - } - } - - IBlockData iblockdata = (IBlockData) PortalTravelAgent.b.getBlockData().set(BlockPortal.AXIS, k5 == 0 ? EnumDirection.EnumAxis.Z : EnumDirection.EnumAxis.X); - - for (i3 = 0; i3 < 2; ++i3) { - for (l2 = 0; l2 < 3; ++l2) { - blockposition_mutableblockposition.d(i5 + i3 * k5, j5 + l2, j2 + i3 * l5); - blockList.setTypeAndData(blockposition_mutableblockposition, iblockdata, 18); // CraftBukkit - } - } - - // CraftBukkit start - org.bukkit.World bworld = this.world.getWorld(); - org.bukkit.event.world.PortalCreateEvent event = new org.bukkit.event.world.PortalCreateEvent((java.util.List) (java.util.List) blockList.getList(), bworld, entity.getBukkitEntity(), org.bukkit.event.world.PortalCreateEvent.CreateReason.NETHER_PAIR); - - this.world.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - blockList.updateList(); - } - // CraftBukkit end - return true; - } - - public void a(long i) { - if (i % 100L == 0L) { - this.b(i); - this.c(i); - } - - } - - private void b(long i) { - LongIterator longiterator = this.f.values().iterator(); - - while (longiterator.hasNext()) { - long j = longiterator.nextLong(); - - if (j <= i) { - longiterator.remove(); - } - } - - } - - private void c(long i) { - long j = i - 300L; - Iterator iterator = this.e.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - PortalTravelAgent.ChunkCoordinatesPortal portaltravelagent_chunkcoordinatesportal = (PortalTravelAgent.ChunkCoordinatesPortal) entry.getValue(); - - if (portaltravelagent_chunkcoordinatesportal.b < j) { - BlockPosition2D blockposition2d = (BlockPosition2D) entry.getKey(); - Logger logger = PortalTravelAgent.LOGGER; - Supplier[] asupplier = new Supplier[2]; - WorldProvider worldprovider = this.world.getWorldProvider(); - - asupplier[0] = worldprovider::getDimensionManager; - asupplier[1] = () -> { - return blockposition2d; - }; - logger.debug("Removing nether portal ticket for {}:{}", asupplier); - this.world.getChunkProvider().removeTicket(TicketType.PORTAL, new ChunkCoordIntPair(portaltravelagent_chunkcoordinatesportal.a), 3, blockposition2d); - iterator.remove(); - } - } - - } - - static class ChunkCoordinatesPortal { - - public final BlockPosition a; - public long b; - - public ChunkCoordinatesPortal(BlockPosition blockposition, long i) { - this.a = blockposition; - this.b = i; - } - } -} diff --git a/src/main/java/net/minecraft/server/PotionUtil.java b/src/main/java/net/minecraft/server/PotionUtil.java deleted file mode 100644 index bf4172be5..000000000 --- a/src/main/java/net/minecraft/server/PotionUtil.java +++ /dev/null @@ -1,144 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -public class PotionUtil { - - public static List getEffects(ItemStack itemstack) { - return a(itemstack.getTag()); - } - - public static List a(PotionRegistry potionregistry, Collection collection) { - List list = Lists.newArrayList(); - - list.addAll(potionregistry.a()); - list.addAll(collection); - return list; - } - - public static List a(@Nullable NBTTagCompound nbttagcompound) { - List list = Lists.newArrayList(); - - list.addAll(c(nbttagcompound).a()); - a(nbttagcompound, (List) list); - return list; - } - - public static List b(ItemStack itemstack) { - return b(itemstack.getTag()); - } - - public static List b(@Nullable NBTTagCompound nbttagcompound) { - List list = Lists.newArrayList(); - - a(nbttagcompound, (List) list); - return list; - } - - public static void a(@Nullable NBTTagCompound nbttagcompound, List list) { - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("CustomPotionEffects", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("CustomPotionEffects", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompound(i); - MobEffect mobeffect = MobEffect.b(nbttagcompound1); - - if (mobeffect != null) { - list.add(mobeffect); - } - } - } - - } - - public static int c(ItemStack itemstack) { - NBTTagCompound nbttagcompound = itemstack.getTag(); - - return nbttagcompound != null && nbttagcompound.hasKeyOfType("CustomPotionColor", 99) ? nbttagcompound.getInt("CustomPotionColor") : (d(itemstack) == Potions.EMPTY ? 16253176 : a((Collection) getEffects(itemstack))); - } - - public static int a(PotionRegistry potionregistry) { - return potionregistry == Potions.EMPTY ? 16253176 : a((Collection) potionregistry.a()); - } - - public static int a(Collection collection) { - int i = 3694022; - - if (collection.isEmpty()) { - return 3694022; - } else { - float f = 0.0F; - float f1 = 0.0F; - float f2 = 0.0F; - int j = 0; - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - if (mobeffect.isShowParticles()) { - int k = mobeffect.getMobEffect().getColor(); - int l = mobeffect.getAmplifier() + 1; - - f += (float) (l * (k >> 16 & 255)) / 255.0F; - f1 += (float) (l * (k >> 8 & 255)) / 255.0F; - f2 += (float) (l * (k >> 0 & 255)) / 255.0F; - j += l; - } - } - - if (j == 0) { - return 0; - } else { - f = f / (float) j * 255.0F; - f1 = f1 / (float) j * 255.0F; - f2 = f2 / (float) j * 255.0F; - return (int) f << 16 | (int) f1 << 8 | (int) f2; - } - } - } - - public static PotionRegistry d(ItemStack itemstack) { - return c(itemstack.getTag()); - } - - public static PotionRegistry c(@Nullable NBTTagCompound nbttagcompound) { - return nbttagcompound == null ? Potions.EMPTY : PotionRegistry.a(nbttagcompound.getString("Potion")); - } - - public static ItemStack addPotionToItemStack(ItemStack itemstack, PotionRegistry potionregistry) { return a(itemstack, potionregistry); } // Paper - OBFHELPER - public static ItemStack a(ItemStack itemstack, PotionRegistry potionregistry) { - MinecraftKey minecraftkey = IRegistry.POTION.getKey(potionregistry); - - if (potionregistry == Potions.EMPTY) { - itemstack.removeTag("Potion"); - } else { - itemstack.getOrCreateTag().setString("Potion", minecraftkey.toString()); - } - - return itemstack; - } - - public static ItemStack a(ItemStack itemstack, Collection collection) { - if (collection.isEmpty()) { - return itemstack; - } else { - NBTTagCompound nbttagcompound = itemstack.getOrCreateTag(); - NBTTagList nbttaglist = nbttagcompound.getList("CustomPotionEffects", 9); - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - MobEffect mobeffect = (MobEffect) iterator.next(); - - nbttaglist.add(mobeffect.a(new NBTTagCompound())); - } - - nbttagcompound.set("CustomPotionEffects", nbttaglist); - return itemstack; - } - } -} diff --git a/src/main/java/net/minecraft/server/PropertyManager.java b/src/main/java/net/minecraft/server/PropertyManager.java deleted file mode 100644 index 729455ce5..000000000 --- a/src/main/java/net/minecraft/server/PropertyManager.java +++ /dev/null @@ -1,249 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.MoreObjects; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.util.Objects; -import java.util.Properties; -import java.util.function.Function; -import java.util.function.IntFunction; -import java.util.function.Supplier; -import java.util.function.UnaryOperator; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import joptsimple.OptionSet; // CraftBukkit - -public abstract class PropertyManager> { - - private static final Logger LOGGER = LogManager.getLogger(); - public final Properties properties; - // CraftBukkit start - private OptionSet options = null; - - public PropertyManager(Properties properties, final OptionSet options) { - this.properties = properties; - - this.options = options; - } - - private String getOverride(String name, String value) { - if ((this.options != null) && (this.options.has(name)) && !name.equals( "online-mode")) { // Spigot - return String.valueOf(this.options.valueOf(name)); - } - - return value; - } - // CraftBukkit end - - public static Properties loadPropertiesFile(java.nio.file.Path java_nio_file_path) { - Properties properties = new Properties(); - - try { - InputStream inputstream = Files.newInputStream(java_nio_file_path); - Throwable throwable = null; - - try { - properties.load(inputstream); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (inputstream != null) { - if (throwable != null) { - try { - inputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - inputstream.close(); - } - } - - } - } catch (IOException ioexception) { - PropertyManager.LOGGER.error("Failed to load properties from file: " + java_nio_file_path); - } - - return properties; - } - - public void savePropertiesFile(java.nio.file.Path java_nio_file_path) { - try { - // CraftBukkit start - Don't attempt writing to file if it's read only - if (java_nio_file_path.toFile().exists() && !java_nio_file_path.toFile().canWrite()) { - return; - } - // CraftBukkit end - OutputStream outputstream = Files.newOutputStream(java_nio_file_path); - Throwable throwable = null; - - try { - this.properties.store(outputstream, "Minecraft server properties"); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (outputstream != null) { - if (throwable != null) { - try { - outputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - outputstream.close(); - } - } - - } - } catch (IOException ioexception) { - PropertyManager.LOGGER.error("Failed to store properties to file: " + java_nio_file_path); - } - - } - - private static Function a(Function function) { - return (s) -> { - try { - return (V) function.apply(s); // CraftBukkit - decompile error - } catch (NumberFormatException numberformatexception) { - return null; - } - }; - } - - protected static Function a(IntFunction intfunction, Function function) { - return (s) -> { - try { - return intfunction.apply(Integer.parseInt(s)); - } catch (NumberFormatException numberformatexception) { - return function.apply(s); - } - }; - } - - @Nullable String getSettingIfExists(final String path) { return this.c(path); } // Paper - OBFHELPER - @Nullable private String c(String s) { // Paper - OBFHELPER - return (String) getOverride(s, this.properties.getProperty(s)); // CraftBukkit - } - - @Nullable - protected V a(String s, Function function) { - String s1 = this.c(s); - - if (s1 == null) { - return null; - } else { - this.properties.remove(s); - return function.apply(s1); - } - } - - protected V a(String s, Function function, Function function1, V v0) { - String s1 = this.c(s); - V v1 = MoreObjects.firstNonNull(s1 != null ? function.apply(s1) : null, v0); - - this.properties.put(s, function1.apply(v1)); - return v1; - } - - protected PropertyManager.EditableProperty b(String s, Function function, Function function1, V v0) { - String s1 = this.c(s); - V v1 = MoreObjects.firstNonNull(s1 != null ? function.apply(s1) : null, v0); - - this.properties.put(s, function1.apply(v1)); - return new PropertyManager.EditableProperty(s, v1, function1); // CraftBukkit - decompile error - } - - protected V a(String s, Function function, UnaryOperator unaryoperator, Function function1, V v0) { - return this.a(s, (s1) -> { - V v1 = function.apply(s1); - - return v1 != null ? unaryoperator.apply(v1) : null; - }, function1, v0); - } - - protected V a(String s, Function function, V v0) { - return this.a(s, function, Objects::toString, v0); - } - - protected PropertyManager.EditableProperty b(String s, Function function, V v0) { - return this.b(s, function, Objects::toString, v0); - } - - protected String getString(String s, String s1) { - return (String) this.a(s, Function.identity(), Function.identity(), s1); - } - - @Nullable - protected String a(String s) { - return (String) this.a(s, Function.identity()); - } - - protected int getInt(String s, int i) { - return (Integer) this.a(s, a(Integer::parseInt), i); // CraftBukkit - decompile error - } - - protected PropertyManager.EditableProperty b(String s, int i) { - return this.b(s, a(Integer::parseInt), i); - } - - protected int a(String s, UnaryOperator unaryoperator, int i) { - return (Integer) this.a(s, a(Integer::parseInt), unaryoperator, Objects::toString, i); - } - - protected long getLong(String s, long i) { - return (Long) this.a(s, a(Long::parseLong), i); // CraftBukkit - decompile error - } - - protected boolean getBoolean(String s, boolean flag) { - return (Boolean) this.a(s, Boolean::valueOf, (Object) flag); - } - - protected PropertyManager.EditableProperty b(String s, boolean flag) { - return this.b(s, Boolean::valueOf, flag); - } - - @Nullable - protected Boolean b(String s) { - return (Boolean) this.a(s, Boolean::valueOf); - } - - protected Properties a() { - Properties properties = new Properties(); - - properties.putAll(this.properties); - return properties; - } - - protected abstract T reload(Properties properties, OptionSet optionset); // CraftBukkit - - public class EditableProperty implements Supplier { - - private final String b; - private final V c; - private final Function d; - - private EditableProperty(String s, V object, Function function) { // CraftBukkit - decompile error - this.b = s; - this.c = object; - this.d = function; - } - - public V get() { - return this.c; - } - - public T set(V v0) { - Properties properties = PropertyManager.this.a(); - - properties.put(this.b, this.d.apply(v0)); - return PropertyManager.this.reload(properties, PropertyManager.this.options); // CraftBukkit - } - } -} diff --git a/src/main/java/net/minecraft/server/ProtoChunk.java b/src/main/java/net/minecraft/server/ProtoChunk.java deleted file mode 100644 index 7bad12eb0..000000000 --- a/src/main/java/net/minecraft/server/ProtoChunk.java +++ /dev/null @@ -1,512 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import it.unimi.dsi.fastutil.longs.LongOpenHashSet; -import it.unimi.dsi.fastutil.longs.LongSet; -import it.unimi.dsi.fastutil.shorts.ShortList; -import java.util.BitSet; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class ProtoChunk implements IChunkAccess { - - private static final Logger LOGGER = LogManager.getLogger(); - private final ChunkCoordIntPair b; - private volatile boolean c; - private BiomeBase[] d; - @Nullable - private volatile LightEngine e; - private final Map f; - private volatile ChunkStatus g; - private final Map h; - private final Map i; - private final ChunkSection[] j; - private final List k; - private final List l; - private final ShortList[] m; - private final Map n; - private final Map o; - private final ChunkConverter p; - private final ProtoChunkTickList q; - private final ProtoChunkTickList r; - private long s; - private final Map t; - private volatile boolean u; - private final GeneratorAccess world; // Paper - Anti-Xray - - public ProtoChunk(ChunkCoordIntPair chunkcoordintpair, ChunkConverter chunkconverter) { - // Paper start - add world parameter - this(chunkcoordintpair, chunkconverter, (GeneratorAccess)null); - } - public ProtoChunk(ChunkCoordIntPair chunkcoordintpair, ChunkConverter chunkconverter, GeneratorAccess world) { - // Paper end - this(chunkcoordintpair, chunkconverter, (ChunkSection[]) null, new ProtoChunkTickList<>((block) -> { - return block == null || block.getBlockData().isAir(); - }, chunkcoordintpair), new ProtoChunkTickList<>((fluidtype) -> { - return fluidtype == null || fluidtype == FluidTypes.EMPTY; - }, chunkcoordintpair), world); // Paper - add world parameter - } - - public ProtoChunk(ChunkCoordIntPair chunkcoordintpair, ChunkConverter chunkconverter, @Nullable ChunkSection[] achunksection, ProtoChunkTickList protochunkticklist, ProtoChunkTickList protochunkticklist1) { - // Paper start - add world parameter - this(chunkcoordintpair, chunkconverter, achunksection, protochunkticklist, protochunkticklist1, (GeneratorAccess)null); - } - public ProtoChunk(ChunkCoordIntPair chunkcoordintpair, ChunkConverter chunkconverter, @Nullable ChunkSection[] achunksection, ProtoChunkTickList protochunkticklist, ProtoChunkTickList protochunkticklist1, GeneratorAccess world) { - this.world = world; - // Paper end - this.f = Maps.newEnumMap(HeightMap.Type.class); - this.g = ChunkStatus.EMPTY; - this.h = Maps.newHashMap(); - this.i = Maps.newHashMap(); - this.j = new ChunkSection[16]; - this.k = Lists.newArrayList(); - this.l = Lists.newArrayList(); - this.m = new ShortList[16]; - this.n = Maps.newHashMap(); - this.o = Maps.newHashMap(); - this.t = Maps.newHashMap(); - this.b = chunkcoordintpair; - this.p = chunkconverter; - this.q = protochunkticklist; - this.r = protochunkticklist1; - if (achunksection != null) { - if (this.j.length == achunksection.length) { - System.arraycopy(achunksection, 0, this.j, 0, this.j.length); - } else { - ProtoChunk.LOGGER.warn("Could not set level chunk sections, array length is {} instead of {}", achunksection.length, this.j.length); - } - } - - } - - // Paper start - If loaded util - @Override - public Fluid getFluidIfLoaded(BlockPosition blockposition) { - return this.getFluid(blockposition); - } - - @Override - public IBlockData getTypeIfLoaded(BlockPosition blockposition) { - return this.getType(blockposition); - } - // Paper end - - @Override - public IBlockData getType(BlockPosition blockposition) { - int i = blockposition.getY(); - - if (World.b(i)) { - return Blocks.VOID_AIR.getBlockData(); - } else { - ChunkSection chunksection = this.getSections()[i >> 4]; - - return ChunkSection.a(chunksection) ? Blocks.AIR.getBlockData() : chunksection.getType(blockposition.getX() & 15, i & 15, blockposition.getZ() & 15); - } - } - - @Override - public Fluid getFluid(BlockPosition blockposition) { - int i = blockposition.getY(); - - if (World.b(i)) { - return FluidTypes.EMPTY.i(); - } else { - ChunkSection chunksection = this.getSections()[i >> 4]; - - return ChunkSection.a(chunksection) ? FluidTypes.EMPTY.i() : chunksection.b(blockposition.getX() & 15, i & 15, blockposition.getZ() & 15); - } - } - - @Override - public Stream m() { - return this.l.stream(); - } - - public ShortList[] w() { - ShortList[] ashortlist = new ShortList[16]; - Iterator iterator = this.l.iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition = (BlockPosition) iterator.next(); - - IChunkAccess.a(ashortlist, blockposition.getY() >> 4).add(l(blockposition)); - } - - return ashortlist; - } - - public void b(short short0, int i) { - this.k(a(short0, i, this.b)); - } - - public void k(BlockPosition blockposition) { - this.l.add(blockposition.immutableCopy()); - } - - @Nullable - @Override - public IBlockData setType(BlockPosition blockposition, IBlockData iblockdata, boolean flag) { - int i = blockposition.getX(); - int j = blockposition.getY(); - int k = blockposition.getZ(); - - if (j >= 0 && j < 256) { - if (this.j[j >> 4] == Chunk.a && iblockdata.getBlock() == Blocks.AIR) { - return iblockdata; - } else { - if (iblockdata.h() > 0) { - this.l.add(new BlockPosition((i & 15) + this.getPos().d(), j, (k & 15) + this.getPos().e())); - } - - ChunkSection chunksection = this.a(j >> 4); - IBlockData iblockdata1 = chunksection.setType(i & 15, j & 15, k & 15, iblockdata); - - if (this.g.b(ChunkStatus.FEATURES) && iblockdata != iblockdata1 && (iblockdata.b((IBlockAccess) this, blockposition) != iblockdata1.b((IBlockAccess) this, blockposition) || iblockdata.h() != iblockdata1.h() || iblockdata.g() || iblockdata1.g())) { - LightEngine lightengine = this.e(); - - lightengine.a(blockposition); - } - - EnumSet enumset = this.getChunkStatus().h(); - EnumSet enumset1 = null; - Iterator iterator = enumset.iterator(); - - HeightMap.Type heightmap_type; - - while (iterator.hasNext()) { - heightmap_type = (HeightMap.Type) iterator.next(); - HeightMap heightmap = (HeightMap) this.f.get(heightmap_type); - - if (heightmap == null) { - if (enumset1 == null) { - enumset1 = EnumSet.noneOf(HeightMap.Type.class); - } - - enumset1.add(heightmap_type); - } - } - - if (enumset1 != null) { - HeightMap.a(this, enumset1); - } - - iterator = enumset.iterator(); - - while (iterator.hasNext()) { - heightmap_type = (HeightMap.Type) iterator.next(); - ((HeightMap) this.f.get(heightmap_type)).a(i & 15, j, k & 15, iblockdata); - } - - return iblockdata1; - } - } else { - return Blocks.VOID_AIR.getBlockData(); - } - } - - public ChunkSection a(int i) { - if (this.j[i] == Chunk.a) { - this.j[i] = new ChunkSection(i << 4, this, this.world, true); // Paper - Anti-Xray - } - - return this.j[i]; - } - - @Override - public void setTileEntity(BlockPosition blockposition, TileEntity tileentity) { - tileentity.setPosition(blockposition); - this.h.put(blockposition, tileentity); - } - - @Override - public Set c() { - Set set = Sets.newHashSet(this.i.keySet()); - - set.addAll(this.h.keySet()); - return set; - } - - @Nullable - @Override - public TileEntity getTileEntity(BlockPosition blockposition) { - return (TileEntity) this.h.get(blockposition); - } - - public Map x() { - return this.h; - } - - public void b(NBTTagCompound nbttagcompound) { - this.k.add(nbttagcompound); - } - - @Override - public void a(Entity entity) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - entity.d(nbttagcompound); - this.b(nbttagcompound); - } - - public List y() { - return this.k; - } - - @Override - public void a(BiomeBase[] abiomebase) { - this.d = abiomebase; - } - - @Override - public BiomeBase[] getBiomeIndex() { - return this.d; - } - - @Override - public void setNeedsSaving(boolean flag) { - this.c = flag; - } - - @Override - public boolean isNeedsSaving() { - return this.c; - } - - @Override - public ChunkStatus getChunkStatus() { - return this.g; - } - - public void a(ChunkStatus chunkstatus) { - this.g = chunkstatus; - this.setNeedsSaving(true); - } - - @Override - public ChunkSection[] getSections() { - return this.j; - } - - @Nullable - @Override - public LightEngine e() { - return this.e; - } - - @Override - public Collection> f() { - return Collections.unmodifiableSet(this.f.entrySet()); - } - - @Override - public void a(HeightMap.Type heightmap_type, long[] along) { - this.b(heightmap_type).a(along); - } - - @Override - public HeightMap b(HeightMap.Type heightmap_type) { - return (HeightMap) this.f.computeIfAbsent(heightmap_type, (heightmap_type1) -> { - return new HeightMap(this, heightmap_type1); - }); - } - - @Override - public int a(HeightMap.Type heightmap_type, int i, int j) { - HeightMap heightmap = (HeightMap) this.f.get(heightmap_type); - - if (heightmap == null) { - HeightMap.a(this, EnumSet.of(heightmap_type)); - heightmap = (HeightMap) this.f.get(heightmap_type); - } - - return heightmap.a(i & 15, j & 15) - 1; - } - - @Override - public ChunkCoordIntPair getPos() { - return this.b; - } - - @Override - public void setLastSaved(long i) {} - - @Nullable - @Override - public StructureStart a(String s) { - return (StructureStart) this.n.get(s); - } - - @Override - public void a(String s, StructureStart structurestart) { - this.n.put(s, structurestart); - this.c = true; - } - - @Override - public Map h() { - return Collections.unmodifiableMap(this.n); - } - - @Override - public void a(Map map) { - this.n.clear(); - this.n.putAll(map); - this.c = true; - } - - @Override - public LongSet b(String s) { - return (LongSet) this.o.computeIfAbsent(s, (s1) -> { - return new LongOpenHashSet(); - }); - } - - @Override - public void a(String s, long i) { - ((LongSet) this.o.computeIfAbsent(s, (s1) -> { - return new LongOpenHashSet(); - })).add(i); - this.c = true; - } - - @Override - public Map v() { - return Collections.unmodifiableMap(this.o); - } - - @Override - public void b(Map map) { - this.o.clear(); - this.o.putAll(map); - this.c = true; - } - - public static short l(BlockPosition blockposition) { - int i = blockposition.getX(); - int j = blockposition.getY(); - int k = blockposition.getZ(); - int l = i & 15; - int i1 = j & 15; - int j1 = k & 15; - - return (short) (l | i1 << 4 | j1 << 8); - } - - public static BlockPosition a(short short0, int i, ChunkCoordIntPair chunkcoordintpair) { - int j = (short0 & 15) + (chunkcoordintpair.x << 4); - int k = (short0 >>> 4 & 15) + (i << 4); - int l = (short0 >>> 8 & 15) + (chunkcoordintpair.z << 4); - - return new BlockPosition(j, k, l); - } - - @Override - public void f(BlockPosition blockposition) { - if (!World.isOutsideWorld(blockposition)) { - IChunkAccess.a(this.m, blockposition.getY() >> 4).add(l(blockposition)); - } - - } - - @Override - public ShortList[] l() { - return this.m; - } - - @Override - public void a(short short0, int i) { - IChunkAccess.a(this.m, i).add(short0); - } - - @Override - public ProtoChunkTickList n() { - return this.q; - } - - @Override - public ProtoChunkTickList o() { - return this.r; - } - - @Override - public ChunkConverter p() { - return this.p; - } - - @Override - public void b(long i) { - this.s = i; - } - - @Override - public long q() { - return this.s; - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - this.i.put(new BlockPosition(nbttagcompound.getInt("x"), nbttagcompound.getInt("y"), nbttagcompound.getInt("z")), nbttagcompound); - } - - public Map z() { - return Collections.unmodifiableMap(this.i); - } - - @Override - public NBTTagCompound i(BlockPosition blockposition) { - return (NBTTagCompound) this.i.get(blockposition); - } - - @Nullable - @Override - public NBTTagCompound j(BlockPosition blockposition) { - TileEntity tileentity = this.getTileEntity(blockposition); - - return tileentity != null ? tileentity.save(new NBTTagCompound()) : (NBTTagCompound) this.i.get(blockposition); - } - - @Override - public void removeTileEntity(BlockPosition blockposition) { - this.h.remove(blockposition); - this.i.remove(blockposition); - } - - @Override - public BitSet a(WorldGenStage.Features worldgenstage_features) { - return (BitSet) this.t.computeIfAbsent(worldgenstage_features, (worldgenstage_features1) -> { - return new BitSet(65536); - }); - } - - public void a(WorldGenStage.Features worldgenstage_features, BitSet bitset) { - this.t.put(worldgenstage_features, bitset); - } - - @Override - public void a(LightEngine lightengine) { - this.e = lightengine; - } - - @Override - public boolean r() { - return this.u; - } - - @Override - public void b(boolean flag) { - this.u = flag; - this.setNeedsSaving(true); - } -} diff --git a/src/main/java/net/minecraft/server/Raid.java b/src/main/java/net/minecraft/server/Raid.java deleted file mode 100644 index fa15f20da..000000000 --- a/src/main/java/net/minecraft/server/Raid.java +++ /dev/null @@ -1,832 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -import java.util.function.Predicate; -import java.util.stream.Stream; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -public class Raid { - - private static final ChatMessage a = new ChatMessage("event.minecraft.raid", new Object[0]); - private static final ChatMessage b = new ChatMessage("event.minecraft.raid.victory", new Object[0]); - private static final ChatMessage c = new ChatMessage("event.minecraft.raid.defeat", new Object[0]); - private static final IChatBaseComponent d = Raid.a.g().a(" - ").addSibling(Raid.b); - private static final IChatBaseComponent e = Raid.a.g().a(" - ").addSibling(Raid.c); - private final Map f = Maps.newHashMap(); - private final Map> g = Maps.newHashMap(); - public final Set h = Sets.newHashSet(); // PAIL rename heroes, private -> public - public long i; // PAIL rename activeTicks, private -> public - private BlockPosition j; - private final WorldServer k; - private boolean l; - private final int m; - public float n; // PAIL rename originTotalHealth, private -> public - public int o; // PAIL rename badOmenLevel, private -> public - private boolean p; - private int q; - private final BossBattleServer r; - private int s; - private int t; - private final Random u; - public final int v; // PAIL rename totalWaves, private -> public - private Raid.Status w; - private int x; - private Optional y; - - public Raid(int i, WorldServer worldserver, BlockPosition blockposition) { - this.r = new BossBattleServer(Raid.a, BossBattle.BarColor.RED, BossBattle.BarStyle.NOTCHED_10); - this.u = new Random(); - this.y = Optional.empty(); - this.m = i; - this.k = worldserver; - this.p = true; - this.t = 300; - this.r.setProgress(0.0F); - this.j = blockposition; - this.v = this.a(worldserver.getDifficulty()); - this.w = Raid.Status.ONGOING; - } - - public Raid(WorldServer worldserver, NBTTagCompound nbttagcompound) { - this.r = new BossBattleServer(Raid.a, BossBattle.BarColor.RED, BossBattle.BarStyle.NOTCHED_10); - this.u = new Random(); - this.y = Optional.empty(); - this.k = worldserver; - this.m = nbttagcompound.getInt("Id"); - this.l = nbttagcompound.getBoolean("Started"); - this.p = nbttagcompound.getBoolean("Active"); - this.i = nbttagcompound.getLong("TicksActive"); - this.o = nbttagcompound.getInt("BadOmenLevel"); - this.q = nbttagcompound.getInt("GroupsSpawned"); - this.t = nbttagcompound.getInt("PreRaidTicks"); - this.s = nbttagcompound.getInt("PostRaidTicks"); - this.n = nbttagcompound.getFloat("TotalHealth"); - this.j = new BlockPosition(nbttagcompound.getInt("CX"), nbttagcompound.getInt("CY"), nbttagcompound.getInt("CZ")); - this.v = nbttagcompound.getInt("NumGroups"); - this.w = Raid.Status.b(nbttagcompound.getString("Status")); - this.h.clear(); - if (nbttagcompound.hasKeyOfType("HeroesOfTheVillage", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("HeroesOfTheVillage", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompound(i); - UUID uuid = nbttagcompound1.a("UUID"); - - this.h.add(uuid); - } - } - - } - - public boolean a() { - return this.e() || this.f(); - } - - public boolean b() { - return this.c() && this.r() == 0 && this.t > 0; - } - - public boolean c() { - return this.q > 0; - } - - public boolean d() { - return this.w == Raid.Status.STOPPED; - } - - public boolean e() { - return this.w == Raid.Status.VICTORY; - } - - public boolean f() { - return this.w == Raid.Status.LOSS; - } - - // CraftBukkit start - public boolean isInProgress() { - return this.w == Status.ONGOING; - } - // CraftBukkit end - - public World i() { - return this.k; - } - - public boolean j() { - return this.l; - } - - public int k() { - return this.q; - } - - private Predicate x() { - return (entityplayer) -> { - BlockPosition blockposition = new BlockPosition(entityplayer); - - return entityplayer.isAlive() && this.k.c_(blockposition) == this; - }; - } - - private void y() { - Set set = Sets.newHashSet(this.r.getPlayers()); - List list = this.k.a(this.x()); - Iterator iterator = list.iterator(); - - EntityPlayer entityplayer; - - while (iterator.hasNext()) { - entityplayer = (EntityPlayer) iterator.next(); - if (!set.contains(entityplayer)) { - this.r.addPlayer(entityplayer); - } - } - - iterator = set.iterator(); - - while (iterator.hasNext()) { - entityplayer = (EntityPlayer) iterator.next(); - if (!list.contains(entityplayer)) { - this.r.removePlayer(entityplayer); - } - } - - } - - public int l() { - return 5; - } - - public int m() { - return this.o; - } - - public void a(EntityHuman entityhuman) { - if (entityhuman.hasEffect(MobEffects.BAD_OMEN)) { - this.o += entityhuman.getEffect(MobEffects.BAD_OMEN).getAmplifier() + 1; - this.o = MathHelper.clamp(this.o, 0, this.l()); - } - - entityhuman.removeEffect(MobEffects.BAD_OMEN); - } - - public void n() { - this.p = false; - this.r.b(); - this.w = Raid.Status.STOPPED; - } - - public void o() { - if (!this.d()) { - if (this.w == Raid.Status.ONGOING) { - boolean flag = this.p; - - this.p = this.k.isLoaded(this.j); - if (this.k.getDifficulty() == EnumDifficulty.PEACEFUL) { - org.bukkit.craftbukkit.event.CraftEventFactory.callRaidStopEvent(this, org.bukkit.event.raid.RaidStopEvent.Reason.PEACE); // CraftBukkit - this.n(); - return; - } - - if (flag != this.p) { - this.r.setVisible(this.p); - } - - if (!this.p) { - return; - } - - if (!this.k.b_(this.j)) { - this.z(); - } - - if (!this.k.b_(this.j)) { - if (this.q > 0) { - this.w = Raid.Status.LOSS; - org.bukkit.craftbukkit.event.CraftEventFactory.callRaidFinishEvent(this, new java.util.ArrayList<>()); // CraftBukkit - } else { - org.bukkit.craftbukkit.event.CraftEventFactory.callRaidStopEvent(this, org.bukkit.event.raid.RaidStopEvent.Reason.NOT_IN_VILLAGE); // CraftBukkit - this.n(); - } - } - - ++this.i; - if (this.i >= 48000L) { - org.bukkit.craftbukkit.event.CraftEventFactory.callRaidStopEvent(this, org.bukkit.event.raid.RaidStopEvent.Reason.TIMEOUT); // CraftBukkit - this.n(); - return; - } - - int i = this.r(); - boolean flag1; - - if (i == 0 && this.A()) { - if (this.t > 0) { - flag1 = this.y.isPresent(); - boolean flag2 = !flag1 && this.t % 5 == 0; - - if (flag1 && !this.k.getChunkProvider().a(new ChunkCoordIntPair((BlockPosition) this.y.get()))) { - flag2 = true; - } - - if (flag2) { - byte b0 = 0; - - if (this.t < 100) { - b0 = 1; - } else if (this.t < 40) { - b0 = 2; - } - - this.y = this.d(b0); - } - - if (this.t == 300 || this.t % 20 == 0) { - this.y(); - } - - --this.t; - this.r.setProgress(MathHelper.a((float) (300 - this.t) / 300.0F, 0.0F, 1.0F)); - } else if (this.t == 0 && this.q > 0) { - this.t = 300; - this.r.a((IChatBaseComponent) Raid.a); - return; - } - } - - if (this.i % 20L == 0L) { - this.y(); - this.F(); - if (i > 0) { - if (i <= 2) { - this.r.a(Raid.a.g().a(" - ").addSibling(new ChatMessage("event.minecraft.raid.raiders_remaining", new Object[]{i}))); - } else { - this.r.a((IChatBaseComponent) Raid.a); - } - } else { - this.r.a((IChatBaseComponent) Raid.a); - } - } - - flag1 = false; - int j = 0; - - while (this.G()) { - BlockPosition blockposition = this.y.isPresent() ? (BlockPosition) this.y.get() : this.a(j, 20); - - if (blockposition != null) { - this.l = true; - this.b(blockposition); - if (!flag1) { - this.a(blockposition); - flag1 = true; - } - } else { - ++j; - } - - if (j > 3) { - org.bukkit.craftbukkit.event.CraftEventFactory.callRaidStopEvent(this, org.bukkit.event.raid.RaidStopEvent.Reason.UNSPAWNABLE); // CraftBukkit - this.n(); - break; - } - } - - if (this.j() && !this.A() && i == 0) { - if (this.s < 40) { - ++this.s; - } else { - this.w = Raid.Status.VICTORY; - Iterator iterator = this.h.iterator(); - - List winners = new java.util.ArrayList<>(); // CraftBukkit - while (iterator.hasNext()) { - UUID uuid = (UUID) iterator.next(); - Entity entity = this.k.getEntity(uuid); - - if (entity instanceof EntityLiving && !entity.isSpectator()) { - EntityLiving entityliving = (EntityLiving) entity; - - entityliving.addEffect(new MobEffect(MobEffects.HERO_OF_THE_VILLAGE, 48000, this.o - 1, false, false, true)); - if (entityliving instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entityliving; - - entityplayer.a(StatisticList.RAID_WIN); - CriterionTriggers.H.a(entityplayer); - winners.add(entityplayer.getBukkitEntity()); // CraftBukkit - } - } - } - org.bukkit.craftbukkit.event.CraftEventFactory.callRaidFinishEvent(this, winners); // CraftBukkit - } - } - - this.H(); - } else if (this.a()) { - ++this.x; - if (this.x >= 600) { - org.bukkit.craftbukkit.event.CraftEventFactory.callRaidStopEvent(this, org.bukkit.event.raid.RaidStopEvent.Reason.FINISHED); // CraftBukkit - this.n(); - return; - } - - if (this.x % 20 == 0) { - this.y(); - this.r.setVisible(true); - if (this.e()) { - this.r.setProgress(0.0F); - this.r.a(Raid.d); - } else { - this.r.a(Raid.e); - } - } - } - - } - } - - private void z() { - Stream stream = SectionPosition.a(SectionPosition.a(this.j), 2); - WorldServer worldserver = this.k; - - this.k.getClass(); - stream.filter(worldserver::a).map(SectionPosition::t).min(Comparator.comparingDouble((blockposition) -> { - return blockposition.m(this.j); - })).ifPresent(this::c); - } - - private Optional d(int i) { - for (int j = 0; j < 3; ++j) { - BlockPosition blockposition = this.a(i, 1); - - if (blockposition != null) { - return Optional.of(blockposition); - } - } - - return Optional.empty(); - } - - private boolean A() { - return this.C() ? !this.D() : !this.B(); - } - - private boolean B() { - return this.k() == this.v; - } - - private boolean C() { - return this.o > 1; - } - - private boolean D() { - return this.k() > this.v; - } - - private boolean E() { - return this.B() && this.r() == 0 && this.C(); - } - - private void F() { - Iterator> iterator = this.g.values().iterator(); - HashSet hashset = Sets.newHashSet(); - - while (iterator.hasNext()) { - Set set = (Set) iterator.next(); - Iterator iterator1 = set.iterator(); - - while (iterator1.hasNext()) { - EntityRaider entityraider = (EntityRaider) iterator1.next(); - BlockPosition blockposition = new BlockPosition(entityraider); - - if (!entityraider.dead && entityraider.dimension == this.k.getWorldProvider().getDimensionManager() && this.j.m(blockposition) < 12544.0D) { - if (entityraider.ticksLived > 600) { - if (this.k.getEntity(entityraider.getUniqueID()) == null) { - hashset.add(entityraider); - } - - if (!this.k.b_(blockposition) && entityraider.cw() > 2400) { - entityraider.b(entityraider.en() + 1); - } - - if (entityraider.en() >= 30) { - hashset.add(entityraider); - } - } - } else { - hashset.add(entityraider); - } - } - } - - Iterator iterator2 = hashset.iterator(); - - while (iterator2.hasNext()) { - EntityRaider entityraider1 = (EntityRaider) iterator2.next(); - - this.a(entityraider1, true); - } - - } - - private void a(BlockPosition blockposition) { - float f = 13.0F; - boolean flag = true; - Iterator iterator = this.k.getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman = (EntityHuman) iterator.next(); - Vec3D vec3d = new Vec3D(entityhuman.locX, entityhuman.locY, entityhuman.locZ); - Vec3D vec3d1 = new Vec3D((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()); - float f1 = MathHelper.sqrt((vec3d1.x - vec3d.x) * (vec3d1.x - vec3d.x) + (vec3d1.z - vec3d.z) * (vec3d1.z - vec3d.z)); - double d0 = vec3d.x + (double) (13.0F / f1) * (vec3d1.x - vec3d.x); - double d1 = vec3d.z + (double) (13.0F / f1) * (vec3d1.z - vec3d.z); - - if (f1 <= 64.0F || this.k.b_(new BlockPosition(entityhuman))) { - ((EntityPlayer) entityhuman).playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(SoundEffects.EVENT_RAID_HORN, SoundCategory.NEUTRAL, d0, entityhuman.locY, d1, 64.0F, 1.0F)); - } - } - - } - - private void b(BlockPosition blockposition) { - boolean flag = false; - int i = this.q + 1; - - this.n = 0.0F; - DifficultyDamageScaler difficultydamagescaler = this.k.getDamageScaler(blockposition); - boolean flag1 = this.E(); - Raid.Wave[] araid_wave = Raid.Wave.f; - int j = araid_wave.length; - - // CraftBukkit start - EntityRaider leader = null; - List raiders = new java.util.ArrayList<>(); - // CraftBukkit end - for (int k = 0; k < j; ++k) { - Raid.Wave raid_wave = araid_wave[k]; - int l = this.a(raid_wave, i, flag1) + this.a(raid_wave, this.u, i, difficultydamagescaler, flag1); - int i1 = 0; - - for (int j1 = 0; j1 < l; ++j1) { - EntityRaider entityraider = (EntityRaider) raid_wave.g.a((World) this.k); - - if (!flag && entityraider.dX()) { - entityraider.setPatrolLeader(true); - this.a(i, entityraider); - flag = true; - leader = entityraider; // CraftBukkit - } - - this.a(i, entityraider, blockposition, false); - raiders.add(entityraider); // CraftBukkit - if (raid_wave.g == EntityTypes.RAVAGER) { - EntityRaider entityraider1 = null; - - if (i == this.a(EnumDifficulty.NORMAL)) { - entityraider1 = (EntityRaider) EntityTypes.PILLAGER.a((World) this.k); - } else if (i >= this.a(EnumDifficulty.HARD)) { - if (i1 == 0) { - entityraider1 = (EntityRaider) EntityTypes.EVOKER.a((World) this.k); - } else { - entityraider1 = (EntityRaider) EntityTypes.VINDICATOR.a((World) this.k); - } - } - - ++i1; - if (entityraider1 != null) { - this.a(i, entityraider1, blockposition, false); - entityraider1.setPositionRotation(blockposition, 0.0F, 0.0F); - entityraider1.startRiding(entityraider); - raiders.add(entityraider); // CraftBukkit - } - } - } - } - - this.y = Optional.empty(); - ++this.q; - this.p(); - this.H(); - org.bukkit.craftbukkit.event.CraftEventFactory.callRaidSpawnWaveEvent(this, leader, raiders); // CraftBukkit - } - - public void a(int i, EntityRaider entityraider, @Nullable BlockPosition blockposition, boolean flag) { - boolean flag1 = this.b(i, entityraider); - - if (flag1) { - entityraider.a(this); - entityraider.a(i); - entityraider.t(true); - entityraider.b(0); - if (!flag && blockposition != null) { - entityraider.setPosition((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 1.0D, (double) blockposition.getZ() + 0.5D); - entityraider.prepare(this.k, this.k.getDamageScaler(blockposition), EnumMobSpawn.EVENT, (GroupDataEntity) null, (NBTTagCompound) null); - entityraider.a(i, false); - entityraider.onGround = true; - this.k.addEntity(entityraider, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.RAID); // CraftBukkit - } - } - - } - - public void p() { - this.r.setProgress(MathHelper.a(this.q() / this.n, 0.0F, 1.0F)); - } - - public float q() { - float f = 0.0F; - Iterator iterator = this.g.values().iterator(); - - while (iterator.hasNext()) { - Set set = (Set) iterator.next(); - - EntityRaider entityraider; - - for (Iterator iterator1 = set.iterator(); iterator1.hasNext(); f += entityraider.getHealth()) { - entityraider = (EntityRaider) iterator1.next(); - } - } - - return f; - } - - private boolean G() { - return this.t == 0 && (this.q < this.v || this.E()) && this.r() == 0; - } - - public int r() { - return this.g.values().stream().mapToInt(Set::size).sum(); - } - - public void a(@Nonnull EntityRaider entityraider, boolean flag) { - Set set = (Set) this.g.get(entityraider.el()); - - if (set != null) { - boolean flag1 = set.remove(entityraider); - - if (flag1) { - if (flag) { - this.n -= entityraider.getHealth(); - } - - entityraider.a((Raid) null); - this.p(); - this.H(); - } - } - - } - - private void H() { - this.k.C().b(); - } - - public static ItemStack s() { - ItemStack itemstack = new ItemStack(Items.WHITE_BANNER); - NBTTagCompound nbttagcompound = itemstack.a("BlockEntityTag"); - NBTTagList nbttaglist = (new EnumBannerPatternType.a()).a(EnumBannerPatternType.RHOMBUS_MIDDLE, EnumColor.CYAN).a(EnumBannerPatternType.STRIPE_BOTTOM, EnumColor.LIGHT_GRAY).a(EnumBannerPatternType.STRIPE_CENTER, EnumColor.GRAY).a(EnumBannerPatternType.BORDER, EnumColor.LIGHT_GRAY).a(EnumBannerPatternType.STRIPE_MIDDLE, EnumColor.BLACK).a(EnumBannerPatternType.HALF_HORIZONTAL, EnumColor.LIGHT_GRAY).a(EnumBannerPatternType.CIRCLE_MIDDLE, EnumColor.LIGHT_GRAY).a(EnumBannerPatternType.BORDER, EnumColor.BLACK).a(); - - nbttagcompound.set("Patterns", nbttaglist); - itemstack.a((new ChatMessage("block.minecraft.ominous_banner", new Object[0])).a(EnumChatFormat.GOLD)); - return itemstack; - } - - @Nullable - public EntityRaider b(int i) { - return (EntityRaider) this.f.get(i); - } - - @Nullable - private BlockPosition a(int i, int j) { - int k = i == 0 ? 2 : 2 - i; - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - - for (int l = 0; l < j; ++l) { - float f = this.k.random.nextFloat() * 6.2831855F; - int i1 = this.j.getX() + MathHelper.d(MathHelper.cos(f) * 32.0F * (float) k) + this.k.random.nextInt(5); - int j1 = this.j.getZ() + MathHelper.d(MathHelper.sin(f) * 32.0F * (float) k) + this.k.random.nextInt(5); - int k1 = this.k.a(HeightMap.Type.WORLD_SURFACE, i1, j1); - - blockposition_mutableblockposition.d(i1, k1, j1); - if ((!this.k.b_(blockposition_mutableblockposition) || i >= 2) && this.k.isAreaLoaded(blockposition_mutableblockposition.getX() - 10, blockposition_mutableblockposition.getY() - 10, blockposition_mutableblockposition.getZ() - 10, blockposition_mutableblockposition.getX() + 10, blockposition_mutableblockposition.getY() + 10, blockposition_mutableblockposition.getZ() + 10) && this.k.getChunkProvider().a(new ChunkCoordIntPair(blockposition_mutableblockposition)) && (SpawnerCreature.a(EntityPositionTypes.Surface.ON_GROUND, (IWorldReader) this.k, (BlockPosition) blockposition_mutableblockposition, EntityTypes.RAVAGER) || this.k.getType(blockposition_mutableblockposition.down()).getBlock() == Blocks.SNOW && this.k.getType(blockposition_mutableblockposition).isAir())) { - return blockposition_mutableblockposition; - } - } - - return null; - } - - private boolean b(int i, EntityRaider entityraider) { - return this.a(i, entityraider, true); - } - - public boolean a(int i, EntityRaider entityraider, boolean flag) { - this.g.computeIfAbsent(i, (integer) -> { - return Sets.newHashSet(); - }); - Set set = (Set) this.g.get(i); - EntityRaider entityraider1 = null; - Iterator iterator = set.iterator(); - - while (iterator.hasNext()) { - EntityRaider entityraider2 = (EntityRaider) iterator.next(); - - if (entityraider2.getUniqueID().equals(entityraider.getUniqueID())) { - entityraider1 = entityraider2; - break; - } - } - - if (entityraider1 != null) { - set.remove(entityraider1); - set.add(entityraider); - } - - set.add(entityraider); - if (flag) { - this.n += entityraider.getHealth(); - } - - this.p(); - this.H(); - return true; - } - - public void a(int i, EntityRaider entityraider) { - this.f.put(i, entityraider); - entityraider.setSlot(EnumItemSlot.HEAD, s()); - entityraider.a(EnumItemSlot.HEAD, 2.0F); - } - - public void c(int i) { - this.f.remove(i); - } - - public BlockPosition t() { - return this.j; - } - - private void c(BlockPosition blockposition) { - this.j = blockposition; - } - - public int u() { - return this.m; - } - - private int a(Raid.Wave raid_wave, int i, boolean flag) { - return flag ? raid_wave.h[this.v] : raid_wave.h[i]; - } - - private int a(Raid.Wave raid_wave, Random random, int i, DifficultyDamageScaler difficultydamagescaler, boolean flag) { - EnumDifficulty enumdifficulty = difficultydamagescaler.a(); - boolean flag1 = enumdifficulty == EnumDifficulty.EASY; - boolean flag2 = enumdifficulty == EnumDifficulty.NORMAL; - int j; - - switch (raid_wave) { - case WITCH: - if (flag1 || i <= 2 || i == 4) { - return 0; - } - - j = 1; - break; - case PILLAGER: - case VINDICATOR: - if (flag1) { - j = random.nextInt(2); - } else if (flag2) { - j = 1; - } else { - j = 2; - } - break; - case RAVAGER: - j = !flag1 && flag ? 1 : 0; - break; - default: - return 0; - } - - return j > 0 ? random.nextInt(j + 1) : 0; - } - - public boolean v() { - return this.p; - } - - public NBTTagCompound a(NBTTagCompound nbttagcompound) { - nbttagcompound.setInt("Id", this.m); - nbttagcompound.setBoolean("Started", this.l); - nbttagcompound.setBoolean("Active", this.p); - nbttagcompound.setLong("TicksActive", this.i); - nbttagcompound.setInt("BadOmenLevel", this.o); - nbttagcompound.setInt("GroupsSpawned", this.q); - nbttagcompound.setInt("PreRaidTicks", this.t); - nbttagcompound.setInt("PostRaidTicks", this.s); - nbttagcompound.setFloat("TotalHealth", this.n); - nbttagcompound.setInt("NumGroups", this.v); - nbttagcompound.setString("Status", this.w.a()); - nbttagcompound.setInt("CX", this.j.getX()); - nbttagcompound.setInt("CY", this.j.getY()); - nbttagcompound.setInt("CZ", this.j.getZ()); - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.h.iterator(); - - while (iterator.hasNext()) { - UUID uuid = (UUID) iterator.next(); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - nbttagcompound1.a("UUID", uuid); - nbttaglist.add(nbttagcompound1); - } - - nbttagcompound.set("HeroesOfTheVillage", nbttaglist); - return nbttagcompound; - } - - public int a(EnumDifficulty enumdifficulty) { - switch (enumdifficulty) { - case EASY: - return 3; - case NORMAL: - return 5; - case HARD: - return 7; - default: - return 0; - } - } - - public float w() { - int i = this.m(); - - return i == 2 ? 0.1F : (i == 3 ? 0.25F : (i == 4 ? 0.5F : (i == 5 ? 0.75F : 0.0F))); - } - - public void a(Entity entity) { - this.h.add(entity.getUniqueID()); - } - - // CraftBukkit start - a method to get all raiders - public java.util.Collection getRaiders() { - return this.g.values().stream().flatMap(Set::stream).collect(java.util.stream.Collectors.toSet()); - } - // CraftBukkit end - - static enum Wave { - - VINDICATOR(EntityTypes.VINDICATOR, new int[]{0, 0, 2, 0, 1, 4, 2, 5}), EVOKER(EntityTypes.EVOKER, new int[]{0, 0, 0, 0, 0, 1, 1, 2}), PILLAGER(EntityTypes.PILLAGER, new int[]{0, 4, 3, 3, 4, 4, 4, 2}), WITCH(EntityTypes.WITCH, new int[]{0, 0, 0, 0, 3, 0, 0, 1}), RAVAGER(EntityTypes.RAVAGER, new int[]{0, 0, 0, 1, 0, 1, 0, 2}); - - private static final Raid.Wave[] f = values(); - private final EntityTypes g; - private final int[] h; - - private Wave(EntityTypes entitytypes, int[] aint) { - this.g = entitytypes; - this.h = aint; - } - } - - static enum Status { - - ONGOING, VICTORY, LOSS, STOPPED; - - private static final Raid.Status[] e = values(); - - private Status() {} - - private static Raid.Status b(String s) { - Raid.Status[] araid_status = Raid.Status.e; - int i = araid_status.length; - - for (int j = 0; j < i; ++j) { - Raid.Status raid_status = araid_status[j]; - - if (s.equalsIgnoreCase(raid_status.name())) { - return raid_status; - } - } - - return Raid.Status.ONGOING; - } - - public String a() { - return this.name().toLowerCase(Locale.ROOT); - } - } -} diff --git a/src/main/java/net/minecraft/server/RandomPositionGenerator.java b/src/main/java/net/minecraft/server/RandomPositionGenerator.java deleted file mode 100644 index 643dc0241..000000000 --- a/src/main/java/net/minecraft/server/RandomPositionGenerator.java +++ /dev/null @@ -1,172 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import java.util.function.ToDoubleFunction; -import javax.annotation.Nullable; - -public class RandomPositionGenerator { - - @Nullable - public static Vec3D a(EntityCreature entitycreature, int i, int j) { - return d(entitycreature, i, j, (Vec3D) null); - } - - @Nullable - public static Vec3D b(EntityCreature entitycreature, int i, int j) { - entitycreature.getClass(); - return a(entitycreature, i, j, entitycreature::f); - } - - @Nullable - public static Vec3D a(EntityCreature entitycreature, int i, int j, ToDoubleFunction todoublefunction) { - return a(entitycreature, i, j, (Vec3D) null, false, 0.0D, todoublefunction); - } - - @Nullable - public static Vec3D a(EntityCreature entitycreature, int i, int j, Vec3D vec3d) { - Vec3D vec3d1 = vec3d.a(entitycreature.locX, entitycreature.locY, entitycreature.locZ); - - return d(entitycreature, i, j, vec3d1); - } - - @Nullable - public static Vec3D a(EntityCreature entitycreature, int i, int j, Vec3D vec3d, double d0) { - Vec3D vec3d1 = vec3d.a(entitycreature.locX, entitycreature.locY, entitycreature.locZ); - - entitycreature.getClass(); - return a(entitycreature, i, j, vec3d1, true, d0, entitycreature::f); - } - - @Nullable - public static Vec3D b(EntityCreature entitycreature, int i, int j, Vec3D vec3d) { - Vec3D vec3d1 = (new Vec3D(entitycreature.locX, entitycreature.locY, entitycreature.locZ)).d(vec3d); - - entitycreature.getClass(); - return a(entitycreature, i, j, vec3d1, false, 1.5707963705062866D, entitycreature::f); - } - - @Nullable - public static Vec3D c(EntityCreature entitycreature, int i, int j, Vec3D vec3d) { - Vec3D vec3d1 = (new Vec3D(entitycreature.locX, entitycreature.locY, entitycreature.locZ)).d(vec3d); - - return d(entitycreature, i, j, vec3d1); - } - - @Nullable - private static Vec3D d(EntityCreature entitycreature, int i, int j, @Nullable Vec3D vec3d) { - entitycreature.getClass(); - return a(entitycreature, i, j, vec3d, true, 1.5707963705062866D, entitycreature::f); - } - - @Nullable - private static Vec3D a(EntityCreature entitycreature, int i, int j, @Nullable Vec3D vec3d, boolean flag, double d0, ToDoubleFunction todoublefunction) { - NavigationAbstract navigationabstract = entitycreature.getNavigation(); - Random random = entitycreature.getRandom(); - boolean flag1; - - if (entitycreature.dL()) { - flag1 = entitycreature.dI().a((IPosition) entitycreature.getPositionVector(), (double) (entitycreature.dJ() + (float) i) + 1.0D); - } else { - flag1 = false; - } - - boolean flag2 = false; - double d1 = Double.NEGATIVE_INFINITY; - BlockPosition blockposition = new BlockPosition(entitycreature); - - for (int k = 0; k < 10; ++k) { - BlockPosition blockposition1 = a(random, i, j, vec3d, d0); - - if (blockposition1 != null) { - int l = blockposition1.getX(); - int i1 = blockposition1.getY(); - int j1 = blockposition1.getZ(); - BlockPosition blockposition2; - - if (entitycreature.dL() && i > 1) { - blockposition2 = entitycreature.dI(); - if (entitycreature.locX > (double) blockposition2.getX()) { - l -= random.nextInt(i / 2); - } else { - l += random.nextInt(i / 2); - } - - if (entitycreature.locZ > (double) blockposition2.getZ()) { - j1 -= random.nextInt(i / 2); - } else { - j1 += random.nextInt(i / 2); - } - } - - blockposition2 = new BlockPosition((double) l + entitycreature.locX, (double) i1 + entitycreature.locY, (double) j1 + entitycreature.locZ); - if (!entitycreature.world.isLoaded(blockposition2)) continue; // Paper - if ((!flag1 || entitycreature.a(blockposition2)) && navigationabstract.a(blockposition2)) { - if (!flag) { - blockposition2 = a(blockposition2, entitycreature); - if (b(blockposition2, entitycreature)) { - continue; - } - } - - double d2 = todoublefunction.applyAsDouble(blockposition2); - - if (d2 > d1) { - d1 = d2; - blockposition = blockposition2; - flag2 = true; - } - } - } - } - - if (flag2) { - return new Vec3D(blockposition); - } else { - return null; - } - } - - @Nullable - private static BlockPosition a(Random random, int i, int j, @Nullable Vec3D vec3d, double d0) { - if (vec3d != null && d0 < 3.141592653589793D) { - double d1 = MathHelper.d(vec3d.z, vec3d.x) - 1.5707963705062866D; - double d2 = d1 + (double) (2.0F * random.nextFloat() - 1.0F) * d0; - double d3 = Math.sqrt(random.nextDouble()) * (double) MathHelper.a * (double) i; - double d4 = -d3 * Math.sin(d2); - double d5 = d3 * Math.cos(d2); - - if (Math.abs(d4) <= (double) i && Math.abs(d5) <= (double) i) { - int k = random.nextInt(2 * j + 1) - j; - - return new BlockPosition(d4, (double) k, d5); - } else { - return null; - } - } else { - int l = random.nextInt(2 * i + 1) - i; - int i1 = random.nextInt(2 * j + 1) - j; - int j1 = random.nextInt(2 * i + 1) - i; - - return new BlockPosition(l, i1, j1); - } - } - - private static BlockPosition a(BlockPosition blockposition, EntityCreature entitycreature) { - if (!entitycreature.world.getType(blockposition).getMaterial().isBuildable()) { - return blockposition; - } else { - BlockPosition blockposition1; - - for (blockposition1 = blockposition.up(); blockposition1.getY() < entitycreature.world.getBuildHeight() && entitycreature.world.getType(blockposition1).getMaterial().isBuildable(); blockposition1 = blockposition1.up()) { - ; - } - - return blockposition1; - } - } - - private static boolean b(BlockPosition blockposition, EntityCreature entitycreature) { - Fluid fluid = entitycreature.world.getFluidIfLoaded(blockposition); // Paper - return fluid != null && fluid.a(TagsFluid.WATER); // Paper - } -} diff --git a/src/main/java/net/minecraft/server/RayTrace.java b/src/main/java/net/minecraft/server/RayTrace.java deleted file mode 100644 index 615c18277..000000000 --- a/src/main/java/net/minecraft/server/RayTrace.java +++ /dev/null @@ -1,76 +0,0 @@ -package net.minecraft.server; - -import java.util.function.Predicate; - -public class RayTrace { - - private final Vec3D a; - private final Vec3D b; - private final RayTrace.BlockCollisionOption c; - private final RayTrace.FluidCollisionOption d; - private final VoxelShapeCollision e; - - public RayTrace(Vec3D vec3d, Vec3D vec3d1, RayTrace.BlockCollisionOption raytrace_blockcollisionoption, RayTrace.FluidCollisionOption raytrace_fluidcollisionoption, Entity entity) { - this.a = vec3d; - this.b = vec3d1; - this.c = raytrace_blockcollisionoption; - this.d = raytrace_fluidcollisionoption; - this.e = (entity == null) ? VoxelShapeCollision.a() : VoxelShapeCollision.a(entity); // CraftBukkit - } - - public Vec3D a() { - return this.b; - } - - public Vec3D b() { - return this.a; - } - - public VoxelShape a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.c.get(iblockdata, iblockaccess, blockposition, this.e); - } - - public VoxelShape a(Fluid fluid, IBlockAccess iblockaccess, BlockPosition blockposition) { - return this.d.a(fluid) ? fluid.d(iblockaccess, blockposition) : VoxelShapes.a(); - } - - public static enum FluidCollisionOption { - - NONE((fluid) -> { - return false; - }), SOURCE_ONLY(Fluid::isSource), ANY((fluid) -> { - return !fluid.isEmpty(); - }); - - private final Predicate predicate; - - private FluidCollisionOption(Predicate predicate) { // CraftBukkit - decompile error - this.predicate = predicate; - } - - public boolean a(Fluid fluid) { - return this.predicate.test(fluid); - } - } - - public interface c { - - VoxelShape get(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision); - } - - public static enum BlockCollisionOption implements RayTrace.c { - - COLLIDER(IBlockData::b), OUTLINE(IBlockData::a); - - private final RayTrace.c c; - - private BlockCollisionOption(RayTrace.c raytrace_c) { - this.c = raytrace_c; - } - - @Override - public VoxelShape get(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { - return this.c.get(iblockdata, iblockaccess, blockposition, voxelshapecollision); - } - } -} diff --git a/src/main/java/net/minecraft/server/RecipeArmorDye.java b/src/main/java/net/minecraft/server/RecipeArmorDye.java deleted file mode 100644 index 92bdd30c2..000000000 --- a/src/main/java/net/minecraft/server/RecipeArmorDye.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.List; - -public class RecipeArmorDye extends ShapelessRecipes { // CraftBukkit - added extends - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipeArmorDye(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.LEATHER_HELMET), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.BONE_MEAL))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - ItemStack itemstack = ItemStack.a; - List list = Lists.newArrayList(); - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack1 = inventorycrafting.getItem(i); - - if (!itemstack1.isEmpty()) { - if (itemstack1.getItem() instanceof IDyeable) { - if (!itemstack.isEmpty()) { - return false; - } - - itemstack = itemstack1; - } else { - if (!(itemstack1.getItem() instanceof ItemDye)) { - return false; - } - - list.add(itemstack1); - } - } - } - - return !itemstack.isEmpty() && !list.isEmpty(); - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - List list = Lists.newArrayList(); - ItemStack itemstack = ItemStack.a; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack1 = inventorycrafting.getItem(i); - - if (!itemstack1.isEmpty()) { - Item item = itemstack1.getItem(); - - if (item instanceof IDyeable) { - if (!itemstack.isEmpty()) { - return ItemStack.a; - } - - itemstack = itemstack1.cloneItemStack(); - } else { - if (!(item instanceof ItemDye)) { - return ItemStack.a; - } - - list.add((ItemDye) item); - } - } - } - - if (!itemstack.isEmpty() && !list.isEmpty()) { - return IDyeable.a(itemstack, list); - } else { - return ItemStack.a; - } - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.c; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeBannerDuplicate.java b/src/main/java/net/minecraft/server/RecipeBannerDuplicate.java deleted file mode 100644 index 3fb5c101a..000000000 --- a/src/main/java/net/minecraft/server/RecipeBannerDuplicate.java +++ /dev/null @@ -1,98 +0,0 @@ -package net.minecraft.server; - -public class RecipeBannerDuplicate extends ShapelessRecipes { // CraftBukkit - added extends - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipeBannerDuplicate(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.WHITE_BANNER), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.WHITE_BANNER))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - EnumColor enumcolor = null; - ItemStack itemstack = null; - ItemStack itemstack1 = null; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack2 = inventorycrafting.getItem(i); - Item item = itemstack2.getItem(); - - if (item instanceof ItemBanner) { - ItemBanner itembanner = (ItemBanner) item; - - if (enumcolor == null) { - enumcolor = itembanner.b(); - } else if (enumcolor != itembanner.b()) { - return false; - } - - int j = TileEntityBanner.a(itemstack2); - - if (j > 6) { - return false; - } - - if (j > 0) { - if (itemstack != null) { - return false; - } - - itemstack = itemstack2; - } else { - if (itemstack1 != null) { - return false; - } - - itemstack1 = itemstack2; - } - } - } - - return itemstack != null && itemstack1 != null; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack = inventorycrafting.getItem(i); - - if (!itemstack.isEmpty()) { - int j = TileEntityBanner.a(itemstack); - - if (j > 0 && j <= 6) { - ItemStack itemstack1 = itemstack.cloneItemStack(); - - itemstack1.setCount(1); - return itemstack1; - } - } - } - - return ItemStack.a; - } - - public NonNullList b(InventoryCrafting inventorycrafting) { - NonNullList nonnulllist = NonNullList.a(inventorycrafting.getSize(), ItemStack.a); - - for (int i = 0; i < nonnulllist.size(); ++i) { - ItemStack itemstack = inventorycrafting.getItem(i); - - if (!itemstack.isEmpty()) { - if (itemstack.getItem().o()) { - nonnulllist.set(i, new ItemStack(itemstack.getItem().n())); - } else if (itemstack.hasTag() && TileEntityBanner.a(itemstack) > 0) { - ItemStack itemstack1 = itemstack.cloneItemStack(); - - itemstack1.setCount(1); - nonnulllist.set(i, itemstack1); - } - } - } - - return nonnulllist; - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.k; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeBlasting.java b/src/main/java/net/minecraft/server/RecipeBlasting.java deleted file mode 100644 index a2d76d597..000000000 --- a/src/main/java/net/minecraft/server/RecipeBlasting.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftBlastingRecipe; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftRecipe; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.Recipe; -// CraftBukkit end - -public class RecipeBlasting extends RecipeCooking { - - public RecipeBlasting(MinecraftKey minecraftkey, String s, RecipeItemStack recipeitemstack, ItemStack itemstack, float f, int i) { - super(Recipes.BLASTING, minecraftkey, s, recipeitemstack, itemstack, f, i); - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.q; - } - - // CraftBukkit start - @Override - public Recipe toBukkitRecipe() { - CraftItemStack result = CraftItemStack.asCraftMirror(this.result); - - CraftBlastingRecipe recipe = new CraftBlastingRecipe(CraftNamespacedKey.fromMinecraft(this.key), result, CraftRecipe.toBukkit(this.ingredient), this.experience, this.cookingTime); - recipe.setGroup(this.group); - - return recipe; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/RecipeBookClone.java b/src/main/java/net/minecraft/server/RecipeBookClone.java deleted file mode 100644 index 9feaad43a..000000000 --- a/src/main/java/net/minecraft/server/RecipeBookClone.java +++ /dev/null @@ -1,98 +0,0 @@ -package net.minecraft.server; - -public class RecipeBookClone extends ShapelessRecipes { // CraftBukkit - added extends - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipeBookClone(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.WRITTEN_BOOK), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.WRITABLE_BOOK))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - int i = 0; - ItemStack itemstack = ItemStack.a; - - for (int j = 0; j < inventorycrafting.getSize(); ++j) { - ItemStack itemstack1 = inventorycrafting.getItem(j); - - if (!itemstack1.isEmpty()) { - if (itemstack1.getItem() == Items.WRITTEN_BOOK) { - if (!itemstack.isEmpty()) { - return false; - } - - itemstack = itemstack1; - } else { - if (itemstack1.getItem() != Items.WRITABLE_BOOK) { - return false; - } - - ++i; - } - } - } - - return !itemstack.isEmpty() && itemstack.hasTag() && i > 0; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - int i = 0; - ItemStack itemstack = ItemStack.a; - - for (int j = 0; j < inventorycrafting.getSize(); ++j) { - ItemStack itemstack1 = inventorycrafting.getItem(j); - - if (!itemstack1.isEmpty()) { - if (itemstack1.getItem() == Items.WRITTEN_BOOK) { - if (!itemstack.isEmpty()) { - return ItemStack.a; - } - - itemstack = itemstack1; - } else { - if (itemstack1.getItem() != Items.WRITABLE_BOOK) { - return ItemStack.a; - } - - ++i; - } - } - } - - if (!itemstack.isEmpty() && itemstack.hasTag() && i >= 1 && ItemWrittenBook.e(itemstack) < 2) { - ItemStack itemstack2 = new ItemStack(Items.WRITTEN_BOOK, i); - NBTTagCompound nbttagcompound = itemstack.getTag().clone(); - - nbttagcompound.setInt("generation", ItemWrittenBook.e(itemstack) + 1); - itemstack2.setTag(nbttagcompound); - return itemstack2; - } else { - return ItemStack.a; - } - } - - public NonNullList b(InventoryCrafting inventorycrafting) { - NonNullList nonnulllist = NonNullList.a(inventorycrafting.getSize(), ItemStack.a); - - for (int i = 0; i < nonnulllist.size(); ++i) { - ItemStack itemstack = inventorycrafting.getItem(i); - - if (itemstack.getItem().o()) { - nonnulllist.set(i, new ItemStack(itemstack.getItem().n())); - } else if (itemstack.getItem() instanceof ItemWrittenBook) { - ItemStack itemstack1 = itemstack.cloneItemStack(); - - itemstack1.setCount(1); - nonnulllist.set(i, itemstack1); - break; - } - } - - return nonnulllist; - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.d; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeBookServer.java b/src/main/java/net/minecraft/server/RecipeBookServer.java deleted file mode 100644 index 0e66bdda8..000000000 --- a/src/main/java/net/minecraft/server/RecipeBookServer.java +++ /dev/null @@ -1,144 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import java.util.function.Consumer; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit - -public class RecipeBookServer extends RecipeBook { - - private static final Logger LOGGER = LogManager.getLogger(); - private final CraftingManager l; - - public RecipeBookServer(CraftingManager craftingmanager) { - this.l = craftingmanager; - } - - public int a(Collection> collection, EntityPlayer entityplayer) { - List list = Lists.newArrayList(); - int i = 0; - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - IRecipe irecipe = (IRecipe) iterator.next(); - MinecraftKey minecraftkey = irecipe.getKey(); - - if (!this.a.contains(minecraftkey) && !irecipe.isComplex() && CraftEventFactory.handlePlayerRecipeListUpdateEvent(entityplayer, minecraftkey)) { // CraftBukkit - this.a(minecraftkey); - this.c(minecraftkey); - list.add(minecraftkey); - CriterionTriggers.f.a(entityplayer, irecipe); - ++i; - } - } - - this.a(PacketPlayOutRecipes.Action.ADD, entityplayer, list); - return i; - } - - public int b(Collection> collection, EntityPlayer entityplayer) { - List list = Lists.newArrayList(); - int i = 0; - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - IRecipe irecipe = (IRecipe) iterator.next(); - MinecraftKey minecraftkey = irecipe.getKey(); - - if (this.a.contains(minecraftkey)) { - this.b(minecraftkey); - list.add(minecraftkey); - ++i; - } - } - - this.a(PacketPlayOutRecipes.Action.REMOVE, entityplayer, list); - return i; - } - - private void a(PacketPlayOutRecipes.Action packetplayoutrecipes_action, EntityPlayer entityplayer, List list) { - if (entityplayer.playerConnection == null) return; // SPIGOT-4478 during PlayerLoginEvent - entityplayer.playerConnection.sendPacket(new PacketPlayOutRecipes(packetplayoutrecipes_action, list, Collections.emptyList(), this.c, this.d, this.e, this.f)); - } - - public NBTTagCompound save() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setBoolean("isGuiOpen", this.c); - nbttagcompound.setBoolean("isFilteringCraftable", this.d); - nbttagcompound.setBoolean("isFurnaceGuiOpen", this.e); - nbttagcompound.setBoolean("isFurnaceFilteringCraftable", this.f); - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.a.iterator(); - - while (iterator.hasNext()) { - MinecraftKey minecraftkey = (MinecraftKey) iterator.next(); - // Paper start - ignore missing recipes - final Optional> recipe = this.l.a(minecraftkey); - if (!recipe.isPresent()) continue; - // Paper end - - nbttaglist.add(new NBTTagString(minecraftkey.toString())); - } - - nbttagcompound.set("recipes", nbttaglist); - NBTTagList nbttaglist1 = new NBTTagList(); - Iterator iterator1 = this.b.iterator(); - - while (iterator1.hasNext()) { - MinecraftKey minecraftkey1 = (MinecraftKey) iterator1.next(); - // Paper start - ignore missing recipes - final Optional> recipe = this.l.a(minecraftkey1); - if (!recipe.isPresent()) continue; - // Paper end - - nbttaglist1.add(new NBTTagString(minecraftkey1.toString())); - } - - nbttagcompound.set("toBeDisplayed", nbttaglist1); - return nbttagcompound; - } - - public void a(NBTTagCompound nbttagcompound) { - this.c = nbttagcompound.getBoolean("isGuiOpen"); - this.d = nbttagcompound.getBoolean("isFilteringCraftable"); - this.e = nbttagcompound.getBoolean("isFurnaceGuiOpen"); - this.f = nbttagcompound.getBoolean("isFurnaceFilteringCraftable"); - NBTTagList nbttaglist = nbttagcompound.getList("recipes", 8); - - this.a(nbttaglist, this::a); - NBTTagList nbttaglist1 = nbttagcompound.getList("toBeDisplayed", 8); - - this.a(nbttaglist1, this::f); - } - - private void a(NBTTagList nbttaglist, Consumer> consumer) { - for (int i = 0; i < nbttaglist.size(); ++i) { - String s = nbttaglist.getString(i); - - try { - MinecraftKey minecraftkey = new MinecraftKey(s); - Optional> optional = this.l.a(minecraftkey); - - if (!optional.isPresent()) { - RecipeBookServer.LOGGER.error("Tried to load unrecognized recipe: {} removed now.", minecraftkey); - } else { - consumer.accept(optional.get()); - } - } catch (ResourceKeyInvalidException resourcekeyinvalidexception) { - RecipeBookServer.LOGGER.error("Tried to load improperly formatted recipe: {} removed now.", s); - } - } - - } - - public void a(EntityPlayer entityplayer) { - entityplayer.playerConnection.sendPacket(new PacketPlayOutRecipes(PacketPlayOutRecipes.Action.INIT, this.a, this.b, this.c, this.d, this.e, this.f)); - } -} diff --git a/src/main/java/net/minecraft/server/RecipeCampfire.java b/src/main/java/net/minecraft/server/RecipeCampfire.java deleted file mode 100644 index 678f039cf..000000000 --- a/src/main/java/net/minecraft/server/RecipeCampfire.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftCampfireRecipe; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftRecipe; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.Recipe; -// CraftBukkit end - -public class RecipeCampfire extends RecipeCooking { - - public RecipeCampfire(MinecraftKey minecraftkey, String s, RecipeItemStack recipeitemstack, ItemStack itemstack, float f, int i) { - super(Recipes.CAMPFIRE_COOKING, minecraftkey, s, recipeitemstack, itemstack, f, i); - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.s; - } - - // CraftBukkit start - @Override - public Recipe toBukkitRecipe() { - CraftItemStack result = CraftItemStack.asCraftMirror(this.result); - - CraftCampfireRecipe recipe = new CraftCampfireRecipe(CraftNamespacedKey.fromMinecraft(this.key), result, CraftRecipe.toBukkit(this.ingredient), this.experience, this.cookingTime); - recipe.setGroup(this.group); - - return recipe; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/RecipeFireworks.java b/src/main/java/net/minecraft/server/RecipeFireworks.java deleted file mode 100644 index 1602afb87..000000000 --- a/src/main/java/net/minecraft/server/RecipeFireworks.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.minecraft.server; - -public class RecipeFireworks extends ShapelessRecipes { // CraftBukkit - added extends - - private static final RecipeItemStack a = RecipeItemStack.a(Items.PAPER); - private static final RecipeItemStack b = RecipeItemStack.a(Items.GUNPOWDER); - private static final RecipeItemStack c = RecipeItemStack.a(Items.FIREWORK_STAR); - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipeFireworks(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.FIREWORK_ROCKET, 3), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.GUNPOWDER))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - boolean flag = false; - int i = 0; - - for (int j = 0; j < inventorycrafting.getSize(); ++j) { - ItemStack itemstack = inventorycrafting.getItem(j); - - if (!itemstack.isEmpty()) { - if (RecipeFireworks.a.test(itemstack)) { - if (flag) { - return false; - } - - flag = true; - } else if (RecipeFireworks.b.test(itemstack)) { - ++i; - if (i > 3) { - return false; - } - } else if (!RecipeFireworks.c.test(itemstack)) { - return false; - } - } - } - - return flag && i >= 1; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - ItemStack itemstack = new ItemStack(Items.FIREWORK_ROCKET, 3); - NBTTagCompound nbttagcompound = itemstack.a("Fireworks"); - NBTTagList nbttaglist = new NBTTagList(); - int i = 0; - - for (int j = 0; j < inventorycrafting.getSize(); ++j) { - ItemStack itemstack1 = inventorycrafting.getItem(j); - - if (!itemstack1.isEmpty()) { - if (RecipeFireworks.b.test(itemstack1)) { - ++i; - } else if (RecipeFireworks.c.test(itemstack1)) { - NBTTagCompound nbttagcompound1 = itemstack1.b("Explosion"); - - if (nbttagcompound1 != null) { - nbttaglist.add(nbttagcompound1); - } - } - } - } - - nbttagcompound.setByte("Flight", (byte) i); - if (!nbttaglist.isEmpty()) { - nbttagcompound.set("Explosions", nbttaglist); - } - - return itemstack; - } - - @Override - public ItemStack c() { - return new ItemStack(Items.FIREWORK_ROCKET); - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.g; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeFireworksFade.java b/src/main/java/net/minecraft/server/RecipeFireworksFade.java deleted file mode 100644 index 22875f3f2..000000000 --- a/src/main/java/net/minecraft/server/RecipeFireworksFade.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.List; - -public class RecipeFireworksFade extends ShapelessRecipes { // CraftBukkit - added extends - - private static final RecipeItemStack a = RecipeItemStack.a(Items.FIREWORK_STAR); - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipeFireworksFade(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.FIREWORK_STAR), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.FIREWORK_STAR, Items.BONE_MEAL))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - boolean flag = false; - boolean flag1 = false; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack = inventorycrafting.getItem(i); - - if (!itemstack.isEmpty()) { - if (itemstack.getItem() instanceof ItemDye) { - flag = true; - } else { - if (!RecipeFireworksFade.a.test(itemstack)) { - return false; - } - - if (flag1) { - return false; - } - - flag1 = true; - } - } - } - - return flag1 && flag; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - List list = Lists.newArrayList(); - ItemStack itemstack = null; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack1 = inventorycrafting.getItem(i); - Item item = itemstack1.getItem(); - - if (item instanceof ItemDye) { - list.add(((ItemDye) item).d().f()); - } else if (RecipeFireworksFade.a.test(itemstack1)) { - itemstack = itemstack1.cloneItemStack(); - itemstack.setCount(1); - } - } - - if (itemstack != null && !list.isEmpty()) { - itemstack.a("Explosion").b("FadeColors", (List) list); - return itemstack; - } else { - return ItemStack.a; - } - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.i; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeFireworksStar.java b/src/main/java/net/minecraft/server/RecipeFireworksStar.java deleted file mode 100644 index 7d75f0834..000000000 --- a/src/main/java/net/minecraft/server/RecipeFireworksStar.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class RecipeFireworksStar extends ShapelessRecipes { // CraftBukkit - added extends - - private static final RecipeItemStack a = RecipeItemStack.a(Items.FIRE_CHARGE, Items.FEATHER, Items.GOLD_NUGGET, Items.SKELETON_SKULL, Items.WITHER_SKELETON_SKULL, Items.CREEPER_HEAD, Items.PLAYER_HEAD, Items.DRAGON_HEAD, Items.ZOMBIE_HEAD); - private static final RecipeItemStack b = RecipeItemStack.a(Items.DIAMOND); - private static final RecipeItemStack c = RecipeItemStack.a(Items.GLOWSTONE_DUST); - private static final Map d = (Map) SystemUtils.a(Maps.newHashMap(), (hashmap) -> { // CraftBukkit - decompile error - hashmap.put(Items.FIRE_CHARGE, ItemFireworks.EffectType.LARGE_BALL); - hashmap.put(Items.FEATHER, ItemFireworks.EffectType.BURST); - hashmap.put(Items.GOLD_NUGGET, ItemFireworks.EffectType.STAR); - hashmap.put(Items.SKELETON_SKULL, ItemFireworks.EffectType.CREEPER); - hashmap.put(Items.WITHER_SKELETON_SKULL, ItemFireworks.EffectType.CREEPER); - hashmap.put(Items.CREEPER_HEAD, ItemFireworks.EffectType.CREEPER); - hashmap.put(Items.PLAYER_HEAD, ItemFireworks.EffectType.CREEPER); - hashmap.put(Items.DRAGON_HEAD, ItemFireworks.EffectType.CREEPER); - hashmap.put(Items.ZOMBIE_HEAD, ItemFireworks.EffectType.CREEPER); - }); - private static final RecipeItemStack e = RecipeItemStack.a(Items.GUNPOWDER); - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipeFireworksStar(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.FIREWORK_STAR), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.GUNPOWDER))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - boolean flag = false; - boolean flag1 = false; - boolean flag2 = false; - boolean flag3 = false; - boolean flag4 = false; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack = inventorycrafting.getItem(i); - - if (!itemstack.isEmpty()) { - if (RecipeFireworksStar.a.test(itemstack)) { - if (flag2) { - return false; - } - - flag2 = true; - } else if (RecipeFireworksStar.c.test(itemstack)) { - if (flag4) { - return false; - } - - flag4 = true; - } else if (RecipeFireworksStar.b.test(itemstack)) { - if (flag3) { - return false; - } - - flag3 = true; - } else if (RecipeFireworksStar.e.test(itemstack)) { - if (flag) { - return false; - } - - flag = true; - } else { - if (!(itemstack.getItem() instanceof ItemDye)) { - return false; - } - - flag1 = true; - } - } - } - - return flag && flag1; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - ItemStack itemstack = new ItemStack(Items.FIREWORK_STAR); - NBTTagCompound nbttagcompound = itemstack.a("Explosion"); - ItemFireworks.EffectType itemfireworks_effecttype = ItemFireworks.EffectType.SMALL_BALL; - List list = Lists.newArrayList(); - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack1 = inventorycrafting.getItem(i); - - if (!itemstack1.isEmpty()) { - if (RecipeFireworksStar.a.test(itemstack1)) { - itemfireworks_effecttype = (ItemFireworks.EffectType) RecipeFireworksStar.d.get(itemstack1.getItem()); - } else if (RecipeFireworksStar.c.test(itemstack1)) { - nbttagcompound.setBoolean("Flicker", true); - } else if (RecipeFireworksStar.b.test(itemstack1)) { - nbttagcompound.setBoolean("Trail", true); - } else if (itemstack1.getItem() instanceof ItemDye) { - list.add(((ItemDye) itemstack1.getItem()).d().f()); - } - } - } - - nbttagcompound.b("Colors", (List) list); - nbttagcompound.setByte("Type", (byte) itemfireworks_effecttype.a()); - return itemstack; - } - - @Override - public ItemStack c() { - return new ItemStack(Items.FIREWORK_STAR); - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.h; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeItemStack.java b/src/main/java/net/minecraft/server/RecipeItemStack.java deleted file mode 100644 index e339310dd..000000000 --- a/src/main/java/net/minecraft/server/RecipeItemStack.java +++ /dev/null @@ -1,265 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntComparators; -import it.unimi.dsi.fastutil.ints.IntList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.function.Predicate; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; -import javax.annotation.Nullable; - -public final class RecipeItemStack implements Predicate { - - private static final Predicate b = (recipeitemstack_provider) -> { - return !recipeitemstack_provider.a().stream().allMatch(ItemStack::isEmpty); - }; - public static final RecipeItemStack a = new RecipeItemStack(Stream.empty()); - private final RecipeItemStack.Provider[] c; - public ItemStack[] choices; - private IntList e; - public boolean exact; // CraftBukkit - - public RecipeItemStack(Stream stream) { - this.c = (RecipeItemStack.Provider[]) stream.filter(RecipeItemStack.b).toArray((i) -> { - return new RecipeItemStack.Provider[i]; - }); - } - - public void buildChoices() { - if (this.choices == null) { - this.choices = (ItemStack[]) Arrays.stream(this.c).flatMap((recipeitemstack_provider) -> { - return recipeitemstack_provider.a().stream(); - }).distinct().toArray((i) -> { - return new ItemStack[i]; - }); - } - - } - - public boolean test(@Nullable ItemStack itemstack) { - if (itemstack == null) { - return false; - } else if (this.c.length == 0) { - return itemstack.isEmpty(); - } else { - this.buildChoices(); - ItemStack[] aitemstack = this.choices; - int i = aitemstack.length; - - for (int j = 0; j < i; ++j) { - ItemStack itemstack1 = aitemstack[j]; - - // CraftBukkit start - if (exact) { - if (itemstack1.getItem() == itemstack.getItem() && ItemStack.equals(itemstack, itemstack1)) { - return true; - } - - continue; - } - // CraftBukkit end - if (itemstack1.getItem() == itemstack.getItem()) { - return true; - } - } - - return false; - } - } - - public IntList b() { - if (this.e == null) { - this.buildChoices(); - this.e = new IntArrayList(this.choices.length); - ItemStack[] aitemstack = this.choices; - int i = aitemstack.length; - - for (int j = 0; j < i; ++j) { - ItemStack itemstack = aitemstack[j]; - - this.e.add(AutoRecipeStackManager.c(itemstack)); - } - - this.e.sort(IntComparators.NATURAL_COMPARATOR); - } - - return this.e; - } - - public void a(PacketDataSerializer packetdataserializer) { - this.buildChoices(); - packetdataserializer.d(this.choices.length); - - for (int i = 0; i < this.choices.length; ++i) { - packetdataserializer.a(this.choices[i]); - } - - } - - public JsonElement c() { - if (this.c.length == 1) { - return this.c[0].b(); - } else { - JsonArray jsonarray = new JsonArray(); - RecipeItemStack.Provider[] arecipeitemstack_provider = this.c; - int i = arecipeitemstack_provider.length; - - for (int j = 0; j < i; ++j) { - RecipeItemStack.Provider recipeitemstack_provider = arecipeitemstack_provider[j]; - - jsonarray.add(recipeitemstack_provider.b()); - } - - return jsonarray; - } - } - - public boolean d() { - return this.c.length == 0 && (this.choices == null || this.choices.length == 0) && (this.e == null || this.e.isEmpty()); - } - - private static RecipeItemStack a(Stream stream) { - RecipeItemStack recipeitemstack = new RecipeItemStack(stream); - - return recipeitemstack.c.length == 0 ? RecipeItemStack.a : recipeitemstack; - } - - public static RecipeItemStack a(IMaterial... aimaterial) { - return a(Arrays.stream(aimaterial).map((imaterial) -> { - return new RecipeItemStack.StackProvider(new ItemStack(imaterial)); - })); - } - - public static RecipeItemStack a(Tag tag) { - return a(Stream.of(new RecipeItemStack.b(tag))); - } - - public static RecipeItemStack b(PacketDataSerializer packetdataserializer) { - int i = packetdataserializer.i(); - - return a(Stream.generate(() -> { - return new RecipeItemStack.StackProvider(packetdataserializer.m()); - }).limit((long) i)); - } - - public static RecipeItemStack a(@Nullable JsonElement jsonelement) { - if (jsonelement != null && !jsonelement.isJsonNull()) { - if (jsonelement.isJsonObject()) { - return a(Stream.of(a(jsonelement.getAsJsonObject()))); - } else if (jsonelement.isJsonArray()) { - JsonArray jsonarray = jsonelement.getAsJsonArray(); - - if (jsonarray.size() == 0) { - throw new JsonSyntaxException("Item array cannot be empty, at least one item must be defined"); - } else { - return a(StreamSupport.stream(jsonarray.spliterator(), false).map((jsonelement1) -> { - return a(ChatDeserializer.m(jsonelement1, "item")); - })); - } - } else { - throw new JsonSyntaxException("Expected item to be object or array of objects"); - } - } else { - throw new JsonSyntaxException("Item cannot be null"); - } - } - - public static RecipeItemStack.Provider a(JsonObject jsonobject) { - if (jsonobject.has("item") && jsonobject.has("tag")) { - throw new JsonParseException("An ingredient entry is either a tag or an item, not both"); - } else { - MinecraftKey minecraftkey; - - if (jsonobject.has("item")) { - minecraftkey = new MinecraftKey(ChatDeserializer.h(jsonobject, "item")); - Item item = (Item) IRegistry.ITEM.getOptional(minecraftkey).orElseThrow(() -> { - return new JsonSyntaxException("Unknown item '" + minecraftkey + "'"); - }); - - return new RecipeItemStack.StackProvider(new ItemStack(item)); - } else if (jsonobject.has("tag")) { - minecraftkey = new MinecraftKey(ChatDeserializer.h(jsonobject, "tag")); - Tag tag = TagsItem.a().a(minecraftkey); - - if (tag == null) { - throw new JsonSyntaxException("Unknown item tag '" + minecraftkey + "'"); - } else { - return new RecipeItemStack.b(tag); - } - } else { - throw new JsonParseException("An ingredient entry needs either a tag or an item"); - } - } - } - - static class b implements RecipeItemStack.Provider { - - private final Tag a; - - private b(Tag tag) { - this.a = tag; - } - - @Override - public Collection a() { - List list = Lists.newArrayList(); - Iterator iterator = this.a.a().iterator(); - - while (iterator.hasNext()) { - Item item = (Item) iterator.next(); - - list.add(new ItemStack(item)); - } - - return list; - } - - @Override - public JsonObject b() { - JsonObject jsonobject = new JsonObject(); - - jsonobject.addProperty("tag", this.a.c().toString()); - return jsonobject; - } - } - - public static class StackProvider implements RecipeItemStack.Provider { - - private final ItemStack a; - - public StackProvider(ItemStack itemstack) { - this.a = itemstack; - } - - @Override - public Collection a() { - return Collections.singleton(this.a); - } - - @Override - public JsonObject b() { - JsonObject jsonobject = new JsonObject(); - - jsonobject.addProperty("item", IRegistry.ITEM.getKey(this.a.getItem()).toString()); - return jsonobject; - } - } - - public interface Provider { - - Collection a(); - - JsonObject b(); - } -} diff --git a/src/main/java/net/minecraft/server/RecipeMapClone.java b/src/main/java/net/minecraft/server/RecipeMapClone.java deleted file mode 100644 index 57f7b94d4..000000000 --- a/src/main/java/net/minecraft/server/RecipeMapClone.java +++ /dev/null @@ -1,76 +0,0 @@ -package net.minecraft.server; - -public class RecipeMapClone extends ShapelessRecipes { // CraftBukkit - added extends - - // CraftBukkit start - Delegate to new parent class - public RecipeMapClone(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.MAP), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.MAP))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - int i = 0; - ItemStack itemstack = ItemStack.a; - - for (int j = 0; j < inventorycrafting.getSize(); ++j) { - ItemStack itemstack1 = inventorycrafting.getItem(j); - - if (!itemstack1.isEmpty()) { - if (itemstack1.getItem() == Items.FILLED_MAP) { - if (!itemstack.isEmpty()) { - return false; - } - - itemstack = itemstack1; - } else { - if (itemstack1.getItem() != Items.MAP) { - return false; - } - - ++i; - } - } - } - - return !itemstack.isEmpty() && i > 0; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - int i = 0; - ItemStack itemstack = ItemStack.a; - - for (int j = 0; j < inventorycrafting.getSize(); ++j) { - ItemStack itemstack1 = inventorycrafting.getItem(j); - - if (!itemstack1.isEmpty()) { - if (itemstack1.getItem() == Items.FILLED_MAP) { - if (!itemstack.isEmpty()) { - return ItemStack.a; - } - - itemstack = itemstack1; - } else { - if (itemstack1.getItem() != Items.MAP) { - return ItemStack.a; - } - - ++i; - } - } - } - - if (!itemstack.isEmpty() && i >= 1) { - ItemStack itemstack2 = itemstack.cloneItemStack(); - - itemstack2.setCount(i + 1); - return itemstack2; - } else { - return ItemStack.a; - } - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.e; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeRepair.java b/src/main/java/net/minecraft/server/RecipeRepair.java deleted file mode 100644 index a674c53cd..000000000 --- a/src/main/java/net/minecraft/server/RecipeRepair.java +++ /dev/null @@ -1,92 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.List; -import java.util.stream.Stream; // CraftBukkit - -public class RecipeRepair extends ShapelessRecipes { // CraftBukkit - added extends - - // CraftBukkit start - Delegate to new parent class - public RecipeRepair(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.LEATHER_HELMET), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.LEATHER_HELMET))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - List list = Lists.newArrayList(); - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack = inventorycrafting.getItem(i); - - if (!itemstack.isEmpty()) { - list.add(itemstack); - if (list.size() > 1) { - ItemStack itemstack1 = (ItemStack) list.get(0); - - if (itemstack.getItem() != itemstack1.getItem() || itemstack1.getCount() != 1 || itemstack.getCount() != 1 || !itemstack1.getItem().usesDurability()) { - return false; - } - } - } - } - - return list.size() == 2; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - List list = Lists.newArrayList(); - - ItemStack itemstack; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - itemstack = inventorycrafting.getItem(i); - if (!itemstack.isEmpty()) { - list.add(itemstack); - if (list.size() > 1) { - ItemStack itemstack1 = (ItemStack) list.get(0); - - if (itemstack.getItem() != itemstack1.getItem() || itemstack1.getCount() != 1 || itemstack.getCount() != 1 || !itemstack1.getItem().usesDurability()) { - return ItemStack.a; - } - } - } - } - - if (list.size() == 2) { - ItemStack itemstack2 = (ItemStack) list.get(0); - - itemstack = (ItemStack) list.get(1); - if (itemstack2.getItem() == itemstack.getItem() && itemstack2.getCount() == 1 && itemstack.getCount() == 1 && itemstack2.getItem().usesDurability()) { - Item item = itemstack2.getItem(); - int j = item.getMaxDurability() - itemstack2.getDamage(); - int k = item.getMaxDurability() - itemstack.getDamage(); - int l = j + k + item.getMaxDurability() * 5 / 100; - int i1 = item.getMaxDurability() - l; - - if (i1 < 0) { - i1 = 0; - } - - ItemStack itemstack3 = new ItemStack(itemstack2.getItem()); - - itemstack3.setDamage(i1); - // CraftBukkit start - Construct a dummy repair recipe - NonNullList ingredients = NonNullList.a(); - ingredients.add(new RecipeItemStack(Stream.of(new RecipeItemStack.StackProvider(itemstack2.cloneItemStack())))); - ingredients.add(new RecipeItemStack(Stream.of(new RecipeItemStack.StackProvider(itemstack.cloneItemStack())))); - ShapelessRecipes recipe = new ShapelessRecipes(new MinecraftKey("repairitem"), "", itemstack3.cloneItemStack(), ingredients); - inventorycrafting.setCurrentRecipe(recipe); - itemstack3 = org.bukkit.craftbukkit.event.CraftEventFactory.callPreCraftEvent(inventorycrafting, inventorycrafting.resultInventory, itemstack3, inventorycrafting.container.getBukkitView(), true); - // CraftBukkit end - return itemstack3; - } - } - - return ItemStack.a; - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.o; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeShulkerBox.java b/src/main/java/net/minecraft/server/RecipeShulkerBox.java deleted file mode 100644 index 905b49190..000000000 --- a/src/main/java/net/minecraft/server/RecipeShulkerBox.java +++ /dev/null @@ -1,69 +0,0 @@ -package net.minecraft.server; - -public class RecipeShulkerBox extends ShapelessRecipes { // CraftBukkit - added extends - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipeShulkerBox(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Blocks.WHITE_SHULKER_BOX), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.BONE_MEAL))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - int i = 0; - int j = 0; - - for (int k = 0; k < inventorycrafting.getSize(); ++k) { - ItemStack itemstack = inventorycrafting.getItem(k); - - if (!itemstack.isEmpty()) { - if (Block.asBlock(itemstack.getItem()) instanceof BlockShulkerBox) { - ++i; - } else { - if (!(itemstack.getItem() instanceof ItemDye)) { - return false; - } - - ++j; - } - - if (j > 1 || i > 1) { - return false; - } - } - } - - return i == 1 && j == 1; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - ItemStack itemstack = ItemStack.a; - ItemDye itemdye = (ItemDye) Items.WHITE_DYE; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack1 = inventorycrafting.getItem(i); - - if (!itemstack1.isEmpty()) { - Item item = itemstack1.getItem(); - - if (Block.asBlock(item) instanceof BlockShulkerBox) { - itemstack = itemstack1; - } else if (item instanceof ItemDye) { - itemdye = (ItemDye) item; - } - } - } - - ItemStack itemstack2 = BlockShulkerBox.b(itemdye.d()); - - if (itemstack.hasTag()) { - itemstack2.setTag(itemstack.getTag().clone()); - } - - return itemstack2; - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.m; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeSmoking.java b/src/main/java/net/minecraft/server/RecipeSmoking.java deleted file mode 100644 index 0e436af10..000000000 --- a/src/main/java/net/minecraft/server/RecipeSmoking.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftRecipe; -import org.bukkit.craftbukkit.inventory.CraftSmokingRecipe; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.Recipe; -// CraftBukkit end - -public class RecipeSmoking extends RecipeCooking { - - public RecipeSmoking(MinecraftKey minecraftkey, String s, RecipeItemStack recipeitemstack, ItemStack itemstack, float f, int i) { - super(Recipes.SMOKING, minecraftkey, s, recipeitemstack, itemstack, f, i); - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.r; - } - - // CraftBukkit start - @Override - public Recipe toBukkitRecipe() { - CraftItemStack result = CraftItemStack.asCraftMirror(this.result); - - CraftSmokingRecipe recipe = new CraftSmokingRecipe(CraftNamespacedKey.fromMinecraft(this.key), result, CraftRecipe.toBukkit(this.ingredient), this.experience, this.cookingTime); - recipe.setGroup(this.group); - - return recipe; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/RecipeStonecutting.java b/src/main/java/net/minecraft/server/RecipeStonecutting.java deleted file mode 100644 index 2dc0954f6..000000000 --- a/src/main/java/net/minecraft/server/RecipeStonecutting.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.minecraft.server; - -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftRecipe; -import org.bukkit.craftbukkit.inventory.CraftStonecuttingRecipe; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.Recipe; -// CraftBukkit end - -public class RecipeStonecutting extends RecipeSingleItem { - - public RecipeStonecutting(MinecraftKey minecraftkey, String s, RecipeItemStack recipeitemstack, ItemStack itemstack) { - super(Recipes.STONECUTTING, RecipeSerializer.t, minecraftkey, s, recipeitemstack, itemstack); - } - - @Override - public boolean a(IInventory iinventory, World world) { - return this.ingredient.test(iinventory.getItem(0)); - } - - // CraftBukkit start - @Override - public Recipe toBukkitRecipe() { - CraftItemStack result = CraftItemStack.asCraftMirror(this.result); - - CraftStonecuttingRecipe recipe = new CraftStonecuttingRecipe(CraftNamespacedKey.fromMinecraft(this.key), result, CraftRecipe.toBukkit(this.ingredient)); - recipe.setGroup(this.group); - - return recipe; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/RecipeSuspiciousStew.java b/src/main/java/net/minecraft/server/RecipeSuspiciousStew.java deleted file mode 100644 index 21b55b852..000000000 --- a/src/main/java/net/minecraft/server/RecipeSuspiciousStew.java +++ /dev/null @@ -1,68 +0,0 @@ -package net.minecraft.server; - -public class RecipeSuspiciousStew extends ShapelessRecipes { // CraftBukkit - added extends - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipeSuspiciousStew(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.SUSPICIOUS_STEW), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.BOWL))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - boolean flag = false; - boolean flag1 = false; - boolean flag2 = false; - boolean flag3 = false; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack = inventorycrafting.getItem(i); - - if (!itemstack.isEmpty()) { - if (itemstack.getItem() == Blocks.BROWN_MUSHROOM.getItem() && !flag2) { - flag2 = true; - } else if (itemstack.getItem() == Blocks.RED_MUSHROOM.getItem() && !flag1) { - flag1 = true; - } else if (itemstack.getItem().a(TagsItem.SMALL_FLOWERS) && !flag) { - flag = true; - } else { - if (itemstack.getItem() != Items.BOWL || flag3) { - return false; - } - - flag3 = true; - } - } - } - - return flag && flag2 && flag1 && flag3; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - ItemStack itemstack = ItemStack.a; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack1 = inventorycrafting.getItem(i); - - if (!itemstack1.isEmpty() && itemstack1.getItem().a(TagsItem.SMALL_FLOWERS)) { - itemstack = itemstack1; - break; - } - } - - ItemStack itemstack2 = new ItemStack(Items.SUSPICIOUS_STEW, 1); - - if (itemstack.getItem() instanceof ItemBlock && ((ItemBlock) itemstack.getItem()).getBlock() instanceof BlockFlowers) { - BlockFlowers blockflowers = (BlockFlowers) ((ItemBlock) itemstack.getItem()).getBlock(); - MobEffectList mobeffectlist = blockflowers.d(); - - ItemSuspiciousStew.a(itemstack2, mobeffectlist, blockflowers.e()); - } - - return itemstack2; - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.n; - } -} diff --git a/src/main/java/net/minecraft/server/RecipeTippedArrow.java b/src/main/java/net/minecraft/server/RecipeTippedArrow.java deleted file mode 100644 index 690f262d0..000000000 --- a/src/main/java/net/minecraft/server/RecipeTippedArrow.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.minecraft.server; - -import java.util.Collection; - -public class RecipeTippedArrow extends ShapedRecipes { // CraftBukkit - - // CraftBukkit start - public RecipeTippedArrow(MinecraftKey minecraftkey) { - super(minecraftkey, "", 3, 3, NonNullList.a(RecipeItemStack.a, - RecipeItemStack.a(Items.ARROW), RecipeItemStack.a(Items.ARROW), RecipeItemStack.a(Items.ARROW), - RecipeItemStack.a(Items.ARROW), RecipeItemStack.a(Items.LINGERING_POTION), RecipeItemStack.a(Items.ARROW), - RecipeItemStack.a(Items.ARROW), RecipeItemStack.a(Items.ARROW), RecipeItemStack.a(Items.ARROW)), - new ItemStack(Items.TIPPED_ARROW, 8)); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - if (inventorycrafting.g() == 3 && inventorycrafting.f() == 3) { - for (int i = 0; i < inventorycrafting.g(); ++i) { - for (int j = 0; j < inventorycrafting.f(); ++j) { - ItemStack itemstack = inventorycrafting.getItem(i + j * inventorycrafting.g()); - - if (itemstack.isEmpty()) { - return false; - } - - Item item = itemstack.getItem(); - - if (i == 1 && j == 1) { - if (item != Items.LINGERING_POTION) { - return false; - } - } else if (item != Items.ARROW) { - return false; - } - } - } - - return true; - } else { - return false; - } - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - ItemStack itemstack = inventorycrafting.getItem(1 + inventorycrafting.g()); - - if (itemstack.getItem() != Items.LINGERING_POTION) { - return ItemStack.a; - } else { - ItemStack itemstack1 = new ItemStack(Items.TIPPED_ARROW, 8); - - PotionUtil.a(itemstack1, PotionUtil.d(itemstack)); - PotionUtil.a(itemstack1, (Collection) PotionUtil.b(itemstack)); - return itemstack1; - } - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.j; - } -} diff --git a/src/main/java/net/minecraft/server/RecipiesShield.java b/src/main/java/net/minecraft/server/RecipiesShield.java deleted file mode 100644 index 60aa2524a..000000000 --- a/src/main/java/net/minecraft/server/RecipiesShield.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.minecraft.server; - -public class RecipiesShield extends ShapelessRecipes { // CraftBukkit - added extends - - // CraftBukkit start - Delegate to new parent class with bogus info - public RecipiesShield(MinecraftKey minecraftkey) { - super(minecraftkey, "", new ItemStack(Items.SHIELD), NonNullList.a(RecipeItemStack.a, RecipeItemStack.a(Items.WHITE_BANNER))); - } - // CraftBukkit end - - public boolean a(InventoryCrafting inventorycrafting, World world) { - ItemStack itemstack = ItemStack.a; - ItemStack itemstack1 = ItemStack.a; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack2 = inventorycrafting.getItem(i); - - if (!itemstack2.isEmpty()) { - if (itemstack2.getItem() instanceof ItemBanner) { - if (!itemstack1.isEmpty()) { - return false; - } - - itemstack1 = itemstack2; - } else { - if (itemstack2.getItem() != Items.SHIELD) { - return false; - } - - if (!itemstack.isEmpty()) { - return false; - } - - if (itemstack2.b("BlockEntityTag") != null) { - return false; - } - - itemstack = itemstack2; - } - } - } - - if (!itemstack.isEmpty() && !itemstack1.isEmpty()) { - return true; - } else { - return false; - } - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - ItemStack itemstack = ItemStack.a; - ItemStack itemstack1 = ItemStack.a; - - for (int i = 0; i < inventorycrafting.getSize(); ++i) { - ItemStack itemstack2 = inventorycrafting.getItem(i); - - if (!itemstack2.isEmpty()) { - if (itemstack2.getItem() instanceof ItemBanner) { - itemstack = itemstack2; - } else if (itemstack2.getItem() == Items.SHIELD) { - itemstack1 = itemstack2.cloneItemStack(); - } - } - } - - if (itemstack1.isEmpty()) { - return itemstack1; - } else { - NBTTagCompound nbttagcompound = itemstack.b("BlockEntityTag"); - NBTTagCompound nbttagcompound1 = nbttagcompound == null ? new NBTTagCompound() : nbttagcompound.clone(); - - nbttagcompound1.setInt("Base", ((ItemBanner) itemstack.getItem()).b().getColorIndex()); - itemstack1.a("BlockEntityTag", (NBTBase) nbttagcompound1); - return itemstack1; - } - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.l; - } -} diff --git a/src/main/java/net/minecraft/server/RegionFile.java b/src/main/java/net/minecraft/server/RegionFile.java deleted file mode 100644 index 22144eb00..000000000 --- a/src/main/java/net/minecraft/server/RegionFile.java +++ /dev/null @@ -1,573 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.exception.ServerInternalException; -import com.google.common.collect.Lists; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.List; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.InflaterInputStream; -import javax.annotation.Nullable; - -public class RegionFile implements AutoCloseable { - - // Spigot start - // Minecraft is limited to 256 sections per chunk. So 1MB. This can easily be overriden. - // So we extend this to use the REAL size when the count is maxed by seeking to that section and reading the length. - private static final boolean ENABLE_EXTENDED_SAVE = Boolean.parseBoolean(System.getProperty("net.minecraft.server.RegionFile.enableExtendedSave", "true")); - final File file; // Paper - private -> package - // Spigot end - private static final byte[] a = new byte[4096]; - private final RandomAccessFile b; private RandomAccessFile getDataFile() { return this.b; } // Paper - OBFHELPER // PAIL dataFile - private final int[] c = new int[1024]; private final int[] offsets = c; // Paper - OBFHELPER - private final int[] d = new int[1024]; private final int[] timestamps = d; // Paper - OBFHELPER - private final List e; // PAIL freeSectors - - // Paper start - Cache chunk status - private final ChunkStatus[] statuses = new ChunkStatus[32 * 32]; - - private boolean closed; - - // invoked on write/read - public void setStatus(int x, int z, ChunkStatus status) { - if (this.closed) { - // We've used an invalid region file. - throw new IllegalStateException("RegionFile is closed"); - } - this.statuses[this.getChunkLocation(new ChunkCoordIntPair(x, z))] = status; - } - - public ChunkStatus getStatusIfCached(int x, int z) { - if (this.closed) { - // We've used an invalid region file. - throw new IllegalStateException("RegionFile is closed"); - } - final int location = this.getChunkLocation(new ChunkCoordIntPair(x, z)); - return this.statuses[location]; - } - // Paper end - - public RegionFile(File file) throws IOException { - this.b = new RandomAccessFile(file, "rw"); - this.file = file; // Spigot // Paper - We need this earlier - if (this.b.length() < 8192L) { // Paper - headers should be 8192 - this.b.write(RegionFile.a); - this.b.write(RegionFile.a); - } - - int i; - - if ((this.b.length() & 4095L) != 0L) { - for (i = 0; (long) i < (this.b.length() & 4095L); ++i) { - this.b.write(0); - } - } - - i = (int) this.b.length() / 4096; - this.e = Lists.newArrayListWithCapacity(i); - - int j; - - for (j = 0; j < i; ++j) { - this.e.add(true); - } - - this.e.set(0, false); - this.e.set(1, false); - this.b.seek(0L); - - // Paper Start - java.nio.ByteBuffer header = java.nio.ByteBuffer.allocate(8192); - while (header.hasRemaining()) { - if (this.getDataFile().getChannel().read(header) == -1) throw new java.io.EOFException(); - } - ((java.nio.Buffer) header).clear(); - java.nio.IntBuffer headerAsInts = header.asIntBuffer(); - initOversizedState(); - // Paper End - - int k; - - for (j = 0; j < 1024; ++j) { - k = headerAsInts.get(); // Paper - this.c[j] = k; - // Spigot start - int length = k & 255; - if (length == 255) { - if ((k >> 8) <= this.e.size()) { - // We're maxed out, so we need to read the proper length from the section - this.b.seek((k >> 8) * 4096); - length = (this.b.readInt() + 4) / 4096 + 1; - this.b.seek(j * 4 + 4); // Go back to where we were - } - } - if (k > 0 && (k >> 8) > 1 && (k >> 8) + (length) <= this.e.size()) { // Paper >= 1 as 0/1 are the headers, and negative isnt valid - for (int l = 0; l < (length); ++l) { - // Spigot end - this.e.set((k >> 8) + l, false); - } - } - // Spigot start - else if (length > 0) { - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.WARNING, "Invalid chunk: ({0}, {1}) Offset: {2} Length: {3} runs off end file. {4}", new Object[]{j % 32, (int) (j / 32), k >> 8, length, file}); - deleteChunk(j); // Paper - } - // Spigot end - } - - for (j = 0; j < 1024; ++j) { - k = headerAsInts.get(); // Paper - if (this.offsets[j] != 0) this.timestamps[j] = k; // Paper - don't set timestamp if it got 0'd above due to corruption - } - - // Paper - we need this earlier - } - - @Nullable - public synchronized DataInputStream getReadStream(ChunkCoordIntPair chunkcoordintpair) { return this.a(chunkcoordintpair); } public synchronized DataInputStream a(ChunkCoordIntPair chunkcoordintpair) { // Paper - OBFHELPER - try { - int i = this.getOffset(chunkcoordintpair); - - if (i == 0) { - return null; - } else { - int j = i >> 8; - int k = i & 255; - // Spigot start - if (k == 255) { - this.b.seek(j * 4096); - k = (this.b.readInt() + 4) / 4096 + 1; - } - // Spigot end - - if (j + k > this.e.size()) { - return null; - } else { - this.b.seek((long) (j * 4096)); - int l = this.b.readInt(); - - if (l > 4096 * k) { - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.WARNING, "Invalid chunk: ({0}) Offset: {1} Invalid Size: {2}>{3} {4}", new Object[]{chunkcoordintpair, j, l, k * 4096, this.file}); // Spigot - return null; - } else if (l <= 0) { - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.WARNING, "Invalid chunk: ({0}) Offset: {1} Invalid Size: {2} {3}", new Object[]{chunkcoordintpair, j, l, this.file}); // Spigot - return null; - } else { - byte b0 = this.b.readByte(); - byte[] abyte; - - if (b0 == 1) { - abyte = new byte[l - 1]; - this.b.read(abyte); - return new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(abyte)))); - } else if (b0 == 2) { - abyte = new byte[l - 1]; - this.b.read(abyte); - return new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(abyte)))); - } else { - return null; - } - } - } - } - } catch (IOException ioexception) { - ServerInternalException.reportInternalException(ioexception); // Paper - return null; - } - } - - public boolean b(ChunkCoordIntPair chunkcoordintpair) { - int i = this.getOffset(chunkcoordintpair); - - if (i == 0) { - return false; - } else { - int j = i >> 8; - int k = i & 255; - - if (j + k > this.e.size()) { - return false; - } else { - try { - this.b.seek((long) (j * 4096)); - int l = this.b.readInt(); - - return l > 4096 * k ? false : l > 0; - } catch (IOException ioexception) { - return false; - } - } - } - } - - public DataOutputStream getWriteStream(ChunkCoordIntPair chunkcoordintpair) { return this.c(chunkcoordintpair); } public DataOutputStream c(ChunkCoordIntPair chunkcoordintpair) { // Paper - OBFHELPER - return new DataOutputStream(new RegionFile.ChunkBuffer(chunkcoordintpair)); // Paper - remove middleware, move deflate to .close() for dynamic levels - } - - protected synchronized void a(ChunkCoordIntPair chunkcoordintpair, byte[] abyte, int i) { - try { - int j = this.getOffset(chunkcoordintpair); - int k = j >> 8; final int oldSectorOffset = k; // Spigot - store variable for later - int l = j & 255; final int oldSectorCount; // Spigot - store variable for later - // Spigot start - if (l == 255) { - this.b.seek(k * 4096); - l = (this.b.readInt() + 4) / 4096 + 1; - } - // Spigot end - int i1 = (i + 5) / 4096 + 1; - oldSectorCount = l; // Spigot - store variable for later (watch out for re-assignments of l) - - if (i1 >= 256) { - // Spigot start - if (!USE_SPIGOT_OVERSIZED_METHOD && !RegionFileCache.isOverzealous()) throw new ChunkTooLargeException(chunkcoordintpair.x, chunkcoordintpair.z, l); // Paper - throw error instead - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.WARNING,"Large Chunk Detected: ({0}) Size: {1} {2}", new Object[]{chunkcoordintpair, i1, this.file}); - if (!ENABLE_EXTENDED_SAVE) throw new RuntimeException(String.format("Too big to save, %d > 1048576", i)); // Paper - move after our check - // Spigot end - } - - if (false && k != 0 && l == i1) { // Spigot - We never want to overrite old data - this.a(k, abyte, i); - } else { - int j1; - - // Spigot start - We do not free old sectors until we are done writing the new chunk data - /* - for (j1 = 0; j1 < l; ++j1) { - this.e.set(k + j1, true); - } - */ - // Spigot end - - j1 = this.e.indexOf(true); - int k1 = 0; - int l1; - - if (j1 != -1) { - for (l1 = j1; l1 < this.e.size(); ++l1) { - if (k1 != 0) { - if ((Boolean) this.e.get(l1)) { - ++k1; - } else { - k1 = 0; - } - } else if ((Boolean) this.e.get(l1)) { - j1 = l1; - k1 = 1; - } - - if (k1 >= i1) { - break; - } - } - } - - if (k1 >= i1) { - k = j1; - // this.a(chunkcoordintpair, j1 << 8 | (i1 > 255 ? 255 : i1)); // Spigot // Spigot - We only write to header after we've written chunk data - - for (l1 = 0; l1 < i1; ++l1) { - this.e.set(k + l1, false); - } - - this.writeChunk(chunkcoordintpair, j1 << 8 | (i1 > 255 ? 255 : i1), k, abyte, i); // Spigot - Ensure we do not corrupt region files - } else { - this.b.seek(this.b.length()); - k = this.e.size(); - - for (l1 = 0; l1 < i1; ++l1) { - this.b.write(RegionFile.a); - this.e.add(false); - } - - this.writeChunk(chunkcoordintpair, k << 8 | (i1 > 255 ? 255 : i1), k, abyte, i); // Spigot - Ensure we do not corrupt region files - } - - // Spigot start - Now that we've written the new chunk we can free the old data - for (int off = 0; off < oldSectorCount; ++off) { - this.e.set(oldSectorOffset + off, true); - } - // Spigot end - } - - // this.b(chunkcoordintpair, (int) (SystemUtils.getTimeMillis() / 1000L)); // Spigot - move this into writeChunk - } catch (IOException ioexception) { - com.destroystokyo.paper.util.SneakyThrow.sneaky(ioexception); // Paper - we want the upper try/catch to retry this - } - - } - - private void a(int i, byte[] abyte, int j) throws IOException { // PAIL writeChunkData - this.b.seek((long) (i * 4096)); - this.writeIntAndByte(j + 1, (byte)2); // Spigot - Avoid 4 io write calls - this.b.write(abyte, 0, j); - } - - private int getOffset(ChunkCoordIntPair chunkcoordintpair) { - return this.c[this.f(chunkcoordintpair)]; - } - - public final boolean chunkExists(ChunkCoordIntPair chunkPos) { return this.d(chunkPos); } // Paper - OBFHELPER - public boolean d(ChunkCoordIntPair chunkcoordintpair) { - return this.getOffset(chunkcoordintpair) != 0; - } - - private void a(ChunkCoordIntPair chunkcoordintpair, int i) throws IOException { // PAIL updateChunkHeader - int j = this.f(chunkcoordintpair); - - //this.c[j] = i; // Spigot - move this to after the write - this.b.seek((long) (j * 4)); - this.writeInt(i); // Spigot - Avoid 3 io write calls - this.c[j] = i; // Spigot - move this to after the write - } - - private final int getChunkLocation(ChunkCoordIntPair chunkcoordintpair) { return this.f(chunkcoordintpair); } // Paper - OBFHELPER - private int f(ChunkCoordIntPair chunkcoordintpair) { - return chunkcoordintpair.j() + chunkcoordintpair.k() * 32; - } - - private void b(ChunkCoordIntPair chunkcoordintpair, int i) throws IOException { // PAIL updateChunkTime - int j = this.f(chunkcoordintpair); - - // this.d[j] = i; // Spigot - move this to after the write - this.b.seek((long) (4096 + j * 4)); - this.writeInt(i); // Spigot - Avoid 3 io write calls - this.d[j] = i; // Spigot - move this to after the write - } - - public synchronized void close() throws IOException { // Paper - synchronize - this.closed = true; // Paper - this.b.close(); - } - - // Spigot start - Make region files reliable - private static final boolean FLUSH_ON_SAVE = Boolean.getBoolean("spigot.flush-on-save") || Boolean.getBoolean("paper.flush-on-save"); // Paper - preserve old flag - private void syncRegionFile() throws IOException { - if (!FLUSH_ON_SAVE) { - return; - } - this.b.getFD().sync(); // rethrow exception as we want to avoid corrupting a regionfile - } - - private final java.nio.ByteBuffer scratchBuffer = java.nio.ByteBuffer.allocate(8); - - private void writeInt(final int value) throws IOException { - this.scratchBuffer.putInt(0, value); - this.b.write(this.scratchBuffer.array(), 0, 4); - } - - // writes v1 then v2 - private void writeIntAndByte(final int v1, final byte v2) throws IOException { - this.scratchBuffer.putInt(0, v1); - this.scratchBuffer.put(4, v2); - this.b.write(this.scratchBuffer.array(), 0, 5); - } - - private void writeChunk(final ChunkCoordIntPair chunk, final int chunkHeaderData, final int chunkOffset, final byte[] chunkData, final int chunkDataLength) throws IOException { - this.a(chunkOffset, chunkData, chunkDataLength); // chunk data - this.syncRegionFile(); // Sync is required to ensure the previous data is written successfully - this.b(chunk, (int) (SystemUtils.getTimeMillis() / 1000L)); // chunk time - this.a(chunk, chunkHeaderData); // chunk header - this.syncRegionFile(); // Ensure header changes go through - } - // Spigot end - - // Paper start - public synchronized void deleteChunk(int j1) { - backup(); - int k = offsets[j1]; - int x = j1 & 1024; - int z = j1 >> 2; - int offset = (k >> 8); - int len = (k & 255); - String debug = "idx:" + + j1 + " - " + x + "," + z + " - offset: " + offset + " - len: " + len; - try { - timestamps[j1] = 0; - offsets[j1] = 0; - RandomAccessFile file = getDataFile(); - file.seek(j1 * 4); - file.writeInt(0); - // clear the timestamp - file.seek(4096 + j1 * 4); - file.writeInt(0); - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.SEVERE, "Deleted corrupt chunk (" + debug + ") " + this.file.getAbsolutePath(), e); - } catch (IOException e) { - - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.SEVERE, "Error deleting corrupt chunk (" + debug + ") " + this.file.getAbsolutePath(), e); - } - } - private boolean backedUp = false; - private synchronized void backup() { - if (backedUp) { - return; - } - backedUp = true; - java.text.DateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd"); - java.util.Date today = new java.util.Date(); - File corrupt = new File(file.getParentFile(), file.getName() + "." + formatter.format(today) + ".corrupt"); - if (corrupt.exists()) { - return; - } - org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(); - logger.error("Region file " + file.getAbsolutePath() + " was corrupt. Backing up to " + corrupt.getAbsolutePath() + " and repairing"); - try { - java.nio.file.Files.copy(file.toPath(), corrupt.toPath()); - - } catch (IOException e) { - logger.error("Error backing up corrupt file" + file.getAbsolutePath(), e); - } - } - - private final byte[] oversized = new byte[1024]; - private int oversizedCount = 0; - - private synchronized void initOversizedState() throws IOException { - File metaFile = getOversizedMetaFile(); - if (metaFile.exists()) { - final byte[] read = java.nio.file.Files.readAllBytes(metaFile.toPath()); - System.arraycopy(read, 0, oversized, 0, oversized.length); - for (byte temp : oversized) { - oversizedCount += temp; - } - } - } - - private static int getChunkIndex(int x, int z) { - return (x & 31) + (z & 31) * 32; - } - synchronized boolean isOversized(int x, int z) { - return this.oversized[getChunkIndex(x, z)] == 1; - } - synchronized void setOversized(int x, int z, boolean oversized) throws IOException { - final int offset = getChunkIndex(x, z); - boolean previous = this.oversized[offset] == 1; - this.oversized[offset] = (byte) (oversized ? 1 : 0); - if (!previous && oversized) { - oversizedCount++; - } else if (!oversized && previous) { - oversizedCount--; - } - if (previous && !oversized) { - File oversizedFile = getOversizedFile(x, z); - if (oversizedFile.exists()) { - oversizedFile.delete(); - } - } - if (oversizedCount > 0) { - if (previous != oversized) { - writeOversizedMeta(); - } - } else if (previous) { - File oversizedMetaFile = getOversizedMetaFile(); - if (oversizedMetaFile.exists()) { - oversizedMetaFile.delete(); - } - } - } - - private void writeOversizedMeta() throws IOException { - java.nio.file.Files.write(getOversizedMetaFile().toPath(), oversized); - } - - private File getOversizedMetaFile() { - return new File(this.file.getParentFile(), this.file.getName().replaceAll("\\.mca$", "") + ".oversized.nbt"); - } - - private File getOversizedFile(int x, int z) { - return new File(this.file.getParentFile(), this.file.getName().replaceAll("\\.mca$", "") + "_oversized_" + x + "_" + z + ".nbt"); - } - - void writeOversizedData(int x, int z, NBTTagCompound oversizedData) throws IOException { - File file = getOversizedFile(x, z); - try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new DeflaterOutputStream(new java.io.FileOutputStream(file), new java.util.zip.Deflater(java.util.zip.Deflater.BEST_COMPRESSION), 32 * 1024), 32 * 1024))) { - NBTCompressedStreamTools.writeNBT(oversizedData, out); - } - this.setOversized(x, z, true); - - } - - synchronized NBTTagCompound getOversizedData(int x, int z) throws IOException { - File file = getOversizedFile(x, z); - try (DataInputStream out = new DataInputStream(new BufferedInputStream(new InflaterInputStream(new java.io.FileInputStream(file))))) { - return NBTCompressedStreamTools.readNBT(out); - } - - } - - private static final boolean USE_SPIGOT_OVERSIZED_METHOD = Boolean.getBoolean("Paper.useSpigotExtendedSaveMethod"); // Paper - static { - if (USE_SPIGOT_OVERSIZED_METHOD) { - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.SEVERE, "===================================="); - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.SEVERE, "Using Spigot Oversized Chunk save method. Warning this will result in extremely fragmented chunks, as well as making the entire region file unable to be to used in any other software but Forge or Spigot (not usable in Vanilla or CraftBukkit). Paper's method is highly recommended."); - org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.SEVERE, "===================================="); - } - } - public class ChunkTooLargeException extends RuntimeException { - public ChunkTooLargeException(int x, int z, int sectors) { - super("Chunk " + x + "," + z + " of " + RegionFile.this.file.toString() + " is too large (" + sectors + "/255)"); - } - } - private static class DirectByteArrayOutputStream extends ByteArrayOutputStream { - public DirectByteArrayOutputStream() { - super(); - } - - public DirectByteArrayOutputStream(int size) { - super(size); - } - - public byte[] getBuffer() { - return this.buf; - } - } - // Paper end - - class ChunkBuffer extends ByteArrayOutputStream { - - private final ChunkCoordIntPair b; - - public ChunkBuffer(ChunkCoordIntPair chunkcoordintpair) { - super(8096); - this.b = chunkcoordintpair; - } - - public void close() throws IOException { - // Paper start - apply dynamic compression - int origLength = this.count; - byte[] buf = this.buf; - DirectByteArrayOutputStream out = compressData(buf, origLength); - byte[] bytes = out.getBuffer(); - int length = out.size(); - - RegionFile.this.a(this.b, bytes, length); // Paper - change to bytes/length - } - } - - private static final byte[] compressionBuffer = new byte[1024 * 64]; // 64k fits most standard chunks input size even, ideally 1 pass through zlib - private static final java.util.zip.Deflater deflater = new java.util.zip.Deflater(); - // since file IO is single threaded, no benefit to using per-region file buffers/synchronization, we can change that later if it becomes viable. - private static DirectByteArrayOutputStream compressData(byte[] buf, int length) throws IOException { - synchronized (deflater) { - deflater.setInput(buf, 0, length); - deflater.finish(); - - DirectByteArrayOutputStream out = new DirectByteArrayOutputStream(length); - while (!deflater.finished()) { - out.write(compressionBuffer, 0, deflater.deflate(compressionBuffer)); - } - out.close(); - deflater.reset(); - return out; - } - } - // Paper end - -} diff --git a/src/main/java/net/minecraft/server/RegionFileCache.java b/src/main/java/net/minecraft/server/RegionFileCache.java deleted file mode 100644 index d3d610742..000000000 --- a/src/main/java/net/minecraft/server/RegionFileCache.java +++ /dev/null @@ -1,371 +0,0 @@ -package net.minecraft.server; - -import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import javax.annotation.Nullable; -import com.destroystokyo.paper.PaperConfig; // Paper - -import org.apache.logging.log4j.LogManager; - -public abstract class RegionFileCache implements AutoCloseable { - - public final Long2ObjectLinkedOpenHashMap cache = new Long2ObjectLinkedOpenHashMap(); - private final File a; - // Paper start - private final File templateWorld; - private final File actualWorld; - private boolean useAltWorld; - // Paper end - - - protected RegionFileCache(File file) { - this.a = file; - // Paper end - - this.actualWorld = file; - if (com.destroystokyo.paper.PaperConfig.useVersionedWorld) { - this.useAltWorld = true; - String name = file.getName(); - File container = file.getParentFile().getParentFile(); - if (name.equals("DIM-1") || name.equals("DIM1")) { - container = container.getParentFile(); - } - this.templateWorld = new File(container, name); - File region = new File(file, "region"); - if (!region.exists()) { - region.mkdirs(); - } - } else { - this.useAltWorld = false; - this.templateWorld = file; - } - // Paper start - } - - // Paper start - public synchronized RegionFile getRegionFileIfLoaded(ChunkCoordIntPair chunkcoordintpair) { // Paper - synchronize for async io - return this.cache.getAndMoveToFirst(ChunkCoordIntPair.pair(chunkcoordintpair.getRegionX(), chunkcoordintpair.getRegionZ())); - } - // Paper end - - public RegionFile getRegionFile(ChunkCoordIntPair chunkcoordintpair, boolean existingOnly) throws IOException { return this.a(chunkcoordintpair, existingOnly); } // Paper - OBFHELPER - private synchronized RegionFile a(ChunkCoordIntPair chunkcoordintpair, boolean existingOnly) throws IOException { // CraftBukkit // Paper - synchronize for async io - long i = ChunkCoordIntPair.pair(chunkcoordintpair.getRegionX(), chunkcoordintpair.getRegionZ()); - RegionFile regionfile = (RegionFile) this.cache.getAndMoveToFirst(i); - - if (regionfile != null) { - return regionfile; - } else { - if (this.cache.size() >= PaperConfig.regionFileCacheSize) { // Paper - configurable - ((RegionFile) this.cache.removeLast()).close(); - } - - if (!this.a.exists()) { - this.a.mkdirs(); - } - - copyIfNeeded(chunkcoordintpair.x, chunkcoordintpair.z); // Paper - File file = new File(this.a, "r." + chunkcoordintpair.getRegionX() + "." + chunkcoordintpair.getRegionZ() + ".mca"); - if (existingOnly && !file.exists()) return null; // CraftBukkit - RegionFile regionfile1 = new RegionFile(file); - - this.cache.putAndMoveToFirst(i, regionfile1); - return regionfile1; - } - } - - public static File getRegionFileName(File file, int i, int j) { - File file1 = new File(file, "region"); - return new File(file1, "r." + (i >> 5) + "." + (j >> 5) + ".mca"); - } - public synchronized boolean hasRegionFile(File file, int i, int j) { - return cache.containsKey(ChunkCoordIntPair.pair(i, j)); - } - // Paper start - private static void printOversizedLog(String msg, File file, int x, int z) { - org.apache.logging.log4j.LogManager.getLogger().fatal(msg + " (" + file.toString().replaceAll(".+[\\\\/]", "") + " - " + x + "," + z + ") Go clean it up to remove this message. /minecraft:tp " + (x<<4)+" 128 "+(z<<4) + " - DO NOT REPORT THIS TO PAPER - You may ask for help on Discord, but do not file an issue. These error messages can not be removed."); - } - - private static final int DEFAULT_SIZE_THRESHOLD = 1024 * 8; - private static final int OVERZEALOUS_TOTAL_THRESHOLD = 1024 * 64; - private static final int OVERZEALOUS_THRESHOLD = 1024; - private static int SIZE_THRESHOLD = DEFAULT_SIZE_THRESHOLD; - private static void resetFilterThresholds() { - SIZE_THRESHOLD = Math.max(1024 * 4, Integer.getInteger("Paper.FilterThreshhold", DEFAULT_SIZE_THRESHOLD)); - } - static { - resetFilterThresholds(); - } - - static boolean isOverzealous() { - return SIZE_THRESHOLD == OVERZEALOUS_THRESHOLD; - } - - private void writeRegion(ChunkCoordIntPair chunk, NBTTagCompound nbttagcompound) throws IOException { - RegionFile regionfile = getRegionFile(chunk, false); - - int chunkX = chunk.x; - int chunkZ = chunk.z; - - DataOutputStream out = regionfile.getWriteStream(chunk); - try { - NBTCompressedStreamTools.writeNBT(nbttagcompound, out); - out.close(); - regionfile.setStatus(chunk.x, chunk.z, ChunkRegionLoader.getStatus(nbttagcompound)); // Paper - cache status on disk - regionfile.setOversized(chunkX, chunkZ, false); - } catch (RegionFile.ChunkTooLargeException ignored) { - printOversizedLog("ChunkTooLarge! Someone is trying to duplicate.", regionfile.file, chunkX, chunkZ); - // Clone as we are now modifying it, don't want to corrupt the pending save state - nbttagcompound = nbttagcompound.clone(); - // Filter out TileEntities and Entities - NBTTagCompound oversizedData = filterChunkData(nbttagcompound); - //noinspection SynchronizationOnLocalVariableOrMethodParameter - synchronized (regionfile) { - out = regionfile.getWriteStream(chunk); - NBTCompressedStreamTools.writeNBT(nbttagcompound, out); - try { - out.close(); - // 2048 is below the min allowed, so it means we enter overzealous mode below - if (SIZE_THRESHOLD == OVERZEALOUS_THRESHOLD) { - resetFilterThresholds(); - } - regionfile.setStatus(chunk.x, chunk.z, ChunkRegionLoader.getStatus(nbttagcompound)); // Paper - cache status on disk - } catch (RegionFile.ChunkTooLargeException e) { - printOversizedLog("ChunkTooLarge even after reduction. Trying in overzealous mode.", regionfile.file, chunkX, chunkZ); - // Eek, major fail. We have retry logic, so reduce threshholds and fall back - SIZE_THRESHOLD = OVERZEALOUS_THRESHOLD; - throw e; - } - - regionfile.writeOversizedData(chunkX, chunkZ, oversizedData); - } - } - } - - private static NBTTagCompound filterChunkData(NBTTagCompound chunk) { - NBTTagCompound oversizedLevel = new NBTTagCompound(); - NBTTagCompound level = chunk.getCompound("Level"); - filterChunkList(level, oversizedLevel, "Entities"); - filterChunkList(level, oversizedLevel, "TileEntities"); - NBTTagCompound oversized = new NBTTagCompound(); - oversized.set("Level", oversizedLevel); - return oversized; - } - - private static void filterChunkList(NBTTagCompound level, NBTTagCompound extra, String key) { - NBTTagList list = level.getList(key, 10); - NBTTagList newList = extra.getList(key, 10); - int totalSize = 0; - for (java.util.Iterator iterator = list.list.iterator(); iterator.hasNext();) { - NBTBase object = iterator.next(); - int nbtSize = getNBTSize(object); - if (nbtSize > SIZE_THRESHOLD || (SIZE_THRESHOLD == OVERZEALOUS_THRESHOLD && totalSize > OVERZEALOUS_TOTAL_THRESHOLD)) { - newList.add(object); - iterator.remove(); - } else { - totalSize += nbtSize; - } - } - level.set(key, list); - extra.set(key, newList); - } - - - private static NBTTagCompound readOversizedChunk(RegionFile regionfile, ChunkCoordIntPair chunkCoordinate) throws IOException { - synchronized (regionfile) { - try (DataInputStream datainputstream = regionfile.getReadStream(chunkCoordinate)) { - // Paper start - Handle bad chunks more gracefully - also handle similarly with oversized data - NBTTagCompound oversizedData = null; - - try { - oversizedData = regionfile.getOversizedData(chunkCoordinate.x, chunkCoordinate.z); - } catch (Exception ex) {} - - NBTTagCompound chunk; - - try { - chunk = NBTCompressedStreamTools.readNBT(datainputstream); - } catch (final Exception ex) { - return null; - } - // Paper end - if (oversizedData == null) { - return chunk; - } - NBTTagCompound oversizedLevel = oversizedData.getCompound("Level"); - NBTTagCompound level = chunk.getCompound("Level"); - - mergeChunkList(level, oversizedLevel, "Entities"); - mergeChunkList(level, oversizedLevel, "TileEntities"); - - chunk.set("Level", level); - - return chunk; - } catch (Throwable throwable) { - throwable.printStackTrace(); - throw throwable; - } - } - } - - private static void mergeChunkList(NBTTagCompound level, NBTTagCompound oversizedLevel, String key) { - NBTTagList levelList = level.getList(key, 10); - NBTTagList oversizedList = oversizedLevel.getList(key, 10); - - if (!oversizedList.isEmpty()) { - levelList.addAll(oversizedList); - level.set(key, levelList); - } - } - - private static int getNBTSize(NBTBase nbtBase) { - DataOutputStream test = new DataOutputStream(new org.apache.commons.io.output.NullOutputStream()); - try { - nbtBase.write(test); - return test.size(); - } catch (IOException e) { - e.printStackTrace(); - return 0; - } - } - - // Paper End - - @Nullable - public NBTTagCompound read(ChunkCoordIntPair chunkcoordintpair) throws IOException { - RegionFile regionfile = this.a(chunkcoordintpair, false); // CraftBukkit - DataInputStream datainputstream = regionfile.a(chunkcoordintpair); - // Paper start - if (regionfile.isOversized(chunkcoordintpair.x, chunkcoordintpair.z)) { - printOversizedLog("Loading Oversized Chunk!", regionfile.file, chunkcoordintpair.x, chunkcoordintpair.z); - return readOversizedChunk(regionfile, chunkcoordintpair); - } - // Paper end - Throwable throwable = null; - - NBTTagCompound nbttagcompound; - - try { - if (datainputstream != null) { - // Paper start - Handle bad chunks more gracefully - try { - return NBTCompressedStreamTools.a(datainputstream); - } catch (Exception ex) { - return null; - } - // Paper end - } - - nbttagcompound = null; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (datainputstream != null) { - if (throwable != null) { - try { - datainputstream.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - datainputstream.close(); - } - } - - } - - return nbttagcompound; - } - - protected void write(ChunkCoordIntPair chunkcoordintpair, NBTTagCompound nbttagcompound) throws IOException { - int attempts = 0; Exception laste = null; while (attempts++ < 5) { try { // Paper - // Paper start - this.writeRegion(chunkcoordintpair, nbttagcompound); -// RegionFile regionfile = this.a(chunkcoordintpair, false); // CraftBukkit -// DataOutputStream dataoutputstream = regionfile.c(chunkcoordintpair); -// Throwable throwable = null; -// -// try { -// NBTCompressedStreamTools.a(nbttagcompound, (DataOutput) dataoutputstream); -// } catch (Throwable throwable1) { -// throwable = throwable1; -// throw throwable1; -// } finally { -// if (dataoutputstream != null) { -// if (throwable != null) { -// try { -// dataoutputstream.close(); -// } catch (Throwable throwable2) { -// throwable.addSuppressed(throwable2); -// } -// } else { -// dataoutputstream.close(); -// } -// } -// -// } - // Paper end - - // Paper start - return; - } catch (Exception ex) { - laste = ex; - } - } - - if (laste != null) { - com.destroystokyo.paper.exception.ServerInternalException.reportInternalException(laste); - MinecraftServer.LOGGER.error("Failed to save chunk", laste); - } - // Paper end - } - - public void close() throws IOException { - ObjectIterator objectiterator = this.cache.values().iterator(); - - while (objectiterator.hasNext()) { - RegionFile regionfile = (RegionFile) objectiterator.next(); - - regionfile.close(); - } - - } - - // CraftBukkit start - public synchronized boolean chunkExists(ChunkCoordIntPair pos) throws IOException { // Paper - synchronize - copyIfNeeded(pos.x, pos.z); // Paper - RegionFile regionfile = a(pos, true); - - return regionfile != null ? regionfile.d(pos) : false; - } - // CraftBukkit end - - private void copyIfNeeded(int x, int z) { - if (!useAltWorld) { - return; - } - synchronized (RegionFileCache.class) { - if (hasRegionFile(this.actualWorld, x, z)) { - return; - } - File actual = RegionFileCache.getRegionFileName(this.actualWorld, x, z); - File template = RegionFileCache.getRegionFileName(this.templateWorld, x, z); - if (!actual.exists() && template.exists()) { - try { - net.minecraft.server.MinecraftServer.LOGGER.info("Copying" + template + " to " + actual); - java.nio.file.Files.copy(template.toPath(), actual.toPath(), java.nio.file.StandardCopyOption.COPY_ATTRIBUTES); - } catch (IOException e1) { - LogManager.getLogger().error("Error copying " + template + " to " + actual, e1); - MinecraftServer.getServer().safeShutdown(false); - com.destroystokyo.paper.util.SneakyThrow.sneaky(e1); - } - } - } - } -} diff --git a/src/main/java/net/minecraft/server/RegionFileSection.java b/src/main/java/net/minecraft/server/RegionFileSection.java deleted file mode 100644 index 04b7dab64..000000000 --- a/src/main/java/net/minecraft/server/RegionFileSection.java +++ /dev/null @@ -1,242 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.mojang.datafixers.DataFixer; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.OptionalDynamic; -import com.mojang.datafixers.types.DynamicOps; -import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet; -import java.io.File; -import java.io.IOException; -import java.util.Map; -import java.util.Optional; -import java.util.function.BiFunction; -import java.util.function.BooleanSupplier; -import java.util.function.Function; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class RegionFileSection extends RegionFileCache { - - private static final Logger LOGGER = LogManager.getLogger(); - private final Long2ObjectMap> b = new Long2ObjectOpenHashMap(); - protected final LongLinkedOpenHashSet d = new LongLinkedOpenHashSet(); // Paper - private -> protected - private final BiFunction, R> e; - private final Function f; - private final DataFixer g; - private final DataFixTypes h; - - public RegionFileSection(File file, BiFunction, R> bifunction, Function function, DataFixer datafixer, DataFixTypes datafixtypes) { - super(file); - this.e = bifunction; - this.f = function; - this.g = datafixer; - this.h = datafixtypes; - } - - protected void a(BooleanSupplier booleansupplier) { - while (!this.d.isEmpty() && booleansupplier.getAsBoolean()) { // Paper - conflict here to avoid obfhelpers - ChunkCoordIntPair chunkcoordintpair = SectionPosition.a(this.d.firstLong()).u(); // Paper - conflict here to avoid obfhelpers - - this.d(chunkcoordintpair); - } - - } - - @Nullable - protected Optional c(long i) { - return (Optional) this.b.get(i); - } - - protected Optional d(long i) { - SectionPosition sectionposition = SectionPosition.a(i); - - if (this.b(sectionposition)) { - return Optional.empty(); - } else { - Optional optional = this.c(i); - - if (optional != null) { - return optional; - } else { - this.b(sectionposition.u()); - optional = this.c(i); - if (optional == null) { - throw new IllegalStateException(); - } else { - return optional; - } - } - } - } - - protected boolean b(SectionPosition sectionposition) { - return World.b(SectionPosition.c(sectionposition.b())); - } - - protected R e(long i) { - Optional optional = this.d(i); - - if (optional.isPresent()) { - return optional.get(); // Paper - decompile fix - } else { - R r0 = this.f.apply(() -> { // Paper - decompile fix - this.a(i); - }); - - this.b.put(i, Optional.of(r0)); - return r0; - } - } - - private void b(ChunkCoordIntPair chunkcoordintpair) { - // Paper start - load data in function - this.loadInData(chunkcoordintpair, this.c(chunkcoordintpair)); - } - public void loadInData(ChunkCoordIntPair chunkPos, NBTTagCompound compound) { - this.a(chunkPos, DynamicOpsNBT.a, compound); - // Paper end - } - - @Nullable - private NBTTagCompound c(ChunkCoordIntPair chunkcoordintpair) { - try { - return this.read(chunkcoordintpair); - } catch (IOException ioexception) { - RegionFileSection.LOGGER.error("Error reading chunk {} data from disk", chunkcoordintpair, ioexception); - return null; - } - } - - private void a(ChunkCoordIntPair chunkcoordintpair, DynamicOps dynamicops, @Nullable T t0) { - if (t0 == null) { - for (int i = 0; i < 16; ++i) { - this.b.put(SectionPosition.a(chunkcoordintpair, i).v(), Optional.empty()); - } - } else { - Dynamic dynamic = new Dynamic(dynamicops, t0); - int j = a(dynamic); - int k = SharedConstants.a().getWorldVersion(); - boolean flag = j != k; - Dynamic dynamic1 = this.g.update(this.h.a(), dynamic, j, k); - OptionalDynamic optionaldynamic = dynamic1.get("Sections"); - - for (int l = 0; l < 16; ++l) { - long i1 = SectionPosition.a(chunkcoordintpair, l).v(); - Optional optional = optionaldynamic.get(Integer.toString(l)).get().map((dynamic2) -> { - return this.e.apply(() -> { // Paper - decompile fix - this.a(i1); - }, dynamic2); - }); - - this.b.put(i1, optional); - optional.ifPresent((minecraftserializable) -> { - this.b(i1); - if (flag) { - this.a(i1); - } - - }); - } - } - - } - - private void d(ChunkCoordIntPair chunkcoordintpair) { - Dynamic dynamic = this.a(chunkcoordintpair, DynamicOpsNBT.a); // Paper - conflict here to avoid adding obfhelpers :) - NBTBase nbtbase = (NBTBase) dynamic.getValue(); - - if (nbtbase instanceof NBTTagCompound) { - try { - this.write(chunkcoordintpair, (NBTTagCompound) nbtbase); - } catch (IOException ioexception) { - RegionFileSection.LOGGER.error("Error writing data to disk", ioexception); - } - } else { - RegionFileSection.LOGGER.error("Expected compound tag, got {}", nbtbase); - } - - } - - // Paper start - internal get data function, copied from above - private NBTTagCompound getDataInternal(ChunkCoordIntPair chunkcoordintpair) { - Dynamic dynamic = this.a(chunkcoordintpair, DynamicOpsNBT.a); - NBTBase nbtbase = (NBTBase) dynamic.getValue(); - - if (nbtbase instanceof NBTTagCompound) { - return (NBTTagCompound)nbtbase; - } else { - RegionFileSection.LOGGER.error("Expected compound tag, got {}", nbtbase); - } - return null; - } - // Paper end - - private Dynamic a(ChunkCoordIntPair chunkcoordintpair, DynamicOps dynamicops) { - Map map = Maps.newHashMap(); - - for (int i = 0; i < 16; ++i) { - long j = SectionPosition.a(chunkcoordintpair, i).v(); - - this.d.remove(j); - Optional optional = (Optional) this.b.get(j); - - if (optional != null && optional.isPresent()) { - map.put(dynamicops.createString(Integer.toString(i)), ((MinecraftSerializable) optional.get()).a(dynamicops)); - } - } - - return new Dynamic(dynamicops, dynamicops.createMap(ImmutableMap.of(dynamicops.createString("Sections"), dynamicops.createMap(map), dynamicops.createString("DataVersion"), dynamicops.createInt(SharedConstants.a().getWorldVersion())))); - } - - protected void b(long i) {} - - protected void a(long i) { - Optional optional = (Optional) this.b.get(i); - - if (optional != null && optional.isPresent()) { - this.d.add(i); - } else { - RegionFileSection.LOGGER.warn("No data for position: {}", SectionPosition.a(i)); - } - } - - private static int a(Dynamic dynamic) { - return ((Number) dynamic.get("DataVersion").asNumber().orElse(1945)).intValue(); - } - - public void a(ChunkCoordIntPair chunkcoordintpair) { - if (!this.d.isEmpty()) { - for (int i = 0; i < 16; ++i) { - long j = SectionPosition.a(chunkcoordintpair, i).v(); // Paper - conflict here to avoid obfhelpers - - if (this.d.contains(j)) { // Paper - conflict here to avoid obfhelpers - this.d(chunkcoordintpair); - return; - } - } - } - - } - - // Paper start - get data function - public NBTTagCompound getData(ChunkCoordIntPair chunkcoordintpair) { - // Note: Copied from above - // This is checking if the data exists, then it builds it later in getDataInternal(ChunkCoordIntPair) - if (!this.d.isEmpty()) { - for (int i = 0; i < 16; ++i) { - long j = SectionPosition.a(chunkcoordintpair, i).v(); - - if (this.d.contains(j)) { - return this.getDataInternal(chunkcoordintpair); - } - } - } - return null; - } - // Paper end -} diff --git a/src/main/java/net/minecraft/server/RegionLimitedWorldAccess.java b/src/main/java/net/minecraft/server/RegionLimitedWorldAccess.java deleted file mode 100644 index ac6687754..000000000 --- a/src/main/java/net/minecraft/server/RegionLimitedWorldAccess.java +++ /dev/null @@ -1,396 +0,0 @@ -package net.minecraft.server; - -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.function.Predicate; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class RegionLimitedWorldAccess implements GeneratorAccess { - - private static final Logger LOGGER = LogManager.getLogger(); - private final List b; - private final int c; - private final int d; - private final int e; - private final WorldServer f; - private final long g; - private final int h; - private final WorldData i; - private final Random j; - private final WorldProvider k; - private final GeneratorSettingsDefault l; - private final TickList m = new TickListWorldGen<>((blockposition) -> { - return this.w(blockposition).n(); - }); - private final TickList n = new TickListWorldGen<>((blockposition) -> { - return this.w(blockposition).o(); - }); - - public RegionLimitedWorldAccess(WorldServer worldserver, List list) { - int i = MathHelper.floor(Math.sqrt((double) list.size())); - - if (i * i != list.size()) { - throw new IllegalStateException("Cache size is not a square."); - } else { - ChunkCoordIntPair chunkcoordintpair = ((IChunkAccess) list.get(list.size() / 2)).getPos(); - - this.b = list; - this.c = chunkcoordintpair.x; - this.d = chunkcoordintpair.z; - this.e = i; - this.f = worldserver; - this.g = worldserver.getSeed(); - this.l = worldserver.getChunkProvider().getChunkGenerator().getSettings(); - this.h = worldserver.getSeaLevel(); - this.i = worldserver.getWorldData(); - this.j = worldserver.getRandom(); - this.k = worldserver.getWorldProvider(); - } - } - - public int a() { - return this.c; - } - - public int b() { - return this.d; - } - - @Override - public IChunkAccess getChunkAt(int i, int j) { - return this.getChunkAt(i, j, ChunkStatus.EMPTY); - } - - @Nullable - @Override - public IChunkAccess getChunkAt(int i, int j, ChunkStatus chunkstatus, boolean flag) { - IChunkAccess ichunkaccess; - - if (this.isChunkLoaded(i, j)) { - ChunkCoordIntPair chunkcoordintpair = ((IChunkAccess) this.b.get(0)).getPos(); - int k = i - chunkcoordintpair.x; - int l = j - chunkcoordintpair.z; - - ichunkaccess = (IChunkAccess) this.b.get(k + l * this.e); - if (ichunkaccess.getChunkStatus().b(chunkstatus)) { - return ichunkaccess; - } - } else { - ichunkaccess = null; - } - - if (!flag) { - return null; - } else { - IChunkAccess ichunkaccess1 = (IChunkAccess) this.b.get(0); - IChunkAccess ichunkaccess2 = (IChunkAccess) this.b.get(this.b.size() - 1); - - RegionLimitedWorldAccess.LOGGER.error("Requested chunk : {} {}", i, j); - RegionLimitedWorldAccess.LOGGER.error("Region bounds : {} {} | {} {}", ichunkaccess1.getPos().x, ichunkaccess1.getPos().z, ichunkaccess2.getPos().x, ichunkaccess2.getPos().z); - if (ichunkaccess != null) { - throw new RuntimeException(String.format("Chunk is not of correct status. Expecting %s, got %s | %s %s", chunkstatus, ichunkaccess.getChunkStatus(), i, j)); - } else { - throw new RuntimeException(String.format("We are asking a region for a chunk out of bound | %s %s", i, j)); - } - } - } - - @Override - public boolean isChunkLoaded(int i, int j) { - IChunkAccess ichunkaccess = (IChunkAccess) this.b.get(0); - IChunkAccess ichunkaccess1 = (IChunkAccess) this.b.get(this.b.size() - 1); - - return i >= ichunkaccess.getPos().x && i <= ichunkaccess1.getPos().x && j >= ichunkaccess.getPos().z && j <= ichunkaccess1.getPos().z; - } - - // Paper start - if loaded util - @Nullable - @Override - public IChunkAccess getChunkIfLoadedImmediately(int x, int z) { - return this.getChunkAt(x, z, ChunkStatus.FULL, false); - } - - @Override - public IBlockData getTypeIfLoaded(BlockPosition blockposition) { - IChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4); - return chunk == null ? null : chunk.getType(blockposition); - } - - @Override - public Fluid getFluidIfLoaded(BlockPosition blockposition) { - IChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4); - return chunk == null ? null : chunk.getFluid(blockposition); - } - // Paper end - - @Override - public IBlockData getType(BlockPosition blockposition) { - return this.getChunkAt(blockposition.getX() >> 4, blockposition.getZ() >> 4).getType(blockposition); - } - - @Override - public Fluid getFluid(BlockPosition blockposition) { - return this.w(blockposition).getFluid(blockposition); - } - - @Nullable - @Override - public EntityHuman a(double d0, double d1, double d2, double d3, Predicate predicate) { - return null; - } - - @Override - public int c() { - return 0; - } - - @Override - public BiomeBase getBiome(BlockPosition blockposition) { - BiomeBase biomebase = this.w(blockposition).getBiomeIndex()[blockposition.getX() & 15 | (blockposition.getZ() & 15) << 4]; - - if (biomebase == null) { - throw new RuntimeException(String.format("Biome is null @ %s", blockposition)); - } else { - return biomebase; - } - } - - @Override - public int getBrightness(EnumSkyBlock enumskyblock, BlockPosition blockposition) { - return this.getChunkProvider().getLightEngine().a(enumskyblock).b(blockposition); - } - - @Override - public int getLightLevel(BlockPosition blockposition, int i) { - return this.w(blockposition).a(blockposition, i, this.getWorldProvider().g()); - } - - @Override - public boolean b(BlockPosition blockposition, boolean flag) { - IBlockData iblockdata = this.getType(blockposition); - - if (iblockdata.isAir()) { - return false; - } else { - if (flag) { - TileEntity tileentity = iblockdata.getBlock().isTileEntity() ? this.getTileEntity(blockposition) : null; - - Block.a(iblockdata, (World) this.f, blockposition, tileentity); - } - - return this.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3); - } - } - - @Nullable - @Override - public TileEntity getTileEntity(BlockPosition blockposition) { - IChunkAccess ichunkaccess = this.w(blockposition); - TileEntity tileentity = ichunkaccess.getTileEntity(blockposition); - - if (tileentity != null) { - return tileentity; - } else { - NBTTagCompound nbttagcompound = ichunkaccess.i(blockposition); - - if (nbttagcompound != null) { - if ("DUMMY".equals(nbttagcompound.getString("id"))) { - Block block = this.getType(blockposition).getBlock(); - - if (!(block instanceof ITileEntity)) { - return null; - } - - tileentity = ((ITileEntity) block).createTile(this.f); - } else { - tileentity = TileEntity.create(nbttagcompound); - } - - if (tileentity != null) { - ichunkaccess.setTileEntity(blockposition, tileentity); - return tileentity; - } - } - - if (ichunkaccess.getType(blockposition).getBlock() instanceof ITileEntity) { - RegionLimitedWorldAccess.LOGGER.warn("Tried to access a block entity before it was created. {}", blockposition); - } - - return null; - } - } - - @Override - public boolean setTypeAndData(BlockPosition blockposition, IBlockData iblockdata, int i) { - IChunkAccess ichunkaccess = this.w(blockposition); - IBlockData iblockdata1 = ichunkaccess.setType(blockposition, iblockdata, false); - - if (iblockdata1 != null) { - this.f.a(blockposition, iblockdata1, iblockdata); - } - - Block block = iblockdata.getBlock(); - - if (block.isTileEntity()) { - if (ichunkaccess.getChunkStatus().getType() == ChunkStatus.Type.LEVELCHUNK) { - ichunkaccess.setTileEntity(blockposition, ((ITileEntity) block).createTile(this)); - } else { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setInt("x", blockposition.getX()); - nbttagcompound.setInt("y", blockposition.getY()); - nbttagcompound.setInt("z", blockposition.getZ()); - nbttagcompound.setString("id", "DUMMY"); - ichunkaccess.a(nbttagcompound); - } - } else if (iblockdata1 != null && iblockdata1.getBlock().isTileEntity()) { - ichunkaccess.removeTileEntity(blockposition); - } - - if (iblockdata.n(this, blockposition)) { - this.i(blockposition); - } - - return true; - } - - private void i(BlockPosition blockposition) { - this.w(blockposition).f(blockposition); - } - - @Override - public boolean addEntity(Entity entity) { - // CraftBukkit start - return addEntity(entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT); - } - - @Override - public boolean addEntity(Entity entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason reason) { - // CraftBukkit end - int i = MathHelper.floor(entity.locX / 16.0D); - int j = MathHelper.floor(entity.locZ / 16.0D); - - this.getChunkAt(i, j).a(entity); - return true; - } - - @Override - public boolean a(BlockPosition blockposition, boolean flag) { - return this.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3); - } - - @Override - public WorldBorder getWorldBorder() { - return this.f.getWorldBorder(); - } - - @Override - public boolean a(@Nullable Entity entity, VoxelShape voxelshape) { - return true; - } - - @Override - public boolean e() { - return false; - } - - @Deprecated - @Override - public WorldServer getMinecraftWorld() { - return this.f; - } - - @Override - public WorldData getWorldData() { - return this.i; - } - - @Override - public DifficultyDamageScaler getDamageScaler(BlockPosition blockposition) { - if (!this.isChunkLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4)) { - throw new RuntimeException("We are asking a region for a chunk out of bound"); - } else { - return new DifficultyDamageScaler(this.f.getDifficulty(), this.f.getDayTime(), 0L, this.f.aa()); - } - } - - @Override - public IChunkProvider getChunkProvider() { - return this.f.getChunkProvider(); - } - - @Override - public long getSeed() { - return this.g; - } - - @Override - public TickList getBlockTickList() { - return this.m; - } - - @Override - public TickList getFluidTickList() { - return this.n; - } - - @Override - public int getSeaLevel() { - return this.h; - } - - @Override - public Random getRandom() { - return this.j; - } - - @Override - public void update(BlockPosition blockposition, Block block) {} - - @Override - public int a(HeightMap.Type heightmap_type, int i, int j) { - return this.getChunkAt(i >> 4, j >> 4).a(heightmap_type, i & 15, j & 15) + 1; - } - - @Override - public void playSound(@Nullable EntityHuman entityhuman, BlockPosition blockposition, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) {} - - @Override - public void addParticle(ParticleParam particleparam, double d0, double d1, double d2, double d3, double d4, double d5) {} - - @Override - public void a(@Nullable EntityHuman entityhuman, int i, BlockPosition blockposition, int j) {} - - @Override - public WorldProvider getWorldProvider() { - return this.k; - } - - @Override - public boolean a(BlockPosition blockposition, Predicate predicate) { - return predicate.test(this.getType(blockposition)); - } - - @Override - public List a(Class oclass, AxisAlignedBB axisalignedbb, @Nullable Predicate predicate) { - return Collections.emptyList(); - } - - @Override - public List getEntities(@Nullable Entity entity, AxisAlignedBB axisalignedbb, @Nullable Predicate predicate) { - return Collections.emptyList(); - } - - @Override - public List getPlayers() { - return Collections.emptyList(); - } - - @Override - public BlockPosition getHighestBlockYAt(HeightMap.Type heightmap_type, BlockPosition blockposition) { - return new BlockPosition(blockposition.getX(), this.a(heightmap_type, blockposition.getX(), blockposition.getZ()), blockposition.getZ()); - } -} diff --git a/src/main/java/net/minecraft/server/RegistryBlockID.java b/src/main/java/net/minecraft/server/RegistryBlockID.java deleted file mode 100644 index 60948afa4..000000000 --- a/src/main/java/net/minecraft/server/RegistryBlockID.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Predicates; -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; - -public class RegistryBlockID implements Registry { - - private int a; - private final IdentityHashMap b; - private final List c; - - public RegistryBlockID() { - this(512); - } - - public RegistryBlockID(int i) { - this.c = Lists.newArrayListWithExpectedSize(i); - this.b = new IdentityHashMap(i); - } - - public void a(T t0, int i) { - this.b.put(t0, i); - - while (this.c.size() <= i) { - this.c.add(null); // Paper - decompile fix - } - - this.c.set(i, t0); - if (this.a <= i) { - this.a = i + 1; - } - - } - - public void b(T t0) { - this.a(t0, this.a); - } - - public int getId(T t0) { - Integer integer = (Integer) this.b.get(t0); - - return integer == null ? -1 : integer; - } - - @Nullable - @Override - public final T fromId(int i) { - return i >= 0 && i < this.c.size() ? this.c.get(i) : null; - } - - public Iterator iterator() { - return Iterators.filter(this.c.iterator(), Predicates.notNull()); - } - - public int size() { return this.a(); } // Paper - OBFHELPER - public int a() { - return this.b.size(); - } -} diff --git a/src/main/java/net/minecraft/server/RegistryID.java b/src/main/java/net/minecraft/server/RegistryID.java deleted file mode 100644 index e8a48b9a4..000000000 --- a/src/main/java/net/minecraft/server/RegistryID.java +++ /dev/null @@ -1,167 +0,0 @@ -package net.minecraft.server; - -import com.google.common.base.Predicates; -import com.google.common.collect.Iterators; -import java.util.Arrays; -import java.util.Iterator; -import javax.annotation.Nullable; - -public class RegistryID implements Registry { - - private static final Object a = null; - private K[] b; - private int[] c; - private K[] d; - private int e; - private int f; - private java.util.BitSet usedIds; // Paper - - public RegistryID(int i) { - i = (int) ((float) i / 0.8F); - this.b = (K[]) (new Object[i]); // Paper - decompile fix - this.c = new int[i]; - this.d = (K[]) (new Object[i]); // Paper - decompile fix - this.usedIds = new java.util.BitSet(); // Paper - } - - public int getId(@Nullable K k0) { - return this.c(this.b(k0, this.d(k0))); - } - - @Nullable - @Override - public K fromId(int i) { - return i >= 0 && i < this.d.length ? this.d[i] : null; - } - - private int c(int i) { - return i == -1 ? -1 : this.c[i]; - } - - public int c(K k0) { - int i = this.c(); - - this.a(k0, i); - return i; - } - - private int c() { - // Paper start - /* - while (this.e < this.d.length && this.d[this.e] != null) { - ++this.e; - } - */ - this.e = this.usedIds.nextClearBit(0); - // Paper end - - return this.e; - } - - private void d(int i) { - K[] ak = this.b; - int[] aint = this.c; - - this.b = (K[]) (new Object[i]); // Paper - decompile fix - this.c = new int[i]; - this.d = (K[]) (new Object[i]); // Paper - decompile fix - this.e = 0; - this.f = 0; - this.usedIds.clear(); // Paper - - for (int j = 0; j < ak.length; ++j) { - if (ak[j] != null) { - this.a(ak[j], aint[j]); - } - } - - } - - public void a(K k0, int i) { - int j = Math.max(i, this.f + 1); - int k; - - if ((float) j >= (float) this.b.length * 0.8F) { - for (k = this.b.length << 1; k < i; k <<= 1) { - ; - } - - this.d(k); - } - - k = this.e(this.d(k0)); - this.b[k] = k0; - this.c[k] = i; - this.d[i] = k0; - this.usedIds.set(i); // Paper - ++this.f; - if (i == this.e) { - ++this.e; - } - - } - - private int d(@Nullable K k0) { - return (MathHelper.f(System.identityHashCode(k0)) & Integer.MAX_VALUE) % this.b.length; - } - - private int b(@Nullable K k0, int i) { - int j; - - for (j = i; j < this.b.length; ++j) { - if (this.b[j] == k0) { - return j; - } - - if (this.b[j] == RegistryID.a) { - return -1; - } - } - - for (j = 0; j < i; ++j) { - if (this.b[j] == k0) { - return j; - } - - if (this.b[j] == RegistryID.a) { - return -1; - } - } - - return -1; - } - - private int e(int i) { - int j; - - for (j = i; j < this.b.length; ++j) { - if (this.b[j] == RegistryID.a) { - return j; - } - } - - for (j = 0; j < i; ++j) { - if (this.b[j] == RegistryID.a) { - return j; - } - } - - throw new RuntimeException("Overflowed :("); - } - - public Iterator iterator() { - return Iterators.filter(Iterators.forArray(this.d), Predicates.notNull()); - } - - public void a() { - Arrays.fill(this.b, (Object) null); - Arrays.fill(this.d, (Object) null); - this.e = 0; - this.f = 0; - this.usedIds.clear(); // Paper - } - - public int b() { - return this.f; - } -} diff --git a/src/main/java/net/minecraft/server/RegistryMaterials.java b/src/main/java/net/minecraft/server/RegistryMaterials.java deleted file mode 100644 index fed38e6ef..000000000 --- a/src/main/java/net/minecraft/server/RegistryMaterials.java +++ /dev/null @@ -1,106 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.Optional; -import java.util.Random; -import java.util.Set; -import javax.annotation.Nullable; -import org.apache.commons.lang3.Validate; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class RegistryMaterials extends IRegistryWritable { - - protected static final Logger LOGGER = LogManager.getLogger(); - protected final RegistryID b = new RegistryID<>(2048); // Paper - use bigger expected size to reduce collisions - protected final BiMap c = HashBiMap.create(2048); // Paper - use bigger expected size to reduce collisions - protected T[] d; // Paper - Decompile fix - private int R; - - public RegistryMaterials() {} - - @Override - public V a(int i, MinecraftKey minecraftkey, V v0) { - this.b.a(v0, i); - Validate.notNull(minecraftkey); - Validate.notNull(v0); - this.d = null; - if (this.c.containsKey(minecraftkey)) { - RegistryMaterials.LOGGER.debug("Adding duplicate key '{}' to registry", minecraftkey); - } - - this.c.put(minecraftkey, v0); - if (this.R <= i) { - this.R = i + 1; - } - - return v0; - } - - @Override - public V a(MinecraftKey minecraftkey, V v0) { - return this.a(this.R, minecraftkey, v0); - } - - @Nullable - @Override - public MinecraftKey getKey(T t0) { - return (MinecraftKey) this.c.inverse().get(t0); - } - - @Override - public int a(@Nullable T t0) { - return this.b.getId(t0); - } - - @Nullable - @Override - public T fromId(int i) { - return this.b.fromId(i); - } - - public Iterator iterator() { - return this.b.iterator(); - } - - @Nullable - @Override - public T get(@Nullable MinecraftKey minecraftkey) { - return this.c.get(minecraftkey); - } - - @Override - public Optional getOptional(@Nullable MinecraftKey minecraftkey) { - return Optional.ofNullable(this.c.get(minecraftkey)); - } - - @Override - public Set keySet() { - return Collections.unmodifiableSet(this.c.keySet()); - } - - @Override - public boolean c() { - return this.c.isEmpty(); - } - - @Nullable - @Override - public T a(Random random) { - if (this.d == null) { - Collection collection = this.c.values(); - - if (collection.isEmpty()) { - return null; - } - - this.d = (T[]) collection.toArray(new Object[collection.size()]); // Paper - Decompile fix - } - - return this.d[random.nextInt(this.d.length)]; - } -} diff --git a/src/main/java/net/minecraft/server/RemoteConnectionThread.java b/src/main/java/net/minecraft/server/RemoteConnectionThread.java deleted file mode 100644 index d821ef9a7..000000000 --- a/src/main/java/net/minecraft/server/RemoteConnectionThread.java +++ /dev/null @@ -1,188 +0,0 @@ -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; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public abstract class RemoteConnectionThread implements Runnable { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final AtomicInteger i = new AtomicInteger(0); - protected boolean a; - protected final IMinecraftServer b; protected IMinecraftServer getServer() { return this.b; } // Paper - OBFHELPER - protected final String c; - protected Thread d; - protected final int e = 5; - protected final List f = Lists.newArrayList(); - protected final 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.i.incrementAndGet()); - this.d.setUncaughtExceptionHandler(new ThreadNamedUncaughtExceptionHandler(RemoteConnectionThread.LOGGER)); - this.d.start(); - this.a = true; - } - - public synchronized void b() { - this.a = false; - if (null != this.d) { - int i = 0; - - while (this.d.isAlive()) { - try { - this.d.join(1000L); - ++i; - if (5 <= i) { - this.c("Waited " + i + " seconds attempting force stop!"); - this.a(true); - } else if (this.d.isAlive()) { - this.c("Thread " + this + " (" + this.d.getState() + ") failed to exit after " + i + " second(s)"); - this.c("Stack:"); - StackTraceElement[] astacktraceelement = this.d.getStackTrace(); - int j = astacktraceelement.length; - - for (int k = 0; k < j; ++k) { - StackTraceElement stacktraceelement = astacktraceelement[k]; - - this.c(stacktraceelement.toString()); - } - - this.d.interrupt(); - } - } catch (InterruptedException interruptedexception) { - ; - } - } - - this.a(true); - this.d = null; - } - } - - 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 getPlayerCount() { return this.d(); } // Paper - OBFHELPER - protected int d() { - return this.b.getPlayerCount(); - } - - 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/src/main/java/net/minecraft/server/RemoteControlCommandListener.java b/src/main/java/net/minecraft/server/RemoteControlCommandListener.java deleted file mode 100644 index e32c475e1..000000000 --- a/src/main/java/net/minecraft/server/RemoteControlCommandListener.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.minecraft.server; - -public class RemoteControlCommandListener implements ICommandListener { - - private final StringBuffer buffer = new StringBuffer(); - private final MinecraftServer server; - - public RemoteControlCommandListener(MinecraftServer minecraftserver) { - this.server = minecraftserver; - } - - public void clearMessages() { - this.buffer.setLength(0); - } - - public String getMessages() { - return this.buffer.toString(); - } - - public CommandListenerWrapper getWrapper() { - WorldServer worldserver = this.server.getWorldServer(DimensionManager.OVERWORLD); - - return new CommandListenerWrapper(this, new Vec3D(worldserver.getSpawn()), Vec2F.a, worldserver, 4, "Recon", new ChatComponentText("Rcon"), this.server, (Entity) null); - } - - // CraftBukkit start - Send a String - public void sendMessage(String message) { - this.buffer.append(message); - } - - @Override - public org.bukkit.command.CommandSender getBukkitSender(CommandListenerWrapper wrapper) { - return server.remoteConsole; - } - // CraftBukkit end - - @Override - public void sendMessage(IChatBaseComponent ichatbasecomponent) { - this.buffer.append(ichatbasecomponent.getString()); - } - - @Override - public boolean shouldSendSuccess() { - return true; - } - - @Override - public boolean shouldSendFailure() { - return true; - } - - @Override - public boolean shouldBroadcastCommands() { - return this.server.l(); - } -} diff --git a/src/main/java/net/minecraft/server/RemoteControlListener.java b/src/main/java/net/minecraft/server/RemoteControlListener.java deleted file mode 100644 index 2ce490be0..000000000 --- a/src/main/java/net/minecraft/server/RemoteControlListener.java +++ /dev/null @@ -1,116 +0,0 @@ -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 final int h; - private String i; - private ServerSocket j; - private final String k; - private Map l; - - public RemoteControlListener(IMinecraftServer iminecraftserver) { - super(iminecraftserver, "RCON Listener"); - DedicatedServerProperties dedicatedserverproperties = iminecraftserver.getDedicatedServerProperties(); - - this.h = dedicatedserverproperties.rconPort; - this.k = dedicatedserverproperties.rconPassword; - this.i = dedicatedserverproperties.rconIp; // Paper - Configurable rcon ip - if (this.i.isEmpty()) { - this.i = "0.0.0.0"; - } - - this.f(); - this.j = null; - } - - private void f() { - this.l = Maps.newHashMap(); - } - - private void g() { - Iterator iterator = this.l.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.i + ":" + this.h); - - try { - while (this.a) { - try { - Socket socket = this.j.accept(); - - socket.setSoTimeout(500); - RemoteControlSession remotecontrolsession = new RemoteControlSession(this.b, this.k, socket); - - remotecontrolsession.a(); - this.l.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.j); - } - - } - - @Override - public void a() { - if (this.k.isEmpty()) { - this.c("No rcon password set in server.properties, rcon disabled!"); - } else if (0 < this.h && 65535 >= this.h) { - if (!this.a) { - try { - this.j = new ServerSocket(this.h, 0, InetAddress.getByName(this.i)); - this.j.setSoTimeout(500); - super.a(); - } catch (IOException ioexception) { - this.c("Unable to initialise rcon on " + this.i + ":" + this.h + " : " + ioexception.getMessage()); - } - - } - } else { - this.c("Invalid rcon port " + this.h + " found in server.properties, rcon disabled!"); - } - } - - @Override - public void b() { - super.b(); - Iterator iterator = this.l.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - ((RemoteControlSession) entry.getValue()).b(); - } - - this.b(this.j); - this.f(); - } -} diff --git a/src/main/java/net/minecraft/server/RemoteStatusListener.java b/src/main/java/net/minecraft/server/RemoteStatusListener.java deleted file mode 100644 index 67e94a6f0..000000000 --- a/src/main/java/net/minecraft/server/RemoteStatusListener.java +++ /dev/null @@ -1,423 +0,0 @@ -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.nio.charset.StandardCharsets; -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 final int i; - private final int j; private int getServerPort() { return this.j; } // Paper - OBFHELPER - private final int k; private int getMaxPlayers() { return this.k; } // Paper - OBFHELPER - private final String l; private String getMotd() { return this.l; } // Paper - OBFHELPER - private final String m; private String getWorldName() { return this.m; } // Paper - OBFHELPER - private DatagramSocket n; - private final byte[] o = new byte[1460]; - private DatagramPacket p; - private final Map q; - private String r; private String getServerHost() { return this.r; } // Paper - OBFHELPER - private String s; - private final Map t; - private final long u; - private final RemoteStatusReply v; private RemoteStatusReply getCachedFullResponse() { return this.v; } // Paper - OBFHELPER - private long w; - - public RemoteStatusListener(IMinecraftServer iminecraftserver) { - super(iminecraftserver, "Query Listener"); - this.i = iminecraftserver.getDedicatedServerProperties().queryPort; - this.s = iminecraftserver.e_(); - this.j = iminecraftserver.e(); - this.l = iminecraftserver.f_(); - this.k = iminecraftserver.getMaxPlayers(); - this.m = iminecraftserver.getWorld(); - this.w = 0L; - this.r = "0.0.0.0"; - if (!this.s.isEmpty() && !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 server.properties: " + unknownhostexception.getMessage()); - } - } - - 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)) { - 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())); - /* Paper start - GS4 Query event - 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); - */ - com.destroystokyo.paper.event.server.GS4QueryEvent.QueryType queryType = - com.destroystokyo.paper.event.server.GS4QueryEvent.QueryType.BASIC; - com.destroystokyo.paper.event.server.GS4QueryEvent.QueryResponse queryResponse = com.destroystokyo.paper.event.server.GS4QueryEvent.QueryResponse.builder() - .motd(this.getMotd()) - .map(this.getWorldName()) - .currentPlayers(this.getPlayerCount()) - .maxPlayers(this.getMaxPlayers()) - .port(this.getServerPort()) - .hostname(this.getServerHost()) - .gameVersion(this.getServer().getVersion()) - .serverVersion(org.bukkit.Bukkit.getServer().getName() + " on " + org.bukkit.Bukkit.getServer().getBukkitVersion()) - .build(); - com.destroystokyo.paper.event.server.GS4QueryEvent queryEvent = - new com.destroystokyo.paper.event.server.GS4QueryEvent(queryType, datagrampacket.getAddress(), queryResponse); - queryEvent.callEvent(); - queryResponse = queryEvent.getResponse(); - remotestatusreply.writeString(queryResponse.getMotd()); - remotestatusreply.writeString("SMP"); - remotestatusreply.writeString(queryResponse.getMap()); - remotestatusreply.writeString(Integer.toString(queryResponse.getCurrentPlayers())); - remotestatusreply.writeString(Integer.toString(queryResponse.getMaxPlayers())); - remotestatusreply.writeShort((short) queryResponse.getPort()); - remotestatusreply.writeString(queryResponse.getHostname()); - // Paper end - 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 = SystemUtils.getMonotonicMillis(); - - 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); - /* Paper start - GS4 Query event - 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); - */ - // Pack plugins - java.util.List plugins = java.util.Collections.emptyList(); - org.bukkit.plugin.Plugin[] bukkitPlugins; - if(((DedicatedServer) this.getServer()).server.getQueryPlugins() && (bukkitPlugins = org.bukkit.Bukkit.getPluginManager().getPlugins()).length > 0) { - plugins = java.util.stream.Stream.of(bukkitPlugins) - .map(plugin -> com.destroystokyo.paper.event.server.GS4QueryEvent.QueryResponse.PluginInformation.of(plugin.getName(), plugin.getDescription().getVersion())) - .collect(java.util.stream.Collectors.toList()); - } - - com.destroystokyo.paper.event.server.GS4QueryEvent.QueryResponse queryResponse = com.destroystokyo.paper.event.server.GS4QueryEvent.QueryResponse.builder() - .motd(this.getMotd()) - .map(this.getWorldName()) - .currentPlayers(this.getPlayerCount()) - .maxPlayers(this.getMaxPlayers()) - .port(this.getServerPort()) - .hostname(this.getServerHost()) - .plugins(plugins) - .players(this.getServer().getPlayers()) - .gameVersion(this.getServer().getVersion()) - .serverVersion(org.bukkit.Bukkit.getServer().getName() + " on " + org.bukkit.Bukkit.getServer().getBukkitVersion()) - .build(); - com.destroystokyo.paper.event.server.GS4QueryEvent.QueryType queryType = - com.destroystokyo.paper.event.server.GS4QueryEvent.QueryType.FULL; - com.destroystokyo.paper.event.server.GS4QueryEvent queryEvent = - new com.destroystokyo.paper.event.server.GS4QueryEvent(queryType, datagrampacket.getAddress(), queryResponse); - queryEvent.callEvent(); - queryResponse = queryEvent.getResponse(); - this.getCachedFullResponse().writeString("hostname"); - this.getCachedFullResponse().writeString(queryResponse.getMotd()); - this.getCachedFullResponse().writeString("gametype"); - this.getCachedFullResponse().writeString("SMP"); - this.getCachedFullResponse().writeString("game_id"); - this.getCachedFullResponse().writeString("MINECRAFT"); - this.getCachedFullResponse().writeString("version"); - this.getCachedFullResponse().writeString(queryResponse.getGameVersion()); - this.getCachedFullResponse().writeString("plugins"); - java.lang.StringBuilder pluginsString = new java.lang.StringBuilder(); - pluginsString.append(queryResponse.getServerVersion()); - if(!queryResponse.getPlugins().isEmpty()) { - pluginsString.append(": "); - Iterator iter = queryResponse.getPlugins().iterator(); - while(iter.hasNext()) { - com.destroystokyo.paper.event.server.GS4QueryEvent.QueryResponse.PluginInformation info = iter.next(); - pluginsString.append(info.getName()); - if (info.getVersion() != null) { - pluginsString.append(' ').append(info.getVersion().replaceAll(";", ",")); - } - if (iter.hasNext()) { - pluginsString.append(';').append(' '); - } - } - } - this.getCachedFullResponse().writeString(pluginsString.toString()); - this.getCachedFullResponse().writeString("map"); - this.getCachedFullResponse().writeString(queryResponse.getMap()); - this.getCachedFullResponse().writeString("numplayers"); - this.getCachedFullResponse().writeString(Integer.toString(queryResponse.getCurrentPlayers())); - this.getCachedFullResponse().writeString("maxplayers"); - this.getCachedFullResponse().writeString(Integer.toString(queryResponse.getMaxPlayers())); - this.getCachedFullResponse().writeString("hostport"); - this.getCachedFullResponse().writeString(Integer.toString(queryResponse.getPort())); - this.getCachedFullResponse().writeString("hostip"); - this.getCachedFullResponse().writeString(queryResponse.getHostname()); - // The "meaningless data" start, copied from above - this.getCachedFullResponse().writeInt(0); - this.getCachedFullResponse().writeInt(1); - this.getCachedFullResponse().writeString("player_"); - this.getCachedFullResponse().writeInt(0); - // "Meaningless data" end - queryResponse.getPlayers().forEach(this.getCachedFullResponse()::writeStringUnchecked); - this.getCachedFullResponse().writeInt(0); - // Paper end - 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 false; - } else { - byte[] abyte = datagrampacket.getData(); - - return ((RemoteStatusListener.RemoteStatusChallenge) this.t.get(socketaddress)).a() != StatusChallengeUtils.c(abyte, 7, datagrampacket.getLength()) ? false : 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 = SystemUtils.getMonotonicMillis(); - - 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)) { - iterator.remove(); - } - } - - } - } - } - - public void run() { - this.b("Query running on " + this.s + ":" + this.i); - this.h = SystemUtils.getMonotonicMillis(); - 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(); - } - - } - - @Override - public void a() { - if (!this.a) { - if (0 < this.i && 65535 >= this.i) { - if (this.g()) { - super.a(); - } - - } else { - this.c("Invalid query port " + this.i + " found in server.properties (queries disabled)"); - } - } - } - - private void a(Exception exception) { - if (this.a) { - this.c("Unexpected exception, buggy JRE? (" + exception + ")"); - 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 final long time = (new Date()).getTime(); - private final int token; - private final byte[] identity; - private final byte[] e; - private final 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, StandardCharsets.UTF_8); - this.token = (new Random()).nextInt(16777216); - this.e = String.format("\t%s%d\u0000", this.f, this.token).getBytes(StandardCharsets.UTF_8); - } - - public Boolean a(long i) { - return this.time < i; - } - - public int a() { - return this.token; - } - - public byte[] b() { - return this.e; - } - - public byte[] c() { - return this.identity; - } - } -} diff --git a/src/main/java/net/minecraft/server/RemoteStatusReply.java b/src/main/java/net/minecraft/server/RemoteStatusReply.java deleted file mode 100644 index 73efea7e1..000000000 --- a/src/main/java/net/minecraft/server/RemoteStatusReply.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.minecraft.server; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -public class RemoteStatusReply { - - private final ByteArrayOutputStream a; - private final DataOutputStream b; - - public RemoteStatusReply(int i) { - this.a = new ByteArrayOutputStream(i); - this.b = new DataOutputStream(this.a); - } - - public void a(byte[] abyte) throws IOException { - this.b.write(abyte, 0, abyte.length); - } - - public void writeString(String string) throws IOException { this.a(string); } // Paper - OBFHELPER - public void a(String s) throws IOException { - this.b.writeBytes(s); - this.b.write(0); - } - // Paper start - unchecked exception variant to use in Stream API - public void writeStringUnchecked(String string) { - try { - writeString(string); - } catch (IOException e) { - com.destroystokyo.paper.util.SneakyThrow.sneaky(e); - } - } - // Paper end - - public void writeInt(int i) throws IOException { this.a(i); } // Paper - OBFHELPER - public void a(int i) throws IOException { - this.b.write(i); - } - - public void writeShort(short i) throws IOException { this.a(i); } // Paper - OBFHELPER - public void a(short short0) throws IOException { - this.b.writeShort(Short.reverseBytes(short0)); - } - - public byte[] a() { - return this.a.toByteArray(); - } - - public void b() { - this.a.reset(); - } -} diff --git a/src/main/java/net/minecraft/server/ScoreboardServer.java b/src/main/java/net/minecraft/server/ScoreboardServer.java deleted file mode 100644 index 929397a4c..000000000 --- a/src/main/java/net/minecraft/server/ScoreboardServer.java +++ /dev/null @@ -1,256 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import javax.annotation.Nullable; - -public class ScoreboardServer extends Scoreboard { - - private final MinecraftServer a; - private final Set b = Sets.newHashSet(); - private Runnable[] c = new Runnable[0]; - - public ScoreboardServer(MinecraftServer minecraftserver) { - this.a = minecraftserver; - } - - @Override - public void handleScoreChanged(ScoreboardScore scoreboardscore) { - super.handleScoreChanged(scoreboardscore); - if (this.b.contains(scoreboardscore.getObjective())) { - this.sendAll(new PacketPlayOutScoreboardScore(ScoreboardServer.Action.CHANGE, scoreboardscore.getObjective().getName(), scoreboardscore.getPlayerName(), scoreboardscore.getScore())); - } - - this.b(); - } - - @Override - public void handlePlayerRemoved(String s) { - super.handlePlayerRemoved(s); - this.sendAll(new PacketPlayOutScoreboardScore(ScoreboardServer.Action.REMOVE, (String) null, s, 0)); - this.b(); - } - - @Override - public void a(String s, ScoreboardObjective scoreboardobjective) { - super.a(s, scoreboardobjective); - if (this.b.contains(scoreboardobjective)) { - this.sendAll(new PacketPlayOutScoreboardScore(ScoreboardServer.Action.REMOVE, scoreboardobjective.getName(), s, 0)); - } - - this.b(); - } - - @Override - public void setDisplaySlot(int i, @Nullable 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(); - } - - @Override - public boolean addPlayerToTeam(String s, ScoreboardTeam scoreboardteam) { - if (super.addPlayerToTeam(s, scoreboardteam)) { - this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, Arrays.asList(s), 3)); - this.b(); - return true; - } else { - return false; - } - } - - @Override - public void removePlayerFromTeam(String s, ScoreboardTeam scoreboardteam) { - super.removePlayerFromTeam(s, scoreboardteam); - this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, Arrays.asList(s), 4)); - this.b(); - } - - @Override - public void handleObjectiveAdded(ScoreboardObjective scoreboardobjective) { - super.handleObjectiveAdded(scoreboardobjective); - this.b(); - } - - @Override - public void handleObjectiveChanged(ScoreboardObjective scoreboardobjective) { - super.handleObjectiveChanged(scoreboardobjective); - if (this.b.contains(scoreboardobjective)) { - this.sendAll(new PacketPlayOutScoreboardObjective(scoreboardobjective, 2)); - } - - this.b(); - } - - @Override - public void handleObjectiveRemoved(ScoreboardObjective scoreboardobjective) { - super.handleObjectiveRemoved(scoreboardobjective); - if (this.b.contains(scoreboardobjective)) { - this.g(scoreboardobjective); - } - - this.b(); - } - - @Override - public void handleTeamAdded(ScoreboardTeam scoreboardteam) { - super.handleTeamAdded(scoreboardteam); - this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, 0)); - this.b(); - } - - @Override - public void handleTeamChanged(ScoreboardTeam scoreboardteam) { - super.handleTeamChanged(scoreboardteam); - this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, 2)); - this.b(); - } - - @Override - public void handleTeamRemoved(ScoreboardTeam scoreboardteam) { - super.handleTeamRemoved(scoreboardteam); - this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, 1)); - this.b(); - } - - public void a(Runnable runnable) { - this.c = (Runnable[]) Arrays.copyOf(this.c, this.c.length + 1); - this.c[this.c.length - 1] = runnable; - } - - protected void b() { - Runnable[] arunnable = this.c; - int i = arunnable.length; - - for (int j = 0; j < i; ++j) { - Runnable runnable = arunnable[j]; - - runnable.run(); - } - - } - - public List> getScoreboardScorePacketsForObjective(ScoreboardObjective scoreboardobjective) { - List> list = Lists.newArrayList(); - - list.add(new PacketPlayOutScoreboardObjective(scoreboardobjective, 0)); - - for (int i = 0; i < 19; ++i) { - if (this.getObjectiveForSlot(i) == scoreboardobjective) { - list.add(new PacketPlayOutScoreboardDisplayObjective(i, scoreboardobjective)); - } - } - - Iterator iterator = this.getScoresForObjective(scoreboardobjective).iterator(); - - while (iterator.hasNext()) { - ScoreboardScore scoreboardscore = (ScoreboardScore) iterator.next(); - - list.add(new PacketPlayOutScoreboardScore(ScoreboardServer.Action.CHANGE, scoreboardscore.getObjective().getName(), scoreboardscore.getPlayerName(), scoreboardscore.getScore())); - } - - return list; - } - - public void e(ScoreboardObjective scoreboardobjective) { - List> list = this.getScoreboardScorePacketsForObjective(scoreboardobjective); - Iterator iterator = this.a.getPlayerList().getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - if (entityplayer.getBukkitEntity().getScoreboard().getHandle() != this) continue; // CraftBukkit - Only players on this board - Iterator iterator1 = list.iterator(); - - while (iterator1.hasNext()) { - Packet packet = (Packet) iterator1.next(); - - entityplayer.playerConnection.sendPacket(packet); - } - } - - this.b.add(scoreboardobjective); - } - - public List> f(ScoreboardObjective scoreboardobjective) { - List> list = Lists.newArrayList(); - - list.add(new PacketPlayOutScoreboardObjective(scoreboardobjective, 1)); - - for (int i = 0; i < 19; ++i) { - if (this.getObjectiveForSlot(i) == scoreboardobjective) { - list.add(new PacketPlayOutScoreboardDisplayObjective(i, scoreboardobjective)); - } - } - - return list; - } - - public void g(ScoreboardObjective scoreboardobjective) { - List> list = this.f(scoreboardobjective); - Iterator iterator = this.a.getPlayerList().getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - if (entityplayer.getBukkitEntity().getScoreboard().getHandle() != this) continue; // CraftBukkit - Only players on this board - Iterator iterator1 = list.iterator(); - - while (iterator1.hasNext()) { - Packet packet = (Packet) iterator1.next(); - - 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) { - for (EntityPlayer entityplayer : (List) this.a.getPlayerList().players) { - if (entityplayer.getBukkitEntity().getScoreboard().getHandle() == this) { - entityplayer.playerConnection.sendPacket(packet); - } - } - } - // CraftBukkit end - - public static enum Action { - - CHANGE, REMOVE; - - private Action() {} - } -} diff --git a/src/main/java/net/minecraft/server/SecondaryWorldServer.java b/src/main/java/net/minecraft/server/SecondaryWorldServer.java deleted file mode 100644 index e167b588e..000000000 --- a/src/main/java/net/minecraft/server/SecondaryWorldServer.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.minecraft.server; - -import java.util.concurrent.Executor; - -public class SecondaryWorldServer extends WorldServer { - - // CraftBukkit start - Add WorldData, Environment and ChunkGenerator arguments - public SecondaryWorldServer(WorldServer worldserver, MinecraftServer minecraftserver, Executor executor, WorldNBTStorage worldnbtstorage, DimensionManager dimensionmanager, GameProfilerFiller gameprofilerfiller, WorldLoadListener worldloadlistener, WorldData worldData, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen) { - super(minecraftserver, executor, worldnbtstorage, worldData, dimensionmanager, gameprofilerfiller, worldloadlistener, env, gen); - // worldserver.getWorldBorder().a((IWorldBorderListener) (new IWorldBorderListener.a(this.getWorldBorder()))); - // CraftBukkit end - } - - // @Override // CraftBukkit - // protected void a() {} // CraftBukkit -} diff --git a/src/main/java/net/minecraft/server/ServerConnection.java b/src/main/java/net/minecraft/server/ServerConnection.java deleted file mode 100644 index 379c79272..000000000 --- a/src/main/java/net/minecraft/server/ServerConnection.java +++ /dev/null @@ -1,174 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelException; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.epoll.Epoll; -import io.netty.channel.epoll.EpollEventLoopGroup; -import io.netty.channel.epoll.EpollServerSocketChannel; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.ServerSocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.timeout.ReadTimeoutHandler; -import io.netty.util.concurrent.Future; -import java.io.IOException; -import java.net.InetAddress; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class ServerConnection { - - private static final Logger LOGGER = LogManager.getLogger(); - public static final LazyInitVar a = new LazyInitVar<>(() -> { - return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Server IO #%d").setDaemon(true).build()); - }); - public static final LazyInitVar b = new LazyInitVar<>(() -> { - return new EpollEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Epoll Server IO #%d").setDaemon(true).build()); - }); - private final MinecraftServer e; - public volatile boolean c; - private final List f = Collections.synchronizedList(Lists.newArrayList()); - private final List g = Collections.synchronizedList(Lists.newArrayList()); - // Paper start - prevent blocking on adding a new network manager while the server is ticking - private final List pending = Collections.synchronizedList(Lists.newArrayList()); - private void addPending() { - synchronized (pending) { - this.g.addAll(pending); // Paper - OBFHELPER - List of network managers - pending.clear(); - } - } - // Paper end - - public ServerConnection(MinecraftServer minecraftserver) { - this.e = minecraftserver; - this.c = true; - } - - public void a(@Nullable InetAddress inetaddress, int i) throws IOException { - List list = this.f; - - synchronized (this.f) { - Class oclass; - LazyInitVar lazyinitvar; - - if (Epoll.isAvailable() && this.e.X()) { - oclass = EpollServerSocketChannel.class; - lazyinitvar = ServerConnection.b; - ServerConnection.LOGGER.info("Using epoll channel type"); - } else { - oclass = NioServerSocketChannel.class; - lazyinitvar = ServerConnection.a; - ServerConnection.LOGGER.info("Using default channel type"); - } - - this.f.add(((ServerBootstrap) ((ServerBootstrap) (new ServerBootstrap()).channel(oclass)).childHandler(new ChannelInitializer() { - protected void initChannel(Channel channel) throws Exception { - try { - channel.config().setOption(ChannelOption.TCP_NODELAY, true); - } catch (ChannelException channelexception) { - ; - } - - channel.pipeline().addLast("timeout", new ReadTimeoutHandler(30)).addLast("legacy_query", new LegacyPingHandler(ServerConnection.this)).addLast("splitter", new PacketSplitter()).addLast("decoder", new PacketDecoder(EnumProtocolDirection.SERVERBOUND)).addLast("prepender", new PacketPrepender()).addLast("encoder", new PacketEncoder(EnumProtocolDirection.CLIENTBOUND)); - NetworkManager networkmanager = new NetworkManager(EnumProtocolDirection.SERVERBOUND); - - pending.add(networkmanager); // Paper - channel.pipeline().addLast("packet_handler", networkmanager); - networkmanager.setPacketListener(new HandshakeListener(ServerConnection.this.e, networkmanager)); - } - }).group((EventLoopGroup) lazyinitvar.a()).localAddress(inetaddress, i)).option(ChannelOption.AUTO_READ, false).bind().syncUninterruptibly()); // CraftBukkit - } - } - - // CraftBukkit start - public void acceptConnections() { - synchronized (this.f) { // PAIL: listeningChannels - for (ChannelFuture f : this.f) { - f.channel().config().setAutoRead(true); - } - } - } - // CraftBukkit end - - public void b() { - this.c = false; - Iterator iterator = this.f.iterator(); - - while (iterator.hasNext()) { - ChannelFuture channelfuture = (ChannelFuture) iterator.next(); - - try { - channelfuture.channel().close().sync(); - } catch (InterruptedException interruptedexception) { - ServerConnection.LOGGER.error("Interrupted whilst closing channel"); - } - } - - } - - public void c() { - List list = this.g; - - synchronized (this.g) { - // Spigot Start - addPending(); // Paper - // This prevents players from 'gaming' the server, and strategically relogging to increase their position in the tick order - if ( org.spigotmc.SpigotConfig.playerShuffle > 0 && MinecraftServer.currentTick % org.spigotmc.SpigotConfig.playerShuffle == 0 ) - { - Collections.shuffle( this.g ); - } - // Spigot End - Iterator iterator = this.g.iterator(); - - while (iterator.hasNext()) { - NetworkManager networkmanager = (NetworkManager) iterator.next(); - - if (!networkmanager.h()) { - if (networkmanager.isConnected()) { - try { - networkmanager.a(); - } catch (Exception exception) { - if (networkmanager.isLocal()) { - CrashReport crashreport = CrashReport.a(exception, "Ticking memory connection"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Ticking connection"); - - crashreportsystemdetails.a("Connection", networkmanager::toString); - throw new ReportedException(crashreport); - } - - ServerConnection.LOGGER.warn("Failed to handle packet for {}", networkmanager.getSocketAddress(), exception); - ChatComponentText chatcomponenttext = new ChatComponentText("Internal server error"); - - networkmanager.sendPacket(new PacketPlayOutKickDisconnect(chatcomponenttext), (future) -> { - networkmanager.close(chatcomponenttext); - }); - networkmanager.stopReading(); - } - } else { - // Spigot Start - // Fix a race condition where a NetworkManager could be unregistered just before connection. - if (networkmanager.preparing) continue; - // Spigot End - iterator.remove(); - networkmanager.handleDisconnection(); - } - } - } - - } - } - - public MinecraftServer d() { - return this.e; - } -} diff --git a/src/main/java/net/minecraft/server/ServerPing.java b/src/main/java/net/minecraft/server/ServerPing.java deleted file mode 100644 index ea52e89bd..000000000 --- a/src/main/java/net/minecraft/server/ServerPing.java +++ /dev/null @@ -1,226 +0,0 @@ -package net.minecraft.server; - -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.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.mojang.authlib.GameProfile; -import java.lang.reflect.Type; -import java.util.UUID; - -public class ServerPing { - - private IChatBaseComponent a; - private ServerPing.ServerPingPlayerSample b; - private ServerPing.ServerData c; - private String d; - - public ServerPing() {} - - public IChatBaseComponent a() { - return this.a; - } - - public void setMOTD(IChatBaseComponent ichatbasecomponent) { - this.a = ichatbasecomponent; - } - - public ServerPingPlayerSample getPlayers() { return b(); } // Paper - OBFHELPER - public ServerPing.ServerPingPlayerSample b() { - return this.b; - } - - public void setPlayerSample(ServerPing.ServerPingPlayerSample serverping_serverpingplayersample) { - this.b = serverping_serverpingplayersample; - } - - public ServerPing.ServerData getServerData() { - return this.c; - } - - public void setServerInfo(ServerPing.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 deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { - JsonObject jsonobject = ChatDeserializer.m(jsonelement, "status"); - ServerPing serverping = new ServerPing(); - - if (jsonobject.has("description")) { - serverping.setMOTD((IChatBaseComponent) jsondeserializationcontext.deserialize(jsonobject.get("description"), IChatBaseComponent.class)); - } - - if (jsonobject.has("players")) { - serverping.setPlayerSample((ServerPing.ServerPingPlayerSample) jsondeserializationcontext.deserialize(jsonobject.get("players"), ServerPing.ServerPingPlayerSample.class)); - } - - if (jsonobject.has("version")) { - serverping.setServerInfo((ServerPing.ServerData) jsondeserializationcontext.deserialize(jsonobject.get("version"), ServerPing.ServerData.class)); - } - - if (jsonobject.has("favicon")) { - serverping.setFavicon(ChatDeserializer.h(jsonobject, "favicon")); - } - - return serverping; - } - - public JsonElement serialize(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.getServerData() != null) { - jsonobject.add("version", jsonserializationcontext.serialize(serverping.getServerData())); - } - - if (serverping.d() != null) { - jsonobject.addProperty("favicon", serverping.d()); - } - - return jsonobject; - } - } - - 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 getProtocolVersion() { - return this.b; - } - - public static class Serializer implements JsonDeserializer, JsonSerializer { - - public Serializer() {} - - public ServerPing.ServerData deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { - JsonObject jsonobject = ChatDeserializer.m(jsonelement, "version"); - - return new ServerPing.ServerData(ChatDeserializer.h(jsonobject, "name"), ChatDeserializer.n(jsonobject, "protocol")); - } - - public JsonElement serialize(ServerPing.ServerData serverping_serverdata, Type type, JsonSerializationContext jsonserializationcontext) { - JsonObject jsonobject = new JsonObject(); - - jsonobject.addProperty("name", serverping_serverdata.a()); - jsonobject.addProperty("protocol", serverping_serverdata.getProtocolVersion()); - return jsonobject; - } - } - } - - 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[] getSample() { return c(); } // Paper - OBFHELPER - public GameProfile[] c() { - return this.c; - } - - public void setSample(GameProfile[] sample) { a(sample); } // Paper - OBFHELPER - public void a(GameProfile[] agameprofile) { - this.c = agameprofile; - } - - public static class Serializer implements JsonDeserializer, JsonSerializer { - - public Serializer() {} - - public ServerPing.ServerPingPlayerSample deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { - JsonObject jsonobject = ChatDeserializer.m(jsonelement, "players"); - ServerPing.ServerPingPlayerSample serverping_serverpingplayersample = new ServerPing.ServerPingPlayerSample(ChatDeserializer.n(jsonobject, "max"), ChatDeserializer.n(jsonobject, "online")); - - if (ChatDeserializer.d(jsonobject, "sample")) { - JsonArray jsonarray = ChatDeserializer.u(jsonobject, "sample"); - - if (jsonarray.size() > 0) { - GameProfile[] agameprofile = new GameProfile[jsonarray.size()]; - - for (int i = 0; i < agameprofile.length; ++i) { - JsonObject jsonobject1 = ChatDeserializer.m(jsonarray.get(i), "player[" + i + "]"); - String s = ChatDeserializer.h(jsonobject1, "id"); - - agameprofile[i] = new GameProfile(UUID.fromString(s), ChatDeserializer.h(jsonobject1, "name")); - } - - serverping_serverpingplayersample.a(agameprofile); - } - } - - return serverping_serverpingplayersample; - } - - public JsonElement serialize(ServerPing.ServerPingPlayerSample serverping_serverpingplayersample, Type type, JsonSerializationContext jsonserializationcontext) { - JsonObject jsonobject = new JsonObject(); - - jsonobject.addProperty("max", serverping_serverpingplayersample.a()); - jsonobject.addProperty("online", serverping_serverpingplayersample.b()); - if (serverping_serverpingplayersample.c() != null && serverping_serverpingplayersample.c().length > 0) { - JsonArray jsonarray = new JsonArray(); - - for (int i = 0; i < serverping_serverpingplayersample.c().length; ++i) { - JsonObject jsonobject1 = new JsonObject(); - UUID uuid = serverping_serverpingplayersample.c()[i].getId(); - - jsonobject1.addProperty("id", uuid == null ? "" : uuid.toString()); - jsonobject1.addProperty("name", serverping_serverpingplayersample.c()[i].getName()); - jsonarray.add(jsonobject1); - } - - jsonobject.add("sample", jsonarray); - } - - return jsonobject; - } - } - } -} diff --git a/src/main/java/net/minecraft/server/ServerStatisticManager.java b/src/main/java/net/minecraft/server/ServerStatisticManager.java deleted file mode 100644 index 1e911a889..000000000 --- a/src/main/java/net/minecraft/server/ServerStatisticManager.java +++ /dev/null @@ -1,243 +0,0 @@ -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.JsonPrimitive; -import com.google.gson.internal.Streams; -import com.google.gson.stream.JsonReader; -import com.mojang.datafixers.DataFixer; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.util.Iterator; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.Map.Entry; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class ServerStatisticManager extends StatisticManager { - - private static final Logger LOGGER = LogManager.getLogger(); - private final MinecraftServer c; - private final File d; - private final Set> e = Sets.newHashSet(); - private int f = -300; - - public ServerStatisticManager(MinecraftServer minecraftserver, File file) { - this.c = minecraftserver; - this.d = file; - // Spigot start - for ( Map.Entry entry : org.spigotmc.SpigotConfig.forcedStats.entrySet() ) - { - Statistic wrapper = StatisticList.CUSTOM.b( entry.getKey() ); - this.a.put( wrapper, entry.getValue().intValue() ); - } - // Spigot end - if (file.isFile()) { - try { - this.a(minecraftserver.aB(), org.apache.commons.io.FileUtils.readFileToString(file)); - } catch (IOException ioexception) { - ServerStatisticManager.LOGGER.error("Couldn't read statistics file {}", file, ioexception); - } catch (JsonParseException jsonparseexception) { - ServerStatisticManager.LOGGER.error("Couldn't parse statistics file {}", file, jsonparseexception); - } - } - - } - - public void a() { - if ( org.spigotmc.SpigotConfig.disableStatSaving ) return; // Spigot - try { - org.apache.commons.io.FileUtils.writeStringToFile(this.d, this.b()); - } catch (IOException ioexception) { - ServerStatisticManager.LOGGER.error("Couldn't save stats", ioexception); - } - - } - - @Override - public void setStatistic(EntityHuman entityhuman, Statistic statistic, int i) { - if ( org.spigotmc.SpigotConfig.disableStatSaving ) return; // Spigot - super.setStatistic(entityhuman, statistic, i); - this.e.add(statistic); - } - - private Set> d() { - Set> set = Sets.newHashSet(this.e); - - this.e.clear(); - return set; - } - - public void a(DataFixer datafixer, String s) { - try { - JsonReader jsonreader = new JsonReader(new StringReader(s)); - Throwable throwable = null; - - try { - jsonreader.setLenient(false); - JsonElement jsonelement = Streams.parse(jsonreader); - - if (!jsonelement.isJsonNull()) { - NBTTagCompound nbttagcompound = a(jsonelement.getAsJsonObject()); - - if (!nbttagcompound.hasKeyOfType("DataVersion", 99)) { - nbttagcompound.setInt("DataVersion", 1343); - } - - nbttagcompound = GameProfileSerializer.a(datafixer, DataFixTypes.STATS, nbttagcompound, nbttagcompound.getInt("DataVersion")); - if (nbttagcompound.hasKeyOfType("stats", 10)) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("stats"); - Iterator iterator = nbttagcompound1.getKeys().iterator(); - - while (iterator.hasNext()) { - String s1 = (String) iterator.next(); - - if (nbttagcompound1.hasKeyOfType(s1, 10)) { - SystemUtils.a(IRegistry.STATS.getOptional(new MinecraftKey(s1)), (statisticwrapper) -> { - NBTTagCompound nbttagcompound2 = nbttagcompound1.getCompound(s1); - Iterator iterator1 = nbttagcompound2.getKeys().iterator(); - - while (iterator1.hasNext()) { - String s2 = (String) iterator1.next(); - - if (nbttagcompound2.hasKeyOfType(s2, 99)) { - SystemUtils.a(this.a(statisticwrapper, s2), (statistic) -> { - this.a.put(statistic, nbttagcompound2.getInt(s2)); - }, () -> { - ServerStatisticManager.LOGGER.warn("Invalid statistic in {}: Don't know what {} is", this.d, s2); - }); - } else { - ServerStatisticManager.LOGGER.warn("Invalid statistic value in {}: Don't know what {} is for key {}", this.d, nbttagcompound2.get(s2), s2); - } - } - - }, () -> { - ServerStatisticManager.LOGGER.warn("Invalid statistic type in {}: Don't know what {} is", this.d, s1); - }); - } - } - } - - return; - } - - ServerStatisticManager.LOGGER.error("Unable to parse Stat data from {}", this.d); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (jsonreader != null) { - if (throwable != null) { - try { - jsonreader.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - jsonreader.close(); - } - } - - } - - } catch (IOException | JsonParseException jsonparseexception) { - ServerStatisticManager.LOGGER.error("Unable to parse Stat data from {}", this.d, jsonparseexception); - } - } - - private Optional> a(StatisticWrapper statisticwrapper, String s) { - Optional optional = Optional.ofNullable(MinecraftKey.a(s)); - IRegistry iregistry = statisticwrapper.getRegistry(); - - iregistry.getClass(); - Optional optional2 = optional.flatMap(iregistry::getOptional); - statisticwrapper.getClass(); - return optional2.map(statisticwrapper::b); - } - - private static NBTTagCompound a(JsonObject jsonobject) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - Iterator iterator = jsonobject.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - JsonElement jsonelement = (JsonElement) entry.getValue(); - - if (jsonelement.isJsonObject()) { - nbttagcompound.set((String) entry.getKey(), a(jsonelement.getAsJsonObject())); - } else if (jsonelement.isJsonPrimitive()) { - JsonPrimitive jsonprimitive = jsonelement.getAsJsonPrimitive(); - - if (jsonprimitive.isNumber()) { - nbttagcompound.setInt((String) entry.getKey(), jsonprimitive.getAsInt()); - } - } - } - - return nbttagcompound; - } - - protected String b() { - Map, JsonObject> map = Maps.newHashMap(); - ObjectIterator objectiterator = this.a.object2IntEntrySet().iterator(); - - while (objectiterator.hasNext()) { - it.unimi.dsi.fastutil.objects.Object2IntMap.Entry> it_unimi_dsi_fastutil_objects_object2intmap_entry = (it.unimi.dsi.fastutil.objects.Object2IntMap.Entry) objectiterator.next(); - Statistic statistic = (Statistic) it_unimi_dsi_fastutil_objects_object2intmap_entry.getKey(); - - ((JsonObject) map.computeIfAbsent(statistic.getWrapper(), (statisticwrapper) -> { - return new JsonObject(); - })).addProperty(b(statistic).toString(), it_unimi_dsi_fastutil_objects_object2intmap_entry.getIntValue()); - } - - JsonObject jsonobject = new JsonObject(); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry, JsonObject> entry = (Entry) iterator.next(); - - jsonobject.add(IRegistry.STATS.getKey(entry.getKey()).toString(), (JsonElement) entry.getValue()); - } - - JsonObject jsonobject1 = new JsonObject(); - - jsonobject1.add("stats", jsonobject); - jsonobject1.addProperty("DataVersion", SharedConstants.a().getWorldVersion()); - return jsonobject1.toString(); - } - - private static MinecraftKey b(Statistic statistic) { - return statistic.getWrapper().getRegistry().getKey(statistic.b()); - } - - public void c() { - this.e.addAll(this.a.keySet()); - } - - public void a(EntityPlayer entityplayer) { - int i = this.c.aj(); - Object2IntMap> object2intmap = new Object2IntOpenHashMap(); - - if (i - this.f > 300) { - this.f = i; - Iterator iterator = this.d().iterator(); - - while (iterator.hasNext()) { - Statistic statistic = (Statistic) iterator.next(); - - object2intmap.put(statistic, this.getStatisticValue(statistic)); - } - } - - entityplayer.playerConnection.sendPacket(new PacketPlayOutStatistic(object2intmap)); - } -} diff --git a/src/main/java/net/minecraft/server/ShapedRecipes.java b/src/main/java/net/minecraft/server/ShapedRecipes.java deleted file mode 100644 index 5942e89f9..000000000 --- a/src/main/java/net/minecraft/server/ShapedRecipes.java +++ /dev/null @@ -1,371 +0,0 @@ -package net.minecraft.server; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; -// CraftBukkit start -import java.util.ArrayList; -import java.util.List; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftRecipe; -import org.bukkit.craftbukkit.inventory.CraftShapedRecipe; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.RecipeChoice; -// CraftBukkit end - -public class ShapedRecipes implements RecipeCrafting { - - private final int width; - private final int height; - private final NonNullList items; - private final ItemStack result; - private final MinecraftKey key; - private final String group; - - public ShapedRecipes(MinecraftKey minecraftkey, String s, int i, int j, NonNullList nonnulllist, ItemStack itemstack) { - this.key = minecraftkey; - this.group = s; - this.width = i; - this.height = j; - this.items = nonnulllist; - this.result = itemstack; - } - - // CraftBukkit start - public org.bukkit.inventory.ShapedRecipe toBukkitRecipe() { - CraftItemStack result = CraftItemStack.asCraftMirror(this.result); - CraftShapedRecipe recipe = new CraftShapedRecipe(result, this); - recipe.setGroup(this.group); - - 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 (RecipeItemStack list : this.items) { - RecipeChoice choice = CraftRecipe.toBukkit(list); - if (choice != null) { - recipe.setIngredient(c, choice); - } - - c++; - } - return recipe; - } - // CraftBukkit end - - @Override - public MinecraftKey getKey() { - return this.key; - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.a; - } - - @Override - public ItemStack c() { - return this.result; - } - - @Override - public NonNullList a() { - return this.items; - } - - public boolean a(InventoryCrafting inventorycrafting, World world) { - for (int i = 0; i <= inventorycrafting.g() - this.width; ++i) { - for (int j = 0; j <= inventorycrafting.f() - 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 < inventorycrafting.g(); ++k) { - for (int l = 0; l < inventorycrafting.f(); ++l) { - int i1 = k - i; - int j1 = l - j; - RecipeItemStack recipeitemstack = RecipeItemStack.a; - - if (i1 >= 0 && j1 >= 0 && i1 < this.width && j1 < this.height) { - if (flag) { - recipeitemstack = (RecipeItemStack) this.items.get(this.width - i1 - 1 + j1 * this.width); - } else { - recipeitemstack = (RecipeItemStack) this.items.get(i1 + j1 * this.width); - } - } - - if (!recipeitemstack.test(inventorycrafting.getItem(k + l * inventorycrafting.g()))) { - return false; - } - } - } - - return true; - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - return this.c().cloneItemStack(); - } - - public int i() { - return this.width; - } - - public int j() { - return this.height; - } - - private static NonNullList b(String[] astring, Map map, int i, int j) { - NonNullList nonnulllist = NonNullList.a(i * j, RecipeItemStack.a); - Set set = Sets.newHashSet(map.keySet()); - - set.remove(" "); - - for (int k = 0; k < astring.length; ++k) { - for (int l = 0; l < astring[k].length(); ++l) { - String s = astring[k].substring(l, l + 1); - RecipeItemStack recipeitemstack = (RecipeItemStack) map.get(s); - - if (recipeitemstack == null) { - throw new JsonSyntaxException("Pattern references symbol '" + s + "' but it's not defined in the key"); - } - - set.remove(s); - nonnulllist.set(l + i * k, recipeitemstack); - } - } - - if (!set.isEmpty()) { - throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + set); - } else { - return nonnulllist; - } - } - - @VisibleForTesting - static String[] a(String... astring) { - int i = Integer.MAX_VALUE; - int j = 0; - int k = 0; - int l = 0; - - for (int i1 = 0; i1 < astring.length; ++i1) { - String s = astring[i1]; - - i = Math.min(i, a(s)); - int j1 = b(s); - - j = Math.max(j, j1); - if (j1 < 0) { - if (k == i1) { - ++k; - } - - ++l; - } else { - l = 0; - } - } - - if (astring.length == l) { - return new String[0]; - } else { - String[] astring1 = new String[astring.length - l - k]; - - for (int k1 = 0; k1 < astring1.length; ++k1) { - astring1[k1] = astring[k1 + k].substring(i, j + 1); - } - - return astring1; - } - } - - private static int a(String s) { - int i; - - for (i = 0; i < s.length() && s.charAt(i) == ' '; ++i) { - ; - } - - return i; - } - - private static int b(String s) { - int i; - - for (i = s.length() - 1; i >= 0 && s.charAt(i) == ' '; --i) { - ; - } - - return i; - } - - private static String[] b(JsonArray jsonarray) { - String[] astring = new String[jsonarray.size()]; - - if (astring.length > 3) { - throw new JsonSyntaxException("Invalid pattern: too many rows, 3 is maximum"); - } else if (astring.length == 0) { - throw new JsonSyntaxException("Invalid pattern: empty pattern not allowed"); - } else { - for (int i = 0; i < astring.length; ++i) { - String s = ChatDeserializer.a(jsonarray.get(i), "pattern[" + i + "]"); - - if (s.length() > 3) { - throw new JsonSyntaxException("Invalid pattern: too many columns, 3 is maximum"); - } - - if (i > 0 && astring[0].length() != s.length()) { - throw new JsonSyntaxException("Invalid pattern: each row must be the same width"); - } - - astring[i] = s; - } - - return astring; - } - } - - private static Map c(JsonObject jsonobject) { - Map map = Maps.newHashMap(); - Iterator iterator = jsonobject.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - if (((String) entry.getKey()).length() != 1) { - throw new JsonSyntaxException("Invalid key entry: '" + (String) entry.getKey() + "' is an invalid symbol (must be 1 character only)."); - } - - if (" ".equals(entry.getKey())) { - throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); - } - - map.put(entry.getKey(), RecipeItemStack.a((JsonElement) entry.getValue())); - } - - map.put(" ", RecipeItemStack.a); - return map; - } - - public static ItemStack a(JsonObject jsonobject) { - String s = ChatDeserializer.h(jsonobject, "item"); - Item item = (Item) IRegistry.ITEM.getOptional(new MinecraftKey(s)).orElseThrow(() -> { - return new JsonSyntaxException("Unknown item '" + s + "'"); - }); - - if (jsonobject.has("data")) { - throw new JsonParseException("Disallowed data tag found"); - } else { - int i = ChatDeserializer.a(jsonobject, "count", (int) 1); - - return new ItemStack(item, i); - } - } - - public static class a implements RecipeSerializer { - - public a() {} - - @Override - public ShapedRecipes a(MinecraftKey minecraftkey, JsonObject jsonobject) { - String s = ChatDeserializer.a(jsonobject, "group", ""); - Map map = ShapedRecipes.c(ChatDeserializer.t(jsonobject, "key")); - String[] astring = ShapedRecipes.a(ShapedRecipes.b(ChatDeserializer.u(jsonobject, "pattern"))); - int i = astring[0].length(); - int j = astring.length; - NonNullList nonnulllist = ShapedRecipes.b(astring, map, i, j); - ItemStack itemstack = ShapedRecipes.a(ChatDeserializer.t(jsonobject, "result")); - - return new ShapedRecipes(minecraftkey, s, i, j, nonnulllist, itemstack); - } - - @Override - public ShapedRecipes a(MinecraftKey minecraftkey, PacketDataSerializer packetdataserializer) { - int i = packetdataserializer.i(); - int j = packetdataserializer.i(); - String s = packetdataserializer.e(32767); - NonNullList nonnulllist = NonNullList.a(i * j, RecipeItemStack.a); - - for (int k = 0; k < nonnulllist.size(); ++k) { - nonnulllist.set(k, RecipeItemStack.b(packetdataserializer)); - } - - ItemStack itemstack = packetdataserializer.m(); - - return new ShapedRecipes(minecraftkey, s, i, j, nonnulllist, itemstack); - } - - public void a(PacketDataSerializer packetdataserializer, ShapedRecipes shapedrecipes) { - packetdataserializer.d(shapedrecipes.width); - packetdataserializer.d(shapedrecipes.height); - packetdataserializer.a(shapedrecipes.group); - Iterator iterator = shapedrecipes.items.iterator(); - - while (iterator.hasNext()) { - RecipeItemStack recipeitemstack = (RecipeItemStack) iterator.next(); - - recipeitemstack.a(packetdataserializer); - } - - packetdataserializer.a(shapedrecipes.result); - } - } -} diff --git a/src/main/java/net/minecraft/server/ShapelessRecipes.java b/src/main/java/net/minecraft/server/ShapelessRecipes.java deleted file mode 100644 index 691e697d6..000000000 --- a/src/main/java/net/minecraft/server/ShapelessRecipes.java +++ /dev/null @@ -1,175 +0,0 @@ -package net.minecraft.server; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import it.unimi.dsi.fastutil.ints.IntList; -import java.util.Iterator; -// CraftBukkit start -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftRecipe; -import org.bukkit.craftbukkit.inventory.CraftShapelessRecipe; -// CraftBukkit end - -public class ShapelessRecipes implements RecipeCrafting { - - private final MinecraftKey key; - private final String group; - private final ItemStack result; - private final NonNullList ingredients; - - public ShapelessRecipes(MinecraftKey minecraftkey, String s, ItemStack itemstack, NonNullList nonnulllist) { - this.key = minecraftkey; - this.group = s; - this.result = itemstack; - this.ingredients = nonnulllist; - } - - // CraftBukkit start - @SuppressWarnings("unchecked") - public org.bukkit.inventory.ShapelessRecipe toBukkitRecipe() { - CraftItemStack result = CraftItemStack.asCraftMirror(this.result); - CraftShapelessRecipe recipe = new CraftShapelessRecipe(result, this); - recipe.setGroup(this.group); - - for (RecipeItemStack list : this.ingredients) { - recipe.addIngredient(CraftRecipe.toBukkit(list)); - } - return recipe; - } - // CraftBukkit end - - @Override - public MinecraftKey getKey() { - return this.key; - } - - @Override - public RecipeSerializer getRecipeSerializer() { - return RecipeSerializer.b; - } - - @Override - public ItemStack c() { - return this.result; - } - - @Override - public NonNullList a() { - return this.ingredients; - } - - public boolean a(InventoryCrafting inventorycrafting, World world) { - AutoRecipeStackManager autorecipestackmanager = new AutoRecipeStackManager(); - int i = 0; - - // Paper start - java.util.List providedItems = new java.util.ArrayList<>(); - co.aikar.util.Counter matchedProvided = new co.aikar.util.Counter<>(); - co.aikar.util.Counter matchedIngredients = new co.aikar.util.Counter<>(); - // Paper end - for (int j = 0; j < inventorycrafting.getSize(); ++j) { - ItemStack itemstack = inventorycrafting.getItem(j); - - if (!itemstack.isEmpty()) { - // Paper start - itemstack = itemstack.cloneItemStack(); - providedItems.add(itemstack); - for (RecipeItemStack ingredient : ingredients) { - if (ingredient.test(itemstack)) { - matchedProvided.increment(itemstack); - matchedIngredients.increment(ingredient); - } - } - // Paper end - } - } - - // Paper start - java.util.List ingredients = new java.util.ArrayList<>(this.ingredients); - providedItems.sort(java.util.Comparator.comparingInt((ItemStack c) -> (int) matchedProvided.getCount(c)).reversed()); - ingredients.sort(java.util.Comparator.comparingInt((RecipeItemStack c) -> (int) matchedIngredients.getCount(c))); - - PROVIDED: - for (ItemStack provided : providedItems) { - for (Iterator itIngredient = ingredients.iterator(); itIngredient.hasNext(); ) { - RecipeItemStack ingredient = itIngredient.next(); - if (ingredient.test(provided)) { - itIngredient.remove(); - continue PROVIDED; - } - } - return false; - } - return ingredients.isEmpty(); - // Paper end - } - - public ItemStack a(InventoryCrafting inventorycrafting) { - return this.result.cloneItemStack(); - } - - public static class a implements RecipeSerializer { - - public a() {} - - @Override - public ShapelessRecipes a(MinecraftKey minecraftkey, JsonObject jsonobject) { - String s = ChatDeserializer.a(jsonobject, "group", ""); - NonNullList nonnulllist = a(ChatDeserializer.u(jsonobject, "ingredients")); - - if (nonnulllist.isEmpty()) { - throw new JsonParseException("No ingredients for shapeless recipe"); - } else if (nonnulllist.size() > 9) { - throw new JsonParseException("Too many ingredients for shapeless recipe"); - } else { - ItemStack itemstack = ShapedRecipes.a(ChatDeserializer.t(jsonobject, "result")); - - return new ShapelessRecipes(minecraftkey, s, itemstack, nonnulllist); - } - } - - private static NonNullList a(JsonArray jsonarray) { - NonNullList nonnulllist = NonNullList.a(); - - for (int i = 0; i < jsonarray.size(); ++i) { - RecipeItemStack recipeitemstack = RecipeItemStack.a(jsonarray.get(i)); - - if (!recipeitemstack.d()) { - nonnulllist.add(recipeitemstack); - } - } - - return nonnulllist; - } - - @Override - public ShapelessRecipes a(MinecraftKey minecraftkey, PacketDataSerializer packetdataserializer) { - String s = packetdataserializer.e(32767); - int i = packetdataserializer.i(); - NonNullList nonnulllist = NonNullList.a(i, RecipeItemStack.a); - - for (int j = 0; j < nonnulllist.size(); ++j) { - nonnulllist.set(j, RecipeItemStack.b(packetdataserializer)); - } - - ItemStack itemstack = packetdataserializer.m(); - - return new ShapelessRecipes(minecraftkey, s, itemstack, nonnulllist); - } - - public void a(PacketDataSerializer packetdataserializer, ShapelessRecipes shapelessrecipes) { - packetdataserializer.a(shapelessrecipes.group); - packetdataserializer.d(shapelessrecipes.ingredients.size()); - Iterator iterator = shapelessrecipes.ingredients.iterator(); - - while (iterator.hasNext()) { - RecipeItemStack recipeitemstack = (RecipeItemStack) iterator.next(); - - recipeitemstack.a(packetdataserializer); - } - - packetdataserializer.a(shapelessrecipes.result); - } - } -} diff --git a/src/main/java/net/minecraft/server/SlotFurnaceResult.java b/src/main/java/net/minecraft/server/SlotFurnaceResult.java deleted file mode 100644 index edc4a5c34..000000000 --- a/src/main/java/net/minecraft/server/SlotFurnaceResult.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.minecraft.server; - -public class SlotFurnaceResult extends Slot { - - private final EntityHuman a; public final EntityHuman getPlayer() { return this.a; } // Paper OBFHELPER - private int b; - - public SlotFurnaceResult(EntityHuman entityhuman, IInventory iinventory, int i, int j, int k) { - super(iinventory, i, j, k); - this.a = entityhuman; - } - - @Override - public boolean isAllowed(ItemStack itemstack) { - return false; - } - - @Override - public ItemStack a(int i) { - if (this.hasItem()) { - this.b += Math.min(i, this.getItem().getCount()); - } - - return super.a(i); - } - - @Override - public ItemStack a(EntityHuman entityhuman, ItemStack itemstack) { - this.c(itemstack); - super.a(entityhuman, itemstack); - return itemstack; - } - - @Override - protected void a(ItemStack itemstack, int i) { - this.b += i; - this.c(itemstack); - } - - @Override - protected void c(ItemStack itemstack) { - itemstack.a(this.a.world, this.a, this.b); - if (!this.a.world.isClientSide && this.inventory instanceof TileEntityFurnace) { - ((TileEntityFurnace) this.inventory).d(this.a, itemstack, this.b); // CraftBukkit - } - - this.b = 0; - } -} diff --git a/src/main/java/net/minecraft/server/SoundEffectType.java b/src/main/java/net/minecraft/server/SoundEffectType.java deleted file mode 100644 index ccd5b0529..000000000 --- a/src/main/java/net/minecraft/server/SoundEffectType.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.minecraft.server; - -public class SoundEffectType { - - public static final SoundEffectType a = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_WOOD_BREAK, SoundEffects.BLOCK_WOOD_STEP, SoundEffects.BLOCK_WOOD_PLACE, SoundEffects.BLOCK_WOOD_HIT, SoundEffects.BLOCK_WOOD_FALL); - public static final SoundEffectType b = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_GRAVEL_BREAK, SoundEffects.BLOCK_GRAVEL_STEP, SoundEffects.BLOCK_GRAVEL_PLACE, SoundEffects.BLOCK_GRAVEL_HIT, SoundEffects.BLOCK_GRAVEL_FALL); - public static final SoundEffectType c = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_GRASS_BREAK, SoundEffects.BLOCK_GRASS_STEP, SoundEffects.BLOCK_GRASS_PLACE, SoundEffects.BLOCK_GRASS_HIT, SoundEffects.BLOCK_GRASS_FALL); - public static final SoundEffectType d = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_STONE_BREAK, SoundEffects.BLOCK_STONE_STEP, SoundEffects.BLOCK_STONE_PLACE, SoundEffects.BLOCK_STONE_HIT, SoundEffects.BLOCK_STONE_FALL); - public static final SoundEffectType e = new SoundEffectType(1.0F, 1.5F, SoundEffects.BLOCK_METAL_BREAK, SoundEffects.BLOCK_METAL_STEP, SoundEffects.BLOCK_METAL_PLACE, SoundEffects.BLOCK_METAL_HIT, SoundEffects.BLOCK_METAL_FALL); - public static final SoundEffectType f = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_GLASS_BREAK, SoundEffects.BLOCK_GLASS_STEP, SoundEffects.BLOCK_GLASS_PLACE, SoundEffects.BLOCK_GLASS_HIT, SoundEffects.BLOCK_GLASS_FALL); - public static final SoundEffectType g = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_WOOL_BREAK, SoundEffects.BLOCK_WOOL_STEP, SoundEffects.BLOCK_WOOL_PLACE, SoundEffects.BLOCK_WOOL_HIT, SoundEffects.BLOCK_WOOL_FALL); - public static final SoundEffectType h = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_SAND_BREAK, SoundEffects.BLOCK_SAND_STEP, SoundEffects.BLOCK_SAND_PLACE, SoundEffects.BLOCK_SAND_HIT, SoundEffects.BLOCK_SAND_FALL); - public static final SoundEffectType i = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_SNOW_BREAK, SoundEffects.BLOCK_SNOW_STEP, SoundEffects.BLOCK_SNOW_PLACE, SoundEffects.BLOCK_SNOW_HIT, SoundEffects.BLOCK_SNOW_FALL); - public static final SoundEffectType j = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_LADDER_BREAK, SoundEffects.BLOCK_LADDER_STEP, SoundEffects.BLOCK_LADDER_PLACE, SoundEffects.BLOCK_LADDER_HIT, SoundEffects.BLOCK_LADDER_FALL); - public static final SoundEffectType k = new SoundEffectType(0.3F, 1.0F, SoundEffects.BLOCK_ANVIL_BREAK, SoundEffects.BLOCK_ANVIL_STEP, SoundEffects.BLOCK_ANVIL_PLACE, SoundEffects.BLOCK_ANVIL_HIT, SoundEffects.BLOCK_ANVIL_FALL); - public static final SoundEffectType l = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_SLIME_BLOCK_BREAK, SoundEffects.BLOCK_SLIME_BLOCK_STEP, SoundEffects.BLOCK_SLIME_BLOCK_PLACE, SoundEffects.BLOCK_SLIME_BLOCK_HIT, SoundEffects.BLOCK_SLIME_BLOCK_FALL); - public static final SoundEffectType m = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_WET_GRASS_BREAK, SoundEffects.BLOCK_WET_GRASS_STEP, SoundEffects.BLOCK_WET_GRASS_PLACE, SoundEffects.BLOCK_WET_GRASS_HIT, SoundEffects.BLOCK_WET_GRASS_FALL); - public static final SoundEffectType n = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_CORAL_BLOCK_BREAK, SoundEffects.BLOCK_CORAL_BLOCK_STEP, SoundEffects.BLOCK_CORAL_BLOCK_PLACE, SoundEffects.BLOCK_CORAL_BLOCK_HIT, SoundEffects.BLOCK_CORAL_BLOCK_FALL); - public static final SoundEffectType o = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_BAMBOO_BREAK, SoundEffects.BLOCK_BAMBOO_STEP, SoundEffects.BLOCK_BAMBOO_PLACE, SoundEffects.BLOCK_BAMBOO_HIT, SoundEffects.BLOCK_BAMBOO_FALL); - public static final SoundEffectType p = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_BAMBOO_SAPLING_BREAK, SoundEffects.BLOCK_BAMBOO_STEP, SoundEffects.BLOCK_BAMBOO_SAPLING_PLACE, SoundEffects.BLOCK_BAMBOO_SAPLING_HIT, SoundEffects.BLOCK_BAMBOO_FALL); - public static final SoundEffectType q = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_SCAFFOLDING_BREAK, SoundEffects.BLOCK_SCAFFOLDING_STEP, SoundEffects.BLOCK_SCAFFOLDING_PLACE, SoundEffects.BLOCK_SCAFFOLDING_HIT, SoundEffects.BLOCK_SCAFFOLDING_FALL); - public static final SoundEffectType r = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_SWEET_BERRY_BUSH_BREAK, SoundEffects.BLOCK_GRASS_STEP, SoundEffects.BLOCK_SWEET_BERRY_BUSH_PLACE, SoundEffects.BLOCK_GRASS_HIT, SoundEffects.BLOCK_GRASS_FALL); - public static final SoundEffectType s = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_CROP_BREAK, SoundEffects.BLOCK_GRASS_STEP, SoundEffects.ITEM_CROP_PLANT, SoundEffects.BLOCK_GRASS_HIT, SoundEffects.BLOCK_GRASS_FALL); - public static final SoundEffectType t = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_WOOD_BREAK, SoundEffects.BLOCK_WOOD_STEP, SoundEffects.ITEM_CROP_PLANT, SoundEffects.BLOCK_WOOD_HIT, SoundEffects.BLOCK_WOOD_FALL); - public static final SoundEffectType u = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_NETHER_WART_BREAK, SoundEffects.BLOCK_STONE_STEP, SoundEffects.ITEM_NETHER_WART_PLANT, SoundEffects.BLOCK_STONE_HIT, SoundEffects.BLOCK_STONE_FALL); - public static final SoundEffectType v = new SoundEffectType(1.0F, 1.0F, SoundEffects.BLOCK_LANTERN_BREAK, SoundEffects.BLOCK_LANTERN_STEP, SoundEffects.BLOCK_LANTERN_PLACE, SoundEffects.BLOCK_LANTERN_HIT, SoundEffects.BLOCK_LANTERN_FALL); - public final float w; - public final float x; - private final SoundEffect y; public final SoundEffect getBreakSound() { return this.y; } // Paper - OBFHELPER - private final SoundEffect z; - private final SoundEffect A; - private final SoundEffect B; public final SoundEffect getHitSound() { return this.B; } // Paper - OBFHELPER - private final SoundEffect C; - - public SoundEffectType(float f, float f1, SoundEffect soundeffect, SoundEffect soundeffect1, SoundEffect soundeffect2, SoundEffect soundeffect3, SoundEffect soundeffect4) { - this.w = f; - this.x = f1; - this.y = soundeffect; - this.z = soundeffect1; - this.A = soundeffect2; - this.B = soundeffect3; - this.C = soundeffect4; - } - - public float a() { - return this.w; - } - - public float b() { - return this.x; - } - - public final SoundEffect getStepSound() { return this.d(); } // Paper - OBFHELPER - public SoundEffect d() { - return this.z; - } - - public final SoundEffect getPlaceSound() { return this.e(); } // Paper - OBFHELPER - public SoundEffect e() { - return this.A; - } - - public final SoundEffect getFallSound() { return this.g(); } // Paper - OBFHELPER - public SoundEffect g() { - return this.C; - } -} diff --git a/src/main/java/net/minecraft/server/SpawnerCreature.java b/src/main/java/net/minecraft/server/SpawnerCreature.java deleted file mode 100644 index 9d4a96ae4..000000000 --- a/src/main/java/net/minecraft/server/SpawnerCreature.java +++ /dev/null @@ -1,283 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import java.util.Objects; -import java.util.Random; -import java.util.function.Consumer; // Paper -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import com.destroystokyo.paper.exception.ServerInternalException; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; -// CraftBukkit end - -public final class SpawnerCreature { - - private static final Logger LOGGER = LogManager.getLogger(); - - // Paper start - add maxSpawns parameter and return spawned mobs - public static void a(EnumCreatureType enumcreaturetype, World world, Chunk chunk, BlockPosition blockposition) { - spawnMobs(enumcreaturetype, world, chunk, blockposition, Integer.MAX_VALUE, null); - } - public static int spawnMobs(EnumCreatureType enumcreaturetype, World world, Chunk chunk, BlockPosition blockposition, int maxSpawns, Consumer trackEntity) { - // Paper end - ChunkGenerator chunkgenerator = world.getChunkProvider().getChunkGenerator(); - int i = 0; // Paper - force diff on name change - BlockPosition blockposition1 = getRandomPosition(world, chunk); - int j = blockposition1.getX(); - int k = blockposition1.getY(); - int l = blockposition1.getZ(); - - if (k >= 1) { - IBlockData iblockdata = world.getTypeIfLoadedAndInBounds(blockposition1); // Paper - don't load chunks for mob spawn - - if (iblockdata != null && !iblockdata.isOccluding(chunk, blockposition1)) { // Paper - don't load chunks for mob spawn - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - int i1 = 0; - - while (i1 < 3) { - int j1 = j; - int k1 = l; - boolean flag = true; - BiomeBase.BiomeMeta biomebase_biomemeta = null; - GroupDataEntity groupdataentity = null; - int l1 = MathHelper.f(Math.random() * 4.0D); - int i2 = 0; // Paper - force diff on name change - int j2 = 0; - - while (true) { - if (j2 < l1) { - label104: - { - j1 += world.random.nextInt(6) - world.random.nextInt(6); - k1 += world.random.nextInt(6) - world.random.nextInt(6); - blockposition_mutableblockposition.d(j1, k, k1); - float f = (float) j1 + 0.5F; - float f1 = (float) k1 + 0.5F; - EntityHuman entityhuman = world.a((double) f, (double) f1, -1.0D); - - if (entityhuman != null) { - double d0 = entityhuman.e((double) f, (double) k, (double) f1); - - if (d0 > 576.0D && !blockposition.a((IPosition) (new Vec3D((double) f, (double) k, (double) f1)), 24.0D) && world.isLoadedAndInBounds(blockposition_mutableblockposition)) { // Paper - don't load chunks for mob spawn - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(blockposition_mutableblockposition); - - if (Objects.equals(chunkcoordintpair, chunk.getPos()) || world.getChunkProvider().a(chunkcoordintpair)) { - if (biomebase_biomemeta == null) { - biomebase_biomemeta = a(chunkgenerator, enumcreaturetype, world.random, (BlockPosition) blockposition_mutableblockposition); - if (biomebase_biomemeta == null) { - break label104; - } - - l1 = biomebase_biomemeta.c + world.random.nextInt(1 + biomebase_biomemeta.d - biomebase_biomemeta.c); - } - - if (biomebase_biomemeta.b.e() != EnumCreatureType.MISC && (biomebase_biomemeta.b.d() || d0 <= 16384.0D)) { - EntityTypes entitytypes = biomebase_biomemeta.b; - - if (entitytypes.b() && a(chunkgenerator, enumcreaturetype, biomebase_biomemeta, (BlockPosition) blockposition_mutableblockposition)) { - EntityPositionTypes.Surface entitypositiontypes_surface = EntityPositionTypes.a(entitytypes); - - if (a(entitypositiontypes_surface, (IWorldReader) world, (BlockPosition) blockposition_mutableblockposition, entitytypes) && EntityPositionTypes.a(entitytypes, world, EnumMobSpawn.NATURAL, blockposition_mutableblockposition, world.random) && world.c(entitytypes.a((double) f, (double) k, (double) f1))) { - EntityInsentient entityinsentient; - - // Paper start - com.destroystokyo.paper.event.entity.PreCreatureSpawnEvent event; - EntityTypes cls = biomebase_biomemeta.b; - org.bukkit.entity.EntityType type = org.bukkit.entity.EntityType.fromName(EntityTypes.getName(cls).getKey()); - if (type != null) { - event = new com.destroystokyo.paper.event.entity.PreCreatureSpawnEvent( - MCUtil.toLocation(world, blockposition_mutableblockposition), - type, SpawnReason.NATURAL - ); - if (!event.callEvent()) { - if (event.shouldAbortSpawn()) { - return i; // Paper - } - ++i2; - continue; - } - } - // Paper end - - try { - Entity entity = entitytypes.a(world); - - if (!(entity instanceof EntityInsentient)) { - throw new IllegalStateException("Trying to spawn a non-mob: " + IRegistry.ENTITY_TYPE.getKey(entitytypes)); - } - - entityinsentient = (EntityInsentient) entity; - } catch (Exception exception) { - SpawnerCreature.LOGGER.warn("Failed to create mob", exception); - ServerInternalException.reportInternalException(exception); // Paper - return i; // Paper - } - - entityinsentient.setPositionRotation((double) f, (double) k, (double) f1, world.random.nextFloat() * 360.0F, 0.0F); - if ((d0 <= 16384.0D || !entityinsentient.isTypeNotPersistent(d0)) && entityinsentient.a((GeneratorAccess) world, EnumMobSpawn.NATURAL) && entityinsentient.a((IWorldReader) world)) { - groupdataentity = entityinsentient.prepare(world, world.getDamageScaler(new BlockPosition(entityinsentient)), EnumMobSpawn.NATURAL, groupdataentity, (NBTTagCompound) null); - // CraftBukkit start - if (world.addEntity(entityinsentient, SpawnReason.NATURAL)) { - ++i; // Paper - force diff on name change - ++i2; - if (trackEntity != null) { - trackEntity.accept(entityinsentient); // Paper - } - } - if (i >= maxSpawns) { return i; } // Paper - // CraftBukkit end - if (i >= entityinsentient.dC()) { - return i; // Paper - } - - if (entityinsentient.c(i2)) { - break label104; - } - } - } - } - } - } - } - } - - ++j2; - continue; - } - } - - ++i1; - break; - } - } - - } - } - return i; // Paper - } - - @Nullable - private static BiomeBase.BiomeMeta a(ChunkGenerator chunkgenerator, EnumCreatureType enumcreaturetype, Random random, BlockPosition blockposition) { - List list = chunkgenerator.getMobsFor(enumcreaturetype, blockposition); - - return list.isEmpty() ? null : (BiomeBase.BiomeMeta) WeightedRandom.a(random, list); - } - - private static boolean a(ChunkGenerator chunkgenerator, EnumCreatureType enumcreaturetype, BiomeBase.BiomeMeta biomebase_biomemeta, BlockPosition blockposition) { - List list = chunkgenerator.getMobsFor(enumcreaturetype, blockposition); - - return list.isEmpty() ? false : list.contains(biomebase_biomemeta); - } - - private static BlockPosition getRandomPosition(World world, Chunk chunk) { - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - int i = chunkcoordintpair.d() + world.random.nextInt(16); - int j = chunkcoordintpair.e() + world.random.nextInt(16); - int k = chunk.a(HeightMap.Type.WORLD_SURFACE, i, j) + 1; - int l = world.random.nextInt(k + 1); - - return new BlockPosition(i, l, j); - } - - public static boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, Fluid fluid) { - return iblockdata.o(iblockaccess, blockposition) ? false : (iblockdata.isPowerSource() ? false : (!fluid.isEmpty() ? false : !iblockdata.a(TagsBlock.RAILS))); - } - - public static boolean a(EntityPositionTypes.Surface entitypositiontypes_surface, IWorldReader iworldreader, BlockPosition blockposition, @Nullable EntityTypes entitytypes) { - if (entitypositiontypes_surface == EntityPositionTypes.Surface.NO_RESTRICTIONS) { - return true; - } else if (entitytypes != null && iworldreader.getWorldBorder().a(blockposition)) { - IBlockData iblockdata = iworldreader.getType(blockposition); - Fluid fluid = iworldreader.getFluid(blockposition); - BlockPosition blockposition1 = blockposition.up(); - BlockPosition blockposition2 = blockposition.down(); - - switch (entitypositiontypes_surface) { - case IN_WATER: - return fluid.a(TagsFluid.WATER) && iworldreader.getFluid(blockposition2).a(TagsFluid.WATER) && !iworldreader.getType(blockposition1).isOccluding(iworldreader, blockposition1); - case ON_GROUND: - default: - IBlockData iblockdata1 = iworldreader.getType(blockposition2); - - return !iblockdata1.a((IBlockAccess) iworldreader, blockposition2, entitytypes) ? false : a((IBlockAccess) iworldreader, blockposition, iblockdata, fluid) && a((IBlockAccess) iworldreader, blockposition1, iworldreader.getType(blockposition1), iworldreader.getFluid(blockposition1)); - } - } else { - return false; - } - } - - public static void a(GeneratorAccess generatoraccess, BiomeBase biomebase, int i, int j, Random random) { - List list = biomebase.getMobs(EnumCreatureType.CREATURE); - - if (!list.isEmpty()) { - int k = i << 4; - int l = j << 4; - - while (random.nextFloat() < biomebase.d()) { - BiomeBase.BiomeMeta biomebase_biomemeta = (BiomeBase.BiomeMeta) WeightedRandom.a(random, list); - int i1 = biomebase_biomemeta.c + random.nextInt(1 + biomebase_biomemeta.d - biomebase_biomemeta.c); - GroupDataEntity groupdataentity = null; - int j1 = k + random.nextInt(16); - int k1 = l + random.nextInt(16); - 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 = a(generatoraccess, biomebase_biomemeta.b, j1, k1); - - if (biomebase_biomemeta.b.b() && a(EntityPositionTypes.Surface.ON_GROUND, (IWorldReader) generatoraccess, blockposition, biomebase_biomemeta.b)) { - float f = biomebase_biomemeta.b.i(); - double d0 = MathHelper.a((double) j1, (double) k + (double) f, (double) k + 16.0D - (double) f); - double d1 = MathHelper.a((double) k1, (double) l + (double) f, (double) l + 16.0D - (double) f); - - if (!generatoraccess.c(biomebase_biomemeta.b.a(d0, (double) blockposition.getY(), d1)) || !EntityPositionTypes.a(biomebase_biomemeta.b, generatoraccess, EnumMobSpawn.CHUNK_GENERATION, new BlockPosition(d0, (double) blockposition.getY(), d1), generatoraccess.getRandom())) { - continue; - } - - Entity entity; - - try { - entity = biomebase_biomemeta.b.a(generatoraccess.getMinecraftWorld()); - } catch (Exception exception) { - SpawnerCreature.LOGGER.warn("Failed to create mob", exception); - ServerInternalException.reportInternalException(exception); // Paper - continue; - } - - entity.setPositionRotation(d0, (double) blockposition.getY(), d1, random.nextFloat() * 360.0F, 0.0F); - if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - - if (entityinsentient.a(generatoraccess, EnumMobSpawn.CHUNK_GENERATION) && entityinsentient.a((IWorldReader) generatoraccess)) { - groupdataentity = entityinsentient.prepare(generatoraccess, generatoraccess.getDamageScaler(new BlockPosition(entityinsentient)), EnumMobSpawn.CHUNK_GENERATION, groupdataentity, (NBTTagCompound) null); - generatoraccess.addEntity(entityinsentient, SpawnReason.CHUNK_GEN); // CraftBukkit - flag = true; - } - } - } - - j1 += random.nextInt(5) - random.nextInt(5); - - for (k1 += random.nextInt(5) - random.nextInt(5); j1 < k || j1 >= k + 16 || k1 < l || k1 >= l + 16; k1 = i2 + random.nextInt(5) - random.nextInt(5)) { - j1 = l1 + random.nextInt(5) - random.nextInt(5); - } - } - } - } - - } - } - - private static BlockPosition a(IWorldReader iworldreader, @Nullable EntityTypes entitytypes, int i, int j) { - BlockPosition blockposition = new BlockPosition(i, iworldreader.a(EntityPositionTypes.b(entitytypes), i, j), j); - BlockPosition blockposition1 = blockposition.down(); - - return iworldreader.getType(blockposition1).a((IBlockAccess) iworldreader, blockposition1, PathMode.LAND) ? blockposition1 : blockposition; - } -} diff --git a/src/main/java/net/minecraft/server/StatisticManager.java b/src/main/java/net/minecraft/server/StatisticManager.java deleted file mode 100644 index ec4226242..000000000 --- a/src/main/java/net/minecraft/server/StatisticManager.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.minecraft.server; - -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntMaps; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; - -public class StatisticManager { - - protected final Object2IntMap> a = Object2IntMaps.synchronize(new Object2IntOpenHashMap()); - - public StatisticManager() { - this.a.defaultReturnValue(0); - } - - public void b(EntityHuman entityhuman, Statistic statistic, int i) { - // 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) { - this.a.put(statistic, i); - } - - public int getStatisticValue(Statistic statistic) { - return this.a.getInt(statistic); - } -} diff --git a/src/main/java/net/minecraft/server/StructureGenerator.java b/src/main/java/net/minecraft/server/StructureGenerator.java deleted file mode 100644 index 7b2eace75..000000000 --- a/src/main/java/net/minecraft/server/StructureGenerator.java +++ /dev/null @@ -1,175 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.datafixers.Dynamic; -import it.unimi.dsi.fastutil.longs.LongIterator; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.function.Function; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public abstract class StructureGenerator extends WorldGenerator { - - private static final Logger LOGGER = LogManager.getLogger(); - - public StructureGenerator(Function, ? extends C> function) { - super(function, false); - } - - @Override - public boolean generate(GeneratorAccess generatoraccess, ChunkGenerator chunkgenerator, Random random, BlockPosition blockposition, C c0) { - if (!generatoraccess.getWorldData().shouldGenerateMapFeatures()) { - return false; - } else { - int i = blockposition.getX() >> 4; - int j = blockposition.getZ() >> 4; - int k = i << 4; - int l = j << 4; - boolean flag = false; - LongIterator longiterator = generatoraccess.getChunkAt(i, j).b(this.b()).iterator(); - - while (longiterator.hasNext()) { - Long olong = (Long) longiterator.next(); - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(olong); - StructureStart structurestart = generatoraccess.getChunkAt(chunkcoordintpair.x, chunkcoordintpair.z).a(this.b()); - - if (structurestart != null && structurestart != StructureStart.a) { - structurestart.a(generatoraccess, random, new StructureBoundingBox(k, l, k + 15, l + 15), new ChunkCoordIntPair(i, j)); - flag = true; - } - } - - return flag; - } - } - - protected StructureStart a(GeneratorAccess generatoraccess, BlockPosition blockposition, boolean flag) { - List list = this.a(generatoraccess, blockposition.getX() >> 4, blockposition.getZ() >> 4); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - StructureStart structurestart = (StructureStart) iterator.next(); - - if (structurestart.e() && structurestart.c().b((BaseBlockPosition) blockposition)) { - if (!flag) { - return structurestart; - } - - Iterator iterator1 = structurestart.d().iterator(); - - while (iterator1.hasNext()) { - StructurePiece structurepiece = (StructurePiece) iterator1.next(); - - if (structurepiece.g().b((BaseBlockPosition) blockposition)) { - return structurestart; - } - } - } - } - - return StructureStart.a; - } - - public boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - return this.a(generatoraccess, blockposition, false).e(); - } - - public boolean b(GeneratorAccess generatoraccess, BlockPosition blockposition) { - return this.a(generatoraccess, blockposition, true).e(); - } - - @Nullable - public BlockPosition getNearestGeneratedFeature(World world, ChunkGenerator chunkgenerator, BlockPosition blockposition, int i, boolean flag) { - if (!chunkgenerator.getWorldChunkManager().a(this)) { - return null; - } else { - int j = blockposition.getX() >> 4; - int k = blockposition.getZ() >> 4; - int l = 0; - SeededRandom seededrandom = new SeededRandom(); - - while (l <= i) { - int i1 = -l; - - while (true) { - if (i1 <= l) { - boolean flag1 = i1 == -l || i1 == l; - - for (int j1 = -l; j1 <= l; ++j1) { - boolean flag2 = j1 == -l || j1 == l; - - if (flag1 || flag2) { - ChunkCoordIntPair chunkcoordintpair = this.a(chunkgenerator, seededrandom, j, k, i1, j1); - if (!world.getWorldBorder().isChunkInBounds(chunkcoordintpair.x, chunkcoordintpair.z)) { continue; } // Paper - StructureStart structurestart = world.getChunkAt(chunkcoordintpair.x, chunkcoordintpair.z, ChunkStatus.STRUCTURE_STARTS).a(this.b()); - - if (structurestart != null && structurestart.e()) { - if (flag && structurestart.h()) { - structurestart.i(); - return structurestart.a(); - } - - if (!flag) { - return structurestart.a(); - } - } - - if (l == 0) { - break; - } - } - } - - if (l != 0) { - ++i1; - continue; - } - } - - ++l; - break; - } - } - - return null; - } - } - - private List a(GeneratorAccess generatoraccess, int i, int j) { - List list = Lists.newArrayList(); - IChunkAccess ichunkaccess = generatoraccess.getChunkAt(i, j, ChunkStatus.STRUCTURE_REFERENCES); - LongIterator longiterator = ichunkaccess.b(this.b()).iterator(); - - while (longiterator.hasNext()) { - long k = longiterator.nextLong(); - IChunkAccess ichunkaccess1 = generatoraccess.getChunkAt(ChunkCoordIntPair.getX(k), ChunkCoordIntPair.getZ(k), ChunkStatus.STRUCTURE_STARTS, false); // CraftBukkit - don't load chunks - StructureStart structurestart = ichunkaccess1.a(this.b()); - - if (structurestart != null) { - list.add(structurestart); - } - } - - return list; - } - - protected ChunkCoordIntPair a(ChunkGenerator chunkgenerator, Random random, int i, int j, int k, int l) { - return new ChunkCoordIntPair(i + k, j + l); - } - - public abstract boolean a(ChunkGenerator chunkgenerator, Random random, int i, int j); - - public abstract StructureGenerator.a a(); - - public abstract String b(); - - public abstract int c(); - - public interface a { - - StructureStart create(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l); - } -} diff --git a/src/main/java/net/minecraft/server/SystemUtils.java b/src/main/java/net/minecraft/server/SystemUtils.java deleted file mode 100644 index 35594821c..000000000 --- a/src/main/java/net/minecraft/server/SystemUtils.java +++ /dev/null @@ -1,268 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.MoreExecutors; -import com.mojang.datafixers.DataFixUtils; -import com.mojang.datafixers.Dynamic; -import it.unimi.dsi.fastutil.Hash.Strategy; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.time.Instant; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.Map.Entry; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ForkJoinWorkerThread; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; -import java.util.function.LongSupplier; -import java.util.function.Supplier; -import java.util.stream.Collector; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class SystemUtils { - - private static final AtomicInteger b = new AtomicInteger(1); - private static final ExecutorService c = k(); - public static LongSupplier a = System::nanoTime; - private static final Logger LOGGER = LogManager.getLogger(); - - public static Collector, ?, Map> a() { - return Collectors.toMap(Entry::getKey, Entry::getValue); - } - - public static > String a(IBlockState iblockstate, T object) { // Paper - decompile fix - return iblockstate.a(object); // Paper - decompile fix - } - - public static String a(String s, @Nullable MinecraftKey minecraftkey) { - return minecraftkey == null ? s + ".unregistered_sadface" : s + '.' + minecraftkey.getNamespace() + '.' + minecraftkey.getKey().replace('/', '.'); - } - - public static long getMonotonicMillis() { - return getMonotonicNanos() / 1000000L; - } - - public static long getMonotonicNanos() { - return System.nanoTime(); // Paper - } - - public static long getTimeMillis() { - return Instant.now().toEpochMilli(); - } - - private static ExecutorService k() { - int i = Math.min(6, Math.max(Runtime.getRuntime().availableProcessors() - 2, 2)); // Paper - use more reasonable default - 2 is hard minimum to avoid using unlimited threads - Object object; - - if (i <= 0) { - object = MoreExecutors.newDirectExecutorService(); - } else { - object = new ForkJoinPool(i, (forkjoinpool) -> { - ForkJoinWorkerThread forkjoinworkerthread = new ForkJoinWorkerThread(forkjoinpool) { - }; - - forkjoinworkerthread.setName("Server-Worker-" + SystemUtils.b.getAndIncrement()); - return forkjoinworkerthread; - }, (thread, throwable) -> { - if (throwable instanceof CompletionException) { - throwable = throwable.getCause(); - } - - if (throwable instanceof ReportedException) { - DispenserRegistry.a(((ReportedException) throwable).a().e()); - System.exit(-1); - } - - SystemUtils.LOGGER.error(String.format("Caught exception in thread %s", thread), throwable); - }, true); - } - - return (ExecutorService) object; - } - - public static Executor e() { - return SystemUtils.c; - } - - public static void f() { - SystemUtils.c.shutdown(); - - boolean flag; - - try { - flag = SystemUtils.c.awaitTermination(3L, TimeUnit.SECONDS); - } catch (InterruptedException interruptedexception) { - flag = false; - } - - if (!flag) { - SystemUtils.c.shutdownNow(); - } - - } - - public static SystemUtils.OS g() { - String s = System.getProperty("os.name").toLowerCase(Locale.ROOT); - - return s.contains("win") ? SystemUtils.OS.WINDOWS : (s.contains("mac") ? SystemUtils.OS.OSX : (s.contains("solaris") ? SystemUtils.OS.SOLARIS : (s.contains("sunos") ? SystemUtils.OS.SOLARIS : (s.contains("linux") ? SystemUtils.OS.LINUX : (s.contains("unix") ? SystemUtils.OS.LINUX : SystemUtils.OS.UNKNOWN))))); - } - - public static Stream h() { - RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean(); - - return runtimemxbean.getInputArguments().stream().filter((s) -> { - return s.startsWith("-X"); - }); - } - - public static T a(List list) { - return list.get(list.size() - 1); - } - - public static T a(Iterable iterable, @Nullable T t0) { - Iterator iterator = iterable.iterator(); - T t1 = iterator.next(); - - if (t0 != null) { - Object object = t1; - - while (object != t0) { - if (iterator.hasNext()) { - object = iterator.next(); - } - } - - if (iterator.hasNext()) { - return iterator.next(); - } - } - - return t1; - } - - public static T b(Iterable iterable, @Nullable T t0) { - Iterator iterator = iterable.iterator(); - - T object; // Paper - decompile fix - T object1; // Paper - decompile fix - - for (object1 = null; iterator.hasNext(); object1 = object) { - object = iterator.next(); - if (object == t0) { - if (object1 == null) { - object1 = iterator.hasNext() ? Iterators.getLast(iterator) : t0; - } - break; - } - } - - return object1; - } - - public static T a(Supplier supplier) { - return supplier.get(); - } - - public static T a(T t0, Consumer consumer) { - consumer.accept(t0); - return t0; - } - - public static Strategy i() { - return (Strategy) SystemUtils.IdentityHashingStrategy.INSTANCE; // Paper - decompile fix - } - - public static CompletableFuture> b(List> list) { - List list1 = Lists.newArrayListWithCapacity(list.size()); - CompletableFuture[] acompletablefuture = new CompletableFuture[list.size()]; - CompletableFuture completablefuture = new CompletableFuture(); - - list.forEach((completablefuture1) -> { - int i = list1.size(); - - list1.add(null); // Paper - decompile fix - acompletablefuture[i] = completablefuture1.whenComplete((object, throwable) -> { - if (throwable != null) { - completablefuture.completeExceptionally(throwable); - } else { - list1.set(i, object); - } - - }); - }); - return CompletableFuture.allOf(acompletablefuture).applyToEither(completablefuture, (ovoid) -> { - return list1; - }); - } - - public static Stream a(Optional optional) { - return (Stream) DataFixUtils.orElseGet(optional.map(Stream::of), Stream::empty); - } - - public static Optional a(Optional optional, Consumer consumer, Runnable runnable) { - if (optional.isPresent()) { - consumer.accept(optional.get()); - } else { - runnable.run(); - } - - return optional; - } - - public static Runnable a(Runnable runnable, Supplier supplier) { - return runnable; - } - - public static Optional a(String s, Dynamic dynamic) { - return dynamic.get(s + "Most").asNumber().flatMap((number) -> { - return dynamic.get(s + "Least").asNumber().map((number1) -> { - return new UUID(number.longValue(), number1.longValue()); - }); - }); - } - - public static Dynamic a(String s, UUID uuid, Dynamic dynamic) { - return dynamic.set(s + "Most", dynamic.createLong(uuid.getMostSignificantBits())).set(s + "Least", dynamic.createLong(uuid.getLeastSignificantBits())); - } - - static enum IdentityHashingStrategy implements Strategy { - - INSTANCE; - - private IdentityHashingStrategy() {} - - public int hashCode(Object object) { - return System.identityHashCode(object); - } - - public boolean equals(Object object, Object object1) { - return object == object1; - } - } - - public static enum OS { - - LINUX, SOLARIS, WINDOWS { - }, - OSX { - }, - UNKNOWN; - - private OS() {} - } -} diff --git a/src/main/java/net/minecraft/server/TagRegistry.java b/src/main/java/net/minecraft/server/TagRegistry.java deleted file mode 100644 index 36ce76af1..000000000 --- a/src/main/java/net/minecraft/server/TagRegistry.java +++ /dev/null @@ -1,98 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.util.Pair; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; - -public class TagRegistry implements IReloadListener { - - private final TagsServer blockTags; - private final TagsServer itemTags; - private final TagsServer fluidTags; - private final TagsServer> entityTags; - - public TagRegistry() { - this.blockTags = new TagsServer<>(IRegistry.BLOCK, "tags/blocks", "block"); - this.itemTags = new TagsServer<>(IRegistry.ITEM, "tags/items", "item"); - this.fluidTags = new TagsServer<>(IRegistry.FLUID, "tags/fluids", "fluid"); - this.entityTags = new TagsServer<>(IRegistry.ENTITY_TYPE, "tags/entity_types", "entity_type"); - } - - public TagsServer getBlockTags() { - return this.blockTags; - } - - public TagsServer getItemTags() { - return this.itemTags; - } - - public TagsServer getFluidTags() { - return this.fluidTags; - } - - public TagsServer> getEntityTags() { - return this.entityTags; - } - - public void a(PacketDataSerializer packetdataserializer) { - this.blockTags.a(packetdataserializer); - this.itemTags.a(packetdataserializer); - this.fluidTags.a(packetdataserializer); - this.entityTags.a(packetdataserializer); - } - - public static TagRegistry b(PacketDataSerializer packetdataserializer) { - TagRegistry tagregistry = new TagRegistry(); - - tagregistry.getBlockTags().b(packetdataserializer); - tagregistry.getItemTags().b(packetdataserializer); - tagregistry.getFluidTags().b(packetdataserializer); - tagregistry.getEntityTags().b(packetdataserializer); - return tagregistry; - } - - @Override - public CompletableFuture a(IReloadListener.a ireloadlistener_a, IResourceManager iresourcemanager, GameProfilerFiller gameprofilerfiller, GameProfilerFiller gameprofilerfiller1, Executor executor, Executor executor1) { - CompletableFuture>> completablefuture = this.blockTags.a(iresourcemanager, executor); - CompletableFuture>> completablefuture1 = this.itemTags.a(iresourcemanager, executor); - CompletableFuture>> completablefuture2 = this.fluidTags.a(iresourcemanager, executor); - CompletableFuture>>> completablefuture3 = this.entityTags.a(iresourcemanager, executor); - CompletableFuture completablefuture4 = completablefuture.thenCombine(completablefuture1, Pair::of).thenCombine(completablefuture2.thenCombine(completablefuture3, Pair::of), (pair, pair1) -> { // CraftBukkit - decompile error - return new TagRegistry.a((Map) pair.getFirst(), (Map) pair.getSecond(), (Map) pair1.getFirst(), (Map) pair1.getSecond()); - }); - - ireloadlistener_a.getClass(); - return completablefuture4.thenCompose(ireloadlistener_a::a).thenAcceptAsync((tagregistry_a) -> { - this.blockTags.a(tagregistry_a.a); - this.itemTags.a(tagregistry_a.b); - this.fluidTags.a(tagregistry_a.c); - this.entityTags.a(tagregistry_a.d); - TagsBlock.a((Tags) this.blockTags); - TagsItem.a((Tags) this.itemTags); - TagsFluid.a((Tags) this.fluidTags); - TagsEntity.a((Tags) this.entityTags); - // CraftBukkit start - this.blockTags.version++; - this.itemTags.version++; - this.fluidTags.version++; - this.entityTags.version++; - // CraftBukkit end - }, executor1); - } - - public static class a { - - final Map> a; - final Map> b; - final Map> c; - final Map>> d; - - public a(Map> map, Map> map1, Map> map2, Map>> map3) { - this.a = map; - this.b = map1; - this.c = map2; - this.d = map3; - } - } -} diff --git a/src/main/java/net/minecraft/server/TagsServer.java b/src/main/java/net/minecraft/server/TagsServer.java deleted file mode 100644 index 7ed9f2cd5..000000000 --- a/src/main/java/net/minecraft/server/TagsServer.java +++ /dev/null @@ -1,58 +0,0 @@ -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 TagsServer extends Tags { - - private final IRegistry a; - public int version; // CraftBukkit - - public TagsServer(IRegistry iregistry, String s, String s1) { - super(iregistry::getOptional, s, false, s1); - this.a = iregistry; - } - - public void a(PacketDataSerializer packetdataserializer) { - Map> map = this.b(); - - packetdataserializer.d(map.size()); - Iterator iterator = map.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry> entry = (Entry) iterator.next(); - - packetdataserializer.a((MinecraftKey) entry.getKey()); - packetdataserializer.d(((Tag) entry.getValue()).a().size()); - Iterator iterator1 = ((Tag) entry.getValue()).a().iterator(); - - while (iterator1.hasNext()) { - T t0 = (T) iterator1.next(); // CraftBukkit - decompile error - - packetdataserializer.d(this.a.a(t0)); - } - } - - } - - public void b(PacketDataSerializer packetdataserializer) { - Map> map = Maps.newHashMap(); - int i = packetdataserializer.i(); - - for (int j = 0; j < i; ++j) { - MinecraftKey minecraftkey = packetdataserializer.o(); - int k = packetdataserializer.i(); - Tag.a tag_a = Tag.a.a(); - - for (int l = 0; l < k; ++l) { - tag_a.a(this.a.fromId(packetdataserializer.i())); - } - - map.put(minecraftkey, tag_a.b(minecraftkey)); - } - - this.b((Map) map); - } -} diff --git a/src/main/java/net/minecraft/server/TickListServer.java b/src/main/java/net/minecraft/server/TickListServer.java deleted file mode 100644 index f533860bb..000000000 --- a/src/main/java/net/minecraft/server/TickListServer.java +++ /dev/null @@ -1,235 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Queues; -import com.google.common.collect.Sets; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Queue; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Stream; -import javax.annotation.Nullable; - -public class TickListServer implements TickList { - - protected final Predicate a; - private final Function b; - private final Function c; - private final Set> nextTickListHash = Sets.newHashSet(); - private final TreeSet> nextTickList = Sets.newTreeSet(NextTickListEntry.a()); - private final WorldServer f; - private final Queue> g = Queues.newArrayDeque(); - private final List> h = Lists.newArrayList(); - private final Consumer> i; - - public TickListServer(WorldServer worldserver, Predicate predicate, Function function, Function function1, Consumer> consumer, String timingsType) { // Paper - this.a = predicate; - this.b = function; - this.c = function1; - this.f = worldserver; - this.i = consumer; - this.timingCleanup = co.aikar.timings.WorldTimingsHandler.getTickList(worldserver, timingsType + " - Cleanup"); - this.timingTicking = co.aikar.timings.WorldTimingsHandler.getTickList(worldserver, timingsType + " - Ticking"); - } - private final co.aikar.timings.Timing timingCleanup; // Paper - private final co.aikar.timings.Timing timingTicking; // Paper - // Paper end - - public void b() { - int i = this.nextTickList.size(); - - if (false) { // CraftBukkit - throw new IllegalStateException("TickNextTick list out of synch"); - } else { - if (i > 65536) { - // CraftBukkit start - If the server has too much to process over time, try to alleviate that - if (i > 20 * 65536) { - i = i / 20; - } else { - i = 65536; - } - // CraftBukkit end - } - - ChunkProviderServer chunkproviderserver = this.f.getChunkProvider(); - Iterator> iterator = this.nextTickList.iterator(); - - this.f.getMethodProfiler().enter("cleaning"); - - this.timingCleanup.startTiming(); // Paper - NextTickListEntry nextticklistentry; - - while (i > 0 && iterator.hasNext()) { - nextticklistentry = (NextTickListEntry) iterator.next(); - if (nextticklistentry.b > this.f.getTime()) { - break; - } - - if (chunkproviderserver.a(nextticklistentry.a)) { - iterator.remove(); - this.nextTickListHash.remove(nextticklistentry); - this.g.add(nextticklistentry); - --i; - } - } - this.timingCleanup.stopTiming(); // Paper - - this.timingTicking.startTiming(); // Paper - this.f.getMethodProfiler().exitEnter("ticking"); - - while ((nextticklistentry = (NextTickListEntry) this.g.poll()) != null) { - if (chunkproviderserver.a(nextticklistentry.a)) { - try { - this.h.add(nextticklistentry); - this.i.accept(nextticklistentry); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.a(throwable, "Exception while ticking"); - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Block being ticked"); - - CrashReportSystemDetails.a(crashreportsystemdetails, nextticklistentry.a, (IBlockData) null); - throw new ReportedException(crashreport); - } - } else { - this.a(nextticklistentry.a, (T) nextticklistentry.b(), 0); // CraftBukkit - decompile error - } - } - - this.f.getMethodProfiler().exit(); - this.timingTicking.stopTiming(); // Paper - this.h.clear(); - this.g.clear(); - } - } - - @Override - public boolean b(BlockPosition blockposition, T t0) { - return this.g.contains(new NextTickListEntry<>(blockposition, t0)); - } - - @Override - public void a(Stream> stream) { - stream.forEach(this::a); - } - - public List> a(ChunkCoordIntPair chunkcoordintpair, boolean flag, boolean flag1) { - int i = (chunkcoordintpair.x << 4) - 2; - int j = i + 16 + 2; - int k = (chunkcoordintpair.z << 4) - 2; - int l = k + 16 + 2; - - return this.a(new StructureBoundingBox(i, 0, k, j, 256, l), flag, flag1); - } - - public List> a(StructureBoundingBox structureboundingbox, boolean flag, boolean flag1) { - List> list = this.a((List) null, this.nextTickList, structureboundingbox, flag); - - if (flag && list != null) { - this.nextTickListHash.removeAll(list); - } - - list = this.a(list, this.g, structureboundingbox, flag); - if (!flag1) { - list = this.a(list, this.h, structureboundingbox, flag); - } - - return list == null ? Collections.emptyList() : list; - } - - @Nullable - private List> a(@Nullable List> list, Collection> collection, StructureBoundingBox structureboundingbox, boolean flag) { - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - NextTickListEntry 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 (list == null) { - list = Lists.newArrayList(); - } - - ((List) list).add(nextticklistentry); - } - } - - return (List) list; - } - - public void a(StructureBoundingBox structureboundingbox, BlockPosition blockposition) { - List> list = this.a(structureboundingbox, false, false); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - NextTickListEntry nextticklistentry = (NextTickListEntry) iterator.next(); - - if (structureboundingbox.b((BaseBlockPosition) nextticklistentry.a)) { - BlockPosition blockposition1 = nextticklistentry.a.a((BaseBlockPosition) blockposition); - T t0 = nextticklistentry.b(); - - this.a(new NextTickListEntry<>(blockposition1, t0, nextticklistentry.b, nextticklistentry.c)); - } - } - - } - - public NBTTagList a(ChunkCoordIntPair chunkcoordintpair) { - List> list = this.a(chunkcoordintpair, false, true); - - return a(this.b, list, this.f.getTime()); - } - - public static NBTTagList a(Function function, Iterable> iterable, long i) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = iterable.iterator(); - - while (iterator.hasNext()) { - NextTickListEntry nextticklistentry = (NextTickListEntry) iterator.next(); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setString("i", ((MinecraftKey) function.apply(nextticklistentry.b())).toString()); - nbttagcompound.setInt("x", nextticklistentry.a.getX()); - nbttagcompound.setInt("y", nextticklistentry.a.getY()); - nbttagcompound.setInt("z", nextticklistentry.a.getZ()); - nbttagcompound.setInt("t", (int) (nextticklistentry.b - i)); - nbttagcompound.setInt("p", nextticklistentry.c.a()); - nbttaglist.add(nbttagcompound); - } - - return nbttaglist; - } - - @Override - public boolean a(BlockPosition blockposition, T t0) { - return this.nextTickListHash.contains(new NextTickListEntry<>(blockposition, t0)); - } - - @Override - public void a(BlockPosition blockposition, T t0, int i, TickListPriority ticklistpriority) { - if (!this.a.test(t0)) { - this.a(new NextTickListEntry<>(blockposition, t0, (long) i + this.f.getTime(), ticklistpriority)); - } - - } - - private void a(NextTickListEntry nextticklistentry) { - if (!this.nextTickListHash.contains(nextticklistentry)) { - this.nextTickListHash.add(nextticklistentry); - this.nextTickList.add(nextticklistentry); - } - - } - - public int a() { - return this.nextTickListHash.size(); - } -} diff --git a/src/main/java/net/minecraft/server/Ticket.java b/src/main/java/net/minecraft/server/Ticket.java deleted file mode 100644 index badbe6c19..000000000 --- a/src/main/java/net/minecraft/server/Ticket.java +++ /dev/null @@ -1,65 +0,0 @@ -package net.minecraft.server; - -import java.util.Objects; - -public final class Ticket implements Comparable> { - - private final TicketType a; - private final int b; - public final T identifier; public final T getObjectReason() { return this.identifier; } // Paper - OBFHELPER - private final long d; public final long getCreationTick() { return this.d; } // Paper - OBFHELPER - - protected Ticket(TicketType tickettype, int i, T t0, long j) { - this.a = tickettype; - this.b = i; - this.identifier = t0; - this.d = j; - } - - public int compareTo(Ticket ticket) { - int i = Integer.compare(this.b, ticket.b); - - if (i != 0) { - return i; - } else { - int j = Integer.compare(System.identityHashCode(this.a), System.identityHashCode(ticket.a)); - - return j != 0 ? j : this.a.a().compare(this.identifier, (T)ticket.identifier); // Paper - decompile fix - } - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (!(object instanceof Ticket)) { - return false; - } else { - Ticket ticket = (Ticket) object; - - return this.b == ticket.b && Objects.equals(this.a, ticket.a) && Objects.equals(this.identifier, ticket.identifier); - } - } - - public int hashCode() { - return Objects.hash(new Object[]{this.a, this.b, this.identifier}); - } - - public String toString() { - return "Ticket[" + this.a + " " + this.b + " (" + this.identifier + ")] at " + this.d; - } - - public TicketType getTicketType() { - return this.a; - } - - public final int getTicketLevel() { return this.b(); } // Paper - OBFHELPER - public int b() { - return this.b; - } - - public boolean a(long i) { - long j = this.a.b(); - - return j != 0L && i - this.d > j; - } -} diff --git a/src/main/java/net/minecraft/server/TicketType.java b/src/main/java/net/minecraft/server/TicketType.java deleted file mode 100644 index e3150f85a..000000000 --- a/src/main/java/net/minecraft/server/TicketType.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.minecraft.server; - -import java.util.Comparator; - -public class TicketType { - - private final String i; - private final Comparator j; - public long loadPeriod; - public static final TicketType START = a("start", (unit, unit1) -> { - return 0; - }); - public static final TicketType DRAGON = a("dragon", (unit, unit1) -> { - return 0; - }); - public static final TicketType PLAYER = a("player", Comparator.comparingLong(ChunkCoordIntPair::pair)); - public static final TicketType FORCED = a("forced", Comparator.comparingLong(ChunkCoordIntPair::pair)); - public static final TicketType LIGHT = a("light", Comparator.comparingLong(ChunkCoordIntPair::pair)); - public static final TicketType PORTAL = a("portal", Comparator.comparingLong(BlockPosition2D::b)); - public static final TicketType POST_TELEPORT = a("post_teleport", Integer::compareTo, 5); - public static final TicketType UNKNOWN = a("unknown", Comparator.comparingLong(ChunkCoordIntPair::pair), 1); - public static final TicketType PLUGIN = a("plugin", (a, b) -> 0); // CraftBukkit - public static final TicketType PLUGIN_TICKET = a("plugin_ticket", (plugin1, plugin2) -> plugin1.getClass().getName().compareTo(plugin2.getClass().getName())); // Craftbukkit - public static final TicketType ANTIXRAY = a("antixray", Integer::compareTo); // Paper - Anti-Xray - public static final TicketType ASYNC_LOAD = a("async_load", Long::compareTo); // Paper - - public static TicketType a(String s, Comparator comparator) { - return new TicketType<>(s, comparator, 0L); - } - - public static TicketType a(String s, Comparator comparator, int i) { - return new TicketType<>(s, comparator, (long) i); - } - - protected TicketType(String s, Comparator comparator, long i) { - this.i = s; - this.j = comparator; - this.loadPeriod = i; - } - - public String toString() { - return this.i; - } - - public Comparator a() { - return this.j; - } - - public long b() { - return this.loadPeriod; - } -} diff --git a/src/main/java/net/minecraft/server/TileEntity.java b/src/main/java/net/minecraft/server/TileEntity.java deleted file mode 100644 index b8ddb99fa..000000000 --- a/src/main/java/net/minecraft/server/TileEntity.java +++ /dev/null @@ -1,254 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.util.Supplier; -// CraftBukkit start -import org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer; -import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry; -import org.bukkit.inventory.InventoryHolder; -// CraftBukkit end -import co.aikar.timings.MinecraftTimings; // Paper -import co.aikar.timings.Timing; // Paper - -public abstract class TileEntity implements KeyedObject { // Paper - - public Timing tickTimer = MinecraftTimings.getTileEntityTimings(this); // Paper - // CraftBukkit start - data containers - private static final CraftPersistentDataTypeRegistry DATA_TYPE_REGISTRY = new CraftPersistentDataTypeRegistry(); - public CraftPersistentDataContainer persistentDataContainer; - // CraftBukkit end - private static final Logger LOGGER = LogManager.getLogger(); - boolean isLoadingStructure = false; // Paper - private final TileEntityTypes b; public TileEntityTypes getTileEntityType() { return b; } // Paper - OBFHELPER - @Nullable - protected World world; - protected BlockPosition position; - protected boolean f; - @Nullable - private IBlockData c; - private boolean g; - - public TileEntity(TileEntityTypes tileentitytypes) { - this.position = BlockPosition.ZERO; - this.b = tileentitytypes; - } - - // Paper start - private String tileEntityKeyString = null; - private MinecraftKey tileEntityKey = null; - - @Override - public MinecraftKey getMinecraftKey() { - if (tileEntityKey == null) { - tileEntityKey = TileEntityTypes.a(this.getTileEntityType()); - tileEntityKeyString = tileEntityKey != null ? tileEntityKey.toString() : null; - } - return tileEntityKey; - } - - @Override - public String getMinecraftKeyString() { - getMinecraftKey(); // Try to load if it doesn't exists. - return tileEntityKeyString; - } - - private java.lang.ref.WeakReference currentChunk = null; - public Chunk getCurrentChunk() { - final Chunk chunk = currentChunk != null ? currentChunk.get() : null; - return chunk != null && chunk.isLoaded() ? chunk : null; - } - public void setCurrentChunk(Chunk chunk) { - this.currentChunk = chunk != null ? new java.lang.ref.WeakReference<>(chunk) : null; - } - static boolean IGNORE_TILE_UPDATES = false; - // Paper end - - @Nullable - public World getWorld() { - return this.world; - } - - public void setWorld(World world) { - this.world = world; - } - - public boolean hasWorld() { - return this.world != null; - } - - public void load(NBTTagCompound nbttagcompound) { - this.position = new BlockPosition(nbttagcompound.getInt("x"), nbttagcompound.getInt("y"), nbttagcompound.getInt("z")); - // CraftBukkit start - read container - this.persistentDataContainer = new CraftPersistentDataContainer(DATA_TYPE_REGISTRY); - - NBTTagCompound persistentDataTag = nbttagcompound.getCompound("PublicBukkitValues"); - if (persistentDataTag != null) { - this.persistentDataContainer.putAll(persistentDataTag); - } - // CraftBukkit end - } - - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - return this.d(nbttagcompound); - } - - private NBTTagCompound d(NBTTagCompound nbttagcompound) { - MinecraftKey minecraftkey = TileEntityTypes.a(this.q()); - - if (minecraftkey == null) { - throw new RuntimeException(this.getClass() + " is missing a mapping! This is a bug!"); - } else { - nbttagcompound.setString("id", minecraftkey.toString()); - nbttagcompound.setInt("x", this.position.getX()); - nbttagcompound.setInt("y", this.position.getY()); - nbttagcompound.setInt("z", this.position.getZ()); - // CraftBukkit start - store container - if (this.persistentDataContainer != null && !this.persistentDataContainer.isEmpty()) { - nbttagcompound.set("PublicBukkitValues", this.persistentDataContainer.toTagCompound()); - } - // CraftBukkit end - return nbttagcompound; - } - } - - @Nullable - public static TileEntity create(NBTTagCompound nbttagcompound) { - String s = nbttagcompound.getString("id"); - - return (TileEntity) IRegistry.BLOCK_ENTITY_TYPE.getOptional(new MinecraftKey(s)).map((tileentitytypes) -> { - try { - return tileentitytypes.a(); - } catch (Throwable throwable) { - TileEntity.LOGGER.error("Failed to create block entity {}", s, throwable); - return null; - } - }).map((tileentity) -> { - try { - tileentity.load(nbttagcompound); - return tileentity; - } catch (Throwable throwable) { - TileEntity.LOGGER.error("Failed to load data for block entity {}", s, throwable); - return null; - } - }).orElseGet(() -> { - TileEntity.LOGGER.warn("Skipping BlockEntity with id {}", s); - return null; - }); - } - - public void update() { - if (this.world != null) { - if (IGNORE_TILE_UPDATES) return; // Paper - this.c = this.world.getType(this.position); - this.world.b(this.position, this); - if (!this.c.isAir()) { - this.world.updateAdjacentComparators(this.position, this.c.getBlock()); - } - } - - } - - public BlockPosition getPosition() { - return this.position; - } - - public IBlockData getBlock() { - if (this.c == null) { - this.c = this.world.getType(this.position); - } - - return this.c; - } - - @Nullable - public PacketPlayOutTileEntityData getUpdatePacket() { - return null; - } - - public NBTTagCompound b() { - return this.d(new NBTTagCompound()); - } - - public boolean isRemoved() { - return this.f; - } - - public void V_() { - this.f = true; - } - - public void n() { - this.f = false; - } - - public boolean setProperty(int i, int j) { - return false; - } - - public void invalidateBlockCache() { - this.c = null; - } - - public void a(CrashReportSystemDetails crashreportsystemdetails) { - crashreportsystemdetails.a("Name", () -> { - return IRegistry.BLOCK_ENTITY_TYPE.getKey(this.q()) + " // " + this.getClass().getCanonicalName(); - }); - if (this.world != null) { - // Paper start - Prevent TileEntity and Entity crashes - IBlockData block = this.getBlock(); - if (block != null) { - CrashReportSystemDetails.a(crashreportsystemdetails, this.position, block); - } - // Paper end - CrashReportSystemDetails.a(crashreportsystemdetails, this.position, this.world.getType(this.position)); - } - } - - public void setPosition(BlockPosition blockposition) { - this.position = blockposition.immutableCopy(); - } - - public boolean isFilteredNBT() { - return false; - } - - public void a(EnumBlockRotation enumblockrotation) {} - - public void a(EnumBlockMirror enumblockmirror) {} - - public TileEntityTypes q() { - return this.b; - } - - public void r() { - if (!this.g) { - this.g = true; - TileEntity.LOGGER.warn("Block entity invalid: {} @ {}", new Supplier[]{() -> { - return IRegistry.BLOCK_ENTITY_TYPE.getKey(this.q()); - }, this::getPosition}); - } - } - - // CraftBukkit start - add method - // Paper start - public InventoryHolder getOwner() { - return getOwner(true); - } - public InventoryHolder getOwner(boolean useSnapshot) { - // Paper end - 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(useSnapshot); // Paper - if (state instanceof InventoryHolder) return (InventoryHolder) state; - return null; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/TileEntityBanner.java b/src/main/java/net/minecraft/server/TileEntityBanner.java deleted file mode 100644 index bfc58a775..000000000 --- a/src/main/java/net/minecraft/server/TileEntityBanner.java +++ /dev/null @@ -1,121 +0,0 @@ -package net.minecraft.server; - -import java.util.List; -import java.util.function.Supplier; -import javax.annotation.Nullable; - -public class TileEntityBanner extends TileEntity implements INamableTileEntity { - - private IChatBaseComponent a; - public EnumColor color; - public NBTTagList patterns; - private boolean g; - private List h; - private List i; - private String j; - - public TileEntityBanner() { - super(TileEntityTypes.BANNER); - this.color = EnumColor.WHITE; - } - - public TileEntityBanner(EnumColor enumcolor) { - this(); - this.color = enumcolor; - } - - @Override - public IChatBaseComponent getDisplayName() { - return (IChatBaseComponent) (this.a != null ? this.a : new ChatMessage("block.minecraft.banner", new Object[0])); - } - - @Nullable - @Override - public IChatBaseComponent getCustomName() { - return this.a; - } - - public void a(IChatBaseComponent ichatbasecomponent) { - this.a = ichatbasecomponent; - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - if (this.patterns != null) { - nbttagcompound.set("Patterns", this.patterns); - } - - if (this.a != null) { - nbttagcompound.setString("CustomName", IChatBaseComponent.ChatSerializer.a(this.a)); - } - - return nbttagcompound; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - if (nbttagcompound.hasKeyOfType("CustomName", 8)) { - this.a = MCUtil.getBaseComponentFromNbt("CustomName", nbttagcompound); // Paper - Catch ParseException - } - - if (this.hasWorld()) { - this.color = ((BlockBannerAbstract) this.getBlock().getBlock()).getColor(); - } else { - this.color = null; - } - - this.patterns = nbttagcompound.getList("Patterns", 10); - // CraftBukkit start - while (this.patterns.size() > 20) { - this.patterns.remove(20); - } - // CraftBukkit end - this.h = null; - this.i = null; - this.j = null; - this.g = true; - } - - @Nullable - @Override - public PacketPlayOutTileEntityData getUpdatePacket() { - return new PacketPlayOutTileEntityData(this.position, 6, this.b()); - } - - @Override - public NBTTagCompound b() { - return this.save(new NBTTagCompound()); - } - - public static int a(ItemStack itemstack) { - NBTTagCompound nbttagcompound = itemstack.b("BlockEntityTag"); - - return nbttagcompound != null && nbttagcompound.hasKey("Patterns") ? nbttagcompound.getList("Patterns", 10).size() : 0; - } - - public static void b(ItemStack itemstack) { - NBTTagCompound nbttagcompound = itemstack.b("BlockEntityTag"); - - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("Patterns", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("Patterns", 10); - - if (!nbttaglist.isEmpty()) { - nbttaglist.remove(nbttaglist.size() - 1); - if (nbttaglist.isEmpty()) { - itemstack.removeTag("BlockEntityTag"); - } - - } - } - } - - public EnumColor a(Supplier supplier) { - if (this.color == null) { - this.color = ((BlockBannerAbstract) ((IBlockData) supplier.get()).getBlock()).getColor(); - } - - return this.color; - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityBarrel.java b/src/main/java/net/minecraft/server/TileEntityBarrel.java deleted file mode 100644 index 5d80ec801..000000000 --- a/src/main/java/net/minecraft/server/TileEntityBarrel.java +++ /dev/null @@ -1,228 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; - -// CraftBukkit start -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.bukkit.Location; -import org.bukkit.block.Barrel; -import org.bukkit.block.Lectern; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.InventoryHolder; -// CraftBukkit end - -public class TileEntityBarrel extends TileEntityLootable { - - // CraftBukkit start - add fields and methods - public List transaction = new ArrayList<>(); - private int maxStack = MAX_STACK; - - @Override - public List 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 int getMaxStackSize() { - return maxStack; - } - - @Override - public void setMaxStackSize(int i) { - maxStack = i; - } - // CraftBukkit end - private NonNullList items; - private int b; - - private TileEntityBarrel(TileEntityTypes tileentitytypes) { - super(tileentitytypes); - this.items = NonNullList.a(27, ItemStack.a); - } - - public TileEntityBarrel() { - this(TileEntityTypes.BARREL); - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - if (!this.e(nbttagcompound)) { - ContainerUtil.a(nbttagcompound, this.items); - } - - return nbttagcompound; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.items = NonNullList.a(this.getSize(), ItemStack.a); - if (!this.d(nbttagcompound)) { - ContainerUtil.b(nbttagcompound, this.items); - } - - } - - @Override - public int getSize() { - return 27; - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public ItemStack getItem(int i) { - return (ItemStack) this.items.get(i); - } - - @Override - public ItemStack splitStack(int i, int j) { - return ContainerUtil.a(this.items, i, j); - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - return ContainerUtil.a(this.items, i); - } - - @Override - public void setItem(int i, ItemStack itemstack) { - this.items.set(i, itemstack); - if (itemstack.getCount() > this.getMaxStackSize()) { - itemstack.setCount(this.getMaxStackSize()); - } - - } - - @Override - public void clear() { - this.items.clear(); - } - - @Override - protected NonNullList f() { - return this.items; - } - - @Override - protected void a(NonNullList nonnulllist) { - this.items = nonnulllist; - } - - @Override - protected IChatBaseComponent getContainerName() { - return new ChatMessage("container.barrel", new Object[0]); - } - - @Override - protected Container createContainer(int i, PlayerInventory playerinventory) { - return ContainerChest.a(i, playerinventory, this); - } - - @Override - public void startOpen(EntityHuman entityhuman) { - if (!entityhuman.isSpectator()) { - if (this.b < 0) { - this.b = 0; - } - - ++this.b; - IBlockData iblockdata = this.getBlock(); - boolean flag = (Boolean) iblockdata.get(BlockBarrel.b); - - if (!flag) { - this.a(iblockdata, SoundEffects.BLOCK_BARREL_OPEN); - this.a(iblockdata, true); - } - - this.s(); - } - - } - - private void s() { - this.world.getBlockTickList().a(this.getPosition(), this.getBlock().getBlock(), 5); - } - - public void h() { - int i = this.position.getX(); - int j = this.position.getY(); - int k = this.position.getZ(); - - this.b = TileEntityChest.a(this.world, this, i, j, k); - if (this.b > 0) { - this.s(); - } else { - IBlockData iblockdata = this.getBlock(); - - if (iblockdata.getBlock() != Blocks.BARREL) { - this.V_(); - return; - } - - boolean flag = (Boolean) iblockdata.get(BlockBarrel.b); - - if (flag) { - this.a(iblockdata, SoundEffects.BLOCK_BARREL_CLOSE); - this.a(iblockdata, false); - } - } - - } - - @Override - public void closeContainer(EntityHuman entityhuman) { - if (!entityhuman.isSpectator()) { - --this.b; - } - - } - - private void a(IBlockData iblockdata, boolean flag) { - this.world.setTypeAndData(this.getPosition(), (IBlockData) iblockdata.set(BlockBarrel.b, flag), 3); - } - - private void a(IBlockData iblockdata, SoundEffect soundeffect) { - BaseBlockPosition baseblockposition = ((EnumDirection) iblockdata.get(BlockBarrel.a)).n(); - double d0 = (double) this.position.getX() + 0.5D + (double) baseblockposition.getX() / 2.0D; - double d1 = (double) this.position.getY() + 0.5D + (double) baseblockposition.getY() / 2.0D; - double d2 = (double) this.position.getZ() + 0.5D + (double) baseblockposition.getZ() / 2.0D; - - this.world.playSound((EntityHuman) null, d0, d1, d2, soundeffect, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityBeacon.java b/src/main/java/net/minecraft/server/TileEntityBeacon.java deleted file mode 100644 index e510234db..000000000 --- a/src/main/java/net/minecraft/server/TileEntityBeacon.java +++ /dev/null @@ -1,391 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.entity.HumanEntity; -import org.bukkit.potion.PotionEffect; -// CraftBukkit end -// Paper start -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.entity.Player; -import com.destroystokyo.paper.event.block.BeaconEffectEvent; -// Paper end - -public class TileEntityBeacon extends TileEntity implements ITileInventory, ITickable { - - public static final MobEffectList[][] a = new MobEffectList[][]{{MobEffects.FASTER_MOVEMENT, MobEffects.FASTER_DIG}, {MobEffects.RESISTANCE, MobEffects.JUMP}, {MobEffects.INCREASE_DAMAGE}, {MobEffects.REGENERATION}}; - private static final Set b = (Set) Arrays.stream(TileEntityBeacon.a).flatMap(Arrays::stream).collect(Collectors.toSet()); - private List c = Lists.newArrayList(); - private List g = Lists.newArrayList(); - public int levels = 0; - private int i = -1; - @Nullable - public MobEffectList primaryEffect; - @Nullable - public MobEffectList secondaryEffect; - @Nullable - public IChatBaseComponent customName; - public ChestLock chestLock; - private final IContainerProperties containerProperties; - // CraftBukkit start - add fields and methods - public PotionEffect getPrimaryEffect() { - return (this.primaryEffect != null) ? CraftPotionUtil.toBukkit(new MobEffect(this.primaryEffect, getLevel(), getAmplification(), true, true)) : null; - } - - public PotionEffect getSecondaryEffect() { - return (hasSecondaryEffect()) ? CraftPotionUtil.toBukkit(new MobEffect(this.secondaryEffect, getLevel(), getAmplification(), true, true)) : null; - } - // CraftBukkit end - - public TileEntityBeacon() { - super(TileEntityTypes.BEACON); - this.chestLock = ChestLock.a; - this.containerProperties = new IContainerProperties() { - @Override - public int getProperty(int i) { - switch (i) { - case 0: - return TileEntityBeacon.this.levels; - case 1: - return MobEffectList.getId(TileEntityBeacon.this.primaryEffect); - case 2: - return MobEffectList.getId(TileEntityBeacon.this.secondaryEffect); - default: - return 0; - } - } - - @Override - public void setProperty(int i, int j) { - switch (i) { - case 0: - TileEntityBeacon.this.levels = j; - break; - case 1: - if (!TileEntityBeacon.this.world.isClientSide && !TileEntityBeacon.this.c.isEmpty()) { - TileEntityBeacon.this.a(SoundEffects.BLOCK_BEACON_POWER_SELECT); - } - - TileEntityBeacon.this.primaryEffect = TileEntityBeacon.b(j); - break; - case 2: - TileEntityBeacon.this.secondaryEffect = TileEntityBeacon.b(j); - } - - } - - @Override - public int a() { - return 3; - } - }; - } - - @Override - public void tick() { - int i = this.position.getX(); - int j = this.position.getY(); - int k = this.position.getZ(); - BlockPosition blockposition; - - if (this.i < j) { - blockposition = this.position; - this.g = Lists.newArrayList(); - this.i = blockposition.getY() - 1; - } else { - blockposition = new BlockPosition(i, this.i + 1, k); - } - - TileEntityBeacon.BeaconColorTracker tileentitybeacon_beaconcolortracker = this.g.isEmpty() ? null : (TileEntityBeacon.BeaconColorTracker) this.g.get(this.g.size() - 1); - int l = this.world.a(HeightMap.Type.WORLD_SURFACE, i, k); - - int i1; - - for (i1 = 0; i1 < 10 && blockposition.getY() <= l; ++i1) { - IBlockData iblockdata = this.world.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (block instanceof IBeaconBeam) { - float[] afloat = ((IBeaconBeam) block).a().d(); - - if (this.g.size() <= 1) { - tileentitybeacon_beaconcolortracker = new TileEntityBeacon.BeaconColorTracker(afloat); - this.g.add(tileentitybeacon_beaconcolortracker); - } else if (tileentitybeacon_beaconcolortracker != null) { - if (Arrays.equals(afloat, tileentitybeacon_beaconcolortracker.a)) { - tileentitybeacon_beaconcolortracker.a(); - } else { - tileentitybeacon_beaconcolortracker = new TileEntityBeacon.BeaconColorTracker(new float[]{(tileentitybeacon_beaconcolortracker.a[0] + afloat[0]) / 2.0F, (tileentitybeacon_beaconcolortracker.a[1] + afloat[1]) / 2.0F, (tileentitybeacon_beaconcolortracker.a[2] + afloat[2]) / 2.0F}); - this.g.add(tileentitybeacon_beaconcolortracker); - } - } - } else { - if (tileentitybeacon_beaconcolortracker == null || iblockdata.b((IBlockAccess) this.world, blockposition) >= 15 && block != Blocks.BEDROCK) { - this.g.clear(); - this.i = l; - break; - } - - tileentitybeacon_beaconcolortracker.a(); - } - - blockposition = blockposition.up(); - ++this.i; - } - - i1 = this.levels; - if (this.world.getTime() % 80L == 0L) { - if (!this.c.isEmpty()) { - this.a(i, j, k); - } - - if (this.levels > 0 && !this.c.isEmpty()) { - this.applyEffects(); - this.a(SoundEffects.BLOCK_BEACON_AMBIENT); - } - } - - if (this.i >= l) { - this.i = -1; - boolean flag = i1 > 0; - - this.c = this.g; - if (!this.world.isClientSide) { - boolean flag1 = this.levels > 0; - - if (!flag && flag1) { - this.a(SoundEffects.BLOCK_BEACON_ACTIVATE); - Iterator iterator = this.world.a(EntityPlayer.class, (new AxisAlignedBB((double) i, (double) j, (double) k, (double) i, (double) (j - 4), (double) k)).grow(10.0D, 5.0D, 10.0D)).iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - CriterionTriggers.l.a(entityplayer, this); - } - } else if (flag && !flag1) { - this.a(SoundEffects.BLOCK_BEACON_DEACTIVATE); - } - } - } - - } - - private void a(int i, int j, int k) { - this.levels = 0; - - for (int l = 1; l <= 4; this.levels = l++) { - int i1 = j - l; - - if (i1 < 0) { - break; - } - - boolean flag = true; - - for (int j1 = i - l; j1 <= i + l && flag; ++j1) { - for (int k1 = k - l; k1 <= k + l; ++k1) { - Block block = this.world.getType(new BlockPosition(j1, i1, k1)).getBlock(); - - if (block != Blocks.EMERALD_BLOCK && block != Blocks.GOLD_BLOCK && block != Blocks.DIAMOND_BLOCK && block != Blocks.IRON_BLOCK) { - flag = false; - break; - } - } - } - - if (!flag) { - break; - } - } - - } - - @Override - public void V_() { - this.a(SoundEffects.BLOCK_BEACON_DEACTIVATE); - super.V_(); - } - - // CraftBukkit start - split into components - private byte getAmplification() { - { - byte b0 = 0; - - if (this.levels >= 4 && this.primaryEffect == this.secondaryEffect) { - b0 = 1; - } - - return b0; - } - } - - private int getLevel() { - { - int i = (9 + this.levels * 2) * 20; - return i; - } - } - - public List getHumansInRange() { - { - double d0 = (double) (this.levels * 10 + 10); - - AxisAlignedBB axisalignedbb = (new AxisAlignedBB(this.position)).g(d0).b(0.0D, (double) this.world.getBuildHeight(), 0.0D); - List list = this.world.a(EntityHuman.class, axisalignedbb); - - return list; - } - } - - private void applyEffect(List list, MobEffectList effects, int i, int b0) { - // Paper - BeaconEffectEvent - applyEffect(list, effects, i, b0, true); - } - - private void applyEffect(List list, MobEffectList effects, int i, int b0, boolean isPrimary) { - // Paper - BeaconEffectEvent - { - Iterator iterator = list.iterator(); - - EntityHuman entityhuman; - - // Paper start - BeaconEffectEvent - org.bukkit.block.Block block = world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()); - PotionEffect effect = CraftPotionUtil.toBukkit(new MobEffect(effects, i, b0, true, true)); - // Paper end - - while (iterator.hasNext()) { - entityhuman = (EntityHuman) iterator.next(); - - // Paper start - BeaconEffectEvent - BeaconEffectEvent event = new BeaconEffectEvent(block, effect, (Player) entityhuman.getBukkitEntity(), isPrimary); - if (CraftEventFactory.callEvent(event).isCancelled()) continue; - PotionEffect eventEffect = event.getEffect(); - entityhuman.addEffect(new MobEffect(MobEffectList.fromId(eventEffect.getType().getId()), eventEffect.getDuration(), eventEffect.getAmplifier(), true, true), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.BEACON); - // Paper end - } - } - } - - private boolean hasSecondaryEffect() { - { - if (this.levels >= 4 && this.primaryEffect != this.secondaryEffect && this.secondaryEffect != null) { - return true; - } - - return false; - } - } - - private void applyEffects() { - if (!this.world.isClientSide && this.primaryEffect != null) { - double d0 = (double) (this.levels * 10 + 10); - byte b0 = getAmplification(); - - int i = getLevel(); - List list = getHumansInRange(); - - applyEffect(list, this.primaryEffect, i, b0, true); // Paper - BeaconEffectEvent - - if (hasSecondaryEffect()) { - applyEffect(list, this.secondaryEffect, i, 0, false); // Paper - BeaconEffectEvent - } - } - - } - // CraftBukkit end - - public void a(SoundEffect soundeffect) { - this.world.playSound((EntityHuman) null, this.position, soundeffect, SoundCategory.BLOCKS, 1.0F, 1.0F); - } - - public int h() { - return this.levels; - } - - @Nullable - @Override - public PacketPlayOutTileEntityData getUpdatePacket() { - return new PacketPlayOutTileEntityData(this.position, 3, this.b()); - } - - @Override - public NBTTagCompound b() { - return this.save(new NBTTagCompound()); - } - - @Nullable - private static MobEffectList b(int i) { - MobEffectList mobeffectlist = MobEffectList.fromId(i); - - return TileEntityBeacon.b.contains(mobeffectlist) ? mobeffectlist : null; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - // Craftbukkit start - persist manually set non-default beacon effects (SPIGOT-3598) - this.primaryEffect = MobEffectList.fromId(nbttagcompound.getInt("Primary")); - this.secondaryEffect = MobEffectList.fromId(nbttagcompound.getInt("Secondary")); - this.levels = nbttagcompound.getInt("Levels"); // SPIGOT-5053, use where available - // Craftbukkit end - if (nbttagcompound.hasKeyOfType("CustomName", 8)) { - this.customName = IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("CustomName")); - } - - this.chestLock = ChestLock.b(nbttagcompound); - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - nbttagcompound.setInt("Primary", MobEffectList.getId(this.primaryEffect)); - nbttagcompound.setInt("Secondary", MobEffectList.getId(this.secondaryEffect)); - nbttagcompound.setInt("Levels", this.levels); - if (this.customName != null) { - nbttagcompound.setString("CustomName", IChatBaseComponent.ChatSerializer.a(this.customName)); - } - - this.chestLock.a(nbttagcompound); - return nbttagcompound; - } - - public void setCustomName(@Nullable IChatBaseComponent ichatbasecomponent) { - this.customName = ichatbasecomponent; - } - - @Nullable - @Override - public Container createMenu(int i, PlayerInventory playerinventory, EntityHuman entityhuman) { - return TileEntityContainer.a(entityhuman, this.chestLock, this.getScoreboardDisplayName()) ? new ContainerBeacon(i, playerinventory, this.containerProperties, ContainerAccess.at(this.world, this.getPosition())) : null; - } - - @Override - public IChatBaseComponent getScoreboardDisplayName() { - return (IChatBaseComponent) (this.customName != null ? this.customName : new ChatMessage("container.beacon", new Object[0])); - } - - public static class BeaconColorTracker { - - private final float[] a; - private int b; - - public BeaconColorTracker(float[] afloat) { - this.a = afloat; - this.b = 1; - } - - protected void a() { - ++this.b; - } - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityBrewingStand.java b/src/main/java/net/minecraft/server/TileEntityBrewingStand.java deleted file mode 100644 index f96da4ee4..000000000 --- a/src/main/java/net/minecraft/server/TileEntityBrewingStand.java +++ /dev/null @@ -1,340 +0,0 @@ -package net.minecraft.server; - -import java.util.Arrays; -import java.util.Iterator; -import javax.annotation.Nullable; - -// CraftBukkit start -import java.util.List; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.inventory.BrewEvent; -import org.bukkit.event.inventory.BrewingStandFuelEvent; -import org.bukkit.inventory.InventoryHolder; -// CraftBukkit end - -public class TileEntityBrewingStand extends TileEntityContainer implements IWorldInventory, ITickable { - - private static final int[] b = new int[]{3}; - private static final int[] c = new int[]{0, 1, 2, 3}; - private static final int[] g = new int[]{0, 1, 2, 4}; - private NonNullList items; - public int brewTime; - private boolean[] j; - private Item k; - public int fuelLevel; - protected final IContainerProperties a; - // CraftBukkit start - add fields and methods - private int lastTick = MinecraftServer.currentTick; - public List transaction = new java.util.ArrayList(); - private int maxStack = 64; - - public void onOpen(CraftHumanEntity who) { - transaction.add(who); - } - - public void onClose(CraftHumanEntity who) { - transaction.remove(who); - } - - public List getViewers() { - return transaction; - } - - public List getContents() { - return this.items; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - // CraftBukkit end - - public TileEntityBrewingStand() { - super(TileEntityTypes.BREWING_STAND); - this.items = NonNullList.a(5, ItemStack.a); - this.a = new IContainerProperties() { - @Override - public int getProperty(int i) { - switch (i) { - case 0: - return TileEntityBrewingStand.this.brewTime; - case 1: - return TileEntityBrewingStand.this.fuelLevel; - default: - return 0; - } - } - - @Override - public void setProperty(int i, int j) { - switch (i) { - case 0: - TileEntityBrewingStand.this.brewTime = j; - break; - case 1: - TileEntityBrewingStand.this.fuelLevel = j; - } - - } - - @Override - public int a() { - return 2; - } - }; - } - - @Override - protected IChatBaseComponent getContainerName() { - return new ChatMessage("container.brewing", new Object[0]); - } - - @Override - public int getSize() { - return this.items.size(); - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public void tick() { - ItemStack itemstack = (ItemStack) this.items.get(4); - - if (this.fuelLevel <= 0 && itemstack.getItem() == Items.BLAZE_POWDER) { - // CraftBukkit start - BrewingStandFuelEvent event = new BrewingStandFuelEvent(world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), CraftItemStack.asCraftMirror(itemstack), 20); - this.world.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - - this.fuelLevel = event.getFuelPower(); - if (this.fuelLevel > 0 && event.isConsuming()) { - itemstack.subtract(1); - } - // CraftBukkit end - this.update(); - } - - boolean flag = this.h(); - boolean flag1 = this.brewTime > 0; - ItemStack itemstack1 = (ItemStack) this.items.get(3); - - // CraftBukkit start - Use wall time instead of ticks for brewing - int elapsedTicks = MinecraftServer.currentTick - this.lastTick; - this.lastTick = MinecraftServer.currentTick; - - if (flag1) { - this.brewTime -= elapsedTicks; - boolean flag2 = this.brewTime <= 0; // == -> <= - // CraftBukkit end - - if (flag2 && flag) { - this.s(); - this.update(); - } else if (!flag) { - this.brewTime = 0; - this.update(); - } else if (this.k != itemstack1.getItem()) { - this.brewTime = 0; - this.update(); - } - } else if (flag && this.fuelLevel > 0) { - --this.fuelLevel; - this.brewTime = 400; - this.k = itemstack1.getItem(); - this.update(); - } - - if (!this.world.isClientSide) { - boolean[] aboolean = this.f(); - - if (!Arrays.equals(aboolean, this.j)) { - this.j = 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) iblockdata.set(BlockBrewingStand.HAS_BOTTLE[i], aboolean[i]); - } - - this.world.setTypeAndData(this.position, iblockdata, 2); - } - } - - } - - public boolean[] f() { - boolean[] aboolean = new boolean[3]; - - for (int i = 0; i < 3; ++i) { - if (!((ItemStack) this.items.get(i)).isEmpty()) { - aboolean[i] = true; - } - } - - return aboolean; - } - - private boolean h() { - ItemStack itemstack = (ItemStack) this.items.get(3); - - if (itemstack.isEmpty()) { - return false; - } else if (!PotionBrewer.a(itemstack)) { - return false; - } else { - for (int i = 0; i < 3; ++i) { - ItemStack itemstack1 = (ItemStack) this.items.get(i); - - if (!itemstack1.isEmpty() && PotionBrewer.a(itemstack1, itemstack)) { - return true; - } - } - - return false; - } - } - - private void s() { - ItemStack itemstack = (ItemStack) this.items.get(3); - // CraftBukkit start - InventoryHolder owner = this.getOwner(); - if (owner != null) { - BrewEvent event = new BrewEvent(world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), (org.bukkit.inventory.BrewerInventory) owner.getInventory(), this.fuelLevel); - org.bukkit.Bukkit.getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - } - // CraftBukkit end - - for (int i = 0; i < 3; ++i) { - this.items.set(i, PotionBrewer.d(itemstack, (ItemStack) this.items.get(i))); - } - - itemstack.subtract(1); - BlockPosition blockposition = this.getPosition(); - - if (itemstack.getItem().o()) { - ItemStack itemstack1 = new ItemStack(itemstack.getItem().n()); - - if (itemstack.isEmpty()) { - itemstack = itemstack1; - } else if (!this.world.isClientSide) { - InventoryUtils.dropItem(this.world, (double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), itemstack1); - } - } - - this.items.set(3, itemstack); - this.world.triggerEffect(1035, blockposition, 0); - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.items = NonNullList.a(this.getSize(), ItemStack.a); - ContainerUtil.b(nbttagcompound, this.items); - this.brewTime = nbttagcompound.getShort("BrewTime"); - this.fuelLevel = nbttagcompound.getByte("Fuel"); - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - nbttagcompound.setShort("BrewTime", (short) this.brewTime); - ContainerUtil.a(nbttagcompound, this.items); - nbttagcompound.setByte("Fuel", (byte) this.fuelLevel); - return nbttagcompound; - } - - @Override - public ItemStack getItem(int i) { - return i >= 0 && i < this.items.size() ? (ItemStack) this.items.get(i) : ItemStack.a; - } - - @Override - public ItemStack splitStack(int i, int j) { - return ContainerUtil.a(this.items, i, j); - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - return ContainerUtil.a(this.items, i); - } - - @Override - public void setItem(int i, ItemStack itemstack) { - if (i >= 0 && i < this.items.size()) { - this.items.set(i, itemstack); - } - - } - - @Override - public boolean a(EntityHuman entityhuman) { - return this.world.getTileEntity(this.position) != this ? false : entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; - } - - @Override - public boolean b(int i, ItemStack itemstack) { - if (i == 3) { - return PotionBrewer.a(itemstack); - } else { - Item item = itemstack.getItem(); - - return i == 4 ? item == Items.BLAZE_POWDER : (item == Items.POTION || item == Items.SPLASH_POTION || item == Items.LINGERING_POTION || item == Items.GLASS_BOTTLE) && this.getItem(i).isEmpty(); - } - } - - @Override - public int[] getSlotsForFace(EnumDirection enumdirection) { - return enumdirection == EnumDirection.UP ? TileEntityBrewingStand.b : (enumdirection == EnumDirection.DOWN ? TileEntityBrewingStand.c : TileEntityBrewingStand.g); - } - - @Override - public boolean canPlaceItemThroughFace(int i, ItemStack itemstack, @Nullable EnumDirection enumdirection) { - return this.b(i, itemstack); - } - - @Override - public boolean canTakeItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { - return i == 3 ? itemstack.getItem() == Items.GLASS_BOTTLE : true; - } - - @Override - public void clear() { - this.items.clear(); - } - - @Override - protected Container createContainer(int i, PlayerInventory playerinventory) { - return new ContainerBrewingStand(i, playerinventory, this, this.a); - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityCampfire.java b/src/main/java/net/minecraft/server/TileEntityCampfire.java deleted file mode 100644 index 2317adde4..000000000 --- a/src/main/java/net/minecraft/server/TileEntityCampfire.java +++ /dev/null @@ -1,204 +0,0 @@ -package net.minecraft.server; - -import java.util.Optional; -import java.util.Random; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.event.block.BlockCookEvent; -// CraftBukkit end - -public class TileEntityCampfire extends TileEntity implements Clearable, ITickable { - - private final NonNullList items; - public final int[] cookingTimes; - public final int[] cookingTotalTimes; - - public TileEntityCampfire() { - super(TileEntityTypes.CAMPFIRE); - this.items = NonNullList.a(4, ItemStack.a); - this.cookingTimes = new int[4]; - this.cookingTotalTimes = new int[4]; - } - - @Override - public void tick() { - boolean flag = (Boolean) this.getBlock().get(BlockCampfire.b); - boolean flag1 = this.world.isClientSide; - - if (flag1) { - if (flag) { - this.s(); - } - - } else { - if (flag) { - this.h(); - } else { - for (int i = 0; i < this.items.size(); ++i) { - if (this.cookingTimes[i] > 0) { - this.cookingTimes[i] = MathHelper.clamp(this.cookingTimes[i] - 2, 0, this.cookingTotalTimes[i]); - } - } - } - - } - } - - private void h() { - for (int i = 0; i < this.items.size(); ++i) { - ItemStack itemstack = (ItemStack) this.items.get(i); - - if (!itemstack.isEmpty()) { - int j = this.cookingTimes[i]++; - - if (this.cookingTimes[i] >= this.cookingTotalTimes[i]) { - InventorySubcontainer inventorysubcontainer = new InventorySubcontainer(new ItemStack[]{itemstack}); - ItemStack itemstack1 = (ItemStack) this.world.getCraftingManager().craft(Recipes.CAMPFIRE_COOKING, inventorysubcontainer, this.world).map((recipecampfire) -> { - return recipecampfire.a(inventorysubcontainer); - }).orElse(itemstack); - BlockPosition blockposition = this.getPosition(); - - // CraftBukkit start - fire BlockCookEvent - CraftItemStack source = CraftItemStack.asCraftMirror(itemstack); - org.bukkit.inventory.ItemStack result = CraftItemStack.asBukkitCopy(itemstack1); - - BlockCookEvent blockCookEvent = new BlockCookEvent(CraftBlock.at(this.world, this.position), source, result); - this.world.getServer().getPluginManager().callEvent(blockCookEvent); - - if (blockCookEvent.isCancelled()) { - return; - } - - result = blockCookEvent.getResult(); - itemstack1 = CraftItemStack.asNMSCopy(result); - // CraftBukkit end - InventoryUtils.dropItem(this.world, (double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), itemstack1); - this.items.set(i, ItemStack.a); - this.t(); - } - } - } - - } - - private void s() { - World world = this.getWorld(); - - if (world != null) { - BlockPosition blockposition = this.getPosition(); - Random random = world.random; - int i; - - if (random.nextFloat() < 0.11F) { - for (i = 0; i < random.nextInt(2) + 2; ++i) { - BlockCampfire.a(world, blockposition, (Boolean) this.getBlock().get(BlockCampfire.c), false); - } - } - - i = ((EnumDirection) this.getBlock().get(BlockCampfire.e)).get2DRotationValue(); - - for (int j = 0; j < this.items.size(); ++j) { - if (!((ItemStack) this.items.get(j)).isEmpty() && random.nextFloat() < 0.2F) { - EnumDirection enumdirection = EnumDirection.fromType2(Math.floorMod(j + i, 4)); - float f = 0.3125F; - double d0 = (double) blockposition.getX() + 0.5D - (double) ((float) enumdirection.getAdjacentX() * 0.3125F) + (double) ((float) enumdirection.e().getAdjacentX() * 0.3125F); - double d1 = (double) blockposition.getY() + 0.5D; - double d2 = (double) blockposition.getZ() + 0.5D - (double) ((float) enumdirection.getAdjacentZ() * 0.3125F) + (double) ((float) enumdirection.e().getAdjacentZ() * 0.3125F); - - for (int k = 0; k < 4; ++k) { - world.addParticle(Particles.SMOKE, d0, d1, d2, 0.0D, 5.0E-4D, 0.0D); - } - } - } - - } - } - - public NonNullList getItems() { - return this.items; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.items.clear(); - ContainerUtil.b(nbttagcompound, this.items); - int[] aint; - - if (nbttagcompound.hasKeyOfType("CookingTimes", 11)) { - aint = nbttagcompound.getIntArray("CookingTimes"); - System.arraycopy(aint, 0, this.cookingTimes, 0, Math.min(this.cookingTotalTimes.length, aint.length)); - } - - if (nbttagcompound.hasKeyOfType("CookingTotalTimes", 11)) { - aint = nbttagcompound.getIntArray("CookingTotalTimes"); - System.arraycopy(aint, 0, this.cookingTotalTimes, 0, Math.min(this.cookingTotalTimes.length, aint.length)); - } - - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - this.d(nbttagcompound); - nbttagcompound.setIntArray("CookingTimes", this.cookingTimes); - nbttagcompound.setIntArray("CookingTotalTimes", this.cookingTotalTimes); - return nbttagcompound; - } - - private NBTTagCompound d(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - ContainerUtil.a(nbttagcompound, this.items, true); - return nbttagcompound; - } - - @Nullable - @Override - public PacketPlayOutTileEntityData getUpdatePacket() { - return new PacketPlayOutTileEntityData(this.position, 13, this.b()); - } - - @Override - public NBTTagCompound b() { - return this.d(new NBTTagCompound()); - } - - public Optional a(ItemStack itemstack) { - return this.items.stream().noneMatch(ItemStack::isEmpty) ? Optional.empty() : this.world.getCraftingManager().craft(Recipes.CAMPFIRE_COOKING, new InventorySubcontainer(new ItemStack[]{itemstack}), this.world); - } - - public boolean a(ItemStack itemstack, int i) { - for (int j = 0; j < this.items.size(); ++j) { - ItemStack itemstack1 = (ItemStack) this.items.get(j); - - if (itemstack1.isEmpty()) { - this.cookingTotalTimes[j] = i; - this.cookingTimes[j] = 0; - this.items.set(j, itemstack.cloneAndSubtract(1)); - this.t(); - return true; - } - } - - return false; - } - - private void t() { - this.update(); - this.getWorld().notify(this.getPosition(), this.getBlock(), this.getBlock(), 3); - } - - @Override - public void clear() { - this.items.clear(); - } - - public void f() { - if (!this.getWorld().isClientSide) { - InventoryUtils.a(this.getWorld(), this.getPosition(), this.getItems()); - } - - this.t(); - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityChest.java b/src/main/java/net/minecraft/server/TileEntityChest.java deleted file mode 100644 index 4aa56e50e..000000000 --- a/src/main/java/net/minecraft/server/TileEntityChest.java +++ /dev/null @@ -1,315 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -// CraftBukkit end - -public class TileEntityChest extends TileEntityLootable { // Paper - Remove ITickable - - private NonNullList items; - protected float a; - protected float b; - protected int viewingCount; - private int j; - - // CraftBukkit start - add fields and methods - public List transaction = new java.util.ArrayList(); - private int maxStack = MAX_STACK; - - public List 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; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - // CraftBukkit end - - protected TileEntityChest(TileEntityTypes tileentitytypes) { - super(tileentitytypes); - this.items = NonNullList.a(27, ItemStack.a); - } - - public TileEntityChest() { - this(TileEntityTypes.CHEST); - } - - @Override - public int getSize() { - return 27; - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - protected IChatBaseComponent getContainerName() { - return new ChatMessage("container.chest", new Object[0]); - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.items = NonNullList.a(this.getSize(), ItemStack.a); - if (!this.d(nbttagcompound)) { - ContainerUtil.b(nbttagcompound, this.items); - } - - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - if (!this.e(nbttagcompound)) { - ContainerUtil.a(nbttagcompound, this.items); - } - - return nbttagcompound; - } - - public void tick() { - int i = this.position.getX(); - int j = this.position.getY(); - int k = this.position.getZ(); - - ++this.j; - } - - public void doOpenLogic() { - int i = this.position.getX(); - int j = this.position.getY(); - int k = this.position.getZ(); - - //this.viewingCount = a(this.world, this, this.j, i, j, k, this.viewingCount); // Paper - check is faulty given our logic is called before active container set - this.b = this.a; - float f = 0.1F; - - if (this.viewingCount > 0 && this.a == 0.0F) { - this.a(SoundEffects.BLOCK_CHEST_OPEN); - } - } - - public void doCloseLogic() { - if (this.viewingCount == 0 /* && this.a > 0.0F || this.viewingCount > 0 && this.a < 1.0F */) { // Paper - disable all but player count check - /* // Paper - disable animation stuff - float f1 = this.a; - - if (this.viewingCount > 0) { - this.a += 0.1F; - } else { - this.a -= 0.1F; - } - - if (this.a > 1.0F) { - this.a = 1.0F; - } - - float f2 = 0.5F; - - if (this.a < 0.5F && f1 >= 0.5F) { - */ - MCUtil.scheduleTask(10, () -> { - this.a(SoundEffects.BLOCK_CHEST_CLOSE); - }); - //} // Paper end - - if (this.a < 0.0F) { - this.a = 0.0F; - } - } - - } - - public static int a(World world, TileEntityContainer tileentitycontainer, int i, int j, int k, int l, int i1) { - if (!world.isClientSide && i1 != 0 && (i + j + k + l) % 200 == 0) { - i1 = a(world, tileentitycontainer, j, k, l); - } - - return i1; - } - - public static int a(World world, TileEntityContainer tileentitycontainer, int i, int j, int k) { - int l = 0; - float f = 5.0F; - List list = world.a(EntityHuman.class, new AxisAlignedBB((double) ((float) i - 5.0F), (double) ((float) j - 5.0F), (double) ((float) k - 5.0F), (double) ((float) (i + 1) + 5.0F), (double) ((float) (j + 1) + 5.0F), (double) ((float) (k + 1) + 5.0F))); - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman = (EntityHuman) iterator.next(); - - if (entityhuman.activeContainer instanceof ContainerChest) { - IInventory iinventory = ((ContainerChest) entityhuman.activeContainer).e(); - - if (iinventory == tileentitycontainer || iinventory instanceof InventoryLargeChest && ((InventoryLargeChest) iinventory).a((IInventory) tileentitycontainer)) { - ++l; - } - } - } - - return l; - } - - private void a(SoundEffect soundeffect) { - if (!this.getBlock().hasProperty(BlockChest.b)) { return; } // Paper - this can be delayed, double check exists - Fixes GH-2074 - BlockPropertyChestType blockpropertychesttype = (BlockPropertyChestType) this.getBlock().get(BlockChest.b); - - if (blockpropertychesttype != BlockPropertyChestType.LEFT) { - double d0 = (double) this.position.getX() + 0.5D; - double d1 = (double) this.position.getY() + 0.5D; - double d2 = (double) this.position.getZ() + 0.5D; - - if (blockpropertychesttype == BlockPropertyChestType.RIGHT) { - EnumDirection enumdirection = BlockChest.j(this.getBlock()); - - d0 += (double) enumdirection.getAdjacentX() * 0.5D; - d2 += (double) enumdirection.getAdjacentZ() * 0.5D; - } - - this.world.playSound((EntityHuman) null, d0, d1, d2, soundeffect, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); - } - } - - @Override - public boolean setProperty(int i, int j) { - if (i == 1) { - this.viewingCount = j; - return true; - } else { - return super.setProperty(i, j); - } - } - - @Override - public void startOpen(EntityHuman entityhuman) { - if (!entityhuman.isSpectator()) { - if (this.viewingCount < 0) { - this.viewingCount = 0; - } - int oldPower = Math.max(0, Math.min(15, this.viewingCount)); // CraftBukkit - Get power before new viewer is added - - ++this.viewingCount; - if (this.world == null) return; // CraftBukkit - doOpenLogic(); // Paper - - // CraftBukkit start - Call redstone event - if (this.getBlock().getBlock() == Blocks.TRAPPED_CHEST) { - int newPower = Math.max(0, Math.min(15, this.viewingCount)); - - if (oldPower != newPower) { - org.bukkit.craftbukkit.event.CraftEventFactory.callRedstoneChange(world, position, oldPower, newPower); - } - } - // CraftBukkit end - this.onOpen(); - } - - } - - @Override - public void closeContainer(EntityHuman entityhuman) { - if (!entityhuman.isSpectator()) { - int oldPower = Math.max(0, Math.min(15, this.viewingCount)); // CraftBukkit - Get power before new viewer is added - --this.viewingCount; - - // CraftBukkit start - Call redstone event - doCloseLogic(); // Paper - if (this.getBlock().getBlock() == Blocks.TRAPPED_CHEST) { - int newPower = Math.max(0, Math.min(15, this.viewingCount)); - - if (oldPower != newPower) { - org.bukkit.craftbukkit.event.CraftEventFactory.callRedstoneChange(world, position, oldPower, newPower); - } - } - // CraftBukkit end - this.onOpen(); - } - - } - - protected void onOpen() { - Block block = this.getBlock().getBlock(); - - if (block instanceof BlockChest) { - this.world.playBlockAction(this.position, block, 1, this.viewingCount); - this.world.applyPhysics(this.position, block); - } - - } - - @Override - protected NonNullList f() { - return this.items; - } - - @Override - protected void a(NonNullList nonnulllist) { - this.items = nonnulllist; - } - - public static int a(IBlockAccess iblockaccess, BlockPosition blockposition) { - IBlockData iblockdata = iblockaccess.getType(blockposition); - - if (iblockdata.getBlock().isTileEntity()) { - TileEntity tileentity = iblockaccess.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityChest) { - return ((TileEntityChest) tileentity).viewingCount; - } - } - - return 0; - } - - public static void a(TileEntityChest tileentitychest, TileEntityChest tileentitychest1) { - NonNullList nonnulllist = tileentitychest.f(); - - tileentitychest.a(tileentitychest1.f()); - tileentitychest1.a(nonnulllist); - } - - @Override - protected Container createContainer(int i, PlayerInventory playerinventory) { - return ContainerChest.a(i, playerinventory, this); - } - - // CraftBukkit start - @Override - public boolean isFilteredNBT() { - return false; // Paper - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/TileEntityCommand.java b/src/main/java/net/minecraft/server/TileEntityCommand.java deleted file mode 100644 index 22e5828d5..000000000 --- a/src/main/java/net/minecraft/server/TileEntityCommand.java +++ /dev/null @@ -1,168 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class TileEntityCommand extends TileEntity { - - private boolean a; - private boolean b; - private boolean c; - private boolean g; - private final CommandBlockListenerAbstract h = new CommandBlockListenerAbstract() { - // CraftBukkit start - @Override - public org.bukkit.command.CommandSender getBukkitSender(CommandListenerWrapper wrapper) { - return new org.bukkit.craftbukkit.command.CraftBlockCommandSender(wrapper, TileEntityCommand.this); - } - // CraftBukkit end - - @Override - public void setCommand(String s) { - super.setCommand(s); - TileEntityCommand.this.update(); - } - - @Override - public WorldServer d() { - return (WorldServer) TileEntityCommand.this.world; - } - - @Override - public void e() { - IBlockData iblockdata = TileEntityCommand.this.world.getType(TileEntityCommand.this.position); - - this.d().notify(TileEntityCommand.this.position, iblockdata, iblockdata, 3); - } - - @Override - public CommandListenerWrapper getWrapper() { - return new CommandListenerWrapper(this, new Vec3D((double) TileEntityCommand.this.position.getX() + 0.5D, (double) TileEntityCommand.this.position.getY() + 0.5D, (double) TileEntityCommand.this.position.getZ() + 0.5D), Vec2F.a, this.d(), 2, this.getName().getString(), this.getName(), this.d().getMinecraftServer(), (Entity) null); - } - }; - - public TileEntityCommand() { - super(TileEntityTypes.COMMAND_BLOCK); - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - this.h.a(nbttagcompound); - nbttagcompound.setBoolean("powered", this.f()); - nbttagcompound.setBoolean("conditionMet", this.h()); - nbttagcompound.setBoolean("auto", this.g()); - return nbttagcompound; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.h.b(nbttagcompound); - this.a = nbttagcompound.getBoolean("powered"); - this.c = nbttagcompound.getBoolean("conditionMet"); - this.b(nbttagcompound.getBoolean("auto")); - } - - @Nullable - @Override - public PacketPlayOutTileEntityData getUpdatePacket() { - if (this.t()) { - this.c(false); - NBTTagCompound nbttagcompound = this.save(new NBTTagCompound()); - - return new PacketPlayOutTileEntityData(this.position, 2, nbttagcompound); - } else { - return null; - } - } - - @Override - public boolean isFilteredNBT() { - return true; - } - - public CommandBlockListenerAbstract getCommandBlock() { - return this.h; - } - - public void a(boolean flag) { - this.a = flag; - } - - public boolean f() { - return this.a; - } - - public boolean g() { - return this.b; - } - - public void b(boolean flag) { - boolean flag1 = this.b; - - this.b = flag; - if (!flag1 && flag && !this.a && this.world != null && this.u() != TileEntityCommand.Type.SEQUENCE) { - Block block = this.getBlock().getBlock(); - - if (block instanceof BlockCommand) { - this.s(); - this.world.getBlockTickList().a(this.position, block, block.a((IWorldReader) this.world)); - } - } - - } - - public boolean h() { - return this.c; - } - - public boolean s() { - this.c = true; - if (this.v()) { - BlockPosition blockposition = this.position.shift(((EnumDirection) this.world.getType(this.position).get(BlockCommand.a)).opposite()); - - if (this.world.getType(blockposition).getBlock() instanceof BlockCommand) { - TileEntity tileentity = this.world.getTileEntity(blockposition); - - this.c = tileentity instanceof TileEntityCommand && ((TileEntityCommand) tileentity).getCommandBlock().i() > 0; - } else { - this.c = false; - } - } - - return this.c; - } - - public boolean t() { - return this.g; - } - - public void c(boolean flag) { - this.g = flag; - } - - public TileEntityCommand.Type u() { - Block block = this.getBlock().getBlock(); - - return block == Blocks.COMMAND_BLOCK ? TileEntityCommand.Type.REDSTONE : (block == Blocks.REPEATING_COMMAND_BLOCK ? TileEntityCommand.Type.AUTO : (block == Blocks.CHAIN_COMMAND_BLOCK ? TileEntityCommand.Type.SEQUENCE : TileEntityCommand.Type.REDSTONE)); - } - - public boolean v() { - IBlockData iblockdata = this.world.getType(this.getPosition()); - - return iblockdata.getBlock() instanceof BlockCommand ? (Boolean) iblockdata.get(BlockCommand.b) : false; - } - - @Override - public void n() { - this.invalidateBlockCache(); - super.n(); - } - - public static enum Type { - - SEQUENCE, AUTO, REDSTONE; - - private Type() {} - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityConduit.java b/src/main/java/net/minecraft/server/TileEntityConduit.java deleted file mode 100644 index d5011ec9b..000000000 --- a/src/main/java/net/minecraft/server/TileEntityConduit.java +++ /dev/null @@ -1,297 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.UUID; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.event.CraftEventFactory; -// CraftBukkit end - -public class TileEntityConduit extends TileEntity implements ITickable { - - private static final Block[] b = new Block[]{Blocks.PRISMARINE, Blocks.PRISMARINE_BRICKS, Blocks.SEA_LANTERN, Blocks.DARK_PRISMARINE}; - public int a; - private float c; - private boolean g; - private boolean h; - private final List i; - @Nullable - private EntityLiving target; - @Nullable - private UUID k; - private long l; - - public TileEntityConduit() { - this(TileEntityTypes.CONDUIT); - } - - public TileEntityConduit(TileEntityTypes tileentitytypes) { - super(tileentitytypes); - this.i = Lists.newArrayList(); - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - if (nbttagcompound.hasKey("target_uuid")) { - this.k = GameProfileSerializer.b(nbttagcompound.getCompound("target_uuid")); - } else { - this.k = null; - } - - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - if (this.target != null) { - nbttagcompound.set("target_uuid", GameProfileSerializer.a(this.target.getUniqueID())); - } - - return nbttagcompound; - } - - @Nullable - @Override - public PacketPlayOutTileEntityData getUpdatePacket() { - return new PacketPlayOutTileEntityData(this.position, 5, this.b()); - } - - @Override - public NBTTagCompound b() { - return this.save(new NBTTagCompound()); - } - - @Override - public void tick() { - ++this.a; - long i = this.world.getTime(); - - if (i % 40L == 0L) { - this.a(this.h()); - if (!this.world.isClientSide && this.d()) { - this.s(); - this.t(); - } - } - - if (i % 80L == 0L && this.d()) { - this.a(SoundEffects.BLOCK_CONDUIT_AMBIENT); - } - - if (i > this.l && this.d()) { - this.l = i + 60L + (long) this.world.getRandom().nextInt(40); - this.a(SoundEffects.BLOCK_CONDUIT_AMBIENT_SHORT); - } - - if (this.world.isClientSide) { - this.u(); - this.y(); - if (this.d()) { - ++this.c; - } - } - - } - - private boolean h() { - this.i.clear(); - - int i; - int j; - int k; - - for (i = -1; i <= 1; ++i) { - for (j = -1; j <= 1; ++j) { - for (k = -1; k <= 1; ++k) { - BlockPosition blockposition = this.position.b(i, j, k); - - if (!this.world.x(blockposition)) { - return false; - } - } - } - } - - for (i = -2; i <= 2; ++i) { - for (j = -2; j <= 2; ++j) { - for (k = -2; k <= 2; ++k) { - int l = Math.abs(i); - int i1 = Math.abs(j); - int j1 = Math.abs(k); - - if ((l > 1 || i1 > 1 || j1 > 1) && (i == 0 && (i1 == 2 || j1 == 2) || j == 0 && (l == 2 || j1 == 2) || k == 0 && (l == 2 || i1 == 2))) { - BlockPosition blockposition1 = this.position.b(i, j, k); - IBlockData iblockdata = this.world.getType(blockposition1); - Block[] ablock = TileEntityConduit.b; - int k1 = ablock.length; - - for (int l1 = 0; l1 < k1; ++l1) { - Block block = ablock[l1]; - - if (iblockdata.getBlock() == block) { - this.i.add(blockposition1); - } - } - } - } - } - } - - this.b(this.i.size() >= 42); - return this.i.size() >= 16; - } - - private void s() { - int i = this.i.size(); - int j = i / 7 * 16; - int k = this.position.getX(); - int l = this.position.getY(); - int i1 = this.position.getZ(); - AxisAlignedBB axisalignedbb = (new AxisAlignedBB((double) k, (double) l, (double) i1, (double) (k + 1), (double) (l + 1), (double) (i1 + 1))).g((double) j).b(0.0D, (double) this.world.getBuildHeight(), 0.0D); - List list = this.world.a(EntityHuman.class, axisalignedbb); - - if (!list.isEmpty()) { - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman = (EntityHuman) iterator.next(); - - if (this.position.a((BaseBlockPosition) (new BlockPosition(entityhuman)), (double) j) && entityhuman.isInWaterOrRain()) { - entityhuman.addEffect(new MobEffect(MobEffects.CONDUIT_POWER, 260, 0, true, true), org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONDUIT); // CraftBukkit - } - } - - } - } - - private void t() { - EntityLiving entityliving = this.target; - int i = this.i.size(); - - if (i < 42) { - this.target = null; - } else if (this.target == null && this.k != null) { - this.target = this.x(); - this.k = null; - } else if (this.target == null) { - List list = this.world.a(EntityLiving.class, this.v(), (java.util.function.Predicate) (entityliving1) -> { // CraftBukkit - decompile error - return entityliving1 instanceof IMonster && entityliving1.isInWaterOrRain(); - }); - - if (!list.isEmpty()) { - this.target = (EntityLiving) list.get(this.world.random.nextInt(list.size())); - } - } else if (!this.target.isAlive() || !this.position.a((BaseBlockPosition) (new BlockPosition(this.target)), 8.0D)) { - this.target = null; - } - - if (this.target != null) { - // CraftBukkit start - CraftEventFactory.blockDamage = CraftBlock.at(this.world, this.position); - if (this.target.damageEntity(DamageSource.MAGIC, 4.0F)) { - this.world.playSound((EntityHuman) null, this.target.locX, this.target.locY, this.target.locZ, SoundEffects.BLOCK_CONDUIT_ATTACK_TARGET, SoundCategory.BLOCKS, 1.0F, 1.0F); - } - CraftEventFactory.blockDamage = null; - // CraftBukkit end - } - - if (entityliving != this.target) { - IBlockData iblockdata = this.getBlock(); - - this.world.notify(this.position, iblockdata, iblockdata, 2); - } - - } - - private void u() { - if (this.k == null) { - this.target = null; - } else if (this.target == null || !this.target.getUniqueID().equals(this.k)) { - this.target = this.x(); - if (this.target == null) { - this.k = null; - } - } - - } - - private AxisAlignedBB v() { - int i = this.position.getX(); - int j = this.position.getY(); - int k = this.position.getZ(); - - return (new AxisAlignedBB((double) i, (double) j, (double) k, (double) (i + 1), (double) (j + 1), (double) (k + 1))).g(8.0D); - } - - @Nullable - private EntityLiving x() { - List list = this.world.a(EntityLiving.class, this.v(), (java.util.function.Predicate) (entityliving) -> { // CraftBukkit - decompile error - return entityliving.getUniqueID().equals(this.k); - }); - - return list.size() == 1 ? (EntityLiving) list.get(0) : null; - } - - private void y() { - Random random = this.world.random; - float f = MathHelper.sin((float) (this.a + 35) * 0.1F) / 2.0F + 0.5F; - - f = (f * f + f) * 0.3F; - Vec3D vec3d = new Vec3D((double) ((float) this.position.getX() + 0.5F), (double) ((float) this.position.getY() + 1.5F + f), (double) ((float) this.position.getZ() + 0.5F)); - Iterator iterator = this.i.iterator(); - - float f1; - float f2; - - while (iterator.hasNext()) { - BlockPosition blockposition = (BlockPosition) iterator.next(); - - if (random.nextInt(50) == 0) { - f1 = -0.5F + random.nextFloat(); - f2 = -2.0F + random.nextFloat(); - float f3 = -0.5F + random.nextFloat(); - BlockPosition blockposition1 = blockposition.b(this.position); - Vec3D vec3d1 = (new Vec3D((double) f1, (double) f2, (double) f3)).add((double) blockposition1.getX(), (double) blockposition1.getY(), (double) blockposition1.getZ()); - - this.world.addParticle(Particles.NAUTILUS, vec3d.x, vec3d.y, vec3d.z, vec3d1.x, vec3d1.y, vec3d1.z); - } - } - - if (this.target != null) { - Vec3D vec3d2 = new Vec3D(this.target.locX, this.target.locY + (double) this.target.getHeadHeight(), this.target.locZ); - float f4 = (-0.5F + random.nextFloat()) * (3.0F + this.target.getWidth()); - - f1 = -1.0F + random.nextFloat() * this.target.getHeight(); - f2 = (-0.5F + random.nextFloat()) * (3.0F + this.target.getWidth()); - Vec3D vec3d3 = new Vec3D((double) f4, (double) f1, (double) f2); - - this.world.addParticle(Particles.NAUTILUS, vec3d2.x, vec3d2.y, vec3d2.z, vec3d3.x, vec3d3.y, vec3d3.z); - } - - } - - public boolean d() { - return this.g; - } - - private void a(boolean flag) { - if (flag != this.g) { - this.a(flag ? SoundEffects.BLOCK_CONDUIT_ACTIVATE : SoundEffects.BLOCK_CONDUIT_DEACTIVATE); - } - - this.g = flag; - } - - private void b(boolean flag) { - this.h = flag; - } - - public void a(SoundEffect soundeffect) { - this.world.playSound((EntityHuman) null, this.position, soundeffect, SoundCategory.BLOCKS, 1.0F, 1.0F); - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityContainer.java b/src/main/java/net/minecraft/server/TileEntityContainer.java deleted file mode 100644 index ab6b86e4e..000000000 --- a/src/main/java/net/minecraft/server/TileEntityContainer.java +++ /dev/null @@ -1,87 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public abstract class TileEntityContainer extends TileEntity implements IInventory, ITileInventory, INamableTileEntity { - - public ChestLock chestLock; - public IChatBaseComponent customName; - - protected TileEntityContainer(TileEntityTypes tileentitytypes) { - super(tileentitytypes); - this.chestLock = ChestLock.a; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.chestLock = ChestLock.b(nbttagcompound); - if (nbttagcompound.hasKeyOfType("CustomName", 8)) { - this.customName = MCUtil.getBaseComponentFromNbt("CustomName", nbttagcompound); // Paper - Catch ParseException - } - - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - this.chestLock.a(nbttagcompound); - if (this.customName != null) { - nbttagcompound.setString("CustomName", IChatBaseComponent.ChatSerializer.a(this.customName)); - } - - return nbttagcompound; - } - - public void setCustomName(IChatBaseComponent ichatbasecomponent) { - this.customName = ichatbasecomponent; - } - - @Override - public IChatBaseComponent getDisplayName() { - return this.customName != null ? this.customName : this.getContainerName(); - } - - @Override - public IChatBaseComponent getScoreboardDisplayName() { - return this.getDisplayName(); - } - - @Nullable - @Override - public IChatBaseComponent getCustomName() { - return this.customName; - } - - protected abstract IChatBaseComponent getContainerName(); - - public boolean e(EntityHuman entityhuman) { - return a(entityhuman, this.chestLock, this.getScoreboardDisplayName()); - } - - public static boolean a(EntityHuman entityhuman, ChestLock chestlock, IChatBaseComponent ichatbasecomponent) { - if (!entityhuman.isSpectator() && !chestlock.a(entityhuman.getItemInMainHand())) { - entityhuman.a((IChatBaseComponent) (new ChatMessage("container.isLocked", new Object[]{ichatbasecomponent})), true); - entityhuman.a(SoundEffects.BLOCK_CHEST_LOCKED, SoundCategory.BLOCKS, 1.0F, 1.0F); - return false; - } else { - return true; - } - } - - @Nullable - @Override - public Container createMenu(int i, PlayerInventory playerinventory, EntityHuman entityhuman) { - return this.e(entityhuman) ? this.createContainer(i, playerinventory) : null; - } - - protected abstract Container createContainer(int i, PlayerInventory playerinventory); - - // CraftBukkit start - @Override - public org.bukkit.Location getLocation() { - if (world == null) return null; - return new org.bukkit.Location(world.getWorld(), position.getX(), position.getY(), position.getZ()); - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/TileEntityDispenser.java b/src/main/java/net/minecraft/server/TileEntityDispenser.java deleted file mode 100644 index 37a5bde68..000000000 --- a/src/main/java/net/minecraft/server/TileEntityDispenser.java +++ /dev/null @@ -1,142 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.Random; -// CraftBukkit start -import java.util.List; - -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -// CraftBukkit end - -public class TileEntityDispenser extends TileEntityLootable { - - private static final Random a = new Random(); - private NonNullList items; - - // CraftBukkit start - add fields and methods - public List transaction = new java.util.ArrayList(); - private int maxStack = MAX_STACK; - - public List 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; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - // CraftBukkit end - - protected TileEntityDispenser(TileEntityTypes tileentitytypes) { - super(tileentitytypes); - this.items = NonNullList.a(9, ItemStack.a); - } - - public TileEntityDispenser() { - this(TileEntityTypes.DISPENSER); - } - - @Override - public int getSize() { - return 9; - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - public int h() { - this.d((EntityHuman) null); - int i = -1; - int j = 1; - - for (int k = 0; k < this.items.size(); ++k) { - if (!((ItemStack) this.items.get(k)).isEmpty() && TileEntityDispenser.a.nextInt(j++) == 0) { - i = k; - } - } - - return i; - } - - public int addItem(ItemStack itemstack) { - for (int i = 0; i < this.items.size(); ++i) { - if (((ItemStack) this.items.get(i)).isEmpty()) { - this.setItem(i, itemstack); - return i; - } - } - - return -1; - } - - @Override - protected IChatBaseComponent getContainerName() { - return new ChatMessage("container.dispenser", new Object[0]); - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.items = NonNullList.a(this.getSize(), ItemStack.a); - if (!this.d(nbttagcompound)) { - ContainerUtil.b(nbttagcompound, this.items); - } - - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - if (!this.e(nbttagcompound)) { - ContainerUtil.a(nbttagcompound, this.items); - } - - return nbttagcompound; - } - - @Override - protected NonNullList f() { - return this.items; - } - - @Override - protected void a(NonNullList nonnulllist) { - this.items = nonnulllist; - } - - @Override - protected Container createContainer(int i, PlayerInventory playerinventory) { - return new ContainerDispenser(i, playerinventory, this); - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityEndGateway.java b/src/main/java/net/minecraft/server/TileEntityEndGateway.java deleted file mode 100644 index 15dccc905..000000000 --- a/src/main/java/net/minecraft/server/TileEntityEndGateway.java +++ /dev/null @@ -1,269 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.event.player.PlayerTeleportEvent; -// CraftBukkit end - -public class TileEntityEndGateway extends TileEntityEnderPortal implements ITickable { - - private static final Logger LOGGER = LogManager.getLogger(); - public long age; - private int c; - public BlockPosition exitPortal; - public boolean exactTeleport; - - public TileEntityEndGateway() { - super(TileEntityTypes.END_GATEWAY); - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - nbttagcompound.setLong("Age", this.age); - if (this.exitPortal != null) { - nbttagcompound.set("ExitPortal", GameProfileSerializer.a(this.exitPortal)); - } - - if (this.exactTeleport) { - nbttagcompound.setBoolean("ExactTeleport", this.exactTeleport); - } - - return nbttagcompound; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.age = nbttagcompound.getLong("Age"); - if (nbttagcompound.hasKeyOfType("ExitPortal", 10)) { - this.exitPortal = GameProfileSerializer.c(nbttagcompound.getCompound("ExitPortal")); - } - - this.exactTeleport = nbttagcompound.getBoolean("ExactTeleport"); - } - - @Override - public void tick() { - boolean flag = this.d(); - boolean flag1 = this.f(); - - ++this.age; - if (flag1) { - --this.c; - } else if (!this.world.isClientSide) { - List list = this.world.a(Entity.class, new AxisAlignedBB(this.getPosition())); - - if (!list.isEmpty()) { - this.a((Entity) list.get(0)); - } - - if (this.age % 2400L == 0L) { - this.h(); - } - } - - if (flag != this.d() || flag1 != this.f()) { - this.update(); - } - - } - - public boolean d() { - return this.age < 200L; - } - - public boolean f() { - return this.c > 0; - } - - @Nullable - @Override - public PacketPlayOutTileEntityData getUpdatePacket() { - return new PacketPlayOutTileEntityData(this.position, 8, this.b()); - } - - @Override - public NBTTagCompound b() { - return this.save(new NBTTagCompound()); - } - - public void h() { - if (!this.world.isClientSide) { - this.c = 40; - this.world.playBlockAction(this.getPosition(), this.getBlock().getBlock(), 1, 0); - this.update(); - } - - } - - @Override - public boolean setProperty(int i, int j) { - if (i == 1) { - this.c = 40; - return true; - } else { - return super.setProperty(i, j); - } - } - - public void a(Entity entity) { - if (!this.world.isClientSide && !this.f()) { - this.c = 100; - if (this.exitPortal == null && this.world.worldProvider instanceof WorldProviderTheEnd) { - this.u(); - } - - if (this.exitPortal != null) { - BlockPosition blockposition = this.exactTeleport ? this.exitPortal : this.t(); - - // CraftBukkit start - Fire PlayerTeleportEvent - if (entity instanceof EntityPlayer) { - org.bukkit.craftbukkit.entity.CraftPlayer player = (CraftPlayer) entity.getBukkitEntity(); - org.bukkit.Location location = new Location(world.getWorld(), (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D); - location.setPitch(player.getLocation().getPitch()); - location.setYaw(player.getLocation().getYaw()); - - PlayerTeleportEvent teleEvent = new com.destroystokyo.paper.event.player.PlayerTeleportEndGatewayEvent(player, player.getLocation(), location, new org.bukkit.craftbukkit.block.CraftEndGateway(MCUtil.toLocation(world, this.getPosition()).getBlock())); // Paper - Bukkit.getPluginManager().callEvent(teleEvent); - if (teleEvent.isCancelled()) { - return; - } - - ((EntityPlayer) entity).playerConnection.teleport(teleEvent.getTo()); - this.f(); // CraftBukkit - call at end of method - return; - - } - // CraftBukkit end - // Paper start - EntityTeleportEndGatewayEvent - replicated from above - org.bukkit.craftbukkit.entity.CraftEntity bukkitEntity = entity.getBukkitEntity(); - org.bukkit.Location location = new Location(world.getWorld(), (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D); - location.setPitch(bukkitEntity.getLocation().getPitch()); - location.setYaw(bukkitEntity.getLocation().getYaw()); - - com.destroystokyo.paper.event.entity.EntityTeleportEndGatewayEvent event = new com.destroystokyo.paper.event.entity.EntityTeleportEndGatewayEvent(bukkitEntity, bukkitEntity.getLocation(), location, new org.bukkit.craftbukkit.block.CraftEndGateway(MCUtil.toLocation(world, this.getPosition()).getBlock())); - if (!event.callEvent()) { - return; - } - - entity.enderTeleportAndLoad(event.getTo().getX(), event.getTo().getY(), event.getTo().getZ()); - // Paper end - EntityTeleportEndGatewayEvent - } - - this.h(); - } - } - - private BlockPosition t() { - BlockPosition blockposition = a(this.world, this.exitPortal, 5, false); - - TileEntityEndGateway.LOGGER.debug("Best exit position for portal at {} is {}", this.exitPortal, blockposition); - return blockposition.up(); - } - - private void u() { - Vec3D vec3d = (new Vec3D((double) this.getPosition().getX(), 0.0D, (double) this.getPosition().getZ())).d(); - Vec3D vec3d1 = vec3d.a(1024.0D); - - int i; - - for (i = 16; a(this.world, vec3d1).b() > 0 && i-- > 0; vec3d1 = vec3d1.e(vec3d.a(-16.0D))) { - TileEntityEndGateway.LOGGER.debug("Skipping backwards past nonempty chunk at {}", vec3d1); - } - - for (i = 16; a(this.world, vec3d1).b() == 0 && i-- > 0; vec3d1 = vec3d1.e(vec3d.a(16.0D))) { - TileEntityEndGateway.LOGGER.debug("Skipping forward past empty chunk at {}", vec3d1); - } - - TileEntityEndGateway.LOGGER.debug("Found chunk at {}", vec3d1); - Chunk chunk = a(this.world, vec3d1); - - this.exitPortal = a(chunk); - if (this.exitPortal == null) { - this.exitPortal = new BlockPosition(vec3d1.x + 0.5D, 75.0D, vec3d1.z + 0.5D); - TileEntityEndGateway.LOGGER.debug("Failed to find suitable block, settling on {}", this.exitPortal); - WorldGenerator.END_ISLAND.generate(this.world, this.world.getChunkProvider().getChunkGenerator(), new Random(this.exitPortal.asLong()), this.exitPortal, WorldGenFeatureConfiguration.e); - } else { - TileEntityEndGateway.LOGGER.debug("Found block at {}", this.exitPortal); - } - - this.exitPortal = a(this.world, this.exitPortal, 16, true); - TileEntityEndGateway.LOGGER.debug("Creating portal at {}", this.exitPortal); - this.exitPortal = this.exitPortal.up(10); - this.b(this.exitPortal); - this.update(); - } - - private static BlockPosition a(IBlockAccess iblockaccess, BlockPosition blockposition, int i, boolean flag) { - BlockPosition blockposition1 = null; - - for (int j = -i; j <= i; ++j) { - for (int k = -i; k <= i; ++k) { - if (j != 0 || k != 0 || flag) { - for (int l = 255; l > (blockposition1 == null ? 0 : blockposition1.getY()); --l) { - BlockPosition blockposition2 = new BlockPosition(blockposition.getX() + j, l, blockposition.getZ() + k); - IBlockData iblockdata = iblockaccess.getType(blockposition2); - - if (iblockdata.o(iblockaccess, blockposition2) && (flag || iblockdata.getBlock() != Blocks.BEDROCK)) { - blockposition1 = blockposition2; - break; - } - } - } - } - } - - return blockposition1 == null ? blockposition : blockposition1; - } - - private static Chunk a(World world, Vec3D vec3d) { - return world.getChunkAt(MathHelper.floor(vec3d.x / 16.0D), MathHelper.floor(vec3d.z / 16.0D)); - } - - @Nullable - private static BlockPosition a(Chunk chunk) { - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - BlockPosition blockposition = new BlockPosition(chunkcoordintpair.d(), 30, chunkcoordintpair.e()); - int i = chunk.b() + 16 - 1; - BlockPosition blockposition1 = new BlockPosition(chunkcoordintpair.f(), i, chunkcoordintpair.g()); - BlockPosition blockposition2 = null; - double d0 = 0.0D; - Iterator iterator = BlockPosition.a(blockposition, blockposition1).iterator(); - - while (iterator.hasNext()) { - BlockPosition blockposition3 = (BlockPosition) iterator.next(); - IBlockData iblockdata = chunk.getType(blockposition3); - BlockPosition blockposition4 = blockposition3.up(); - BlockPosition blockposition5 = blockposition3.up(2); - - if (iblockdata.getBlock() == Blocks.END_STONE && !chunk.getType(blockposition4).o(chunk, blockposition4) && !chunk.getType(blockposition5).o(chunk, blockposition5)) { - double d1 = blockposition3.distanceSquared(0.0D, 0.0D, 0.0D, true); - - if (blockposition2 == null || d1 < d0) { - blockposition2 = blockposition3; - d0 = d1; - } - } - } - - return blockposition2; - } - - private void b(BlockPosition blockposition) { - WorldGenerator.END_GATEWAY.generate(this.world, this.world.getChunkProvider().getChunkGenerator(), new Random(), blockposition, WorldGenEndGatewayConfiguration.a(this.getPosition(), false)); - } - - public void a(BlockPosition blockposition, boolean flag) { - this.exactTeleport = flag; - this.exitPortal = blockposition; - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityEnderChest.java b/src/main/java/net/minecraft/server/TileEntityEnderChest.java deleted file mode 100644 index ae6784b6a..000000000 --- a/src/main/java/net/minecraft/server/TileEntityEnderChest.java +++ /dev/null @@ -1,116 +0,0 @@ -package net.minecraft.server; - -public class TileEntityEnderChest extends TileEntity { // Paper - Remove ITickable - - public float a; - public float b; - public int c; - private int g; - - public TileEntityEnderChest() { - super(TileEntityTypes.ENDER_CHEST); - } - - public void tick() { - if (++this.g % 20 * 4 == 0) { - this.world.playBlockAction(this.position, Blocks.ENDER_CHEST, 1, this.c); - } - - this.b = this.a; - /* // Paper - int i = this.position.getX(); - int j = this.position.getY(); - int k = this.position.getZ(); - float f = 0.1F; - double d0; - // Paper start - */ - } - - private void doOpenLogic() { - int i = this.position.getX(); - int j = this.position.getY(); - int k = this.position.getZ(); - double d0; - // Paper end - - if (this.c > 0 && this.a == 0.0F) { - double d1 = (double) i + 0.5D; - - d0 = (double) k + 0.5D; - this.world.playSound((EntityHuman) null, d1, (double) j + 0.5D, d0, SoundEffects.BLOCK_ENDER_CHEST_OPEN, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); - } - // Paper start - } - - private void doCloseLogic() { - int i = this.position.getX(); - int j = this.position.getY(); - int k = this.position.getZ(); - double d0; - - if (this.c == 0) { /* && this.a > 0.0F || this.c > 0 && this.a < 1.0F) { - // Paper end - float f1 = this.a; - - if (this.c > 0) { - this.a += 0.1F; - } else { - this.a -= 0.1F; - } - - if (this.a > 1.0F) { - this.a = 1.0F; - } - - float f2 = 0.5F; - - if (this.a < 0.5F && f1 >= 0.5F) { - // Paper start - */ - d0 = (double) i + 0.5D; - double d2 = (double) k + 0.5D; - - MCUtil.scheduleTask(10, () -> { - this.world.playSound((EntityHuman) null, d0, (double) j + 0.5D, d2, SoundEffects.BLOCK_ENDER_CHEST_CLOSE, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); - }); - - if (this.a < 0.0F) { - this.a = 0.0F; - } - } - - } - - @Override - public boolean setProperty(int i, int j) { - if (i == 1) { - this.c = j; - return true; - } else { - return super.setProperty(i, j); - } - } - - @Override - public void V_() { - this.invalidateBlockCache(); - super.V_(); - } - - public void d() { - ++this.c; - this.world.playBlockAction(this.position, Blocks.ENDER_CHEST, 1, this.c); - doOpenLogic(); // Paper - } - - public void f() { - --this.c; - this.world.playBlockAction(this.position, Blocks.ENDER_CHEST, 1, this.c); - doCloseLogic(); // Paper - } - - public boolean a(EntityHuman entityhuman) { - return this.world.getTileEntity(this.position) != this ? false : 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/src/main/java/net/minecraft/server/TileEntityFurnace.java b/src/main/java/net/minecraft/server/TileEntityFurnace.java deleted file mode 100644 index 55b564610..000000000 --- a/src/main/java/net/minecraft/server/TileEntityFurnace.java +++ /dev/null @@ -1,581 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import javax.annotation.Nullable; -// CraftBukkit start -import java.util.List; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.FurnaceBurnEvent; -import org.bukkit.event.inventory.FurnaceExtractEvent; -import org.bukkit.event.inventory.FurnaceSmeltEvent; -// CraftBukkit end - -public abstract class TileEntityFurnace extends TileEntityContainer implements IWorldInventory, RecipeHolder, AutoRecipeOutput, ITickable { - - private static final int[] g = new int[]{0}; - private static final int[] h = new int[]{2, 1}; - private static final int[] i = new int[]{1}; - protected NonNullList items; - public int burnTime; - private int ticksForCurrentFuel; - public double cookSpeedMultiplier = 1.0; // Paper - cook speed multiplier API - public int cookTime; - public int cookTimeTotal; - protected final IContainerProperties b; - private final Map n; - protected final Recipes c; - - protected TileEntityFurnace(TileEntityTypes tileentitytypes, Recipes recipes) { - super(tileentitytypes); - this.items = NonNullList.a(3, ItemStack.a); - this.b = new IContainerProperties() { - @Override - public int getProperty(int i) { - switch (i) { - case 0: - return TileEntityFurnace.this.burnTime; - case 1: - return TileEntityFurnace.this.ticksForCurrentFuel; - case 2: - return TileEntityFurnace.this.cookTime; - case 3: - return TileEntityFurnace.this.cookTimeTotal; - default: - return 0; - } - } - - @Override - public void setProperty(int i, int j) { - switch (i) { - case 0: - TileEntityFurnace.this.burnTime = j; - break; - case 1: - TileEntityFurnace.this.ticksForCurrentFuel = j; - break; - case 2: - TileEntityFurnace.this.cookTime = j; - break; - case 3: - TileEntityFurnace.this.cookTimeTotal = j; - } - - } - - @Override - public int a() { - return 4; - } - }; - this.n = Maps.newHashMap(); - this.c = recipes; - } - - public static Map f() { - Map map = Maps.newLinkedHashMap(); - - a(map, (IMaterial) Items.LAVA_BUCKET, 20000); - a(map, (IMaterial) Blocks.COAL_BLOCK, 16000); - a(map, (IMaterial) Items.BLAZE_ROD, 2400); - a(map, (IMaterial) Items.COAL, 1600); - a(map, (IMaterial) Items.CHARCOAL, 1600); - a(map, TagsItem.LOGS, 300); - a(map, TagsItem.PLANKS, 300); - a(map, TagsItem.WOODEN_STAIRS, 300); - a(map, TagsItem.WOODEN_SLABS, 150); - a(map, TagsItem.WOODEN_TRAPDOORS, 300); - a(map, TagsItem.WOODEN_PRESSURE_PLATES, 300); - a(map, (IMaterial) Blocks.OAK_FENCE, 300); - a(map, (IMaterial) Blocks.BIRCH_FENCE, 300); - a(map, (IMaterial) Blocks.SPRUCE_FENCE, 300); - a(map, (IMaterial) Blocks.JUNGLE_FENCE, 300); - a(map, (IMaterial) Blocks.DARK_OAK_FENCE, 300); - a(map, (IMaterial) Blocks.ACACIA_FENCE, 300); - a(map, (IMaterial) Blocks.OAK_FENCE_GATE, 300); - a(map, (IMaterial) Blocks.BIRCH_FENCE_GATE, 300); - a(map, (IMaterial) Blocks.SPRUCE_FENCE_GATE, 300); - a(map, (IMaterial) Blocks.JUNGLE_FENCE_GATE, 300); - a(map, (IMaterial) Blocks.DARK_OAK_FENCE_GATE, 300); - a(map, (IMaterial) Blocks.ACACIA_FENCE_GATE, 300); - a(map, (IMaterial) Blocks.NOTE_BLOCK, 300); - a(map, (IMaterial) Blocks.BOOKSHELF, 300); - a(map, (IMaterial) Blocks.LECTERN, 300); - a(map, (IMaterial) Blocks.JUKEBOX, 300); - a(map, (IMaterial) Blocks.CHEST, 300); - a(map, (IMaterial) Blocks.TRAPPED_CHEST, 300); - a(map, (IMaterial) Blocks.CRAFTING_TABLE, 300); - a(map, (IMaterial) Blocks.DAYLIGHT_DETECTOR, 300); - a(map, TagsItem.BANNERS, 300); - a(map, (IMaterial) Items.BOW, 300); - a(map, (IMaterial) Items.FISHING_ROD, 300); - a(map, (IMaterial) Blocks.LADDER, 300); - a(map, TagsItem.SIGNS, 200); - a(map, (IMaterial) Items.WOODEN_SHOVEL, 200); - a(map, (IMaterial) Items.WOODEN_SWORD, 200); - a(map, (IMaterial) Items.WOODEN_HOE, 200); - a(map, (IMaterial) Items.WOODEN_AXE, 200); - a(map, (IMaterial) Items.WOODEN_PICKAXE, 200); - a(map, TagsItem.WOODEN_DOORS, 200); - a(map, TagsItem.BOATS, 200); - a(map, TagsItem.WOOL, 100); - a(map, TagsItem.WOODEN_BUTTONS, 100); - a(map, (IMaterial) Items.STICK, 100); - a(map, TagsItem.SAPLINGS, 100); - a(map, (IMaterial) Items.BOWL, 100); - a(map, TagsItem.CARPETS, 67); - a(map, (IMaterial) Blocks.DRIED_KELP_BLOCK, 4001); - a(map, (IMaterial) Items.CROSSBOW, 300); - a(map, (IMaterial) Blocks.BAMBOO, 50); - a(map, (IMaterial) Blocks.DEAD_BUSH, 100); - a(map, (IMaterial) Blocks.SCAFFOLDING, 50); - a(map, (IMaterial) Blocks.LOOM, 300); - a(map, (IMaterial) Blocks.BARREL, 300); - a(map, (IMaterial) Blocks.CARTOGRAPHY_TABLE, 300); - a(map, (IMaterial) Blocks.FLETCHING_TABLE, 300); - a(map, (IMaterial) Blocks.SMITHING_TABLE, 300); - a(map, (IMaterial) Blocks.COMPOSTER, 300); - return map; - } - - // CraftBukkit start - add fields and methods - private int maxStack = MAX_STACK; - public List transaction = new java.util.ArrayList(); - - public List 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; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - // CraftBukkit end - - private static void a(Map map, Tag tag, int i) { - Iterator iterator = tag.a().iterator(); - - while (iterator.hasNext()) { - Item item = (Item) iterator.next(); - - map.put(item, i); - } - - } - - private static void a(Map map, IMaterial imaterial, int i) { - map.put(imaterial.getItem(), i); - } - - private boolean isBurning() { - return this.burnTime > 0; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.items = NonNullList.a(this.getSize(), ItemStack.a); - ContainerUtil.b(nbttagcompound, this.items); - this.burnTime = nbttagcompound.getShort("BurnTime"); - this.cookTime = nbttagcompound.getShort("CookTime"); - this.cookTimeTotal = nbttagcompound.getShort("CookTimeTotal"); - this.ticksForCurrentFuel = this.fuelTime((ItemStack) this.items.get(1)); - short short0 = nbttagcompound.getShort("RecipesUsedSize"); - - for (int i = 0; i < short0; ++i) { - MinecraftKey minecraftkey = new MinecraftKey(nbttagcompound.getString("RecipeLocation" + i)); - int j = nbttagcompound.getInt("RecipeAmount" + i); - - this.n.put(minecraftkey, j); - } - - // Paper start - cook speed API - if (nbttagcompound.hasKey("Paper.CookSpeedMultiplier")) { - this.cookSpeedMultiplier = nbttagcompound.getDouble("Paper.CookSpeedMultiplier"); - } - // Paper end - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - nbttagcompound.setShort("BurnTime", (short) this.burnTime); - nbttagcompound.setShort("CookTime", (short) this.cookTime); - nbttagcompound.setShort("CookTimeTotal", (short) this.cookTimeTotal); - nbttagcompound.setDouble("Paper.CookSpeedMultiplier", this.cookSpeedMultiplier); // Paper - cook speed multiplier API - ContainerUtil.a(nbttagcompound, this.items); - nbttagcompound.setShort("RecipesUsedSize", (short) this.n.size()); - int i = 0; - - for (Iterator iterator = this.n.entrySet().iterator(); iterator.hasNext(); ++i) { - Entry entry = (Entry) iterator.next(); - - nbttagcompound.setString("RecipeLocation" + i, ((MinecraftKey) entry.getKey()).toString()); - nbttagcompound.setInt("RecipeAmount" + i, (Integer) entry.getValue()); - } - - return nbttagcompound; - } - - @Override - public void tick() { - boolean flag = this.isBurning(); - boolean flag1 = false; - - if (this.isBurning()) { - --this.burnTime; - } - - if (!this.world.isClientSide) { - ItemStack itemstack = (ItemStack) this.items.get(1); - - if (!this.isBurning() && (itemstack.isEmpty() || ((ItemStack) this.items.get(0)).isEmpty())) { - if (!this.isBurning() && this.cookTime > 0) { - this.cookTime = MathHelper.clamp(this.cookTime - 2, 0, this.cookTimeTotal); - } - } else { - IRecipe irecipe = this.world.getCraftingManager().craft((Recipes) this.c, this, this.world).orElse(null); // Eclipse fail - - if (!this.isBurning() && this.canBurn(irecipe)) { - // CraftBukkit start - CraftItemStack fuel = CraftItemStack.asCraftMirror(itemstack); - - FurnaceBurnEvent furnaceBurnEvent = new FurnaceBurnEvent(CraftBlock.at(this.world, this.position), fuel, fuelTime(itemstack)); - this.world.getServer().getPluginManager().callEvent(furnaceBurnEvent); - - if (furnaceBurnEvent.isCancelled()) { - return; - } - - this.burnTime = furnaceBurnEvent.getBurnTime(); - this.ticksForCurrentFuel = this.burnTime; - if (this.isBurning() && furnaceBurnEvent.isBurning()) { - // CraftBukkit end - flag1 = true; - if (!itemstack.isEmpty()) { - Item item = itemstack.getItem(); - - itemstack.subtract(1); - if (itemstack.isEmpty()) { - Item item1 = item.n(); - - this.items.set(1, item1 == null ? ItemStack.a : new ItemStack(item1)); - } - } - } - } - - if (this.isBurning() && this.canBurn(irecipe)) { - this.cookTime += cookSpeedMultiplier; // Paper - cook speed multiplier API - if (this.cookTime >= this.cookTimeTotal) { // Paper - cook speed multiplier API - this.cookTime = 0; - this.cookTimeTotal = this.getRecipeCookingTime(); - this.burn(irecipe); - flag1 = true; - } - } else { - this.cookTime = 0; - } - } - - if (flag != this.isBurning()) { - flag1 = true; - this.world.setTypeAndData(this.position, (IBlockData) this.world.getType(this.position).set(BlockFurnace.LIT, this.isBurning()), 3); - } - } - - if (flag1) { - this.update(); - } - - } - - protected boolean canBurn(@Nullable IRecipe irecipe) { - if (!((ItemStack) this.items.get(0)).isEmpty() && irecipe != null) { - ItemStack itemstack = irecipe.c(); - - if (itemstack.isEmpty()) { - return false; - } else { - ItemStack itemstack1 = (ItemStack) this.items.get(2); - - return itemstack1.isEmpty() ? true : (!itemstack1.doMaterialsMatch(itemstack) ? false : (itemstack1.getCount() < this.getMaxStackSize() && itemstack1.getCount() < itemstack1.getMaxStackSize() ? true : itemstack1.getCount() < itemstack.getMaxStackSize())); - } - } else { - return false; - } - } - - private void burn(@Nullable IRecipe irecipe) { - if (irecipe != null && this.canBurn(irecipe)) { - ItemStack itemstack = (ItemStack) this.items.get(0); - ItemStack itemstack1 = irecipe.c(); - ItemStack itemstack2 = (ItemStack) this.items.get(2); - - // CraftBukkit start - fire FurnaceSmeltEvent - CraftItemStack source = CraftItemStack.asCraftMirror(itemstack); - org.bukkit.inventory.ItemStack result = CraftItemStack.asBukkitCopy(itemstack1); - - 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(); - itemstack1 = CraftItemStack.asNMSCopy(result); - - if (!itemstack1.isEmpty()) { - if (itemstack2.isEmpty()) { - this.items.set(2, itemstack1.cloneItemStack()); - } else if (CraftItemStack.asCraftMirror(itemstack2).isSimilar(result)) { - itemstack2.add(itemstack1.getCount()); - } else { - return; - } - } - - /* - if (itemstack2.isEmpty()) { - this.items.set(2, itemstack1.cloneItemStack()); - } else if (itemstack2.getItem() == itemstack1.getItem()) { - itemstack2.add(1); - } - */ - // CraftBukkit end - - if (!this.world.isClientSide) { - this.a(irecipe); - } - - if (itemstack.getItem() == Blocks.WET_SPONGE.getItem() && !((ItemStack) this.items.get(1)).isEmpty() && ((ItemStack) this.items.get(1)).getItem() == Items.BUCKET) { - this.items.set(1, new ItemStack(Items.WATER_BUCKET)); - } - - itemstack.subtract(1); - } - } - - protected int fuelTime(ItemStack itemstack) { - if (itemstack.isEmpty()) { - return 0; - } else { - Item item = itemstack.getItem(); - - return (Integer) f().getOrDefault(item, 0); - } - } - - protected int getRecipeCookingTime() { - return (this.hasWorld()) ? (Integer) this.world.getCraftingManager().craft((Recipes) this.c, this, this.world).map(RecipeCooking::e).orElse(200) : 200; // CraftBukkit - SPIGOT-4302 // Eclipse fail - } - - public static boolean isFuel(ItemStack itemstack) { - return f().containsKey(itemstack.getItem()); - } - - @Override - public int[] getSlotsForFace(EnumDirection enumdirection) { - return enumdirection == EnumDirection.DOWN ? TileEntityFurnace.h : (enumdirection == EnumDirection.UP ? TileEntityFurnace.g : TileEntityFurnace.i); - } - - @Override - public boolean canPlaceItemThroughFace(int i, ItemStack itemstack, @Nullable EnumDirection enumdirection) { - return this.b(i, itemstack); - } - - @Override - public boolean canTakeItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { - if (enumdirection == EnumDirection.DOWN && i == 1) { - Item item = itemstack.getItem(); - - if (item != Items.WATER_BUCKET && item != Items.BUCKET) { - return false; - } - } - - return true; - } - - @Override - public int getSize() { - return this.items.size(); - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public ItemStack getItem(int i) { - return (ItemStack) this.items.get(i); - } - - @Override - public ItemStack splitStack(int i, int j) { - return ContainerUtil.a(this.items, i, j); - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - return ContainerUtil.a(this.items, i); - } - - @Override - public void setItem(int i, ItemStack itemstack) { - ItemStack itemstack1 = (ItemStack) this.items.get(i); - boolean flag = !itemstack.isEmpty() && itemstack.doMaterialsMatch(itemstack1) && ItemStack.equals(itemstack, itemstack1); - - this.items.set(i, itemstack); - if (itemstack.getCount() > this.getMaxStackSize()) { - itemstack.setCount(this.getMaxStackSize()); - } - - if (i == 0 && !flag) { - this.cookTimeTotal = this.getRecipeCookingTime(); - this.cookTime = 0; - this.update(); - } - - } - - @Override - public boolean a(EntityHuman entityhuman) { - return this.world.getTileEntity(this.position) != this ? false : entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; - } - - @Override - public boolean b(int i, ItemStack itemstack) { - if (i == 2) { - return false; - } else if (i != 1) { - return true; - } else { - ItemStack itemstack1 = (ItemStack) this.items.get(1); - - return isFuel(itemstack) || itemstack.getItem() == Items.BUCKET && itemstack1.getItem() != Items.BUCKET; - } - } - - @Override - public void clear() { - this.items.clear(); - } - - @Override - public void a(@Nullable IRecipe irecipe) { - if (irecipe != null) { - this.n.compute(irecipe.getKey(), (minecraftkey, integer) -> { - return 1 + (integer == null ? 0 : integer); - }); - } - - } - - @Nullable - @Override - public IRecipe U_() { - return null; - } - - @Override - public void b(EntityHuman entityhuman) {} - - public void d(EntityHuman entityhuman, ItemStack itemstack, int amount) { // CraftBukkit - List> list = Lists.newArrayList(); - Iterator iterator = this.n.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - entityhuman.world.getCraftingManager().a((MinecraftKey) entry.getKey()).ifPresent((irecipe) -> { - list.add(irecipe); - a(entityhuman, (Integer) entry.getValue(), ((RecipeCooking) irecipe).b(), itemstack, amount); // CraftBukkit - }); - } - - entityhuman.discoverRecipes(list); - this.n.clear(); - } - - private void a(EntityHuman entityhuman, int i, float f, ItemStack itemstack, int amount) { // CraftBukkit - 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 - if (amount != 0) { - FurnaceExtractEvent event = new FurnaceExtractEvent((Player) entityhuman.getBukkitEntity(), CraftBlock.at(world, position), org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(itemstack.getItem()), amount, i); - world.getServer().getPluginManager().callEvent(event); - i = event.getExpToDrop(); - } - // CraftBukkit end - - while (i > 0) { - j = EntityExperienceOrb.getOrbValue(i); - i -= j; - entityhuman.world.addEntity(new EntityExperienceOrb(entityhuman.world, entityhuman.locX, entityhuman.locY + 0.5D, entityhuman.locZ + 0.5D, j, org.bukkit.entity.ExperienceOrb.SpawnReason.FURNACE, entityhuman)); // Paper - } - - } - - @Override - public void a(AutoRecipeStackManager autorecipestackmanager) { - Iterator iterator = this.items.iterator(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - - autorecipestackmanager.b(itemstack); - } - - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityHopper.java b/src/main/java/net/minecraft/server/TileEntityHopper.java deleted file mode 100644 index 6f6519f6c..000000000 --- a/src/main/java/net/minecraft/server/TileEntityHopper.java +++ /dev/null @@ -1,696 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import javax.annotation.Nullable; - -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.inventory.InventoryMoveItemEvent; -import org.bukkit.event.inventory.InventoryPickupItemEvent; -import org.bukkit.inventory.Inventory; -// CraftBukkit end - -public class TileEntityHopper extends TileEntityLootable implements IHopper, ITickable { - - private NonNullList items; - private int j; - private long k; - - // CraftBukkit start - add fields and methods - public List transaction = new java.util.ArrayList(); - private int maxStack = MAX_STACK; - - public List 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; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - // CraftBukkit end - - public TileEntityHopper() { - super(TileEntityTypes.HOPPER); - this.items = NonNullList.a(5, ItemStack.a); - this.j = -1; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.items = NonNullList.a(this.getSize(), ItemStack.a); - if (!this.d(nbttagcompound)) { - ContainerUtil.b(nbttagcompound, this.items); - } - - this.j = nbttagcompound.getInt("TransferCooldown"); - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - if (!this.e(nbttagcompound)) { - ContainerUtil.a(nbttagcompound, this.items); - } - - nbttagcompound.setInt("TransferCooldown", this.j); - return nbttagcompound; - } - - @Override - public int getSize() { - return this.items.size(); - } - - @Override - public ItemStack splitStack(int i, int j) { - this.d((EntityHuman) null); - return ContainerUtil.a(this.f(), i, j); - } - - @Override - public void setItem(int i, ItemStack itemstack) { - this.d((EntityHuman) null); - this.f().set(i, itemstack); - if (itemstack.getCount() > this.getMaxStackSize()) { - itemstack.setCount(this.getMaxStackSize()); - } - - } - - @Override - protected IChatBaseComponent getContainerName() { - return new ChatMessage("container.hopper", new Object[0]); - } - - @Override - public void tick() { - if (this.world != null && !this.world.isClientSide) { - --this.j; - this.k = this.world.getTime(); - if (!this.v()) { - this.setCooldown(0); - // Spigot start - boolean result = this.a(() -> { - return a((IHopper) this); - }); - if (!result && this.world.spigotConfig.hopperCheck > 1) { - this.setCooldown(this.world.spigotConfig.hopperCheck); - } - // Spigot end - } - - } - } - - private boolean a(Supplier supplier) { - if (this.world != null && !this.world.isClientSide) { - if (!this.v() && (Boolean) this.getBlock().get(BlockHopper.ENABLED)) { - boolean flag = false; - - if (!this.h()) { - flag = this.t(); - } - - if (!this.s()) { - flag |= (Boolean) supplier.get(); - } - - if (flag) { - this.setCooldown(world.spigotConfig.hopperTransfer); // Spigot - this.update(); - return true; - } - } - - return false; - } else { - return false; - } - } - - private boolean h() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public boolean isNotEmpty() { - return this.h(); - } - - private boolean s() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (!itemstack.isEmpty() && itemstack.getCount() == itemstack.getMaxStackSize()); - - return false; - } - - // Paper start - Optimize Hoppers - private static boolean skipPullModeEventFire = false; - private static boolean skipPushModeEventFire = false; - static boolean skipHopperEvents = false; - - private boolean hopperPush(IInventory iinventory, EnumDirection enumdirection) { - skipPushModeEventFire = skipHopperEvents; - boolean foundItem = false; - for (int i = 0; i < this.getSize(); ++i) { - if (!this.getItem(i).isEmpty()) { - foundItem = true; - ItemStack origItemStack = this.getItem(i); - ItemStack itemstack = origItemStack; - - final int origCount = origItemStack.getCount(); - final int moved = Math.min(world.spigotConfig.hopperAmount, origCount); - origItemStack.setCount(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(iinventory, itemstack); - if (itemstack == null) { // cancelled - origItemStack.setCount(origCount); - return false; - } - } - final ItemStack itemstack2 = addItem(this, iinventory, itemstack, enumdirection); - final int remaining = itemstack2.getCount(); - if (remaining != moved) { - origItemStack = origItemStack.cloneItemStack(true); - origItemStack.setCount(origCount - moved + remaining); - this.setItem(i, origItemStack); - iinventory.update(); - return true; - } - origItemStack.setCount(origCount); - } - } - if (foundItem && world.paperConfig.cooldownHopperWhenFull) { // Inventory was full - cooldown - this.setCooldown(world.spigotConfig.hopperTransfer); - } - return false; - } - - private static boolean hopperPull(IHopper ihopper, IInventory iinventory, int i) { - ItemStack origItemStack = iinventory.getItem(i); - ItemStack itemstack = origItemStack; - final int origCount = origItemStack.getCount(); - final World world = ihopper.getWorld(); - final int moved = Math.min(world.spigotConfig.hopperAmount, origCount); - itemstack.setCount(moved); - - if (!skipPullModeEventFire) { - itemstack = callPullMoveEvent(ihopper, iinventory, itemstack); - if (itemstack == null) { // cancelled - origItemStack.setCount(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 = addItem(iinventory, ihopper, itemstack, null); - final int remaining = itemstack2.getCount(); - if (remaining != moved) { - origItemStack = origItemStack.cloneItemStack(true); - origItemStack.setCount(origCount - moved + remaining); - IGNORE_TILE_UPDATES = true; - iinventory.setItem(i, origItemStack); - IGNORE_TILE_UPDATES = false; - iinventory.update(); - return true; - } - origItemStack.setCount(origCount); - - if (world.paperConfig.cooldownHopperWhenFull) { - cooldownHopper(ihopper); - } - - return false; - } - - private ItemStack callPushMoveEvent(IInventory iinventory, ItemStack itemstack) { - Inventory destinationInventory = getInventory(iinventory); - InventoryMoveItemEvent event = new InventoryMoveItemEvent(this.getOwner(false).getInventory(), - CraftItemStack.asCraftMirror(itemstack), destinationInventory, true); - boolean result = event.callEvent(); - if (!event.calledGetItem && !event.calledSetItem) { - skipPushModeEventFire = true; - } - if (!result) { - cooldownHopper(this); - 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; - } - } - - private static Inventory getInventory(IInventory iinventory) { - 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 if (iinventory instanceof TileEntity) { - sourceInventory = ((TileEntity) iinventory).getOwner(false).getInventory(); - } else { - sourceInventory = iinventory.getOwner().getInventory(); - } - return sourceInventory; - } - - private static void cooldownHopper(IHopper hopper) { - if (hopper instanceof TileEntityHopper) { - ((TileEntityHopper) hopper).setCooldown(hopper.getWorld().spigotConfig.hopperTransfer); - } else if (hopper instanceof EntityMinecartHopper) { - ((EntityMinecartHopper) hopper).setCooldown(hopper.getWorld().spigotConfig.hopperTransfer / 2); - } - } - // Paper end - - private boolean t() { - IInventory iinventory = this.u(); - - if (iinventory == null) { - return false; - } else { - EnumDirection enumdirection = ((EnumDirection) this.getBlock().get(BlockHopper.FACING)).opposite(); - - if (this.b(iinventory, enumdirection)) { - return false; - } else { - return hopperPush(iinventory, enumdirection); /* // Paper - disable rest - for (int i = 0; i < this.getSize(); ++i) { - if (!this.getItem(i).isEmpty()) { - ItemStack itemstack = this.getItem(i).cloneItemStack(); - // ItemStack itemstack1 = addItem(this, iinventory, this.splitStack(i, 1), enumdirection); - - // CraftBukkit start - Call event when pushing items into other inventories - CraftItemStack oitemstack = CraftItemStack.asCraftMirror(this.splitStack(i, world.spigotConfig.hopperAmount)); // Spigot - - 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(); - } - - 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.setCooldown(world.spigotConfig.hopperTransfer); // Spigot - return false; - } - int origCount = event.getItem().getAmount(); // Spigot - ItemStack itemstack1 = addItem(this, iinventory, CraftItemStack.asNMSCopy(event.getItem()), enumdirection); - // CraftBukkit end - - if (itemstack1.isEmpty()) { - iinventory.update(); - return true; - } - - itemstack.subtract(origCount - itemstack1.getCount()); // Spigot - this.setItem(i, itemstack); - } - } - - return false;*/ // Paper - end commenting out replaced block for Hopper Optimizations - } - } - } - - private static IntStream a(IInventory iinventory, EnumDirection enumdirection) { - return iinventory instanceof IWorldInventory ? IntStream.of(((IWorldInventory) iinventory).getSlotsForFace(enumdirection)) : IntStream.range(0, iinventory.getSize()); - } - - private boolean b(IInventory iinventory, EnumDirection enumdirection) { - return a(iinventory, enumdirection).allMatch((i) -> { - ItemStack itemstack = iinventory.getItem(i); - - return itemstack.getCount() >= itemstack.getMaxStackSize(); - }); - } - - private static boolean c(IInventory iinventory, EnumDirection enumdirection) { - return a(iinventory, enumdirection).allMatch((i) -> { - return iinventory.getItem(i).isEmpty(); - }); - } - - public static boolean a(IHopper ihopper) { - IInventory iinventory = b(ihopper); - - if (iinventory != null) { - EnumDirection enumdirection = EnumDirection.DOWN; - - return c(iinventory, enumdirection) ? false : a(iinventory, enumdirection).anyMatch((i) -> { - skipPullModeEventFire = skipHopperEvents; // Paper - return a(ihopper, iinventory, i, enumdirection); - }); - } else { - Iterator iterator = c(ihopper).iterator(); - - EntityItem entityitem; - - do { - if (!iterator.hasNext()) { - return false; - } - - entityitem = (EntityItem) iterator.next(); - } while (!a((IInventory) ihopper, entityitem)); - - return true; - } - } - - private static boolean a(IHopper ihopper, IInventory iinventory, int i, EnumDirection enumdirection) { - ItemStack itemstack = iinventory.getItem(i); - - if (!itemstack.isEmpty() && b(iinventory, itemstack, i, enumdirection)) { - return hopperPull(ihopper, iinventory, i); /* // Paper - disable rest - ItemStack itemstack1 = itemstack.cloneItemStack(); - // ItemStack itemstack2 = addItem(iinventory, ihopper, iinventory.splitStack(i, 1), (EnumDirection) null); - // 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 - - 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).setCooldown(ihopper.getWorld().spigotConfig.hopperTransfer); // Spigot - } else if (ihopper instanceof EntityMinecartHopper) { - ((EntityMinecartHopper) ihopper).setCooldown(ihopper.getWorld().spigotConfig.hopperTransfer / 2); // Spigot - } - return false; - } - int origCount = event.getItem().getAmount(); // Spigot - ItemStack itemstack2 = addItem(iinventory, ihopper, CraftItemStack.asNMSCopy(event.getItem()), null); - // CraftBukkit end - - if (itemstack2.isEmpty()) { - iinventory.update(); - return true; - } - - itemstack1.subtract(origCount - itemstack2.getCount()); // Spigot - iinventory.setItem(i, itemstack1);*/ // Paper - end commenting out replaced block for Hopper Optimizations - } - - return false; - } - - public static boolean a(IInventory iinventory, EntityItem entityitem) { - boolean flag = false; - // CraftBukkit start - InventoryPickupItemEvent event = new InventoryPickupItemEvent(getInventory(iinventory), (org.bukkit.entity.Item) entityitem.getBukkitEntity()); // Paper - use getInventory() to avoid snapshot creation - entityitem.world.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return false; - } - // CraftBukkit end - ItemStack itemstack = entityitem.getItemStack().cloneItemStack(); - ItemStack itemstack1 = addItem((IInventory) null, iinventory, itemstack, (EnumDirection) null); - - if (itemstack1.isEmpty()) { - flag = true; - entityitem.die(); - } else { - entityitem.setItemStack(itemstack1); - } - - return flag; - } - - public static ItemStack addItem(@Nullable IInventory iinventory, IInventory iinventory1, ItemStack itemstack, @Nullable EnumDirection enumdirection) { - if (iinventory1 instanceof IWorldInventory && enumdirection != null) { - IWorldInventory iworldinventory = (IWorldInventory) iinventory1; - int[] aint = iworldinventory.getSlotsForFace(enumdirection); - - for (int i = 0; i < aint.length && !itemstack.isEmpty(); ++i) { - itemstack = a(iinventory, iinventory1, itemstack, aint[i], enumdirection); - } - } else { - int j = iinventory1.getSize(); - - for (int k = 0; k < j && !itemstack.isEmpty(); ++k) { - itemstack = a(iinventory, iinventory1, itemstack, k, enumdirection); - } - } - - return itemstack; - } - - private static boolean a(IInventory iinventory, ItemStack itemstack, int i, @Nullable EnumDirection enumdirection) { - return !iinventory.b(i, itemstack) ? false : !(iinventory instanceof IWorldInventory) || ((IWorldInventory) iinventory).canPlaceItemThroughFace(i, itemstack, enumdirection); - } - - 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 a(@Nullable IInventory iinventory, IInventory iinventory1, ItemStack itemstack, int i, @Nullable EnumDirection enumdirection) { - ItemStack itemstack1 = iinventory1.getItem(i); - - if (a(iinventory1, itemstack, i, enumdirection)) { - boolean flag = false; - boolean flag1 = iinventory1.isNotEmpty(); - - if (itemstack1.isEmpty()) { - IGNORE_TILE_UPDATES = true; // Paper - iinventory1.setItem(i, itemstack); - IGNORE_TILE_UPDATES = false; // Paper - itemstack = ItemStack.a; - flag = true; - } else if (a(itemstack1, itemstack)) { - int j = itemstack.getMaxStackSize() - itemstack1.getCount(); - int k = Math.min(itemstack.getCount(), j); - - itemstack.subtract(k); - itemstack1.add(k); - flag = k > 0; - } - - if (flag) { - if (flag1 && iinventory1 instanceof TileEntityHopper) { - TileEntityHopper tileentityhopper = (TileEntityHopper) iinventory1; - - if (!tileentityhopper.x()) { - byte b0 = 0; - - if (iinventory instanceof TileEntityHopper) { - TileEntityHopper tileentityhopper1 = (TileEntityHopper) iinventory; - - if (tileentityhopper.k >= tileentityhopper1.k) { - b0 = 1; - } - } - - tileentityhopper.setCooldown(tileentityhopper.world.spigotConfig.hopperTransfer - b0); // Spigot - } - } - - iinventory1.update(); - } - } - - return itemstack; - } - - @Nullable - private IInventory u() { - EnumDirection enumdirection = (EnumDirection) this.getBlock().get(BlockHopper.FACING); - - return a(this.getWorld(), this.position.shift(enumdirection)); - } - - @Nullable - public static IInventory b(IHopper ihopper) { - return a(ihopper.getWorld(), ihopper.z(), ihopper.A() + 1.0D, ihopper.B()); - } - - public static List c(IHopper ihopper) { - return (List) ihopper.N_().d().stream().flatMap((axisalignedbb) -> { - return ihopper.getWorld().a(EntityItem.class, axisalignedbb.d(ihopper.z() - 0.5D, ihopper.A() - 0.5D, ihopper.B() - 0.5D), IEntitySelector.a).stream(); - }).collect(Collectors.toList()); - } - - @Nullable - public static IInventory a(World world, BlockPosition blockposition) { - return a(world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D); - } - - @Nullable - public static IInventory a(World world, double d0, double d1, double d2) { - Object object = null; - BlockPosition blockposition = new BlockPosition(d0, d1, d2); - if ( !world.isLoaded( blockposition ) ) return null; // Spigot - IBlockData iblockdata = world.getType(blockposition); - Block block = iblockdata.getBlock(); - - if (block instanceof IInventoryHolder) { - object = ((IInventoryHolder) block).a(iblockdata, world, blockposition); - } else if (block.isTileEntity()) { - TileEntity tileentity = world.getTileEntity(blockposition); - - if (tileentity instanceof IInventory) { - object = (IInventory) tileentity; - if (object instanceof TileEntityChest && block instanceof BlockChest) { - object = BlockChest.getInventory(iblockdata, world, blockposition, true); - } - } - } - - if (object == null) { - List list = world.getEntities((Entity) null, new AxisAlignedBB(d0 - 0.5D, d1 - 0.5D, d2 - 0.5D, d0 + 0.5D, d1 + 0.5D, d2 + 0.5D), IEntitySelector.d); - - if (!list.isEmpty()) { - object = (IInventory) list.get(world.random.nextInt(list.size())); - } - } - - return (IInventory) object; - } - - private static boolean a(ItemStack itemstack, ItemStack itemstack1) { - return itemstack.getItem() != itemstack1.getItem() ? false : (itemstack.getDamage() != itemstack1.getDamage() ? false : (itemstack.getCount() > itemstack.getMaxStackSize() ? false : ItemStack.equals(itemstack, itemstack1))); - } - - @Override - public double z() { - return (double) this.position.getX() + 0.5D; - } - - @Override - public double A() { - return (double) this.position.getY() + 0.5D; - } - - @Override - public double B() { - return (double) this.position.getZ() + 0.5D; - } - - private void setCooldown(int i) { - this.j = i; - } - - private boolean v() { - return this.j > 0; - } - - private boolean x() { - return this.j > 8; - } - - @Override - protected NonNullList f() { - return this.items; - } - - @Override - protected void a(NonNullList nonnulllist) { - this.items = nonnulllist; - } - - public void a(Entity entity) { - if (entity instanceof EntityItem) { - BlockPosition blockposition = this.getPosition(); - - if (VoxelShapes.c(VoxelShapes.a(entity.getBoundingBox().d((double) (-blockposition.getX()), (double) (-blockposition.getY()), (double) (-blockposition.getZ()))), this.N_(), OperatorBoolean.AND)) { - this.a(() -> { - return a((IInventory) this, (EntityItem) entity); - }); - } - } - - } - - @Override - protected Container createContainer(int i, PlayerInventory playerinventory) { - return new ContainerHopper(i, playerinventory, this); - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityLectern.java b/src/main/java/net/minecraft/server/TileEntityLectern.java deleted file mode 100644 index 221de42e5..000000000 --- a/src/main/java/net/minecraft/server/TileEntityLectern.java +++ /dev/null @@ -1,310 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -// CraftBukkit start -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.bukkit.Location; -import org.bukkit.block.Lectern; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.InventoryHolder; -// CraftBukkit end - -public class TileEntityLectern extends TileEntity implements Clearable, ITileInventory, ICommandListener { // CraftBukkit - ICommandListener - - // CraftBukkit start - add fields and methods - public final IInventory inventory = new LecternInventory(); - public class LecternInventory implements IInventory { - - public List transaction = new ArrayList<>(); - private int maxStack = 1; - - @Override - public List getContents() { - return Arrays.asList(book); - } - - @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 void setMaxStackSize(int i) { - maxStack = i; - } - - @Override - public Location getLocation() { - return new Location(world.getWorld(), position.getX(), position.getY(), position.getZ()); - } - - @Override - public InventoryHolder getOwner() { - return (Lectern) TileEntityLectern.this.getOwner(); - } - // CraftBukkit end - - @Override - public int getSize() { - return 1; - } - - @Override - public boolean isNotEmpty() { - return TileEntityLectern.this.book.isEmpty(); - } - - @Override - public ItemStack getItem(int i) { - return i == 0 ? TileEntityLectern.this.book : ItemStack.a; - } - - @Override - public ItemStack splitStack(int i, int j) { - if (i == 0) { - ItemStack itemstack = TileEntityLectern.this.book.cloneAndSubtract(j); - - if (TileEntityLectern.this.book.isEmpty()) { - TileEntityLectern.this.t(); - } - - return itemstack; - } else { - return ItemStack.a; - } - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - if (i == 0) { - ItemStack itemstack = TileEntityLectern.this.book; - - TileEntityLectern.this.book = ItemStack.a; - TileEntityLectern.this.t(); - return itemstack; - } else { - return ItemStack.a; - } - } - - @Override - // CraftBukkit start - public void setItem(int i, ItemStack itemstack) { - if (i == 0) { - TileEntityLectern.this.setBook(itemstack); - if (TileEntityLectern.this.getWorld() != null) { - BlockLectern.setHasBook(TileEntityLectern.this.getWorld(), TileEntityLectern.this.getPosition(), TileEntityLectern.this.getBlock(), TileEntityLectern.this.hasBook()); - } - } - } - // CraftBukkit end - - @Override - public int getMaxStackSize() { - return maxStack; // CraftBukkit - } - - @Override - public void update() { - TileEntityLectern.this.update(); - } - - @Override - public boolean a(EntityHuman entityhuman) { - return TileEntityLectern.this.world.getTileEntity(TileEntityLectern.this.position) != TileEntityLectern.this ? false : (entityhuman.e((double) TileEntityLectern.this.position.getX() + 0.5D, (double) TileEntityLectern.this.position.getY() + 0.5D, (double) TileEntityLectern.this.position.getZ() + 0.5D) > 64.0D ? false : TileEntityLectern.this.hasBook()); - } - - @Override - public boolean b(int i, ItemStack itemstack) { - return false; - } - - @Override - public void clear() {} - }; - private final IContainerProperties containerProperties = new IContainerProperties() { - @Override - public int getProperty(int i) { - return i == 0 ? TileEntityLectern.this.page : 0; - } - - @Override - public void setProperty(int i, int j) { - if (i == 0) { - TileEntityLectern.this.setPage(j); - } - - } - - @Override - public int a() { - return 1; - } - }; - private ItemStack book; - private int page; - private int maxPage; - - public TileEntityLectern() { - super(TileEntityTypes.LECTERN); - this.book = ItemStack.a; - } - - public ItemStack getBook() { - return this.book; - } - - public boolean hasBook() { - Item item = this.book.getItem(); - - return item == Items.WRITABLE_BOOK || item == Items.WRITTEN_BOOK; - } - - public void setBook(ItemStack itemstack) { - this.a(itemstack, (EntityHuman) null); - } - - private void t() { - this.page = 0; - this.maxPage = 0; - BlockLectern.setHasBook(this.getWorld(), this.getPosition(), this.getBlock(), false); - } - - public void a(ItemStack itemstack, @Nullable EntityHuman entityhuman) { - this.book = this.b(itemstack, entityhuman); - this.page = 0; - this.maxPage = ItemWrittenBook.j(this.book); - this.update(); - } - - public void setPage(int i) { - int j = MathHelper.clamp(i, 0, this.maxPage - 1); - - if (j != this.page) { - this.page = j; - this.update(); - BlockLectern.a(this.getWorld(), this.getPosition(), this.getBlock()); - } - - } - - public int getPage() { - return this.page; - } - - public int s() { - float f = this.maxPage > 1 ? (float) this.getPage() / ((float) this.maxPage - 1.0F) : 1.0F; - - return MathHelper.d(f * 14.0F) + (this.hasBook() ? 1 : 0); - } - - private ItemStack b(ItemStack itemstack, @Nullable EntityHuman entityhuman) { - if (this.world instanceof WorldServer && itemstack.getItem() == Items.WRITTEN_BOOK) { - ItemWrittenBook.a(itemstack, this.a(entityhuman), entityhuman); - } - - return itemstack; - } - - // CraftBukkit start - @Override - public void sendMessage(IChatBaseComponent ichatbasecomponent) { - } - - @Override - public org.bukkit.command.CommandSender getBukkitSender(CommandListenerWrapper wrapper) { - return wrapper.getEntity() != null ? wrapper.getEntity().getBukkitSender(wrapper) : new org.bukkit.craftbukkit.command.CraftBlockCommandSender(wrapper, this); - } - - @Override - public boolean shouldSendSuccess() { - return false; - } - - @Override - public boolean shouldSendFailure() { - return false; - } - - @Override - public boolean shouldBroadcastCommands() { - return false; - } - - // CraftBukkit end - private CommandListenerWrapper a(@Nullable EntityHuman entityhuman) { - String s; - Object object; - - if (entityhuman == null) { - s = "Lectern"; - object = new ChatComponentText("Lectern"); - } else { - s = entityhuman.getDisplayName().getString(); - object = entityhuman.getScoreboardDisplayName(); - } - - Vec3D vec3d = new Vec3D((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D); - - // CraftBukkit - this - return new CommandListenerWrapper(this, vec3d, Vec2F.a, (WorldServer) this.world, 2, s, (IChatBaseComponent) object, this.world.getMinecraftServer(), entityhuman); - } - - @Override - public boolean isFilteredNBT() { - return true; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - if (nbttagcompound.hasKeyOfType("Book", 10)) { - this.book = this.b(ItemStack.a(nbttagcompound.getCompound("Book")), (EntityHuman) null); - } else { - this.book = ItemStack.a; - } - - this.maxPage = ItemWrittenBook.j(this.book); - this.page = MathHelper.clamp(nbttagcompound.getInt("Page"), 0, this.maxPage - 1); - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - if (!this.getBook().isEmpty()) { - nbttagcompound.set("Book", this.getBook().save(new NBTTagCompound())); - nbttagcompound.setInt("Page", this.page); - } - - return nbttagcompound; - } - - @Override - public void clear() { - this.setBook(ItemStack.a); - } - - @Override - public Container createMenu(int i, PlayerInventory playerinventory, EntityHuman entityhuman) { - return new ContainerLectern(i, this.inventory, this.containerProperties, playerinventory); // CraftBukkit - } - - @Override - public IChatBaseComponent getScoreboardDisplayName() { - return new ChatMessage("container.lectern", new Object[0]); - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityLootable.java b/src/main/java/net/minecraft/server/TileEntityLootable.java deleted file mode 100644 index a12d49fc4..000000000 --- a/src/main/java/net/minecraft/server/TileEntityLootable.java +++ /dev/null @@ -1,136 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public abstract class TileEntityLootable extends TileEntityContainer { - - @Nullable - public MinecraftKey lootTable; public MinecraftKey getLootTableKey() { return this.lootTable; } public void setLootTable(final MinecraftKey key) { this.lootTable = key; } // Paper - OBFHELPER - public long lootTableSeed; public long getSeed() { return this.lootTableSeed; } public void setSeed(final long seed) { this.lootTableSeed = seed; } // Paper - OBFHELPER - public final com.destroystokyo.paper.loottable.PaperLootableInventoryData lootableData = new com.destroystokyo.paper.loottable.PaperLootableInventoryData(new com.destroystokyo.paper.loottable.PaperTileEntityLootableInventory(this)); // Paper - - protected TileEntityLootable(TileEntityTypes tileentitytypes) { - super(tileentitytypes); - } - - public static void a(IBlockAccess iblockaccess, Random random, BlockPosition blockposition, MinecraftKey minecraftkey) { - TileEntity tileentity = iblockaccess.getTileEntity(blockposition); - - if (tileentity instanceof TileEntityLootable) { - ((TileEntityLootable) tileentity).setLootTable(minecraftkey, random.nextLong()); - } - - } - - protected boolean d(NBTTagCompound nbttagcompound) { - this.lootableData.loadNbt(nbttagcompound); // Paper - if (nbttagcompound.hasKeyOfType("LootTable", 8)) { - this.lootTable = new MinecraftKey(nbttagcompound.getString("LootTable")); - this.lootTableSeed = nbttagcompound.getLong("LootTableSeed"); - return false; // Paper - always load the items, table may still remain - } else { - return false; - } - } - - protected boolean e(NBTTagCompound nbttagcompound) { - this.lootableData.saveNbt(nbttagcompound); // Paper - if (this.lootTable == null) { - return false; - } else { - nbttagcompound.setString("LootTable", this.lootTable.toString()); - if (this.lootTableSeed != 0L) { - nbttagcompound.setLong("LootTableSeed", this.lootTableSeed); - } - - return false; // Paper - always save the items, table may still remain - } - } - - public void d(@Nullable EntityHuman entityhuman) { - if (this.lootableData.shouldReplenish(entityhuman) && this.world.getMinecraftServer() != null) { // Paper - LootTable loottable = this.world.getMinecraftServer().getLootTableRegistry().getLootTable(this.lootTable); - - this.lootableData.processRefill(entityhuman); // Paper - LootTableInfo.Builder loottableinfo_builder = (new LootTableInfo.Builder((WorldServer) this.world)).set(LootContextParameters.POSITION, new BlockPosition(this.position)).a(this.lootTableSeed); - - if (entityhuman != null) { - loottableinfo_builder.a(entityhuman.eb()).set(LootContextParameters.THIS_ENTITY, entityhuman); - } - - loottable.fillInventory(this, loottableinfo_builder.build(LootContextParameterSets.CHEST)); - } - - } - - public void setLootTable(MinecraftKey minecraftkey, long i) { - this.lootTable = minecraftkey; - this.lootTableSeed = i; - } - - @Override - public ItemStack getItem(int i) { - this.d((EntityHuman) null); - return (ItemStack) this.f().get(i); - } - - @Override - public ItemStack splitStack(int i, int j) { - this.d((EntityHuman) null); - ItemStack itemstack = ContainerUtil.a(this.f(), i, j); - - if (!itemstack.isEmpty()) { - this.update(); - } - - return itemstack; - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - this.d((EntityHuman) null); - return ContainerUtil.a(this.f(), i); - } - - @Override - public void setItem(int i, ItemStack itemstack) { - this.d((EntityHuman) null); - this.f().set(i, itemstack); - if (itemstack.getCount() > this.getMaxStackSize()) { - itemstack.setCount(this.getMaxStackSize()); - } - - this.update(); - } - - @Override - public boolean a(EntityHuman entityhuman) { - return this.world.getTileEntity(this.position) != this ? false : entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; - } - - @Override - public void clear() { - this.f().clear(); - } - - protected abstract NonNullList f(); - - protected abstract void a(NonNullList nonnulllist); - - @Override - public boolean e(EntityHuman entityhuman) { - return super.e(entityhuman) && (this.lootTable == null || !entityhuman.isSpectator()); - } - - @Nullable - @Override - public Container createMenu(int i, PlayerInventory playerinventory, EntityHuman entityhuman) { - if (this.e(entityhuman)) { - this.d(playerinventory.player); - return this.createContainer(i, playerinventory); - } else { - return null; - } - } -} diff --git a/src/main/java/net/minecraft/server/TileEntityShulkerBox.java b/src/main/java/net/minecraft/server/TileEntityShulkerBox.java deleted file mode 100644 index fe64a99bd..000000000 --- a/src/main/java/net/minecraft/server/TileEntityShulkerBox.java +++ /dev/null @@ -1,325 +0,0 @@ -package net.minecraft.server; - -import java.util.Iterator; -import java.util.List; -import java.util.stream.IntStream; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -// CraftBukkit end - -public class TileEntityShulkerBox extends TileEntityLootable implements IWorldInventory, ITickable { - - private static final int[] a = IntStream.range(0, 27).toArray(); - private NonNullList contents; - private int c; - private TileEntityShulkerBox.AnimationPhase i; - private float j; - private float k; - private EnumColor l; - private boolean m; - - // CraftBukkit start - add fields and methods - public List transaction = new java.util.ArrayList(); - private int maxStack = MAX_STACK; - - public List getContents() { - return this.contents; - } - - public void onOpen(CraftHumanEntity who) { - transaction.add(who); - } - - public void onClose(CraftHumanEntity who) { - transaction.remove(who); - } - - public List getViewers() { - return transaction; - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - public void setMaxStackSize(int size) { - maxStack = size; - } - // CraftBukkit end - - public TileEntityShulkerBox(@Nullable EnumColor enumcolor) { - super(TileEntityTypes.SHULKER_BOX); - this.contents = NonNullList.a(27, ItemStack.a); - this.i = TileEntityShulkerBox.AnimationPhase.CLOSED; - this.l = enumcolor; - } - - public TileEntityShulkerBox() { - this((EnumColor) null); - this.m = true; - } - - @Override - public void tick() { - this.h(); - if (this.i == TileEntityShulkerBox.AnimationPhase.OPENING || this.i == TileEntityShulkerBox.AnimationPhase.CLOSING) { - this.u(); - } - - } - - protected void h() { - this.k = this.j; - switch (this.i) { - case CLOSED: - this.j = 0.0F; - break; - case OPENING: - this.j += 0.1F; - if (this.j >= 1.0F) { - this.u(); - this.i = TileEntityShulkerBox.AnimationPhase.OPENED; - this.j = 1.0F; - this.v(); - } - break; - case CLOSING: - this.j -= 0.1F; - if (this.j <= 0.0F) { - this.i = TileEntityShulkerBox.AnimationPhase.CLOSED; - this.j = 0.0F; - this.v(); - } - break; - case OPENED: - this.j = 1.0F; - } - - } - - public TileEntityShulkerBox.AnimationPhase s() { - return this.i; - } - - public AxisAlignedBB a(IBlockData iblockdata) { - return this.b((EnumDirection) iblockdata.get(BlockShulkerBox.a)); - } - - public AxisAlignedBB b(EnumDirection enumdirection) { - float f = this.a(1.0F); - - return VoxelShapes.b().getBoundingBox().b((double) (0.5F * f * (float) enumdirection.getAdjacentX()), (double) (0.5F * f * (float) enumdirection.getAdjacentY()), (double) (0.5F * f * (float) enumdirection.getAdjacentZ())); - } - - private AxisAlignedBB c(EnumDirection enumdirection) { - EnumDirection enumdirection1 = enumdirection.opposite(); - - return this.b(enumdirection).a((double) enumdirection1.getAdjacentX(), (double) enumdirection1.getAdjacentY(), (double) enumdirection1.getAdjacentZ()); - } - - private void u() { - IBlockData iblockdata = this.world.getType(this.getPosition()); - - if (iblockdata.getBlock() instanceof BlockShulkerBox) { - EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockShulkerBox.a); - AxisAlignedBB axisalignedbb = this.c(enumdirection).a(this.position); - List list = this.world.getEntities((Entity) null, axisalignedbb); - - if (!list.isEmpty()) { - for (int i = 0; i < list.size(); ++i) { - Entity entity = (Entity) list.get(i); - - if (entity.getPushReaction() != EnumPistonReaction.IGNORE) { - double d0 = 0.0D; - double d1 = 0.0D; - double d2 = 0.0D; - AxisAlignedBB axisalignedbb1 = entity.getBoundingBox(); - - switch (enumdirection.k()) { - case X: - if (enumdirection.c() == EnumDirection.EnumAxisDirection.POSITIVE) { - d0 = axisalignedbb.maxX - axisalignedbb1.minX; - } else { - d0 = axisalignedbb1.maxX - axisalignedbb.minX; - } - - d0 += 0.01D; - break; - case Y: - if (enumdirection.c() == EnumDirection.EnumAxisDirection.POSITIVE) { - d1 = axisalignedbb.maxY - axisalignedbb1.minY; - } else { - d1 = axisalignedbb1.maxY - axisalignedbb.minY; - } - - d1 += 0.01D; - break; - case Z: - if (enumdirection.c() == EnumDirection.EnumAxisDirection.POSITIVE) { - d2 = axisalignedbb.maxZ - axisalignedbb1.minZ; - } else { - d2 = axisalignedbb1.maxZ - axisalignedbb.minZ; - } - - d2 += 0.01D; - } - - entity.move(EnumMoveType.SHULKER_BOX, new Vec3D(d0 * (double) enumdirection.getAdjacentX(), d1 * (double) enumdirection.getAdjacentY(), d2 * (double) enumdirection.getAdjacentZ())); - } - } - - } - } - } - - @Override - public int getSize() { - return this.contents.size(); - } - - @Override - public boolean setProperty(int i, int j) { - if (i == 1) { - this.c = j; - if (j == 0) { - this.i = TileEntityShulkerBox.AnimationPhase.CLOSING; - this.v(); - } - - if (j == 1) { - this.i = TileEntityShulkerBox.AnimationPhase.OPENING; - this.v(); - } - - return true; - } else { - return super.setProperty(i, j); - } - } - - private void v() { - this.getBlock().a(this.getWorld(), this.getPosition(), 3); - } - - @Override - public void startOpen(EntityHuman entityhuman) { - if (!entityhuman.isSpectator()) { - if (this.c < 0) { - this.c = 0; - } - - ++this.c; - this.world.playBlockAction(this.position, this.getBlock().getBlock(), 1, this.c); - if (this.c == 1) { - this.world.playSound((EntityHuman) null, this.position, SoundEffects.BLOCK_SHULKER_BOX_OPEN, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); - } - } - - } - - @Override - public void closeContainer(EntityHuman entityhuman) { - if (!entityhuman.isSpectator()) { - --this.c; - this.world.playBlockAction(this.position, this.getBlock().getBlock(), 1, this.c); - if (this.c <= 0) { - this.world.playSound((EntityHuman) null, this.position, SoundEffects.BLOCK_SHULKER_BOX_CLOSE, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); - } - } - - } - - @Override - protected IChatBaseComponent getContainerName() { - return new ChatMessage("container.shulkerBox", new Object[0]); - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - this.f(nbttagcompound); - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - return this.g(nbttagcompound); - } - - public void f(NBTTagCompound nbttagcompound) { - this.contents = NonNullList.a(this.getSize(), ItemStack.a); - if (!this.d(nbttagcompound) && nbttagcompound.hasKeyOfType("Items", 9)) { - ContainerUtil.b(nbttagcompound, this.contents); - } - - } - - public NBTTagCompound g(NBTTagCompound nbttagcompound) { - if (!this.e(nbttagcompound)) { - ContainerUtil.a(nbttagcompound, this.contents, false); - } - - return nbttagcompound; - } - - @Override - protected NonNullList f() { - return this.contents; - } - - @Override - protected void a(NonNullList nonnulllist) { - this.contents = nonnulllist; - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.contents.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - - @Override - public int[] getSlotsForFace(EnumDirection enumdirection) { - return TileEntityShulkerBox.a; - } - - @Override - public boolean canPlaceItemThroughFace(int i, ItemStack itemstack, @Nullable EnumDirection enumdirection) { - return !(Block.asBlock(itemstack.getItem()) instanceof BlockShulkerBox); - } - - @Override - public boolean canTakeItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { - return true; - } - - public float a(float f) { - return MathHelper.g(f, this.k, this.j); - } - - @Override - protected Container createContainer(int i, PlayerInventory playerinventory) { - return new ContainerShulkerBox(i, playerinventory, this); - } - - public static enum AnimationPhase { - - CLOSED, OPENING, OPENED, CLOSING; - - private AnimationPhase() {} - } -} diff --git a/src/main/java/net/minecraft/server/TileEntitySign.java b/src/main/java/net/minecraft/server/TileEntitySign.java deleted file mode 100644 index 0a8d9b52d..000000000 --- a/src/main/java/net/minecraft/server/TileEntitySign.java +++ /dev/null @@ -1,223 +0,0 @@ -package net.minecraft.server; - -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import javax.annotation.Nullable; - -public class TileEntitySign extends TileEntity implements ICommandListener { // CraftBukkit - implements - - public final IChatBaseComponent[] lines = new IChatBaseComponent[]{new ChatComponentText(""), new ChatComponentText(""), new ChatComponentText(""), new ChatComponentText("")}; - private int c = -1; - private int g = -1; - private int h = -1; - public boolean isEditable = true; - private EntityHuman j; - private final String[] k = new String[4]; - private EnumColor color; - - // Paper start - Strip invalid unicode from signs on load - private static final boolean keepInvalidUnicode = Boolean.getBoolean("Paper.keepInvalidUnicode"); // Allow people to keep their bad unicode if they really want it - private boolean privateUnicodeRemoved = false; - public java.util.UUID signEditor; - private static final boolean CONVERT_LEGACY_SIGNS = Boolean.getBoolean("convertLegacySigns"); - // Paper end - - public TileEntitySign() { - super(TileEntityTypes.SIGN); - this.color = EnumColor.BLACK; - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(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 (CONVERT_LEGACY_SIGNS) { // Paper - nbttagcompound.setBoolean("Bukkit.isConverted", true); - } - // CraftBukkit end - - nbttagcompound.setString("Color", this.color.b()); - // Paper start - Only remove private area unicode once // TODO - this doesn't need to run for every sign, check data ver - if (this.privateUnicodeRemoved) { - nbttagcompound.setBoolean("Paper.RemovedPrivateUnicode", true); - } - // Paper end - - return nbttagcompound; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - this.isEditable = false; - super.load(nbttagcompound); - this.color = EnumColor.a(nbttagcompound.getString("Color"), EnumColor.BLACK); - - // Paper start - Keep track, only do it once per sign - this.privateUnicodeRemoved = nbttagcompound.getBoolean("Paper.RemovedPrivateUnicode"); - boolean ranUnicodeRemoval = false; - // Paper end - - // 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 = "\"\""; - } - - // Paper start - Strip private use area unicode from signs - if (s != null && !keepInvalidUnicode && !this.privateUnicodeRemoved) { - StringBuilder builder = new StringBuilder(); - for (char character : s.toCharArray()) { - if (Character.UnicodeBlock.of(character) != Character.UnicodeBlock.PRIVATE_USE_AREA) { - builder.append(character); - } - } - s = builder.toString(); - ranUnicodeRemoval = true; - } - // Paper end - - try { - //IChatBaseComponent ichatbasecomponent = IChatBaseComponent.ChatSerializer.a(s.isEmpty() ? "\"\"" : s); // Paper - move down - the old format might throw a json error - - if (oldSign && !isLoadingStructure) { // Paper - saved structures will be in the new format, but will not have isConverted - lines[i] = org.bukkit.craftbukkit.util.CraftChatMessage.fromString(s)[0]; - continue; - } - // CraftBukkit end - IChatBaseComponent ichatbasecomponent = IChatBaseComponent.ChatSerializer.a(s.isEmpty() ? "\"\"" : s); // Paper - after old sign - - if (this.world instanceof WorldServer) { - try { - this.lines[i] = ChatComponentUtils.filterForDisplay(this.a((EntityPlayer) null), ichatbasecomponent, (Entity) null, 0); - } catch (CommandSyntaxException commandsyntaxexception) { - this.lines[i] = ichatbasecomponent; - } - } else { - this.lines[i] = ichatbasecomponent; - } - } catch (com.google.gson.JsonParseException jsonparseexception) { - this.lines[i] = new ChatComponentText(s); - } - - this.k[i] = null; - } - - if (ranUnicodeRemoval) this.privateUnicodeRemoved = true; // Paper - Flag to write NBT - } - - public void a(int i, IChatBaseComponent ichatbasecomponent) { - this.lines[i] = ichatbasecomponent; - this.k[i] = null; - } - - @Nullable - @Override - public PacketPlayOutTileEntityData getUpdatePacket() { - return new PacketPlayOutTileEntityData(this.position, 9, this.b()); - } - - @Override - public NBTTagCompound b() { - return this.save(new NBTTagCompound()); - } - - @Override - public boolean isFilteredNBT() { - return true; - } - - public boolean d() { - return this.isEditable; - } - - public void a(EntityHuman entityhuman) { - // Paper start - //this.g = entityhuman; - signEditor = entityhuman != null ? entityhuman.getUniqueID() : null; - // Paper end - } - - public EntityHuman f() { - return this.j; - } - - public boolean b(EntityHuman entityhuman) { - IChatBaseComponent[] aichatbasecomponent = this.lines; - int i = aichatbasecomponent.length; - - for (int j = 0; j < i; ++j) { - IChatBaseComponent ichatbasecomponent = aichatbasecomponent[j]; - ChatModifier chatmodifier = ichatbasecomponent == null ? null : ichatbasecomponent.getChatModifier(); - - if (chatmodifier != null && chatmodifier.getClickEvent() != null) { - ChatClickable chatclickable = chatmodifier.getClickEvent(); - - if (chatclickable.a() == ChatClickable.EnumClickAction.RUN_COMMAND) { - entityhuman.getMinecraftServer().getCommandDispatcher().a(this.a((EntityPlayer) entityhuman), chatclickable.b()); - } - } - } - - return true; - } - - // CraftBukkit start - @Override - public void sendMessage(IChatBaseComponent ichatbasecomponent) {} - - @Override - public org.bukkit.command.CommandSender getBukkitSender(CommandListenerWrapper wrapper) { - return wrapper.getEntity() != null ? wrapper.getEntity().getBukkitSender(wrapper) : new org.bukkit.craftbukkit.command.CraftBlockCommandSender(wrapper, this); - } - - @Override - public boolean shouldSendSuccess() { - return false; - } - - @Override - public boolean shouldSendFailure() { - return false; - } - - @Override - public boolean shouldBroadcastCommands() { - return false; - } - // CraftBukkit end - - public CommandListenerWrapper a(@Nullable EntityPlayer entityplayer) { - String s = entityplayer == null ? "Sign" : entityplayer.getDisplayName().getString(); - Object object = entityplayer == null ? new ChatComponentText("Sign") : entityplayer.getScoreboardDisplayName(); - - // CraftBukkit - this - return new CommandListenerWrapper(this, new Vec3D((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D), Vec2F.a, (WorldServer) this.world, 2, s, (IChatBaseComponent) object, this.world.getMinecraftServer(), entityplayer); - } - - public EnumColor getColor() { - return this.color; - } - - public boolean setColor(EnumColor enumcolor) { - if (enumcolor != this.getColor()) { - this.color = enumcolor; - this.update(); - if (this.world != null) this.world.notify(this.getPosition(), this.getBlock(), this.getBlock(), 3); // CraftBukkit - skip notify if world is null (SPIGOT-5122) - return true; - } else { - return false; - } - } -} diff --git a/src/main/java/net/minecraft/server/TileEntitySkull.java b/src/main/java/net/minecraft/server/TileEntitySkull.java deleted file mode 100644 index 0882d82ce..000000000 --- a/src/main/java/net/minecraft/server/TileEntitySkull.java +++ /dev/null @@ -1,251 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Iterables; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.minecraft.MinecraftSessionService; -import com.mojang.authlib.properties.Property; -import java.util.UUID; -import javax.annotation.Nullable; - -// Spigot start -import com.google.common.base.Predicate; -import com.google.common.cache.LoadingCache; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.util.concurrent.Futures; -import java.util.concurrent.Executors; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import com.mojang.authlib.Agent; -import com.mojang.authlib.ProfileLookupCallback; -import java.util.concurrent.Callable; -// Spigot end - -public class TileEntitySkull extends TileEntity /*implements ITickable*/ { // Paper - remove tickable - - public GameProfile gameProfile; - private int b; - private boolean c; - private static UserCache userCache; - private static MinecraftSessionService sessionService; - // Spigot start - public static final ExecutorService executor = Executors.newFixedThreadPool(3, - new ThreadFactoryBuilder() - .setNameFormat("Head Conversion Thread - %1$d") - .build() - ); - 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 = TileEntitySkull.sessionService.fillProfileProperties( profile, true ); - } - } - - - return profile; - } - } ); - // Spigot end - - public TileEntitySkull() { - super(TileEntityTypes.SKULL); - } - - public static void a(UserCache usercache) { - TileEntitySkull.userCache = usercache; - } - - public static void a(MinecraftSessionService minecraftsessionservice) { - TileEntitySkull.sessionService = minecraftsessionservice; - } - - @Override - public NBTTagCompound save(NBTTagCompound nbttagcompound) { - super.save(nbttagcompound); - if (this.gameProfile != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - GameProfileSerializer.serialize(nbttagcompound1, this.gameProfile); - nbttagcompound.set("Owner", nbttagcompound1); - } - - return nbttagcompound; - } - - @Override - public void load(NBTTagCompound nbttagcompound) { - super.load(nbttagcompound); - if (nbttagcompound.hasKeyOfType("Owner", 10)) { - this.setGameProfile(GameProfileSerializer.deserialize(nbttagcompound.getCompound("Owner"))); - } else if (nbttagcompound.hasKeyOfType("ExtraType", 8)) { - String s = nbttagcompound.getString("ExtraType"); - - if (!UtilColor.b(s)) { - this.setGameProfile(new GameProfile((UUID) null, s)); - } - } - - } - - // Paper - remove override - public void tick() { - Block block = this.getBlock().getBlock(); - - if (block == Blocks.DRAGON_HEAD || block == Blocks.DRAGON_WALL_HEAD) { - if (this.world.isBlockIndirectlyPowered(this.position)) { - this.c = true; - ++this.b; - } else { - this.c = false; - } - } - - } - - @Nullable - @Override - public PacketPlayOutTileEntityData getUpdatePacket() { - return new PacketPlayOutTileEntityData(this.position, 4, sanitizeTileEntityUUID(this.b())); // Paper - } - - // Paper start - static NBTTagCompound sanitizeTileEntityUUID(NBTTagCompound cmp) { - NBTTagCompound owner = cmp.getCompound("Owner"); - if (!owner.isEmpty()) { - sanitizeUUID(owner); - } - return cmp; - } - - static void sanitizeUUID(NBTTagCompound owner) { - NBTTagCompound properties = owner.getCompound("Properties"); - NBTTagList list = null; - if (!properties.isEmpty()) { - list = properties.getList("textures", 10); - } - - if (list != null && !list.isEmpty()) { - String textures = ((NBTTagCompound)list.get(0)).getString("Value"); - if (textures != null && textures.length() > 3) { - String uuid = UUID.nameUUIDFromBytes(textures.getBytes()).toString(); - owner.setString("Id", uuid); - return; - } - } - owner.setString("Id", UUID.randomUUID().toString()); - } - // Paper end - - @Override - public NBTTagCompound b() { - return this.save(new NBTTagCompound()); - } - - public void setGameProfile(@Nullable GameProfile gameprofile) { - this.gameProfile = gameprofile; - this.f(); - } - - private void f() { - // Spigot start - GameProfile profile = this.gameProfile; - b(profile, new Predicate() { - - @Override - public boolean apply(GameProfile input) { - gameProfile = input; - update(); - return false; - } - }, false); - // Spigot end - } - - // Spigot start - Support async lookups - public static Future b(final GameProfile gameprofile, final Predicate callback, boolean sync) { - if (gameprofile != null && !UtilColor.b(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(java.util.Locale.ROOT)); - if (profile != null && Iterables.getFirst(profile.getProperties().get("textures"), (Object) null) != null) { - callback.apply(profile); - - return Futures.immediateFuture(profile); - } else { - Callable callable = new Callable() { - @Override - public GameProfile call() { - final GameProfile profile = skinCache.getUnchecked(gameprofile.getName().toLowerCase(java.util.Locale.ROOT)); - MinecraftServer.getServer().processQueue.add(new Runnable() { - @Override - public void run() { - if (profile == null) { - callback.apply(gameprofile); - } else { - callback.apply(profile); - } - } - }); - return profile; - } - }; - if (sync) { - try { - return Futures.immediateFuture(callable.call()); - } catch (Exception ex) { - com.google.common.base.Throwables.throwIfUnchecked(ex); - throw new RuntimeException(ex); // Not possible - } - } else { - return executor.submit(callable); - } - } - } - } else { - callback.apply(gameprofile); - } - - return Futures.immediateFuture(gameprofile); - } - // Spigot end -} diff --git a/src/main/java/net/minecraft/server/UserCache.java b/src/main/java/net/minecraft/server/UserCache.java deleted file mode 100644 index 1d4bf64b1..000000000 --- a/src/main/java/net/minecraft/server/UserCache.java +++ /dev/null @@ -1,357 +0,0 @@ -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.io.Files; -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 com.mojang.authlib.Agent; -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.GameProfileRepository; -import com.mojang.authlib.ProfileLookupCallback; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Deque; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.UUID; -import javax.annotation.Nullable; -import org.apache.commons.io.IOUtils; - -public class UserCache { - - public static final SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); - private static boolean c; - private final Map d = new java.util.concurrent.ConcurrentHashMap<>();private final Map nameCache = d; // Paper - OBFHELPER // Paper - private final Map e = new java.util.concurrent.ConcurrentHashMap<>(); // Paper - private final Deque f = new java.util.concurrent.LinkedBlockingDeque(); // CraftBukkit - private final GameProfileRepository g; - protected final Gson b; - private final File h; - private static final ParameterizedType i = new ParameterizedType() { - public Type[] getActualTypeArguments() { - return new Type[]{UserCache.UserCacheEntry.class}; - } - - public Type getRawType() { - return List.class; - } - - public Type getOwnerType() { - return null; - } - }; - - public UserCache(GameProfileRepository gameprofilerepository, File file) { - this.g = gameprofilerepository; - this.h = file; - GsonBuilder gsonbuilder = new GsonBuilder(); - - gsonbuilder.registerTypeHierarchyAdapter(UserCache.UserCacheEntry.class, new UserCache.BanEntrySerializer()); - this.b = gsonbuilder.create(); - this.b(); - } - - private static GameProfile a(GameProfileRepository gameprofilerepository, 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; - } - }; - - gameprofilerepository.findProfilesByNames(new String[]{s}, Agent.MINECRAFT, profilelookupcallback); - if (!d() && agameprofile[0] == null && !org.apache.commons.lang3.StringUtils.isBlank(s)) { // Paper - Don't lookup a profile with a blank name - UUID uuid = EntityHuman.a(new GameProfile((UUID) null, s)); - GameProfile gameprofile = new GameProfile(uuid, s); - - profilelookupcallback.onProfileLookupSucceeded(gameprofile); - } - - return agameprofile[0]; - } - - public static void a(boolean flag) { - UserCache.c = flag; - } - - private static boolean d() { - return UserCache.c; - } - - public void a(GameProfile gameprofile) { - this.a(gameprofile, (Date) null); - } - - private synchronized void a(GameProfile gameprofile, Date date) { // Paper - synchronize - UUID uuid = gameprofile.getId(); - - if (date == null) { - Calendar calendar = Calendar.getInstance(); - - calendar.setTime(new Date()); - calendar.add(2, 1); - date = calendar.getTime(); - } - - UserCache.UserCacheEntry usercache_usercacheentry = new UserCache.UserCacheEntry(gameprofile, date); - - //if (this.e.containsKey(uuid)) { // Paper - UserCache.UserCacheEntry usercache_usercacheentry1 = (UserCache.UserCacheEntry) this.e.get(uuid); - if (usercache_usercacheentry1 != null) { // Paper - - this.d.remove(usercache_usercacheentry1.a().getName().toLowerCase(Locale.ROOT)); - this.f.remove(gameprofile); - } - - this.d.put(gameprofile.getName().toLowerCase(Locale.ROOT), usercache_usercacheentry); - this.e.put(uuid, usercache_usercacheentry); - this.f.addFirst(gameprofile); - if( !org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly ) this.c(); // Spigot - skip saving if disabled - } - - @Nullable - public synchronized GameProfile getProfile(String s) { // Paper - synchronize - String s1 = s.toLowerCase(Locale.ROOT); - UserCache.UserCacheEntry usercache_usercacheentry = (UserCache.UserCacheEntry) this.d.get(s1); - - if (usercache_usercacheentry != null && (new Date()).getTime() >= usercache_usercacheentry.c.getTime()) { - this.e.remove(usercache_usercacheentry.a().getId()); - this.d.remove(usercache_usercacheentry.a().getName().toLowerCase(Locale.ROOT)); - this.f.remove(usercache_usercacheentry.a()); - usercache_usercacheentry = null; - } - - GameProfile gameprofile; - - if (usercache_usercacheentry != null) { - gameprofile = usercache_usercacheentry.a(); - this.f.remove(gameprofile); - this.f.addFirst(gameprofile); - } else { - gameprofile = a(this.g, s); // Spigot - use correct case for offline players - if (gameprofile != null) { - this.a(gameprofile); - usercache_usercacheentry = (UserCache.UserCacheEntry) this.d.get(s1); - } - } - - if( !org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly ) this.c(); // Spigot - skip saving if disabled - return usercache_usercacheentry == null ? null : usercache_usercacheentry.a(); - } - - // Paper start - @Nullable public GameProfile getProfileIfCached(String name) { - UserCache.UserCacheEntry entry = this.nameCache.get(name.toLowerCase(Locale.ROOT)); - return entry == null ? null : entry.getProfile(); - } - // Paper end - - @Nullable public GameProfile getProfile(UUID uuid) { return a(uuid); } // Paper - OBFHELPER - @Nullable - public GameProfile a(UUID uuid) { - UserCache.UserCacheEntry usercache_usercacheentry = (UserCache.UserCacheEntry) this.e.get(uuid); - - return usercache_usercacheentry == null ? null : usercache_usercacheentry.a(); - } - - private UserCache.UserCacheEntry b(UUID uuid) { - UserCache.UserCacheEntry usercache_usercacheentry = (UserCache.UserCacheEntry) this.e.get(uuid); - - if (usercache_usercacheentry != null) { - GameProfile gameprofile = usercache_usercacheentry.a(); - - this.f.remove(gameprofile); - this.f.addFirst(gameprofile); - } - - return usercache_usercacheentry; - } - - public void b() { - BufferedReader bufferedreader = null; - - try { - bufferedreader = Files.newReader(this.h, StandardCharsets.UTF_8); - List list = (List) ChatDeserializer.a(this.b, (Reader) bufferedreader, (Type) UserCache.i); - - this.d.clear(); - this.e.clear(); - this.f.clear(); - if (list != null) { - Iterator iterator = Lists.reverse(list).iterator(); - - while (iterator.hasNext()) { - UserCache.UserCacheEntry usercache_usercacheentry = (UserCache.UserCacheEntry) iterator.next(); - - if (usercache_usercacheentry != null) { - this.a(usercache_usercacheentry.a(), usercache_usercacheentry.b()); - } - } - } - } catch (FileNotFoundException filenotfoundexception) { - ; - // Spigot Start - } catch (com.google.gson.JsonSyntaxException ex) { - JsonList.LOGGER.warn( "Usercache.json is corrupted or has bad formatting. Deleting it to prevent further issues." ); - this.h.delete(); - // Spigot End - } catch (JsonParseException jsonparseexception) { - ; - } finally { - IOUtils.closeQuietly(bufferedreader); - } - - } - - // Paper start - public void c() { - c(true); - } - public void c(boolean asyncSave) { - // Paper end - String s = this.b.toJson(this.a(org.spigotmc.SpigotConfig.userCacheCap)); - Runnable save = () -> { - - BufferedWriter bufferedwriter = null; - - try { - bufferedwriter = Files.newWriter(this.h, StandardCharsets.UTF_8); - bufferedwriter.write(s); - return; - } catch (FileNotFoundException filenotfoundexception) { - return; - } catch (IOException ioexception) { - ; - } finally { - IOUtils.closeQuietly(bufferedwriter); - } - // Paper start - }; - if (asyncSave) { - MCUtil.scheduleAsyncTask(save); - } else { - save.run(); - } - // Paper end - - } - - private List a(int i) { - List list = Lists.newArrayList(); - List list1 = Lists.newArrayList(Iterators.limit(this.f.iterator(), i)); - Iterator iterator = list1.iterator(); - - while (iterator.hasNext()) { - GameProfile gameprofile = (GameProfile) iterator.next(); - UserCache.UserCacheEntry usercache_usercacheentry = this.b(gameprofile.getId()); - - if (usercache_usercacheentry != null) { - list.add(usercache_usercacheentry); - } - } - - return list; - } - - class UserCacheEntry { - - private final GameProfile b;public GameProfile getProfile() { return b; } // Paper - OBFHELPER - 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; - } - } - - class BanEntrySerializer implements JsonDeserializer, JsonSerializer { - - private BanEntrySerializer() {} - - public JsonElement serialize(UserCache.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 ? "" : uuid.toString()); - jsonobject.addProperty("expiresOn", UserCache.a.format(usercache_usercacheentry.b())); - return jsonobject; - } - - public UserCache.UserCacheEntry deserialize(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 parseexception) { - date = null; - } - } - - if (s1 != null && s != null) { - UUID uuid; - - try { - uuid = UUID.fromString(s); - } catch (Throwable throwable) { - return null; - } - - return UserCache.this.new UserCacheEntry(new GameProfile(uuid, s1), date); - } else { - return null; - } - } else { - return null; - } - } else { - return null; - } - } - } -} diff --git a/src/main/java/net/minecraft/server/VillagePlace.java b/src/main/java/net/minecraft/server/VillagePlace.java deleted file mode 100644 index fb99b4306..000000000 --- a/src/main/java/net/minecraft/server/VillagePlace.java +++ /dev/null @@ -1,289 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.DataFixer; -import it.unimi.dsi.fastutil.longs.Long2ByteMap; -import it.unimi.dsi.fastutil.longs.Long2ByteOpenHashMap; -import java.io.File; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import java.util.function.BiConsumer; -import java.util.function.BooleanSupplier; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -public class VillagePlace extends RegionFileSection { - - private final VillagePlace.a a = new VillagePlace.a(); - - private final WorldServer world; // Paper - - public VillagePlace(File file, DataFixer datafixer) { - // Paper start - this(file, datafixer, null); - } - public VillagePlace(File file, DataFixer datafixer, WorldServer world) { - // Paper end - super(file, VillagePlaceSection::new, VillagePlaceSection::new, datafixer, DataFixTypes.POI_CHUNK); - this.world = world; // Paper - } - - public void a(BlockPosition blockposition, VillagePlaceType villageplacetype) { - ((VillagePlaceSection) this.e(SectionPosition.a(blockposition).v())).a(blockposition, villageplacetype); - } - - public void a(BlockPosition blockposition) { - ((VillagePlaceSection) this.e(SectionPosition.a(blockposition).v())).a(blockposition); - } - - public long a(Predicate predicate, BlockPosition blockposition, int i, VillagePlace.Occupancy villageplace_occupancy) { - return this.b(predicate, blockposition, i, villageplace_occupancy).count(); - } - - public Stream b(Predicate predicate, BlockPosition blockposition, int i, VillagePlace.Occupancy villageplace_occupancy) { - int j = i * i; - - return ChunkCoordIntPair.a(new ChunkCoordIntPair(blockposition), Math.floorDiv(i, 16)).flatMap((chunkcoordintpair) -> { - return this.a(predicate, chunkcoordintpair, villageplace_occupancy).filter((villageplacerecord) -> { - return villageplacerecord.f().m(blockposition) <= (double) j; - }); - }); - } - - public Stream a(Predicate predicate, ChunkCoordIntPair chunkcoordintpair, VillagePlace.Occupancy villageplace_occupancy) { - return IntStream.range(0, 16).boxed().flatMap((integer) -> { - return this.a(predicate, SectionPosition.a(chunkcoordintpair, integer).v(), villageplace_occupancy); - }); - } - - private Stream a(Predicate predicate, long i, VillagePlace.Occupancy villageplace_occupancy) { - return (Stream) this.d(i).map((villageplacesection) -> { - return villageplacesection.a(predicate, villageplace_occupancy); - }).orElseGet(Stream::empty); - } - - public Stream a(Predicate predicate, Predicate predicate1, BlockPosition blockposition, int i, VillagePlace.Occupancy villageplace_occupancy) { - return this.b(predicate, blockposition, i, villageplace_occupancy).map(VillagePlaceRecord::f).filter(predicate1); - } - - public Optional b(Predicate predicate, Predicate predicate1, BlockPosition blockposition, int i, VillagePlace.Occupancy villageplace_occupancy) { - return this.a(predicate, predicate1, blockposition, i, villageplace_occupancy).findFirst(); - } - - public Optional c(Predicate predicate, Predicate predicate1, BlockPosition blockposition, int i, VillagePlace.Occupancy villageplace_occupancy) { - return this.b(predicate, blockposition, i, villageplace_occupancy).map(VillagePlaceRecord::f).sorted(Comparator.comparingDouble((blockposition1) -> { - return blockposition1.m(blockposition); - })).filter(predicate1).findFirst(); - } - - public Optional a(Predicate predicate, Predicate predicate1, BlockPosition blockposition, int i) { - return this.b(predicate, blockposition, i, VillagePlace.Occupancy.HAS_SPACE).filter((villageplacerecord) -> { - return predicate1.test(villageplacerecord.f()); - }).findFirst().map((villageplacerecord) -> { - villageplacerecord.b(); - return villageplacerecord.f(); - }); - } - - public Optional a(Predicate predicate, Predicate predicate1, VillagePlace.Occupancy villageplace_occupancy, BlockPosition blockposition, int i, Random random) { - List list = (List) this.b(predicate, blockposition, i, villageplace_occupancy).collect(Collectors.toList()); - - Collections.shuffle(list, random); - return list.stream().filter((villageplacerecord) -> { - return predicate1.test(villageplacerecord.f()); - }).findFirst().map(VillagePlaceRecord::f); - } - - public boolean b(BlockPosition blockposition) { - return ((VillagePlaceSection) this.e(SectionPosition.a(blockposition).v())).c(blockposition); - } - - public boolean a(BlockPosition blockposition, Predicate predicate) { - return (Boolean) this.d(SectionPosition.a(blockposition).v()).map((villageplacesection) -> { - return villageplacesection.a(blockposition, predicate); - }).orElse(false); - } - - public Optional c(BlockPosition blockposition) { - VillagePlaceSection villageplacesection = (VillagePlaceSection) this.e(SectionPosition.a(blockposition).v()); - - return villageplacesection.d(blockposition); - } - - public int a(SectionPosition sectionposition) { - this.a.a(); - return this.a.c(sectionposition.v()); - } - - private boolean f(long i) { - Optional optional = this.c(i); - - return optional == null ? false : (Boolean) optional.map((villageplacesection) -> { - return villageplacesection.a(VillagePlaceType.a, VillagePlace.Occupancy.IS_OCCUPIED).count() > 0L; - }).orElse(false); - } - - @Override - public void a(BooleanSupplier booleansupplier) { - // Paper start - async chunk io - if (this.world == null) { - super.a(booleansupplier); - } else if (!this.world.isSavingDisabled()) { // Paper - only save if saving is enabled - //super.a(booleansupplier); // re-implement below - // Paper start - target unloading aggressively - int queueTarget = Math.min(this.d.size() - 100, (int)(this.d.size() * 0.96)); - while (!((RegionFileSection)this).d.isEmpty() && (this.d.size() > queueTarget || booleansupplier.getAsBoolean())) { - // Paper end - ChunkCoordIntPair chunkcoordintpair = SectionPosition.a(((RegionFileSection)this).d.firstLong()).u(); - - NBTTagCompound data; - try (co.aikar.timings.Timing ignored1 = this.world.timings.poiSaveDataSerialization.startTiming()) { - data = this.getData(chunkcoordintpair); - } - com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.scheduleSave(this.world, - chunkcoordintpair.x, chunkcoordintpair.z, data, null, com.destroystokyo.paper.io.PrioritizedTaskQueue.LOW_PRIORITY); - } - } - // Paper end - this.a.a(); - } - - @Override - protected void a(long i) { - super.a(i); - this.a.b(i, this.a.b(i), false); - } - - @Override - protected void b(long i) { - this.a.b(i, this.a.b(i), false); - } - - public void a(ChunkCoordIntPair chunkcoordintpair, ChunkSection chunksection) { - SectionPosition sectionposition = SectionPosition.a(chunkcoordintpair, chunksection.getYPosition() >> 4); - - SystemUtils.a(this.d(sectionposition.v()), (villageplacesection) -> { - villageplacesection.a((biconsumer) -> { - if (a(chunksection)) { - this.a(chunksection, sectionposition, biconsumer); - } - - }); - }, () -> { - if (a(chunksection)) { - VillagePlaceSection villageplacesection = (VillagePlaceSection) this.e(sectionposition.v()); - - this.a(chunksection, sectionposition, villageplacesection::a); - } - - }); - } - - private static boolean a(ChunkSection chunksection) { - Stream stream = VillagePlaceType.f(); // Paper - decompile fix - - chunksection.getClass(); - return stream.anyMatch(chunksection::a); - } - - private void a(ChunkSection chunksection, SectionPosition sectionposition, BiConsumer biconsumer) { - sectionposition.w().forEach((blockposition) -> { - IBlockData iblockdata = chunksection.getType(SectionPosition.b(blockposition.getX()), SectionPosition.b(blockposition.getY()), SectionPosition.b(blockposition.getZ())); - - VillagePlaceType.b(iblockdata).ifPresent((villageplacetype) -> { - biconsumer.accept(blockposition, villageplacetype); - }); - }); - } - - final class a extends LightEngineGraphSection { - - private final Long2ByteMap b = new Long2ByteOpenHashMap(); - - protected a() { - super(7, 16, 256); - this.b.defaultReturnValue((byte) 7); - } - - @Override - protected int b(long i) { - return VillagePlace.this.f(i) ? 0 : 7; - } - - @Override - protected int c(long i) { - return this.b.get(i); - } - - @Override - protected void a(long i, int j) { - if (j > 6) { - this.b.remove(i); - } else { - this.b.put(i, (byte) j); - } - - } - - public void a() { - super.b(Integer.MAX_VALUE); - } - } - - // Paper start - Asynchronous chunk io - @javax.annotation.Nullable - @Override - public NBTTagCompound read(ChunkCoordIntPair chunkcoordintpair) throws java.io.IOException { - if (this.world != null && Thread.currentThread() != com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE) { - NBTTagCompound ret = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE - .loadChunkDataAsyncFuture(this.world, chunkcoordintpair.x, chunkcoordintpair.z, com.destroystokyo.paper.io.IOUtil.getPriorityForCurrentThread(), - true, false, true).join().poiData; - - if (ret == com.destroystokyo.paper.io.PaperFileIOThread.FAILURE_VALUE) { - throw new java.io.IOException("See logs for further detail"); - } - return ret; - } - return super.read(chunkcoordintpair); - } - - @Override - public void write(ChunkCoordIntPair chunkcoordintpair, NBTTagCompound nbttagcompound) throws java.io.IOException { - if (this.world != null && Thread.currentThread() != com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE) { - com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.scheduleSave( - this.world, chunkcoordintpair.x, chunkcoordintpair.z, nbttagcompound, null, - com.destroystokyo.paper.io.IOUtil.getPriorityForCurrentThread()); - - Boolean ret = com.destroystokyo.paper.io.PaperFileIOThread.Holder.INSTANCE.waitForIOToComplete(this.world, - chunkcoordintpair.x, chunkcoordintpair.z, true, true); - - if (ret == Boolean.FALSE) { - throw new java.io.IOException("See logs for further detail"); - } - return; - } - super.write(chunkcoordintpair, nbttagcompound); - } - // Paper end - - public static enum Occupancy { - - HAS_SPACE(VillagePlaceRecord::d), IS_OCCUPIED(VillagePlaceRecord::e), ANY((villageplacerecord) -> { - return true; - }); - - private final Predicate d; - - private Occupancy(Predicate predicate) { // Paper - decompile fix - this.d = predicate; - } - - public Predicate a() { - return this.d; - } - } -} diff --git a/src/main/java/net/minecraft/server/VillageSiege.java b/src/main/java/net/minecraft/server/VillageSiege.java deleted file mode 100644 index 6e4c5d4d8..000000000 --- a/src/main/java/net/minecraft/server/VillageSiege.java +++ /dev/null @@ -1,136 +0,0 @@ -package net.minecraft.server; - -import com.destroystokyo.paper.exception.ServerInternalException; - -import java.util.Iterator; -import javax.annotation.Nullable; - -public class VillageSiege { - - private boolean a; - private VillageSiege.State b; - private int c; - private int d; - private int e; - private int f; - private int g; - - public VillageSiege() { - this.b = VillageSiege.State.SIEGE_DONE; - } - - public int a(WorldServer worldserver, boolean flag, boolean flag1) { - if (!worldserver.J() && flag) { - float f = worldserver.j(0.0F); - - if ((double) f == 0.5D) { - this.b = worldserver.random.nextInt(10) == 0 ? VillageSiege.State.SIEGE_TONIGHT : VillageSiege.State.SIEGE_DONE; - } - - if (this.b == VillageSiege.State.SIEGE_DONE) { - return 0; - } else { - if (!this.a) { - if (!this.a(worldserver)) { - return 0; - } - - this.a = true; - } - - if (this.d > 0) { - --this.d; - return 0; - } else { - this.d = 2; - if (this.c > 0) { - this.b(worldserver); - --this.c; - } else { - this.b = VillageSiege.State.SIEGE_DONE; - } - - return 1; - } - } - } else { - this.b = VillageSiege.State.SIEGE_DONE; - this.a = false; - return 0; - } - } - - private boolean a(WorldServer worldserver) { - Iterator iterator = worldserver.getPlayers().iterator(); - - while (iterator.hasNext()) { - EntityHuman entityhuman = (EntityHuman) iterator.next(); - - if (!entityhuman.isSpectator()) { - BlockPosition blockposition = entityhuman.getChunkCoordinates(); - - if (worldserver.b_(blockposition) && worldserver.getBiome(blockposition).o() != BiomeBase.Geography.MUSHROOM) { - for (int i = 0; i < 10; ++i) { - float f = worldserver.random.nextFloat() * 6.2831855F; - - this.e = blockposition.getX() + MathHelper.d(MathHelper.cos(f) * 32.0F); - this.f = blockposition.getY(); - this.g = blockposition.getZ() + MathHelper.d(MathHelper.sin(f) * 32.0F); - if (this.a(worldserver, new BlockPosition(this.e, this.f, this.g)) != null) { - this.d = 0; - this.c = 20; - break; - } - } - - return true; - } - } - } - - return false; - } - - private void b(WorldServer worldserver) { - Vec3D vec3d = this.a(worldserver, new BlockPosition(this.e, this.f, this.g)); - - if (vec3d != null) { - EntityZombie entityzombie; - - try { - entityzombie = new EntityZombie(worldserver); - entityzombie.prepare(worldserver, worldserver.getDamageScaler(new BlockPosition(entityzombie)), EnumMobSpawn.EVENT, (GroupDataEntity) null, (NBTTagCompound) null); - } catch (Exception exception) { - exception.printStackTrace(); - ServerInternalException.reportInternalException(exception); // Paper - return; - } - - entityzombie.setPositionRotation(vec3d.x, vec3d.y, vec3d.z, worldserver.random.nextFloat() * 360.0F, 0.0F); - worldserver.addEntity(entityzombie, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.VILLAGE_INVASION); // CraftBukkit - } - } - - @Nullable - private Vec3D a(WorldServer worldserver, BlockPosition blockposition) { - for (int i = 0; i < 10; ++i) { - int j = blockposition.getX() + worldserver.random.nextInt(16) - 8; - int k = blockposition.getZ() + worldserver.random.nextInt(16) - 8; - int l = worldserver.a(HeightMap.Type.WORLD_SURFACE, j, k); - BlockPosition blockposition1 = new BlockPosition(j, l, k); - - if (worldserver.b_(blockposition1) && EntityMonster.c(EntityTypes.ZOMBIE, worldserver, EnumMobSpawn.EVENT, blockposition1, worldserver.random)) { - return new Vec3D((double) blockposition1.getX() + 0.5D, (double) blockposition1.getY(), (double) blockposition1.getZ() + 0.5D); - } - } - - return null; - } - - static enum State { - - SIEGE_CAN_ACTIVATE, SIEGE_TONIGHT, SIEGE_DONE; - - private State() {} - } -} diff --git a/src/main/java/net/minecraft/server/VillagerTrades.java b/src/main/java/net/minecraft/server/VillagerTrades.java deleted file mode 100644 index 99374fe2a..000000000 --- a/src/main/java/net/minecraft/server/VillagerTrades.java +++ /dev/null @@ -1,372 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Random; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -public class VillagerTrades { - - public static final Map> a = SystemUtils.a(Maps.newHashMap(), (hashmap) -> { // Paper - decompile fix - hashmap.put(VillagerProfession.FARMER, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.WHEAT, 20, 16, 2), new VillagerTrades.b(Items.POTATO, 26, 16, 2), new VillagerTrades.b(Items.CARROT, 22, 16, 2), new VillagerTrades.b(Items.BEETROOT, 15, 16, 2), new VillagerTrades.h(Items.BREAD, 1, 6, 16, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Blocks.PUMPKIN, 6, 12, 10), new VillagerTrades.h(Items.PUMPKIN_PIE, 1, 4, 5), new VillagerTrades.h(Items.APPLE, 1, 4, 16, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Items.COOKIE, 3, 18, 10), new VillagerTrades.b(Blocks.MELON, 4, 12, 20)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Blocks.CAKE, 1, 1, 12, 15), new VillagerTrades.i(MobEffects.NIGHT_VISION, 100, 15), new VillagerTrades.i(MobEffects.JUMP, 160, 15), new VillagerTrades.i(MobEffects.WEAKNESS, 140, 15), new VillagerTrades.i(MobEffects.BLINDNESS, 120, 15), new VillagerTrades.i(MobEffects.POISON, 280, 15), new VillagerTrades.i(MobEffects.SATURATION, 7, 15)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Items.GOLDEN_CARROT, 3, 3, 30), new VillagerTrades.h(Items.GLISTERING_MELON_SLICE, 4, 3, 30)}))); - hashmap.put(VillagerProfession.FISHERMAN, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.STRING, 20, 16, 2), new VillagerTrades.b(Items.COAL, 10, 16, 2), new VillagerTrades.g(Items.COD, 6, Items.COOKED_COD, 6, 16, 1), new VillagerTrades.h(Items.COD_BUCKET, 3, 1, 16, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.COD, 15, 16, 10), new VillagerTrades.g(Items.SALMON, 6, Items.COOKED_SALMON, 6, 16, 5), new VillagerTrades.h(Items.pS, 2, 1, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.SALMON, 13, 16, 20), new VillagerTrades.e(Items.FISHING_ROD, 3, 3, 10, 0.2F)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.TROPICAL_FISH, 6, 12, 30)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.PUFFERFISH, 4, 12, 30), new VillagerTrades.c(1, 12, 30, ImmutableMap.builder().put(VillagerType.PLAINS, Items.OAK_BOAT).put(VillagerType.TAIGA, Items.SPRUCE_BOAT).put(VillagerType.SNOW, Items.SPRUCE_BOAT).put(VillagerType.DESERT, Items.JUNGLE_BOAT).put(VillagerType.JUNGLE, Items.JUNGLE_BOAT).put(VillagerType.SAVANNA, Items.ACACIA_BOAT).put(VillagerType.SWAMP, Items.DARK_OAK_BOAT).build())}))); // Paper - decompile fix - hashmap.put(VillagerProfession.SHEPHERD, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Blocks.WHITE_WOOL, 18, 16, 2), new VillagerTrades.b(Blocks.BROWN_WOOL, 18, 16, 2), new VillagerTrades.b(Blocks.BLACK_WOOL, 18, 16, 2), new VillagerTrades.b(Blocks.GRAY_WOOL, 18, 16, 2), new VillagerTrades.h(Items.SHEARS, 2, 1, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.WHITE_DYE, 12, 16, 10), new VillagerTrades.b(Items.GRAY_DYE, 12, 16, 10), new VillagerTrades.b(Items.BLACK_DYE, 12, 16, 10), new VillagerTrades.b(Items.LIGHT_BLUE_DYE, 12, 16, 10), new VillagerTrades.b(Items.LIME_DYE, 12, 16, 10), new VillagerTrades.h(Blocks.WHITE_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.ORANGE_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.MAGENTA_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.LIGHT_BLUE_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.YELLOW_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.LIME_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.PINK_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.GRAY_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.LIGHT_GRAY_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.CYAN_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.PURPLE_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.BLUE_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.BROWN_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.GREEN_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.RED_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.BLACK_WOOL, 1, 1, 16, 5), new VillagerTrades.h(Blocks.WHITE_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.ORANGE_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.MAGENTA_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.LIGHT_BLUE_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.YELLOW_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.LIME_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.PINK_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.GRAY_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.LIGHT_GRAY_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.CYAN_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.PURPLE_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.BLUE_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.BROWN_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.GREEN_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.RED_CARPET, 1, 4, 16, 5), new VillagerTrades.h(Blocks.BLACK_CARPET, 1, 4, 16, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.YELLOW_DYE, 12, 16, 20), new VillagerTrades.b(Items.LIGHT_GRAY_DYE, 12, 16, 20), new VillagerTrades.b(Items.ORANGE_DYE, 12, 16, 20), new VillagerTrades.b(Items.RED_DYE, 12, 16, 20), new VillagerTrades.b(Items.PINK_DYE, 12, 16, 20), new VillagerTrades.h(Blocks.WHITE_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.YELLOW_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.RED_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.BLACK_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.BLUE_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.BROWN_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.CYAN_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.GRAY_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.GREEN_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.LIGHT_BLUE_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.LIGHT_GRAY_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.LIME_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.MAGENTA_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.ORANGE_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.PINK_BED, 3, 1, 12, 10), new VillagerTrades.h(Blocks.PURPLE_BED, 3, 1, 12, 10)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.BROWN_DYE, 12, 16, 30), new VillagerTrades.b(Items.PURPLE_DYE, 12, 16, 30), new VillagerTrades.b(Items.BLUE_DYE, 12, 16, 30), new VillagerTrades.b(Items.GREEN_DYE, 12, 16, 30), new VillagerTrades.b(Items.MAGENTA_DYE, 12, 16, 30), new VillagerTrades.b(Items.CYAN_DYE, 12, 16, 30), new VillagerTrades.h(Items.WHITE_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.BLUE_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.LIGHT_BLUE_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.RED_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.PINK_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.GREEN_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.LIME_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.GRAY_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.BLACK_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.PURPLE_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.MAGENTA_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.CYAN_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.BROWN_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.YELLOW_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.ORANGE_BANNER, 3, 1, 12, 15), new VillagerTrades.h(Items.LIGHT_GRAY_BANNER, 3, 1, 12, 15)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Items.PAINTING, 2, 3, 30)}))); - hashmap.put(VillagerProfession.FLETCHER, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.STICK, 32, 16, 2), new VillagerTrades.h(Items.ARROW, 1, 16, 1), new VillagerTrades.g(Blocks.GRAVEL, 10, Items.FLINT, 10, 12, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.FLINT, 26, 12, 10), new VillagerTrades.h(Items.BOW, 2, 1, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.STRING, 14, 16, 20), new VillagerTrades.h(Items.CROSSBOW, 3, 1, 10)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.FEATHER, 24, 16, 30), new VillagerTrades.e(Items.BOW, 2, 3, 15)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.dE, 8, 12, 30), new VillagerTrades.e(Items.CROSSBOW, 3, 3, 15), new VillagerTrades.j(Items.ARROW, 5, Items.TIPPED_ARROW, 5, 2, 12, 30)}))); - hashmap.put(VillagerProfession.LIBRARIAN, a(ImmutableMap.builder().put(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.PAPER, 24, 16, 2), new VillagerTrades.d(1), new VillagerTrades.h(Blocks.BOOKSHELF, 6, 3, 12, 1)}).put(2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.BOOK, 4, 12, 10), new VillagerTrades.d(5), new VillagerTrades.h(Items.pQ, 1, 1, 5)}).put(3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.INK_SAC, 5, 12, 20), new VillagerTrades.d(10), new VillagerTrades.h(Items.am, 1, 4, 10)}).put(4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.WRITABLE_BOOK, 2, 12, 30), new VillagerTrades.d(15), new VillagerTrades.h(Items.CLOCK, 5, 1, 15), new VillagerTrades.h(Items.COMPASS, 4, 1, 15)}).put(5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Items.NAME_TAG, 20, 1, 30)}).build())); // Paper - decompile fix - hashmap.put(VillagerProfession.CARTOGRAPHER, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.PAPER, 24, 16, 2), new VillagerTrades.h(Items.MAP, 7, 1, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.df, 11, 16, 10), new VillagerTrades.k(13, "Monument", MapIcon.Type.MONUMENT, 12, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.COMPASS, 1, 12, 20), new VillagerTrades.k(14, "Mansion", MapIcon.Type.MANSION, 12, 10)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Items.ITEM_FRAME, 7, 1, 15), new VillagerTrades.h(Items.WHITE_BANNER, 3, 1, 15), new VillagerTrades.h(Items.BLUE_BANNER, 3, 1, 15), new VillagerTrades.h(Items.LIGHT_BLUE_BANNER, 3, 1, 15), new VillagerTrades.h(Items.RED_BANNER, 3, 1, 15), new VillagerTrades.h(Items.PINK_BANNER, 3, 1, 15), new VillagerTrades.h(Items.GREEN_BANNER, 3, 1, 15), new VillagerTrades.h(Items.LIME_BANNER, 3, 1, 15), new VillagerTrades.h(Items.GRAY_BANNER, 3, 1, 15), new VillagerTrades.h(Items.BLACK_BANNER, 3, 1, 15), new VillagerTrades.h(Items.PURPLE_BANNER, 3, 1, 15), new VillagerTrades.h(Items.MAGENTA_BANNER, 3, 1, 15), new VillagerTrades.h(Items.CYAN_BANNER, 3, 1, 15), new VillagerTrades.h(Items.BROWN_BANNER, 3, 1, 15), new VillagerTrades.h(Items.YELLOW_BANNER, 3, 1, 15), new VillagerTrades.h(Items.ORANGE_BANNER, 3, 1, 15), new VillagerTrades.h(Items.LIGHT_GRAY_BANNER, 3, 1, 15)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Items.GLOBE_BANNER_PATTERN, 8, 1, 30)}))); - hashmap.put(VillagerProfession.CLERIC, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.ROTTEN_FLESH, 32, 16, 2), new VillagerTrades.h(Items.REDSTONE, 1, 2, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.GOLD_INGOT, 3, 12, 10), new VillagerTrades.h(Items.LAPIS_LAZULI, 1, 1, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.RABBIT_FOOT, 2, 12, 20), new VillagerTrades.h(Blocks.GLOWSTONE, 4, 1, 12, 10)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.SCUTE, 4, 12, 30), new VillagerTrades.b(Items.GLASS_BOTTLE, 9, 12, 30), new VillagerTrades.h(Items.ENDER_PEARL, 5, 1, 15)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.NETHER_WART, 22, 12, 30), new VillagerTrades.h(Items.EXPERIENCE_BOTTLE, 3, 1, 30)}))); - hashmap.put(VillagerProfession.ARMORER, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.COAL, 15, 16, 2), new VillagerTrades.h(new ItemStack(Items.IRON_LEGGINGS), 7, 1, 12, 1, 0.2F), new VillagerTrades.h(new ItemStack(Items.IRON_BOOTS), 4, 1, 12, 1, 0.2F), new VillagerTrades.h(new ItemStack(Items.IRON_HELMET), 5, 1, 12, 1, 0.2F), new VillagerTrades.h(new ItemStack(Items.IRON_CHESTPLATE), 9, 1, 12, 1, 0.2F)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.IRON_INGOT, 4, 12, 10), new VillagerTrades.h(new ItemStack(Items.pP), 36, 1, 12, 5, 0.2F), new VillagerTrades.h(new ItemStack(Items.CHAINMAIL_BOOTS), 1, 1, 12, 5, 0.2F), new VillagerTrades.h(new ItemStack(Items.CHAINMAIL_LEGGINGS), 3, 1, 12, 5, 0.2F)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.LAVA_BUCKET, 1, 12, 20), new VillagerTrades.b(Items.DIAMOND, 1, 12, 20), new VillagerTrades.h(new ItemStack(Items.CHAINMAIL_HELMET), 1, 1, 12, 10, 0.2F), new VillagerTrades.h(new ItemStack(Items.CHAINMAIL_CHESTPLATE), 4, 1, 12, 10, 0.2F), new VillagerTrades.h(new ItemStack(Items.SHIELD), 5, 1, 12, 10, 0.2F)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.e(Items.DIAMOND_LEGGINGS, 14, 3, 15, 0.2F), new VillagerTrades.e(Items.DIAMOND_BOOTS, 8, 3, 15, 0.2F)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.e(Items.DIAMOND_HELMET, 8, 3, 30, 0.2F), new VillagerTrades.e(Items.DIAMOND_CHESTPLATE, 16, 3, 30, 0.2F)}))); - hashmap.put(VillagerProfession.WEAPONSMITH, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.COAL, 15, 16, 2), new VillagerTrades.h(new ItemStack(Items.IRON_AXE), 3, 1, 12, 1, 0.2F), new VillagerTrades.e(Items.IRON_SWORD, 2, 3, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.IRON_INGOT, 4, 12, 10), new VillagerTrades.h(new ItemStack(Items.pP), 36, 1, 12, 5, 0.2F)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.FLINT, 24, 12, 20)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.DIAMOND, 1, 12, 30), new VillagerTrades.e(Items.DIAMOND_AXE, 12, 3, 15, 0.2F)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.e(Items.DIAMOND_SWORD, 8, 3, 30, 0.2F)}))); - hashmap.put(VillagerProfession.TOOLSMITH, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.COAL, 15, 16, 2), new VillagerTrades.h(new ItemStack(Items.STONE_AXE), 1, 1, 12, 1, 0.2F), new VillagerTrades.h(new ItemStack(Items.STONE_SHOVEL), 1, 1, 12, 1, 0.2F), new VillagerTrades.h(new ItemStack(Items.STONE_PICKAXE), 1, 1, 12, 1, 0.2F), new VillagerTrades.h(new ItemStack(Items.STONE_HOE), 1, 1, 12, 1, 0.2F)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.IRON_INGOT, 4, 12, 10), new VillagerTrades.h(new ItemStack(Items.pP), 36, 1, 12, 5, 0.2F)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.FLINT, 30, 12, 20), new VillagerTrades.e(Items.IRON_AXE, 1, 3, 10, 0.2F), new VillagerTrades.e(Items.IRON_SHOVEL, 2, 3, 10, 0.2F), new VillagerTrades.e(Items.IRON_PICKAXE, 3, 3, 10, 0.2F), new VillagerTrades.h(new ItemStack(Items.DIAMOND_HOE), 4, 1, 3, 10, 0.2F)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.DIAMOND, 1, 12, 30), new VillagerTrades.e(Items.DIAMOND_AXE, 12, 3, 15, 0.2F), new VillagerTrades.e(Items.DIAMOND_SHOVEL, 5, 3, 15, 0.2F)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.e(Items.DIAMOND_PICKAXE, 13, 3, 30, 0.2F)}))); - hashmap.put(VillagerProfession.BUTCHER, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.CHICKEN, 14, 16, 2), new VillagerTrades.b(Items.PORKCHOP, 7, 16, 2), new VillagerTrades.b(Items.RABBIT, 4, 16, 2), new VillagerTrades.h(Items.RABBIT_STEW, 1, 1, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.COAL, 15, 16, 2), new VillagerTrades.h(Items.COOKED_PORKCHOP, 1, 5, 16, 5), new VillagerTrades.h(Items.COOKED_CHICKEN, 1, 8, 16, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.MUTTON, 7, 16, 20), new VillagerTrades.b(Items.BEEF, 10, 16, 20)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.kP, 10, 12, 30)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.SWEET_BERRIES, 10, 12, 30)}))); - hashmap.put(VillagerProfession.LEATHERWORKER, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.LEATHER, 6, 16, 2), new VillagerTrades.a(Items.LEATHER_LEGGINGS, 3), new VillagerTrades.a(Items.LEATHER_CHESTPLATE, 7)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.FLINT, 26, 12, 10), new VillagerTrades.a(Items.LEATHER_HELMET, 5, 12, 5), new VillagerTrades.a(Items.LEATHER_BOOTS, 4, 12, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.RABBIT_HIDE, 9, 12, 20), new VillagerTrades.a(Items.LEATHER_CHESTPLATE, 7)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.SCUTE, 4, 12, 30), new VillagerTrades.a(Items.LEATHER_HORSE_ARMOR, 6, 12, 15)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(new ItemStack(Items.SADDLE), 6, 1, 12, 30, 0.2F), new VillagerTrades.a(Items.LEATHER_HELMET, 5, 12, 30)}))); - hashmap.put(VillagerProfession.MASON, a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.CLAY_BALL, 10, 16, 2), new VillagerTrades.h(Items.BRICK, 1, 10, 16, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Blocks.STONE, 20, 16, 10), new VillagerTrades.h(Blocks.CHISELED_STONE_BRICKS, 1, 4, 16, 5)}, 3, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Blocks.GRANITE, 16, 16, 20), new VillagerTrades.b(Blocks.ANDESITE, 16, 16, 20), new VillagerTrades.b(Blocks.DIORITE, 16, 16, 20), new VillagerTrades.h(Blocks.POLISHED_ANDESITE, 1, 4, 16, 10), new VillagerTrades.h(Blocks.POLISHED_DIORITE, 1, 4, 16, 10), new VillagerTrades.h(Blocks.POLISHED_GRANITE, 1, 4, 16, 10)}, 4, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.b(Items.QUARTZ, 12, 12, 30), new VillagerTrades.h(Blocks.ORANGE_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.WHITE_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.BLUE_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.LIGHT_BLUE_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.GRAY_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.LIGHT_GRAY_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.BLACK_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.RED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.PINK_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.MAGENTA_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.LIME_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.GREEN_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.CYAN_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.PURPLE_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.YELLOW_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.BROWN_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.ORANGE_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.WHITE_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.BLUE_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.LIGHT_BLUE_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.GRAY_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.LIGHT_GRAY_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.BLACK_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.RED_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.PINK_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.MAGENTA_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.LIME_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.GREEN_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.CYAN_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.PURPLE_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.YELLOW_GLAZED_TERRACOTTA, 1, 1, 12, 15), new VillagerTrades.h(Blocks.BROWN_GLAZED_TERRACOTTA, 1, 1, 12, 15)}, 5, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Blocks.QUARTZ_PILLAR, 1, 1, 12, 30), new VillagerTrades.h(Blocks.QUARTZ_BLOCK, 1, 1, 12, 30)}))); - }); - public static final Int2ObjectMap b = a(ImmutableMap.of(1, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Items.aC, 2, 1, 5, 1), new VillagerTrades.h(Items.SLIME_BALL, 4, 1, 5, 1), new VillagerTrades.h(Items.cJ, 2, 1, 5, 1), new VillagerTrades.h(Items.NAUTILUS_SHELL, 5, 1, 5, 1), new VillagerTrades.h(Items.az, 1, 1, 12, 1), new VillagerTrades.h(Items.kN, 1, 1, 8, 1), new VillagerTrades.h(Items.cF, 1, 1, 4, 1), new VillagerTrades.h(Items.kO, 3, 1, 12, 1), new VillagerTrades.h(Items.cw, 3, 1, 8, 1), new VillagerTrades.h(Items.aU, 1, 1, 12, 1), new VillagerTrades.h(Items.aV, 1, 1, 12, 1), new VillagerTrades.h(Items.aW, 1, 1, 8, 1), new VillagerTrades.h(Items.aX, 1, 1, 12, 1), new VillagerTrades.h(Items.aY, 1, 1, 12, 1), new VillagerTrades.h(Items.aZ, 1, 1, 12, 1), new VillagerTrades.h(Items.ba, 1, 1, 12, 1), new VillagerTrades.h(Items.bb, 1, 1, 12, 1), new VillagerTrades.h(Items.bc, 1, 1, 12, 1), new VillagerTrades.h(Items.bd, 1, 1, 12, 1), new VillagerTrades.h(Items.be, 1, 1, 12, 1), new VillagerTrades.h(Items.bf, 1, 1, 7, 1), new VillagerTrades.h(Items.WHEAT_SEEDS, 1, 1, 12, 1), new VillagerTrades.h(Items.BEETROOT_SEEDS, 1, 1, 12, 1), new VillagerTrades.h(Items.PUMPKIN_SEEDS, 1, 1, 12, 1), new VillagerTrades.h(Items.MELON_SEEDS, 1, 1, 12, 1), new VillagerTrades.h(Items.x, 5, 1, 8, 1), new VillagerTrades.h(Items.v, 5, 1, 8, 1), new VillagerTrades.h(Items.y, 5, 1, 8, 1), new VillagerTrades.h(Items.w, 5, 1, 8, 1), new VillagerTrades.h(Items.t, 5, 1, 8, 1), new VillagerTrades.h(Items.u, 5, 1, 8, 1), new VillagerTrades.h(Items.RED_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.WHITE_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.BLUE_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.PINK_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.BLACK_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.GREEN_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.LIGHT_GRAY_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.MAGENTA_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.YELLOW_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.GRAY_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.PURPLE_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.LIGHT_BLUE_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.LIME_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.ORANGE_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.BROWN_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.CYAN_DYE, 1, 3, 12, 1), new VillagerTrades.h(Items.hK, 3, 1, 8, 1), new VillagerTrades.h(Items.hL, 3, 1, 8, 1), new VillagerTrades.h(Items.hM, 3, 1, 8, 1), new VillagerTrades.h(Items.hN, 3, 1, 8, 1), new VillagerTrades.h(Items.hJ, 3, 1, 8, 1), new VillagerTrades.h(Items.dh, 1, 1, 12, 1), new VillagerTrades.h(Items.bh, 1, 1, 12, 1), new VillagerTrades.h(Items.bi, 1, 1, 12, 1), new VillagerTrades.h(Items.dr, 1, 2, 5, 1), new VillagerTrades.h(Items.A, 1, 8, 8, 1), new VillagerTrades.h(Items.B, 1, 4, 6, 1)}, 2, new VillagerTrades.IMerchantRecipeOption[]{new VillagerTrades.h(Items.TROPICAL_FISH_BUCKET, 5, 1, 4, 1), new VillagerTrades.h(Items.PUFFERFISH_BUCKET, 5, 1, 4, 1), new VillagerTrades.h(Items.fg, 3, 1, 6, 1), new VillagerTrades.h(Items.ii, 6, 1, 6, 1), new VillagerTrades.h(Items.GUNPOWDER, 1, 1, 8, 1), new VillagerTrades.h(Items.l, 3, 3, 6, 1)})); - - private static Int2ObjectMap a(ImmutableMap immutablemap) { - return new Int2ObjectOpenHashMap(immutablemap); - } - - static class g implements VillagerTrades.IMerchantRecipeOption { - - private final ItemStack a; - private final int b; - private final int c; - private final ItemStack d; - private final int e; - private final int f; - private final int g; - private final float h; - - public g(IMaterial imaterial, int i, Item item, int j, int k, int l) { - this(imaterial, i, 1, item, j, k, l); - } - - public g(IMaterial imaterial, int i, int j, Item item, int k, int l, int i1) { - this.a = new ItemStack(imaterial); - this.b = i; - this.c = j; - this.d = new ItemStack(item); - this.e = k; - this.f = l; - this.g = i1; - this.h = 0.05F; - } - - @Nullable - @Override - public MerchantRecipe a(Entity entity, Random random) { - return new MerchantRecipe(new ItemStack(Items.EMERALD, this.c), new ItemStack(this.a.getItem(), this.b), new ItemStack(this.d.getItem(), this.e), this.f, this.g, this.h); - } - } - - static class k implements VillagerTrades.IMerchantRecipeOption { - - private final int a; - private final String b; - private final MapIcon.Type c; - private final int d; - private final int e; - - public k(int i, String s, MapIcon.Type mapicon_type, int j, int k) { - this.a = i; - this.b = s; - this.c = mapicon_type; - this.d = j; - this.e = k; - } - - @Nullable - @Override - public MerchantRecipe a(Entity entity, Random random) { - World world = entity.world; - if (!world.paperConfig.enableTreasureMaps) return null; //Paper - BlockPosition blockposition = world.a(this.b, new BlockPosition(entity), 100, !world.paperConfig.treasureMapsAlreadyDiscovered); //Paper - - if (blockposition != null) { - ItemStack itemstack = ItemWorldMap.createFilledMapView(world, blockposition.getX(), blockposition.getZ(), (byte) 2, true, true); - - ItemWorldMap.applySepiaFilter(world, itemstack); - WorldMap.decorateMap(itemstack, blockposition, "+", this.c); - itemstack.a((IChatBaseComponent) (new ChatMessage("filled_map." + this.b.toLowerCase(Locale.ROOT), new Object[0]))); - return new MerchantRecipe(new ItemStack(Items.EMERALD, this.a), new ItemStack(Items.COMPASS), itemstack, this.d, this.e, 0.2F); - } else { - return null; - } - } - } - - static class d implements VillagerTrades.IMerchantRecipeOption { - - private final int a; - - public d(int i) { - this.a = i; - } - - @Override - public MerchantRecipe a(Entity entity, Random random) { - Enchantment enchantment = (Enchantment) IRegistry.ENCHANTMENT.a(random); - int i = MathHelper.nextInt(random, enchantment.getStartLevel(), enchantment.getMaxLevel()); - ItemStack itemstack = ItemEnchantedBook.a(new WeightedRandomEnchant(enchantment, i)); - int j = 2 + random.nextInt(5 + i * 10) + 3 * i; - - if (enchantment.isTreasure()) { - j *= 2; - } - - if (j > 64) { - j = 64; - } - - return new MerchantRecipe(new ItemStack(Items.EMERALD, j), new ItemStack(Items.BOOK), itemstack, 12, this.a, 0.2F); - } - } - - static class a implements VillagerTrades.IMerchantRecipeOption { - - private final Item a; - private final int b; - private final int c; - private final int d; - - public a(Item item, int i) { - this(item, i, 12, 1); - } - - public a(Item item, int i, int j, int k) { - this.a = item; - this.b = i; - this.c = j; - this.d = k; - } - - @Override - public MerchantRecipe a(Entity entity, Random random) { - ItemStack itemstack = new ItemStack(Items.EMERALD, this.b); - ItemStack itemstack1 = new ItemStack(this.a); - - if (this.a instanceof ItemArmorColorable) { - List list = Lists.newArrayList(); - - list.add(a(random)); - if (random.nextFloat() > 0.7F) { - list.add(a(random)); - } - - if (random.nextFloat() > 0.8F) { - list.add(a(random)); - } - - itemstack1 = IDyeable.a(itemstack1, list); - } - - return new MerchantRecipe(itemstack, itemstack1, this.c, this.d, 0.2F); - } - - private static ItemDye a(Random random) { - return ItemDye.a(EnumColor.fromColorIndex(random.nextInt(16))); - } - } - - static class j implements VillagerTrades.IMerchantRecipeOption { - - private final ItemStack a; - private final int b; - private final int c; - private final int d; - private final int e; - private final Item f; - private final int g; - private final float h; - - public j(Item item, int i, Item item1, int j, int k, int l, int i1) { - this.a = new ItemStack(item1); - this.c = k; - this.d = l; - this.e = i1; - this.f = item; - this.g = i; - this.b = j; - this.h = 0.05F; - } - - @Override - public MerchantRecipe a(Entity entity, Random random) { - ItemStack itemstack = new ItemStack(Items.EMERALD, this.c); - List list = (List) IRegistry.POTION.d().filter((potionregistry) -> { - return !potionregistry.a().isEmpty() && PotionBrewer.a(potionregistry); - }).collect(Collectors.toList()); - PotionRegistry potionregistry = (PotionRegistry) list.get(random.nextInt(list.size())); - ItemStack itemstack1 = PotionUtil.a(new ItemStack(this.a.getItem(), this.b), potionregistry); - - return new MerchantRecipe(itemstack, new ItemStack(this.f, this.g), itemstack1, this.d, this.e, this.h); - } - } - - static class e implements VillagerTrades.IMerchantRecipeOption { - - private final ItemStack a; - private final int b; - private final int c; - private final int d; - private final float e; - - public e(Item item, int i, int j, int k) { - this(item, i, j, k, 0.05F); - } - - public e(Item item, int i, int j, int k, float f) { - this.a = new ItemStack(item); - this.b = i; - this.c = j; - this.d = k; - this.e = f; - } - - @Override - public MerchantRecipe a(Entity entity, Random random) { - int i = 5 + random.nextInt(15); - ItemStack itemstack = EnchantmentManager.a(random, new ItemStack(this.a.getItem()), i, false); - int j = Math.min(this.b + i, 64); - ItemStack itemstack1 = new ItemStack(Items.EMERALD, j); - - return new MerchantRecipe(itemstack1, itemstack, this.c, this.d, this.e); - } - } - - static class i implements VillagerTrades.IMerchantRecipeOption { - - final MobEffectList a; - final int b; - final int c; - private final float d; - - public i(MobEffectList mobeffectlist, int i, int j) { - this.a = mobeffectlist; - this.b = i; - this.c = j; - this.d = 0.05F; - } - - @Nullable - @Override - public MerchantRecipe a(Entity entity, Random random) { - ItemStack itemstack = new ItemStack(Items.SUSPICIOUS_STEW, 1); - - ItemSuspiciousStew.a(itemstack, this.a, this.b); - return new MerchantRecipe(new ItemStack(Items.EMERALD, 1), itemstack, 12, this.c, this.d); - } - } - - static class h implements VillagerTrades.IMerchantRecipeOption { - - private final ItemStack a; - private final int b; - private final int c; - private final int d; - private final int e; - private final float f; - - public h(Block block, int i, int j, int k, int l) { - this(new ItemStack(block), i, j, k, l); - } - - public h(Item item, int i, int j, int k) { - this(new ItemStack(item), i, j, 12, k); - } - - public h(Item item, int i, int j, int k, int l) { - this(new ItemStack(item), i, j, k, l); - } - - public h(ItemStack itemstack, int i, int j, int k, int l) { - this(itemstack, i, j, k, l, 0.05F); - } - - public h(ItemStack itemstack, int i, int j, int k, int l, float f) { - this.a = itemstack; - this.b = i; - this.c = j; - this.d = k; - this.e = l; - this.f = f; - } - - @Override - public MerchantRecipe a(Entity entity, Random random) { - return new MerchantRecipe(new ItemStack(Items.EMERALD, this.b), new ItemStack(this.a.getItem(), this.c), this.d, this.e, this.f); - } - } - - static class c implements VillagerTrades.IMerchantRecipeOption { - - private final Map a; - private final int b; - private final int c; - private final int d; - - public c(int i, int j, int k, Map map) { - IRegistry.VILLAGER_TYPE.d().filter((villagertype) -> { - return !map.containsKey(villagertype); - }).findAny().ifPresent((villagertype) -> { - throw new IllegalStateException("Missing trade for villager type: " + IRegistry.VILLAGER_TYPE.getKey(villagertype)); - }); - this.a = map; - this.b = i; - this.c = j; - this.d = k; - } - - @Nullable - @Override - public MerchantRecipe a(Entity entity, Random random) { - if (entity instanceof VillagerDataHolder) { - ItemStack itemstack = new ItemStack((IMaterial) this.a.get(((VillagerDataHolder) entity).getVillagerData().getType()), this.b); - - return new MerchantRecipe(itemstack, new ItemStack(Items.EMERALD), this.c, this.d, 0.05F); - } else { - return null; - } - } - } - - static class b implements VillagerTrades.IMerchantRecipeOption { - - private final Item a; - private final int b; - private final int c; - private final int d; - private final float e; - - public b(IMaterial imaterial, int i, int j, int k) { - this.a = imaterial.getItem(); - this.b = i; - this.c = j; - this.d = k; - this.e = 0.05F; - } - - @Override - public MerchantRecipe a(Entity entity, Random random) { - ItemStack itemstack = new ItemStack(this.a, this.b); - - return new MerchantRecipe(itemstack, new ItemStack(Items.EMERALD), this.c, this.d, this.e); - } - } - - public interface IMerchantRecipeOption { - - @Nullable - MerchantRecipe a(Entity entity, Random random); - } -} diff --git a/src/main/java/net/minecraft/server/VoxelShape.java b/src/main/java/net/minecraft/server/VoxelShape.java deleted file mode 100644 index 092f02cc2..000000000 --- a/src/main/java/net/minecraft/server/VoxelShape.java +++ /dev/null @@ -1,211 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.math.DoubleMath; -import it.unimi.dsi.fastutil.doubles.DoubleList; -import java.util.List; -import javax.annotation.Nullable; - -public abstract class VoxelShape { - - protected final VoxelShapeDiscrete a; - @Nullable - private VoxelShape[] b; - - VoxelShape(VoxelShapeDiscrete voxelshapediscrete) { - this.a = voxelshapediscrete; - } - - public double b(EnumDirection.EnumAxis enumdirection_enumaxis) { - int i = this.a.a(enumdirection_enumaxis); - - return i >= this.a.c(enumdirection_enumaxis) ? Double.POSITIVE_INFINITY : this.a(enumdirection_enumaxis, i); - } - - public double c(EnumDirection.EnumAxis enumdirection_enumaxis) { - int i = this.a.b(enumdirection_enumaxis); - - return i <= 0 ? Double.NEGATIVE_INFINITY : this.a(enumdirection_enumaxis, i); - } - - public AxisAlignedBB getBoundingBox() { - if (this.isEmpty()) { - throw new UnsupportedOperationException("No bounds for empty shape."); - } else { - return new AxisAlignedBB(this.b(EnumDirection.EnumAxis.X), this.b(EnumDirection.EnumAxis.Y), this.b(EnumDirection.EnumAxis.Z), this.c(EnumDirection.EnumAxis.X), this.c(EnumDirection.EnumAxis.Y), this.c(EnumDirection.EnumAxis.Z)); - } - } - - protected double a(EnumDirection.EnumAxis enumdirection_enumaxis, int i) { - return this.a(enumdirection_enumaxis).getDouble(i); - } - - protected abstract DoubleList a(EnumDirection.EnumAxis enumdirection_enumaxis); - - public boolean isEmpty() { - return this.a.a(); - } - - public final VoxelShape offset(double x, double y, double z) { return this.a(x, y, z); } // Paper - OBFHELPER - public VoxelShape a(double d0, double d1, double d2) { - return (VoxelShape) (this.isEmpty() ? VoxelShapes.a() : new VoxelShapeArray(this.a, new DoubleListOffset(this.a(EnumDirection.EnumAxis.X), d0), new DoubleListOffset(this.a(EnumDirection.EnumAxis.Y), d1), new DoubleListOffset(this.a(EnumDirection.EnumAxis.Z), d2))); - } - - public VoxelShape c() { - VoxelShape[] avoxelshape = new VoxelShape[]{VoxelShapes.a()}; - - this.b((d0, d1, d2, d3, d4, d5) -> { - avoxelshape[0] = VoxelShapes.b(avoxelshape[0], VoxelShapes.create(d0, d1, d2, d3, d4, d5), OperatorBoolean.OR); - }); - return avoxelshape[0]; - } - - public void b(VoxelShapes.a voxelshapes_a) { - DoubleList doublelist = this.a(EnumDirection.EnumAxis.X); - DoubleList doublelist1 = this.a(EnumDirection.EnumAxis.Y); - DoubleList doublelist2 = this.a(EnumDirection.EnumAxis.Z); - - this.a.b((i, j, k, l, i1, j1) -> { - voxelshapes_a.consume(doublelist.getDouble(i), doublelist1.getDouble(j), doublelist2.getDouble(k), doublelist.getDouble(l), doublelist1.getDouble(i1), doublelist2.getDouble(j1)); - }, true); - } - - public List d() { - List list = Lists.newArrayList(); - - this.b((d0, d1, d2, d3, d4, d5) -> { - list.add(new AxisAlignedBB(d0, d1, d2, d3, d4, d5)); - }); - return list; - } - - protected int a(EnumDirection.EnumAxis enumdirection_enumaxis, double d0) { - return MathHelper.a(0, this.a.c(enumdirection_enumaxis) + 1, (i) -> { - return i < 0 ? false : (i > this.a.c(enumdirection_enumaxis) ? true : d0 < this.a(enumdirection_enumaxis, i)); - }) - 1; - } - - protected boolean b(double d0, double d1, double d2) { - return this.a.c(this.a(EnumDirection.EnumAxis.X, d0), this.a(EnumDirection.EnumAxis.Y, d1), this.a(EnumDirection.EnumAxis.Z, d2)); - } - - @Nullable - public MovingObjectPositionBlock rayTrace(Vec3D vec3d, Vec3D vec3d1, BlockPosition blockposition) { - if (this.isEmpty()) { - return null; - } else { - Vec3D vec3d2 = vec3d1.d(vec3d); - - if (vec3d2.g() < 1.0E-7D) { - return null; - } else { - Vec3D vec3d3 = vec3d.e(vec3d2.a(0.001D)); - - return this.b(vec3d3.x - (double) blockposition.getX(), vec3d3.y - (double) blockposition.getY(), vec3d3.z - (double) blockposition.getZ()) ? new MovingObjectPositionBlock(vec3d3, EnumDirection.a(vec3d2.x, vec3d2.y, vec3d2.z).opposite(), blockposition, true) : AxisAlignedBB.a(this.d(), vec3d, vec3d1, blockposition); - } - } - } - - public VoxelShape a(EnumDirection enumdirection) { - if (!this.isEmpty() && this != VoxelShapes.b()) { - VoxelShape voxelshape; - - if (this.b != null) { - voxelshape = this.b[enumdirection.ordinal()]; - if (voxelshape != null) { - return voxelshape; - } - } else { - this.b = new VoxelShape[6]; - } - - voxelshape = this.b(enumdirection); - this.b[enumdirection.ordinal()] = voxelshape; - return voxelshape; - } else { - return this; - } - } - - private VoxelShape b(EnumDirection enumdirection) { - EnumDirection.EnumAxis enumdirection_enumaxis = enumdirection.k(); - EnumDirection.EnumAxisDirection enumdirection_enumaxisdirection = enumdirection.c(); - DoubleList doublelist = this.a(enumdirection_enumaxis); - - if (doublelist.size() == 2 && DoubleMath.fuzzyEquals(doublelist.getDouble(0), 0.0D, 1.0E-7D) && DoubleMath.fuzzyEquals(doublelist.getDouble(1), 1.0D, 1.0E-7D)) { - return this; - } else { - int i = this.a(enumdirection_enumaxis, enumdirection_enumaxisdirection == EnumDirection.EnumAxisDirection.POSITIVE ? 0.9999999D : 1.0E-7D); - - return new VoxelShapeSlice(this, enumdirection_enumaxis, i); - } - } - - public double a(EnumDirection.EnumAxis enumdirection_enumaxis, AxisAlignedBB axisalignedbb, double d0) { - return this.a(EnumAxisCycle.a(enumdirection_enumaxis, EnumDirection.EnumAxis.X), axisalignedbb, d0); - } - - protected double a(EnumAxisCycle enumaxiscycle, AxisAlignedBB axisalignedbb, double d0) { - if (this.isEmpty()) { - return d0; - } else if (Math.abs(d0) < 1.0E-7D) { - return 0.0D; - } else { - EnumAxisCycle enumaxiscycle1 = enumaxiscycle.a(); - EnumDirection.EnumAxis enumdirection_enumaxis = enumaxiscycle1.a(EnumDirection.EnumAxis.X); - EnumDirection.EnumAxis enumdirection_enumaxis1 = enumaxiscycle1.a(EnumDirection.EnumAxis.Y); - EnumDirection.EnumAxis enumdirection_enumaxis2 = enumaxiscycle1.a(EnumDirection.EnumAxis.Z); - double d1 = axisalignedbb.b(enumdirection_enumaxis); - double d2 = axisalignedbb.a(enumdirection_enumaxis); - int i = this.a(enumdirection_enumaxis, d2 + 1.0E-7D); - int j = this.a(enumdirection_enumaxis, d1 - 1.0E-7D); - int k = Math.max(0, this.a(enumdirection_enumaxis1, axisalignedbb.a(enumdirection_enumaxis1) + 1.0E-7D)); - int l = Math.min(this.a.c(enumdirection_enumaxis1), this.a(enumdirection_enumaxis1, axisalignedbb.b(enumdirection_enumaxis1) - 1.0E-7D) + 1); - int i1 = Math.max(0, this.a(enumdirection_enumaxis2, axisalignedbb.a(enumdirection_enumaxis2) + 1.0E-7D)); - int j1 = Math.min(this.a.c(enumdirection_enumaxis2), this.a(enumdirection_enumaxis2, axisalignedbb.b(enumdirection_enumaxis2) - 1.0E-7D) + 1); - int k1 = this.a.c(enumdirection_enumaxis); - double d3; - int l1; - int i2; - int j2; - - if (d0 > 0.0D) { - for (l1 = j + 1; l1 < k1; ++l1) { - for (i2 = k; i2 < l; ++i2) { - for (j2 = i1; j2 < j1; ++j2) { - if (this.a.a(enumaxiscycle1, l1, i2, j2)) { - d3 = this.a(enumdirection_enumaxis, l1) - d1; - if (d3 >= -1.0E-7D) { - d0 = Math.min(d0, d3); - } - - return d0; - } - } - } - } - } else if (d0 < 0.0D) { - for (l1 = i - 1; l1 >= 0; --l1) { - for (i2 = k; i2 < l; ++i2) { - for (j2 = i1; j2 < j1; ++j2) { - if (this.a.a(enumaxiscycle1, l1, i2, j2)) { - d3 = this.a(enumdirection_enumaxis, l1 + 1) - d2; - if (d3 <= 1.0E-7D) { - d0 = Math.max(d0, d3); - } - - return d0; - } - } - } - } - } - - return d0; - } - } - - public String toString() { - return this.isEmpty() ? "EMPTY" : "VoxelShape[" + this.getBoundingBox() + "]"; - } -} diff --git a/src/main/java/net/minecraft/server/VoxelShapes.java b/src/main/java/net/minecraft/server/VoxelShapes.java deleted file mode 100644 index c8bd4b703..000000000 --- a/src/main/java/net/minecraft/server/VoxelShapes.java +++ /dev/null @@ -1,338 +0,0 @@ -package net.minecraft.server; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.math.DoubleMath; -import com.google.common.math.IntMath; -import it.unimi.dsi.fastutil.doubles.DoubleArrayList; -import it.unimi.dsi.fastutil.doubles.DoubleList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.Objects; -import java.util.stream.Stream; - -public final class VoxelShapes { - - private static final VoxelShape b = (VoxelShape) SystemUtils.a(() -> { - VoxelShapeBitSet voxelshapebitset = new VoxelShapeBitSet(1, 1, 1); - - voxelshapebitset.a(0, 0, 0, true, true); - return new VoxelShapeCube(voxelshapebitset); - }); - public static final VoxelShape a = create(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); - private static final VoxelShape c = new VoxelShapeArray(new VoxelShapeBitSet(0, 0, 0), new DoubleArrayList(new double[]{0.0D}), new DoubleArrayList(new double[]{0.0D}), new DoubleArrayList(new double[]{0.0D})); - - public static VoxelShape a() { - return VoxelShapes.c; - } - - public static VoxelShape b() { - return VoxelShapes.b; - } - - public static VoxelShape create(double d0, double d1, double d2, double d3, double d4, double d5) { - return a(new AxisAlignedBB(d0, d1, d2, d3, d4, d5)); - } - - public static final VoxelShape of(AxisAlignedBB axisAlignedbb) { return VoxelShapes.a(axisAlignedbb); } // Paper - OBFHELPER - public static VoxelShape a(AxisAlignedBB axisalignedbb) { - int i = a(axisalignedbb.minX, axisalignedbb.maxX); - int j = a(axisalignedbb.minY, axisalignedbb.maxY); - int k = a(axisalignedbb.minZ, axisalignedbb.maxZ); - - if (i >= 0 && j >= 0 && k >= 0) { - if (i == 0 && j == 0 && k == 0) { - return axisalignedbb.e(0.5D, 0.5D, 0.5D) ? b() : a(); - } else { - int l = 1 << i; - int i1 = 1 << j; - int j1 = 1 << k; - int k1 = (int) Math.round(axisalignedbb.minX * (double) l); - int l1 = (int) Math.round(axisalignedbb.maxX * (double) l); - int i2 = (int) Math.round(axisalignedbb.minY * (double) i1); - int j2 = (int) Math.round(axisalignedbb.maxY * (double) i1); - int k2 = (int) Math.round(axisalignedbb.minZ * (double) j1); - int l2 = (int) Math.round(axisalignedbb.maxZ * (double) j1); - VoxelShapeBitSet voxelshapebitset = new VoxelShapeBitSet(l, i1, j1, k1, i2, k2, l1, j2, l2); - - for (long i3 = (long) k1; i3 < (long) l1; ++i3) { - for (long j3 = (long) i2; j3 < (long) j2; ++j3) { - for (long k3 = (long) k2; k3 < (long) l2; ++k3) { - voxelshapebitset.a((int) i3, (int) j3, (int) k3, false, true); - } - } - } - - return new VoxelShapeCube(voxelshapebitset); - } - } else { - return new VoxelShapeArray(VoxelShapes.b.a, new double[]{axisalignedbb.minX, axisalignedbb.maxX}, new double[]{axisalignedbb.minY, axisalignedbb.maxY}, new double[]{axisalignedbb.minZ, axisalignedbb.maxZ}); - } - } - - private static int a(double d0, double d1) { - if (d0 >= -1.0E-7D && d1 <= 1.0000001D) { - for (int i = 0; i <= 3; ++i) { - double d2 = d0 * (double) (1 << i); - double d3 = d1 * (double) (1 << i); - boolean flag = Math.abs(d2 - Math.floor(d2)) < 1.0E-7D; - boolean flag1 = Math.abs(d3 - Math.floor(d3)) < 1.0E-7D; - - if (flag && flag1) { - return i; - } - } - - return -1; - } else { - return -1; - } - } - - protected static long a(int i, int j) { - return (long) i * (long) (j / IntMath.gcd(i, j)); - } - - public static VoxelShape a(VoxelShape voxelshape, VoxelShape voxelshape1) { - return a(voxelshape, voxelshape1, OperatorBoolean.OR); - } - - public static VoxelShape a(VoxelShape voxelshape, VoxelShape... avoxelshape) { - return (VoxelShape) Arrays.stream(avoxelshape).reduce(voxelshape, VoxelShapes::a); - } - - public static VoxelShape a(VoxelShape voxelshape, VoxelShape voxelshape1, OperatorBoolean operatorboolean) { - return b(voxelshape, voxelshape1, operatorboolean).c(); - } - - public static VoxelShape b(VoxelShape voxelshape, VoxelShape voxelshape1, OperatorBoolean operatorboolean) { - if (operatorboolean.apply(false, false)) { - throw new IllegalArgumentException(); - } else if (voxelshape == voxelshape1) { - return operatorboolean.apply(true, true) ? voxelshape : a(); - } else { - boolean flag = operatorboolean.apply(true, false); - boolean flag1 = operatorboolean.apply(false, true); - - if (voxelshape.isEmpty()) { - return flag1 ? voxelshape1 : a(); - } else if (voxelshape1.isEmpty()) { - return flag ? voxelshape : a(); - } else { - VoxelShapeMerger voxelshapemerger = a(1, voxelshape.a(EnumDirection.EnumAxis.X), voxelshape1.a(EnumDirection.EnumAxis.X), flag, flag1); - VoxelShapeMerger voxelshapemerger1 = a(voxelshapemerger.a().size() - 1, voxelshape.a(EnumDirection.EnumAxis.Y), voxelshape1.a(EnumDirection.EnumAxis.Y), flag, flag1); - VoxelShapeMerger voxelshapemerger2 = a((voxelshapemerger.a().size() - 1) * (voxelshapemerger1.a().size() - 1), voxelshape.a(EnumDirection.EnumAxis.Z), voxelshape1.a(EnumDirection.EnumAxis.Z), flag, flag1); - VoxelShapeBitSet voxelshapebitset = VoxelShapeBitSet.a(voxelshape.a, voxelshape1.a, voxelshapemerger, voxelshapemerger1, voxelshapemerger2, operatorboolean); - - return (VoxelShape) (voxelshapemerger instanceof VoxelShapeCubeMerger && voxelshapemerger1 instanceof VoxelShapeCubeMerger && voxelshapemerger2 instanceof VoxelShapeCubeMerger ? new VoxelShapeCube(voxelshapebitset) : new VoxelShapeArray(voxelshapebitset, voxelshapemerger.a(), voxelshapemerger1.a(), voxelshapemerger2.a())); - } - } - } - - public static final boolean applyOperation(VoxelShape voxelshape, VoxelShape voxelshape1, OperatorBoolean operatorboolean) { return VoxelShapes.c(voxelshape, voxelshape1, operatorboolean); } // Paper - OBFHELPER - public static boolean c(VoxelShape voxelshape, VoxelShape voxelshape1, OperatorBoolean operatorboolean) { - if (operatorboolean.apply(false, false)) { - throw new IllegalArgumentException(); - } else if (voxelshape == voxelshape1) { - return operatorboolean.apply(true, true); - } else if (voxelshape.isEmpty()) { - return operatorboolean.apply(false, !voxelshape1.isEmpty()); - } else if (voxelshape1.isEmpty()) { - return operatorboolean.apply(!voxelshape.isEmpty(), false); - } else { - boolean flag = operatorboolean.apply(true, false); - boolean flag1 = operatorboolean.apply(false, true); - EnumDirection.EnumAxis[] aenumdirection_enumaxis = EnumAxisCycle.d; - int i = aenumdirection_enumaxis.length; - - for (int j = 0; j < i; ++j) { - EnumDirection.EnumAxis enumdirection_enumaxis = aenumdirection_enumaxis[j]; - - if (voxelshape.c(enumdirection_enumaxis) < voxelshape1.b(enumdirection_enumaxis) - 1.0E-7D) { - return flag || flag1; - } - - if (voxelshape1.c(enumdirection_enumaxis) < voxelshape.b(enumdirection_enumaxis) - 1.0E-7D) { - return flag || flag1; - } - } - - VoxelShapeMerger voxelshapemerger = a(1, voxelshape.a(EnumDirection.EnumAxis.X), voxelshape1.a(EnumDirection.EnumAxis.X), flag, flag1); - VoxelShapeMerger voxelshapemerger1 = a(voxelshapemerger.a().size() - 1, voxelshape.a(EnumDirection.EnumAxis.Y), voxelshape1.a(EnumDirection.EnumAxis.Y), flag, flag1); - VoxelShapeMerger voxelshapemerger2 = a((voxelshapemerger.a().size() - 1) * (voxelshapemerger1.a().size() - 1), voxelshape.a(EnumDirection.EnumAxis.Z), voxelshape1.a(EnumDirection.EnumAxis.Z), flag, flag1); - - return a(voxelshapemerger, voxelshapemerger1, voxelshapemerger2, voxelshape.a, voxelshape1.a, operatorboolean); - } - } - - private static boolean a(VoxelShapeMerger voxelshapemerger, VoxelShapeMerger voxelshapemerger1, VoxelShapeMerger voxelshapemerger2, VoxelShapeDiscrete voxelshapediscrete, VoxelShapeDiscrete voxelshapediscrete1, OperatorBoolean operatorboolean) { - return !voxelshapemerger.a((i, j, k) -> { - return voxelshapemerger1.a((l, i1, j1) -> { - return voxelshapemerger2.a((k1, l1, i2) -> { - return !operatorboolean.apply(voxelshapediscrete.c(i, l, k1), voxelshapediscrete1.c(j, i1, l1)); - }); - }); - }); - } - - public static double a(EnumDirection.EnumAxis enumdirection_enumaxis, AxisAlignedBB axisalignedbb, Stream stream, double d0) { - for (Iterator iterator = stream.iterator(); iterator.hasNext(); d0 = ((VoxelShape) iterator.next()).a(enumdirection_enumaxis, axisalignedbb, d0)) { - if (Math.abs(d0) < 1.0E-7D) { - return 0.0D; - } - } - - return d0; - } - - public static double a(EnumDirection.EnumAxis enumdirection_enumaxis, AxisAlignedBB axisalignedbb, IWorldReader iworldreader, double d0, VoxelShapeCollision voxelshapecollision, Stream stream) { - return a(axisalignedbb, iworldreader, d0, voxelshapecollision, EnumAxisCycle.a(enumdirection_enumaxis, EnumDirection.EnumAxis.Z), stream); - } - - private static double a(AxisAlignedBB axisalignedbb, IWorldReader iworldreader, double d0, VoxelShapeCollision voxelshapecollision, EnumAxisCycle enumaxiscycle, Stream stream) { - if (axisalignedbb.b() >= 1.0E-6D && axisalignedbb.c() >= 1.0E-6D && axisalignedbb.d() >= 1.0E-6D) { - if (Math.abs(d0) < 1.0E-7D) { - return 0.0D; - } else { - EnumAxisCycle enumaxiscycle1 = enumaxiscycle.a(); - EnumDirection.EnumAxis enumdirection_enumaxis = enumaxiscycle1.a(EnumDirection.EnumAxis.X); - EnumDirection.EnumAxis enumdirection_enumaxis1 = enumaxiscycle1.a(EnumDirection.EnumAxis.Y); - EnumDirection.EnumAxis enumdirection_enumaxis2 = enumaxiscycle1.a(EnumDirection.EnumAxis.Z); - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - int i = MathHelper.floor(axisalignedbb.a(enumdirection_enumaxis) - 1.0E-7D) - 1; - int j = MathHelper.floor(axisalignedbb.b(enumdirection_enumaxis) + 1.0E-7D) + 1; - int k = MathHelper.floor(axisalignedbb.a(enumdirection_enumaxis1) - 1.0E-7D) - 1; - int l = MathHelper.floor(axisalignedbb.b(enumdirection_enumaxis1) + 1.0E-7D) + 1; - double d1 = axisalignedbb.a(enumdirection_enumaxis2) - 1.0E-7D; - double d2 = axisalignedbb.b(enumdirection_enumaxis2) + 1.0E-7D; - boolean flag = d0 > 0.0D; - int i1 = flag ? MathHelper.floor(axisalignedbb.b(enumdirection_enumaxis2) - 1.0E-7D) - 1 : MathHelper.floor(axisalignedbb.a(enumdirection_enumaxis2) + 1.0E-7D) + 1; - int j1 = a(d0, d1, d2); - int k1 = flag ? 1 : -1; - int l1 = i1; - - while (true) { - if (flag) { - if (l1 > j1) { - break; - } - } else if (l1 < j1) { - break; - } - - for (int i2 = i; i2 <= j; ++i2) { - for (int j2 = k; j2 <= l; ++j2) { - int k2 = 0; - - if (i2 == i || i2 == j) { - ++k2; - } - - if (j2 == k || j2 == l) { - ++k2; - } - - if (l1 == i1 || l1 == j1) { - ++k2; - } - - if (k2 < 3) { - blockposition_mutableblockposition.a(enumaxiscycle1, i2, j2, l1); - IBlockData iblockdata = iworldreader.getType(blockposition_mutableblockposition); - - if ((k2 != 1 || iblockdata.f()) && (k2 != 2 || iblockdata.getBlock() == Blocks.MOVING_PISTON)) { - d0 = iblockdata.b((IBlockAccess) iworldreader, blockposition_mutableblockposition, voxelshapecollision).a(enumdirection_enumaxis2, axisalignedbb.d((double) (-blockposition_mutableblockposition.getX()), (double) (-blockposition_mutableblockposition.getY()), (double) (-blockposition_mutableblockposition.getZ())), d0); - if (Math.abs(d0) < 1.0E-7D) { - return 0.0D; - } - - j1 = a(d0, d1, d2); - } - } - } - } - - l1 += k1; - } - - double[] adouble = new double[]{d0}; - - stream.forEach((voxelshape) -> { - adouble[0] = voxelshape.a(enumdirection_enumaxis2, axisalignedbb, adouble[0]); - }); - return adouble[0]; - } - } else { - return d0; - } - } - - private static int a(double d0, double d1, double d2) { - return d0 > 0.0D ? MathHelper.floor(d2 + d0) + 1 : MathHelper.floor(d1 + d0) - 1; - } - - public static VoxelShape a(VoxelShape voxelshape, EnumDirection enumdirection) { - if (voxelshape == b()) { - return b(); - } else { - EnumDirection.EnumAxis enumdirection_enumaxis = enumdirection.k(); - boolean flag; - int i; - - if (enumdirection.c() == EnumDirection.EnumAxisDirection.POSITIVE) { - flag = DoubleMath.fuzzyEquals(voxelshape.c(enumdirection_enumaxis), 1.0D, 1.0E-7D); - i = voxelshape.a.c(enumdirection_enumaxis) - 1; - } else { - flag = DoubleMath.fuzzyEquals(voxelshape.b(enumdirection_enumaxis), 0.0D, 1.0E-7D); - i = 0; - } - - return (VoxelShape) (!flag ? a() : new VoxelShapeSlice(voxelshape, enumdirection_enumaxis, i)); - } - } - - public static boolean b(VoxelShape voxelshape, VoxelShape voxelshape1, EnumDirection enumdirection) { - if (voxelshape != b() && voxelshape1 != b()) { - EnumDirection.EnumAxis enumdirection_enumaxis = enumdirection.k(); - EnumDirection.EnumAxisDirection enumdirection_enumaxisdirection = enumdirection.c(); - VoxelShape voxelshape2 = enumdirection_enumaxisdirection == EnumDirection.EnumAxisDirection.POSITIVE ? voxelshape : voxelshape1; - VoxelShape voxelshape3 = enumdirection_enumaxisdirection == EnumDirection.EnumAxisDirection.POSITIVE ? voxelshape1 : voxelshape; - - if (!DoubleMath.fuzzyEquals(voxelshape2.c(enumdirection_enumaxis), 1.0D, 1.0E-7D)) { - voxelshape2 = a(); - } - - if (!DoubleMath.fuzzyEquals(voxelshape3.b(enumdirection_enumaxis), 0.0D, 1.0E-7D)) { - voxelshape3 = a(); - } - - return !c(b(), b(new VoxelShapeSlice(voxelshape2, enumdirection_enumaxis, voxelshape2.a.c(enumdirection_enumaxis) - 1), new VoxelShapeSlice(voxelshape3, enumdirection_enumaxis, 0), OperatorBoolean.OR), OperatorBoolean.ONLY_FIRST); - } else { - return true; - } - } - - public static boolean b(VoxelShape voxelshape, VoxelShape voxelshape1) { - return voxelshape != b() && voxelshape1 != b() ? (voxelshape.isEmpty() && voxelshape1.isEmpty() ? false : !c(b(), b(voxelshape, voxelshape1, OperatorBoolean.OR), OperatorBoolean.ONLY_FIRST)) : true; - } - - @VisibleForTesting - protected static VoxelShapeMerger a(int i, DoubleList doublelist, DoubleList doublelist1, boolean flag, boolean flag1) { - int j = doublelist.size() - 1; - int k = doublelist1.size() - 1; - - if (doublelist instanceof VoxelShapeCubePoint && doublelist1 instanceof VoxelShapeCubePoint) { - long l = a(j, k); - - if ((long) i * l <= 256L) { - return new VoxelShapeCubeMerger(j, k); - } - } - - return (VoxelShapeMerger) (doublelist.getDouble(j) < doublelist1.getDouble(0) - 1.0E-7D ? new VoxelShapeMergerDisjoint(doublelist, doublelist1, false) : (doublelist1.getDouble(k) < doublelist.getDouble(0) - 1.0E-7D ? new VoxelShapeMergerDisjoint(doublelist1, doublelist, true) : (j == k && Objects.equals(doublelist, doublelist1) ? (doublelist instanceof VoxelShapeMergerIdentical ? (VoxelShapeMerger) doublelist : (doublelist1 instanceof VoxelShapeMergerIdentical ? (VoxelShapeMerger) doublelist1 : new VoxelShapeMergerIdentical(doublelist))) : new VoxelShapeMergerList(doublelist, doublelist1, flag, flag1)))); - } - - public interface a { - - void consume(double d0, double d1, double d2, double d3, double d4, double d5); - } -} diff --git a/src/main/java/net/minecraft/server/World.java b/src/main/java/net/minecraft/server/World.java deleted file mode 100644 index 1bea6dffe..000000000 --- a/src/main/java/net/minecraft/server/World.java +++ /dev/null @@ -1,1650 +0,0 @@ -package net.minecraft.server; - -import co.aikar.timings.Timing; -import co.aikar.timings.Timings; -import com.destroystokyo.paper.antixray.ChunkPacketBlockController; // Paper - Anti-Xray -import com.destroystokyo.paper.antixray.ChunkPacketBlockControllerAntiXray; // Paper - Anti-Xray -import com.destroystokyo.paper.event.server.ServerExceptionEvent; -import com.destroystokyo.paper.exception.ServerInternalException; -import com.google.common.base.MoreObjects; -import com.google.common.collect.Lists; -import java.io.IOException; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Predicate; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.util.Supplier; - -// CraftBukkit start -import com.google.common.collect.Maps; -import java.util.ArrayList; -import java.util.HashMap; // Paper -import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.block.BlockState; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.block.CraftBlockState; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; -import org.bukkit.event.weather.LightningStrikeEvent; -// CraftBukkit end - -public abstract class World implements IIBlockAccess, GeneratorAccess, AutoCloseable { - - protected static final Logger LOGGER = LogManager.getLogger(); - private static final EnumDirection[] a = EnumDirection.values(); - //public final List tileEntityList = Lists.newArrayList(); // Paper - remove unused list - public final List tileEntityListTick = Lists.newArrayList(); - protected final List tileEntityListPending = Lists.newArrayList(); - protected final java.util.Set tileEntityListUnload = com.google.common.collect.Sets.newHashSet(); // Paper - private final long b = 16777215L; - final Thread serverThread; // CraftBukkit - package private - private int u; public int getSkylightSubtracted() { return this.u; } public void setSkylightSubtracted(int value) { this.u = value;} // Paper - OBFHELPER - protected int i = (new Random()).nextInt(); - protected final int j = 1013904223; - protected float lastRainLevel; - protected float rainLevel; - protected float lastThunderLevel; - protected float thunderLevel; - private int v; - public final Random random = new Random(); - public WorldProvider worldProvider; - protected final IChunkProvider chunkProvider; - public final WorldData worldData; - private final GameProfilerFiller methodProfiler; - public final boolean isClientSide; - protected boolean tickingTileEntities; - private final WorldBorder worldBorder; - - // CraftBukkit start Added the following - private final CraftWorld world; - public boolean pvpMode; - public boolean keepSpawnInMemory = true; - public org.bukkit.generator.ChunkGenerator generator; - public static final boolean DEBUG_ENTITIES = Boolean.getBoolean("debug.entities"); // Paper - - public boolean captureBlockStates = false; - public boolean captureTreeGeneration = false; - public ArrayList capturedBlockStates = new ArrayList() { - @Override - public boolean add(CraftBlockState blockState) { - Iterator blockStateIterator = this.iterator(); - while (blockStateIterator.hasNext()) { - BlockState blockState1 = blockStateIterator.next(); - if (blockState1.getLocation().equals(blockState.getLocation())) { - return false; - } - } - - return super.add(blockState); - } - }; - public List captureDrops; - public long ticksPerAnimalSpawns; - public long ticksPerMonsterSpawns; - public boolean populating; - public final org.spigotmc.SpigotWorldConfig spigotConfig; // Spigot - - public final com.destroystokyo.paper.PaperWorldConfig paperConfig; // Paper - public final ChunkPacketBlockController chunkPacketBlockController; // Paper - Anti-Xray - - public final co.aikar.timings.WorldTimingsHandler timings; // Paper - public static BlockPosition lastPhysicsProblem; // Spigot - private org.spigotmc.TickLimiter entityLimiter; - private org.spigotmc.TickLimiter tileLimiter; - private int tileTickPosition; - public final Map explosionDensityCache = new HashMap<>(); // Paper - Optimize explosions - public java.util.ArrayDeque redstoneUpdateInfos; // Paper - Move from Map in BlockRedstoneTorch to here - // Paper start - yes this is hacky as shit - RegionLimitedWorldAccess regionLimited; - World originalWorld; - public World regionLimited(RegionLimitedWorldAccess limitedWorldAccess) { - try { - World clone = (World) super.clone(); - clone.regionLimited = limitedWorldAccess; - clone.originalWorld = this; - return clone; - } catch (CloneNotSupportedException e1) { - } - return null; - } - ChunkCoordIntPair[] strongholdCoords; - List strongholdStuctures = Lists.newArrayList(); - final java.lang.Object stuctureLock = new Object(); - // Paper end - - public CraftWorld getWorld() { - return this.world; - } - - public CraftServer getServer() { - return (CraftServer) Bukkit.getServer(); - } - - public Chunk getChunkIfLoaded(int x, int z) { - return ((ChunkProviderServer) this.chunkProvider).getChunkAtIfLoadedImmediately(x, z); // Paper - } - - protected World(WorldData worlddata, DimensionManager dimensionmanager, BiFunction bifunction, GameProfilerFiller gameprofilerfiller, boolean flag, org.bukkit.generator.ChunkGenerator gen, org.bukkit.World.Environment env) { - this.spigotConfig = new org.spigotmc.SpigotWorldConfig( worlddata.getName() ); // Spigot - this.paperConfig = new com.destroystokyo.paper.PaperWorldConfig(worlddata.getName(), this.spigotConfig); // Paper - this.chunkPacketBlockController = this.paperConfig.antiXray ? new ChunkPacketBlockControllerAntiXray(this.paperConfig) : ChunkPacketBlockController.NO_OPERATION_INSTANCE; // Paper - Anti-Xray - 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 - this.methodProfiler = gameprofilerfiller; - this.worldData = worlddata; - this.worldProvider = dimensionmanager.getWorldProvider(this); - this.chunkProvider = (IChunkProvider) bifunction.apply(this, this.worldProvider); - this.isClientSide = flag; - this.worldBorder = this.worldProvider.getWorldBorder(); - this.serverThread = Thread.currentThread(); - // CraftBukkit start - getWorldBorder().world = (WorldServer) this; - // From PlayerList.setPlayerFileData - getWorldBorder().a(new IWorldBorderListener() { - public void a(WorldBorder worldborder, double d0) { - getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_SIZE), worldborder.world); - } - - public void a(WorldBorder worldborder, double d0, double d1, long i) { - getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.LERP_SIZE), worldborder.world); - } - - public void a(WorldBorder worldborder, double d0, double d1) { - getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_CENTER), worldborder.world); - } - - public void a(WorldBorder worldborder, int i) { - getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_WARNING_TIME), worldborder.world); - } - - public void b(WorldBorder worldborder, int i) { - getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_WARNING_BLOCKS), worldborder.world); - } - - public void b(WorldBorder worldborder, double d0) {} - - public void c(WorldBorder worldborder, double d0) {} - }); - // CraftBukkit end - timings = new co.aikar.timings.WorldTimingsHandler(this); // Paper - code below can generate new world and access timings - this.keepSpawnInMemory = this.paperConfig.keepSpawnInMemory; // Paper - this.entityLimiter = new org.spigotmc.TickLimiter(spigotConfig.entityMaxTickTime); - this.tileLimiter = new org.spigotmc.TickLimiter(spigotConfig.tileMaxTickTime); - } - - // Paper start - // ret true if no collision - public final boolean checkEntityCollision(IBlockData data, Entity source, VoxelShapeCollision voxelshapedcollision, - BlockPosition position, boolean checkCanSee) { - // Copied from IWorldReader#a(IBlockData, BlockPosition, VoxelShapeCollision) & EntityAccess#a(Entity, VoxelShape) - VoxelShape voxelshape = data.getCollisionShape(this, position, voxelshapedcollision); - if (voxelshape.isEmpty()) { - return true; - } - - voxelshape = voxelshape.offset((double) position.getX(), (double) position.getY(), (double) position.getZ()); - - if (voxelshape.isEmpty()) { - return true; - } - - List entities = this.getEntities(null, voxelshape.getBoundingBox()); - - for (int i = 0, len = entities.size(); i < len; ++i) { - Entity entity = entities.get(i); - - if (checkCanSee && source instanceof EntityPlayer && entity instanceof EntityPlayer - && !((EntityPlayer)source).getBukkitEntity().canSee(((EntityPlayer)entity).getBukkitEntity())) { - continue; - } - - // !entity1.dead && entity1.i && (entity == null || !entity1.x(entity)); - // elide the last check since vanilla calls with entity = null - // only we care about the source for the canSee check - if (entity.dead || !entity.blocksEntitySpawning()) { - continue; - } - - if (VoxelShapes.applyOperation(voxelshape, VoxelShapes.of(entity.getBoundingBox()), OperatorBoolean.AND)) { - return false; - } - } - - return true; - } - // Paper end - - @Override - public BiomeBase getBiome(BlockPosition blockposition) { - IChunkProvider ichunkprovider = this.getChunkProvider(); - Chunk chunk = ichunkprovider.getChunkAt(blockposition.getX() >> 4, blockposition.getZ() >> 4, false); - - if (chunk != null) { - return chunk.getBiome(blockposition); - } else { - ChunkGenerator chunkgenerator = this.getChunkProvider().getChunkGenerator(); - - return chunkgenerator == null ? Biomes.PLAINS : chunkgenerator.getWorldChunkManager().getBiome(blockposition); - } - } - - @Override - public boolean e() { - return this.isClientSide; - } - - @Nullable - public MinecraftServer getMinecraftServer() { - return null; - } - - public IBlockData i(BlockPosition blockposition) { - BlockPosition blockposition1; - - for (blockposition1 = new BlockPosition(blockposition.getX(), this.getSeaLevel(), blockposition.getZ()); !this.isEmpty(blockposition1.up()); blockposition1 = blockposition1.up()) { - ; - } - - return this.getType(blockposition1); - } - - public static boolean isValidLocation(BlockPosition blockposition) { - return blockposition.isValidLocation(); // Paper - } - - public static boolean isOutsideWorld(BlockPosition blockposition) { - return blockposition.isInvalidYLocation(); // Paper - } - - public static boolean b(int i) { - return i < 0 || i >= 256; - } - - public boolean isLoaded(BlockPosition blockposition) { - return getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4) != null; // Paper - } - - // Paper start - public boolean isLoadedAndInBounds(BlockPosition blockposition) { - return getWorldBorder().isInBounds(blockposition) && getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4) != null; - } - public Chunk getChunkIfLoaded(BlockPosition blockposition) { - return getChunkIfLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4); - } - // test if meets light level, return faster - // logic copied from below - public boolean isLightLevel(BlockPosition blockposition, int level) { - return this.getLightLevel(blockposition) >= level; // TODO -// if (isValidLocation(blockposition)) { -// if (this.getType(blockposition).c(this, blockposition)) { // use neighbour brightness (where did this go) -// int sky = getSkylightSubtracted(); -// if (this.getLightLevel(blockposition.up(), sky) >= level) { -// return true; -// } -// if (this.getLightLevel(blockposition.east(), sky) >= level) { -// return true; -// } -// if (this.getLightLevel(blockposition.west(), sky) >= level) { -// return true; -// } -// if (this.getLightLevel(blockposition.south(), sky) >= level) { -// return true; -// } -// if (this.getLightLevel(blockposition.north(), sky) >= level) { -// return true; -// } -// return false; -// } else { -// if (blockposition.getY() >= 256) { -// blockposition = new BlockPosition(blockposition.getX(), 255, blockposition.getZ()); -// } -// -// Chunk chunk = this.getChunkAtWorldCoords(blockposition); -// return chunk.getLightSubtracted(blockposition, this.getSkylightSubtracted()) >= level; -// } -// } else { -// return true; -// } - } - // reduces need to do isLoaded before getType - public IBlockData getTypeIfLoadedAndInBounds(BlockPosition blockposition) { - return getWorldBorder().isInBounds(blockposition) ? getTypeIfLoaded(blockposition) : null; - } - // Paper end - - public Chunk getChunkAtWorldCoords(BlockPosition blockposition) { - return this.getChunkAt(blockposition.getX() >> 4, blockposition.getZ() >> 4); - } - - @Override - public Chunk getChunkAt(int i, int j) { - return (Chunk) this.getChunkAt(i, j, ChunkStatus.FULL); - } - - // Paper start - if loaded - @Nullable - @Override - public IChunkAccess getChunkIfLoadedImmediately(int x, int z) { - return ((ChunkProviderServer)this.chunkProvider).getChunkAtIfLoadedImmediately(x, z); - } - - @Override - public IBlockData getTypeIfLoaded(BlockPosition blockposition) { - // CraftBukkit start - tree generation - if (captureTreeGeneration) { - for (CraftBlockState previous : capturedBlockStates) { - if (previous.getX() == blockposition.getX() && previous.getY() == blockposition.getY() && previous.getZ() == blockposition.getZ()) { - return previous.getHandle(); - } - } - } - // CraftBukkit end - if (!isValidLocation(blockposition)) { - return Blocks.AIR.getBlockData(); - } - IChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4); - - return chunk == null ? null : chunk.getType(blockposition); - } - - @Override - public Fluid getFluidIfLoaded(BlockPosition blockposition) { - IChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4); - - return chunk == null ? null : chunk.getFluid(blockposition); - } - // Paper end - - @Override - public IChunkAccess getChunkAt(int i, int j, ChunkStatus chunkstatus, boolean flag) { - IChunkAccess ichunkaccess = this.chunkProvider.getChunkAt(i, j, chunkstatus, flag); - - if (ichunkaccess == null && flag) { - throw new IllegalStateException("Should always be able to create a chunk!"); - } else { - return ichunkaccess; - } - } - - @Override - public boolean setTypeAndData(BlockPosition blockposition, IBlockData iblockdata, int i) { - // CraftBukkit start - tree generation - if (this.captureTreeGeneration) { - CraftBlockState blockstate = null; - Iterator it = capturedBlockStates.iterator(); - while (it.hasNext()) { - CraftBlockState previous = it.next(); - if (previous.getPosition().equals(blockposition)) { - blockstate = previous; - it.remove(); - break; - } - } - if (blockstate == null) { - blockstate = org.bukkit.craftbukkit.block.CraftBlockState.getBlockState(this, blockposition, i); - } - blockstate.setData(iblockdata); - this.capturedBlockStates.add(blockstate); - return true; - } - // CraftBukkit end - if (isOutsideWorld(blockposition)) { - return false; - } else if (!this.isClientSide && this.worldData.getType() == WorldType.DEBUG_ALL_BLOCK_STATES) { - return false; - } else { - Chunk chunk = this.getChunkAtWorldCoords(blockposition); - Block block = iblockdata.getBlock(); - - // CraftBukkit start - capture blockstates - CraftBlockState blockstate = null; - if (this.captureBlockStates) { - blockstate = (CraftBlockState) world.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()).getState(); // Paper - use CB getState to get a suitable snapshot - this.capturedBlockStates.add(blockstate); - } - // CraftBukkit end - - IBlockData iblockdata1 = chunk.setType(blockposition, iblockdata, (i & 64) != 0, (i & 1024) == 0); // CraftBukkit custom NO_PLACE flag - this.chunkPacketBlockController.onBlockChange(this, blockposition, iblockdata, iblockdata1, i); // Paper - Anti-Xray - - if (iblockdata1 == null) { - // CraftBukkit start - remove blockstate if failed - if (this.captureBlockStates) { - this.capturedBlockStates.remove(blockstate); - } - // CraftBukkit end - return false; - } else { - IBlockData iblockdata2 = this.getType(blockposition); - - if (iblockdata2 != iblockdata1 && (iblockdata2.b((IBlockAccess) this, blockposition) != iblockdata1.b((IBlockAccess) this, blockposition) || iblockdata2.h() != iblockdata1.h() || iblockdata2.g() || iblockdata1.g())) { - this.methodProfiler.enter("queueCheckLight"); - this.getChunkProvider().getLightEngine().a(blockposition); - this.methodProfiler.exit(); - } - - /* - if (iblockdata2 == iblockdata) { - if (iblockdata1 != iblockdata2) { - this.b(blockposition, iblockdata1, iblockdata2); - } - - if ((i & 2) != 0 && (!this.isClientSide || (i & 4) == 0) && (this.isClientSide || chunk.getState() != null && chunk.getState().isAtLeast(PlayerChunk.State.TICKING))) { - this.notify(blockposition, iblockdata1, iblockdata, i); - } - - if (!this.isClientSide && (i & 1) != 0) { - this.update(blockposition, iblockdata1.getBlock()); - if (iblockdata.isComplexRedstone()) { - this.updateAdjacentComparators(blockposition, block); - } - } - - if ((i & 16) == 0) { - int j = i & -2; - - iblockdata1.b(this, blockposition, j); - iblockdata.a(this, blockposition, j); - iblockdata.b(this, blockposition, j); - } - - this.a(blockposition, iblockdata1, iblockdata2); - } - */ - - // CraftBukkit start - if (!this.captureBlockStates) { // Don't notify clients or update physics while capturing blockstates - // Modularize client and physic updates - // Spigot start - try { - notifyAndUpdatePhysics(blockposition, chunk, iblockdata1, iblockdata, iblockdata2, i); - } catch (StackOverflowError ex) { - lastPhysicsProblem = new BlockPosition(blockposition); - } - // Spigot end - } - // CraftBukkit end - - return true; - } - } - } - - // CraftBukkit start - Split off from above in order to directly send client and physic updates - public void notifyAndUpdatePhysics(BlockPosition blockposition, Chunk chunk, IBlockData oldBlock, IBlockData newBlock, IBlockData actualBlock, int i) { - IBlockData iblockdata = newBlock; - IBlockData iblockdata1 = oldBlock; - IBlockData iblockdata2 = actualBlock; - if (iblockdata2 == iblockdata) { - if (iblockdata1 != iblockdata2) { - this.b(blockposition, iblockdata1, iblockdata2); - } - - if ((i & 2) != 0 && (!this.isClientSide || (i & 4) == 0) && (this.isClientSide || chunk == null || (chunk.getState() != null && chunk.getState().isAtLeast(PlayerChunk.State.TICKING)))) { // allow chunk to be null here as chunk.isReady() is false when we send our notification during block placement - this.notify(blockposition, iblockdata1, iblockdata, i); - } - - if (!this.isClientSide && (i & 1) != 0) { - this.update(blockposition, iblockdata1.getBlock()); - if (iblockdata.isComplexRedstone()) { - this.updateAdjacentComparators(blockposition, newBlock.getBlock()); - } - } - - if ((i & 16) == 0) { - int j = i & -2; - - // CraftBukkit start - iblockdata1.b(this, blockposition, j); // Don't call an event for the old block to limit event spam - CraftWorld world = ((WorldServer) this).getWorld(); - if (world != null && ((WorldServer)this).hasPhysicsEvent) { // Paper - BlockPhysicsEvent event = new BlockPhysicsEvent(world.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), CraftBlockData.fromData(iblockdata)); - this.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - } - // CraftBukkit end - iblockdata.a(this, blockposition, j); - iblockdata.b(this, blockposition, j); - } - - this.a(blockposition, iblockdata1, iblockdata2); - } - } - // CraftBukkit end - - public void a(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1) {} - - public boolean setAir(BlockPosition blockposition) { return this.a(blockposition, false); } // Paper - OBFHELPER - public boolean setAir(BlockPosition blockposition, boolean moved) { return this.a(blockposition, moved); } // Paper - OBFHELPER - @Override public boolean a(BlockPosition blockposition, boolean flag) { // Paper - OBFHELPER - Fluid fluid = this.getFluid(blockposition); - - return this.setTypeAndData(blockposition, fluid.getBlockData(), 3 | (flag ? 64 : 0)); - } - - @Override - public boolean b(BlockPosition blockposition, boolean flag) { - IBlockData iblockdata = this.getType(blockposition); - - if (iblockdata.isAir()) { - return false; - } else { - Fluid fluid = this.getFluid(blockposition); - // Paper start - while the above setAir method is named same and looks very similar - // they are NOT used with same intent and the above should not fire this event. The above method is more of a BlockSetToAirEvent, - // it doesn't imply destruction of a block that plays a sound effect / drops an item. - boolean playEffect = true; - if (com.destroystokyo.paper.event.block.BlockDestroyEvent.getHandlerList().getRegisteredListeners().length > 0) { - com.destroystokyo.paper.event.block.BlockDestroyEvent event = new com.destroystokyo.paper.event.block.BlockDestroyEvent(MCUtil.toBukkitBlock(this, blockposition), fluid.getBlockData().createCraftBlockData(), flag); - if (!event.callEvent()) { - return false; - } - playEffect = event.playEffect(); - } - // Paper end - - if (playEffect) this.triggerEffect(2001, blockposition, Block.getCombinedId(iblockdata)); // Paper - if (flag) { - TileEntity tileentity = iblockdata.getBlock().isTileEntity() ? this.getTileEntity(blockposition) : null; - - Block.a(iblockdata, this, blockposition, tileentity); - } - - return this.setTypeAndData(blockposition, fluid.getBlockData(), 3); - } - } - - public boolean setTypeUpdate(BlockPosition blockposition, IBlockData iblockdata) { - return this.setTypeAndData(blockposition, iblockdata, 3); - } - - public abstract void notify(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1, int i); - - @Override - public void update(BlockPosition blockposition, Block block) { - if (this.worldData.getType() != WorldType.DEBUG_ALL_BLOCK_STATES) { - // CraftBukkit start - if (populating) { - return; - } - // CraftBukkit end - this.applyPhysics(blockposition, block); - } - - } - - public void b(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1) {} - - public void applyPhysics(BlockPosition blockposition, Block block) { - if (captureBlockStates) { return; } // Paper - Cancel all physics during placement - this.a(blockposition.west(), block, blockposition); - this.a(blockposition.east(), block, blockposition); - this.a(blockposition.down(), block, blockposition); - this.a(blockposition.up(), block, blockposition); - this.a(blockposition.north(), block, blockposition); - this.a(blockposition.south(), block, blockposition); - } - - public void a(BlockPosition blockposition, Block block, EnumDirection enumdirection) { - if (enumdirection != EnumDirection.WEST) { - this.a(blockposition.west(), block, blockposition); - } - - if (enumdirection != EnumDirection.EAST) { - this.a(blockposition.east(), block, blockposition); - } - - if (enumdirection != EnumDirection.DOWN) { - this.a(blockposition.down(), block, blockposition); - } - - if (enumdirection != EnumDirection.UP) { - this.a(blockposition.up(), block, blockposition); - } - - if (enumdirection != EnumDirection.NORTH) { - this.a(blockposition.north(), block, blockposition); - } - - if (enumdirection != EnumDirection.SOUTH) { - this.a(blockposition.south(), block, blockposition); - } - - } - - public void neighborChanged(BlockPosition pos, Block blockIn, BlockPosition fromPos) { a(pos, blockIn, fromPos); } // Paper - OBFHELPER - public void a(BlockPosition blockposition, Block block, BlockPosition blockposition1) { - if (!this.isClientSide) { - IBlockData iblockdata = this.getType(blockposition); - - try { - // CraftBukkit start - CraftWorld world = ((WorldServer) this).getWorld(); - if (world != null && ((WorldServer)this).hasPhysicsEvent) { // Paper - BlockPhysicsEvent event = new BlockPhysicsEvent(world.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), CraftBlockData.fromData(iblockdata), world.getBlockAt(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ())); - this.getServer().getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return; - } - } - // CraftBukkit end - iblockdata.doPhysics(this, blockposition, block, blockposition1, false); - // Spigot Start - } catch (StackOverflowError ex) { - lastPhysicsProblem = new BlockPosition(blockposition); - // 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", () -> { - try { - return String.format("ID #%s (%s // %s)", IRegistry.BLOCK.getKey(block), block.l(), block.getClass().getCanonicalName()); - } catch (Throwable throwable1) { - return "ID #" + IRegistry.BLOCK.getKey(block); - } - }); - CrashReportSystemDetails.a(crashreportsystemdetails, blockposition, iblockdata); - throw new ReportedException(crashreport); - } - } - } - - @Override - public int getLightLevel(BlockPosition blockposition, int i) { - if (blockposition.getX() >= -30000000 && blockposition.getZ() >= -30000000 && blockposition.getX() < 30000000 && blockposition.getZ() < 30000000) { - if (blockposition.getY() < 0) { - return 0; - } else { - if (blockposition.getY() >= 256) { - blockposition = new BlockPosition(blockposition.getX(), 255, blockposition.getZ()); - } - if (!this.isLoaded(blockposition)) return 0; // Paper - - return this.getChunkAtWorldCoords(blockposition).a(blockposition, i); - } - } else { - return 15; - } - } - - public final int getHighestBlockY(final HeightMap.Type heightmap, final int x, final int z) { return this.a(heightmap, x, z); } // Paper - OBFHELPER - @Override public int a(HeightMap.Type heightmap_type, int i, int j) { // Paper - OBFHELPER - int k; - - if (i >= -30000000 && j >= -30000000 && i < 30000000 && j < 30000000) { - if (this.isChunkLoaded(i >> 4, j >> 4)) { - k = this.getChunkAt(i >> 4, j >> 4).a(heightmap_type, i & 15, j & 15) + 1; - } else { - k = 0; - } - } else { - k = this.getSeaLevel() + 1; - } - - return k; - } - - @Override - public int getBrightness(EnumSkyBlock enumskyblock, BlockPosition blockposition) { - return this.getChunkProvider().getLightEngine().a(enumskyblock).b(blockposition); - } - - @Override - public IBlockData getType(BlockPosition blockposition) { - // CraftBukkit start - tree generation - if (captureTreeGeneration) { - Iterator it = capturedBlockStates.iterator(); - while (it.hasNext()) { - CraftBlockState previous = it.next(); - if (previous.getPosition().equals(blockposition)) { - return previous.getHandle(); - } - } - } - // CraftBukkit end - if (isOutsideWorld(blockposition)) { - return Blocks.VOID_AIR.getBlockData(); - } else { - Chunk chunk = this.getChunkAt(blockposition.getX() >> 4, blockposition.getZ() >> 4); - - return chunk.getType(blockposition); - } - } - - @Override - public Fluid getFluid(BlockPosition blockposition) { - if (isOutsideWorld(blockposition)) { - return FluidTypes.EMPTY.i(); - } else { - Chunk chunk = this.getChunkAtWorldCoords(blockposition); - - return chunk.getFluid(blockposition); - } - } - - public boolean isDayTime() { return J(); } // Paper - OBFHELPER - public boolean J() { - return this.u < 4; - } - - @Override - public void playSound(@Nullable EntityHuman entityhuman, BlockPosition blockposition, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) { - this.playSound(entityhuman, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, soundeffect, soundcategory, f, f1); - } - - // Paper start - OBFHELPER - public final void sendSoundEffect(@Nullable EntityHuman fromEntity, double x, double y, double z, SoundEffect soundeffect, SoundCategory soundcategory, float volume, float pitch) { - this.playSound(fromEntity, x, y, z, soundeffect, soundcategory, volume, pitch); - } - // Paper end - public abstract void playSound(@Nullable EntityHuman entityhuman, double d0, double d1, double d2, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1); - - public abstract void playSound(@Nullable EntityHuman entityhuman, Entity entity, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1); - - public void a(double d0, double d1, double d2, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1, boolean flag) {} - - @Override - public void addParticle(ParticleParam particleparam, double d0, double d1, double d2, double d3, double d4, double d5) {} - - public void b(ParticleParam particleparam, double d0, double d1, double d2, double d3, double d4, double d5) {} - - public void b(ParticleParam particleparam, boolean flag, double d0, double d1, double d2, double d3, double d4, double d5) {} - - public float b(float f) { - float f1 = this.j(f); - - return f1 * 6.2831855F; - } - - public boolean a(TileEntity tileentity) { - if (this.tickingTileEntities) { - World.LOGGER.error("Adding block entity while ticking: {} @ {}", new Supplier[]{() -> { - return IRegistry.BLOCK_ENTITY_TYPE.getKey(tileentity.q()); - }, tileentity::getPosition}); - } - - boolean flag = true; // Paper - remove unused list - - if (flag && tileentity instanceof ITickable && !this.tileEntityListTick.contains(tileentity)) { // Paper - this.tileEntityListTick.add(tileentity); - } - - if (this.isClientSide) { - BlockPosition blockposition = tileentity.getPosition(); - IBlockData iblockdata = this.getType(blockposition); - - this.notify(blockposition, iblockdata, iblockdata, 2); - } - - return flag; - } - - public void a(Collection collection) { - if (this.tickingTileEntities) { - this.tileEntityListPending.addAll(collection); - } else { - Iterator iterator = collection.iterator(); - - while (iterator.hasNext()) { - TileEntity tileentity = (TileEntity) iterator.next(); - - this.a(tileentity); - } - } - - } - - public void tickBlockEntities() { - GameProfilerFiller gameprofilerfiller = this.getMethodProfiler(); - - gameprofilerfiller.enter("blockEntities"); - timings.tileEntityTick.startTiming(); // Spigot - if (!this.tileEntityListUnload.isEmpty()) { - // Paper start - Use alternate implementation with faster contains - java.util.Set toRemove = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); - toRemove.addAll(tileEntityListUnload); - this.tileEntityListTick.removeAll(toRemove); - // Paper end - //this.tileEntityList.removeAll(this.tileEntityListUnload); // Paper - remove unused list - this.tileEntityListUnload.clear(); - } - - this.tickingTileEntities = true; - // Spigot start - // Iterator iterator = this.tileEntityListTick.iterator(); - int tilesThisCycle = 0; - for (tileTickPosition = 0; tileTickPosition < tileEntityListTick.size(); tileTickPosition++) { // Paper - Disable tick limiters - tileTickPosition = (tileTickPosition < tileEntityListTick.size()) ? tileTickPosition : 0; - TileEntity tileentity = (TileEntity) this.tileEntityListTick.get(tileTickPosition); - // Spigot start - if (tileentity == null) { - getServer().getLogger().severe("Spigot has detected a null entity and has removed it, preventing a crash"); - tilesThisCycle--; - this.tileEntityListTick.remove(tileTickPosition--); - continue; - } - // Spigot end - - if (!tileentity.isRemoved() && tileentity.hasWorld()) { - BlockPosition blockposition = tileentity.getPosition(); - - if (this.chunkProvider.a(blockposition) && this.getWorldBorder().a(blockposition)) { - try { - gameprofilerfiller.a(() -> { - return String.valueOf(TileEntityTypes.a(tileentity.q())); - }); - tileentity.tickTimer.startTiming(); // Spigot - if (tileentity.q().a(this.getType(blockposition).getBlock())) { - ((ITickable) tileentity).tick(); - } else { - tileentity.r(); - } - - gameprofilerfiller.exit(); - } catch (Throwable throwable) { - // Paper start - Prevent tile entity and entity crashes - String msg = "TileEntity threw exception at " + tileentity.world.getWorld().getName() + ":" + tileentity.position.getX() + "," + tileentity.position.getY() + "," + tileentity.position.getZ(); - System.err.println(msg); - throwable.printStackTrace(); - getServer().getPluginManager().callEvent(new ServerExceptionEvent(new ServerInternalException(msg, throwable))); - // Paper end - tilesThisCycle--; - this.tileEntityListTick.remove(tileTickPosition--); - continue; - // Paper end - } - // Spigot start - finally { - tileentity.tickTimer.stopTiming(); - } - // Spigot end - } - } - - if (tileentity.isRemoved()) { - // Spigot start - tilesThisCycle--; - this.tileEntityListTick.remove(tileTickPosition--); - // Spigot end - //this.tileEntityList.remove(tileentity); // Paper - remove unused list - if (this.isLoaded(tileentity.getPosition())) { - this.getChunkAtWorldCoords(tileentity.getPosition()).removeTileEntity(tileentity.getPosition()); - } - } - } - - timings.tileEntityTick.stopTiming(); // Spigot - timings.tileEntityPending.startTiming(); // Spigot - this.tickingTileEntities = false; - gameprofilerfiller.exitEnter("pendingBlockEntities"); - if (!this.tileEntityListPending.isEmpty()) { - for (int i = 0; i < this.tileEntityListPending.size(); ++i) { - TileEntity tileentity1 = (TileEntity) this.tileEntityListPending.get(i); - - if (!tileentity1.isRemoved()) { - /* CraftBukkit start - Order matters, moved down - if (!this.tileEntityList.contains(tileentity1)) { - this.a(tileentity1); - } - // CraftBukkit end */ - - if (this.isLoaded(tileentity1.getPosition())) { - Chunk chunk = this.getChunkAtWorldCoords(tileentity1.getPosition()); - IBlockData iblockdata = chunk.getType(tileentity1.getPosition()); - - chunk.setTileEntity(tileentity1.getPosition(), tileentity1); - this.notify(tileentity1.getPosition(), iblockdata, iblockdata, 3); - // CraftBukkit start - // From above, don't screw this up - SPIGOT-1746 - if (true) { // Paper - remove unused list - this.a(tileentity1); - } - // CraftBukkit end - } - } - } - - this.tileEntityListPending.clear(); - } - - timings.tileEntityPending.stopTiming(); // Spigot - co.aikar.timings.TimingHistory.tileEntityTicks += this.tileEntityListTick.size(); // Paper - gameprofilerfiller.exit(); - spigotConfig.currentPrimedTnt = 0; // Spigot - } - - public void a(Consumer consumer, Entity entity) { - try { - consumer.accept(entity); - } catch (Throwable throwable) { - // Paper start - Prevent tile entity and entity crashes - String msg = "Entity threw exception at " + entity.world.getWorld().getName() + ":" + entity.locX + "," + entity.locY + "," + entity.locZ; - System.err.println(msg); - throwable.printStackTrace(); - getServer().getPluginManager().callEvent(new ServerExceptionEvent(new ServerInternalException(msg, throwable))); - entity.dead = true; - return; - // Paper end - } - } - - // Paper start - Prevent armor stands from doing entity lookups - @Override - public boolean getCubes(@Nullable Entity entity, AxisAlignedBB axisAlignedBB) { - if (entity instanceof EntityArmorStand && !entity.world.paperConfig.armorStandEntityLookups) return false; - return GeneratorAccess.super.getCubes(entity, axisAlignedBB); - } - // Paper end - - public boolean a(AxisAlignedBB axisalignedbb) { - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.f(axisalignedbb.maxX); - int k = MathHelper.floor(axisalignedbb.minY); - int l = MathHelper.f(axisalignedbb.maxY); - int i1 = MathHelper.floor(axisalignedbb.minZ); - int j1 = MathHelper.f(axisalignedbb.maxZ); - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - 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(blockposition_pooledblockposition.d(k1, l1, i2)); - - if (!iblockdata.isAir()) { - boolean flag = true; - - return flag; - } - } - } - } - - return false; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - } - - public boolean b(AxisAlignedBB axisalignedbb) { - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.f(axisalignedbb.maxX); - int k = MathHelper.floor(axisalignedbb.minY); - int l = MathHelper.f(axisalignedbb.maxY); - int i1 = MathHelper.floor(axisalignedbb.minZ); - int j1 = MathHelper.f(axisalignedbb.maxZ); - - if (this.isAreaLoaded(i, k, i1, j, l, j1)) { - BlockPosition.PooledBlockPosition blockposition_pooledblockposition = BlockPosition.PooledBlockPosition.r(); - Throwable throwable = null; - - try { - 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(blockposition_pooledblockposition.d(k1, l1, i2)).getBlock(); - - if (block == Blocks.FIRE || block == Blocks.LAVA) { - boolean flag = true; - - return flag; - } - } - } - } - - return false; - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (blockposition_pooledblockposition != null) { - if (throwable != null) { - try { - blockposition_pooledblockposition.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - blockposition_pooledblockposition.close(); - } - } - - } - } else { - return false; - } - } - - public boolean a(AxisAlignedBB axisalignedbb, Material material) { - int i = MathHelper.floor(axisalignedbb.minX); - int j = MathHelper.f(axisalignedbb.maxX); - int k = MathHelper.floor(axisalignedbb.minY); - int l = MathHelper.f(axisalignedbb.maxY); - int i1 = MathHelper.floor(axisalignedbb.minZ); - int j1 = MathHelper.f(axisalignedbb.maxZ); - MaterialPredicate materialpredicate = MaterialPredicate.a(material); - - return BlockPosition.a(i, k, i1, j - 1, l - 1, j1 - 1).anyMatch((blockposition) -> { - return materialpredicate.test(this.getType(blockposition)); - }); - } - - public Explosion explode(@Nullable Entity entity, double d0, double d1, double d2, float f, Explosion.Effect explosion_effect) { - return this.createExplosion(entity, (DamageSource) null, d0, d1, d2, f, false, explosion_effect); - } - - public Explosion createExplosion(@Nullable Entity entity, double d0, double d1, double d2, float f, boolean flag, Explosion.Effect explosion_effect) { - return this.createExplosion(entity, (DamageSource) null, d0, d1, d2, f, flag, explosion_effect); - } - - public Explosion createExplosion(@Nullable Entity entity, @Nullable DamageSource damagesource, double d0, double d1, double d2, float f, boolean flag, Explosion.Effect explosion_effect) { - Explosion explosion = new Explosion(this, entity, d0, d1, d2, f, flag, explosion_effect); - - if (damagesource != null) { - explosion.a(damagesource); - } - - explosion.a(); - explosion.a(true); - return explosion; - } - - public boolean douseFire(@Nullable EntityHuman entityhuman, BlockPosition blockposition, EnumDirection enumdirection) { - blockposition = blockposition.shift(enumdirection); - if (this.getType(blockposition).getBlock() == Blocks.FIRE) { - this.a(entityhuman, 1009, blockposition, 0); - this.a(blockposition, false); - return true; - } else { - return false; - } - } - - public Map capturedTileEntities = Maps.newHashMap(); - @Nullable - @Override - public TileEntity getTileEntity(BlockPosition blockposition) { - if (isOutsideWorld(blockposition)) { - return null; - } else if (!this.isClientSide && Thread.currentThread() != this.serverThread) { - return null; - } else { - // CraftBukkit start - TileEntity tileentity = null; // Paper - if (!capturedTileEntities.isEmpty() && (tileentity = capturedTileEntities.get(blockposition)) != null) { // Paper - return tileentity; // Paper - } - // CraftBukkit end - - //TileEntity tileentity = null; // Paper - move up - - if (this.tickingTileEntities) { - tileentity = this.A(blockposition); - } - - if (tileentity == null) { - tileentity = this.getChunkAtWorldCoords(blockposition).a(blockposition, Chunk.EnumTileEntityState.IMMEDIATE); - } - - if (tileentity == null) { - tileentity = this.A(blockposition); - } - - return tileentity; - } - } - - @Nullable - private TileEntity A(BlockPosition blockposition) { - for (int i = 0; i < this.tileEntityListPending.size(); ++i) { - TileEntity tileentity = (TileEntity) this.tileEntityListPending.get(i); - - if (!tileentity.isRemoved() && tileentity.getPosition().equals(blockposition)) { - return tileentity; - } - } - - return null; - } - - public void setTileEntity(BlockPosition blockposition, @Nullable TileEntity tileentity) { - if (!isOutsideWorld(blockposition)) { - if (tileentity != null && !tileentity.isRemoved()) { - // CraftBukkit start - if (captureBlockStates) { - tileentity.setWorld(this); - tileentity.setPosition(blockposition); - capturedTileEntities.put(blockposition, tileentity); - return; - } - // CraftBukkit end - if (this.tickingTileEntities) { - tileentity.setPosition(blockposition); - Iterator iterator = this.tileEntityListPending.iterator(); - - while (iterator.hasNext()) { - TileEntity tileentity1 = (TileEntity) iterator.next(); - - if (tileentity1.getPosition().equals(blockposition)) { - tileentity1.V_(); - iterator.remove(); - } - } - - tileentity.setWorld(this); // Spigot - No null worlds - this.tileEntityListPending.add(tileentity); - } else { - this.getChunkAtWorldCoords(blockposition).setTileEntity(blockposition, tileentity); - this.a(tileentity); - } - } - - } - } - - public void removeTileEntity(BlockPosition blockposition) { - TileEntity tileentity = this.getTileEntity(blockposition); - - if (tileentity != null && this.tickingTileEntities) { - tileentity.V_(); - this.tileEntityListPending.remove(tileentity); - } else { - if (tileentity != null) { - this.tileEntityListPending.remove(tileentity); - //this.tileEntityList.remove(tileentity); // Paper - remove unused list - this.tileEntityListTick.remove(tileentity); - } - - this.getChunkAtWorldCoords(blockposition).removeTileEntity(blockposition); - } - - } - - public boolean n(BlockPosition blockposition) { - return isOutsideWorld(blockposition) ? false : this.isLoaded(blockposition); // Paper - reduce sync loads - } - - public boolean a(BlockPosition blockposition, Entity entity) { - if (isOutsideWorld(blockposition)) { - return false; - } else { - IChunkAccess ichunkaccess = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4); // Paper - reduce sync loads - - return ichunkaccess == null ? false : ichunkaccess.getType(blockposition).a((IBlockAccess) this, blockposition, entity); - } - } - - public void M() { - double d0 = 1.0D - (double) (this.h(1.0F) * 5.0F) / 16.0D; - double d1 = 1.0D - (double) (this.f(1.0F) * 5.0F) / 16.0D; - double d2 = 0.5D + 2.0D * MathHelper.a((double) MathHelper.cos(this.j(1.0F) * 6.2831855F), -0.25D, 0.25D); - - this.u = (int) ((1.0D - d2 * d0 * d1) * 11.0D); - } - - public void setSpawnFlags(boolean flag, boolean flag1) { - this.getChunkProvider().a(flag, flag1); - } - - protected void N() { - if (this.worldData.hasStorm()) { - this.rainLevel = 1.0F; - if (this.worldData.isThundering()) { - this.thunderLevel = 1.0F; - } - } - - } - - public void close() throws IOException { - this.chunkProvider.close(); - } - - @Override - public ChunkStatus O() { - return ChunkStatus.FULL; - } - - @Override - public List getEntities(@Nullable Entity entity, AxisAlignedBB axisalignedbb, @Nullable Predicate predicate) { - List list = Lists.newArrayList(); - int i = MathHelper.floor((axisalignedbb.minX - 2.0D) / 16.0D); - int j = MathHelper.floor((axisalignedbb.maxX + 2.0D) / 16.0D); - int k = MathHelper.floor((axisalignedbb.minZ - 2.0D) / 16.0D); - int l = MathHelper.floor((axisalignedbb.maxZ + 2.0D) / 16.0D); - - for (int i1 = i; i1 <= j; ++i1) { - for (int j1 = k; j1 <= l; ++j1) { - Chunk chunk = (Chunk)this.getChunkIfLoadedImmediately(i1, j1); // Paper - - if (chunk != null) { - chunk.a(entity, axisalignedbb, list, predicate); - } - } - } - - return list; - } - - public List a(@Nullable EntityTypes entitytypes, AxisAlignedBB axisalignedbb, Predicate predicate) { - int i = MathHelper.floor((axisalignedbb.minX - 2.0D) / 16.0D); - int j = MathHelper.f((axisalignedbb.maxX + 2.0D) / 16.0D); - int k = MathHelper.floor((axisalignedbb.minZ - 2.0D) / 16.0D); - int l = MathHelper.f((axisalignedbb.maxZ + 2.0D) / 16.0D); - List list = Lists.newArrayList(); - - for (int i1 = i; i1 < j; ++i1) { - for (int j1 = k; j1 < l; ++j1) { - Chunk chunk = (Chunk)this.getChunkIfLoadedImmediately(i1, j1); // Paper - - if (chunk != null) { - chunk.a(entitytypes, axisalignedbb, list, predicate); - } - } - } - - return list; - } - - @Override - public List a(Class oclass, AxisAlignedBB axisalignedbb, @Nullable Predicate predicate) { - int i = MathHelper.floor((axisalignedbb.minX - 2.0D) / 16.0D); - int j = MathHelper.f((axisalignedbb.maxX + 2.0D) / 16.0D); - int k = MathHelper.floor((axisalignedbb.minZ - 2.0D) / 16.0D); - int l = MathHelper.f((axisalignedbb.maxZ + 2.0D) / 16.0D); - List list = Lists.newArrayList(); - IChunkProvider ichunkprovider = this.getChunkProvider(); - - for (int i1 = i; i1 < j; ++i1) { - for (int j1 = k; j1 < l; ++j1) { - Chunk chunk = (Chunk)this.getChunkIfLoadedImmediately(i1, j1); // Paper - - if (chunk != null) { - chunk.a(oclass, axisalignedbb, list, predicate); - } - } - } - - return list; - } - - @Override - public List b(Class oclass, AxisAlignedBB axisalignedbb, @Nullable Predicate predicate) { - int i = MathHelper.floor((axisalignedbb.minX - 2.0D) / 16.0D); - int j = MathHelper.f((axisalignedbb.maxX + 2.0D) / 16.0D); - int k = MathHelper.floor((axisalignedbb.minZ - 2.0D) / 16.0D); - int l = MathHelper.f((axisalignedbb.maxZ + 2.0D) / 16.0D); - List list = Lists.newArrayList(); - IChunkProvider ichunkprovider = this.getChunkProvider(); - - for (int i1 = i; i1 < j; ++i1) { - for (int j1 = k; j1 < l; ++j1) { - Chunk chunk = ichunkprovider.a(i1, j1); - - if (chunk != null) { - chunk.a(oclass, axisalignedbb, list, predicate); - } - } - } - - return list; - } - - @Nullable - public abstract Entity getEntity(int i); - - public void b(BlockPosition blockposition, TileEntity tileentity) { - if (this.isLoaded(blockposition)) { - this.getChunkAtWorldCoords(blockposition).markDirty(); - } - - } - - @Override - public int getSeaLevel() { - return 63; - } - - @Override - public World getMinecraftWorld() { - return this; - } - - public WorldType P() { - return this.worldData.getType(); - } - - public int getBlockPower(BlockPosition blockposition) { - byte b0 = 0; - int i = Math.max(b0, this.c(blockposition.down(), EnumDirection.DOWN)); - - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.c(blockposition.up(), EnumDirection.UP)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.c(blockposition.north(), EnumDirection.NORTH)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.c(blockposition.south(), EnumDirection.SOUTH)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.c(blockposition.west(), EnumDirection.WEST)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.c(blockposition.east(), EnumDirection.EAST)); - return i >= 15 ? i : i; - } - } - } - } - } - } - - public boolean isBlockFacePowered(BlockPosition blockposition, EnumDirection enumdirection) { - return this.getBlockFacePower(blockposition, enumdirection) > 0; - } - - public int getBlockFacePower(BlockPosition blockposition, EnumDirection enumdirection) { - IBlockData iblockdata = this.getType(blockposition); - - return iblockdata.isOccluding(this, blockposition) ? this.getBlockPower(blockposition) : iblockdata.b((IBlockAccess) this, blockposition, enumdirection); - } - - public boolean isBlockIndirectlyPowered(BlockPosition blockposition) { - return this.getBlockFacePower(blockposition.down(), EnumDirection.DOWN) > 0 ? true : (this.getBlockFacePower(blockposition.up(), EnumDirection.UP) > 0 ? true : (this.getBlockFacePower(blockposition.north(), EnumDirection.NORTH) > 0 ? true : (this.getBlockFacePower(blockposition.south(), EnumDirection.SOUTH) > 0 ? true : (this.getBlockFacePower(blockposition.west(), EnumDirection.WEST) > 0 ? true : this.getBlockFacePower(blockposition.east(), EnumDirection.EAST) > 0)))); - } - - public int isBlockIndirectlyGettingPowered(BlockPosition pos) { return this.q(pos); } // Paper - OBFHELPER - public int q(BlockPosition blockposition) { - int i = 0; - EnumDirection[] aenumdirection = World.a; - int j = aenumdirection.length; - - for (int k = 0; k < j; ++k) { - EnumDirection enumdirection = aenumdirection[k]; - int l = this.getBlockFacePower(blockposition.shift(enumdirection), enumdirection); - - if (l >= 15) { - return 15; - } - - if (l > i) { - i = l; - } - } - - return i; - } - - public void a(long i) { - this.worldData.setTime(i); - } - - @Override - 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); - } - - protected void a() { - this.a(this.worldData.getTime() + 1L); - if (this.worldData.v().getBoolean(GameRules.DO_DAYLIGHT_CYCLE)) { - this.setDayTime(this.worldData.getDayTime() + 1L); - } - - } - - public BlockPosition getSpawn() { - BlockPosition blockposition = new BlockPosition(this.worldData.b(), this.worldData.c(), this.worldData.d()); - - if (!this.getWorldBorder().a(blockposition)) { - blockposition = this.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, new BlockPosition(this.getWorldBorder().getCenterX(), 0.0D, this.getWorldBorder().getCenterZ())); - } - - return blockposition; - } - - public void a_(BlockPosition blockposition) { - this.worldData.setSpawn(blockposition); - } - - public boolean a(EntityHuman entityhuman, BlockPosition blockposition) { - return true; - } - - public void broadcastEntityEffect(Entity entity, byte b0) {} - - @Override - public IChunkProvider getChunkProvider() { - return this.chunkProvider; - } - - public void playBlockAction(BlockPosition blockposition, Block block, int i, int j) { - this.getType(blockposition).a(this, blockposition, i, j); - } - - @Override - public WorldData getWorldData() { - return this.worldData; - } - - public GameRules getGameRules() { - return this.worldData.v(); - } - - public float f(float f) { - return MathHelper.g(f, this.lastThunderLevel, this.thunderLevel) * this.h(f); - } - - public float h(float f) { - return MathHelper.g(f, this.lastRainLevel, this.rainLevel); - } - - public boolean U() { - return this.worldProvider.g() && !this.worldProvider.h() ? (double) this.f(1.0F) > 0.9D : false; - } - - public boolean isRaining() { - return (double) this.h(1.0F) > 0.2D; - } - - public boolean isRainingAt(BlockPosition blockposition) { - return !this.isRaining() ? false : (!this.f(blockposition) ? false : (this.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, blockposition).getY() > blockposition.getY() ? false : this.getBiome(blockposition).b() == BiomeBase.Precipitation.RAIN)); - } - - public boolean s(BlockPosition blockposition) { - BiomeBase biomebase = this.getBiome(blockposition); - - return biomebase.c(); - } - - @Nullable - public abstract WorldMap a(String s); - - public abstract void a(WorldMap worldmap); - - public abstract int getWorldMapCount(); - - public void b(int i, BlockPosition blockposition, int j) {} - - public int getHeight() { - return this.worldProvider.h() ? 128 : 256; - } - - public CrashReportSystemDetails a(CrashReport crashreport) { - CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Affected level", 1); - - crashreportsystemdetails.a("All players", () -> { - return this.getPlayers().size() + " total; " + this.getPlayers(); - }); - IChunkProvider ichunkprovider = this.chunkProvider; - - this.chunkProvider.getClass(); - crashreportsystemdetails.a("Chunk stats", ichunkprovider::getName); - crashreportsystemdetails.a("Level dimension", () -> { - return this.worldProvider.getDimensionManager().toString(); - }); - - try { - this.worldData.a(crashreportsystemdetails); - } catch (Throwable throwable) { - crashreportsystemdetails.a("Level Data Unobtainable", throwable); - } - - return crashreportsystemdetails; - } - - public abstract void a(int i, BlockPosition blockposition, int j); - - public abstract Scoreboard getScoreboard(); - - public void updateAdjacentComparators(BlockPosition blockposition, Block block) { - Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); - - while (iterator.hasNext()) { - EnumDirection enumdirection = (EnumDirection) iterator.next(); - BlockPosition blockposition1 = blockposition.shift(enumdirection); - - if (this.isLoaded(blockposition1)) { - IBlockData iblockdata = this.getType(blockposition1); - - if (iblockdata.getBlock() == Blocks.COMPARATOR) { - iblockdata.doPhysics(this, blockposition1, block, blockposition, false); - } else if (iblockdata.isOccluding(this, blockposition1)) { - blockposition1 = blockposition1.shift(enumdirection); - iblockdata = this.getType(blockposition1); - if (iblockdata.getBlock() == Blocks.COMPARATOR) { - iblockdata.doPhysics(this, blockposition1, block, blockposition, false); - } - } - } - } - - } - - @Override - public DifficultyDamageScaler getDamageScaler(BlockPosition blockposition) { - long i = 0L; - float f = 0.0F; - - if (this.isLoaded(blockposition)) { - f = this.aa(); - i = this.getChunkAtWorldCoords(blockposition).q(); - } - - return new DifficultyDamageScaler(this.getDifficulty(), this.getDayTime(), i, f); - } - - @Override - public int c() { - return this.u; - } - - public void c(int i) { - this.v = i; - } - - @Override - public WorldBorder getWorldBorder() { - return this.worldBorder; - } - - public void a(Packet packet) { - throw new UnsupportedOperationException("Can't send packets to server unless you're on the client."); - } - - @Nullable - public BlockPosition a(String s, BlockPosition blockposition, int i, boolean flag) { - return null; - } - - @Override - public WorldProvider getWorldProvider() { - return this.worldProvider; - } - - @Override - public Random getRandom() { - return this.random; - } - - @Override - public boolean a(BlockPosition blockposition, Predicate predicate) { - return predicate.test(this.getType(blockposition)); - } - - public abstract CraftingManager getCraftingManager(); - - public abstract TagRegistry t(); - - public BlockPosition a(int i, int j, int k, int l) { - this.i = this.i * 3 + 1013904223; - int i1 = this.i >> 2; - - return new BlockPosition(i + (i1 & 15), j + (i1 >> 16 & l), k + (i1 >> 8 & 15)); - } - - public boolean isSavingDisabled() { - return false; - } - - public GameProfilerFiller getMethodProfiler() { - return this.methodProfiler; - } - - @Override - public BlockPosition getHighestBlockYAt(HeightMap.Type heightmap_type, BlockPosition blockposition) { - return new BlockPosition(blockposition.getX(), this.a(heightmap_type, blockposition.getX(), blockposition.getZ()), blockposition.getZ()); - } -} diff --git a/src/main/java/net/minecraft/server/WorldBorder.java b/src/main/java/net/minecraft/server/WorldBorder.java deleted file mode 100644 index 890258137..000000000 --- a/src/main/java/net/minecraft/server/WorldBorder.java +++ /dev/null @@ -1,424 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import java.util.Iterator; -import java.util.List; - -public class WorldBorder { - - private final List a = Lists.newArrayList(); - private double b = 0.2D; - private double c = 5.0D; - private int d = 15; - private int e = 5; - private double f; - private double g; - private int h = 29999984; - private WorldBorder.a i = new WorldBorder.c(6.0E7D); - public WorldServer world; // CraftBukkit - - public WorldBorder() {} - - public final boolean isInBounds(BlockPosition blockposition) { return this.a(blockposition); } // Paper - OBFHELPER - public boolean a(BlockPosition blockposition) { - return (double) (blockposition.getX() + 1) > this.c() && (double) blockposition.getX() < this.e() && (double) (blockposition.getZ() + 1) > this.d() && (double) blockposition.getZ() < this.f(); - } - - // Paper start - private final BlockPosition.MutableBlockPosition mutPos = new BlockPosition.MutableBlockPosition(); - public boolean isBlockInBounds(int chunkX, int chunkZ) { - this.mutPos.setValues(chunkX, 64, chunkZ); - return this.isInBounds(this.mutPos); - } - public boolean isChunkInBounds(int chunkX, int chunkZ) { - this.mutPos.setValues(((chunkX << 4) + 15), 64, (chunkZ << 4) + 15); - return this.isInBounds(this.mutPos); - } - // Paper end - - public boolean isInBounds(ChunkCoordIntPair chunkcoordintpair) { - return (double) chunkcoordintpair.f() > this.c() && (double) chunkcoordintpair.d() < this.e() && (double) chunkcoordintpair.g() > this.d() && (double) chunkcoordintpair.e() < this.f(); - } - - public boolean a(AxisAlignedBB axisalignedbb) { - return axisalignedbb.maxX > this.c() && axisalignedbb.minX < this.e() && axisalignedbb.maxZ > this.d() && axisalignedbb.minZ < this.f(); - } - - public double a(Entity entity) { - return this.b(entity.locX, entity.locZ); - } - - public VoxelShape a() { - return this.i.m(); - } - - public double b(double d0, double d1) { - double d2 = d1 - this.d(); - double d3 = this.f() - d1; - double d4 = d0 - this.c(); - double d5 = this.e() - d0; - double d6 = Math.min(d4, d5); - - d6 = Math.min(d6, d2); - return Math.min(d6, d3); - } - - public double c() { - return this.i.a(); - } - - public double d() { - return this.i.c(); - } - - public double e() { - return this.i.b(); - } - - public double f() { - return this.i.d(); - } - - public double getCenterX() { - return this.f; - } - - public double getCenterZ() { - return this.g; - } - - public void setCenter(double d0, double d1) { - this.f = d0; - this.g = d1; - this.i.k(); - Iterator iterator = this.l().iterator(); - - while (iterator.hasNext()) { - IWorldBorderListener iworldborderlistener = (IWorldBorderListener) iterator.next(); - - iworldborderlistener.a(this, d0, d1); - } - - } - - public double getSize() { - return this.i.e(); - } - - public long j() { - return this.i.g(); - } - - public double k() { - return this.i.h(); - } - - public void setSize(double d0) { - this.i = new WorldBorder.c(d0); - Iterator iterator = this.l().iterator(); - - while (iterator.hasNext()) { - IWorldBorderListener iworldborderlistener = (IWorldBorderListener) iterator.next(); - - iworldborderlistener.a(this, d0); - } - - } - - public void transitionSizeBetween(double d0, double d1, long i) { - this.i = (WorldBorder.a) (d0 == d1 ? new WorldBorder.c(d1) : new WorldBorder.b(d0, d1, i)); - Iterator iterator = this.l().iterator(); - - while (iterator.hasNext()) { - IWorldBorderListener iworldborderlistener = (IWorldBorderListener) iterator.next(); - - iworldborderlistener.a(this, d0, d1, i); - } - - } - - protected List l() { - 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; - this.i.j(); - } - - public int m() { - return this.h; - } - - public double getDamageBuffer() { - return this.c; - } - - public void setDamageBuffer(double d0) { - this.c = d0; - Iterator iterator = this.l().iterator(); - - while (iterator.hasNext()) { - IWorldBorderListener iworldborderlistener = (IWorldBorderListener) iterator.next(); - - iworldborderlistener.c(this, d0); - } - - } - - public double getDamageAmount() { - return this.b; - } - - public void setDamageAmount(double d0) { - this.b = d0; - Iterator iterator = this.l().iterator(); - - while (iterator.hasNext()) { - IWorldBorderListener iworldborderlistener = (IWorldBorderListener) iterator.next(); - - iworldborderlistener.b(this, d0); - } - - } - - public int getWarningTime() { - return this.d; - } - - public void setWarningTime(int i) { - this.d = i; - Iterator iterator = this.l().iterator(); - - while (iterator.hasNext()) { - IWorldBorderListener iworldborderlistener = (IWorldBorderListener) iterator.next(); - - iworldborderlistener.a(this, i); - } - - } - - public int getWarningDistance() { - return this.e; - } - - public void setWarningDistance(int i) { - this.e = i; - Iterator iterator = this.l().iterator(); - - while (iterator.hasNext()) { - IWorldBorderListener iworldborderlistener = (IWorldBorderListener) iterator.next(); - - iworldborderlistener.b(this, i); - } - - } - - public void s() { - this.i = this.i.l(); - } - - public void a(WorldData worlddata) { - worlddata.a(this.getSize()); - worlddata.d(this.getCenterX()); - worlddata.c(this.getCenterZ()); - worlddata.e(this.getDamageBuffer()); - worlddata.f(this.getDamageAmount()); - worlddata.h(this.getWarningDistance()); - worlddata.i(this.getWarningTime()); - worlddata.b(this.k()); - worlddata.c(this.j()); - } - - public void b(WorldData worlddata) { - this.setCenter(worlddata.B(), worlddata.C()); - this.setDamageAmount(worlddata.H()); - this.setDamageBuffer(worlddata.G()); - this.setWarningDistance(worlddata.I()); - this.setWarningTime(worlddata.J()); - if (worlddata.E() > 0L) { - this.transitionSizeBetween(worlddata.D(), worlddata.F(), worlddata.E()); - } else { - this.setSize(worlddata.D()); - } - - } - - class c implements WorldBorder.a { - - private final double b; - private double c; - private double d; - private double e; - private double f; - private VoxelShape g; - - public c(double d0) { - this.b = d0; - this.n(); - } - - @Override - public double a() { - return this.c; - } - - @Override - public double b() { - return this.e; - } - - @Override - public double c() { - return this.d; - } - - @Override - public double d() { - return this.f; - } - - @Override - public double e() { - return this.b; - } - - @Override - public long g() { - return 0L; - } - - @Override - public double h() { - return this.b; - } - - private void n() { - this.c = Math.max(WorldBorder.this.getCenterX() - this.b / 2.0D, (double) (-WorldBorder.this.h)); - this.d = Math.max(WorldBorder.this.getCenterZ() - this.b / 2.0D, (double) (-WorldBorder.this.h)); - this.e = Math.min(WorldBorder.this.getCenterX() + this.b / 2.0D, (double) WorldBorder.this.h); - this.f = Math.min(WorldBorder.this.getCenterZ() + this.b / 2.0D, (double) WorldBorder.this.h); - this.g = VoxelShapes.a(VoxelShapes.a, VoxelShapes.create(Math.floor(this.a()), Double.NEGATIVE_INFINITY, Math.floor(this.c()), Math.ceil(this.b()), Double.POSITIVE_INFINITY, Math.ceil(this.d())), OperatorBoolean.ONLY_FIRST); - } - - @Override - public void j() { - this.n(); - } - - @Override - public void k() { - this.n(); - } - - @Override - public WorldBorder.a l() { - return this; - } - - @Override - public VoxelShape m() { - return this.g; - } - } - - class b implements WorldBorder.a { - - private final double b; - private final double c; - private final long d; - private final long e; - private final double f; - - private b(double d0, double d1, long i) { - this.b = d0; - this.c = d1; - this.f = (double) i; - this.e = SystemUtils.getMonotonicMillis(); - this.d = this.e + i; - } - - @Override - public double a() { - return Math.max(WorldBorder.this.getCenterX() - this.e() / 2.0D, (double) (-WorldBorder.this.h)); - } - - @Override - public double c() { - return Math.max(WorldBorder.this.getCenterZ() - this.e() / 2.0D, (double) (-WorldBorder.this.h)); - } - - @Override - public double b() { - return Math.min(WorldBorder.this.getCenterX() + this.e() / 2.0D, (double) WorldBorder.this.h); - } - - @Override - public double d() { - return Math.min(WorldBorder.this.getCenterZ() + this.e() / 2.0D, (double) WorldBorder.this.h); - } - - @Override - public double e() { - double d0 = (double) (SystemUtils.getMonotonicMillis() - this.e) / this.f; - - return d0 < 1.0D ? MathHelper.d(d0, this.b, this.c) : this.c; - } - - @Override - public long g() { - return this.d - SystemUtils.getMonotonicMillis(); - } - - @Override - public double h() { - return this.c; - } - - @Override - public void k() {} - - @Override - public void j() {} - - @Override - public WorldBorder.a l() { - return (WorldBorder.a) (this.g() <= 0L ? WorldBorder.this.new c(this.c) : this); - } - - @Override - public VoxelShape m() { - return VoxelShapes.a(VoxelShapes.a, VoxelShapes.create(Math.floor(this.a()), Double.NEGATIVE_INFINITY, Math.floor(this.c()), Math.ceil(this.b()), Double.POSITIVE_INFINITY, Math.ceil(this.d())), OperatorBoolean.ONLY_FIRST); - } - } - - interface a { - - double a(); - - double b(); - - double c(); - - double d(); - - double e(); - - long g(); - - double h(); - - void j(); - - void k(); - - WorldBorder.a l(); - - VoxelShape m(); - } -} diff --git a/src/main/java/net/minecraft/server/WorldData.java b/src/main/java/net/minecraft/server/WorldData.java deleted file mode 100644 index ca4c31458..000000000 --- a/src/main/java/net/minecraft/server/WorldData.java +++ /dev/null @@ -1,827 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.mojang.datafixers.DataFixer; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.types.JsonOps; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.Map.Entry; -import javax.annotation.Nullable; -// CraftBukkit start -import org.bukkit.Bukkit; -import org.bukkit.event.weather.ThunderChangeEvent; -import org.bukkit.event.weather.WeatherChangeEvent; -// CraftBukkit end - -public class WorldData { - - private String b; - private int c; - private boolean d; - public static final EnumDifficulty a = EnumDifficulty.NORMAL; - private long e; - private WorldType f; - private NBTTagCompound g; - @Nullable - private String h; - private int i; - private int j; - private int k; - private long l; - private long m; - private long n; - private long o; - @Nullable - private final DataFixer p; - private final int q; - private boolean r; - private NBTTagCompound s; - private String levelName; - private int u; - private int clearWeatherTime; - private boolean raining; - private int rainTime; - private boolean thundering; - private int thunderTime; - private EnumGamemode A; - private boolean B; - private boolean C; - private boolean D; - private boolean E; - private EnumDifficulty F; - private boolean G; - private double H; - private double I; - private double J; - private long K; - private double L; - private double M; - private double N; - private int O; - private int P; - private final Set Q; - private final Set R; - private final Map S; - private NBTTagCompound T; - private int U; - private int V; - private UUID W; - private final GameRules X; - private final CustomFunctionCallbackTimerQueue Y; - public WorldServer world; // CraftBukkit - - protected WorldData() { - this.f = WorldType.NORMAL; - this.g = new NBTTagCompound(); - this.J = 6.0E7D; - this.M = 5.0D; - this.N = 0.2D; - this.O = 5; - this.P = 15; - this.Q = Sets.newHashSet(); - this.R = Sets.newLinkedHashSet(); - this.S = Maps.newIdentityHashMap(); - this.X = new GameRules(); - this.Y = new CustomFunctionCallbackTimerQueue<>(CustomFunctionCallbackTimers.a); - this.p = null; - this.q = SharedConstants.a().getWorldVersion(); - this.b(new NBTTagCompound()); - } - - public WorldData(NBTTagCompound nbttagcompound, DataFixer datafixer, int i, @Nullable NBTTagCompound nbttagcompound1) { - this.f = WorldType.NORMAL; - this.g = new NBTTagCompound(); - this.J = 6.0E7D; - this.M = 5.0D; - this.N = 0.2D; - this.O = 5; - this.P = 15; - this.Q = Sets.newHashSet(); - this.R = Sets.newLinkedHashSet(); - this.S = Maps.newIdentityHashMap(); - this.X = new GameRules(); - this.Y = new CustomFunctionCallbackTimerQueue<>(CustomFunctionCallbackTimers.a); - this.p = datafixer; - NBTTagCompound nbttagcompound2; - - if (nbttagcompound.hasKeyOfType("Version", 10)) { - nbttagcompound2 = nbttagcompound.getCompound("Version"); - this.b = nbttagcompound2.getString("Name"); - this.c = nbttagcompound2.getInt("Id"); - this.d = nbttagcompound2.getBoolean("Snapshot"); - } - - this.e = com.destroystokyo.paper.PaperConfig.seedOverride.getOrDefault(nbttagcompound.getString("LevelName"), nbttagcompound.getLong("RandomSeed")); // Paper - if (nbttagcompound.hasKeyOfType("generatorName", 8)) { - String s = nbttagcompound.getString("generatorName"); - - this.f = WorldType.getType(s); - if (this.f == null) { - this.f = WorldType.NORMAL; - } else if (this.f == WorldType.CUSTOMIZED) { - this.h = nbttagcompound.getString("generatorOptions"); - } else if (this.f.h()) { - int j = 0; - - if (nbttagcompound.hasKeyOfType("generatorVersion", 99)) { - j = nbttagcompound.getInt("generatorVersion"); - } - - this.f = this.f.a(j); - } - - this.b(nbttagcompound.getCompound("generatorOptions")); - } - - this.A = EnumGamemode.getById(nbttagcompound.getInt("GameType")); - if (nbttagcompound.hasKeyOfType("legacy_custom_options", 8)) { - this.h = nbttagcompound.getString("legacy_custom_options"); - } - - if (nbttagcompound.hasKeyOfType("MapFeatures", 99)) { - this.B = nbttagcompound.getBoolean("MapFeatures"); - } else { - this.B = true; - } - - this.i = nbttagcompound.getInt("SpawnX"); - this.j = nbttagcompound.getInt("SpawnY"); - this.k = nbttagcompound.getInt("SpawnZ"); - this.l = nbttagcompound.getLong("Time"); - if (nbttagcompound.hasKeyOfType("DayTime", 99)) { - this.m = nbttagcompound.getLong("DayTime"); - } else { - this.m = this.l; - } - - this.n = nbttagcompound.getLong("LastPlayed"); - this.o = nbttagcompound.getLong("SizeOnDisk"); - this.levelName = nbttagcompound.getString("LevelName"); - this.u = nbttagcompound.getInt("version"); - this.clearWeatherTime = nbttagcompound.getInt("clearWeatherTime"); - this.rainTime = nbttagcompound.getInt("rainTime"); - this.raining = nbttagcompound.getBoolean("raining"); - this.thunderTime = nbttagcompound.getInt("thunderTime"); - this.thundering = nbttagcompound.getBoolean("thundering"); - this.C = nbttagcompound.getBoolean("hardcore"); - if (nbttagcompound.hasKeyOfType("initialized", 99)) { - this.E = nbttagcompound.getBoolean("initialized"); - } else { - this.E = true; - } - - if (nbttagcompound.hasKeyOfType("allowCommands", 99)) { - this.D = nbttagcompound.getBoolean("allowCommands"); - } else { - this.D = this.A == EnumGamemode.CREATIVE; - } - - this.q = i; - if (nbttagcompound1 != null) { - this.s = nbttagcompound1; - } - - if (nbttagcompound.hasKeyOfType("GameRules", 10)) { - this.X.a(nbttagcompound.getCompound("GameRules")); - } - - if (nbttagcompound.hasKeyOfType("Difficulty", 99)) { - this.F = EnumDifficulty.getById(nbttagcompound.getByte("Difficulty")); - } - - if (nbttagcompound.hasKeyOfType("DifficultyLocked", 1)) { - this.G = nbttagcompound.getBoolean("DifficultyLocked"); - } - - if (nbttagcompound.hasKeyOfType("BorderCenterX", 99)) { - this.H = nbttagcompound.getDouble("BorderCenterX"); - } - - if (nbttagcompound.hasKeyOfType("BorderCenterZ", 99)) { - this.I = nbttagcompound.getDouble("BorderCenterZ"); - } - - if (nbttagcompound.hasKeyOfType("BorderSize", 99)) { - this.J = nbttagcompound.getDouble("BorderSize"); - } - - if (nbttagcompound.hasKeyOfType("BorderSizeLerpTime", 99)) { - this.K = nbttagcompound.getLong("BorderSizeLerpTime"); - } - - if (nbttagcompound.hasKeyOfType("BorderSizeLerpTarget", 99)) { - this.L = nbttagcompound.getDouble("BorderSizeLerpTarget"); - } - - if (nbttagcompound.hasKeyOfType("BorderSafeZone", 99)) { - this.M = nbttagcompound.getDouble("BorderSafeZone"); - } - - if (nbttagcompound.hasKeyOfType("BorderDamagePerBlock", 99)) { - this.N = nbttagcompound.getDouble("BorderDamagePerBlock"); - } - - if (nbttagcompound.hasKeyOfType("BorderWarningBlocks", 99)) { - this.O = nbttagcompound.getInt("BorderWarningBlocks"); - } - - if (nbttagcompound.hasKeyOfType("BorderWarningTime", 99)) { - this.P = nbttagcompound.getInt("BorderWarningTime"); - } - - if (nbttagcompound.hasKeyOfType("DimensionData", 10)) { - nbttagcompound2 = nbttagcompound.getCompound("DimensionData"); - Iterator iterator = nbttagcompound2.getKeys().iterator(); - - while (iterator.hasNext()) { - String s1 = (String) iterator.next(); - - this.S.put(DimensionManager.a(Integer.parseInt(s1)), nbttagcompound2.getCompound(s1)); - } - } - - if (nbttagcompound.hasKeyOfType("DataPacks", 10)) { - nbttagcompound2 = nbttagcompound.getCompound("DataPacks"); - NBTTagList nbttaglist = nbttagcompound2.getList("Disabled", 8); - - for (int k = 0; k < nbttaglist.size(); ++k) { - this.Q.add(nbttaglist.getString(k)); - } - - NBTTagList nbttaglist1 = nbttagcompound2.getList("Enabled", 8); - - for (int l = 0; l < nbttaglist1.size(); ++l) { - this.R.add(nbttaglist1.getString(l)); - } - } - - if (nbttagcompound.hasKeyOfType("CustomBossEvents", 10)) { - this.T = nbttagcompound.getCompound("CustomBossEvents"); - } - - if (nbttagcompound.hasKeyOfType("ScheduledEvents", 9)) { - this.Y.a(nbttagcompound.getList("ScheduledEvents", 10)); - } - - if (nbttagcompound.hasKeyOfType("WanderingTraderSpawnDelay", 99)) { - this.U = nbttagcompound.getInt("WanderingTraderSpawnDelay"); - } - - if (nbttagcompound.hasKeyOfType("WanderingTraderSpawnChance", 99)) { - this.V = nbttagcompound.getInt("WanderingTraderSpawnChance"); - } - - if (nbttagcompound.hasKeyOfType("WanderingTraderId", 8)) { - this.W = UUID.fromString(nbttagcompound.getString("WanderingTraderId")); - } - - } - - public WorldData(WorldSettings worldsettings, String s) { - this.f = WorldType.NORMAL; - this.g = new NBTTagCompound(); - this.J = 6.0E7D; - this.M = 5.0D; - this.N = 0.2D; - this.O = 5; - this.P = 15; - this.Q = Sets.newHashSet(); - this.R = Sets.newLinkedHashSet(); - this.S = Maps.newIdentityHashMap(); - this.X = new GameRules(); - this.Y = new CustomFunctionCallbackTimerQueue<>(CustomFunctionCallbackTimers.a); - this.p = null; - this.q = SharedConstants.a().getWorldVersion(); - this.a(worldsettings); - this.levelName = s; - this.F = WorldData.a; - this.E = false; - } - - public void a(WorldSettings worldsettings) { - this.e = worldsettings.d(); - this.A = worldsettings.e(); - this.B = worldsettings.g(); - this.C = worldsettings.f(); - this.f = worldsettings.h(); - this.b((NBTTagCompound) Dynamic.convert(JsonOps.INSTANCE, DynamicOpsNBT.a, worldsettings.j())); - this.D = worldsettings.i(); - } - - public NBTTagCompound a(@Nullable NBTTagCompound nbttagcompound) { - this.T(); - if (nbttagcompound == null) { - nbttagcompound = this.s; - } - - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - - this.a(nbttagcompound1, nbttagcompound); - return nbttagcompound1; - } - - private void a(NBTTagCompound nbttagcompound, NBTTagCompound nbttagcompound1) { - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - - nbttagcompound2.setString("Name", SharedConstants.a().getName()); - nbttagcompound2.setInt("Id", SharedConstants.a().getWorldVersion()); - nbttagcompound2.setBoolean("Snapshot", !SharedConstants.a().isStable()); - nbttagcompound.set("Version", nbttagcompound2); - nbttagcompound.setInt("DataVersion", SharedConstants.a().getWorldVersion()); - nbttagcompound.setLong("RandomSeed", this.e); - nbttagcompound.setString("generatorName", this.f.b()); - nbttagcompound.setInt("generatorVersion", this.f.getVersion()); - if (!this.g.isEmpty()) { - nbttagcompound.set("generatorOptions", this.g); - } - - if (this.h != null) { - nbttagcompound.setString("legacy_custom_options", this.h); - } - - nbttagcompound.setInt("GameType", this.A.getId()); - nbttagcompound.setBoolean("MapFeatures", this.B); - nbttagcompound.setInt("SpawnX", this.i); - nbttagcompound.setInt("SpawnY", this.j); - nbttagcompound.setInt("SpawnZ", this.k); - nbttagcompound.setLong("Time", this.l); - nbttagcompound.setLong("DayTime", this.m); - nbttagcompound.setLong("SizeOnDisk", this.o); - nbttagcompound.setLong("LastPlayed", SystemUtils.getTimeMillis()); - nbttagcompound.setString("LevelName", this.levelName); - nbttagcompound.setInt("version", this.u); - nbttagcompound.setInt("clearWeatherTime", this.clearWeatherTime); - nbttagcompound.setInt("rainTime", this.rainTime); - nbttagcompound.setBoolean("raining", this.raining); - nbttagcompound.setInt("thunderTime", this.thunderTime); - nbttagcompound.setBoolean("thundering", this.thundering); - nbttagcompound.setBoolean("hardcore", this.C); - nbttagcompound.setBoolean("allowCommands", this.D); - nbttagcompound.setBoolean("initialized", this.E); - nbttagcompound.setDouble("BorderCenterX", this.H); - nbttagcompound.setDouble("BorderCenterZ", this.I); - nbttagcompound.setDouble("BorderSize", this.J); - nbttagcompound.setLong("BorderSizeLerpTime", this.K); - nbttagcompound.setDouble("BorderSafeZone", this.M); - nbttagcompound.setDouble("BorderDamagePerBlock", this.N); - nbttagcompound.setDouble("BorderSizeLerpTarget", this.L); - nbttagcompound.setDouble("BorderWarningBlocks", (double) this.O); - nbttagcompound.setDouble("BorderWarningTime", (double) this.P); - if (this.F != null) { - nbttagcompound.setByte("Difficulty", (byte) this.F.a()); - } - - nbttagcompound.setBoolean("DifficultyLocked", this.G); - nbttagcompound.set("GameRules", this.X.a()); - NBTTagCompound nbttagcompound3 = new NBTTagCompound(); - Iterator iterator = this.S.entrySet().iterator(); - - while (iterator.hasNext()) { - Entry entry = (Entry) iterator.next(); - - nbttagcompound3.set(String.valueOf(((DimensionManager) entry.getKey()).getDimensionID()), (NBTBase) entry.getValue()); - } - - nbttagcompound.set("DimensionData", nbttagcompound3); - if (nbttagcompound1 != null) { - nbttagcompound.set("Player", nbttagcompound1); - } - - NBTTagCompound nbttagcompound4 = new NBTTagCompound(); - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator1 = this.R.iterator(); - - while (iterator1.hasNext()) { - String s = (String) iterator1.next(); - - nbttaglist.add(new NBTTagString(s)); - } - - nbttagcompound4.set("Enabled", nbttaglist); - NBTTagList nbttaglist1 = new NBTTagList(); - Iterator iterator2 = this.Q.iterator(); - - while (iterator2.hasNext()) { - String s1 = (String) iterator2.next(); - - nbttaglist1.add(new NBTTagString(s1)); - } - - nbttagcompound4.set("Disabled", nbttaglist1); - nbttagcompound.set("DataPacks", nbttagcompound4); - if (this.T != null) { - nbttagcompound.set("CustomBossEvents", this.T); - } - - nbttagcompound.set("ScheduledEvents", this.Y.b()); - nbttagcompound.setInt("WanderingTraderSpawnDelay", this.U); - nbttagcompound.setInt("WanderingTraderSpawnChance", this.V); - if (this.W != null) { - nbttagcompound.setString("WanderingTraderId", this.W.toString()); - } - - nbttagcompound.setString("Bukkit.Version", Bukkit.getName() + "/" + Bukkit.getVersion() + "/" + Bukkit.getBukkitVersion()); // CraftBukkit - } - - public long getSeed() { - return this.e; - } - - public int b() { - return this.i; - } - - public int c() { - return this.j; - } - - public int d() { - return this.k; - } - - public long getTime() { - return this.l; - } - - public long getDayTime() { - return this.m; - } - - private void T() { - if (!this.r && this.s != null) { - if (this.q < SharedConstants.a().getWorldVersion()) { - if (this.p == null) { - throw new NullPointerException("Fixer Upper not set inside LevelData, and the player tag is not upgraded."); - } - - this.s = GameProfileSerializer.a(this.p, DataFixTypes.PLAYER, this.s, this.q); - } - - this.r = true; - } - } - - public NBTTagCompound h() { - this.T(); - return this.s; - } - - public void setTime(long i) { - this.l = i; - } - - public void setDayTime(long i) { - this.m = i; - } - - public void setSpawn(BlockPosition blockposition) { - this.i = blockposition.getX(); - this.j = blockposition.getY(); - this.k = blockposition.getZ(); - } - - public String getName() { - return this.levelName; - } - - public void setName(String s) { - this.levelName = s; - } - - public int j() { - return this.u; - } - - public void d(int i) { - this.u = i; - } - - public int z() { - return this.clearWeatherTime; - } - - public void g(int i) { - this.clearWeatherTime = i; - } - - public boolean isThundering() { - return this.thundering; - } - - public void setThundering(boolean flag) { - // CraftBukkit start - if (this.thundering == flag) { - return; - } - - 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; - } - } - // CraftBukkit end - this.thundering = flag; - } - - public int getThunderDuration() { - return this.thunderTime; - } - - public void setThunderDuration(int i) { - this.thunderTime = i; - } - - public boolean hasStorm() { - return this.raining; - } - - public void setStorm(boolean flag) { - // CraftBukkit start - if (this.raining == flag) { - return; - } - - 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; - } - } - // CraftBukkit end - this.raining = flag; - } - - public int getWeatherDuration() { - return this.rainTime; - } - - public void setWeatherDuration(int i) { - this.rainTime = i; - } - - public EnumGamemode getGameType() { - return this.A; - } - - public boolean shouldGenerateMapFeatures() { - return this.B; - } - - public void f(boolean flag) { - this.B = flag; - } - - public void setGameType(EnumGamemode enumgamemode) { - this.A = enumgamemode; - } - - public boolean isHardcore() { - return this.C; - } - - public void g(boolean flag) { - this.C = flag; - } - - public WorldType getType() { - return this.f; - } - - public void a(WorldType worldtype) { - this.f = worldtype; - } - - public NBTTagCompound getGeneratorOptions() { - return this.g; - } - - public void b(NBTTagCompound nbttagcompound) { - this.g = nbttagcompound; - } - - public boolean t() { - return this.D; - } - - public void c(boolean flag) { - this.D = flag; - } - - public boolean u() { - return this.E; - } - - public void d(boolean flag) { - this.E = flag; - } - - public GameRules v() { - return this.X; - } - - public double B() { - return this.H; - } - - public double C() { - return this.I; - } - - public double D() { - return this.J; - } - - public void a(double d0) { - this.J = d0; - } - - public long E() { - return this.K; - } - - public void c(long i) { - this.K = i; - } - - public double F() { - return this.L; - } - - public void b(double d0) { - this.L = d0; - } - - public void c(double d0) { - this.I = d0; - } - - public void d(double d0) { - this.H = d0; - } - - public double G() { - return this.M; - } - - public void e(double d0) { - this.M = d0; - } - - public double H() { - return this.N; - } - - public void f(double d0) { - this.N = d0; - } - - public int I() { - return this.O; - } - - public int J() { - return this.P; - } - - public void h(int i) { - this.O = i; - } - - public void i(int i) { - this.P = i; - } - - public EnumDifficulty getDifficulty() { - return this.F; - } - - public void setDifficulty(EnumDifficulty enumdifficulty) { - this.F = enumdifficulty; - // CraftBukkit start - PacketPlayOutServerDifficulty packet = new PacketPlayOutServerDifficulty(this.getDifficulty(), this.isDifficultyLocked()); - for (EntityPlayer player : (java.util.List) (java.util.List) world.getPlayers()) { - player.playerConnection.sendPacket(packet); - } - // CraftBukkit end - } - - public boolean isDifficultyLocked() { - return this.G; - } - - public void e(boolean flag) { - this.G = flag; - } - - public CustomFunctionCallbackTimerQueue y() { - return this.Y; - } - - public void a(CrashReportSystemDetails crashreportsystemdetails) { - crashreportsystemdetails.a("Level name", () -> { - return this.levelName; - }); - crashreportsystemdetails.a("Level seed", () -> { - return String.valueOf(this.e); - }); - crashreportsystemdetails.a("Level generator", () -> { - return String.format("ID %02d - %s, ver %d. Features enabled: %b", this.f.i(), this.f.name(), this.f.getVersion(), this.B); - }); - crashreportsystemdetails.a("Level generator options", () -> { - return this.g.toString(); - }); - crashreportsystemdetails.a("Level spawn location", () -> { - return CrashReportSystemDetails.a(this.i, this.j, this.k); - }); - crashreportsystemdetails.a("Level time", () -> { - return String.format("%d game time, %d day time", this.l, this.m); - }); - crashreportsystemdetails.a("Level storage version", () -> { - String s = "Unknown?"; - - try { - switch (this.u) { - case 19132: - s = "McRegion"; - break; - case 19133: - s = "Anvil"; - } - } catch (Throwable throwable) { - ; - } - - return String.format("0x%05X - %s", this.u, s); - }); - crashreportsystemdetails.a("Level weather", () -> { - return String.format("Rain time: %d (now: %b), thunder time: %d (now: %b)", this.rainTime, this.raining, this.thunderTime, this.thundering); - }); - crashreportsystemdetails.a("Level game mode", () -> { - return String.format("Game mode: %s (ID %d). Hardcore: %b. Cheats: %b", this.A.b(), this.A.getId(), this.C, this.D); - }); - } - - public NBTTagCompound a(DimensionManager dimensionmanager) { - NBTTagCompound nbttagcompound = (NBTTagCompound) this.S.get(dimensionmanager); - - return nbttagcompound == null ? new NBTTagCompound() : nbttagcompound; - } - - public void a(DimensionManager dimensionmanager, NBTTagCompound nbttagcompound) { - this.S.put(dimensionmanager, nbttagcompound); - } - - public Set N() { - return this.Q; - } - - public Set O() { - return this.R; - } - - @Nullable - public NBTTagCompound getCustomBossEvents() { - return this.T; - } - - public void c(@Nullable NBTTagCompound nbttagcompound) { - this.T = nbttagcompound; - } - - public int Q() { - return this.U; - } - - public void j(int i) { - this.U = i; - } - - public int R() { - return this.V; - } - - public void k(int i) { - this.V = i; - } - - public void a(UUID uuid) { - this.W = uuid; - } - - // CraftBukkit start - Check if the name stored in NBT is the correct one - public void checkName( String name ) { - if ( !this.levelName.equals( name ) ) { - this.levelName = name; - } - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/WorldGenFeatureDesertPyramid.java b/src/main/java/net/minecraft/server/WorldGenFeatureDesertPyramid.java deleted file mode 100644 index c54484631..000000000 --- a/src/main/java/net/minecraft/server/WorldGenFeatureDesertPyramid.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.function.Function; - -public class WorldGenFeatureDesertPyramid extends WorldGenFeatureRandomScattered { - - public WorldGenFeatureDesertPyramid(Function, ? extends WorldGenFeatureEmptyConfiguration> function) { - super(function); - } - - @Override - public String b() { - return "Desert_Pyramid"; - } - - @Override - public int c() { - return 3; - } - - @Override - public StructureGenerator.a a() { - return WorldGenFeatureDesertPyramid.a::new; - } - - @Override - // Spigot start - protected int getSeed(World world) { - return world.spigotConfig.desertSeed; - // Spigot end - } - - public static class a extends StructureStart { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - WorldGenDesertPyramidPiece worldgendesertpyramidpiece = new WorldGenDesertPyramidPiece(this.d, i * 16, j * 16); - - this.b.add(worldgendesertpyramidpiece); - this.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenFeatureIgloo.java b/src/main/java/net/minecraft/server/WorldGenFeatureIgloo.java deleted file mode 100644 index 6f8a97942..000000000 --- a/src/main/java/net/minecraft/server/WorldGenFeatureIgloo.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.function.Function; - -public class WorldGenFeatureIgloo extends WorldGenFeatureRandomScattered { - - public WorldGenFeatureIgloo(Function, ? extends WorldGenFeatureEmptyConfiguration> function) { - super(function); - } - - @Override - public String b() { - return "Igloo"; - } - - @Override - public int c() { - return 3; - } - - @Override - public StructureGenerator.a a() { - return WorldGenFeatureIgloo.a::new; - } - - @Override - // Spigot start - protected int getSeed(World world) { - return world.spigotConfig.iglooSeed; - // Spigot end - } - - public static class a extends StructureStart { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - WorldGenFeatureEmptyConfiguration worldgenfeatureemptyconfiguration = (WorldGenFeatureEmptyConfiguration) chunkgenerator.getFeatureConfiguration(biomebase, WorldGenerator.IGLOO); - int k = i * 16; - int l = j * 16; - BlockPosition blockposition = new BlockPosition(k, 90, l); - EnumBlockRotation enumblockrotation = EnumBlockRotation.values()[this.d.nextInt(EnumBlockRotation.values().length)]; - - WorldGenIglooPiece.a(definedstructuremanager, blockposition, enumblockrotation, this.b, this.d, worldgenfeatureemptyconfiguration); - this.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenFeatureJunglePyramid.java b/src/main/java/net/minecraft/server/WorldGenFeatureJunglePyramid.java deleted file mode 100644 index ca6b1ee8a..000000000 --- a/src/main/java/net/minecraft/server/WorldGenFeatureJunglePyramid.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.function.Function; - -public class WorldGenFeatureJunglePyramid extends WorldGenFeatureRandomScattered { - - public WorldGenFeatureJunglePyramid(Function, ? extends WorldGenFeatureEmptyConfiguration> function) { - super(function); - } - - @Override - public String b() { - return "Jungle_Pyramid"; - } - - @Override - public int c() { - return 3; - } - - @Override - public StructureGenerator.a a() { - return WorldGenFeatureJunglePyramid.a::new; - } - - @Override - // Spigot start - protected int getSeed(World world) { - return world.spigotConfig.jungleSeed; - // Spigot end - } - - public static class a extends StructureStart { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - WorldGenJunglePyramidPiece worldgenjunglepyramidpiece = new WorldGenJunglePyramidPiece(this.d, i * 16, j * 16); - - this.b.add(worldgenjunglepyramidpiece); - this.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenFeatureOceanRuin.java b/src/main/java/net/minecraft/server/WorldGenFeatureOceanRuin.java deleted file mode 100644 index 7d553ee46..000000000 --- a/src/main/java/net/minecraft/server/WorldGenFeatureOceanRuin.java +++ /dev/null @@ -1,88 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.Arrays; -import java.util.Map; -import java.util.Random; -import java.util.function.Function; -import java.util.stream.Collectors; - -public class WorldGenFeatureOceanRuin extends WorldGenFeatureRandomScattered { - - public WorldGenFeatureOceanRuin(Function, ? extends WorldGenFeatureOceanRuinConfiguration> function) { - super(function); - } - - @Override - public String b() { - return "Ocean_Ruin"; - } - - @Override - public int c() { - return 3; - } - - @Override - protected int a(ChunkGenerator chunkgenerator) { - return chunkgenerator.getSettings().l(); - } - - @Override - protected int b(ChunkGenerator chunkgenerator) { - return chunkgenerator.getSettings().m(); - } - - @Override - public StructureGenerator.a a() { - return WorldGenFeatureOceanRuin.a::new; - } - - @Override - // Spigot start - protected int getSeed(World world) { - return world.spigotConfig.oceanSeed; - // Spigot end - } - - public static enum Temperature { - - WARM("warm"), COLD("cold"); - - private static final Map c = (Map) Arrays.stream(values()).collect(Collectors.toMap(WorldGenFeatureOceanRuin.Temperature::a, (worldgenfeatureoceanruin_temperature) -> { - return worldgenfeatureoceanruin_temperature; - })); - private final String d; - - private Temperature(String s) { - this.d = s; - } - - public String a() { - return this.d; - } - - public static WorldGenFeatureOceanRuin.Temperature a(String s) { - return (WorldGenFeatureOceanRuin.Temperature) WorldGenFeatureOceanRuin.Temperature.c.get(s); - } - } - - public static class a extends StructureStart { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - WorldGenFeatureOceanRuinConfiguration worldgenfeatureoceanruinconfiguration = (WorldGenFeatureOceanRuinConfiguration) chunkgenerator.getFeatureConfiguration(biomebase, WorldGenerator.OCEAN_RUIN); - int k = i * 16; - int l = j * 16; - BlockPosition blockposition = new BlockPosition(k, 90, l); - EnumBlockRotation enumblockrotation = EnumBlockRotation.values()[this.d.nextInt(EnumBlockRotation.values().length)]; - - WorldGenFeatureOceanRuinPieces.a(definedstructuremanager, blockposition, enumblockrotation, this.b, (Random) this.d, worldgenfeatureoceanruinconfiguration); - this.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenFeaturePillagerOutpost.java b/src/main/java/net/minecraft/server/WorldGenFeaturePillagerOutpost.java deleted file mode 100644 index 5da5605cf..000000000 --- a/src/main/java/net/minecraft/server/WorldGenFeaturePillagerOutpost.java +++ /dev/null @@ -1,90 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.datafixers.Dynamic; -import java.util.List; -import java.util.Random; -import java.util.function.Function; - -public class WorldGenFeaturePillagerOutpost extends WorldGenFeatureRandomScattered { - - private static final List a = Lists.newArrayList(new BiomeBase.BiomeMeta[]{new BiomeBase.BiomeMeta(EntityTypes.PILLAGER, 1, 1, 1)}); - - public WorldGenFeaturePillagerOutpost(Function, ? extends WorldGenFeaturePillagerOutpostConfiguration> function) { - super(function); - } - - @Override - public String b() { - return "Pillager_Outpost"; - } - - @Override - public int c() { - return 3; - } - - @Override - public List e() { - return WorldGenFeaturePillagerOutpost.a; - } - - @Override - public boolean a(ChunkGenerator chunkgenerator, Random random, int i, int j) { - ChunkCoordIntPair chunkcoordintpair = this.a(chunkgenerator, random, i, j, 0, 0); - - if (i == chunkcoordintpair.x && j == chunkcoordintpair.z) { - int k = i >> 4; - int l = j >> 4; - - random.setSeed((long) (k ^ l << 4) ^ chunkgenerator.getSeed()); - random.nextInt(); - if (random.nextInt(5) != 0) { - return false; - } - - BiomeBase biomebase = chunkgenerator.getWorldChunkManager().getBiome(new BlockPosition((i << 4) + 9, 0, (j << 4) + 9)); - - if (chunkgenerator.canSpawnStructure(biomebase, WorldGenerator.PILLAGER_OUTPOST)) { - for (int i1 = i - 10; i1 <= i + 10; ++i1) { - for (int j1 = j - 10; j1 <= j + 10; ++j1) { - if (WorldGenerator.VILLAGE.a(chunkgenerator, random, i1, j1)) { - return false; - } - } - } - - return true; - } - } - - return false; - } - - @Override - public StructureGenerator.a a() { - return WorldGenFeaturePillagerOutpost.a::new; - } - - @Override - // Spigot start - protected int getSeed(World world) { - return world.spigotConfig.outpostSeed; - // Spigot end - } - - public static class a extends StructureAbstract { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - BlockPosition blockposition = new BlockPosition(i * 16, 90, j * 16); - - WorldGenFeaturePillagerOutpostPieces.a(chunkgenerator, definedstructuremanager, blockposition, this.b, this.d); - this.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenFeatureRandomScattered.java b/src/main/java/net/minecraft/server/WorldGenFeatureRandomScattered.java deleted file mode 100644 index 49ae612b1..000000000 --- a/src/main/java/net/minecraft/server/WorldGenFeatureRandomScattered.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.Random; -import java.util.function.Function; - -public abstract class WorldGenFeatureRandomScattered extends StructureGenerator { - - public WorldGenFeatureRandomScattered(Function, ? extends C> function) { - super(function); - } - - @Override - protected ChunkCoordIntPair a(ChunkGenerator chunkgenerator, Random random, int i, int j, int k, int l) { - int i1 = this.a(chunkgenerator); - int j1 = this.b(chunkgenerator); - int k1 = i + i1 * k; - int l1 = j + i1 * l; - int i2 = k1 < 0 ? k1 - i1 + 1 : k1; - int j2 = l1 < 0 ? l1 - i1 + 1 : l1; - int k2 = i2 / i1; - int l2 = j2 / i1; - - ((SeededRandom) random).a(chunkgenerator.getSeed(), k2, l2, this.getSeed(chunkgenerator.getWorld())); // Spigot - k2 *= i1; - l2 *= i1; - k2 += random.nextInt(i1 - j1); - l2 += random.nextInt(i1 - j1); - return new ChunkCoordIntPair(k2, l2); - } - - @Override - public boolean a(ChunkGenerator chunkgenerator, Random random, int i, int j) { - ChunkCoordIntPair chunkcoordintpair = this.a(chunkgenerator, random, i, j, 0, 0); - - if (i == chunkcoordintpair.x && j == chunkcoordintpair.z) { - BiomeBase biomebase = chunkgenerator.getWorldChunkManager().getBiome(new BlockPosition(i * 16 + 9, 0, j * 16 + 9)); - - if (chunkgenerator.canSpawnStructure(biomebase, this)) { - return true; - } - } - - return false; - } - - protected int a(ChunkGenerator chunkgenerator) { - return chunkgenerator.getSettings().h(); - } - - protected int b(ChunkGenerator chunkgenerator) { - return chunkgenerator.getSettings().i(); - } - - protected abstract int getSeed(World world); // Spigot -} diff --git a/src/main/java/net/minecraft/server/WorldGenFeatureShipwreck.java b/src/main/java/net/minecraft/server/WorldGenFeatureShipwreck.java deleted file mode 100644 index 061eb2569..000000000 --- a/src/main/java/net/minecraft/server/WorldGenFeatureShipwreck.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.function.Function; - -public class WorldGenFeatureShipwreck extends WorldGenFeatureRandomScattered { - - public WorldGenFeatureShipwreck(Function, ? extends WorldGenFeatureShipwreckConfiguration> function) { - super(function); - } - - @Override - public String b() { - return "Shipwreck"; - } - - @Override - public int c() { - return 3; - } - - @Override - public StructureGenerator.a a() { - return WorldGenFeatureShipwreck.a::new; - } - - @Override - // Spigot start - protected int getSeed(World world) { - return world.spigotConfig.shipwreckSeed; - // Spigot end - } - - @Override - protected int a(ChunkGenerator chunkgenerator) { - return chunkgenerator.getSettings().j(); - } - - @Override - protected int b(ChunkGenerator chunkgenerator) { - return chunkgenerator.getSettings().k(); - } - - public static class a extends StructureStart { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - WorldGenFeatureShipwreckConfiguration worldgenfeatureshipwreckconfiguration = (WorldGenFeatureShipwreckConfiguration) chunkgenerator.getFeatureConfiguration(biomebase, WorldGenerator.SHIPWRECK); - EnumBlockRotation enumblockrotation = EnumBlockRotation.values()[this.d.nextInt(EnumBlockRotation.values().length)]; - BlockPosition blockposition = new BlockPosition(i * 16, 90, j * 16); - - WorldGenShipwreck.a(definedstructuremanager, blockposition, enumblockrotation, this.b, this.d, worldgenfeatureshipwreckconfiguration); - this.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenFeatureSwampHut.java b/src/main/java/net/minecraft/server/WorldGenFeatureSwampHut.java deleted file mode 100644 index 69f5f3ef6..000000000 --- a/src/main/java/net/minecraft/server/WorldGenFeatureSwampHut.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.datafixers.Dynamic; -import java.util.List; -import java.util.function.Function; - -public class WorldGenFeatureSwampHut extends WorldGenFeatureRandomScattered { - - private static final List a = Lists.newArrayList(new BiomeBase.BiomeMeta[]{new BiomeBase.BiomeMeta(EntityTypes.WITCH, 1, 1, 1)}); - private static final List aS = Lists.newArrayList(new BiomeBase.BiomeMeta[]{new BiomeBase.BiomeMeta(EntityTypes.CAT, 1, 1, 1)}); - - public WorldGenFeatureSwampHut(Function, ? extends WorldGenFeatureEmptyConfiguration> function) { - super(function); - } - - @Override - public String b() { - return "Swamp_Hut"; - } - - @Override - public int c() { - return 3; - } - - @Override - public StructureGenerator.a a() { - return WorldGenFeatureSwampHut.a::new; - } - - @Override - // Spigot start - protected int getSeed(World world) { - return world.spigotConfig.swampSeed; - // Spigot end - } - - @Override - public List e() { - return WorldGenFeatureSwampHut.a; - } - - @Override - public List f() { - return WorldGenFeatureSwampHut.aS; - } - - public boolean c(GeneratorAccess generatoraccess, BlockPosition blockposition) { - StructureStart structurestart = this.a(generatoraccess, blockposition, true); - - if (structurestart != StructureStart.a && structurestart instanceof WorldGenFeatureSwampHut.a && !structurestart.d().isEmpty()) { - StructurePiece structurepiece = (StructurePiece) structurestart.d().get(0); - - return structurepiece instanceof WorldGenWitchHut; - } else { - return false; - } - } - - public static class a extends StructureStart { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - WorldGenWitchHut worldgenwitchhut = new WorldGenWitchHut(this.d, i * 16, j * 16); - - this.b.add(worldgenwitchhut); - this.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenGroundBush.java b/src/main/java/net/minecraft/server/WorldGenGroundBush.java deleted file mode 100644 index fc70a3855..000000000 --- a/src/main/java/net/minecraft/server/WorldGenGroundBush.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.Random; -import java.util.Set; -import java.util.function.Function; - -public class WorldGenGroundBush extends WorldGenTreeAbstract { - - private final IBlockData a; - private final IBlockData aS; - - public WorldGenGroundBush(Function, ? extends WorldGenFeatureEmptyConfiguration> function, IBlockData iblockdata, IBlockData iblockdata1) { - super(function, false); - this.aS = iblockdata; - this.a = iblockdata1; - } - - @Override - public boolean a(Set set, VirtualLevelWritable virtuallevelwritable, Random random, BlockPosition blockposition, StructureBoundingBox structureboundingbox) { - blockposition = virtuallevelwritable.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, blockposition).down(); - if (h(virtuallevelwritable, blockposition)) { - blockposition = blockposition.up(); - this.a(set, (IWorldWriter) virtuallevelwritable, blockposition, this.aS, structureboundingbox); - - 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) { - BlockPosition blockposition1 = new BlockPosition(l, i, j1); - - if (g(virtuallevelwritable, blockposition1)) { - this.a(set, (IWorldWriter) virtuallevelwritable, blockposition1, this.a, structureboundingbox); - } - } - } - } - } - // CraftBukkit start - Return false if gen was unsuccessful - } else { - return false; - } - // CraftBukkit end - - - return true; - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenMegaTreeProvider.java b/src/main/java/net/minecraft/server/WorldGenMegaTreeProvider.java deleted file mode 100644 index ecd54e08f..000000000 --- a/src/main/java/net/minecraft/server/WorldGenMegaTreeProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public abstract class WorldGenMegaTreeProvider extends WorldGenTreeProvider { - - public WorldGenMegaTreeProvider() {} - - @Override - public boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, Random random) { - for (int i = 0; i >= -1; --i) { - for (int j = 0; j >= -1; --j) { - if (a(iblockdata, generatoraccess, blockposition, i, j)) { - return this.a(generatoraccess, blockposition, iblockdata, random, i, j); - } - } - } - - return super.a(generatoraccess, blockposition, iblockdata, random); - } - - @Nullable - protected abstract WorldGenTreeAbstract a(Random random); - - public boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, Random random, int i, int j) { - WorldGenTreeAbstract worldgentreeabstract = this.a(random); - - if (worldgentreeabstract == null) { - return false; - } else { - setTreeType(worldgentreeabstract); // CraftBukkit - IBlockData iblockdata1 = Blocks.AIR.getBlockData(); - - generatoraccess.setTypeAndData(blockposition.b(i, 0, j), iblockdata1, 4); - generatoraccess.setTypeAndData(blockposition.b(i + 1, 0, j), iblockdata1, 4); - generatoraccess.setTypeAndData(blockposition.b(i, 0, j + 1), iblockdata1, 4); - generatoraccess.setTypeAndData(blockposition.b(i + 1, 0, j + 1), iblockdata1, 4); - if (worldgentreeabstract.generate(generatoraccess, generatoraccess.getChunkProvider().getChunkGenerator(), random, blockposition.b(i, 0, j), WorldGenFeatureConfiguration.e)) { - return true; - } else { - generatoraccess.setTypeAndData(blockposition.b(i, 0, j), iblockdata, 4); - generatoraccess.setTypeAndData(blockposition.b(i + 1, 0, j), iblockdata, 4); - generatoraccess.setTypeAndData(blockposition.b(i, 0, j + 1), iblockdata, 4); - generatoraccess.setTypeAndData(blockposition.b(i + 1, 0, j + 1), iblockdata, 4); - return false; - } - } - } - - public static boolean a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, int i, int j) { - Block block = iblockdata.getBlock(); - - return block == iblockaccess.getType(blockposition.b(i, 0, j)).getBlock() && block == iblockaccess.getType(blockposition.b(i + 1, 0, j)).getBlock() && block == iblockaccess.getType(blockposition.b(i, 0, j + 1)).getBlock() && block == iblockaccess.getType(blockposition.b(i + 1, 0, j + 1)).getBlock(); - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenMonument.java b/src/main/java/net/minecraft/server/WorldGenMonument.java deleted file mode 100644 index 0f72e94a0..000000000 --- a/src/main/java/net/minecraft/server/WorldGenMonument.java +++ /dev/null @@ -1,128 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.datafixers.Dynamic; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.function.Function; - -public class WorldGenMonument extends StructureGenerator { - - private static final List a = Lists.newArrayList(new BiomeBase.BiomeMeta[]{new BiomeBase.BiomeMeta(EntityTypes.GUARDIAN, 1, 2, 4)}); - - public WorldGenMonument(Function, ? extends WorldGenFeatureEmptyConfiguration> function) { - super(function); - } - - @Override - protected ChunkCoordIntPair a(ChunkGenerator chunkgenerator, Random random, int i, int j, int k, int l) { - int i1 = chunkgenerator.getSettings().c(); - int j1 = chunkgenerator.getSettings().d(); - int k1 = i + i1 * k; - int l1 = j + i1 * l; - int i2 = k1 < 0 ? k1 - i1 + 1 : k1; - int j2 = l1 < 0 ? l1 - i1 + 1 : l1; - int k2 = i2 / i1; - int l2 = j2 / i1; - - ((SeededRandom) random).a(chunkgenerator.getSeed(), k2, l2, chunkgenerator.getWorld().spigotConfig.monumentSeed); // Spigot - k2 *= i1; - l2 *= i1; - k2 += (random.nextInt(i1 - j1) + random.nextInt(i1 - j1)) / 2; - l2 += (random.nextInt(i1 - j1) + random.nextInt(i1 - j1)) / 2; - return new ChunkCoordIntPair(k2, l2); - } - - @Override - public boolean a(ChunkGenerator chunkgenerator, Random random, int i, int j) { - ChunkCoordIntPair chunkcoordintpair = this.a(chunkgenerator, random, i, j, 0, 0); - - if (i == chunkcoordintpair.x && j == chunkcoordintpair.z) { - Set set = chunkgenerator.getWorldChunkManager().a(i * 16 + 9, j * 16 + 9, 16); - Iterator iterator = set.iterator(); - - BiomeBase biomebase; - - do { - if (!iterator.hasNext()) { - Set set1 = chunkgenerator.getWorldChunkManager().a(i * 16 + 9, j * 16 + 9, 29); - Iterator iterator1 = set1.iterator(); - - BiomeBase biomebase1; - - do { - if (!iterator1.hasNext()) { - return true; - } - - biomebase1 = (BiomeBase) iterator1.next(); - } while (biomebase1.o() == BiomeBase.Geography.OCEAN || biomebase1.o() == BiomeBase.Geography.RIVER); - - return false; - } - - biomebase = (BiomeBase) iterator.next(); - } while (chunkgenerator.canSpawnStructure(biomebase, WorldGenerator.OCEAN_MONUMENT)); - - return false; - } else { - return false; - } - } - - @Override - public StructureGenerator.a a() { - return WorldGenMonument.a::new; - } - - @Override - public String b() { - return "Monument"; - } - - @Override - public int c() { - return 8; - } - - @Override - public List e() { - return WorldGenMonument.a; - } - - public static class a extends StructureStart { - - private boolean e; - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - this.b(i, j); - } - - private void b(int i, int j) { - int k = i * 16 - 29; - int l = j * 16 - 29; - EnumDirection enumdirection = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(this.d); - - this.b.add(new WorldGenMonumentPieces.WorldGenMonumentPiece1(this.d, k, l, enumdirection)); - this.b(); - this.e = true; - } - - @Override - public void a(GeneratorAccess generatoraccess, Random random, StructureBoundingBox structureboundingbox, ChunkCoordIntPair chunkcoordintpair) { - if (!this.e) { - this.b.clear(); - this.b(this.f(), this.g()); - } - - super.a(generatoraccess, random, structureboundingbox, chunkcoordintpair); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenStronghold.java b/src/main/java/net/minecraft/server/WorldGenStronghold.java deleted file mode 100644 index c2188ceef..000000000 --- a/src/main/java/net/minecraft/server/WorldGenStronghold.java +++ /dev/null @@ -1,230 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.mojang.datafixers.Dynamic; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.function.Function; -import javax.annotation.Nullable; - -public class WorldGenStronghold extends StructureGenerator { - - /* // Paper start - no shared state - private boolean a; - private ChunkCoordIntPair[] aS; - private final List aT = Lists.newArrayList(); - private long aU; - */ - - public WorldGenStronghold(Function, ? extends WorldGenFeatureEmptyConfiguration> function) { - super(function); - } - - @Override - public boolean a(ChunkGenerator chunkgenerator, Random random, int i, int j) { - // Paper start - /* - if (this.aU != chunkgenerator.getSeed()) { - this.d(); - } - */ - final World world = chunkgenerator.getWorld(); - - synchronized (world.stuctureLock) { - if ( world.strongholdCoords == null) { - this.a(chunkgenerator); - // this.a = true; - }} - // Paper end - - ChunkCoordIntPair[] achunkcoordintpair = world.strongholdCoords; // Paper - int k = achunkcoordintpair.length; - - for (int l = 0; l < k; ++l) { - ChunkCoordIntPair chunkcoordintpair = achunkcoordintpair[l]; - - if (i == chunkcoordintpair.x && j == chunkcoordintpair.z) { - return true; - } - } - - return false; - } - - private void d() { - /* // Paper - this.a = false; - this.aS = null; - this.aT.clear(); - */ // Paper - } - - @Override - public StructureGenerator.a a() { - return WorldGenStronghold.a::new; - } - - @Override - public String b() { - return "Stronghold"; - } - - @Override - public int c() { - return 8; - } - - - @Nullable - @Override - public synchronized BlockPosition getNearestGeneratedFeature(World world, ChunkGenerator chunkgenerator, BlockPosition blockposition, int i, boolean flag) { // CraftBukkit - synchronized - if (!chunkgenerator.getWorldChunkManager().a(this)) { - return null; - } else { - // Paper start - no shared state - /* - if (this.aU != world.getSeed()) { - this.d(); - } - */ - - synchronized (world.stuctureLock) { - if ( world.strongholdCoords == null) { - this.a(chunkgenerator); - //this.a = true; - } - } - // Paper end - - BlockPosition blockposition1 = null; - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); - double d0 = Double.MAX_VALUE; - ChunkCoordIntPair[] achunkcoordintpair = world.strongholdCoords; // Paper - int j = achunkcoordintpair.length; - - for (int k = 0; k < j; ++k) { - ChunkCoordIntPair chunkcoordintpair = achunkcoordintpair[k]; - - blockposition_mutableblockposition.d((chunkcoordintpair.x << 4) + 8, 32, (chunkcoordintpair.z << 4) + 8); - double d1 = blockposition_mutableblockposition.m(blockposition); - - if (blockposition1 == null) { - blockposition1 = new BlockPosition(blockposition_mutableblockposition); - d0 = d1; - } else if (d1 < d0) { - blockposition1 = new BlockPosition(blockposition_mutableblockposition); - d0 = d1; - } - } - - return blockposition1; - } - } - - private void a(ChunkGenerator chunkgenerator) { - //this.aU = chunkgenerator.getSeed(); // Paper - List list = Lists.newArrayList(); - Iterator iterator = IRegistry.BIOME.iterator(); - - while (iterator.hasNext()) { - BiomeBase biomebase = (BiomeBase) iterator.next(); - - if (biomebase != null && chunkgenerator.canSpawnStructure(biomebase, WorldGenerator.STRONGHOLD)) { - list.add(biomebase); - } - } - - int i = chunkgenerator.getSettings().e(); - int j = chunkgenerator.getSettings().f(); - int k = chunkgenerator.getSettings().g(); - - ChunkCoordIntPair[] strongholdCoords = chunkgenerator.getWorld().strongholdCoords = new ChunkCoordIntPair[j]; // Paper - int l = 0; - Iterator iterator1 = chunkgenerator.getWorld().strongholdStuctures.iterator(); // Paper - - while (iterator1.hasNext()) { - StructureStart structurestart = (StructureStart) iterator1.next(); - - if (l < strongholdCoords.length) { // Paper - strongholdCoords[l++] = new ChunkCoordIntPair(structurestart.f(), structurestart.g()); // Paper - } - } - - Random random = new Random(); - - random.setSeed(chunkgenerator.getSeed()); - double d0 = random.nextDouble() * 3.141592653589793D * 2.0D; - int i1 = l; - - if (l < strongholdCoords.length) { // Paper - int j1 = 0; - int k1 = 0; - - for (int l1 = 0; l1 < strongholdCoords.length; ++l1) { // Paper - double d1 = (double) (4 * i + i * k1 * 6) + (random.nextDouble() - 0.5D) * (double) i * 2.5D; - int i2 = (int) Math.round(Math.cos(d0) * d1); - int j2 = (int) Math.round(Math.sin(d0) * d1); - BlockPosition blockposition = chunkgenerator.getWorldChunkManager().a((i2 << 4) + 8, (j2 << 4) + 8, 112, list, random); - - if (blockposition != null) { - i2 = blockposition.getX() >> 4; - j2 = blockposition.getZ() >> 4; - } - - if (l1 >= i1) { - strongholdCoords[l1] = new ChunkCoordIntPair(i2, j2); // Paper - } - - d0 += 6.283185307179586D / (double) k; - ++j1; - if (j1 == k) { - ++k1; - j1 = 0; - k += 2 * k / (k1 + 1); - k = Math.min(k, strongholdCoords.length - l1); - d0 += random.nextDouble() * 3.141592653589793D * 2.0D; - } - } - } - - } - - public static class a extends StructureStart { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - int k = 0; - long l = chunkgenerator.getSeed(); - - WorldGenStrongholdPieces.WorldGenStrongholdStart worldgenstrongholdpieces_worldgenstrongholdstart; - - do { - this.b.clear(); - this.c = StructureBoundingBox.a(); - this.d.c(l + (long) (k++), i, j); - WorldGenStrongholdPieces.a(); - worldgenstrongholdpieces_worldgenstrongholdstart = new WorldGenStrongholdPieces.WorldGenStrongholdStart(this.d, (i << 4) + 2, (j << 4) + 2); - this.b.add(worldgenstrongholdpieces_worldgenstrongholdstart); - worldgenstrongholdpieces_worldgenstrongholdstart.a((StructurePiece) worldgenstrongholdpieces_worldgenstrongholdstart, this.b, (Random) this.d); - List list = worldgenstrongholdpieces_worldgenstrongholdstart.c; - - while (!list.isEmpty()) { - int i1 = this.d.nextInt(list.size()); - StructurePiece structurepiece = (StructurePiece) list.remove(i1); - - structurepiece.a((StructurePiece) worldgenstrongholdpieces_worldgenstrongholdstart, this.b, (Random) this.d); - } - - this.b(); - this.a(chunkgenerator.getSeaLevel(), this.d, 10); - } while (this.b.isEmpty() || worldgenstrongholdpieces_worldgenstrongholdstart.b == null); - - chunkgenerator.getWorld().strongholdStuctures.add(this); // Paper - this worries me, this is never cleared, even in vanilla (world seed never changes "world", and that appears to be the only relevant world) - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenTreeProvider.java b/src/main/java/net/minecraft/server/WorldGenTreeProvider.java deleted file mode 100644 index b410d80f6..000000000 --- a/src/main/java/net/minecraft/server/WorldGenTreeProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; -import org.bukkit.TreeType; // CraftBukkit - -public abstract class WorldGenTreeProvider { - - public WorldGenTreeProvider() {} - - @Nullable - protected abstract WorldGenTreeAbstract b(Random random); - - public boolean a(GeneratorAccess generatoraccess, BlockPosition blockposition, IBlockData iblockdata, Random random) { - WorldGenTreeAbstract worldgentreeabstract = this.b(random); - - if (worldgentreeabstract == null) { - return false; - } else { - setTreeType(worldgentreeabstract); // CraftBukkit - generatoraccess.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 4); - if (worldgentreeabstract.generate(generatoraccess, generatoraccess.getChunkProvider().getChunkGenerator(), random, blockposition, WorldGenFeatureConfiguration.e)) { - return true; - } else { - generatoraccess.setTypeAndData(blockposition, iblockdata, 4); - return false; - } - } - } - - // CraftBukkit start - protected void setTreeType(WorldGenTreeAbstract worldgentreeabstract) { - if (worldgentreeabstract instanceof WorldGenAcaciaTree) { - BlockSapling.treeType = TreeType.ACACIA; - } else if (worldgentreeabstract instanceof WorldGenBigTree) { - BlockSapling.treeType = TreeType.BIG_TREE; - } else if (worldgentreeabstract instanceof WorldGenForest) { - BlockSapling.treeType = TreeType.BIRCH; - } else if (worldgentreeabstract instanceof WorldGenForestTree) { - BlockSapling.treeType = TreeType.DARK_OAK; - } else if (worldgentreeabstract instanceof WorldGenJungleTree) { - BlockSapling.treeType = TreeType.JUNGLE; - } else if (worldgentreeabstract instanceof WorldGenMegaTree) { - BlockSapling.treeType = TreeType.MEGA_REDWOOD; - } else if (worldgentreeabstract instanceof WorldGenTaiga1) { - BlockSapling.treeType = TreeType.REDWOOD; - } else if (worldgentreeabstract instanceof WorldGenTaiga2) { - BlockSapling.treeType = TreeType.REDWOOD; - } else if (worldgentreeabstract instanceof WorldGenTrees) { - BlockSapling.treeType = TreeType.TREE; - } else { - throw new IllegalArgumentException("Unknown tree generator " + worldgentreeabstract); - } - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/WorldGenVillage.java b/src/main/java/net/minecraft/server/WorldGenVillage.java deleted file mode 100644 index b155a73a0..000000000 --- a/src/main/java/net/minecraft/server/WorldGenVillage.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.Dynamic; -import java.util.Random; -import java.util.function.Function; - -public class WorldGenVillage extends StructureGenerator { - - public WorldGenVillage(Function, ? extends WorldGenFeatureVillageConfiguration> function) { - super(function); - } - - @Override - protected ChunkCoordIntPair a(ChunkGenerator chunkgenerator, Random random, int i, int j, int k, int l) { - int i1 = chunkgenerator.getSettings().a(); - int j1 = chunkgenerator.getSettings().b(); - int k1 = i + i1 * k; - int l1 = j + i1 * l; - int i2 = k1 < 0 ? k1 - i1 + 1 : k1; - int j2 = l1 < 0 ? l1 - i1 + 1 : l1; - int k2 = i2 / i1; - int l2 = j2 / i1; - - ((SeededRandom) random).a(chunkgenerator.getSeed(), k2, l2, chunkgenerator.getWorld().spigotConfig.villageSeed); // Spigot - k2 *= i1; - l2 *= i1; - k2 += random.nextInt(i1 - j1); - l2 += random.nextInt(i1 - j1); - return new ChunkCoordIntPair(k2, l2); - } - - @Override - public boolean a(ChunkGenerator chunkgenerator, Random random, int i, int j) { - ChunkCoordIntPair chunkcoordintpair = this.a(chunkgenerator, random, i, j, 0, 0); - - if (i == chunkcoordintpair.x && j == chunkcoordintpair.z) { - BiomeBase biomebase = chunkgenerator.getWorldChunkManager().getBiome(new BlockPosition((i << 4) + 9, 0, (j << 4) + 9)); - - return chunkgenerator.canSpawnStructure(biomebase, WorldGenerator.VILLAGE); - } else { - return false; - } - } - - @Override - public StructureGenerator.a a() { - return WorldGenVillage.a::new; - } - - @Override - public String b() { - return "Village"; - } - - @Override - public int c() { - return 8; - } - - public static class a extends StructureAbstract { - - public a(StructureGenerator structuregenerator, int i, int j, BiomeBase biomebase, StructureBoundingBox structureboundingbox, int k, long l) { - super(structuregenerator, i, j, biomebase, structureboundingbox, k, l); - } - - @Override - public void a(ChunkGenerator chunkgenerator, DefinedStructureManager definedstructuremanager, int i, int j, BiomeBase biomebase) { - WorldGenFeatureVillageConfiguration worldgenfeaturevillageconfiguration = (WorldGenFeatureVillageConfiguration) chunkgenerator.getFeatureConfiguration(biomebase, WorldGenerator.VILLAGE); - BlockPosition blockposition = new BlockPosition(i * 16, 0, j * 16); - - NewVillagePieces.a(chunkgenerator, definedstructuremanager, blockposition, this.b, this.d, worldgenfeaturevillageconfiguration); - this.b(); - } - } -} diff --git a/src/main/java/net/minecraft/server/WorldGenWitchHut.java b/src/main/java/net/minecraft/server/WorldGenWitchHut.java deleted file mode 100644 index e39228cc8..000000000 --- a/src/main/java/net/minecraft/server/WorldGenWitchHut.java +++ /dev/null @@ -1,115 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; - -public class WorldGenWitchHut extends WorldGenScatteredPiece { - - private boolean e; - private boolean f; - - public WorldGenWitchHut(Random random, int i, int j) { - super(WorldGenFeatureStructurePieceType.L, random, i, 64, j, 7, 7, 9); - } - - public WorldGenWitchHut(DefinedStructureManager definedstructuremanager, NBTTagCompound nbttagcompound) { - super(WorldGenFeatureStructurePieceType.L, nbttagcompound); - this.e = nbttagcompound.getBoolean("Witch"); - this.f = nbttagcompound.getBoolean("Cat"); - } - - @Override - protected void a(NBTTagCompound nbttagcompound) { - super.a(nbttagcompound); - nbttagcompound.setBoolean("Witch", this.e); - nbttagcompound.setBoolean("Cat", this.f); - } - - @Override - public boolean a(GeneratorAccess generatoraccess, Random random, StructureBoundingBox structureboundingbox, ChunkCoordIntPair chunkcoordintpair) { - if (!this.a(generatoraccess, structureboundingbox, 0)) { - return false; - } else { - this.a(generatoraccess, structureboundingbox, 1, 1, 1, 5, 1, 7, Blocks.SPRUCE_PLANKS.getBlockData(), Blocks.SPRUCE_PLANKS.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 1, 4, 2, 5, 4, 7, Blocks.SPRUCE_PLANKS.getBlockData(), Blocks.SPRUCE_PLANKS.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 2, 1, 0, 4, 1, 0, Blocks.SPRUCE_PLANKS.getBlockData(), Blocks.SPRUCE_PLANKS.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 2, 2, 2, 3, 3, 2, Blocks.SPRUCE_PLANKS.getBlockData(), Blocks.SPRUCE_PLANKS.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 1, 2, 3, 1, 3, 6, Blocks.SPRUCE_PLANKS.getBlockData(), Blocks.SPRUCE_PLANKS.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 5, 2, 3, 5, 3, 6, Blocks.SPRUCE_PLANKS.getBlockData(), Blocks.SPRUCE_PLANKS.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 2, 2, 7, 4, 3, 7, Blocks.SPRUCE_PLANKS.getBlockData(), Blocks.SPRUCE_PLANKS.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 1, 0, 2, 1, 3, 2, Blocks.OAK_LOG.getBlockData(), Blocks.OAK_LOG.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 5, 0, 2, 5, 3, 2, Blocks.OAK_LOG.getBlockData(), Blocks.OAK_LOG.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 1, 0, 7, 1, 3, 7, Blocks.OAK_LOG.getBlockData(), Blocks.OAK_LOG.getBlockData(), false); - this.a(generatoraccess, structureboundingbox, 5, 0, 7, 5, 3, 7, Blocks.OAK_LOG.getBlockData(), Blocks.OAK_LOG.getBlockData(), false); - this.a(generatoraccess, Blocks.OAK_FENCE.getBlockData(), 2, 3, 2, structureboundingbox); - this.a(generatoraccess, Blocks.OAK_FENCE.getBlockData(), 3, 3, 7, structureboundingbox); - this.a(generatoraccess, Blocks.AIR.getBlockData(), 1, 3, 4, structureboundingbox); - this.a(generatoraccess, Blocks.AIR.getBlockData(), 5, 3, 4, structureboundingbox); - this.a(generatoraccess, Blocks.AIR.getBlockData(), 5, 3, 5, structureboundingbox); - this.a(generatoraccess, Blocks.POTTED_RED_MUSHROOM.getBlockData(), 1, 3, 5, structureboundingbox); - this.a(generatoraccess, Blocks.CRAFTING_TABLE.getBlockData(), 3, 2, 6, structureboundingbox); - this.a(generatoraccess, Blocks.CAULDRON.getBlockData(), 4, 2, 6, structureboundingbox); - this.a(generatoraccess, Blocks.OAK_FENCE.getBlockData(), 1, 2, 1, structureboundingbox); - this.a(generatoraccess, Blocks.OAK_FENCE.getBlockData(), 5, 2, 1, structureboundingbox); - IBlockData iblockdata = (IBlockData) Blocks.SPRUCE_STAIRS.getBlockData().set(BlockStairs.FACING, EnumDirection.NORTH); - IBlockData iblockdata1 = (IBlockData) Blocks.SPRUCE_STAIRS.getBlockData().set(BlockStairs.FACING, EnumDirection.EAST); - IBlockData iblockdata2 = (IBlockData) Blocks.SPRUCE_STAIRS.getBlockData().set(BlockStairs.FACING, EnumDirection.WEST); - IBlockData iblockdata3 = (IBlockData) Blocks.SPRUCE_STAIRS.getBlockData().set(BlockStairs.FACING, EnumDirection.SOUTH); - - this.a(generatoraccess, structureboundingbox, 0, 4, 1, 6, 4, 1, iblockdata, iblockdata, false); - this.a(generatoraccess, structureboundingbox, 0, 4, 2, 0, 4, 7, iblockdata1, iblockdata1, false); - this.a(generatoraccess, structureboundingbox, 6, 4, 2, 6, 4, 7, iblockdata2, iblockdata2, false); - this.a(generatoraccess, structureboundingbox, 0, 4, 8, 6, 4, 8, iblockdata3, iblockdata3, false); - this.a(generatoraccess, (IBlockData) iblockdata.set(BlockStairs.SHAPE, BlockPropertyStairsShape.OUTER_RIGHT), 0, 4, 1, structureboundingbox); - this.a(generatoraccess, (IBlockData) iblockdata.set(BlockStairs.SHAPE, BlockPropertyStairsShape.OUTER_LEFT), 6, 4, 1, structureboundingbox); - this.a(generatoraccess, (IBlockData) iblockdata3.set(BlockStairs.SHAPE, BlockPropertyStairsShape.OUTER_LEFT), 0, 4, 8, structureboundingbox); - this.a(generatoraccess, (IBlockData) iblockdata3.set(BlockStairs.SHAPE, BlockPropertyStairsShape.OUTER_RIGHT), 6, 4, 8, structureboundingbox); - - int i; - int j; - - for (j = 2; j <= 7; j += 5) { - for (i = 1; i <= 5; i += 4) { - this.b(generatoraccess, Blocks.OAK_LOG.getBlockData(), i, -1, j, structureboundingbox); - } - } - - if (!this.e) { - j = this.a(2, 5); - i = this.d(2); - int k = this.b(2, 5); - - if (structureboundingbox.b((BaseBlockPosition) (new BlockPosition(j, i, k)))) { - this.e = true; - EntityWitch entitywitch = (EntityWitch) EntityTypes.WITCH.a(generatoraccess.getMinecraftWorld()); - - entitywitch.setPersistent(); - entitywitch.setPositionRotation((double) j + 0.5D, (double) i, (double) k + 0.5D, 0.0F, 0.0F); - entitywitch.prepare(generatoraccess, generatoraccess.getDamageScaler(new BlockPosition(j, i, k)), EnumMobSpawn.STRUCTURE, (GroupDataEntity) null, (NBTTagCompound) null); - generatoraccess.addEntity(entitywitch, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.CHUNK_GEN); // CraftBukkit - add SpawnReason - } - } - - this.a(generatoraccess, structureboundingbox); - return true; - } - } - - private void a(GeneratorAccess generatoraccess, StructureBoundingBox structureboundingbox) { - if (!this.f) { - int i = this.a(2, 5); - int j = this.d(2); - int k = this.b(2, 5); - - if (structureboundingbox.b((BaseBlockPosition) (new BlockPosition(i, j, k)))) { - this.f = true; - EntityCat entitycat = (EntityCat) EntityTypes.CAT.a(generatoraccess.getMinecraftWorld()); - - entitycat.setPersistent(); - entitycat.setPositionRotation((double) i + 0.5D, (double) j, (double) k + 0.5D, 0.0F, 0.0F); - entitycat.prepare(generatoraccess, generatoraccess.getDamageScaler(new BlockPosition(i, j, k)), EnumMobSpawn.STRUCTURE, (GroupDataEntity) null, (NBTTagCompound) null); - generatoraccess.addEntity(entitycat); - } - } - - } -} diff --git a/src/main/java/net/minecraft/server/WorldLoadListener.java b/src/main/java/net/minecraft/server/WorldLoadListener.java deleted file mode 100644 index 7b6f5b2da..000000000 --- a/src/main/java/net/minecraft/server/WorldLoadListener.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public interface WorldLoadListener { - - void a(ChunkCoordIntPair chunkcoordintpair); - - void a(ChunkCoordIntPair chunkcoordintpair, @Nullable ChunkStatus chunkstatus); - - void b(); - - void setChunkRadius(int radius); // Paper - allow changing chunk radius -} diff --git a/src/main/java/net/minecraft/server/WorldLoadListenerLogger.java b/src/main/java/net/minecraft/server/WorldLoadListenerLogger.java deleted file mode 100644 index ae77805f7..000000000 --- a/src/main/java/net/minecraft/server/WorldLoadListenerLogger.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class WorldLoadListenerLogger implements WorldLoadListener { - - private static final Logger LOGGER = LogManager.getLogger(); - private int b; // Paper - remove final - private int c; - private long d; - private long e = Long.MAX_VALUE; - - public WorldLoadListenerLogger(int i) { - // Paper start - Allow changing radius later for configurable spawn patch - this.setChunkRadius(i); // Move to method - } - - @Override - public void setChunkRadius(int radius) { - // Paper - copied from above - int j = radius * 2 + 1; - - this.b = j * j; - } - // Paper end - - @Override - public void a(ChunkCoordIntPair chunkcoordintpair) { - this.e = SystemUtils.getMonotonicMillis(); - this.d = this.e; - } - - @Override - public void a(ChunkCoordIntPair chunkcoordintpair, @Nullable ChunkStatus chunkstatus) { - if (chunkstatus == ChunkStatus.FULL) { - ++this.c; - } - - int i = this.c(); - - if (SystemUtils.getMonotonicMillis() > this.e) { - this.e += 500L; - WorldLoadListenerLogger.LOGGER.info((new ChatMessage("menu.preparingSpawn", new Object[]{MathHelper.clamp(i, 0, 100)})).getString()); - } - - } - - @Override - public void b() { - WorldLoadListenerLogger.LOGGER.info("Time elapsed: {} ms", SystemUtils.getMonotonicMillis() - this.d); - this.e = Long.MAX_VALUE; - } - - public int c() { - return MathHelper.d((float) this.c * 100.0F / (float) this.b); - } -} diff --git a/src/main/java/net/minecraft/server/WorldMap.java b/src/main/java/net/minecraft/server/WorldMap.java deleted file mode 100644 index 090d3dbd3..000000000 --- a/src/main/java/net/minecraft/server/WorldMap.java +++ /dev/null @@ -1,502 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import javax.annotation.Nullable; - -// CraftBukkit start -import java.util.UUID; - -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.map.CraftMapView; -import org.bukkit.craftbukkit.util.CraftChatMessage; -// CraftBukkit end - -public class WorldMap extends PersistentBase { - - public int centerX; - public int centerZ; - public DimensionManager map; - public boolean track; - public boolean unlimitedTracking; - public byte scale; - public byte[] colors = new byte[16384]; - public boolean locked; - public final List i = Lists.newArrayList(); - public final Map humans = Maps.newHashMap(); - private final Map l = Maps.newHashMap(); - public final Map decorations = Maps.newLinkedHashMap(); - private final Map m = Maps.newHashMap(); - private org.bukkit.craftbukkit.map.RenderData vanillaRender = new org.bukkit.craftbukkit.map.RenderData(); // Paper - - // CraftBukkit start - public final CraftMapView mapView; - private 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(); - vanillaRender.buffer = colors; // Paper - // CraftBukkit end - } - - public void a(int i, int j, int k, boolean flag, boolean flag1, DimensionManager dimensionmanager) { - this.scale = (byte) k; - this.a((double) i, (double) j, this.scale); - this.map = dimensionmanager; - this.track = flag; - this.unlimitedTracking = flag1; - this.b(); - } - - 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; - } - - @Override - public void a(NBTTagCompound nbttagcompound) { - int i = nbttagcompound.getInt("dimension"); - // CraftBukkit start - DimensionManager dimensionmanager = null; - - if (i >= CraftWorld.CUSTOM_DIMENSION_OFFSET) { - 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. */ - dimensionmanager = new DimensionManager(127, null, null, null, false, DimensionManager.OVERWORLD); - } else { - dimensionmanager = world.getHandle().getWorldProvider().getDimensionManager(); - } - } - } else { - dimensionmanager = DimensionManager.a(i); - } - // CraftBukkit end - - if (dimensionmanager == null) { - throw new IllegalArgumentException("Invalid map dimension: " + i); - } else { - this.map = dimensionmanager; - this.centerX = nbttagcompound.getInt("xCenter"); - this.centerZ = nbttagcompound.getInt("zCenter"); - this.scale = (byte) MathHelper.clamp(nbttagcompound.getByte("scale"), 0, 4); - this.track = !nbttagcompound.hasKeyOfType("trackingPosition", 1) || nbttagcompound.getBoolean("trackingPosition"); - this.unlimitedTracking = nbttagcompound.getBoolean("unlimitedTracking"); - this.locked = nbttagcompound.getBoolean("locked"); - this.colors = nbttagcompound.getByteArray("colors"); - if (this.colors.length != 16384) { - this.colors = new byte[16384]; - } - - NBTTagList nbttaglist = nbttagcompound.getList("banners", 10); - - for (int j = 0; j < nbttaglist.size(); ++j) { - MapIconBanner mapiconbanner = MapIconBanner.a(nbttaglist.getCompound(j)); - - this.l.put(mapiconbanner.f(), mapiconbanner); - this.a(mapiconbanner.c(), (GeneratorAccess) null, mapiconbanner.f(), (double) mapiconbanner.a().getX(), (double) mapiconbanner.a().getZ(), 180.0D, mapiconbanner.d()); - } - vanillaRender.buffer = colors; // Paper - - NBTTagList nbttaglist1 = nbttagcompound.getList("frames", 10); - - for (int k = 0; k < nbttaglist1.size(); ++k) { - WorldMapFrame worldmapframe = WorldMapFrame.a(nbttaglist1.getCompound(k)); - - this.m.put(worldmapframe.e(), worldmapframe); - this.a(MapIcon.Type.FRAME, (GeneratorAccess) null, "frame-" + worldmapframe.d(), (double) worldmapframe.b().getX(), (double) worldmapframe.b().getZ(), (double) worldmapframe.c(), (IChatBaseComponent) null); - } - - } - } - - @Override - public NBTTagCompound b(NBTTagCompound nbttagcompound) { - // CraftBukkit start - if (this.map.getDimensionID() >= CraftWorld.CUSTOM_DIMENSION_OFFSET) { - if (this.uniqueId == null) { - for (org.bukkit.World world : server.getWorlds()) { - CraftWorld cWorld = (CraftWorld) world; - if (cWorld.getHandle().getWorldProvider().getDimensionManager() == 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.setInt("dimension", this.map.getDimensionID()); - nbttagcompound.setInt("xCenter", this.centerX); - nbttagcompound.setInt("zCenter", this.centerZ); - nbttagcompound.setByte("scale", this.scale); - nbttagcompound.setByteArray("colors", this.colors); - nbttagcompound.setBoolean("trackingPosition", this.track); - nbttagcompound.setBoolean("unlimitedTracking", this.unlimitedTracking); - nbttagcompound.setBoolean("locked", this.locked); - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = this.l.values().iterator(); - - while (iterator.hasNext()) { - MapIconBanner mapiconbanner = (MapIconBanner) iterator.next(); - - nbttaglist.add(mapiconbanner.e()); - } - - nbttagcompound.set("banners", nbttaglist); - NBTTagList nbttaglist1 = new NBTTagList(); - Iterator iterator1 = this.m.values().iterator(); - - while (iterator1.hasNext()) { - WorldMapFrame worldmapframe = (WorldMapFrame) iterator1.next(); - - nbttaglist1.add(worldmapframe.a()); - } - - nbttagcompound.set("frames", nbttaglist1); - return nbttagcompound; - } - - public void a(WorldMap worldmap) { - this.locked = true; - this.centerX = worldmap.centerX; - this.centerZ = worldmap.centerZ; - this.l.putAll(worldmap.l); - this.decorations.putAll(worldmap.decorations); - System.arraycopy(worldmap.colors, 0, this.colors, 0, worldmap.colors.length); - this.b(); - } - - public void updateSeenPlayers(EntityHuman entityhuman, ItemStack itemstack) { this.a(entityhuman, itemstack); } // Paper - OBFHELPER - public void a(EntityHuman entityhuman, ItemStack itemstack) { - if (!this.humans.containsKey(entityhuman)) { - WorldMap.WorldMapHumanTracker worldmap_worldmaphumantracker = new WorldMap.WorldMapHumanTracker(entityhuman); - - this.humans.put(entityhuman, worldmap_worldmaphumantracker); - this.i.add(worldmap_worldmaphumantracker); - } - - if (!entityhuman.inventory.h(itemstack)) { - this.decorations.remove(entityhuman.getDisplayName().getString()); - } - - for (int i = 0; i < this.i.size(); ++i) { - WorldMap.WorldMapHumanTracker worldmap_worldmaphumantracker1 = (WorldMap.WorldMapHumanTracker) this.i.get(i); - String s = worldmap_worldmaphumantracker1.trackee.getDisplayName().getString(); - - if (!worldmap_worldmaphumantracker1.trackee.dead && (worldmap_worldmaphumantracker1.trackee.inventory.h(itemstack) || itemstack.y())) { - if (!itemstack.y() && worldmap_worldmaphumantracker1.trackee.dimension == this.map && this.track) { - this.a(MapIcon.Type.PLAYER, worldmap_worldmaphumantracker1.trackee.world, s, worldmap_worldmaphumantracker1.trackee.locX, worldmap_worldmaphumantracker1.trackee.locZ, (double) worldmap_worldmaphumantracker1.trackee.yaw, (IChatBaseComponent) null); - } - } else { - this.humans.remove(worldmap_worldmaphumantracker1.trackee); - this.i.remove(worldmap_worldmaphumantracker1); - this.decorations.remove(s); - } - } - - if (itemstack.y() && this.track) { - EntityItemFrame entityitemframe = itemstack.z(); - BlockPosition blockposition = entityitemframe.getBlockPosition(); - WorldMapFrame worldmapframe = (WorldMapFrame) this.m.get(WorldMapFrame.a(blockposition)); - - if (worldmapframe != null && entityitemframe.getId() != worldmapframe.d() && this.m.containsKey(worldmapframe.e())) { - this.decorations.remove("frame-" + worldmapframe.d()); - } - - WorldMapFrame worldmapframe1 = new WorldMapFrame(blockposition, entityitemframe.getDirection().get2DRotationValue() * 90, entityitemframe.getId()); - - this.a(MapIcon.Type.FRAME, entityhuman.world, "frame-" + entityitemframe.getId(), (double) blockposition.getX(), (double) blockposition.getZ(), (double) (entityitemframe.getDirection().get2DRotationValue() * 90), (IChatBaseComponent) null); - this.m.put(worldmapframe1.e(), worldmapframe1); - } - - NBTTagCompound nbttagcompound = itemstack.getTag(); - - if (nbttagcompound != null && nbttagcompound.hasKeyOfType("Decorations", 9)) { - NBTTagList nbttaglist = nbttagcompound.getList("Decorations", 10); - - for (int j = 0; j < nbttaglist.size(); ++j) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompound(j); - - if (!this.decorations.containsKey(nbttagcompound1.getString("id"))) { - this.a(MapIcon.Type.a(nbttagcompound1.getByte("type")), entityhuman.world, nbttagcompound1.getString("id"), nbttagcompound1.getDouble("x"), nbttagcompound1.getDouble("z"), nbttagcompound1.getDouble("rot"), (IChatBaseComponent) null); - } - } - } - - } - - public static void decorateMap(ItemStack itemstack, BlockPosition blockposition, String s, MapIcon.Type mapicon_type) { - NBTTagList nbttaglist; - - if (itemstack.hasTag() && itemstack.getTag().hasKeyOfType("Decorations", 9)) { - nbttaglist = itemstack.getTag().getList("Decorations", 10); - } else { - nbttaglist = new NBTTagList(); - itemstack.a("Decorations", (NBTBase) nbttaglist); - } - - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setByte("type", mapicon_type.a()); - nbttagcompound.setString("id", s); - nbttagcompound.setDouble("x", (double) blockposition.getX()); - nbttagcompound.setDouble("z", (double) blockposition.getZ()); - nbttagcompound.setDouble("rot", 180.0D); - nbttaglist.add(nbttagcompound); - if (mapicon_type.c()) { - NBTTagCompound nbttagcompound1 = itemstack.a("display"); - - nbttagcompound1.setInt("MapColor", mapicon_type.d()); - } - - } - - private void a(MapIcon.Type mapicon_type, @Nullable GeneratorAccess generatoraccess, String s, double d0, double d1, double d2, @Nullable IChatBaseComponent ichatbasecomponent) { - int i = 1 << this.scale; - float f = (float) (d0 - (double) this.centerX) / (float) i; - float f1 = (float) (d1 - (double) this.centerZ) / (float) i; - byte b0 = (byte) ((int) ((double) (f * 2.0F) + 0.5D)); - byte b1 = (byte) ((int) ((double) (f1 * 2.0F) + 0.5D)); - boolean flag = true; - byte b2; - - if (f >= -63.0F && f1 >= -63.0F && f <= 63.0F && f1 <= 63.0F) { - d2 += d2 < 0.0D ? -8.0D : 8.0D; - b2 = (byte) ((int) (d2 * 16.0D / 360.0D)); - if (this.map == DimensionManager.NETHER && generatoraccess != null) { - int j = (int) (generatoraccess.getWorldData().getDayTime() / 10L); - - b2 = (byte) (j * j * 34187121 + j * 121 >> 15 & 15); - } - } else { - if (mapicon_type != MapIcon.Type.PLAYER) { - this.decorations.remove(s); - return; - } - - boolean flag1 = true; - - if (Math.abs(f) < 320.0F && Math.abs(f1) < 320.0F) { - mapicon_type = MapIcon.Type.PLAYER_OFF_MAP; - } else { - if (!this.unlimitedTracking) { - this.decorations.remove(s); - return; - } - - mapicon_type = MapIcon.Type.PLAYER_OFF_LIMITS; - } - - b2 = 0; - if (f <= -63.0F) { - b0 = -128; - } - - if (f1 <= -63.0F) { - b1 = -128; - } - - if (f >= 63.0F) { - b0 = 127; - } - - if (f1 >= 63.0F) { - b1 = 127; - } - } - - this.decorations.put(s, new MapIcon(mapicon_type, b0, b1, b2, ichatbasecomponent)); - } - - @Nullable - public Packet a(ItemStack itemstack, IBlockAccess iblockaccess, EntityHuman entityhuman) { - WorldMap.WorldMapHumanTracker worldmap_worldmaphumantracker = (WorldMap.WorldMapHumanTracker) this.humans.get(entityhuman); - - return worldmap_worldmaphumantracker == null ? null : worldmap_worldmaphumantracker.a(itemstack); - } - - public void flagDirty(int i, int j) { - this.b(); - Iterator iterator = this.i.iterator(); - - while (iterator.hasNext()) { - WorldMap.WorldMapHumanTracker worldmap_worldmaphumantracker = (WorldMap.WorldMapHumanTracker) iterator.next(); - - worldmap_worldmaphumantracker.a(i, j); - } - - } - - public WorldMap.WorldMapHumanTracker a(EntityHuman entityhuman) { - WorldMap.WorldMapHumanTracker worldmap_worldmaphumantracker = (WorldMap.WorldMapHumanTracker) this.humans.get(entityhuman); - - if (worldmap_worldmaphumantracker == null) { - worldmap_worldmaphumantracker = new WorldMap.WorldMapHumanTracker(entityhuman); - this.humans.put(entityhuman, worldmap_worldmaphumantracker); - this.i.add(worldmap_worldmaphumantracker); - } - - return worldmap_worldmaphumantracker; - } - - public void a(GeneratorAccess generatoraccess, BlockPosition blockposition) { - float f = (float) blockposition.getX() + 0.5F; - float f1 = (float) blockposition.getZ() + 0.5F; - int i = 1 << this.scale; - float f2 = (f - (float) this.centerX) / (float) i; - float f3 = (f1 - (float) this.centerZ) / (float) i; - boolean flag = true; - boolean flag1 = false; - - if (f2 >= -63.0F && f3 >= -63.0F && f2 <= 63.0F && f3 <= 63.0F) { - MapIconBanner mapiconbanner = MapIconBanner.a(generatoraccess, blockposition); - - if (mapiconbanner == null) { - return; - } - - boolean flag2 = true; - - if (this.l.containsKey(mapiconbanner.f()) && ((MapIconBanner) this.l.get(mapiconbanner.f())).equals(mapiconbanner)) { - this.l.remove(mapiconbanner.f()); - this.decorations.remove(mapiconbanner.f()); - flag2 = false; - flag1 = true; - } - - if (flag2) { - this.l.put(mapiconbanner.f(), mapiconbanner); - this.a(mapiconbanner.c(), generatoraccess, mapiconbanner.f(), (double) f, (double) f1, 180.0D, mapiconbanner.d()); - flag1 = true; - } - - if (flag1) { - this.b(); - } - } - - } - - public void a(IBlockAccess iblockaccess, int i, int j) { - Iterator iterator = this.l.values().iterator(); - - while (iterator.hasNext()) { - MapIconBanner mapiconbanner = (MapIconBanner) iterator.next(); - - if (mapiconbanner.a().getX() == i && mapiconbanner.a().getZ() == j) { - MapIconBanner mapiconbanner1 = MapIconBanner.a(iblockaccess, mapiconbanner.a()); - - if (!mapiconbanner.equals(mapiconbanner1)) { - iterator.remove(); - this.decorations.remove(mapiconbanner.f()); - } - } - } - - } - - public void a(BlockPosition blockposition, int i) { - this.decorations.remove("frame-" + i); - this.m.remove(WorldMapFrame.a(blockposition)); - } - - public class WorldMapHumanTracker { - - // Paper start - private void addSeenPlayers(java.util.Collection icons) { - org.bukkit.entity.Player player = (org.bukkit.entity.Player) trackee.getBukkitEntity(); - WorldMap.this.decorations.forEach((name, mapIcon) -> { - // If this cursor is for a player check visibility with vanish system - org.bukkit.entity.Player other = org.bukkit.Bukkit.getPlayerExact(name); // Spigot - if (other == null || player.canSee(other)) { - icons.add(mapIcon); - } - }); - } - private boolean shouldUseVanillaMap() { - return mapView.getRenderers().size() == 1 && mapView.getRenderers().get(0).getClass() == org.bukkit.craftbukkit.map.CraftMapRenderer.class; - } - // Paper end - public final EntityHuman trackee; - private boolean d = true; - private int e; - private int f; - private int g = 127; - private int h = 127; - private int i; - public int b; - - public WorldMapHumanTracker(EntityHuman entityhuman) { - this.trackee = entityhuman; - } - - @Nullable - public Packet a(ItemStack itemstack) { - // CraftBukkit start - if (!this.d && this.i % 5 != 0) { this.i++; return null; } // Paper - this won't end up sending, so don't render it! - boolean vanillaMaps = shouldUseVanillaMap(); // Paper - org.bukkit.craftbukkit.map.RenderData render = !vanillaMaps ? WorldMap.this.mapView.render((org.bukkit.craftbukkit.entity.CraftPlayer) this.trackee.getBukkitEntity()) : WorldMap.this.vanillaRender; // CraftBukkit // Paper - - java.util.Collection icons = new java.util.ArrayList(); - if (vanillaMaps) addSeenPlayers(icons); // Paper - - for ( org.bukkit.map.MapCursor cursor : render.cursors) { - - if (cursor.isVisible()) { - icons.add(new MapIcon(MapIcon.Type.a(cursor.getRawType()), cursor.getX(), cursor.getY(), cursor.getDirection(), CraftChatMessage.fromStringOrNull(cursor.getCaption()))); - } - } - - if (this.d) { - this.d = false; - return new PacketPlayOutMap(ItemWorldMap.e(itemstack), WorldMap.this.scale, WorldMap.this.track, WorldMap.this.locked, 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(ItemWorldMap.e(itemstack), WorldMap.this.scale, WorldMap.this.track, WorldMap.this.locked, 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/src/main/java/net/minecraft/server/WorldNBTStorage.java b/src/main/java/net/minecraft/server/WorldNBTStorage.java deleted file mode 100644 index eaae44686..000000000 --- a/src/main/java/net/minecraft/server/WorldNBTStorage.java +++ /dev/null @@ -1,348 +0,0 @@ -package net.minecraft.server; - -import com.mojang.datafixers.DataFixer; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import java.util.UUID; -import org.bukkit.craftbukkit.entity.CraftPlayer; -// CraftBukkit end - -public class WorldNBTStorage implements IPlayerFileData { - - private static final Logger LOGGER = LogManager.getLogger(); - private final File baseDir; - private final File playerDir; - private final long sessionId = SystemUtils.getMonotonicMillis(); - private final String f; - private final DefinedStructureManager g; - protected final DataFixer a; - private UUID uuid = null; // CraftBukkit - - public WorldNBTStorage(File file, String s, @Nullable MinecraftServer minecraftserver, DataFixer datafixer) { - this.a = datafixer; - // Paper start - if (com.destroystokyo.paper.PaperConfig.useVersionedWorld) { - File origBaseDir = new File(file, s); - final String currentVersion = MinecraftServer.getServer().getVersion(); - file = new File(file, currentVersion); - File baseDir = new File(file, s); - - if (!baseDir.exists() && origBaseDir.exists() && !baseDir.mkdirs()) { - LogManager.getLogger().error("Could not create world directory for " + file); - System.exit(1); - } - - try { - boolean printedHeader = false; - String[] dirs = {"advancements", "data", "datapacks", "playerdata", "stats"}; - for (String dir : dirs) { - File origPlayerData = new File(origBaseDir, dir); - File targetPlayerData = new File(baseDir, dir); - if (origPlayerData.exists() && !targetPlayerData.exists()) { - if (!printedHeader) { - LogManager.getLogger().info("**** VERSIONED WORLD - Copying files"); - printedHeader = true; - } - LogManager.getLogger().info("- Copying: " + dir); - org.apache.commons.io.FileUtils.copyDirectory(origPlayerData, targetPlayerData); - } - } - - String[] files = {"level.dat", "level.dat_old", "session.lock", "uid.dat"}; - for (String fileName : files) { - File origPlayerData = new File(origBaseDir, fileName); - File targetPlayerData = new File(baseDir, fileName); - if (origPlayerData.exists() && !targetPlayerData.exists()) { - if (!printedHeader) { - LogManager.getLogger().info("- Copying files"); - printedHeader = true; - } - LogManager.getLogger().info("- Copying: " + fileName); - org.apache.commons.io.FileUtils.copyFile(origPlayerData, targetPlayerData); - - } - } - if (printedHeader) { - LogManager.getLogger().info("**** VERSIONED WORLD - Copying DONE"); - } - } catch (IOException e) { - LogManager.getLogger().error("Error copying versioned world data for " + origBaseDir + " to " + baseDir, e); - com.destroystokyo.paper.util.SneakyThrow.sneaky(e); - } - - } - // Paper end - this.baseDir = new File(file, s); - this.baseDir.mkdirs(); - this.playerDir = new File(this.baseDir, "playerdata"); - this.f = s; - if (minecraftserver != null) { - this.playerDir.mkdirs(); - this.g = new DefinedStructureManager(minecraftserver, this.baseDir, datafixer); - } else { - this.g = null; - } - - this.h(); - } - - public void saveWorldData(WorldData worlddata, @Nullable NBTTagCompound nbttagcompound) { - worlddata.d(19133); - NBTTagCompound nbttagcompound1 = worlddata.a(nbttagcompound); - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - - nbttagcompound2.set("Data", nbttagcompound1); - - try { - File file = new File(this.baseDir, "level.dat_new"); - File file1 = new File(this.baseDir, "level.dat_old"); - File file2 = new File(this.baseDir, "level.dat"); - - NBTCompressedStreamTools.a(nbttagcompound2, (OutputStream) (new FileOutputStream(file))); - if (file1.exists()) { - file1.delete(); - } - - file2.renameTo(file1); - if (file2.exists()) { - file2.delete(); - } - - file.renameTo(file2); - if (file.exists()) { - file.delete(); - } - } catch (Exception exception) { - exception.printStackTrace(); - } - - } - - private void h() { - try { - File file = new File(this.baseDir, "session.lock"); - DataOutputStream dataoutputstream = new DataOutputStream(new FileOutputStream(file)); - - try { - dataoutputstream.writeLong(this.sessionId); - } finally { - dataoutputstream.close(); - } - - } 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(this.baseDir, "session.lock"); - DataInputStream datainputstream = new DataInputStream(new FileInputStream(file)); - - try { - if (datainputstream.readLong() != this.sessionId) { - throw new ExceptionWorldConflict("The save for world located at " + this.baseDir + " is being accessed from another location, aborting"); // Spigot - } - } finally { - datainputstream.close(); - } - - } catch (IOException ioexception) { - throw new ExceptionWorldConflict("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 - } - } - - @Nullable - public WorldData getWorldData() { - File file = new File(this.baseDir, "level.dat"); - - if (file.exists()) { - WorldData worlddata = Convertable.a(file, this.a); - - if (worlddata != null) { - return worlddata; - } - } - - file = new File(this.baseDir, "level.dat_old"); - return file.exists() ? Convertable.a(file, this.a) : null; - } - - public void saveWorldData(WorldData worlddata) { - this.saveWorldData(worlddata, (NBTTagCompound) null); - } - - @Override - public void save(EntityHuman entityhuman) { - if(!com.destroystokyo.paper.PaperConfig.savePlayerData) return; // Paper - Make player data saving configurable - try { - NBTTagCompound nbttagcompound = entityhuman.save(new NBTTagCompound()); - File file = new File(this.playerDir, entityhuman.getUniqueIDString() + ".dat.tmp"); - File file1 = new File(this.playerDir, entityhuman.getUniqueIDString() + ".dat"); - - NBTCompressedStreamTools.a(nbttagcompound, (OutputStream) (new FileOutputStream(file))); - if (file1.exists()) { - file1.delete(); - } - - file.renameTo(file1); - } catch (Exception exception) { - WorldNBTStorage.LOGGER.error("Failed to save player data for {}", entityhuman.getName(), exception); // Paper - } - - } - - @Nullable - @Override - public NBTTagCompound load(EntityHuman entityhuman) { - NBTTagCompound nbttagcompound = null; - - try { - File file = new File(this.playerDir, entityhuman.getUniqueIDString() + ".dat"); - // Spigot Start - boolean usingWrongFile = false; - if ( org.bukkit.Bukkit.getOnlineMode() && !file.exists() ) // Paper - Check online mode first - { - file = new File( this.playerDir, UUID.nameUUIDFromBytes( ( "OfflinePlayer:" + entityhuman.getName() ).getBytes( "UTF-8" ) ).toString() + ".dat"); - 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 (file.exists() && file.isFile()) { - nbttagcompound = NBTCompressedStreamTools.a((InputStream) (new FileInputStream(file))); - } - // Spigot Start - if ( usingWrongFile ) - { - file.renameTo( new File( file.getPath() + ".offline-read" ) ); - } - // Spigot End - } catch (Exception exception) { - WorldNBTStorage.LOGGER.warn("Failed to load player data for {}", entityhuman.getDisplayName().getString()); - } - - 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, entityhuman.getUniqueID().toString() + ".dat").lastModified(); - if (modified < player.getFirstPlayed()) { - player.setFirstPlayed(modified); - } - } - // CraftBukkit end - int i = nbttagcompound.hasKeyOfType("DataVersion", 3) ? nbttagcompound.getInt("DataVersion") : -1; - - entityhuman.f(GameProfileSerializer.a(this.a, DataFixTypes.PLAYER, nbttagcompound, i)); - } - - return nbttagcompound; - } - - // CraftBukkit start - public NBTTagCompound getPlayerData(String s) { - try { - File file1 = new File(this.playerDir, s + ".dat"); - - if (file1.exists()) { - return NBTCompressedStreamTools.a((InputStream) (new FileInputStream(file1))); - } - } catch (Exception exception) { - LOGGER.warn("Failed to load player data for " + s); - } - - return null; - } - // CraftBukkit end - - 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 DefinedStructureManager f() { - return this.g; - } - - public DataFixer getDataFixer() { - return this.a; - } - - // CraftBukkit start - public UUID getUUID() { - if (uuid != null) return uuid; - File file1 = new File(this.baseDir, "uid.dat"); - if (file1.exists()) { - DataInputStream dis = null; - try { - dis = new DataInputStream(new FileInputStream(file1)); - return uuid = new UUID(dis.readLong(), dis.readLong()); - } catch (IOException ex) { - LOGGER.warn("Failed to read " + file1 + ", generating new random UUID", ex); - } finally { - if (dis != null) { - try { - dis.close(); - } catch (IOException ex) { - // NOOP - } - } - } - } - uuid = UUID.randomUUID(); - DataOutputStream dos = null; - try { - dos = new DataOutputStream(new FileOutputStream(file1)); - dos.writeLong(uuid.getMostSignificantBits()); - dos.writeLong(uuid.getLeastSignificantBits()); - } catch (IOException ex) { - LOGGER.warn("Failed to write " + file1, ex); - } finally { - if (dos != null) { - try { - dos.close(); - } catch (IOException ex) { - // NOOP - } - } - } - return uuid; - } - - public File getPlayerDir() { - return playerDir; - } - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/WorldPersistentData.java b/src/main/java/net/minecraft/server/WorldPersistentData.java deleted file mode 100644 index 00e9a1735..000000000 --- a/src/main/java/net/minecraft/server/WorldPersistentData.java +++ /dev/null @@ -1,176 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.Maps; -import com.mojang.datafixers.DataFixer; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.util.Iterator; -import java.util.Map; -import java.util.function.Supplier; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class WorldPersistentData { - - private static final Logger LOGGER = LogManager.getLogger(); - public final Map data = Maps.newHashMap(); - private final DataFixer c; - private final File d; - - public WorldPersistentData(File file, DataFixer datafixer) { - this.c = datafixer; - this.d = file; - } - - private File a(String s) { - return new File(this.d, s + ".dat"); - } - - public T a(Supplier supplier, String s) { - T t0 = this.b(supplier, s); - - if (t0 != null) { - return t0; - } else { - T t1 = supplier.get(); // Paper - decompile fix - - this.a(t1); - return t1; - } - } - - @Nullable - public T b(Supplier supplier, String s) { - T persistentbase = (T) this.data.get(s); // Paper - decompile fix - - if (persistentbase == null && !this.data.containsKey(s)) { - persistentbase = this.c(supplier, s); - this.data.put(s, persistentbase); - } - - return persistentbase; - } - - @Nullable - private T c(Supplier supplier, String s) { - try { - File file = this.a(s); - - if (file.exists()) { - T t0 = supplier.get(); // Paper - decompile fix - NBTTagCompound nbttagcompound = this.a(s, SharedConstants.a().getWorldVersion()); - - t0.a(nbttagcompound.getCompound("data")); - return t0; - } - } catch (Exception exception) { - WorldPersistentData.LOGGER.error("Error loading saved data: {}", s, exception); - } - - return null; - } - - public void a(PersistentBase persistentbase) { - this.data.put(persistentbase.getId(), persistentbase); - } - - public NBTTagCompound a(String s, int i) throws IOException { - File file = this.a(s); - PushbackInputStream pushbackinputstream = new PushbackInputStream(new FileInputStream(file), 2); - Throwable throwable = null; - - NBTTagCompound nbttagcompound; - - try { - NBTTagCompound nbttagcompound1; - - if (this.a(pushbackinputstream)) { - nbttagcompound1 = NBTCompressedStreamTools.a((InputStream) pushbackinputstream); - } else { - DataInputStream datainputstream = new DataInputStream(pushbackinputstream); - Throwable throwable1 = null; - - try { - nbttagcompound1 = NBTCompressedStreamTools.a(datainputstream); - } catch (Throwable throwable2) { - throwable1 = throwable2; - throw throwable2; - } finally { - if (datainputstream != null) { - if (throwable1 != null) { - try { - datainputstream.close(); - } catch (Throwable throwable3) { - throwable1.addSuppressed(throwable3); - } - } else { - datainputstream.close(); - } - } - - } - } - - int j = nbttagcompound1.hasKeyOfType("DataVersion", 99) ? nbttagcompound1.getInt("DataVersion") : 1343; - - nbttagcompound = GameProfileSerializer.a(this.c, DataFixTypes.SAVED_DATA, nbttagcompound1, j, i); - } catch (Throwable throwable4) { - throwable = throwable4; - com.destroystokyo.paper.exception.ServerInternalException.reportInternalException(throwable); // Paper - throw throwable4; - } finally { - if (pushbackinputstream != null) { - if (throwable != null) { - try { - pushbackinputstream.close(); - } catch (Throwable throwable5) { - throwable.addSuppressed(throwable5); - } - } else { - pushbackinputstream.close(); - } - } - - } - - return nbttagcompound; - } - - private boolean a(PushbackInputStream pushbackinputstream) throws IOException { - byte[] abyte = new byte[2]; - boolean flag = false; - int i = pushbackinputstream.read(abyte, 0, 2); - - if (i == 2) { - int j = (abyte[1] & 255) << 8 | abyte[0] & 255; - - if (j == 35615) { - flag = true; - } - } - - if (i != 0) { - pushbackinputstream.unread(abyte, 0, i); - } - - return flag; - } - - public void a() { - Iterator iterator = this.data.values().iterator(); - - while (iterator.hasNext()) { - PersistentBase persistentbase = (PersistentBase) iterator.next(); - - if (persistentbase != null) { - persistentbase.a(this.a(persistentbase.getId())); - } - } - - } -} diff --git a/src/main/java/net/minecraft/server/WorldProvider.java b/src/main/java/net/minecraft/server/WorldProvider.java deleted file mode 100644 index d65e10cb4..000000000 --- a/src/main/java/net/minecraft/server/WorldProvider.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public abstract class WorldProvider { - - public static final float[] a = new float[]{1.0F, 0.75F, 0.5F, 0.25F, 0.0F, 0.25F, 0.5F, 0.75F}; - protected final World b; - private final DimensionManager f; - protected boolean c; - protected boolean d; - protected final float[] e = new float[16]; - private final float[] g = new float[4]; - - public WorldProvider(World world, DimensionManager dimensionmanager) { - this.b = world; - this.f = dimensionmanager; - 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.e[i] = (1.0F - f1) / (f1 * 3.0F + 1.0F) * 1.0F + 0.0F; - } - - } - - public int a(long i) { - return (int) (i / 24000L % 8L + 8L) % 8; - } - - @Nullable - public BlockPosition d() { - return null; - } - - public boolean isNether() { - return this.c; - } - - public boolean g() { - return this.f.hasSkyLight(); - } - - public boolean h() { - return this.d; - } - - public float[] i() { - return this.e; - } - - public WorldBorder getWorldBorder() { - return new WorldBorder(); - } - - public void k() {} - - public void l() {} - - public abstract ChunkGenerator getChunkGenerator(); - - @Nullable - public abstract BlockPosition a(ChunkCoordIntPair chunkcoordintpair, boolean flag); - - @Nullable - public abstract BlockPosition a(int i, int j, boolean flag); - - public abstract float a(long i, float f); - - public abstract boolean isOverworld(); - - public abstract boolean canRespawn(); - - public DimensionManager getDimensionManager() { return this.f; } // CraftBukkit -} diff --git a/src/main/java/net/minecraft/server/WorldProviderHell.java b/src/main/java/net/minecraft/server/WorldProviderHell.java deleted file mode 100644 index d0c9526c1..000000000 --- a/src/main/java/net/minecraft/server/WorldProviderHell.java +++ /dev/null @@ -1,84 +0,0 @@ -package net.minecraft.server; - -import javax.annotation.Nullable; - -public class WorldProviderHell extends WorldProvider { - - public WorldProviderHell(World world, DimensionManager dimensionmanager) { - super(world, dimensionmanager); - this.c = true; - this.d = true; - } - - @Override - protected void a() { - float f = 0.1F; - - for (int i = 0; i <= 15; ++i) { - float f1 = 1.0F - (float) i / 15.0F; - - this.e[i] = (1.0F - f1) / (f1 * 3.0F + 1.0F) * 0.9F + 0.1F; - } - - } - - @Override - public ChunkGenerator getChunkGenerator() { - GeneratorSettingsNether generatorsettingsnether = (GeneratorSettingsNether) ChunkGeneratorType.b.a(); - - generatorsettingsnether.a(Blocks.NETHERRACK.getBlockData()); - generatorsettingsnether.b(Blocks.LAVA.getBlockData()); - return ChunkGeneratorType.b.create(this.b, BiomeLayout.b.a(((BiomeLayoutFixedConfiguration) BiomeLayout.b.a()).a(Biomes.NETHER)), generatorsettingsnether); - } - - @Override - public boolean isOverworld() { - return false; - } - - @Nullable - @Override - public BlockPosition a(ChunkCoordIntPair chunkcoordintpair, boolean flag) { - return null; - } - - @Nullable - @Override - public BlockPosition a(int i, int j, boolean flag) { - return null; - } - - @Override - public float a(long i, float f) { - return 0.5F; - } - - @Override - public boolean canRespawn() { - return false; - } - - @Override - public WorldBorder getWorldBorder() { - return new WorldBorder() { - @Override - public double getCenterX() { - return super.getCenterX(); // CraftBukkit - } - - @Override - public double getCenterZ() { - return super.getCenterZ(); // CraftBukkit - } - }; - } - - // CraftBukkit start - /* - @Override - public DimensionManager getDimensionManager() { - return DimensionManager.NETHER; - } - */ - // CraftBukkit end -} diff --git a/src/main/java/net/minecraft/server/WorldProviderNormal.java b/src/main/java/net/minecraft/server/WorldProviderNormal.java deleted file mode 100644 index 861887117..000000000 --- a/src/main/java/net/minecraft/server/WorldProviderNormal.java +++ /dev/null @@ -1,213 +0,0 @@ -package net.minecraft.server; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mojang.datafixers.Dynamic; -import com.mojang.datafixers.types.JsonOps; -import javax.annotation.Nullable; - -public class WorldProviderNormal extends WorldProvider { - - public WorldProviderNormal(World world, DimensionManager dimensionmanager) { - super(world, dimensionmanager); - } - - // CraftBukkit start - /* - @Override - public DimensionManager getDimensionManager() { - return DimensionManager.OVERWORLD; - } - */ - // CraftBukkit end - - @Override - public ChunkGenerator getChunkGenerator() { - WorldType worldtype = this.b.getWorldData().getType(); - ChunkGeneratorType chunkgeneratortype = ChunkGeneratorType.e; - ChunkGeneratorType chunkgeneratortype1 = ChunkGeneratorType.d; - ChunkGeneratorType chunkgeneratortype2 = ChunkGeneratorType.b; - ChunkGeneratorType chunkgeneratortype3 = ChunkGeneratorType.c; - ChunkGeneratorType chunkgeneratortype4 = ChunkGeneratorType.a; - BiomeLayout biomelayout = BiomeLayout.b; - BiomeLayout biomelayout1 = BiomeLayout.c; - BiomeLayout biomelayout2 = BiomeLayout.a; - - if (worldtype == WorldType.FLAT) { - GeneratorSettingsFlat generatorsettingsflat = GeneratorSettingsFlat.a(new Dynamic(DynamicOpsNBT.a, this.b.getWorldData().getGeneratorOptions())); - BiomeLayoutFixedConfiguration biomelayoutfixedconfiguration = ((BiomeLayoutFixedConfiguration) biomelayout.a()).a(generatorsettingsflat.v()); - - return chunkgeneratortype.create(this.b, biomelayout.a(biomelayoutfixedconfiguration), generatorsettingsflat); - } else if (worldtype == WorldType.DEBUG_ALL_BLOCK_STATES) { - BiomeLayoutFixedConfiguration biomelayoutfixedconfiguration1 = ((BiomeLayoutFixedConfiguration) biomelayout.a()).a(Biomes.PLAINS); - - return chunkgeneratortype1.create(this.b, biomelayout.a(biomelayoutfixedconfiguration1), chunkgeneratortype1.a()); - } else if (worldtype != WorldType.g) { - GeneratorSettingsOverworld generatorsettingsoverworld = (GeneratorSettingsOverworld) chunkgeneratortype4.a(); - BiomeLayoutOverworldConfiguration biomelayoutoverworldconfiguration = ((BiomeLayoutOverworldConfiguration) biomelayout1.a()).a(this.b.getWorldData()).a(generatorsettingsoverworld); - - return chunkgeneratortype4.create(this.b, biomelayout1.a(biomelayoutoverworldconfiguration), generatorsettingsoverworld); - } else { - WorldChunkManager worldchunkmanager = null; - JsonElement jsonelement = (JsonElement) Dynamic.convert(DynamicOpsNBT.a, JsonOps.INSTANCE, this.b.getWorldData().getGeneratorOptions()); - JsonObject jsonobject = jsonelement.getAsJsonObject(); - JsonObject jsonobject1 = jsonobject.getAsJsonObject("biome_source"); - - if (jsonobject1 != null && jsonobject1.has("type") && jsonobject1.has("options")) { - BiomeLayout biomelayout3 = (BiomeLayout) IRegistry.BIOME_SOURCE_TYPE.get(new MinecraftKey(jsonobject1.getAsJsonPrimitive("type").getAsString())); - JsonObject jsonobject2 = jsonobject1.getAsJsonObject("options"); - BiomeBase[] abiomebase = new BiomeBase[]{Biomes.OCEAN}; - - if (jsonobject2.has("biomes")) { - JsonArray jsonarray = jsonobject2.getAsJsonArray("biomes"); - - abiomebase = jsonarray.size() > 0 ? new BiomeBase[jsonarray.size()] : new BiomeBase[]{Biomes.OCEAN}; - - for (int i = 0; i < jsonarray.size(); ++i) { - abiomebase[i] = (BiomeBase) IRegistry.BIOME.getOptional(new MinecraftKey(jsonarray.get(i).getAsString())).orElse(Biomes.OCEAN); - } - } - - if (BiomeLayout.b == biomelayout3) { - BiomeLayoutFixedConfiguration biomelayoutfixedconfiguration2 = ((BiomeLayoutFixedConfiguration) biomelayout.a()).a(abiomebase[0]); - - worldchunkmanager = biomelayout.a(biomelayoutfixedconfiguration2); - } - - if (BiomeLayout.a == biomelayout3) { - int j = jsonobject2.has("size") ? jsonobject2.getAsJsonPrimitive("size").getAsInt() : 2; - BiomeLayoutCheckerboardConfiguration biomelayoutcheckerboardconfiguration = ((BiomeLayoutCheckerboardConfiguration) biomelayout2.a()).a(abiomebase).a(j); - - worldchunkmanager = biomelayout2.a(biomelayoutcheckerboardconfiguration); - } - - if (BiomeLayout.c == biomelayout3) { - BiomeLayoutOverworldConfiguration biomelayoutoverworldconfiguration1 = ((BiomeLayoutOverworldConfiguration) biomelayout1.a()).a(new GeneratorSettingsOverworld()).a(this.b.getWorldData()); - - worldchunkmanager = biomelayout1.a(biomelayoutoverworldconfiguration1); - } - } - - if (worldchunkmanager == null) { - worldchunkmanager = biomelayout.a(((BiomeLayoutFixedConfiguration) biomelayout.a()).a(Biomes.OCEAN)); - } - - IBlockData iblockdata = Blocks.STONE.getBlockData(); - IBlockData iblockdata1 = Blocks.WATER.getBlockData(); - JsonObject jsonobject3 = jsonobject.getAsJsonObject("chunk_generator"); - - if (jsonobject3 != null && jsonobject3.has("options")) { - JsonObject jsonobject4 = jsonobject3.getAsJsonObject("options"); - String s; - - if (jsonobject4.has("default_block")) { - s = jsonobject4.getAsJsonPrimitive("default_block").getAsString(); - iblockdata = ((Block) IRegistry.BLOCK.get(new MinecraftKey(s))).getBlockData(); - } - - if (jsonobject4.has("default_fluid")) { - s = jsonobject4.getAsJsonPrimitive("default_fluid").getAsString(); - iblockdata1 = ((Block) IRegistry.BLOCK.get(new MinecraftKey(s))).getBlockData(); - } - } - - if (jsonobject3 != null && jsonobject3.has("type")) { - ChunkGeneratorType chunkgeneratortype5 = (ChunkGeneratorType) IRegistry.CHUNK_GENERATOR_TYPE.get(new MinecraftKey(jsonobject3.getAsJsonPrimitive("type").getAsString())); - - if (ChunkGeneratorType.b == chunkgeneratortype5) { - GeneratorSettingsNether generatorsettingsnether = (GeneratorSettingsNether) chunkgeneratortype2.a(); - - generatorsettingsnether.a(iblockdata); - generatorsettingsnether.b(iblockdata1); - return chunkgeneratortype2.create(this.b, worldchunkmanager, generatorsettingsnether); - } - - if (ChunkGeneratorType.c == chunkgeneratortype5) { - GeneratorSettingsEnd generatorsettingsend = (GeneratorSettingsEnd) chunkgeneratortype3.a(); - - generatorsettingsend.a(new BlockPosition(0, 64, 0)); - generatorsettingsend.a(iblockdata); - generatorsettingsend.b(iblockdata1); - return chunkgeneratortype3.create(this.b, worldchunkmanager, generatorsettingsend); - } - } - - GeneratorSettingsOverworld generatorsettingsoverworld1 = (GeneratorSettingsOverworld) chunkgeneratortype4.a(); - - generatorsettingsoverworld1.a(iblockdata); - generatorsettingsoverworld1.b(iblockdata1); - return chunkgeneratortype4.create(this.b, worldchunkmanager, generatorsettingsoverworld1); - } - } - - @Nullable - @Override - public BlockPosition a(ChunkCoordIntPair chunkcoordintpair, boolean flag) { - for (int i = chunkcoordintpair.d(); i <= chunkcoordintpair.f(); ++i) { - for (int j = chunkcoordintpair.e(); j <= chunkcoordintpair.g(); ++j) { - BlockPosition blockposition = this.a(i, j, flag); - - if (blockposition != null) { - return blockposition; - } - } - } - - return null; - } - - @Nullable - @Override - public BlockPosition a(int i, int j, boolean flag) { - BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(i, 0, j); - BiomeBase biomebase = this.b.getBiome(blockposition_mutableblockposition); - IBlockData iblockdata = biomebase.q().a(); - - if (flag && !iblockdata.getBlock().a(TagsBlock.VALID_SPAWN)) { - return null; - } else { - Chunk chunk = this.b.getChunkAt(i >> 4, j >> 4); - int k = chunk.a(HeightMap.Type.MOTION_BLOCKING, i & 15, j & 15); - - if (k < 0) { - return null; - } else if (chunk.a(HeightMap.Type.WORLD_SURFACE, i & 15, j & 15) > chunk.a(HeightMap.Type.OCEAN_FLOOR, i & 15, j & 15)) { - return null; - } else { - for (int l = k + 1; l >= 0; --l) { - blockposition_mutableblockposition.d(i, l, j); - IBlockData iblockdata1 = this.b.getType(blockposition_mutableblockposition); - - if (!iblockdata1.p().isEmpty()) { - break; - } - - if (iblockdata1.equals(iblockdata)) { - return blockposition_mutableblockposition.up().immutableCopy(); - } - } - - return null; - } - } - } - - @Override - public float a(long i, float f) { - double d0 = MathHelper.h((double) i / 24000.0D - 0.25D); - double d1 = 0.5D - Math.cos(d0 * 3.141592653589793D) / 2.0D; - - return (float) (d0 * 2.0D + d1) / 3.0F; - } - - @Override - public boolean isOverworld() { - return true; - } - - @Override - public boolean canRespawn() { - return true; - } -} diff --git a/src/main/java/net/minecraft/server/WorldProviderTheEnd.java b/src/main/java/net/minecraft/server/WorldProviderTheEnd.java deleted file mode 100644 index b97408cff..000000000 --- a/src/main/java/net/minecraft/server/WorldProviderTheEnd.java +++ /dev/null @@ -1,95 +0,0 @@ -package net.minecraft.server; - -import java.util.Random; -import javax.annotation.Nullable; - -public class WorldProviderTheEnd extends WorldProvider { - - public static final BlockPosition f = new BlockPosition(100, 50, 0); - private final EnderDragonBattle g; - - public WorldProviderTheEnd(World world, DimensionManager dimensionmanager) { - super(world, dimensionmanager); - NBTTagCompound nbttagcompound = world.getWorldData().a(DimensionManager.THE_END); - - this.g = world instanceof WorldServer ? new EnderDragonBattle((WorldServer) world, nbttagcompound.getCompound("DragonFight")) : null; - } - - @Override - public ChunkGenerator getChunkGenerator() { - GeneratorSettingsEnd generatorsettingsend = (GeneratorSettingsEnd) ChunkGeneratorType.c.a(); - - generatorsettingsend.a(Blocks.END_STONE.getBlockData()); - generatorsettingsend.b(Blocks.AIR.getBlockData()); - generatorsettingsend.a(this.d()); - return ChunkGeneratorType.c.create(this.b, BiomeLayout.d.a(((BiomeLayoutTheEndConfiguration) BiomeLayout.d.a()).a(this.b.getSeed())), generatorsettingsend); - } - - @Override - public float a(long i, float f) { - return 0.5F; // Paper - fix MC-93764 - } - - @Override - public boolean canRespawn() { - return false; - } - - @Override - public boolean isOverworld() { - return false; - } - - @Nullable - @Override - public BlockPosition a(ChunkCoordIntPair chunkcoordintpair, boolean flag) { - Random random = new Random(this.b.getSeed()); - BlockPosition blockposition = new BlockPosition(chunkcoordintpair.d() + random.nextInt(15), 0, chunkcoordintpair.g() + random.nextInt(15)); - - return this.b.i(blockposition).getMaterial().isSolid() ? blockposition : null; - } - - @Override - public BlockPosition d() { - return WorldProviderTheEnd.f; - } - - @Nullable - @Override - public BlockPosition a(int i, int j, boolean flag) { - return this.a(new ChunkCoordIntPair(i >> 4, j >> 4), flag); - } - - // CraftBukkit start - /* - @Override - public DimensionManager getDimensionManager() { - return DimensionManager.THE_END; - } - */ - // CraftBukkit end - - @Override - public void k() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - if (this.g != null) { - nbttagcompound.set("DragonFight", this.g.a()); - } - - this.b.getWorldData().a(DimensionManager.THE_END, nbttagcompound); - } - - @Override - public void l() { - if (this.g != null) { - this.g.b(); - } - - } - - @Nullable - public EnderDragonBattle q() { - return this.g; - } -} diff --git a/src/main/java/net/minecraft/server/WorldServer.java b/src/main/java/net/minecraft/server/WorldServer.java deleted file mode 100644 index 5b18f4bd5..000000000 --- a/src/main/java/net/minecraft/server/WorldServer.java +++ /dev/null @@ -1,2071 +0,0 @@ -package net.minecraft.server; - -import co.aikar.timings.TimingHistory; -import co.aikar.timings.Timings; - -import com.destroystokyo.paper.PaperWorldConfig; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Queues; -import com.google.common.collect.Sets; -import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap.Entry; -import it.unimi.dsi.fastutil.longs.LongSet; -import it.unimi.dsi.fastutil.longs.LongSets; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.Writer; -import java.nio.file.Files; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Queue; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Executor; -import java.util.function.BooleanSupplier; -import java.util.function.Predicate; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -// CraftBukkit start -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.WeatherType; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.server.MapInitializeEvent; -import org.bukkit.event.weather.LightningStrikeEvent; -// CraftBukkit end - -public class WorldServer extends World { - - private static final Logger LOGGER = LogManager.getLogger(); - private final List globalEntityList = Lists.newArrayList(); - public final Int2ObjectMap entitiesById = new Int2ObjectLinkedOpenHashMap(); - private final Map entitiesByUUID = Maps.newHashMap(); - private final Queue entitiesToAdd = Queues.newArrayDeque(); - public final List players = Lists.newArrayList(); // Paper - private -> public - boolean tickingEntities; - private final MinecraftServer server; - private final WorldNBTStorage dataManager; - public boolean savingDisabled; - private boolean C; - private int emptyTime; - private final PortalTravelAgent portalTravelAgent; - private final TickListServer nextTickListBlock; - private final TickListServer nextTickListFluid; - private final Set H; - protected final PersistentRaid c; - private final ObjectLinkedOpenHashSet I; - private boolean ticking; - @Nullable - private final MobSpawnerTrader mobSpawnerTrader; - - // CraftBukkit start - private int tickPosition; - boolean hasPhysicsEvent = true; // Paper - private static Throwable getAddToWorldStackTrace(Entity entity) { - return new Throwable(entity + " Added to world at " + new java.util.Date()); - } - - // Paper start - Asynchronous IO - public final com.destroystokyo.paper.io.PaperFileIOThread.ChunkDataController poiDataController = new com.destroystokyo.paper.io.PaperFileIOThread.ChunkDataController() { - @Override - public void writeData(int x, int z, NBTTagCompound compound) throws java.io.IOException { - WorldServer.this.getChunkProvider().playerChunkMap.getVillagePlace().write(new ChunkCoordIntPair(x, z), compound); - } - - @Override - public NBTTagCompound readData(int x, int z) throws java.io.IOException { - return WorldServer.this.getChunkProvider().playerChunkMap.getVillagePlace().read(new ChunkCoordIntPair(x, z)); - } - - @Override - public T computeForRegionFile(int chunkX, int chunkZ, java.util.function.Function function) { - synchronized (WorldServer.this.getChunkProvider().playerChunkMap.getVillagePlace()) { - RegionFile file; - - try { - file = WorldServer.this.getChunkProvider().playerChunkMap.getVillagePlace().getRegionFile(new ChunkCoordIntPair(chunkX, chunkZ), false); - } catch (java.io.IOException ex) { - throw new RuntimeException(ex); - } - - return function.apply(file); - } - } - - @Override - public T computeForRegionFileIfLoaded(int chunkX, int chunkZ, java.util.function.Function function) { - synchronized (WorldServer.this.getChunkProvider().playerChunkMap.getVillagePlace()) { - RegionFile file = WorldServer.this.getChunkProvider().playerChunkMap.getVillagePlace().getRegionFileIfLoaded(new ChunkCoordIntPair(chunkX, chunkZ)); - return function.apply(file); - } - } - }; - - public final com.destroystokyo.paper.io.PaperFileIOThread.ChunkDataController chunkDataController = new com.destroystokyo.paper.io.PaperFileIOThread.ChunkDataController() { - @Override - public void writeData(int x, int z, NBTTagCompound compound) throws java.io.IOException { - WorldServer.this.getChunkProvider().playerChunkMap.write(new ChunkCoordIntPair(x, z), compound); - } - - @Override - public NBTTagCompound readData(int x, int z) throws java.io.IOException { - return WorldServer.this.getChunkProvider().playerChunkMap.read(new ChunkCoordIntPair(x, z)); - } - - @Override - public T computeForRegionFile(int chunkX, int chunkZ, java.util.function.Function function) { - synchronized (WorldServer.this.getChunkProvider().playerChunkMap) { - RegionFile file; - - try { - file = WorldServer.this.getChunkProvider().playerChunkMap.getRegionFile(new ChunkCoordIntPair(chunkX, chunkZ), false); - } catch (java.io.IOException ex) { - throw new RuntimeException(ex); - } - - return function.apply(file); - } - } - - @Override - public T computeForRegionFileIfLoaded(int chunkX, int chunkZ, java.util.function.Function function) { - synchronized (WorldServer.this.getChunkProvider().playerChunkMap) { - RegionFile file = WorldServer.this.getChunkProvider().playerChunkMap.getRegionFileIfLoaded(new ChunkCoordIntPair(chunkX, chunkZ)); - return function.apply(file); - } - } - }; - public final com.destroystokyo.paper.io.chunk.ChunkTaskManager asyncChunkTaskManager; - // Paper end - // Paper start - @Override - public boolean isChunkLoaded(int x, int z) { - return this.getChunkProvider().getChunkAtIfLoadedImmediately(x, z) != null; - } - // Paper end - - // Add env and gen to constructor - public WorldServer(MinecraftServer minecraftserver, Executor executor, WorldNBTStorage worldnbtstorage, WorldData worlddata, DimensionManager dimensionmanager, GameProfilerFiller gameprofilerfiller, WorldLoadListener worldloadlistener, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen) { - super(worlddata, dimensionmanager, (world, worldprovider) -> { - // CraftBukkit start - ChunkGenerator chunkGenerator; - - if (gen != null) { - chunkGenerator = new org.bukkit.craftbukkit.generator.CustomChunkGenerator(world, world.getSeed(), gen); - } else { - chunkGenerator = worldprovider.getChunkGenerator(); - } - - return new ChunkProviderServer((WorldServer) world, worldnbtstorage.getDirectory(), worldnbtstorage.getDataFixer(), worldnbtstorage.f(), executor, chunkGenerator, world.spigotConfig.viewDistance, worldloadlistener, () -> { // Spigot - return minecraftserver.getWorldServer(DimensionManager.OVERWORLD).getWorldPersistentData(); - }); - // CraftBukkit end - }, gameprofilerfiller, false, gen, env); - this.pvpMode = minecraftserver.getPVP(); - worlddata.world = this; - // CraftBukkit end - this.nextTickListBlock = new TickListServer<>(this, (block) -> { - return block == null || block.getBlockData().isAir(); - }, IRegistry.BLOCK::getKey, IRegistry.BLOCK::get, this::b, "Blocks"); // Paper - Timings - this.nextTickListFluid = new TickListServer<>(this, (fluidtype) -> { - return fluidtype == null || fluidtype == FluidTypes.EMPTY; - }, IRegistry.FLUID::getKey, IRegistry.FLUID::get, this::a, "Fluids"); // Paper - Timings - this.H = Sets.newHashSet(); - this.I = new ObjectLinkedOpenHashSet(); - this.dataManager = worldnbtstorage; - this.server = minecraftserver; - this.portalTravelAgent = new PortalTravelAgent(this); - this.M(); - this.N(); - this.getWorldBorder().a(minecraftserver.aw()); - this.c = (PersistentRaid) this.getWorldPersistentData().a(() -> { - return new PersistentRaid(this); - }, PersistentRaid.a(this.worldProvider)); - if (!minecraftserver.isEmbeddedServer()) { - this.getWorldData().setGameType(minecraftserver.getGamemode()); - } - - this.mobSpawnerTrader = this.worldProvider.getDimensionManager().getType() == DimensionManager.OVERWORLD ? new MobSpawnerTrader(this) : null; // CraftBukkit - getType() - this.getServer().addWorld(this.getWorld()); // CraftBukkit - - this.asyncChunkTaskManager = new com.destroystokyo.paper.io.chunk.ChunkTaskManager(this); // Paper - } - - // CraftBukkit start - @Override - public TileEntity getTileEntity(BlockPosition pos) { - TileEntity result = super.getTileEntity(pos); - if (Thread.currentThread() != this.serverThread) { - // SPIGOT-5378: avoid deadlock, this can be called in loading logic (i.e lighting) but getType() will block on chunk load - return result; - } - Block type = getType(pos).getBlock(); - - if (result != null && type != Blocks.AIR) { - if (!result.q().a(type)) { - 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(), type, found}); - - if (type instanceof ITileEntity) { - TileEntity replacement = ((ITileEntity) type).createTile(this); - replacement.world = this; - this.setTileEntity(pos, replacement); - return replacement; - } else { - return found; - } - } - // CraftBukkit end - - public void doTick(BooleanSupplier booleansupplier) { - GameProfilerFiller gameprofilerfiller = this.getMethodProfiler(); - - this.ticking = true; - gameprofilerfiller.enter("world border"); - this.getWorldBorder().s(); - gameprofilerfiller.exitEnter("weather"); - boolean flag = this.isRaining(); - int i; - - if (this.worldProvider.g()) { - if (this.getGameRules().getBoolean(GameRules.DO_WEATHER_CYCLE)) { - int j = this.worldData.z(); - - i = this.worldData.getThunderDuration(); - int k = this.worldData.getWeatherDuration(); - boolean flag1 = this.worldData.isThundering(); - boolean flag2 = this.worldData.hasStorm(); - - if (j > 0) { - --j; - i = flag1 ? 0 : 1; - k = flag2 ? 0 : 1; - flag1 = false; - flag2 = false; - } else { - if (i > 0) { - --i; - if (i == 0) { - flag1 = !flag1; - } - } else if (flag1) { - i = this.random.nextInt(12000) + 3600; - } else { - i = this.random.nextInt(168000) + 12000; - } - - if (k > 0) { - --k; - if (k == 0) { - flag2 = !flag2; - } - } else if (flag2) { - k = this.random.nextInt(12000) + 12000; - } else { - k = this.random.nextInt(168000) + 12000; - } - } - - this.worldData.setThunderDuration(i); - this.worldData.setWeatherDuration(k); - this.worldData.g(j); - this.worldData.setThundering(flag1); - this.worldData.setStorm(flag2); - } - - this.lastThunderLevel = this.thunderLevel; - if (this.worldData.isThundering()) { - this.thunderLevel = (float) ((double) this.thunderLevel + 0.01D); - } else { - this.thunderLevel = (float) ((double) this.thunderLevel - 0.01D); - } - - this.thunderLevel = MathHelper.a(this.thunderLevel, 0.0F, 1.0F); - this.lastRainLevel = this.rainLevel; - if (this.worldData.hasStorm()) { - this.rainLevel = (float) ((double) this.rainLevel + 0.01D); - } else { - this.rainLevel = (float) ((double) this.rainLevel - 0.01D); - } - - this.rainLevel = MathHelper.a(this.rainLevel, 0.0F, 1.0F); - } - - /* CraftBukkit start - if (this.lastRainLevel != this.rainLevel) { - this.server.getPlayerList().a((Packet) (new PacketPlayOutGameStateChange(7, this.rainLevel)), this.worldProvider.getDimensionManager()); - } - - if (this.lastThunderLevel != this.thunderLevel) { - this.server.getPlayerList().a((Packet) (new PacketPlayOutGameStateChange(8, this.thunderLevel)), this.worldProvider.getDimensionManager()); - } - - if (flag != this.isRaining()) { - if (flag) { - this.server.getPlayerList().sendAll(new PacketPlayOutGameStateChange(2, 0.0F)); - } else { - this.server.getPlayerList().sendAll(new PacketPlayOutGameStateChange(1, 0.0F)); - } - - this.server.getPlayerList().sendAll(new PacketPlayOutGameStateChange(7, this.rainLevel)); - this.server.getPlayerList().sendAll(new PacketPlayOutGameStateChange(8, this.thunderLevel)); - } - // */ - for (int idx = 0; idx < this.players.size(); ++idx) { - if (((EntityPlayer) this.players.get(idx)).world == this) { - ((EntityPlayer) this.players.get(idx)).tickWeather(); - } - } - - if (flag != this.isRaining()) { - // Only send weather packets to those affected - for (int idx = 0; idx < this.players.size(); ++idx) { - if (((EntityPlayer) this.players.get(idx)).world == this) { - ((EntityPlayer) this.players.get(idx)).setPlayerWeather((!flag ? WeatherType.DOWNFALL : WeatherType.CLEAR), false); - } - } - } - for (int idx = 0; idx < this.players.size(); ++idx) { - if (((EntityPlayer) this.players.get(idx)).world == this) { - ((EntityPlayer) this.players.get(idx)).updateWeather(this.lastRainLevel, this.rainLevel, this.lastThunderLevel, this.thunderLevel); - } - } - // CraftBukkit end - - if (this.getWorldData().isHardcore() && this.getDifficulty() != EnumDifficulty.HARD) { - this.getWorldData().setDifficulty(EnumDifficulty.HARD); - } - - if (this.C && this.players.stream().noneMatch((entityplayer) -> { - return !entityplayer.isSpectator() && !entityplayer.isDeeplySleeping() && !entityplayer.fauxSleeping; // CraftBukkit - })) { - this.C = false; - if (this.getGameRules().getBoolean(GameRules.DO_DAYLIGHT_CYCLE)) { - long l = this.worldData.getDayTime() + 24000L; - - this.setDayTime(l - l % 24000L); - } - - this.players.stream().filter(EntityLiving::isSleeping).forEach((entityplayer) -> { - entityplayer.wakeup(false, false, true); - }); - if (this.getGameRules().getBoolean(GameRules.DO_WEATHER_CYCLE)) { - this.clearWeather(); - } - } - - this.M(); - this.a(); - gameprofilerfiller.exitEnter("chunkSource"); - this.timings.chunkProviderTick.startTiming(); // Paper - timings - this.getChunkProvider().tick(booleansupplier); - this.timings.chunkProviderTick.stopTiming(); // Paper - timings - gameprofilerfiller.exitEnter("tickPending"); - timings.scheduledBlocks.startTiming(); // Spigot - if (this.worldData.getType() != WorldType.DEBUG_ALL_BLOCK_STATES) { - this.nextTickListBlock.b(); - this.nextTickListFluid.b(); - } - timings.scheduledBlocks.stopTiming(); // Spigot - - gameprofilerfiller.exitEnter("portalForcer"); - timings.doPortalForcer.startTiming(); // Spigot - this.portalTravelAgent.a(this.getTime()); - timings.doPortalForcer.stopTiming(); // Spigot - gameprofilerfiller.exitEnter("raid"); - this.timings.raids.startTiming(); // Paper - timings - this.c.a(); - if (this.mobSpawnerTrader != null) { - this.mobSpawnerTrader.a(); - } - this.timings.raids.stopTiming(); // Paper - timings - - gameprofilerfiller.exitEnter("blockEvents"); - timings.doSounds.startTiming(); // Spigot - this.ae(); - timings.doSounds.stopTiming(); // Spigot - this.ticking = false; - gameprofilerfiller.exitEnter("entities"); - boolean flag3 = true || !this.players.isEmpty() || !this.getForceLoadedChunks().isEmpty(); // CraftBukkit - this prevents entity cleanup, other issues on servers with no players - - if (flag3) { - this.resetEmptyTime(); - } - - if (flag3 || this.emptyTime++ < 300) { - timings.tickEntities.startTiming(); // Spigot - this.worldProvider.l(); - gameprofilerfiller.enter("global"); - - Entity entity; - - for (i = 0; i < this.globalEntityList.size(); ++i) { - entity = (Entity) this.globalEntityList.get(i); - // CraftBukkit start - Fixed an NPE - if (entity == null) { - continue; - } - // CraftBukkit end - this.a((entity1) -> { - ++entity1.ticksLived; - entity1.tick(); - }, entity); - if (entity.dead) { - this.globalEntityList.remove(i--); - } - } - - gameprofilerfiller.exitEnter("regular"); - this.tickingEntities = true; - ObjectIterator objectiterator = this.entitiesById.int2ObjectEntrySet().iterator(); - - org.spigotmc.ActivationRange.activateEntities(this); // Spigot - timings.entityTick.startTiming(); // Spigot - TimingHistory.entityTicks += this.globalEntityList.size(); // Paper - while (objectiterator.hasNext()) { - Entry entry = (Entry) objectiterator.next(); - Entity entity1 = (Entity) entry.getValue(); - Entity entity2 = entity1.getVehicle(); - - /* CraftBukkit start - We prevent spawning in general, so this butchering is not needed - if (!this.server.getSpawnAnimals() && (entity1 instanceof EntityAnimal || entity1 instanceof EntityWaterAnimal)) { - entity1.die(); - } - - if (!this.server.getSpawnNPCs() && entity1 instanceof NPC) { - entity1.die(); - } - // CraftBukkit end */ - - if (entity2 != null) { - if (!entity2.dead && entity2.w(entity1)) { - continue; - } - - entity1.stopRiding(); - } - - gameprofilerfiller.enter("tick"); - if (!entity1.dead && !(entity1 instanceof EntityComplexPart)) { - this.a(this::entityJoinedWorld, entity1); - ++TimingHistory.entityTicks; // Paper - } - - gameprofilerfiller.exit(); - gameprofilerfiller.enter("remove"); - if (entity1.dead) { - this.removeEntityFromChunk(entity1); - objectiterator.remove(); - this.unregisterEntity(entity1); - } - - gameprofilerfiller.exit(); - } - timings.entityTick.stopTiming(); // Spigot - - this.tickingEntities = false; - - try (co.aikar.timings.Timing ignored = this.timings.newEntities.startTiming()) { // Paper - timings - while ((entity = (Entity) this.entitiesToAdd.poll()) != null) { - this.registerEntity(entity); - } - } // Paper - timings - - gameprofilerfiller.exit(); - timings.tickEntities.stopTiming(); // Spigot - this.tickBlockEntities(); - } - - gameprofilerfiller.exit(); - } - - public void a(Chunk chunk, int i) { - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - boolean flag = this.isRaining(); - int j = chunkcoordintpair.d(); - int k = chunkcoordintpair.e(); - GameProfilerFiller gameprofilerfiller = this.getMethodProfiler(); - - gameprofilerfiller.enter("thunder"); - BlockPosition blockposition; - - if (!this.paperConfig.disableThunder && flag && this.U() && this.random.nextInt(100000) == 0) { // Paper - Disable thunder - blockposition = this.a(this.a(j, 0, k, 15)); - if (this.isRainingAt(blockposition)) { - DifficultyDamageScaler difficultydamagescaler = this.getDamageScaler(blockposition); - boolean flag1 = this.getGameRules().getBoolean(GameRules.DO_MOB_SPAWNING) && this.random.nextDouble() < (double) difficultydamagescaler.b() * paperConfig.skeleHorseSpawnChance; // Paper - - if (flag1) { - EntityHorseSkeleton entityhorseskeleton = (EntityHorseSkeleton) EntityTypes.SKELETON_HORSE.a((World) this); - - entityhorseskeleton.r(true); - entityhorseskeleton.setAgeRaw(0); - entityhorseskeleton.setPosition((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()); - this.addEntity(entityhorseskeleton, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.LIGHTNING); // CraftBukkit - } - - this.strikeLightning(new EntityLightning(this, (double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, flag1), org.bukkit.event.weather.LightningStrikeEvent.Cause.WEATHER); // CraftBukkit - } - } - - gameprofilerfiller.exitEnter("iceandsnow"); - if (!this.paperConfig.disableIceAndSnow && this.random.nextInt(16) == 0) { // Paper - Disable ice and snow - blockposition = this.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, this.a(j, 0, k, 15)); - BlockPosition blockposition1 = blockposition.down(); - BiomeBase biomebase = this.getBiome(blockposition); - - if (biomebase.a((IWorldReader) this, blockposition1)) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(this, blockposition1, Blocks.ICE.getBlockData(), null); // CraftBukkit - } - - if (flag && biomebase.b(this, blockposition)) { - org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockFormEvent(this, blockposition, Blocks.SNOW.getBlockData(), null); // CraftBukkit - } - - if (flag && this.getBiome(blockposition1).b() == BiomeBase.Precipitation.RAIN) { - this.getType(blockposition1).getBlock().c((World) this, blockposition1); - } - } - - gameprofilerfiller.exitEnter("tickBlocks"); - timings.chunkTicksBlocks.startTiming(); // Paper - if (i > 0) { - ChunkSection[] achunksection = chunk.getSections(); - int l = achunksection.length; - - for (int i1 = 0; i1 < l; ++i1) { - ChunkSection chunksection = achunksection[i1]; - - if (chunksection != Chunk.a && chunksection.d()) { - int j1 = chunksection.getYPosition(); - - for (int k1 = 0; k1 < i; ++k1) { - BlockPosition blockposition2 = this.a(j, j1, k, 15); - - gameprofilerfiller.enter("randomTick"); - IBlockData iblockdata = chunksection.getType(blockposition2.getX() - j, blockposition2.getY() - j1, blockposition2.getZ() - k); - - if (iblockdata.q()) { - iblockdata.getBlock().randomTick = true; // Paper - fix MC-113809 - iblockdata.b((World) this, blockposition2, this.random); - iblockdata.getBlock().randomTick = false; // Paper - fix MC-113809 - } - - Fluid fluid = iblockdata.p(); - - if (fluid.h()) { - fluid.b(this, blockposition2, this.random); - } - - gameprofilerfiller.exit(); - } - } - } - } - timings.chunkTicksBlocks.stopTiming(); // Paper - gameprofilerfiller.exit(); - } - - protected BlockPosition a(BlockPosition blockposition) { - BlockPosition blockposition1 = this.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, blockposition); - AxisAlignedBB axisalignedbb = (new AxisAlignedBB(blockposition1, new BlockPosition(blockposition1.getX(), this.getBuildHeight(), blockposition1.getZ()))).g(3.0D); - List list = this.a(EntityLiving.class, axisalignedbb, (java.util.function.Predicate) (entityliving) -> { // CraftBukkit - decompile error - return entityliving != null && entityliving.isAlive() && this.f(entityliving.getChunkCoordinates()); - }); - - if (!list.isEmpty()) { - return ((EntityLiving) list.get(this.random.nextInt(list.size()))).getChunkCoordinates(); - } else { - if (blockposition1.getY() == -1) { - blockposition1 = blockposition1.up(2); - } - - return blockposition1; - } - } - - public boolean b() { - return this.ticking; - } - - public void everyoneSleeping() { - this.C = false; - if (!this.players.isEmpty()) { - int i = 0; - int j = 0; - Iterator iterator = this.players.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - if (entityplayer.isSpectator() || (entityplayer.fauxSleeping && !entityplayer.isSleeping())) { // CraftBukkit - ++i; - } else if (entityplayer.isSleeping()) { - ++j; - } - } - - this.C = j > 0 && j >= this.players.size() - i; - } - - } - - @Override - public ScoreboardServer getScoreboard() { - return this.server.getScoreboard(); - } - - private void clearWeather() { - // CraftBukkit start - this.worldData.setStorm(false); - // 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 (!this.worldData.hasStorm()) { - this.worldData.setWeatherDuration(0); - } - // CraftBukkit end - this.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 (!this.worldData.isThundering()) { - this.worldData.setThunderDuration(0); - } - // CraftBukkit end - } - - public void resetEmptyTime() { - this.emptyTime = 0; - } - - private void a(NextTickListEntry nextticklistentry) { - Fluid fluid = this.getFluid(nextticklistentry.a); - - if (fluid.getType() == nextticklistentry.b()) { - fluid.a((World) this, nextticklistentry.a); - } - - } - - private void b(NextTickListEntry nextticklistentry) { - IBlockData iblockdata = this.getType(nextticklistentry.a); - - if (iblockdata.getBlock() == nextticklistentry.b()) { - iblockdata.a((World) this, nextticklistentry.a, this.random); - } - - } - - public void entityJoinedWorld(Entity entity) { - if (entity instanceof EntityHuman || this.getChunkProvider().a(entity)) { - // Spigot start - if (!org.spigotmc.ActivationRange.checkIfActive(entity)) { - entity.ticksLived++; - entity.inactiveTick(); - return; - } - // Spigot end - - entity.tickTimer.startTiming(); // Spigot - entity.H = entity.locX; - entity.I = entity.locY; - entity.J = entity.locZ; - entity.lastYaw = entity.yaw; - entity.lastPitch = entity.pitch; - if (entity.inChunk) { - ++entity.ticksLived; - this.getMethodProfiler().a(() -> { - return IRegistry.ENTITY_TYPE.getKey(entity.getEntityType()).toString(); - }); - entity.tick(); - entity.postTick(); // CraftBukkit - this.getMethodProfiler().exit(); - } - - this.chunkCheck(entity); - if (entity.inChunk) { - Iterator iterator = entity.getPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity1 = (Entity) iterator.next(); - - this.a(entity, entity1); - } - } - entity.tickTimer.stopTiming(); // Spigot - - } - } - - public void a(Entity entity, Entity entity1) { - if (!entity1.dead && entity1.getVehicle() == entity) { - if (entity1 instanceof EntityHuman || this.getChunkProvider().a(entity1)) { - entity1.H = entity1.locX; - entity1.I = entity1.locY; - entity1.J = entity1.locZ; - entity1.lastYaw = entity1.yaw; - entity1.lastPitch = entity1.pitch; - if (entity1.inChunk) { - ++entity1.ticksLived; - entity1.passengerTick(); - } - - this.chunkCheck(entity1); - if (entity1.inChunk) { - Iterator iterator = entity1.getPassengers().iterator(); - - while (iterator.hasNext()) { - Entity entity2 = (Entity) iterator.next(); - - this.a(entity1, entity2); - } - } - - } - } else { - entity1.stopRiding(); - } - } - - public void chunkCheck(Entity entity) { - this.getMethodProfiler().enter("chunkCheck"); - int i = MathHelper.floor(entity.locX / 16.0D); - int j = Math.min(15, Math.max(0, MathHelper.floor(entity.locY / 16.0D))); // Paper - stay consistent with chunk add/remove behavior - int k = MathHelper.floor(entity.locZ / 16.0D); - - if (!entity.inChunk || entity.chunkX != i || entity.chunkY != j || entity.chunkZ != k) { - if (entity.inChunk && this.isChunkLoaded(entity.chunkX, entity.chunkZ)) { - this.getChunkAt(entity.chunkX, entity.chunkZ).a(entity, entity.chunkY); - } - - if (!entity.valid && !entity.bU() && !this.isChunkLoaded(i, k)) { // Paper - always load chunks to register valid entities location - entity.inChunk = false; - } else { - this.getChunkAt(i, k).a(entity); - } - } - - this.getMethodProfiler().exit(); - } - - @Override - public boolean a(EntityHuman entityhuman, BlockPosition blockposition) { - return !this.server.a(this, blockposition, entityhuman) && this.getWorldBorder().a(blockposition); - } - - public void a(WorldSettings worldsettings) { - if (!this.worldProvider.canRespawn()) { - this.worldData.setSpawn(BlockPosition.ZERO.up(this.chunkProvider.getChunkGenerator().getSpawnHeight())); - } else if (this.worldData.getType() == WorldType.DEBUG_ALL_BLOCK_STATES) { - this.worldData.setSpawn(BlockPosition.ZERO.up()); - } else { - // CraftBukkit start - if (this.generator != null) { - Random rand = new Random(this.getSeed()); - org.bukkit.Location spawn = this.generator.getFixedSpawnLocation(((WorldServer) this).getWorld(), rand); - - if (spawn != null) { - if (spawn.getWorld() != ((WorldServer) this).getWorld()) { - throw new IllegalStateException("Cannot set spawn point for " + this.worldData.getName() + " to be in another world (" + spawn.getWorld().getName() + ")"); - } else { - this.worldData.setSpawn(new BlockPosition(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ())); - return; - } - } - } - // CraftBukkit end - - // Paper start - this is useless if craftbukkit returns early - WorldChunkManager worldchunkmanager = this.chunkProvider.getChunkGenerator().getWorldChunkManager(); - List list = worldchunkmanager.a(); - Random random = new Random(this.getSeed()); - BlockPosition blockposition = worldchunkmanager.a(0, 0, 256, list, random); - ChunkCoordIntPair chunkcoordintpair = blockposition == null ? new ChunkCoordIntPair(0, 0) : new ChunkCoordIntPair(blockposition); - // Paper end - - if (blockposition == null) { - WorldServer.LOGGER.warn("Unable to find spawn biome"); - } - - boolean flag = false; - Iterator iterator = TagsBlock.VALID_SPAWN.a().iterator(); - - while (iterator.hasNext()) { - Block block = (Block) iterator.next(); - - if (worldchunkmanager.b().contains(block.getBlockData())) { - flag = true; - break; - } - } - - this.worldData.setSpawn(chunkcoordintpair.l().b(8, this.chunkProvider.getChunkGenerator().getSpawnHeight(), 8)); - int i = 0; - int j = 0; - int k = 0; - int l = -1; - boolean flag1 = true; - - for (int i1 = 0; i1 < 1024; ++i1) { - if (i > -16 && i <= 16 && j > -16 && j <= 16) { - BlockPosition blockposition1 = this.worldProvider.a(new ChunkCoordIntPair(chunkcoordintpair.x + i, chunkcoordintpair.z + j), flag); - - if (blockposition1 != null) { - this.worldData.setSpawn(blockposition1); - break; - } - } - - if (i == j || i < 0 && i == -j || i > 0 && i == 1 - j) { - int j1 = k; - - k = -l; - l = j1; - } - - i += k; - j += l; - } - - if (worldsettings.c()) { - this.g(); - } - - } - } - - protected void g() { - WorldGenBonusChest worldgenbonuschest = WorldGenerator.BONUS_CHEST; - - for (int i = 0; i < 10; ++i) { - int j = this.worldData.b() + this.random.nextInt(6) - this.random.nextInt(6); - int k = this.worldData.d() + this.random.nextInt(6) - this.random.nextInt(6); - BlockPosition blockposition = this.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, new BlockPosition(j, 0, k)).up(); - - if (worldgenbonuschest.a(this, this.chunkProvider.getChunkGenerator(), this.random, blockposition, WorldGenFeatureConfiguration.e)) { - break; - } - } - - } - - @Nullable - public BlockPosition getDimensionSpawn() { - return this.worldProvider.d(); - } - - // Paper start - derived from below - public void saveIncrementally(boolean doFull) throws ExceptionWorldConflict { - ChunkProviderServer chunkproviderserver = this.getChunkProvider(); - - if (doFull) { - org.bukkit.Bukkit.getPluginManager().callEvent(new org.bukkit.event.world.WorldSaveEvent(getWorld())); - } - - try (co.aikar.timings.Timing ignored = timings.worldSave.startTiming()) { - if (doFull) { - this.k_(); - } - - timings.worldSaveChunks.startTiming(); // Paper - if (!this.isSavingDisabled()) chunkproviderserver.saveIncrementally(); - timings.worldSaveChunks.stopTiming(); // Paper - - - // CraftBukkit start - moved from MinecraftServer.saveChunks - // PAIL - rename - if (doFull) { - WorldServer worldserver1 = this; - WorldData worlddata = worldserver1.getWorldData(); - - worldserver1.getWorldBorder().a(worlddata); - worlddata.c(this.server.getBossBattleCustomData().c()); - worldserver1.getDataManager().saveWorldData(worlddata, this.server.getPlayerList().r()); - // CraftBukkit end - } - } - } - // Paper end - - public void save(@Nullable IProgressUpdate iprogressupdate, boolean flag, boolean flag1) throws ExceptionWorldConflict { - ChunkProviderServer chunkproviderserver = this.getChunkProvider(); - - if (!flag1) { - if (flag) org.bukkit.Bukkit.getPluginManager().callEvent(new org.bukkit.event.world.WorldSaveEvent(getWorld())); // CraftBukkit - try (co.aikar.timings.Timing ignored = timings.worldSave.startTiming()) { // Paper - if (iprogressupdate != null) { - iprogressupdate.a(new ChatMessage("menu.savingLevel", new Object[0])); - } - - this.k_(); - if (iprogressupdate != null) { - iprogressupdate.c(new ChatMessage("menu.savingChunks", new Object[0])); - } - - timings.worldSaveChunks.startTiming(); // Paper - chunkproviderserver.save(flag); - timings.worldSaveChunks.stopTiming(); // Paper - } // Paper - } - - // CraftBukkit start - moved from MinecraftServer.saveChunks - // PAIL - rename - WorldServer worldserver1 = this; - WorldData worlddata = worldserver1.getWorldData(); - - worldserver1.getWorldBorder().a(worlddata); - worlddata.c(this.server.getBossBattleCustomData().c()); - worldserver1.getDataManager().saveWorldData(worlddata, this.server.getPlayerList().r()); - // CraftBukkit end - } - - protected void k_() throws ExceptionWorldConflict { - this.checkSession(); - this.worldProvider.k(); - this.getChunkProvider().getWorldPersistentData().a(); - } - - public List a(@Nullable EntityTypes entitytypes, Predicate predicate) { - List list = Lists.newArrayList(); - ChunkProviderServer chunkproviderserver = this.getChunkProvider(); - ObjectIterator objectiterator = this.entitiesById.values().iterator(); - - while (objectiterator.hasNext()) { - Entity entity = (Entity) objectiterator.next(); - - if ((entitytypes == null || entity.getEntityType() == entitytypes) && chunkproviderserver.isLoaded(MathHelper.floor(entity.locX) >> 4, MathHelper.floor(entity.locZ) >> 4) && predicate.test(entity)) { - list.add(entity); - } - } - - return list; - } - - public List j() { - List list = Lists.newArrayList(); - ObjectIterator objectiterator = this.entitiesById.values().iterator(); - - while (objectiterator.hasNext()) { - Entity entity = (Entity) objectiterator.next(); - - if (entity instanceof EntityEnderDragon && entity.isAlive()) { - list.add((EntityEnderDragon) entity); - } - } - - return list; - } - - public List a(Predicate predicate) { - List list = Lists.newArrayList(); - Iterator iterator = this.players.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - if (predicate.test(entityplayer)) { - list.add(entityplayer); - } - } - - return list; - } - - @Nullable - public EntityPlayer l_() { - List list = this.a(EntityLiving::isAlive); - - return list.isEmpty() ? null : (EntityPlayer) list.get(this.random.nextInt(list.size())); - } - - public Object2IntMap l() { - // Paper start - int[] values = this.countMobs(false); - EnumCreatureType[] byId = EnumCreatureType.values(); - Object2IntMap ret = new Object2IntOpenHashMap<>(); - - for (int i = 0, len = values.length; i < len; ++i) { - ret.put(byId[i], values[i]); - } - - return ret; - } - public int[] countMobs(boolean updatePlayerCounts) { - int[] ret = new int[EntityPlayer.ENUMCREATURETYPE_TOTAL_ENUMS]; - // Paper end - ObjectIterator objectiterator = this.entitiesById.values().iterator(); - - while (objectiterator.hasNext()) { - Entity entity = (Entity) objectiterator.next(); - if (entity.shouldBeRemoved) continue; // Paper - if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - - // CraftBukkit - Split out persistent check, don't apply it to special persistent mobs - if (entityinsentient.isTypeNotPersistent(0) && entityinsentient.isPersistent()) { - continue; - } - } - - EnumCreatureType enumcreaturetype = entity.getEntityType().e(); - - if (enumcreaturetype != EnumCreatureType.MISC && this.getChunkProvider().b(entity)) { - // Paper start - Only count natural spawns - if (!this.paperConfig.countAllMobsForSpawning && - !(entity.spawnReason == CreatureSpawnEvent.SpawnReason.NATURAL || - entity.spawnReason == CreatureSpawnEvent.SpawnReason.CHUNK_GEN)) { - continue; - } - // Paper end - // Paper start - rework mob spawning - if (updatePlayerCounts) { - this.getChunkProvider().playerChunkMap.updatePlayerMobTypeMap(entity); - } - ++ret[enumcreaturetype.ordinal()]; - // Paper end - } - } - - return ret; - } - - @Override - public boolean addEntity(Entity entity) { - // CraftBukkit start - return this.addEntity0(entity, CreatureSpawnEvent.SpawnReason.DEFAULT); - } - - @Override - public boolean addEntity(Entity entity, CreatureSpawnEvent.SpawnReason reason) { - return this.addEntity0(entity, reason); - // CraftBukkit end - } - - public boolean addEntitySerialized(Entity entity) { - // CraftBukkit start - return this.addEntitySerialized(entity, CreatureSpawnEvent.SpawnReason.DEFAULT); - } - - public boolean addEntitySerialized(Entity entity, CreatureSpawnEvent.SpawnReason reason) { - return this.addEntity0(entity, reason); - // CraftBukkit end - } - - public void addEntityTeleport(Entity entity) { - boolean flag = entity.attachedToPlayer; - - entity.attachedToPlayer = true; - this.addEntitySerialized(entity); - entity.attachedToPlayer = flag; - this.chunkCheck(entity); - } - - public void addPlayerCommand(EntityPlayer entityplayer) { - this.addPlayer0(entityplayer); - this.chunkCheck(entityplayer); - } - - public void addPlayerPortal(EntityPlayer entityplayer) { - this.addPlayer0(entityplayer); - this.chunkCheck(entityplayer); - } - - public void addPlayerJoin(EntityPlayer entityplayer) { - this.addPlayer0(entityplayer); - } - - public void addPlayerRespawn(EntityPlayer entityplayer) { - this.addPlayer0(entityplayer); - } - - private void addPlayer0(EntityPlayer entityplayer) { - Entity entity = (Entity) this.entitiesByUUID.get(entityplayer.getUniqueID()); - - if (entity != null) { - WorldServer.LOGGER.warn("Force-added player with duplicate UUID {}", entityplayer.getUniqueID().toString()); - entity.decouple(); - this.removePlayer((EntityPlayer) entity); - } - - this.players.add(entityplayer); - this.everyoneSleeping(); - IChunkAccess ichunkaccess = this.getChunkAt(MathHelper.floor(entityplayer.locX / 16.0D), MathHelper.floor(entityplayer.locZ / 16.0D), ChunkStatus.FULL, true); - - if (ichunkaccess instanceof Chunk) { - ichunkaccess.a((Entity) entityplayer); - } - - this.registerEntity(entityplayer); - } - - // CraftBukkit start - private boolean addEntity0(Entity entity, CreatureSpawnEvent.SpawnReason spawnReason) { - org.spigotmc.AsyncCatcher.catchOp("entity add"); // Spigot - if (entity.spawnReason == null) entity.spawnReason = spawnReason; // Paper - // Paper start - if (entity.valid) { - MinecraftServer.LOGGER.error("Attempted Double World add on " + entity, new Throwable()); - - if (DEBUG_ENTITIES) { - Throwable thr = entity.addedToWorldStack; - if (thr == null) { - MinecraftServer.LOGGER.error("Double add entity has no add stacktrace"); - } else { - MinecraftServer.LOGGER.error("Double add stacktrace: ", thr); - } - } - return true; - } - // Paper end - if (entity.dead) { - // Paper start - if (DEBUG_ENTITIES) { - new Throwable("Tried to add entity " + entity + " but it was marked as removed already").printStackTrace(); // CraftBukkit - getAddToWorldStackTrace(entity).printStackTrace(); - } - // Paper end - // WorldServer.LOGGER.warn("Tried to add entity {} but it was marked as removed already", EntityTypes.getName(entity.getEntityType())); // CraftBukkit - return false; - } else if (this.isUUIDTaken(entity)) { - return false; - } else { - if (!CraftEventFactory.doEntityAddEventCalling(this, entity, spawnReason)) { - return false; - } - // CraftBukkit end - IChunkAccess ichunkaccess = this.getChunkAt(MathHelper.floor(entity.locX / 16.0D), MathHelper.floor(entity.locZ / 16.0D), ChunkStatus.FULL, true); // Paper - always load chunks for entity adds - - if (!(ichunkaccess instanceof Chunk)) { - return false; - } else { - ichunkaccess.a(entity); - this.registerEntity(entity); - return true; - } - } - } - - public boolean addEntityChunk(Entity entity) { - if (this.isUUIDTaken(entity)) { - return false; - } else { - this.registerEntity(entity); - return true; - } - } - - private boolean isUUIDTaken(Entity entity) { - Entity entity1 = (Entity) this.entitiesByUUID.get(entity.getUniqueID()); - - if (entity1 == null) { - return false; - } else { - // Paper start - if (entity1.dead) { - unregisterEntity(entity1); // remove the existing entity - return false; - } - - if (DEBUG_ENTITIES && entity.world.paperConfig.duplicateUUIDMode != PaperWorldConfig.DuplicateUUIDMode.NOTHING) { - WorldServer.LOGGER.error("Keeping entity {} that already exists with UUID {}", EntityTypes.getName(entity1.getEntityType()), entity.getUniqueID().toString()); // CraftBukkit // paper - WorldServer.LOGGER.error("Deleting duplicate entity {}", entity); // CraftBukkit // paper - - if (entity1.addedToWorldStack != null) { - entity1.addedToWorldStack.printStackTrace(); - } - - getAddToWorldStackTrace(entity).printStackTrace(); - } - // Paper end - return true; - } - } - - public void unloadChunk(Chunk chunk) { - // Spigot Start - for (TileEntity tileentity : chunk.getTileEntities().values()) - { - if ( tileentity instanceof IInventory ) - { - for ( org.bukkit.entity.HumanEntity h : Lists.newArrayList((List) ( (IInventory) tileentity ).getViewers() ) ) - { - if ( h instanceof org.bukkit.craftbukkit.entity.CraftHumanEntity ) - { - ( (org.bukkit.craftbukkit.entity.CraftHumanEntity) h).getHandle().closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.UNLOADED); // Paper - } - } - } - } - // Spigot End - this.tileEntityListUnload.addAll(chunk.getTileEntities().values()); - List[] aentityslice = chunk.getEntitySlices(); // Spigot - int i = aentityslice.length; - - for (int j = 0; j < i; ++j) { - List entityslice = aentityslice[j]; // Spigot - Iterator iterator = entityslice.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - // Spigot Start - if ( entity instanceof IInventory ) - { - for ( org.bukkit.entity.HumanEntity h : Lists.newArrayList( (List) ( (IInventory) entity ).getViewers() ) ) - { - if ( h instanceof org.bukkit.craftbukkit.entity.CraftHumanEntity ) - { - ( (org.bukkit.craftbukkit.entity.CraftHumanEntity) h).getHandle().closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.UNLOADED); // Paper - } - } - } - // Spigot End - - if (!(entity instanceof EntityPlayer)) { - if (this.tickingEntities) { - throw new IllegalStateException("Removing entity while ticking!"); - } - - this.entitiesById.remove(entity.getId()); - this.unregisterEntity(entity); - } - } - } - - } - - public void unregisterEntity(Entity entity) { - org.spigotmc.AsyncCatcher.catchOp("entity unregister"); // Spigot - // Spigot start - if ( entity instanceof EntityHuman ) - { - this.getMinecraftServer().worldServer.values().stream().map( WorldServer::getWorldPersistentData ).forEach( (worldData) -> - { - for (Object o : worldData.data.values() ) - { - if ( o instanceof WorldMap ) - { - WorldMap map = (WorldMap) o; - map.humans.remove( (EntityHuman) entity ); - for ( Iterator iter = (Iterator) map.i.iterator(); iter.hasNext(); ) - { - if ( iter.next().trackee == entity ) - { - map.decorations.remove(entity.getDisplayName().getString()); // Paper - iter.remove(); - } - } - } - } - } ); - } - // Spigot end - - if (entity instanceof EntityEnderDragon) { - EntityComplexPart[] aentitycomplexpart = ((EntityEnderDragon) entity).dT(); - int i = aentitycomplexpart.length; - - for (int j = 0; j < i; ++j) { - EntityComplexPart entitycomplexpart = aentitycomplexpart[j]; - - entitycomplexpart.die(); - } - } - - this.entitiesByUUID.remove(entity.getUniqueID()); - this.getChunkProvider().removeEntity(entity); - if (entity instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entity; - - this.players.remove(entityplayer); - } - - this.getScoreboard().a(entity); - // CraftBukkit start - SPIGOT-5278 - if (entity instanceof EntityDrowned) { - this.H.remove(((EntityDrowned) entity).b); - this.H.remove(((EntityDrowned) entity).c); - } else - // CraftBukkit end - if (entity instanceof EntityInsentient) { - this.H.remove(((EntityInsentient) entity).getNavigation()); - } - new com.destroystokyo.paper.event.entity.EntityRemoveFromWorldEvent(entity.getBukkitEntity()).callEvent(); // Paper - fire while valid - entity.valid = false; // CraftBukkit - } - - private void registerEntity(Entity entity) { - org.spigotmc.AsyncCatcher.catchOp("entity register"); // Spigot - if (this.tickingEntities) { - this.entitiesToAdd.add(entity); - } else { - this.entitiesById.put(entity.getId(), entity); - if (entity instanceof EntityEnderDragon) { - EntityComplexPart[] aentitycomplexpart = ((EntityEnderDragon) entity).dT(); - int i = aentitycomplexpart.length; - - for (int j = 0; j < i; ++j) { - EntityComplexPart entitycomplexpart = aentitycomplexpart[j]; - - this.entitiesById.put(entitycomplexpart.getId(), entitycomplexpart); - } - } - - if (DEBUG_ENTITIES) { - entity.addedToWorldStack = getAddToWorldStackTrace(entity); - } - - Entity old = this.entitiesByUUID.put(entity.getUniqueID(), entity); - if (old != null && old.getId() != entity.getId() && old.valid && entity.world.paperConfig.duplicateUUIDMode != com.destroystokyo.paper.PaperWorldConfig.DuplicateUUIDMode.NOTHING) { // Paper - Logger logger = LogManager.getLogger(); - logger.error("Overwrote an existing entity " + old + " with " + entity); - if (DEBUG_ENTITIES) { - if (old.addedToWorldStack != null) { - old.addedToWorldStack.printStackTrace(); - } else { - logger.error("Oddly, the old entity was not added to the world in the normal way. Plugins?"); - } - entity.addedToWorldStack.printStackTrace(); - } - } - - this.getChunkProvider().addEntity(entity); - // CraftBukkit start - SPIGOT-5278 - if (entity instanceof EntityDrowned) { - this.H.add(((EntityDrowned) entity).b); - this.H.add(((EntityDrowned) entity).c); - } else - // CraftBukkit end - if (entity instanceof EntityInsentient) { - this.H.add(((EntityInsentient) entity).getNavigation()); - } - entity.valid = true; // CraftBukkit - // Paper start - Set origin location when the entity is being added to the world - if (entity.origin == null) { - entity.origin = entity.getBukkitEntity().getLocation(); - } - // Paper end - entity.shouldBeRemoved = false; // Paper - shouldn't be removed after being re-added - new com.destroystokyo.paper.event.entity.EntityAddToWorldEvent(entity.getBukkitEntity()).callEvent(); // Paper - fire while valid - } - - } - - public void removeEntity(Entity entity) { - if (this.tickingEntities) { - throw new IllegalStateException("Removing entity while ticking!"); - } else { - this.removeEntityFromChunk(entity); - this.entitiesById.remove(entity.getId()); - this.unregisterEntity(entity); - entity.shouldBeRemoved = true; // Paper - } - } - - private void removeEntityFromChunk(Entity entity) { - IChunkAccess ichunkaccess = this.getChunkAt(entity.chunkX, entity.chunkZ, ChunkStatus.FULL, false); - - if (ichunkaccess instanceof Chunk) { - ((Chunk) ichunkaccess).b(entity); - } - - } - - public void removePlayer(EntityPlayer entityplayer) { - entityplayer.die(); - this.removeEntity(entityplayer); - this.everyoneSleeping(); - } - - public void strikeLightning(EntityLightning entitylightning) { - // CraftBukkit start - this.strikeLightning(entitylightning, LightningStrikeEvent.Cause.UNKNOWN); - } - - public void strikeLightning(EntityLightning entitylightning, LightningStrikeEvent.Cause cause) { - LightningStrikeEvent lightning = new LightningStrikeEvent(this.getWorld(), (org.bukkit.entity.LightningStrike) entitylightning.getBukkitEntity(), cause); - this.getServer().getPluginManager().callEvent(lightning); - - if (lightning.isCancelled()) { - return; - } - // CraftBukkit end - this.globalEntityList.add(entitylightning); - this.server.getPlayerList().sendPacketNearby((EntityHuman) null, entitylightning.locX, entitylightning.locY, entitylightning.locZ, paperConfig.maxLightningFlashDistance, this, new PacketPlayOutSpawnEntityWeather(entitylightning)); // Paper - use world instead of dimension, limit lightning strike effect distance - } - - @Override - public void a(int i, BlockPosition blockposition, int j) { - Iterator iterator = this.server.getPlayerList().getPlayers().iterator(); - - // CraftBukkit start - EntityHuman entityhuman = null; - Entity entity = this.getEntity(i); - if (entity instanceof EntityHuman) entityhuman = (EntityHuman) entity; - // CraftBukkit end - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - if (entityplayer != null && entityplayer.world == this && entityplayer.getId() != i) { - double d0 = (double) blockposition.getX() - entityplayer.locX; - double d1 = (double) blockposition.getY() - entityplayer.locY; - double d2 = (double) blockposition.getZ() - entityplayer.locZ; - - // CraftBukkit start - if (entityhuman != null && entityhuman instanceof EntityPlayer && !entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) { - continue; - } - // CraftBukkit end - - if (d0 * d0 + d1 * d1 + d2 * d2 < 1024.0D) { - entityplayer.playerConnection.sendPacket(new PacketPlayOutBlockBreakAnimation(i, blockposition, j)); - } - } - } - - } - - @Override - public void playSound(@Nullable EntityHuman entityhuman, double d0, double d1, double d2, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) { - this.server.getPlayerList().sendPacketNearby(entityhuman, d0, d1, d2, f > 1.0F ? (double) (16.0F * f) : 16.0D, this.worldProvider.getDimensionManager(), new PacketPlayOutNamedSoundEffect(soundeffect, soundcategory, d0, d1, d2, f, f1)); - } - - @Override - public void playSound(@Nullable EntityHuman entityhuman, Entity entity, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) { - this.server.getPlayerList().sendPacketNearby(entityhuman, entity.locX, entity.locY, entity.locZ, f > 1.0F ? (double) (16.0F * f) : 16.0D, this.worldProvider.getDimensionManager(), new PacketPlayOutEntitySound(soundeffect, soundcategory, entity, f, f1)); - } - - @Override - public void b(int i, BlockPosition blockposition, int j) { - this.server.getPlayerList().sendAll(new PacketPlayOutWorldEvent(i, blockposition, j, true)); - } - - @Override - public void a(@Nullable EntityHuman entityhuman, int i, BlockPosition blockposition, int j) { - this.server.getPlayerList().sendPacketNearby(entityhuman, (double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), 64.0D, this.worldProvider.getDimensionManager(), new PacketPlayOutWorldEvent(i, blockposition, j, false)); - } - - @Override - public void notify(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1, int i) { - this.getChunkProvider().flagDirty(blockposition); - VoxelShape voxelshape = iblockdata.getCollisionShape(this, blockposition); - VoxelShape voxelshape1 = iblockdata1.getCollisionShape(this, blockposition); - - if (VoxelShapes.c(voxelshape, voxelshape1, OperatorBoolean.NOT_SAME)) { - boolean wasTicking = this.tickingEntities; this.tickingEntities = true; // Paper - Iterator iterator = this.H.iterator(); - - while (iterator.hasNext()) { - NavigationAbstract navigationabstract = (NavigationAbstract) iterator.next(); - - if (!navigationabstract.j()) { - navigationabstract.b(blockposition); - } - } - - this.tickingEntities = wasTicking; // Paper - } - } - - @Override - public void broadcastEntityEffect(Entity entity, byte b0) { - this.getChunkProvider().broadcastIncludingSelf(entity, new PacketPlayOutEntityStatus(entity, b0)); - } - - @Override - public ChunkProviderServer getChunkProvider() { - return (ChunkProviderServer) super.getChunkProvider(); - } - - @Override - public Explosion createExplosion(@Nullable Entity entity, DamageSource damagesource, double d0, double d1, double d2, float f, boolean flag, Explosion.Effect explosion_effect) { - // CraftBukkit start - Explosion explosion = super.createExplosion(entity, damagesource, d0, d1, d2, f, flag, explosion_effect); - - if (explosion.wasCanceled) { - return explosion; - } - - /* Remove - Explosion explosion = new Explosion(this, entity, d0, d1, d2, f, flag, explosion_effect); - - if (damagesource != null) { - explosion.a(damagesource); - } - - explosion.a(); - explosion.a(false); - */ - // CraftBukkit end - TODO: Check if explosions are still properly implemented - if (explosion_effect == Explosion.Effect.NONE) { - explosion.clearBlocks(); - } - - Iterator iterator = this.players.iterator(); - - while (iterator.hasNext()) { - EntityPlayer entityplayer = (EntityPlayer) iterator.next(); - - if (entityplayer.e(d0, d1, d2) < 4096.0D) { - entityplayer.playerConnection.sendPacket(new PacketPlayOutExplosion(d0, d1, d2, f, explosion.getBlocks(), (Vec3D) explosion.c().get(entityplayer))); - } - } - - return explosion; - } - - @Override - public void playBlockAction(BlockPosition blockposition, Block block, int i, int j) { - this.I.add(new BlockActionData(blockposition, block, i, j)); - } - - private void ae() { - while (!this.I.isEmpty()) { - BlockActionData blockactiondata = (BlockActionData) this.I.removeFirst(); - - if (this.a(blockactiondata)) { - this.server.getPlayerList().sendPacketNearby((EntityHuman) null, (double) blockactiondata.a().getX(), (double) blockactiondata.a().getY(), (double) blockactiondata.a().getZ(), 64.0D, this, new PacketPlayOutBlockAction(blockactiondata.a(), blockactiondata.b(), blockactiondata.c(), blockactiondata.d())); - } - } - - } - - private boolean a(BlockActionData blockactiondata) { - IBlockData iblockdata = this.getType(blockactiondata.a()); - - return iblockdata.getBlock() == blockactiondata.b() ? iblockdata.a(this, blockactiondata.a(), blockactiondata.c(), blockactiondata.d()) : false; - } - - @Override - public TickListServer getBlockTickList() { - return this.nextTickListBlock; - } - - @Override - public TickListServer getFluidTickList() { - return this.nextTickListFluid; - } - - @Nonnull - @Override - public MinecraftServer getMinecraftServer() { - return this.server; - } - - public PortalTravelAgent getTravelAgent() { - return this.portalTravelAgent; - } - - public DefinedStructureManager r() { - return this.dataManager.f(); - } - - public int a(T t0, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6) { - // CraftBukkit - visibility api support - return sendParticles(null, t0, d0, d1, d2, i, d3, d4, d5, d6, false); - } - - public int sendParticles(EntityPlayer sender, T t0, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6, boolean force) { - // Paper start - Particle API Expansion - return sendParticles(players, sender, t0, d0, d1, d2, i, d3, d4, d5, d6, force); - } - public int sendParticles(List receivers, EntityPlayer sender, T t0, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6, boolean force) { - // Paper end - PacketPlayOutWorldParticles packetplayoutworldparticles = new PacketPlayOutWorldParticles(t0, force, (float) d0, (float) d1, (float) d2, (float) d3, (float) d4, (float) d5, (float) d6, i); - // CraftBukkit end - int j = 0; - - for (EntityHuman entityhuman : receivers) { // Paper - Particle API Expansion - EntityPlayer entityplayer = (EntityPlayer) entityhuman; // Paper - Particle API Expansion - if (sender != null && !entityplayer.getBukkitEntity().canSee(sender.getBukkitEntity())) continue; // CraftBukkit - - if (this.a(entityplayer, force, d0, d1, d2, packetplayoutworldparticles)) { // CraftBukkit - ++j; - } - } - - return j; - } - - public boolean a(EntityPlayer entityplayer, T t0, boolean flag, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6) { - Packet packet = new PacketPlayOutWorldParticles(t0, flag, (float) d0, (float) d1, (float) d2, (float) d3, (float) d4, (float) d5, (float) d6, i); - - return this.a(entityplayer, flag, d0, d1, d2, packet); - } - - private boolean a(EntityPlayer entityplayer, boolean flag, double d0, double d1, double d2, Packet packet) { - if (entityplayer.getWorldServer() != this) { - return false; - } else { - BlockPosition blockposition = entityplayer.getChunkCoordinates(); - - if (blockposition.a((IPosition) (new Vec3D(d0, d1, d2)), flag ? 512.0D : 32.0D)) { - entityplayer.playerConnection.sendPacket(packet); - return true; - } else { - return false; - } - } - } - - @Nullable - @Override - public Entity getEntity(int i) { - return (Entity) this.entitiesById.get(i); - } - - @Nullable - public Entity getEntity(UUID uuid) { - return (Entity) this.entitiesByUUID.get(uuid); - } - - @Nullable - @Override - public BlockPosition a(String s, BlockPosition blockposition, int i, boolean flag) { - return this.getChunkProvider().getChunkGenerator().findNearestMapFeature(this, s, blockposition, i, flag); - } - - @Override - public CraftingManager getCraftingManager() { - return this.server.getCraftingManager(); - } - - @Override - public TagRegistry t() { - return this.server.getTagRegistry(); - } - - @Override - public void a(long i) { - super.a(i); - this.worldData.y().a(this.server, i); - } - - @Override - public boolean isSavingDisabled() { - return this.savingDisabled; - } - - public void checkSession() throws ExceptionWorldConflict { - this.dataManager.checkSession(); - } - - public WorldNBTStorage getDataManager() { - return this.dataManager; - } - - public WorldPersistentData getWorldPersistentData() { - return this.getChunkProvider().getWorldPersistentData(); - } - - @Nullable - @Override - public WorldMap a(String s) { - return (WorldMap) this.getMinecraftServer().getWorldServer(DimensionManager.OVERWORLD).getWorldPersistentData().b(() -> { - // CraftBukkit start - // We only get here when the data file exists, but is not a valid map - WorldMap newMap = new WorldMap(s); - MapInitializeEvent event = new MapInitializeEvent(newMap.mapView); - Bukkit.getServer().getPluginManager().callEvent(event); - return newMap; - // CraftBukkit end - }, s); - } - - @Override - public void a(WorldMap worldmap) { - this.getMinecraftServer().getWorldServer(DimensionManager.OVERWORLD).getWorldPersistentData().a((PersistentBase) worldmap); - } - - @Override - public int getWorldMapCount() { - return ((PersistentIdCounts) this.getMinecraftServer().getWorldServer(DimensionManager.OVERWORLD).getWorldPersistentData().a(PersistentIdCounts::new, "idcounts")).a(); - } - - // Paper start - helper function for configurable spawn radius - public void addTicketsForSpawn(int radiusInBlocks, BlockPosition spawn) { - // In order to respect vanilla behavior, which is ensuring everything but the spawn border can tick, we add tickets - // with level 31 for the non-border spawn chunks - ChunkProviderServer chunkproviderserver = this.getChunkProvider(); - int tickRadius = radiusInBlocks - 16; - - // add ticking chunks - for (int x = -tickRadius; x <= tickRadius; x += 16) { - for (int z = -tickRadius; z <= tickRadius; z += 16) { - // radius of 2 will have the current chunk be level 31 - chunkproviderserver.addTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(x, 0, z)), 2, Unit.INSTANCE); - } - } - - // add border chunks - - // add border along x axis (including corner chunks) - for (int x = -radiusInBlocks; x <= radiusInBlocks; x += 16) { - // top - chunkproviderserver.addTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(x, 0, radiusInBlocks)), 1, Unit.INSTANCE); // level 32 - // bottom - chunkproviderserver.addTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(x, 0, -radiusInBlocks)), 1, Unit.INSTANCE); // level 32 - } - - // add border along z axis (excluding corner chunks) - for (int z = -radiusInBlocks + 16; z < radiusInBlocks; z += 16) { - // right - chunkproviderserver.addTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(radiusInBlocks, 0, z)), 1, Unit.INSTANCE); // level 32 - // left - chunkproviderserver.addTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(-radiusInBlocks, 0, z)), 1, Unit.INSTANCE); // level 32 - } - } - public void removeTicketsForSpawn(int radiusInBlocks, BlockPosition spawn) { - // In order to respect vanilla behavior, which is ensuring everything but the spawn border can tick, we added tickets - // with level 31 for the non-border spawn chunks - ChunkProviderServer chunkproviderserver = this.getChunkProvider(); - int tickRadius = radiusInBlocks - 16; - - // remove ticking chunks - for (int x = -tickRadius; x <= tickRadius; x += 16) { - for (int z = -tickRadius; z <= tickRadius; z += 16) { - // radius of 2 will have the current chunk be level 31 - chunkproviderserver.removeTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(x, 0, z)), 2, Unit.INSTANCE); - } - } - - // remove border chunks - - // remove border along x axis (including corner chunks) - for (int x = -radiusInBlocks; x <= radiusInBlocks; x += 16) { - // top - chunkproviderserver.removeTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(x, 0, radiusInBlocks)), 1, Unit.INSTANCE); // level 32 - // bottom - chunkproviderserver.removeTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(x, 0, -radiusInBlocks)), 1, Unit.INSTANCE); // level 32 - } - - // remove border along z axis (excluding corner chunks) - for (int z = -radiusInBlocks + 16; z < radiusInBlocks; z += 16) { - // right - chunkproviderserver.removeTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(radiusInBlocks, 0, z)), 1, Unit.INSTANCE); // level 32 - // left - chunkproviderserver.removeTicket(TicketType.START, new ChunkCoordIntPair(spawn.add(-radiusInBlocks, 0, z)), 1, Unit.INSTANCE); // level 32 - } - } - // Paper end - - @Override - public void a_(BlockPosition blockposition) { - // Paper - configurable spawn radius - BlockPosition prevSpawn = this.getSpawn(); - - super.a_(blockposition); - if (this.keepSpawnInMemory) { - // if this keepSpawnInMemory is false a plugin has already removed our tickets, do not re-add - this.removeTicketsForSpawn(this.paperConfig.keepLoadedRange, prevSpawn); - this.addTicketsForSpawn(this.paperConfig.keepLoadedRange, blockposition); - } - // Paper end - } - - public LongSet getForceLoadedChunks() { - ForcedChunk forcedchunk = (ForcedChunk) this.getWorldPersistentData().b(ForcedChunk::new, "chunks"); - - return (LongSet) (forcedchunk != null ? LongSets.unmodifiable(forcedchunk.a()) : LongSets.EMPTY_SET); - } - - public boolean setForceLoaded(int i, int j, boolean flag) { - ForcedChunk forcedchunk = (ForcedChunk) this.getWorldPersistentData().a(ForcedChunk::new, "chunks"); - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i, j); - long k = chunkcoordintpair.pair(); - boolean flag1; - - if (flag) { - flag1 = forcedchunk.a().add(k); - if (flag1) { - this.getChunkAt(i, j); - } - } else { - flag1 = forcedchunk.a().remove(k); - } - - forcedchunk.a(flag1); - if (flag1) { - this.getChunkProvider().a(chunkcoordintpair, flag); - } - - return flag1; - } - - @Override - public List getPlayers() { - return this.players; - } - - @Override - public void a(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1) { - Optional optional = VillagePlaceType.b(iblockdata); - Optional optional1 = VillagePlaceType.b(iblockdata1); - - if (!Objects.equals(optional, optional1)) { - BlockPosition blockposition1 = blockposition.immutableCopy(); - - optional.ifPresent((villageplacetype) -> { - this.getMinecraftServer().execute(() -> { - this.B().a(blockposition1); - PacketDebug.b(this, blockposition1); - }); - }); - optional1.ifPresent((villageplacetype) -> { - this.getMinecraftServer().execute(() -> { - this.B().a(blockposition1, villageplacetype); - PacketDebug.a(this, blockposition1); - }); - }); - } - } - - public VillagePlace B() { - return this.getChunkProvider().j(); - } - - public boolean b_(BlockPosition blockposition) { - return this.a(blockposition, 1); - } - - public boolean a(SectionPosition sectionposition) { - return this.b_(sectionposition.t()); - } - - public boolean a(BlockPosition blockposition, int i) { - return i > 6 ? false : this.b(SectionPosition.a(blockposition)) <= i; - } - - public int b(SectionPosition sectionposition) { - return this.B().a(sectionposition); - } - - public PersistentRaid C() { - return this.c; - } - - @Nullable - public Raid c_(BlockPosition blockposition) { - return this.c.a(blockposition, 9216); - } - - public boolean d_(BlockPosition blockposition) { - return this.c_(blockposition) != null; - } - - public void a(ReputationEvent reputationevent, Entity entity, ReputationHandler reputationhandler) { - reputationhandler.a(reputationevent, entity); - } - - public void a(java.nio.file.Path java_nio_file_path) throws IOException { - PlayerChunkMap playerchunkmap = this.getChunkProvider().playerChunkMap; - BufferedWriter bufferedwriter = Files.newBufferedWriter(java_nio_file_path.resolve("stats.txt")); - Throwable throwable = null; - - try { - bufferedwriter.write(String.format("spawning_chunks: %d\n", playerchunkmap.e().b())); - ObjectIterator objectiterator = this.l().object2IntEntrySet().iterator(); - - while (objectiterator.hasNext()) { - it.unimi.dsi.fastutil.objects.Object2IntMap.Entry it_unimi_dsi_fastutil_objects_object2intmap_entry = (it.unimi.dsi.fastutil.objects.Object2IntMap.Entry) objectiterator.next(); - - bufferedwriter.write(String.format("spawn_count.%s: %d\n", ((EnumCreatureType) it_unimi_dsi_fastutil_objects_object2intmap_entry.getKey()).a(), it_unimi_dsi_fastutil_objects_object2intmap_entry.getIntValue())); - } - - bufferedwriter.write(String.format("entities: %d\n", this.entitiesById.size())); - bufferedwriter.write(String.format("block_entities: %d\n", this.tileEntityListTick.size())); // Paper - remove unused list - bufferedwriter.write(String.format("block_ticks: %d\n", this.getBlockTickList().a())); - bufferedwriter.write(String.format("fluid_ticks: %d\n", this.getFluidTickList().a())); - bufferedwriter.write("distance_manager: " + playerchunkmap.e().c() + "\n"); - bufferedwriter.write(String.format("pending_tasks: %d\n", this.getChunkProvider().f())); - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (bufferedwriter != null) { - if (throwable != null) { - try { - bufferedwriter.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - bufferedwriter.close(); - } - } - - } - - CrashReport crashreport = new CrashReport("Level dump", new Exception("dummy")); - - this.a(crashreport); - BufferedWriter bufferedwriter1 = Files.newBufferedWriter(java_nio_file_path.resolve("example_crash.txt")); - Throwable throwable3 = null; - - try { - bufferedwriter1.write(crashreport.e()); - } catch (Throwable throwable4) { - throwable3 = throwable4; - throw throwable4; - } finally { - if (bufferedwriter1 != null) { - if (throwable3 != null) { - try { - bufferedwriter1.close(); - } catch (Throwable throwable5) { - throwable3.addSuppressed(throwable5); - } - } else { - bufferedwriter1.close(); - } - } - - } - - java.nio.file.Path java_nio_file_path1 = java_nio_file_path.resolve("chunks.csv"); - BufferedWriter bufferedwriter2 = Files.newBufferedWriter(java_nio_file_path1); - Throwable throwable6 = null; - - try { - playerchunkmap.a((Writer) bufferedwriter2); - } catch (Throwable throwable7) { - throwable6 = throwable7; - throw throwable7; - } finally { - if (bufferedwriter2 != null) { - if (throwable6 != null) { - try { - bufferedwriter2.close(); - } catch (Throwable throwable8) { - throwable6.addSuppressed(throwable8); - } - } else { - bufferedwriter2.close(); - } - } - - } - - java.nio.file.Path java_nio_file_path2 = java_nio_file_path.resolve("entities.csv"); - BufferedWriter bufferedwriter3 = Files.newBufferedWriter(java_nio_file_path2); - Throwable throwable9 = null; - - try { - a((Writer) bufferedwriter3, (Iterable) this.entitiesById.values()); - } catch (Throwable throwable10) { - throwable9 = throwable10; - throw throwable10; - } finally { - if (bufferedwriter3 != null) { - if (throwable9 != null) { - try { - bufferedwriter3.close(); - } catch (Throwable throwable11) { - throwable9.addSuppressed(throwable11); - } - } else { - bufferedwriter3.close(); - } - } - - } - - java.nio.file.Path java_nio_file_path3 = java_nio_file_path.resolve("global_entities.csv"); - BufferedWriter bufferedwriter4 = Files.newBufferedWriter(java_nio_file_path3); - Throwable throwable12 = null; - - try { - a((Writer) bufferedwriter4, (Iterable) this.globalEntityList); - } catch (Throwable throwable13) { - throwable12 = throwable13; - throw throwable13; - } finally { - if (bufferedwriter4 != null) { - if (throwable12 != null) { - try { - bufferedwriter4.close(); - } catch (Throwable throwable14) { - throwable12.addSuppressed(throwable14); - } - } else { - bufferedwriter4.close(); - } - } - - } - - java.nio.file.Path java_nio_file_path4 = java_nio_file_path.resolve("block_entities.csv"); - BufferedWriter bufferedwriter5 = Files.newBufferedWriter(java_nio_file_path4); - Throwable throwable15 = null; - - try { - this.a((Writer) bufferedwriter5); - } catch (Throwable throwable16) { - throwable15 = throwable16; - throw throwable16; - } finally { - if (bufferedwriter5 != null) { - if (throwable15 != null) { - try { - bufferedwriter5.close(); - } catch (Throwable throwable17) { - throwable15.addSuppressed(throwable17); - } - } else { - bufferedwriter5.close(); - } - } - - } - - } - - private static void a(Writer writer, Iterable iterable) throws IOException { - CSVWriter csvwriter = CSVWriter.a().a("x").a("y").a("z").a("uuid").a("type").a("alive").a("display_name").a("custom_name").a(writer); - Iterator iterator = iterable.iterator(); - - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - IChatBaseComponent ichatbasecomponent = entity.getCustomName(); - IChatBaseComponent ichatbasecomponent1 = entity.getScoreboardDisplayName(); - - csvwriter.a(entity.locX, entity.locY, entity.locZ, entity.getUniqueID(), IRegistry.ENTITY_TYPE.getKey(entity.getEntityType()), entity.isAlive(), ichatbasecomponent1.getString(), ichatbasecomponent != null ? ichatbasecomponent.getString() : null); - } - - } - - private void a(Writer writer) throws IOException { - CSVWriter csvwriter = CSVWriter.a().a("x").a("y").a("z").a("type").a(writer); - Iterator iterator = this.tileEntityListTick.iterator(); // Paper - remove unused list - - while (iterator.hasNext()) { - TileEntity tileentity = (TileEntity) iterator.next(); - BlockPosition blockposition = tileentity.getPosition(); - - csvwriter.a(blockposition.getX(), blockposition.getY(), blockposition.getZ(), IRegistry.BLOCK_ENTITY_TYPE.getKey(tileentity.q())); - } - - } -} diff --git a/src/main/java/net/minecraft/server/WorldUpgrader.java b/src/main/java/net/minecraft/server/WorldUpgrader.java deleted file mode 100644 index af2af1e62..000000000 --- a/src/main/java/net/minecraft/server/WorldUpgrader.java +++ /dev/null @@ -1,276 +0,0 @@ -package net.minecraft.server; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.UnmodifiableIterator; -import com.google.common.collect.ImmutableMap.Builder; -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import it.unimi.dsi.fastutil.objects.Object2FloatMap; -import it.unimi.dsi.fastutil.objects.Object2FloatMaps; -import it.unimi.dsi.fastutil.objects.Object2FloatOpenCustomHashMap; -import java.io.File; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.concurrent.ThreadFactory; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class WorldUpgrader { - - private static final Logger LOGGER = LogManager.getLogger(); - private static final ThreadFactory b = (new ThreadFactoryBuilder()).setDaemon(true).build(); - private final String c; - private final boolean d; - private final WorldNBTStorage e; - private final Thread f; - private final File g; - private volatile boolean h = true; - private volatile boolean i; - private volatile float j; - private volatile int k; - private volatile int l; - private volatile int m; - private final Object2FloatMap n = Object2FloatMaps.synchronize(new Object2FloatOpenCustomHashMap(SystemUtils.i())); - private volatile IChatBaseComponent o = new ChatMessage("optimizeWorld.stage.counting", new Object[0]); - private static final Pattern p = Pattern.compile("^r\\.(-?[0-9]+)\\.(-?[0-9]+)\\.mca$"); - private final WorldPersistentData q; - - public WorldUpgrader(String s, Convertable convertable, WorldData worlddata, boolean flag) { - this.c = worlddata.getName(); - this.d = flag; - this.e = convertable.a(s, (MinecraftServer) null); - this.e.saveWorldData(worlddata); - this.q = new WorldPersistentData(new File(DimensionManager.OVERWORLD.a(this.e.getDirectory()), "data"), this.e.getDataFixer()); - this.g = this.e.getDirectory(); - this.f = WorldUpgrader.b.newThread(this::i); - this.f.setUncaughtExceptionHandler((thread, throwable) -> { - WorldUpgrader.LOGGER.error("Error upgrading world", throwable); - this.o = new ChatMessage("optimizeWorld.stage.failed", new Object[0]); - }); - this.f.start(); - } - - public void a() { - this.h = false; - - try { - this.f.join(); - } catch (InterruptedException interruptedexception) { - ; - } - - } - - private void i() { - File file = this.e.getDirectory(); - - this.k = 0; - Builder> builder = ImmutableMap.builder(); - - List list; - - for (Iterator iterator = DimensionManager.a().iterator(); iterator.hasNext(); this.k += list.size()) { - DimensionManager dimensionmanager = (DimensionManager) iterator.next(); - - list = this.b(dimensionmanager); - builder.put(dimensionmanager, list.listIterator()); - } - - if (this.k == 0) { - this.i = true; - } else { - float f = (float) this.k; - ImmutableMap> immutablemap = builder.build(); - Builder builder1 = ImmutableMap.builder(); - Iterator iterator1 = DimensionManager.a().iterator(); - - while (iterator1.hasNext()) { - DimensionManager dimensionmanager1 = (DimensionManager) iterator1.next(); - File file1 = dimensionmanager1.a(file); - - builder1.put(dimensionmanager1, new IChunkLoader(new File(file1, "region"), this.e.getDataFixer())); - } - - ImmutableMap immutablemap1 = builder1.build(); - long i = SystemUtils.getMonotonicMillis(); - - this.o = new ChatMessage("optimizeWorld.stage.upgrading", new Object[0]); - - while (this.h) { - boolean flag = false; - float f1 = 0.0F; - - float f2; - - for (Iterator iterator2 = DimensionManager.a().iterator(); iterator2.hasNext(); f1 += f2) { - DimensionManager dimensionmanager2 = (DimensionManager) iterator2.next(); - ListIterator listiterator = (ListIterator) immutablemap.get(dimensionmanager2); - IChunkLoader ichunkloader = (IChunkLoader) immutablemap1.get(dimensionmanager2); - - if (listiterator.hasNext()) { - ChunkCoordIntPair chunkcoordintpair = (ChunkCoordIntPair) listiterator.next(); - boolean flag1 = false; - - try { - NBTTagCompound nbttagcompound = ichunkloader.read(chunkcoordintpair); - - if (nbttagcompound != null) { - int j = IChunkLoader.a(nbttagcompound); - NBTTagCompound nbttagcompound1 = ichunkloader.getChunkData(dimensionmanager2, () -> { - return this.q; - }, nbttagcompound, chunkcoordintpair, null); // CraftBukkit - boolean flag2 = j < SharedConstants.a().getWorldVersion(); - - if (this.d) { - NBTTagCompound nbttagcompound2 = nbttagcompound1.getCompound("Level"); - - flag2 = flag2 || nbttagcompound2.hasKey("Heightmaps"); - nbttagcompound2.remove("Heightmaps"); - flag2 = flag2 || nbttagcompound2.hasKey("isLightOn"); - nbttagcompound2.remove("isLightOn"); - } - - if (flag2) { - ichunkloader.write(chunkcoordintpair, nbttagcompound1); - flag1 = true; - } - } - } catch (ReportedException reportedexception) { - Throwable throwable = reportedexception.getCause(); - - if (!(throwable instanceof IOException)) { - throw reportedexception; - } - - WorldUpgrader.LOGGER.error("Error upgrading chunk {}", chunkcoordintpair, throwable); - } catch (IOException ioexception) { - WorldUpgrader.LOGGER.error("Error upgrading chunk {}", chunkcoordintpair, ioexception); - } - - if (flag1) { - ++this.l; - } else { - ++this.m; - } - - flag = true; - } - - f2 = (float) listiterator.nextIndex() / f; - this.n.put(dimensionmanager2, f2); - } - - this.j = f1; - if (!flag) { - this.h = false; - } - } - - this.o = new ChatMessage("optimizeWorld.stage.finished", new Object[0]); - UnmodifiableIterator unmodifiableiterator = immutablemap1.values().iterator(); - - while (unmodifiableiterator.hasNext()) { - IChunkLoader ichunkloader1 = (IChunkLoader) unmodifiableiterator.next(); - - try { - ichunkloader1.close(); - } catch (IOException ioexception1) { - WorldUpgrader.LOGGER.error("Error upgrading chunk", ioexception1); - } - } - - this.q.a(); - i = SystemUtils.getMonotonicMillis() - i; - WorldUpgrader.LOGGER.info("World optimizaton finished after {} ms", i); - this.i = true; - } - } - - private List b(DimensionManager dimensionmanager) { - File file = dimensionmanager.a(this.g); - File file1 = new File(file, "region"); - File[] afile = file1.listFiles((file2, s) -> { - return s.endsWith(".mca"); - }); - - if (afile == null) { - return ImmutableList.of(); - } else { - List list = Lists.newArrayList(); - File[] afile1 = afile; - int i = afile.length; - - for (int j = 0; j < i; ++j) { - File file2 = afile1[j]; - Matcher matcher = WorldUpgrader.p.matcher(file2.getName()); - - if (matcher.matches()) { - int k = Integer.parseInt(matcher.group(1)) << 5; - int l = Integer.parseInt(matcher.group(2)) << 5; - - try { - RegionFile regionfile = new RegionFile(file2); - Throwable throwable = null; - - try { - for (int i1 = 0; i1 < 32; ++i1) { - for (int j1 = 0; j1 < 32; ++j1) { - ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i1 + k, j1 + l); - - if (regionfile.b(chunkcoordintpair)) { - list.add(chunkcoordintpair); - } - } - } - } catch (Throwable throwable1) { - throwable = throwable1; - throw throwable1; - } finally { - if (regionfile != null) { - if (throwable != null) { - try { - regionfile.close(); - } catch (Throwable throwable2) { - throwable.addSuppressed(throwable2); - } - } else { - regionfile.close(); - } - } - - } - } catch (Throwable throwable3) { - ; - } - } - } - - return list; - } - } - - public boolean b() { - return this.i; - } - - public int d() { - return this.k; - } - - public int e() { - return this.l; - } - - public int f() { - return this.m; - } - - public IChatBaseComponent g() { - return this.o; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftArt.java b/src/main/java/org/bukkit/craftbukkit/CraftArt.java deleted file mode 100644 index 378cd360d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftArt.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Preconditions; -import com.google.common.collect.BiMap; -import com.google.common.collect.ImmutableBiMap; -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.Paintings; -import org.bukkit.Art; - -public class CraftArt { - private static final BiMap artwork; - - static { - ImmutableBiMap.Builder artworkBuilder = ImmutableBiMap.builder(); - for (MinecraftKey key : IRegistry.MOTIVE.keySet()) { - artworkBuilder.put(IRegistry.MOTIVE.get(key), Art.getByName(key.getKey())); - } - - artwork = artworkBuilder.build(); - } - - public static Art NotchToBukkit(Paintings art) { - Art bukkit = artwork.get(art); - Preconditions.checkArgument(bukkit != null); - return bukkit; - } - - public static Paintings BukkitToNotch(Art art) { - Paintings nms = artwork.inverse().get(art); - Preconditions.checkArgument(nms != null); - return nms; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftChunk.java b/src/main/java/org/bukkit/craftbukkit/CraftChunk.java deleted file mode 100644 index 373bea4b6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftChunk.java +++ /dev/null @@ -1,386 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Preconditions; -import java.lang.ref.WeakReference; -import java.util.Arrays; -import java.util.Collection; -import net.minecraft.server.BiomeBase; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.Blocks; -import net.minecraft.server.ChunkSection; -import net.minecraft.server.DataPaletteBlock; -import net.minecraft.server.EnumSkyBlock; -import net.minecraft.server.GameProfileSerializer; -import net.minecraft.server.HeightMap; -import net.minecraft.server.IBlockData; -import net.minecraft.server.LightEngine; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NibbleArray; -import net.minecraft.server.SectionPosition; -import net.minecraft.server.SeededRandom; -import net.minecraft.server.WorldChunkManager; -import net.minecraft.server.WorldServer; -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.block.data.BlockData; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.entity.Entity; -import org.bukkit.plugin.Plugin; - -public class CraftChunk implements Chunk { - private WeakReference weakChunk; - private final WorldServer worldServer; - private final int x; - private final int z; - private static final DataPaletteBlock emptyBlockIDs = new ChunkSection(0).getBlocks(); - private static final byte[] emptyLight = new byte[2048]; - - public CraftChunk(net.minecraft.server.Chunk chunk) { - this.weakChunk = new WeakReference(chunk); - - worldServer = (WorldServer) getHandle().world; - x = getHandle().getPos().x; - z = getHandle().getPos().z; - } - - @Override - 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); - - weakChunk = new WeakReference(c); - } - - return c; - } - - void breakLink() { - weakChunk.clear(); - } - - @Override - public int getX() { - return x; - } - - @Override - public int getZ() { - return z; - } - - @Override - public String toString() { - return "CraftChunk{" + "x=" + getX() + "z=" + getZ() + '}'; - } - - @Override - public Block getBlock(int x, int y, int z) { - validateChunkCoordinates(x, y, z); - - return new CraftBlock(worldServer, new BlockPosition((this.x << 4) | x, y, (this.z << 4) | z)); - } - - @Override - public Entity[] getEntities() { - if (!isLoaded()) { - getWorld().getChunkAt(x, z); // Transient load for this tick - } - 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++) { - // Paper start - speed up (was with chunk.entitySlices[i].toArray() and cast checks which costs a lot of performance if called often) - for (net.minecraft.server.Entity entity : chunk.entitySlices[i]) { - if (entity == null) { - continue; - } - entities[index++] = entity.getBukkitEntity(); - } - // Paper end - } - - return entities; - } - - @Override - public BlockState[] getTileEntities() { - // Paper start - return getTileEntities(true); - } - - @Override - public BlockState[] getTileEntities(boolean useSnapshot) { - if (!isLoaded()) { - getWorld().getChunkAt(x, z); // Transient load for this tick - } - // Paper end - 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(useSnapshot); // Paper - } - - return entities; - } - - @Override - public boolean isLoaded() { - return getWorld().isChunkLoaded(this); - } - - @Override - public boolean load() { - return getWorld().loadChunk(getX(), getZ(), true); - } - - @Override - public boolean load(boolean generate) { - return getWorld().loadChunk(getX(), getZ(), generate); - } - - @Override - public boolean unload() { - return getWorld().unloadChunk(getX(), getZ()); - } - - @Override - public boolean isSlimeChunk() { - // 987234911L is deterimined in EntitySlime when seeing if a slime can spawn in a chunk - return SeededRandom.a(getX(), getZ(), getWorld().getSeed(), worldServer.spigotConfig.slimeSeed).nextInt(10) == 0; - } - - @Override - public boolean unload(boolean save) { - return getWorld().unloadChunk(getX(), getZ(), save); - } - - @Override - public boolean isForceLoaded() { - return getWorld().isChunkForceLoaded(getX(), getZ()); - } - - @Override - public void setForceLoaded(boolean forced) { - getWorld().setChunkForceLoaded(getX(), getZ(), forced); - } - - @Override - public boolean addPluginChunkTicket(Plugin plugin) { - return getWorld().addPluginChunkTicket(getX(), getZ(), plugin); - } - - @Override - public boolean removePluginChunkTicket(Plugin plugin) { - return getWorld().removePluginChunkTicket(getX(), getZ(), plugin); - } - - @Override - public Collection getPluginChunkTickets() { - return getWorld().getPluginChunkTickets(getX(), getZ()); - } - - @Override - public long getInhabitedTime() { - return getHandle().q(); - } - - @Override - public void setInhabitedTime(long ticks) { - Preconditions.checkArgument(ticks >= 0, "ticks cannot be negative"); - - getHandle().b(ticks); - } - - @Override - public boolean contains(BlockData block) { - Preconditions.checkArgument(block != null, "Block cannot be null"); - - IBlockData nms = ((CraftBlockData) block).getState(); - for (ChunkSection section : getHandle().getSections()) { - if (section != null && section.getBlocks().a(nms)) { - return true; - } - } - - return false; - } - - @Override - public ChunkSnapshot getChunkSnapshot() { - return getChunkSnapshot(true, false, false); - } - - @Override - public ChunkSnapshot getChunkSnapshot(boolean includeMaxBlockY, boolean includeBiome, boolean includeBiomeTempRain) { - net.minecraft.server.Chunk chunk = getHandle(); - - ChunkSection[] cs = chunk.getSections(); - DataPaletteBlock[] sectionBlockIDs = new DataPaletteBlock[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; - sectionSkyLights[i] = emptyLight; - sectionEmitLights[i] = emptyLight; - sectionEmpty[i] = true; - } else { // Not empty - NBTTagCompound data = new NBTTagCompound(); - cs[i].getBlocks().a(data, "Palette", "BlockStates"); - - DataPaletteBlock blockids = new DataPaletteBlock<>(ChunkSection.GLOBAL_PALETTE, net.minecraft.server.Block.REGISTRY_ID, GameProfileSerializer::d, GameProfileSerializer::a, Blocks.AIR.getBlockData()); // TODO: snapshot whole ChunkSection - blockids.a(data.getList("Palette", CraftMagicNumbers.NBT.TAG_COMPOUND), data.getLongArray("BlockStates")); - - sectionBlockIDs[i] = blockids; - - LightEngine lightengine = chunk.world.getChunkProvider().getLightEngine(); - NibbleArray skyLightArray = lightengine.a(EnumSkyBlock.SKY).a(SectionPosition.a(x, i, z)); - if (skyLightArray == null) { - sectionSkyLights[i] = emptyLight; - } else { - sectionSkyLights[i] = new byte[2048]; - System.arraycopy(skyLightArray.asBytes(), 0, sectionSkyLights[i], 0, 2048); - } - NibbleArray emitLightArray = lightengine.a(EnumSkyBlock.BLOCK).a(SectionPosition.a(x, i, z)); - if (emitLightArray == null) { - sectionEmitLights[i] = emptyLight; - } else { - sectionEmitLights[i] = new byte[2048]; - System.arraycopy(emitLightArray.asBytes(), 0, sectionEmitLights[i], 0, 2048); - } - } - } - - HeightMap hmap = null; - - if (includeMaxBlockY) { - hmap = new HeightMap(null, HeightMap.Type.MOTION_BLOCKING); - hmap.a(chunk.heightMap.get(HeightMap.Type.MOTION_BLOCKING).a()); - } - - BiomeBase[] biome = null; - double[] biomeTemp = null; - - if (includeBiome || includeBiomeTempRain) { - WorldChunkManager wcm = worldServer.getChunkProvider().getChunkGenerator().getWorldChunkManager(); - - if (includeBiome) { - biome = new BiomeBase[256]; - for (int i = 0; i < 256; i++) { - biome[i] = chunk.getBiome(new BlockPosition(i & 0xF, 0, i >> 4)); - } - } - - if (includeBiomeTempRain) { - biomeTemp = new double[256]; - float[] dat = getTemperatures(wcm, getX() << 4, getZ() << 4); - - for (int i = 0; i < 256; i++) { - biomeTemp[i] = dat[i]; - } - } - } - - World world = getWorld(); - return new CraftChunkSnapshot(getX(), getZ(), world.getName(), world.getFullTime(), sectionBlockIDs, sectionSkyLights, sectionEmitLights, sectionEmpty, hmap, biome, biomeTemp); - } - - public static ChunkSnapshot getEmptyChunkSnapshot(int x, int z, CraftWorld world, boolean includeBiome, boolean includeBiomeTempRain) { - BiomeBase[] biome = null; - double[] biomeTemp = null; - - if (includeBiome || includeBiomeTempRain) { - WorldChunkManager wcm = world.getHandle().getChunkProvider().getChunkGenerator().getWorldChunkManager(); - - if (includeBiome) { - biome = new BiomeBase[256]; - for (int i = 0; i < 256; i++) { - biome[i] = world.getHandle().getBiome(new BlockPosition((x << 4) + (i & 0xF), 0, (z << 4) + (i >> 4))); - } - } - - if (includeBiomeTempRain) { - biomeTemp = new double[256]; - float[] dat = getTemperatures(wcm, x << 4, z << 4); - - for (int i = 0; i < 256; i++) { - biomeTemp[i] = dat[i]; - } - } - } - - /* Fill with empty data */ - int hSection = world.getMaxHeight() >> 4; - DataPaletteBlock[] blockIDs = new DataPaletteBlock[hSection]; - byte[][] skyLight = new byte[hSection][]; - byte[][] emitLight = new byte[hSection][]; - boolean[] empty = new boolean[hSection]; - - for (int i = 0; i < hSection; i++) { - blockIDs[i] = emptyBlockIDs; - skyLight[i] = emptyLight; - emitLight[i] = emptyLight; - empty[i] = true; - } - - return new CraftChunkSnapshot(x, z, world.getName(), world.getFullTime(), blockIDs, skyLight, emitLight, empty, new HeightMap(null, HeightMap.Type.MOTION_BLOCKING), biome, biomeTemp); - } - - private static float[] getTemperatures(WorldChunkManager chunkmanager, int chunkX, int chunkZ) { - BiomeBase[] biomes = chunkmanager.getBiomeBlock(chunkX, chunkZ, 16, 16); - float[] temps = new float[biomes.length]; - - for (int i = 0; i < biomes.length; i++) { - float temp = biomes[i].getTemperature(); // Vanilla of olde: ((int) biomes[i].temperature * 65536.0F) / 65536.0F - - if (temp > 1F) { - temp = 1F; - } - - temps[i] = temp; - } - - return temps; - } - - static void validateChunkCoordinates(int x, int y, int z) { - Preconditions.checkArgument(0 <= x && x <= 15, "x out of range (expected 0-15, got %s)", x); - Preconditions.checkArgument(0 <= y && y <= 255, "y out of range (expected 0-255, got %s)", y); - Preconditions.checkArgument(0 <= z && z <= 15, "z out of range (expected 0-15, got %s)", z); - } - - static { - Arrays.fill(emptyLight, (byte) 0xFF); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java b/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java deleted file mode 100644 index 8cf0502af..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java +++ /dev/null @@ -1,145 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Preconditions; -import net.minecraft.server.BiomeBase; -import net.minecraft.server.DataPaletteBlock; -import net.minecraft.server.HeightMap; -import net.minecraft.server.IBlockData; -import org.bukkit.ChunkSnapshot; -import org.bukkit.Material; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; - -/** - * 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 DataPaletteBlock[] blockids; - private final byte[][] skylight; - private final byte[][] emitlight; - private final boolean[] empty; - private final HeightMap hmap; // Height map - private final long captureFulltime; - private final BiomeBase[] biome; - private final double[] biomeTemp; - - CraftChunkSnapshot(int x, int z, String wname, long wtime, DataPaletteBlock[] sectionBlockIDs, byte[][] sectionSkyLights, byte[][] sectionEmitLights, boolean[] sectionEmpty, HeightMap hmap, BiomeBase[] biome, double[] biomeTemp) { - this.x = x; - this.z = z; - this.worldname = wname; - this.captureFulltime = wtime; - this.blockids = sectionBlockIDs; - this.skylight = sectionSkyLights; - this.emitlight = sectionEmitLights; - this.empty = sectionEmpty; - this.hmap = hmap; - this.biome = biome; - this.biomeTemp = biomeTemp; - } - - @Override - public int getX() { - return x; - } - - @Override - public int getZ() { - return z; - } - - @Override - public String getWorldName() { - return worldname; - } - - @Override - public boolean contains(BlockData block) { - Preconditions.checkArgument(block != null, "Block cannot be null"); - - IBlockData nms = ((CraftBlockData) block).getState(); - for (DataPaletteBlock palette : blockids) { - if (palette.a(nms)) { - return true; - } - } - - return false; - } - - @Override - public Material getBlockType(int x, int y, int z) { - CraftChunk.validateChunkCoordinates(x, y, z); - - return CraftMagicNumbers.getMaterial(blockids[y >> 4].a(x, y & 0xF, z).getBlock()); - } - - @Override - public final BlockData getBlockData(int x, int y, int z) { - CraftChunk.validateChunkCoordinates(x, y, z); - - return CraftBlockData.fromData(blockids[y >> 4].a(x, y & 0xF, z)); - } - - @Override - public final int getData(int x, int y, int z) { - CraftChunk.validateChunkCoordinates(x, y, z); - - return CraftMagicNumbers.toLegacyData(blockids[y >> 4].a(x, y & 0xF, z)); - } - - @Override - public final int getBlockSkyLight(int x, int y, int z) { - CraftChunk.validateChunkCoordinates(x, y, z); - - int off = ((y & 0xF) << 7) | (z << 3) | (x >> 1); - return (skylight[y >> 4][off] >> ((x & 1) << 2)) & 0xF; - } - - @Override - public final int getBlockEmittedLight(int x, int y, int z) { - CraftChunk.validateChunkCoordinates(x, y, z); - - int off = ((y & 0xF) << 7) | (z << 3) | (x >> 1); - return (emitlight[y >> 4][off] >> ((x & 1) << 2)) & 0xF; - } - - @Override - public final int getHighestBlockYAt(int x, int z) { - Preconditions.checkState(hmap != null, "ChunkSnapshot created without height map. Please call getSnapshot with includeMaxblocky=true"); - CraftChunk.validateChunkCoordinates(x, 0, z); - - return hmap.a(x, z); - } - - @Override - public final Biome getBiome(int x, int z) { - Preconditions.checkState(biome != null, "ChunkSnapshot created without biome. Please call getSnapshot with includeBiome=true"); - CraftChunk.validateChunkCoordinates(x, 0, z); - - return CraftBlock.biomeBaseToBiome(biome[z << 4 | x]); - } - - @Override - public final double getRawBiomeTemperature(int x, int z) { - Preconditions.checkState(biomeTemp != null, "ChunkSnapshot created without biome temperatures. Please call getSnapshot with includeBiomeTempRain=true"); - CraftChunk.validateChunkCoordinates(x, 0, z); - - return biomeTemp[z << 4 | x]; - } - - @Override - public final long getCaptureFullTime() { - return captureFulltime; - } - - @Override - public final boolean isSectionEmpty(int sy) { - return empty[sy]; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftCrashReport.java b/src/main/java/org/bukkit/craftbukkit/CraftCrashReport.java deleted file mode 100644 index 7511e3813..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftCrashReport.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bukkit.craftbukkit; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; -import net.minecraft.server.CrashReportCallable; -import net.minecraft.server.MinecraftServer; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; - -public class CraftCrashReport implements CrashReportCallable { - - @Override - public Object 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(); - boolean legacy = CraftMagicNumbers.isLegacy(description); - value.append(' ').append(description.getFullName()).append(legacy ? "*" : "").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()); - value.append("\n Force Loaded Chunks: {"); - for (World world : Bukkit.getWorlds()) { - value.append(' ').append(world.getName()).append(": {"); - for (Map.Entry> entry : world.getPluginChunkTickets().entrySet()) { - value.append(' ').append(entry.getKey().getDescription().getFullName()).append(": ").append(Integer.toString(entry.getValue().size())).append(','); - } - value.append("},"); - } - value.append("}"); - } 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/src/main/java/org/bukkit/craftbukkit/CraftEffect.java b/src/main/java/org/bukkit/craftbukkit/CraftEffect.java deleted file mode 100644 index 8345587b5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftEffect.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.bukkit.craftbukkit; - -import net.minecraft.server.Block; -import net.minecraft.server.Item; -import org.apache.commons.lang.Validate; -import org.bukkit.Effect; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.potion.Potion; - -public class CraftEffect { - public static int getDataValue(Effect effect, T data) { - int datavalue; - switch(effect) { - case VILLAGER_PLANT_GROW: - datavalue = (Integer) data; - break; - case POTION_BREAK: - datavalue = ((Potion) data).toDamageValue() & 0x3F; - break; - case RECORD_PLAY: - Validate.isTrue(data == Material.AIR || ((Material) data).isRecord(), "Invalid record type!"); - datavalue = Item.getId(CraftMagicNumbers.getItem((Material) data)); - 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 = Block.getCombinedId(CraftMagicNumbers.getBlock((Material) data).getBlockData()); - break; - default: - datavalue = 0; - } - return datavalue; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java b/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java deleted file mode 100644 index 339ae6b74..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bukkit.craftbukkit; - -import net.minecraft.server.EnumItemSlot; -import org.bukkit.inventory.EquipmentSlot; - -public class CraftEquipmentSlot { - - private static final EnumItemSlot[] slots = new EnumItemSlot[EquipmentSlot.values().length]; - private static final EquipmentSlot[] enums = new EquipmentSlot[EnumItemSlot.values().length]; - - static { - set(EquipmentSlot.HAND, EnumItemSlot.MAINHAND); - set(EquipmentSlot.OFF_HAND, EnumItemSlot.OFFHAND); - set(EquipmentSlot.FEET, EnumItemSlot.FEET); - set(EquipmentSlot.LEGS, EnumItemSlot.LEGS); - set(EquipmentSlot.CHEST, EnumItemSlot.CHEST); - set(EquipmentSlot.HEAD, EnumItemSlot.HEAD); - } - - private static void set(EquipmentSlot type, EnumItemSlot value) { - slots[type.ordinal()] = value; - enums[value.ordinal()] = type; - } - - public static EquipmentSlot getSlot(EnumItemSlot nms) { - return enums[nms.ordinal()]; - } - - public static EnumItemSlot getNMS(EquipmentSlot slot) { - return slots[slot.ordinal()]; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftFluidCollisionMode.java b/src/main/java/org/bukkit/craftbukkit/CraftFluidCollisionMode.java deleted file mode 100644 index 5a51d6abd..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftFluidCollisionMode.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.craftbukkit; - -import net.minecraft.server.RayTrace.FluidCollisionOption; -import org.bukkit.FluidCollisionMode; - -public class CraftFluidCollisionMode { - - private CraftFluidCollisionMode() {} - - public static FluidCollisionOption toNMS(FluidCollisionMode fluidCollisionMode) { - if (fluidCollisionMode == null) return null; - - switch (fluidCollisionMode) { - case ALWAYS: - return FluidCollisionOption.ANY; - case SOURCE_ONLY: - return FluidCollisionOption.SOURCE_ONLY; - case NEVER: - return FluidCollisionOption.NONE; - default: - return null; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftIpBanEntry.java b/src/main/java/org/bukkit/craftbukkit/CraftIpBanEntry.java deleted file mode 100644 index 372404cd1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftIpBanEntry.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.bukkit.craftbukkit; - -import java.io.IOException; -import java.util.Date; -import java.util.logging.Level; -import net.minecraft.server.IpBanEntry; -import net.minecraft.server.IpBanList; -import org.bukkit.Bukkit; - -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/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java b/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java deleted file mode 100644 index 101a32555..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.collect.ImmutableSet; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Date; -import java.util.Set; -import java.util.logging.Level; -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; - -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 = (IpBanEntry) 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, (IpBanEntry) 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/src/main/java/org/bukkit/craftbukkit/CraftLootTable.java b/src/main/java/org/bukkit/craftbukkit/CraftLootTable.java deleted file mode 100644 index 0064d9327..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftLootTable.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.bukkit.craftbukkit; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Random; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.DamageSource; -import net.minecraft.server.Entity; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.IInventory; -import net.minecraft.server.LootContextParameterSets; -import net.minecraft.server.LootContextParameters; -import net.minecraft.server.LootTable; -import net.minecraft.server.LootTableInfo; -import net.minecraft.server.WorldServer; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.entity.CraftEntity; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.craftbukkit.inventory.CraftInventory; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.loot.LootContext; - -public class CraftLootTable implements org.bukkit.loot.LootTable { - - private final LootTable handle; - private final NamespacedKey key; - - public CraftLootTable(NamespacedKey key, LootTable handle) { - this.handle = handle; - this.key = key; - } - - public LootTable getHandle() { - return handle; - } - - @Override - public Collection populateLoot(Random random, LootContext context) { - LootTableInfo nmsContext = convertContext(context); - List nmsItems = handle.populateLoot(nmsContext); - Collection bukkit = new ArrayList<>(nmsItems.size()); - - for (net.minecraft.server.ItemStack item : nmsItems) { - if (item.isEmpty()) { - continue; - } - bukkit.add(CraftItemStack.asBukkitCopy(item)); - } - - return bukkit; - } - - @Override - public void fillInventory(Inventory inventory, Random random, LootContext context) { - LootTableInfo nmsContext = convertContext(context); - CraftInventory craftInventory = (CraftInventory) inventory; - IInventory handle = craftInventory.getInventory(); - - // TODO: When events are added, call event here w/ custom reason? - getHandle().fillInventory(handle, nmsContext); - } - - @Override - public NamespacedKey getKey() { - return key; - } - - private LootTableInfo convertContext(LootContext context) { - Location loc = context.getLocation(); - WorldServer handle = ((CraftWorld) loc.getWorld()).getHandle(); - - LootTableInfo.Builder builder = new LootTableInfo.Builder(handle); - if (getHandle() != LootTable.a) { // PAIL - empty - // builder.luck(context.getLuck()); - - if (context.getLootedEntity() != null) { - Entity nmsLootedEntity = ((CraftEntity) context.getLootedEntity()).getHandle(); - builder.set(LootContextParameters.THIS_ENTITY, nmsLootedEntity); - builder.set(LootContextParameters.DAMAGE_SOURCE, DamageSource.GENERIC); - builder.set(LootContextParameters.POSITION, new BlockPosition(nmsLootedEntity)); - } - - if (context.getKiller() != null) { - EntityHuman nmsKiller = ((CraftHumanEntity) context.getKiller()).getHandle(); - builder.set(LootContextParameters.KILLER_ENTITY, nmsKiller); - // If there is a player killer, damage source should reflect that in case loot tables use that information - builder.set(LootContextParameters.DAMAGE_SOURCE, DamageSource.playerAttack(nmsKiller)); - } - } - - return builder.build(getHandle().getLootContextParameterSet()); - } - - @Override - public String toString() { - return getKey().toString(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof org.bukkit.loot.LootTable)) { - return false; - } - - org.bukkit.loot.LootTable table = (org.bukkit.loot.LootTable) obj; - return table.getKey().equals(this.getKey()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java b/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java deleted file mode 100644 index 3824180ee..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java +++ /dev/null @@ -1,344 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.mojang.authlib.GameProfile; -import java.io.File; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import net.minecraft.server.DimensionManager; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.WhiteListEntry; -import net.minecraft.server.WorldNBTStorage; -import org.bukkit.BanList; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.Server; -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; - -@SerializableAs("Player") -public class CraftOfflinePlayer implements OfflinePlayer, ConfigurationSerializable { - private final GameProfile profile; - private final CraftServer server; - private WorldNBTStorage storage; // Paper - lazy init - - protected CraftOfflinePlayer(CraftServer server, GameProfile profile) { - this.server = server; - this.profile = profile; - //this.storage = (WorldNBTStorage) (server.console.getWorldServer(DimensionManager.OVERWORLD).getDataManager()); // Paper - lazy init - - } - - public GameProfile getProfile() { - return profile; - } - - @Override - public boolean isOnline() { - return getPlayer() != null; - } - - @Override - 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; - } - - @Override - public UUID getUniqueId() { - return profile.getId(); - } - - public Server getServer() { - return server; - } - - @Override - public boolean isOp() { - return server.getHandle().isOp(profile); - } - - @Override - public void setOp(boolean value) { - if (value == isOp()) { - return; - } - - if (value) { - server.getHandle().addOp(profile); - } else { - server.getHandle().removeOp(profile); - } - } - - @Override - 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()); - } - } - - @Override - public boolean isWhitelisted() { - return server.getHandle().getWhitelist().isWhitelisted(profile); - } - - @Override - public void setWhitelisted(boolean value) { - if (value) { - server.getHandle().getWhitelist().add(new WhiteListEntry(profile)); - } else { - server.getHandle().getWhitelist().remove(profile); - } - } - - @Override - 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(UUID.fromString((String) args.get("UUID"))); - } - - @Override - public String toString() { - return getClass().getSimpleName() + "[UUID=" + profile.getId() + "]"; - } - - @Override - public Player getPlayer() { - return server.getPlayer(getUniqueId()); - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !(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; - } - - // Paper - lazy - private WorldNBTStorage getStorageLazy() { - if (this.storage == null) { - net.minecraft.server.WorldServer worldServer = server.console.getWorldServer(DimensionManager.OVERWORLD); - if (worldServer == null) { - throw new IllegalStateException("Cannot get world storage when there are no worlds loaded!"); - } else { - this.storage = (WorldNBTStorage) worldServer.getDataManager(); - } - } - - return this.storage; - } - // Paper end - - private NBTTagCompound getData() { - return getStorageLazy().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(getStorageLazy().getPlayerDir(), getUniqueId() + ".dat"); - } - - @Override - 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; - } - } - - @Override - 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; - } - } - - @Override - public boolean hasPlayedBefore() { - return getData() != null; - } - - // Paper start - @Override - public long getLastLogin() { - Player player = getPlayer(); - if (player != null) return player.getLastLogin(); - - NBTTagCompound data = getPaperData(); - - if (data != null) { - if (data.hasKey("LastLogin")) { - return data.getLong("LastLogin"); - } else { - // if the player file cannot provide accurate data, this is probably the closest we can approximate - File file = getDataFile(); - return file.lastModified(); - } - } else { - return 0; - } - } - - @Override - public long getLastSeen() { - Player player = getPlayer(); - if (player != null) return player.getLastSeen(); - - NBTTagCompound data = getPaperData(); - - if (data != null) { - if (data.hasKey("LastSeen")) { - return data.getLong("LastSeen"); - } else { - // if the player file cannot provide accurate data, this is probably the closest we can approximate - File file = getDataFile(); - return file.lastModified(); - } - } else { - return 0; - } - } - - private NBTTagCompound getPaperData() { - NBTTagCompound result = getData(); - - if (result != null) { - if (!result.hasKey("Paper")) { - result.set("Paper", new NBTTagCompound()); - } - result = result.getCompound("Paper"); - } - - return result; - } - // Paper end - - @Override - 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/src/main/java/org/bukkit/craftbukkit/CraftParticle.java b/src/main/java/org/bukkit/craftbukkit/CraftParticle.java deleted file mode 100644 index 99377033b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftParticle.java +++ /dev/null @@ -1,160 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Preconditions; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import java.util.HashMap; -import java.util.Map; -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.ParticleParam; -import net.minecraft.server.ParticleParamBlock; -import net.minecraft.server.ParticleParamItem; -import net.minecraft.server.ParticleParamRedstone; -import net.minecraft.server.ParticleType; -import org.bukkit.Color; -import org.bukkit.Particle; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; - -public enum CraftParticle { - - EXPLOSION_NORMAL("poof"), - EXPLOSION_LARGE("explosion"), - EXPLOSION_HUGE("explosion_emitter"), - FIREWORKS_SPARK("firework"), - WATER_BUBBLE("bubble"), - WATER_SPLASH("splash"), - WATER_WAKE("fishing"), - SUSPENDED("underwater"), - SUSPENDED_DEPTH("underwater"), - CRIT("crit"), - CRIT_MAGIC("enchanted_hit"), - SMOKE_NORMAL("smoke"), - SMOKE_LARGE("large_smoke"), - SPELL("effect"), - SPELL_INSTANT("instant_effect"), - SPELL_MOB("entity_effect"), - SPELL_MOB_AMBIENT("ambient_entity_effect"), - SPELL_WITCH("witch"), - DRIP_WATER("dripping_water"), - DRIP_LAVA("dripping_lava"), - VILLAGER_ANGRY("angry_villager"), - VILLAGER_HAPPY("happy_villager"), - TOWN_AURA("mycelium"), - NOTE("note"), - PORTAL("portal"), - ENCHANTMENT_TABLE("enchant"), - FLAME("flame"), - LAVA("lava"), - CLOUD("cloud"), - REDSTONE("dust"), - SNOWBALL("item_snowball"), - SNOW_SHOVEL("item_snowball"), - SLIME("item_slime"), - HEART("heart"), - BARRIER("barrier"), - ITEM_CRACK("item"), - BLOCK_CRACK("block"), - BLOCK_DUST("block"), - WATER_DROP("rain"), - MOB_APPEARANCE("elder_guardian"), - DRAGON_BREATH("dragon_breath"), - END_ROD("end_rod"), - DAMAGE_INDICATOR("damage_indicator"), - SWEEP_ATTACK("sweep_attack"), - FALLING_DUST("falling_dust"), - TOTEM("totem_of_undying"), - SPIT("spit"), - SQUID_INK("squid_ink"), - BUBBLE_POP("bubble_pop"), - CURRENT_DOWN("current_down"), - BUBBLE_COLUMN_UP("bubble_column_up"), - NAUTILUS("nautilus"), - DOLPHIN("dolphin"), - SNEEZE("sneeze"), - CAMPFIRE_COSY_SMOKE("campfire_cosy_smoke"), - CAMPFIRE_SIGNAL_SMOKE("campfire_signal_smoke"), - COMPOSTER("composter"), - FLASH("flash"), - FALLING_LAVA("falling_lava"), - LANDING_LAVA("landing_lava"), - FALLING_WATER("falling_water"), - // ----- Legacy Separator ----- - LEGACY_BLOCK_CRACK("block"), - LEGACY_BLOCK_DUST("block"), - LEGACY_FALLING_DUST("falling_dust"); - private final MinecraftKey minecraftKey; - private final Particle bukkit; - private static final BiMap particles; - private static final Map aliases; - - static { - particles = HashBiMap.create(); - aliases = new HashMap<>(); - - for (CraftParticle particle : CraftParticle.values()) { - if (particles.containsValue(particle.minecraftKey)) { - aliases.put(particle.bukkit, particles.inverse().get(particle.minecraftKey)); - } else { - particles.put(particle.bukkit, particle.minecraftKey); - } - } - } - - private CraftParticle(String minecraftKey) { - this.minecraftKey = new MinecraftKey(minecraftKey); - - this.bukkit = Particle.valueOf(this.name()); - Preconditions.checkState(bukkit != null, "Bukkit particle %s does not exist", this.name()); - } - - public static ParticleParam toNMS(Particle bukkit) { - return toNMS(bukkit, null); - } - - public static ParticleParam toNMS(Particle particle, T obj) { - Particle canonical = particle; - if (aliases.containsKey(particle)) { - canonical = aliases.get(particle); - } - - net.minecraft.server.Particle nms = IRegistry.PARTICLE_TYPE.get(particles.get(canonical)); - Preconditions.checkArgument(nms != null, "No NMS particle %s", particle); - - if (particle.getDataType().equals(Void.class)) { - return (ParticleType) nms; - } - Preconditions.checkArgument(obj != null, "Particle %s requires data, null provided", particle); - if (particle.getDataType().equals(ItemStack.class)) { - ItemStack itemStack = (ItemStack) obj; - return new ParticleParamItem((net.minecraft.server.Particle) nms, CraftItemStack.asNMSCopy(itemStack)); - } - if (particle.getDataType() == MaterialData.class) { - MaterialData data = (MaterialData) obj; - return new ParticleParamBlock((net.minecraft.server.Particle) nms, CraftMagicNumbers.getBlock(data)); - } - if (particle.getDataType() == BlockData.class) { - BlockData data = (BlockData) obj; - return new ParticleParamBlock((net.minecraft.server.Particle) nms, ((CraftBlockData) data).getState()); - } - if (particle.getDataType() == Particle.DustOptions.class) { - Particle.DustOptions data = (Particle.DustOptions) obj; - Color color = data.getColor(); - return new ParticleParamRedstone(color.getRed() / 255.0f, color.getGreen() / 255.0f, color.getBlue() / 255.0f, data.getSize()); - } - throw new IllegalArgumentException(particle.getDataType().toString()); - } - - public static Particle toBukkit(net.minecraft.server.ParticleParam nms) { - return toBukkit(nms.getParticle()); - } - - public static Particle toBukkit(net.minecraft.server.Particle nms) { - return particles.inverse().get(IRegistry.PARTICLE_TYPE.getKey(nms)); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftProfileBanEntry.java b/src/main/java/org/bukkit/craftbukkit/CraftProfileBanEntry.java deleted file mode 100644 index bbe91bca1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftProfileBanEntry.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.mojang.authlib.GameProfile; -import java.io.IOException; -import java.util.Date; -import java.util.logging.Level; -import net.minecraft.server.GameProfileBanEntry; -import net.minecraft.server.GameProfileBanList; -import org.bukkit.Bukkit; - -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, 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() { - 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/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java b/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java deleted file mode 100644 index 3938d920b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.collect.ImmutableSet; -import com.mojang.authlib.GameProfile; -import java.io.IOException; -import java.util.Date; -import java.util.Set; -import java.util.UUID; -import java.util.logging.Level; -import net.minecraft.server.GameProfileBanEntry; -import net.minecraft.server.GameProfileBanList; -import net.minecraft.server.JsonListEntry; -import net.minecraft.server.MinecraftServer; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; - -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 = getProfile(target); - if (profile == null) { - return null; - } - - GameProfileBanEntry entry = (GameProfileBanEntry) 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 = 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 (JsonListEntry entry : list.getValues()) { - GameProfile profile = (GameProfile) entry.getKey(); - builder.add(new CraftProfileBanEntry(profile, (GameProfileBanEntry) entry, list)); - } - - return builder.build(); - } - - @Override - public boolean isBanned(String target) { - Validate.notNull(target, "Target cannot be null"); - - GameProfile profile = 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 = getProfile(target); - list.remove(profile); - } - - private GameProfile getProfile(String target) { - UUID uuid = null; - - try { - uuid = UUID.fromString(target); - } catch (IllegalArgumentException ex) { - // - } - - return (uuid != null) ? MinecraftServer.getServer().getUserCache().a(uuid) : MinecraftServer.getServer().getUserCache().getProfile(target); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftRaid.java b/src/main/java/org/bukkit/craftbukkit/CraftRaid.java deleted file mode 100644 index d17cdcb1d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftRaid.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.bukkit.craftbukkit; - -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.function.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.EntityRaider; -import net.minecraft.server.World; -import org.bukkit.Location; -import org.bukkit.Raid; -import org.bukkit.entity.Raider; - -public final class CraftRaid implements Raid { - - private final net.minecraft.server.Raid handle; - - public CraftRaid(net.minecraft.server.Raid handle) { - this.handle = handle; - } - - @Override - public boolean isStarted() { - return handle.j(); // PAIL rename isStarted - } - - @Override - public long getActiveTicks() { - return handle.i; - } - - @Override - public int getBadOmenLevel() { - return handle.o; - } - - @Override - public void setBadOmenLevel(int badOmenLevel) { - int max = handle.l(); // PAIL rename getMaxBadOmenLevel - Preconditions.checkArgument(0 <= badOmenLevel && badOmenLevel <= max, "Bad Omen level must be between 0 and %s", max); - handle.o = badOmenLevel; - } - - @Override - public Location getLocation() { - BlockPosition pos = handle.t(); // PAIL rename getCenterLocation - World world = handle.i(); // PAIL rename getWorld - return new Location(world.getWorld(), pos.getX(), pos.getY(), pos.getZ()); - } - - @Override - public RaidStatus getStatus() { - if (handle.d()) { // PAIL rename isStopped - return RaidStatus.STOPPED; - } else if (handle.e()) { // PAIL rename isVictory - return RaidStatus.VICTORY; - } else if (handle.f()) { // PAIL rename isLoss - return RaidStatus.LOSS; - } else { - return RaidStatus.ONGOING; - } - } - - @Override - public int getSpawnedGroups() { - return handle.k(); // PAIL rename countSpawnedGroups - } - - @Override - public int getTotalGroups() { - return handle.v + (handle.o > 1 ? 1 : 0); - } - - @Override - public int getTotalWaves() { - return handle.v; - } - - @Override - public float getTotalHealth() { - return handle.q(); // PAIL rename sumMobHealth - } - - @Override - public Set getHeroes() { - return Collections.unmodifiableSet(handle.h); - } - - @Override - public List getRaiders() { - return handle.getRaiders().stream().map(new Function() { - @Override - public Raider apply(EntityRaider entityRaider) { - return (Raider) entityRaider.getBukkitEntity(); - } - }).collect(ImmutableList.toImmutableList()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java deleted file mode 100644 index 107d631e8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java +++ /dev/null @@ -1,2170 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import com.google.common.collect.MapMaker; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.mojang.authlib.GameProfile; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.tree.CommandNode; -import com.mojang.brigadier.tree.LiteralCommandNode; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufOutputStream; -import io.netty.buffer.Unpooled; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.function.Consumer; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.imageio.ImageIO; -import net.minecraft.server.Advancement; -import net.minecraft.server.ArgumentEntity; -import net.minecraft.server.Block; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.BossBattleCustom; -import net.minecraft.server.CommandDispatcher; -import net.minecraft.server.CommandListenerWrapper; -import net.minecraft.server.DedicatedPlayerList; -import net.minecraft.server.DedicatedServer; -import net.minecraft.server.DedicatedServerProperties; -import net.minecraft.server.DedicatedServerSettings; -import net.minecraft.server.DimensionManager; -import net.minecraft.server.Enchantments; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.EnumDifficulty; -import net.minecraft.server.EnumGamemode; -import net.minecraft.server.Item; -import net.minecraft.server.ItemWorldMap; -import net.minecraft.server.Items; -import net.minecraft.server.JsonListEntry; -import net.minecraft.server.LootTableRegistry; -import net.minecraft.server.MapIcon; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.MobEffects; -import net.minecraft.server.PlayerList; -import net.minecraft.server.ServerCommand; -import net.minecraft.server.TagsServer; -import net.minecraft.server.TicketType; -import net.minecraft.server.Vec3D; -import net.minecraft.server.WorldData; -import net.minecraft.server.WorldMap; -import net.minecraft.server.WorldNBTStorage; -import net.minecraft.server.WorldServer; -import net.minecraft.server.WorldSettings; -import net.minecraft.server.WorldType; -import org.apache.commons.lang.Validate; -import org.apache.commons.lang3.StringUtils; -import org.bukkit.BanList; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Keyed; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.OfflinePlayer; -import org.bukkit.Server; -import org.bukkit.StructureType; -import org.bukkit.UnsafeValues; -import org.bukkit.Warning.WarningState; -import org.bukkit.World; -import org.bukkit.World.Environment; -import org.bukkit.WorldCreator; -import org.bukkit.block.data.BlockData; -import org.bukkit.boss.BarColor; -import org.bukkit.boss.BarFlag; -import org.bukkit.boss.BarStyle; -import org.bukkit.boss.BossBar; -import org.bukkit.boss.KeyedBossBar; -import org.bukkit.command.Command; -import org.bukkit.command.CommandException; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.command.SimpleCommandMap; -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.block.data.CraftBlockData; -import org.bukkit.craftbukkit.boss.CraftBossBar; -import org.bukkit.craftbukkit.boss.CraftKeyedBossbar; -import org.bukkit.craftbukkit.command.BukkitCommandWrapper; -import org.bukkit.craftbukkit.command.CraftCommandMap; -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.CraftBlastingRecipe; -import org.bukkit.craftbukkit.inventory.CraftCampfireRecipe; -import org.bukkit.craftbukkit.inventory.CraftFurnaceRecipe; -import org.bukkit.craftbukkit.inventory.CraftItemFactory; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftMerchantCustom; -import org.bukkit.craftbukkit.inventory.CraftRecipe; -import org.bukkit.craftbukkit.inventory.CraftShapedRecipe; -import org.bukkit.craftbukkit.inventory.CraftShapelessRecipe; -import org.bukkit.craftbukkit.inventory.CraftSmokingRecipe; -import org.bukkit.craftbukkit.inventory.CraftStonecuttingRecipe; -import org.bukkit.craftbukkit.inventory.RecipeIterator; -import org.bukkit.craftbukkit.inventory.util.CraftInventoryCreator; -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.tag.CraftBlockTag; -import org.bukkit.craftbukkit.tag.CraftItemTag; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.craftbukkit.util.CraftIconCache; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.craftbukkit.util.DatFileFilter; -import org.bukkit.craftbukkit.util.Versioning; -import org.bukkit.craftbukkit.util.permissions.CraftDefaultPermissions; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.command.UnknownCommandEvent; // Paper -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.event.player.PlayerChatTabCompleteEvent; -import org.bukkit.event.server.BroadcastMessageEvent; -import org.bukkit.event.server.ServerLoadEvent; -import org.bukkit.event.server.TabCompleteEvent; -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.BlastingRecipe; -import org.bukkit.inventory.CampfireRecipe; -import org.bukkit.inventory.FurnaceRecipe; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.Recipe; -import org.bukkit.inventory.ShapedRecipe; -import org.bukkit.inventory.ShapelessRecipe; -import org.bukkit.inventory.SmokingRecipe; -import org.bukkit.inventory.StonecuttingRecipe; -import org.bukkit.loot.LootTable; -import org.bukkit.map.MapView; -import org.bukkit.permissions.Permissible; -import org.bukkit.permissions.Permission; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginLoadOrder; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.ServicesManager; -import org.bukkit.plugin.SimplePluginManager; -import org.bukkit.plugin.SimpleServicesManager; -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.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.SafeConstructor; -import org.yaml.snakeyaml.error.MarkedYAMLException; - -import net.md_5.bungee.api.chat.BaseComponent; // Spigot - -import javax.annotation.Nullable; // Paper -import javax.annotation.Nonnull; // Paper - -public final class CraftServer implements Server { - private final String serverName = "Akarin"; // Paper // Akarin - Rebrand - 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 CraftCommandMap commandMap = new CraftCommandMap(this); - private final SimpleHelpMap helpMap = new SimpleHelpMap(this); - private final StandardMessenger messenger = new StandardMessenger(); - private final SimplePluginManager pluginManager = new SimplePluginManager(this, commandMap); - protected final DedicatedServer console; - protected final DedicatedPlayerList playerList; - private final Map worlds = new LinkedHashMap(); - private YamlConfiguration configuration; - private YamlConfiguration commandsConfiguration; - 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 int monsterSpawn = -1; - private int animalSpawn = -1; - private int waterAnimalSpawn = -1; - private int ambientSpawn = -1; - private File container; - private WarningState warningState = WarningState.DEFAULT; - public String minimumAPI; - public CraftScoreboardManager scoreboardManager; - public boolean playerCommandState; - private boolean printSaveWarning; - private CraftIconCache icon; - private boolean overrideAllCommandBlockCommands = false; - public boolean ignoreVanillaPermissions = false; - private final List playerView; - public int reloadCount; - public static Exception excessiveVelEx; // Paper - Velocity warnings - - static { - ConfigurationSerialization.registerClass(CraftOfflinePlayer.class); - CraftItemFactory.instance(); - } - - public CraftServer(DedicatedServer console, PlayerList playerList) { - this.console = console; - this.playerList = (DedicatedPlayerList) playerList; - this.playerView = Collections.unmodifiableList(Lists.transform(playerList.players, new Function() { - @Override - public CraftPlayer apply(EntityPlayer player) { - return player.getBukkitEntity(); - } - })); - this.serverVersion = CraftServer.class.getPackage().getImplementationVersion(); - - Bukkit.setServer(this); - - // Register all the Enchantments and PotionTypes now so we can stop new registration immediately after - Enchantments.DAMAGE_ALL.getClass(); - org.bukkit.enchantments.Enchantment.stopAcceptingRegistrations(); - - Potion.setPotionBrewer(new CraftPotionBrewer()); - MobEffects.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("*"); - ignoreVanillaPermissions = commandsConfiguration.getBoolean("ignore-vanilla-permissions"); - pluginManager.useTimings(configuration.getBoolean("settings.plugin-profiling")); - 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")); - TicketType.PLUGIN.loadPeriod = configuration.getInt("chunk-gc.period-in-ticks"); - minimumAPI = configuration.getString("settings.minimum-api"); - loadIcon(); - } - - 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"); - } - - 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(); - if (com.destroystokyo.paper.PaperConfig.loadPermsBeforePlugins) loadCustomPermissions(); // Paper - } - - Plugin[] plugins = pluginManager.getPlugins(); - - for (Plugin plugin : plugins) { - if ((!plugin.isEnabled()) && (plugin.getDescription().getLoad() == type)) { - enablePlugin(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(); - DefaultPermissions.registerCorePermissions(); - CraftDefaultPermissions.registerCorePermissions(); - if (!com.destroystokyo.paper.PaperConfig.loadPermsBeforePlugins) loadCustomPermissions(); // Paper - helpMap.initializeCommands(); - syncCommands(); - } - } - - public void disablePlugins() { - pluginManager.disablePlugins(); - } - - private void setVanillaCommands(boolean first) { // Spigot - CommandDispatcher dispatcher = console.vanillaCommandDispatcher; - - // Build a list of all Vanilla commands and create wrappers - for (CommandNode cmd : dispatcher.a().getRoot().getChildren()) { - // Spigot start - VanillaCommandWrapper wrapper = new VanillaCommandWrapper(dispatcher, cmd); - 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 syncCommands() { - // Clear existing commands - CommandDispatcher dispatcher = console.commandDispatcher = new CommandDispatcher(); - - // Register all commands, vanilla ones will be using the old dispatcher references - for (Map.Entry entry : commandMap.getKnownCommands().entrySet()) { - String label = entry.getKey(); - Command command = entry.getValue(); - - if (command instanceof VanillaCommandWrapper) { - LiteralCommandNode node = (LiteralCommandNode) ((VanillaCommandWrapper) command).vanillaCommand; - if (!node.getLiteral().equals(label)) { - LiteralCommandNode clone = new LiteralCommandNode(label, node.getCommand(), node.getRequirement(), node.getRedirect(), node.getRedirectModifier(), node.isFork()); - - for (CommandNode child : node.getChildren()) { - clone.addChild(child); - } - node = clone; - } - - dispatcher.a().getRoot().addChild(node); - } else { - new BukkitCommandWrapper(this, entry.getValue()).register(dispatcher.a(), label); - } - } - - // Refresh commands - for (EntityPlayer player : getHandle().players) { - dispatcher.a(player); - } - } - - private void enablePlugin(Plugin plugin) { - try { - List perms = plugin.getDescription().getPermissions(); - - for (Permission perm : perms) { - try { - pluginManager.addPermission(perm, false); - } catch (IllegalArgumentException ex) { - getLogger().log(Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered", ex); - } - } - pluginManager.dirtyPermissibles(); - - pluginManager.enablePlugin(plugin); - } 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 - 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(java.util.Locale.ENGLISH); - int delta = Integer.MAX_VALUE; - for (Player player : getOnlinePlayers()) { - if (player.getName().toLowerCase(java.util.Locale.ENGLISH).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(java.util.Locale.ENGLISH).contains(partialName.toLowerCase(java.util.Locale.ENGLISH))) { - // Partial match - matchedPlayers.add(iterPlayer); - } - } - - return matchedPlayers; - } - - @Override - public int getMaxPlayers() { - return playerList.getMaxPlayers(); - } - - // NOTE: These are dependent on the corresponding call in MinecraftServer - // so if that changes this will need to as well - @Override - public int getPort() { - return this.getServer().getPort(); - } - - @Override - public int getViewDistance() { - return this.getProperties().viewDistance; - } - - @Override - public String getIp() { - return this.getServer().getServerIp(); - } - - @Override - public String getWorldType() { - return this.getProperties().levelType.name(); - } - - @Override - public boolean getGenerateStructures() { - return this.getServer().getGenerateStructures(); - } - - @Override - public boolean getAllowEnd() { - return this.configuration.getBoolean("settings.allow-end"); - } - - @Override - public boolean getAllowNether() { - return this.getServer().getAllowNether(); - } - - 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.getProperties().whiteList.get(); - } - - // NOTE: Temporary calls through to server.properies until its replaced - private DedicatedServerProperties getProperties() { - return this.console.getDedicatedServerProperties(); - } - // End Temporary calls - - @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 || com.destroystokyo.paper.PaperConfig.velocitySupport) { // Paper - Velocity support - 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"); - org.spigotmc.AsyncCatcher.catchOp("command dispatch"); // Spigot - - // Paper Start - if (!org.spigotmc.AsyncCatcher.shuttingDown && !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); - } - }; - net.minecraft.server.MinecraftServer.getServer().processQueue.add(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()); - } - } - // Paper End - - if (commandMap.dispatch(sender, commandLine)) { - return true; - } - - // Spigot start - if (!org.spigotmc.SpigotConfig.unknownCommandMessage.isEmpty()) { - // Paper start - UnknownCommandEvent event = new UnknownCommandEvent(sender, commandLine, org.spigotmc.SpigotConfig.unknownCommandMessage); - Bukkit.getServer().getPluginManager().callEvent(event); - if (StringUtils.isNotEmpty(event.getMessage())) { - sender.sendMessage(event.getMessage()); - } - // Paper end - } - // Spigot end - - return false; - } - - @Override - public void reload() { - org.spigotmc.WatchdogThread.hasStarted = false; // Paper - Disable watchdog early timeout on reload - reloadCount++; - configuration = YamlConfiguration.loadConfiguration(getConfigFile()); - commandsConfiguration = YamlConfiguration.loadConfiguration(getCommandsConfigFile()); - - console.propertyManager = new DedicatedServerSettings(console.options); - DedicatedServerProperties config = console.propertyManager.getProperties(); - - console.setSpawnAnimals(config.spawnAnimals); - console.setPVP(config.pvp); - console.setAllowFlight(config.allowFlight); - console.setMotd(config.motd); - 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")); - TicketType.PLUGIN.loadPeriod = configuration.getInt("chunk-gc.period-in-ticks"); - minimumAPI = configuration.getString("settings.minimum-api"); - printSaveWarning = false; - console.autosavePeriod = configuration.getInt("ticks-per.autosave"); - 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 - com.destroystokyo.paper.PaperConfig.init((File) console.options.valueOf("paper-settings")); // Paper - for (WorldServer world : console.getWorlds()) { - world.worldData.setDifficulty(config.difficulty); - world.setSpawnFlags(config.spawnMonsters, config.spawnAnimals); - if (this.getTicksPerAnimalSpawns() < 0) { - world.ticksPerAnimalSpawns = 400; - } else { - world.ticksPerAnimalSpawns = this.getTicksPerAnimalSpawns(); - } - - if (this.getTicksPerMonsterSpawns() < 0) { - world.ticksPerMonsterSpawns = 1; - } else { - world.ticksPerMonsterSpawns = this.getTicksPerMonsterSpawns(); - } - world.spigotConfig.init(); // Spigot - world.paperConfig.init(); // Paper - } - - Plugin[] pluginClone = pluginManager.getPlugins().clone(); // Paper - pluginManager.clearPlugins(); - commandMap.clearCommands(); - - // Paper start - for (Plugin plugin : pluginClone) { - entityMetadata.removeAll(plugin); - worldMetadata.removeAll(plugin); - playerMetadata.removeAll(plugin); - } - // Paper end - - resetRecipes(); - reloadData(); - org.spigotmc.SpigotConfig.registerCommands(); // Spigot - com.destroystokyo.paper.PaperConfig.registerCommands(); // Paper - overrideAllCommandBlockCommands = commandsConfiguration.getStringList("command-block-overrides").contains("*"); - ignoreVanillaPermissions = commandsConfiguration.getBoolean("ignore-vanilla-permissions"); - - int pollCount = 0; - - // Wait for at most 2.5 seconds for plugins to close their threads - while (pollCount < 50 && getScheduler().getActiveWorkers().size() > 0) { - try { - Thread.sleep(50); - } catch (InterruptedException e) {} - 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); - getPluginManager().callEvent(new ServerLoadEvent(ServerLoadEvent.LoadType.RELOAD)); - org.spigotmc.WatchdogThread.hasStarted = true; // Paper - Disable watchdog early timeout on reload - } - - @Override - public void reloadData() { - console.reload(); - } - - 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.toString()); - return; - } catch (Throwable ex) { - getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML.", ex); - return; - } finally { - try { - stream.close(); - } catch (IOException ex) {} - } - - if (perms == null) { - getLogger().log(Level.INFO, "Server permissions file " + file + " is empty, ignoring it"); - 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) { - Preconditions.checkState(!console.worldServer.isEmpty(), "Cannot create additional worlds on STARTUP"); - 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); - } - - console.convertWorld(name); - - int dimension = CraftWorld.CUSTOM_DIMENSION_OFFSET + console.worldServer.size(); - boolean used = false; - do { - for (WorldServer server : console.getWorlds()) { - used = server.getWorldProvider().getDimensionManager().getDimensionID() + 1 == dimension; // Paper - getDimensionID returns the dimension - 1, so we have to add 1 - if (used) { - dimension++; - break; - } - } - } while(used); - boolean hardcore = false; - - WorldNBTStorage sdm = new WorldNBTStorage(getWorldContainer(), name, getServer(), getHandle().getServer().dataConverterManager); - WorldData worlddata = sdm.getWorldData(); - WorldSettings worldSettings; - // See MinecraftServer.a(String, String, long, WorldType, JsonElement) - if (worlddata == null) { - worldSettings = new WorldSettings(com.destroystokyo.paper.PaperConfig.seedOverride.getOrDefault(name, creator.seed()), EnumGamemode.getById(getDefaultGameMode().getValue()), generateStructures, hardcore, type); // Paper - JsonElement parsedSettings = new JsonParser().parse(creator.generatorSettings()); - if (parsedSettings.isJsonObject()) { - worldSettings.setGeneratorSettings(parsedSettings.getAsJsonObject()); - } - worlddata = new WorldData(worldSettings, name); - } else { - worlddata.setName(name); - worldSettings = new WorldSettings(worlddata); - } - - DimensionManager actualDimension = DimensionManager.a(creator.environment().getId()); - DimensionManager internalDimension = DimensionManager.register(name.toLowerCase(java.util.Locale.ENGLISH), new DimensionManager(dimension, actualDimension.getSuffix(), actualDimension.folder, (w, manager) -> actualDimension.providerFactory.apply(w, manager), actualDimension.hasSkyLight(), actualDimension)); - WorldServer internal = (WorldServer) new WorldServer(console, console.executorService, sdm, worlddata, internalDimension, console.getMethodProfiler(), getServer().worldLoadListenerFactory.create(11), creator.environment(), generator); - - if (!(worlds.containsKey(name.toLowerCase(java.util.Locale.ENGLISH)))) { - return null; - } - - console.initWorld(internal, worlddata, worldSettings); - - internal.worldData.setDifficulty(EnumDifficulty.EASY); - internal.setSpawnFlags(true, true); - console.worldServer.put(internal.getWorldProvider().getDimensionManager(), internal); - - pluginManager.callEvent(new WorldInitEvent(internal.getWorld())); - - getServer().loadSpawn(internal.getChunkProvider().playerChunkMap.worldLoadListener, internal); - - 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.worldServer.containsKey(handle.getWorldProvider().getDimensionManager()))) { - return false; - } - - if (handle.getWorldProvider().getDimensionManager() == DimensionManager.OVERWORLD) { - return false; - } - - if (handle.getPlayers().size() > 0) { - return false; - } - - WorldUnloadEvent e = new WorldUnloadEvent(handle.getWorld()); - pluginManager.callEvent(e); - - if (e.isCancelled()) { - return false; - } - - try { - if (save) { - handle.save(null, true, true); - } - - handle.getChunkProvider().close(save); - } catch (Exception ex) { - getLogger().log(Level.SEVERE, null, ex); - } - - worlds.remove(world.getName().toLowerCase(java.util.Locale.ENGLISH)); - console.worldServer.remove(handle.getWorldProvider().getDimensionManager()); - return true; - } - - public DedicatedServer getServer() { - return console; - } - - @Override - public World getWorld(String name) { - Validate.notNull(name, "Name cannot be null"); - - return worlds.get(name.toLowerCase(java.util.Locale.ENGLISH)); - } - - @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) { - // 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(java.util.Locale.ENGLISH), world); - } - - @Override - public Logger getLogger() { - return logger; - } - - // Paper start - JLine update - /* - public ConsoleReader getReader() { - return console.reader; - } - */ - // Paper end - - @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 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 if (recipe instanceof BlastingRecipe) { - toAdd = CraftBlastingRecipe.fromBukkitRecipe((BlastingRecipe) recipe); - } else if (recipe instanceof CampfireRecipe) { - toAdd = CraftCampfireRecipe.fromBukkitRecipe((CampfireRecipe) recipe); - } else if (recipe instanceof SmokingRecipe) { - toAdd = CraftSmokingRecipe.fromBukkitRecipe((SmokingRecipe) recipe); - } else if (recipe instanceof StonecuttingRecipe) { - toAdd = CraftStonecuttingRecipe.fromBukkitRecipe((StonecuttingRecipe) recipe); - } else { - return false; - } - } - toAdd.addToCraftingManager(); - 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() { - console.getCraftingManager().clearRecipes(); - } - - @Override - public void resetRecipes() { - console.reload(); // Not ideal but hard to reload a subset of a resource pack - } - - @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[commands.size()])); - } - } - - 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 this.getServer().getSpawnProtection(); - } - - @Override - public void setSpawnRadius(int value) { - configuration.set("settings.spawn-radius", value); - saveConfig(); - } - - @Override - public boolean getOnlineMode() { - return console.getOnlineMode(); - } - - @Override - public boolean getAllowFlight() { - return console.getAllowFlight(); - } - - @Override - public boolean isHardcore() { - return console.isHardcore(); - } - - 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(int id) { - WorldMap worldmap = console.getWorldServer(DimensionManager.OVERWORLD).a("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); - WorldMap worldmap = ItemWorldMap.getSavedMap(stack, ((CraftWorld) world).getHandle()); - return worldmap.mapView; - } - - @Override - public ItemStack createExplorerMap(World world, Location location, StructureType structureType) { - return this.createExplorerMap(world, location, structureType, 100, true); - } - - @Override - public ItemStack createExplorerMap(World world, Location location, StructureType structureType, int radius, boolean findUnexplored) { - Validate.notNull(world, "World cannot be null"); - Validate.notNull(structureType, "StructureType cannot be null"); - Validate.notNull(structureType.getMapIcon(), "Cannot create explorer maps for StructureType " + structureType.getName()); - - WorldServer worldServer = ((CraftWorld) world).getHandle(); - Location structureLocation = world.locateNearestStructure(location, structureType, radius, findUnexplored); - BlockPosition structurePosition = new BlockPosition(structureLocation.getBlockX(), structureLocation.getBlockY(), structureLocation.getBlockZ()); - - // Create map with trackPlayer = true, unlimitedTracking = true - net.minecraft.server.ItemStack stack = ItemWorldMap.createFilledMapView(worldServer, structurePosition.getX(), structurePosition.getZ(), MapView.Scale.NORMAL.getValue(), true, true); - ItemWorldMap.applySepiaFilter(worldServer, stack); - // "+" map ID taken from EntityVillager - ItemWorldMap.getSavedMap(stack, worldServer).decorateMap(stack, structurePosition, "+", MapIcon.Type.a(structureType.getMapIcon().getValue())); - - return CraftItemStack.asBukkitCopy(stack); - } - - @Override - public void shutdown() { - console.safeShutdown(false); - } - - @Override - public int broadcast(String message, String permission) { - Set recipients = new HashSet<>(); - for (Permissible permissible : getPluginManager().getPermissionSubscriptions(permission)) { - if (permissible instanceof CommandSender && permissible.hasPermission(permission)) { - recipients.add((CommandSender) permissible); - } - } - - BroadcastMessageEvent broadcastMessageEvent = new BroadcastMessageEvent(!Bukkit.isPrimaryThread(), message, recipients); - getPluginManager().callEvent(broadcastMessageEvent); - - if (broadcastMessageEvent.isCancelled()) { - return 0; - } - - message = broadcastMessageEvent.getMessage(); - - for (CommandSender recipient : recipients) { - recipient.sendMessage(message); - } - - return recipients.size(); - } - - // Paper start - @Nullable - public UUID getPlayerUniqueId(String name) { - Player player = Bukkit.getPlayerExact(name); - if (player != null) { - return player.getUniqueId(); - } - GameProfile profile; - // Only fetch an online UUID in online mode - if (net.minecraft.server.MinecraftServer.getServer().getOnlineMode() - || (org.spigotmc.SpigotConfig.bungee && com.destroystokyo.paper.PaperConfig.bungeeOnlineMode)) { - profile = console.getUserCache().getProfile( name ); - } else { - // Make an OfflinePlayer using an offline mode UUID since the name has no profile - profile = new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)), name); - } - return profile != null ? profile.getId() : null; - } - // Paper end - - @Override - @Deprecated - public OfflinePlayer getOfflinePlayer(String name) { - Validate.notNull(name, "Name cannot be null"); - Validate.notEmpty(name, "Name cannot be empty"); - - OfflinePlayer result = getPlayerExact(name); - if (result == null) { - // Spigot Start - GameProfile profile = null; - // Only fetch an online UUID in online mode - if ( getOnlineMode() - || com.destroystokyo.paper.PaperConfig.isProxyOnlineMode() ) // Paper - Handle via setting - { - profile = console.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 - @SuppressWarnings("unchecked") - 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((GameProfile) 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.setHasWhitelist(value); - } - - @Override - public Set getWhitelistedPlayers() { - Set result = new LinkedHashSet(); - - for (JsonListEntry entry : playerList.getWhitelist().getValues()) { - result.add(getOfflinePlayer((GameProfile) entry.getKey())); - } - - return result; - } - - @Override - public Set getOperators() { - Set result = new HashSet(); - - for (JsonListEntry entry : playerList.getOPs().getValues()) { - result.add(getOfflinePlayer((GameProfile) entry.getKey())); - } - - return result; - } - - @Override - public void reloadWhitelist() { - playerList.reloadWhitelist(); - } - - @Override - public GameMode getDefaultGameMode() { - return GameMode.getByValue(console.getWorldServer(DimensionManager.OVERWORLD).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(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.getWorldServer(DimensionManager.OVERWORLD).getDataManager(); - String[] files = storage.getPlayerDir().list(new DatFileFilter()); - Set players = new HashSet(); - - for (String file : files) { - try { - players.add(getOfflinePlayer(UUID.fromString(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[players.size()]); - } - - @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) { - Validate.isTrue(type.isCreatable(), "Cannot open an inventory of type ", type); - return CraftInventoryCreator.INSTANCE.createInventory(owner, type); - } - - @Override - public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { - Validate.isTrue(type.isCreatable(), "Cannot open an inventory of type ", type); - return CraftInventoryCreator.INSTANCE.createInventory(owner, type, title); - } - - @Override - public Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException { - Validate.isTrue(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got " + size + ")"); - return CraftInventoryCreator.INSTANCE.createInventory(owner, size); - } - - @Override - public Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException { - Validate.isTrue(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got " + size + ")"); - return CraftInventoryCreator.INSTANCE.createInventory(owner, size, title); - } - - @Override - public Merchant createMerchant(String title) { - return new CraftMerchantCustom(title == null ? InventoryType.MERCHANT.getDefaultTitle() : 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; - } - - @Override - public boolean isPrimaryThread() { - return Thread.currentThread().equals(console.serverThread); // Paper - Fix issues with detecting main thread properly - } - - @Override - public String getMotd() { - return console.getMotd(); - } - - @Override - public WarningState getWarningState() { - return warningState; - } - - public List tabComplete(CommandSender sender, String message, WorldServer world, Vec3D pos, boolean forceCommand) { - if (!(sender instanceof Player)) { - return ImmutableList.of(); - } - - List offers; - Player player = (Player) sender; - if (message.startsWith("/") || forceCommand) { - offers = tabCompleteCommand(player, message, world, pos); - } else { - offers = tabCompleteChat(player, message); - } - - TabCompleteEvent tabEvent = new TabCompleteEvent(player, message, offers, message.startsWith("/") || forceCommand, pos != null ? net.minecraft.server.MCUtil.toLocation(((CraftWorld) player.getWorld()).getHandle(), new BlockPosition(pos)) : null); // Paper - getPluginManager().callEvent(tabEvent); - - return tabEvent.isCancelled() ? Collections.EMPTY_LIST : tabEvent.getCompletions(); - } - - public List tabCompleteCommand(Player player, String message, WorldServer world, Vec3D pos) { - // 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 { - if (message.startsWith("/")) { - // Trim leading '/' if present (won't always be present in command blocks) - message = message.substring(1); - } - if (pos == null) { - completions = getCommandMap().tabComplete(player, message); - } else { - completions = getCommandMap().tabComplete(player, message, new Location(world.getWorld(), pos.x, pos.y, pos.z)); - } - } 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()); - } - } - pluginManager.callEvent(event); - - Iterator it = completions.iterator(); - while (it.hasNext()) { - Object current = it.next(); - if (!(current instanceof String)) { - // Sanity - it.remove(); - } - } - Collections.sort(completions, 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); - } - - static CraftIconCache loadServerIcon0(File file) throws Exception { - return loadServerIcon0(ImageIO.read(file)); - } - - @Override - public CraftIconCache loadServerIcon(BufferedImage image) throws Exception { - Validate.notNull(image, "Image cannot be null"); - return loadServerIcon0(image); - } - - static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception { - ByteBuf bytebuf = Unpooled.buffer(); - - 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)); - ByteBuffer bytebuffer = Base64.getEncoder().encode(bytebuf.nioBuffer()); - - return new CraftIconCache("data:image/png;base64," + StandardCharsets.UTF_8.decode(bytebuffer)); - } - - @Override - public void setIdleTimeout(int threshold) { - console.setIdleTimeout(threshold); - } - - @Override - public int getIdleTimeout() { - return console.getIdleTimeout(); - } - - @Override - public ChunkGenerator.ChunkData createChunkData(World world) { - Validate.notNull(world, "World cannot be null"); - return new CraftChunkData(world); - } - - @Override - public BossBar createBossBar(String title, BarColor color, BarStyle style, BarFlag... flags) { - return new CraftBossBar(title, color, style, flags); - } - - @Override - public KeyedBossBar createBossBar(NamespacedKey key, String title, BarColor barColor, BarStyle barStyle, BarFlag... barFlags) { - Preconditions.checkArgument(key != null, "key"); - - BossBattleCustom bossBattleCustom = getServer().getBossBattleCustomData().register(CraftNamespacedKey.toMinecraft(key), CraftChatMessage.fromString(title, true)[0]); - CraftKeyedBossbar craftKeyedBossbar = new CraftKeyedBossbar(bossBattleCustom); - craftKeyedBossbar.setColor(barColor); - craftKeyedBossbar.setStyle(barStyle); - for (BarFlag flag : barFlags) { - craftKeyedBossbar.addFlag(flag); - } - - return craftKeyedBossbar; - } - - @Override - public Iterator getBossBars() { - return Iterators.unmodifiableIterator(Iterators.transform(getServer().getBossBattleCustomData().getBattles().iterator(), new Function() { - @Override - public org.bukkit.boss.KeyedBossBar apply(BossBattleCustom bossBattleCustom) { - return bossBattleCustom.getBukkitEntity(); - } - })); - } - - @Override - public KeyedBossBar getBossBar(NamespacedKey key) { - Preconditions.checkArgument(key != null, "key"); - net.minecraft.server.BossBattleCustom bossBattleCustom = getServer().getBossBattleCustomData().a(CraftNamespacedKey.toMinecraft(key)); - - return (bossBattleCustom == null) ? null : bossBattleCustom.getBukkitEntity(); - } - - @Override - public boolean removeBossBar(NamespacedKey key) { - Preconditions.checkArgument(key != null, "key"); - net.minecraft.server.BossBattleCustomData bossBattleCustomData = getServer().getBossBattleCustomData(); - net.minecraft.server.BossBattleCustom bossBattleCustom = bossBattleCustomData.a(CraftNamespacedKey.toMinecraft(key)); - - if (bossBattleCustom != null) { - bossBattleCustomData.remove(bossBattleCustom); - return true; - } - - return false; - } - - @Override - public Entity getEntity(UUID uuid) { - Validate.notNull(uuid, "UUID cannot be null"); - - for (WorldServer world : getServer().getWorlds()) { - net.minecraft.server.Entity entity = world.getEntity(uuid); - if (entity != null) { - return entity.getBukkitEntity(); - } - } - - return null; - } - - @Override - public org.bukkit.advancement.Advancement getAdvancement(NamespacedKey key) { - Preconditions.checkArgument(key != null, "key"); - - Advancement advancement = console.getAdvancementData().a(CraftNamespacedKey.toMinecraft(key)); - return (advancement == null) ? null : advancement.bukkit; - } - - @Override - public Iterator advancementIterator() { - return Iterators.unmodifiableIterator(Iterators.transform(console.getAdvancementData().a().iterator(), new Function() { // PAIL: rename - @Override - public org.bukkit.advancement.Advancement apply(Advancement advancement) { - return advancement.bukkit; - } - })); - } - - @Override - public BlockData createBlockData(org.bukkit.Material material) { - Validate.isTrue(material != null, "Must provide material"); - - return createBlockData(material, (String) null); - } - - @Override - public BlockData createBlockData(org.bukkit.Material material, Consumer consumer) { - BlockData data = createBlockData(material); - - if (consumer != null) { - consumer.accept(data); - } - - return data; - } - - @Override - public BlockData createBlockData(String data) throws IllegalArgumentException { - Validate.isTrue(data != null, "Must provide data"); - - return createBlockData(null, data); - } - - @Override - public BlockData createBlockData(org.bukkit.Material material, String data) { - Validate.isTrue(material != null || data != null, "Must provide one of material or data"); - - return CraftBlockData.newData(material, data); - } - - @Override - @SuppressWarnings("unchecked") - public org.bukkit.Tag getTag(String registry, NamespacedKey tag, Class clazz) { - MinecraftKey key = CraftNamespacedKey.toMinecraft(tag); - - switch (registry) { - case org.bukkit.Tag.REGISTRY_BLOCKS: - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Block namespace must have material type"); - - return (org.bukkit.Tag) new CraftBlockTag(console.getTagRegistry().getBlockTags(), key); - case org.bukkit.Tag.REGISTRY_ITEMS: - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Item namespace must have material type"); - - return (org.bukkit.Tag) new CraftItemTag(console.getTagRegistry().getItemTags(), key); - default: - throw new IllegalArgumentException(); - } - } - - @Override - @SuppressWarnings("unchecked") - public Iterable> getTags(String registry, Class clazz) { - switch (registry) { - case org.bukkit.Tag.REGISTRY_BLOCKS: - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Block namespace must have material type"); - - TagsServer blockTags = console.getTagRegistry().getBlockTags(); - return blockTags.b().keySet().stream().map(key -> (org.bukkit.Tag) new CraftBlockTag(blockTags, key)).collect(ImmutableList.toImmutableList()); - case org.bukkit.Tag.REGISTRY_ITEMS: - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Item namespace must have material type"); - - TagsServer itemTags = console.getTagRegistry().getItemTags(); - return itemTags.b().keySet().stream().map(key -> (org.bukkit.Tag) new CraftItemTag(itemTags, key)).collect(ImmutableList.toImmutableList()); - default: - throw new IllegalArgumentException(); - } - } - - @Override - public LootTable getLootTable(NamespacedKey key) { - Validate.notNull(key, "NamespacedKey cannot be null"); - - LootTableRegistry registry = getServer().getLootTableRegistry(); - return new CraftLootTable(key, registry.getLootTable(CraftNamespacedKey.toMinecraft(key))); - } - - @Override - public List selectEntities(CommandSender sender, String selector) { - Preconditions.checkArgument(selector != null, "Selector cannot be null"); - Preconditions.checkArgument(sender != null, "Sender cannot be null"); - - ArgumentEntity arg = ArgumentEntity.multipleEntities(); - List nms; - - try { - StringReader reader = new StringReader(selector); - nms = arg.parse(reader, true).getEntities(VanillaCommandWrapper.getListener(sender)); - Preconditions.checkArgument(!reader.canRead(), "Spurious trailing data in selector: " + selector); - } catch (CommandSyntaxException ex) { - throw new IllegalArgumentException("Could not parse selector: " + selector, ex); - } - - return new ArrayList<>(Lists.transform(nms, (entity) -> entity.getBukkitEntity())); - } - - @Deprecated - @Override - public UnsafeValues getUnsafe() { - return CraftMagicNumbers.INSTANCE; - } - - // Paper - Add getTPS API - Further improve tick loop - @Override - public double[] getTPS() { - return new double[] { - net.minecraft.server.MinecraftServer.getServer().tps1.getAverage(), - net.minecraft.server.MinecraftServer.getServer().tps5.getAverage(), - net.minecraft.server.MinecraftServer.getServer().tps15.getAverage() - }; - } - // Paper end - - private final Spigot spigot = new Spigot() - { - - @Deprecated - @Override - public YamlConfiguration getConfig() - { - return org.spigotmc.SpigotConfig.config; - } - - @Override - public YamlConfiguration getBukkitConfig() - { - return configuration; - } - - @Override - public YamlConfiguration getSpigotConfig() - { - return org.spigotmc.SpigotConfig.config; - } - - @Override - public YamlConfiguration getPaperConfig() - { - return com.destroystokyo.paper.PaperConfig.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); - } - } - }; - - public Spigot spigot() - { - return spigot; - } - - // Paper start - @SuppressWarnings({"rawtypes", "unchecked"}) - public static java.nio.file.Path dumpHeap(java.nio.file.Path dir, String name) { - try { - java.nio.file.Files.createDirectories(dir); - - javax.management.MBeanServer server = java.lang.management.ManagementFactory.getPlatformMBeanServer(); - java.nio.file.Path file; - - try { - Class clazz = Class.forName("openj9.lang.management.OpenJ9DiagnosticsMXBean"); - Object openj9Mbean = java.lang.management.ManagementFactory.newPlatformMXBeanProxy(server, "openj9.lang.management:type=OpenJ9Diagnostics", clazz); - java.lang.reflect.Method m = clazz.getMethod("triggerDumpToFile", String.class, String.class); - file = dir.resolve(name + ".phd"); - m.invoke(openj9Mbean, "heap", file.toString()); - } catch (ClassNotFoundException e) { - Class clazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean"); - Object hotspotMBean = java.lang.management.ManagementFactory.newPlatformMXBeanProxy(server, "com.sun.management:type=HotSpotDiagnostic", clazz); - java.lang.reflect.Method m = clazz.getMethod("dumpHeap", String.class, boolean.class); - file = dir.resolve(name + ".hprof"); - m.invoke(hotspotMBean, file.toString(), true); - } - - return file; - } catch (Throwable t) { - Bukkit.getLogger().log(Level.SEVERE, "Could not write heap", t); - return null; - } - } - - @Override - public void reloadPermissions() { - pluginManager.clearPermissions(); - if (com.destroystokyo.paper.PaperConfig.loadPermsBeforePlugins) loadCustomPermissions(); - for (Plugin plugin : pluginManager.getPlugins()) { - for (Permission perm : plugin.getDescription().getPermissions()) { - 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); - } - } - } - if (!com.destroystokyo.paper.PaperConfig.loadPermsBeforePlugins) loadCustomPermissions(); - DefaultPermissions.registerCorePermissions(); - CraftDefaultPermissions.registerCorePermissions(); - } - - @Override - public boolean reloadCommandAliases() { - Set removals = getCommandAliases().keySet().stream() - .map(key -> key.toLowerCase(java.util.Locale.ENGLISH)) - .collect(java.util.stream.Collectors.toSet()); - getCommandMap().getKnownCommands().keySet().removeIf(removals::contains); - File file = getCommandsConfigFile(); - try { - commandsConfiguration.load(file); - } catch (FileNotFoundException ex) { - return false; - } catch (IOException | org.bukkit.configuration.InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); - return false; - } - commandMap.registerServerAliases(); - return true; - } - - @Override - public boolean suggestPlayerNamesWhenNullTabCompletions() { - return com.destroystokyo.paper.PaperConfig.suggestPlayersWhenNullTabCompletions; - } - - @Override - public String getPermissionMessage() { - return com.destroystokyo.paper.PaperConfig.noPermissionMessage; - } - - @Override - public com.destroystokyo.paper.profile.PlayerProfile createProfile(@Nonnull UUID uuid) { - return createProfile(uuid, null); - } - - @Override - public com.destroystokyo.paper.profile.PlayerProfile createProfile(@Nonnull String name) { - return createProfile(null, name); - } - - @Override - public com.destroystokyo.paper.profile.PlayerProfile createProfile(@Nullable UUID uuid, @Nullable String name) { - Player player = uuid != null ? Bukkit.getPlayer(uuid) : (name != null ? Bukkit.getPlayerExact(name) : null); - if (player != null) { - return new com.destroystokyo.paper.profile.CraftPlayerProfile((CraftPlayer)player); - } - return new com.destroystokyo.paper.profile.CraftPlayerProfile(uuid, name); - } - - @Override - public int getCurrentTick() { - return net.minecraft.server.MinecraftServer.currentTick; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftSound.java b/src/main/java/org/bukkit/craftbukkit/CraftSound.java deleted file mode 100644 index 9f317ff2e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftSound.java +++ /dev/null @@ -1,841 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Preconditions; -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.SoundEffect; -import org.apache.commons.lang.Validate; -import org.bukkit.Sound; - -public enum CraftSound { - - AMBIENT_CAVE("ambient.cave"), - AMBIENT_UNDERWATER_ENTER("ambient.underwater.enter"), - AMBIENT_UNDERWATER_EXIT("ambient.underwater.exit"), - AMBIENT_UNDERWATER_LOOP("ambient.underwater.loop"), - AMBIENT_UNDERWATER_LOOP_ADDITIONS("ambient.underwater.loop.additions"), - AMBIENT_UNDERWATER_LOOP_ADDITIONS_RARE("ambient.underwater.loop.additions.rare"), - AMBIENT_UNDERWATER_LOOP_ADDITIONS_ULTRA_RARE("ambient.underwater.loop.additions.ultra_rare"), - BLOCK_ANVIL_BREAK("block.anvil.break"), - BLOCK_ANVIL_DESTROY("block.anvil.destroy"), - BLOCK_ANVIL_FALL("block.anvil.fall"), - BLOCK_ANVIL_HIT("block.anvil.hit"), - BLOCK_ANVIL_LAND("block.anvil.land"), - BLOCK_ANVIL_PLACE("block.anvil.place"), - BLOCK_ANVIL_STEP("block.anvil.step"), - BLOCK_ANVIL_USE("block.anvil.use"), - BLOCK_BAMBOO_BREAK("block.bamboo.break"), - BLOCK_BAMBOO_FALL("block.bamboo.fall"), - BLOCK_BAMBOO_HIT("block.bamboo.hit"), - BLOCK_BAMBOO_PLACE("block.bamboo.place"), - BLOCK_BAMBOO_SAPLING_BREAK("block.bamboo_sapling.break"), - BLOCK_BAMBOO_SAPLING_HIT("block.bamboo_sapling.hit"), - BLOCK_BAMBOO_SAPLING_PLACE("block.bamboo_sapling.place"), - BLOCK_BAMBOO_STEP("block.bamboo.step"), - BLOCK_BARREL_CLOSE("block.barrel.close"), - BLOCK_BARREL_OPEN("block.barrel.open"), - BLOCK_BEACON_ACTIVATE("block.beacon.activate"), - BLOCK_BEACON_AMBIENT("block.beacon.ambient"), - BLOCK_BEACON_DEACTIVATE("block.beacon.deactivate"), - BLOCK_BEACON_POWER_SELECT("block.beacon.power_select"), - BLOCK_BELL_RESONATE("block.bell.resonate"), - BLOCK_BELL_USE("block.bell.use"), - BLOCK_BLASTFURNACE_FIRE_CRACKLE("block.blastfurnace.fire_crackle"), - BLOCK_BREWING_STAND_BREW("block.brewing_stand.brew"), - BLOCK_BUBBLE_COLUMN_BUBBLE_POP("block.bubble_column.bubble_pop"), - BLOCK_BUBBLE_COLUMN_UPWARDS_AMBIENT("block.bubble_column.upwards_ambient"), - BLOCK_BUBBLE_COLUMN_UPWARDS_INSIDE("block.bubble_column.upwards_inside"), - BLOCK_BUBBLE_COLUMN_WHIRLPOOL_AMBIENT("block.bubble_column.whirlpool_ambient"), - BLOCK_BUBBLE_COLUMN_WHIRLPOOL_INSIDE("block.bubble_column.whirlpool_inside"), - BLOCK_CAMPFIRE_CRACKLE("block.campfire.crackle"), - BLOCK_CHEST_CLOSE("block.chest.close"), - BLOCK_CHEST_LOCKED("block.chest.locked"), - BLOCK_CHEST_OPEN("block.chest.open"), - BLOCK_CHORUS_FLOWER_DEATH("block.chorus_flower.death"), - BLOCK_CHORUS_FLOWER_GROW("block.chorus_flower.grow"), - BLOCK_COMPARATOR_CLICK("block.comparator.click"), - BLOCK_COMPOSTER_EMPTY("block.composter.empty"), - BLOCK_COMPOSTER_FILL("block.composter.fill"), - BLOCK_COMPOSTER_FILL_SUCCESS("block.composter.fill_success"), - BLOCK_COMPOSTER_READY("block.composter.ready"), - BLOCK_CONDUIT_ACTIVATE("block.conduit.activate"), - BLOCK_CONDUIT_AMBIENT("block.conduit.ambient"), - BLOCK_CONDUIT_AMBIENT_SHORT("block.conduit.ambient.short"), - BLOCK_CONDUIT_ATTACK_TARGET("block.conduit.attack.target"), - BLOCK_CONDUIT_DEACTIVATE("block.conduit.deactivate"), - BLOCK_CORAL_BLOCK_BREAK("block.coral_block.break"), - BLOCK_CORAL_BLOCK_FALL("block.coral_block.fall"), - BLOCK_CORAL_BLOCK_HIT("block.coral_block.hit"), - BLOCK_CORAL_BLOCK_PLACE("block.coral_block.place"), - BLOCK_CORAL_BLOCK_STEP("block.coral_block.step"), - BLOCK_CROP_BREAK("block.crop.break"), - BLOCK_DISPENSER_DISPENSE("block.dispenser.dispense"), - BLOCK_DISPENSER_FAIL("block.dispenser.fail"), - BLOCK_DISPENSER_LAUNCH("block.dispenser.launch"), - BLOCK_ENCHANTMENT_TABLE_USE("block.enchantment_table.use"), - BLOCK_ENDER_CHEST_CLOSE("block.ender_chest.close"), - BLOCK_ENDER_CHEST_OPEN("block.ender_chest.open"), - BLOCK_END_GATEWAY_SPAWN("block.end_gateway.spawn"), - BLOCK_END_PORTAL_FRAME_FILL("block.end_portal_frame.fill"), - BLOCK_END_PORTAL_SPAWN("block.end_portal.spawn"), - BLOCK_FENCE_GATE_CLOSE("block.fence_gate.close"), - BLOCK_FENCE_GATE_OPEN("block.fence_gate.open"), - BLOCK_FIRE_AMBIENT("block.fire.ambient"), - BLOCK_FIRE_EXTINGUISH("block.fire.extinguish"), - BLOCK_FURNACE_FIRE_CRACKLE("block.furnace.fire_crackle"), - BLOCK_GLASS_BREAK("block.glass.break"), - BLOCK_GLASS_FALL("block.glass.fall"), - BLOCK_GLASS_HIT("block.glass.hit"), - BLOCK_GLASS_PLACE("block.glass.place"), - BLOCK_GLASS_STEP("block.glass.step"), - BLOCK_GRASS_BREAK("block.grass.break"), - BLOCK_GRASS_FALL("block.grass.fall"), - BLOCK_GRASS_HIT("block.grass.hit"), - BLOCK_GRASS_PLACE("block.grass.place"), - BLOCK_GRASS_STEP("block.grass.step"), - BLOCK_GRAVEL_BREAK("block.gravel.break"), - BLOCK_GRAVEL_FALL("block.gravel.fall"), - BLOCK_GRAVEL_HIT("block.gravel.hit"), - BLOCK_GRAVEL_PLACE("block.gravel.place"), - BLOCK_GRAVEL_STEP("block.gravel.step"), - BLOCK_GRINDSTONE_USE("block.grindstone.use"), - BLOCK_IRON_DOOR_CLOSE("block.iron_door.close"), - BLOCK_IRON_DOOR_OPEN("block.iron_door.open"), - BLOCK_IRON_TRAPDOOR_CLOSE("block.iron_trapdoor.close"), - BLOCK_IRON_TRAPDOOR_OPEN("block.iron_trapdoor.open"), - BLOCK_LADDER_BREAK("block.ladder.break"), - BLOCK_LADDER_FALL("block.ladder.fall"), - BLOCK_LADDER_HIT("block.ladder.hit"), - BLOCK_LADDER_PLACE("block.ladder.place"), - BLOCK_LADDER_STEP("block.ladder.step"), - BLOCK_LANTERN_BREAK("block.lantern.break"), - BLOCK_LANTERN_FALL("block.lantern.fall"), - BLOCK_LANTERN_HIT("block.lantern.hit"), - BLOCK_LANTERN_PLACE("block.lantern.place"), - BLOCK_LANTERN_STEP("block.lantern.step"), - BLOCK_LAVA_AMBIENT("block.lava.ambient"), - BLOCK_LAVA_EXTINGUISH("block.lava.extinguish"), - BLOCK_LAVA_POP("block.lava.pop"), - BLOCK_LEVER_CLICK("block.lever.click"), - BLOCK_LILY_PAD_PLACE("block.lily_pad.place"), - BLOCK_METAL_BREAK("block.metal.break"), - BLOCK_METAL_FALL("block.metal.fall"), - BLOCK_METAL_HIT("block.metal.hit"), - BLOCK_METAL_PLACE("block.metal.place"), - BLOCK_METAL_PRESSURE_PLATE_CLICK_OFF("block.metal_pressure_plate.click_off"), - BLOCK_METAL_PRESSURE_PLATE_CLICK_ON("block.metal_pressure_plate.click_on"), - BLOCK_METAL_STEP("block.metal.step"), - BLOCK_NETHER_WART_BREAK("block.nether_wart.break"), - BLOCK_NOTE_BLOCK_BANJO("block.note_block.banjo"), - BLOCK_NOTE_BLOCK_BASEDRUM("block.note_block.basedrum"), - BLOCK_NOTE_BLOCK_BASS("block.note_block.bass"), - BLOCK_NOTE_BLOCK_BELL("block.note_block.bell"), - BLOCK_NOTE_BLOCK_BIT("block.note_block.bit"), - BLOCK_NOTE_BLOCK_CHIME("block.note_block.chime"), - BLOCK_NOTE_BLOCK_COW_BELL("block.note_block.cow_bell"), - BLOCK_NOTE_BLOCK_DIDGERIDOO("block.note_block.didgeridoo"), - BLOCK_NOTE_BLOCK_FLUTE("block.note_block.flute"), - BLOCK_NOTE_BLOCK_GUITAR("block.note_block.guitar"), - BLOCK_NOTE_BLOCK_HARP("block.note_block.harp"), - BLOCK_NOTE_BLOCK_HAT("block.note_block.hat"), - BLOCK_NOTE_BLOCK_IRON_XYLOPHONE("block.note_block.iron_xylophone"), - BLOCK_NOTE_BLOCK_PLING("block.note_block.pling"), - BLOCK_NOTE_BLOCK_SNARE("block.note_block.snare"), - BLOCK_NOTE_BLOCK_XYLOPHONE("block.note_block.xylophone"), - BLOCK_PISTON_CONTRACT("block.piston.contract"), - BLOCK_PISTON_EXTEND("block.piston.extend"), - BLOCK_PORTAL_AMBIENT("block.portal.ambient"), - BLOCK_PORTAL_TRAVEL("block.portal.travel"), - BLOCK_PORTAL_TRIGGER("block.portal.trigger"), - BLOCK_PUMPKIN_CARVE("block.pumpkin.carve"), - BLOCK_REDSTONE_TORCH_BURNOUT("block.redstone_torch.burnout"), - BLOCK_SAND_BREAK("block.sand.break"), - BLOCK_SAND_FALL("block.sand.fall"), - BLOCK_SAND_HIT("block.sand.hit"), - BLOCK_SAND_PLACE("block.sand.place"), - BLOCK_SAND_STEP("block.sand.step"), - BLOCK_SCAFFOLDING_BREAK("block.scaffolding.break"), - BLOCK_SCAFFOLDING_FALL("block.scaffolding.fall"), - BLOCK_SCAFFOLDING_HIT("block.scaffolding.hit"), - BLOCK_SCAFFOLDING_PLACE("block.scaffolding.place"), - BLOCK_SCAFFOLDING_STEP("block.scaffolding.step"), - BLOCK_SHULKER_BOX_CLOSE("block.shulker_box.close"), - BLOCK_SHULKER_BOX_OPEN("block.shulker_box.open"), - BLOCK_SLIME_BLOCK_BREAK("block.slime_block.break"), - BLOCK_SLIME_BLOCK_FALL("block.slime_block.fall"), - BLOCK_SLIME_BLOCK_HIT("block.slime_block.hit"), - BLOCK_SLIME_BLOCK_PLACE("block.slime_block.place"), - BLOCK_SLIME_BLOCK_STEP("block.slime_block.step"), - BLOCK_SMOKER_SMOKE("block.smoker.smoke"), - BLOCK_SNOW_BREAK("block.snow.break"), - BLOCK_SNOW_FALL("block.snow.fall"), - BLOCK_SNOW_HIT("block.snow.hit"), - BLOCK_SNOW_PLACE("block.snow.place"), - BLOCK_SNOW_STEP("block.snow.step"), - BLOCK_STONE_BREAK("block.stone.break"), - BLOCK_STONE_BUTTON_CLICK_OFF("block.stone_button.click_off"), - BLOCK_STONE_BUTTON_CLICK_ON("block.stone_button.click_on"), - BLOCK_STONE_FALL("block.stone.fall"), - BLOCK_STONE_HIT("block.stone.hit"), - BLOCK_STONE_PLACE("block.stone.place"), - BLOCK_STONE_PRESSURE_PLATE_CLICK_OFF("block.stone_pressure_plate.click_off"), - BLOCK_STONE_PRESSURE_PLATE_CLICK_ON("block.stone_pressure_plate.click_on"), - BLOCK_STONE_STEP("block.stone.step"), - BLOCK_SWEET_BERRY_BUSH_BREAK("block.sweet_berry_bush.break"), - BLOCK_SWEET_BERRY_BUSH_PLACE("block.sweet_berry_bush.place"), - BLOCK_TRIPWIRE_ATTACH("block.tripwire.attach"), - BLOCK_TRIPWIRE_CLICK_OFF("block.tripwire.click_off"), - BLOCK_TRIPWIRE_CLICK_ON("block.tripwire.click_on"), - BLOCK_TRIPWIRE_DETACH("block.tripwire.detach"), - BLOCK_WATER_AMBIENT("block.water.ambient"), - BLOCK_WET_GRASS_BREAK("block.wet_grass.break"), - BLOCK_WET_GRASS_FALL("block.wet_grass.fall"), - BLOCK_WET_GRASS_HIT("block.wet_grass.hit"), - BLOCK_WET_GRASS_PLACE("block.wet_grass.place"), - BLOCK_WET_GRASS_STEP("block.wet_grass.step"), - BLOCK_WOODEN_BUTTON_CLICK_OFF("block.wooden_button.click_off"), - BLOCK_WOODEN_BUTTON_CLICK_ON("block.wooden_button.click_on"), - BLOCK_WOODEN_DOOR_CLOSE("block.wooden_door.close"), - BLOCK_WOODEN_DOOR_OPEN("block.wooden_door.open"), - BLOCK_WOODEN_PRESSURE_PLATE_CLICK_OFF("block.wooden_pressure_plate.click_off"), - BLOCK_WOODEN_PRESSURE_PLATE_CLICK_ON("block.wooden_pressure_plate.click_on"), - BLOCK_WOODEN_TRAPDOOR_CLOSE("block.wooden_trapdoor.close"), - BLOCK_WOODEN_TRAPDOOR_OPEN("block.wooden_trapdoor.open"), - BLOCK_WOOD_BREAK("block.wood.break"), - BLOCK_WOOD_FALL("block.wood.fall"), - BLOCK_WOOD_HIT("block.wood.hit"), - BLOCK_WOOD_PLACE("block.wood.place"), - BLOCK_WOOD_STEP("block.wood.step"), - BLOCK_WOOL_BREAK("block.wool.break"), - BLOCK_WOOL_FALL("block.wool.fall"), - BLOCK_WOOL_HIT("block.wool.hit"), - BLOCK_WOOL_PLACE("block.wool.place"), - BLOCK_WOOL_STEP("block.wool.step"), - ENCHANT_THORNS_HIT("enchant.thorns.hit"), - ENTITY_ARMOR_STAND_BREAK("entity.armor_stand.break"), - ENTITY_ARMOR_STAND_FALL("entity.armor_stand.fall"), - ENTITY_ARMOR_STAND_HIT("entity.armor_stand.hit"), - ENTITY_ARMOR_STAND_PLACE("entity.armor_stand.place"), - ENTITY_ARROW_HIT("entity.arrow.hit"), - ENTITY_ARROW_HIT_PLAYER("entity.arrow.hit_player"), - ENTITY_ARROW_SHOOT("entity.arrow.shoot"), - ENTITY_BAT_AMBIENT("entity.bat.ambient"), - ENTITY_BAT_DEATH("entity.bat.death"), - ENTITY_BAT_HURT("entity.bat.hurt"), - ENTITY_BAT_LOOP("entity.bat.loop"), - ENTITY_BAT_TAKEOFF("entity.bat.takeoff"), - ENTITY_BLAZE_AMBIENT("entity.blaze.ambient"), - ENTITY_BLAZE_BURN("entity.blaze.burn"), - ENTITY_BLAZE_DEATH("entity.blaze.death"), - ENTITY_BLAZE_HURT("entity.blaze.hurt"), - ENTITY_BLAZE_SHOOT("entity.blaze.shoot"), - ENTITY_BOAT_PADDLE_LAND("entity.boat.paddle_land"), - ENTITY_BOAT_PADDLE_WATER("entity.boat.paddle_water"), - ENTITY_CAT_AMBIENT("entity.cat.ambient"), - ENTITY_CAT_BEG_FOR_FOOD("entity.cat.beg_for_food"), - ENTITY_CAT_DEATH("entity.cat.death"), - ENTITY_CAT_EAT("entity.cat.eat"), - ENTITY_CAT_HISS("entity.cat.hiss"), - ENTITY_CAT_HURT("entity.cat.hurt"), - ENTITY_CAT_PURR("entity.cat.purr"), - ENTITY_CAT_PURREOW("entity.cat.purreow"), - ENTITY_CAT_STRAY_AMBIENT("entity.cat.stray_ambient"), - ENTITY_CHICKEN_AMBIENT("entity.chicken.ambient"), - ENTITY_CHICKEN_DEATH("entity.chicken.death"), - ENTITY_CHICKEN_EGG("entity.chicken.egg"), - ENTITY_CHICKEN_HURT("entity.chicken.hurt"), - ENTITY_CHICKEN_STEP("entity.chicken.step"), - ENTITY_COD_AMBIENT("entity.cod.ambient"), - ENTITY_COD_DEATH("entity.cod.death"), - ENTITY_COD_FLOP("entity.cod.flop"), - ENTITY_COD_HURT("entity.cod.hurt"), - ENTITY_COW_AMBIENT("entity.cow.ambient"), - ENTITY_COW_DEATH("entity.cow.death"), - ENTITY_COW_HURT("entity.cow.hurt"), - ENTITY_COW_MILK("entity.cow.milk"), - ENTITY_COW_STEP("entity.cow.step"), - ENTITY_CREEPER_DEATH("entity.creeper.death"), - ENTITY_CREEPER_HURT("entity.creeper.hurt"), - ENTITY_CREEPER_PRIMED("entity.creeper.primed"), - ENTITY_DOLPHIN_AMBIENT("entity.dolphin.ambient"), - ENTITY_DOLPHIN_AMBIENT_WATER("entity.dolphin.ambient_water"), - ENTITY_DOLPHIN_ATTACK("entity.dolphin.attack"), - ENTITY_DOLPHIN_DEATH("entity.dolphin.death"), - ENTITY_DOLPHIN_EAT("entity.dolphin.eat"), - ENTITY_DOLPHIN_HURT("entity.dolphin.hurt"), - ENTITY_DOLPHIN_JUMP("entity.dolphin.jump"), - ENTITY_DOLPHIN_PLAY("entity.dolphin.play"), - ENTITY_DOLPHIN_SPLASH("entity.dolphin.splash"), - ENTITY_DOLPHIN_SWIM("entity.dolphin.swim"), - ENTITY_DONKEY_AMBIENT("entity.donkey.ambient"), - ENTITY_DONKEY_ANGRY("entity.donkey.angry"), - ENTITY_DONKEY_CHEST("entity.donkey.chest"), - ENTITY_DONKEY_DEATH("entity.donkey.death"), - ENTITY_DONKEY_HURT("entity.donkey.hurt"), - ENTITY_DRAGON_FIREBALL_EXPLODE("entity.dragon_fireball.explode"), - ENTITY_DROWNED_AMBIENT("entity.drowned.ambient"), - ENTITY_DROWNED_AMBIENT_WATER("entity.drowned.ambient_water"), - ENTITY_DROWNED_DEATH("entity.drowned.death"), - ENTITY_DROWNED_DEATH_WATER("entity.drowned.death_water"), - ENTITY_DROWNED_HURT("entity.drowned.hurt"), - ENTITY_DROWNED_HURT_WATER("entity.drowned.hurt_water"), - ENTITY_DROWNED_SHOOT("entity.drowned.shoot"), - ENTITY_DROWNED_STEP("entity.drowned.step"), - ENTITY_DROWNED_SWIM("entity.drowned.swim"), - ENTITY_EGG_THROW("entity.egg.throw"), - ENTITY_ELDER_GUARDIAN_AMBIENT("entity.elder_guardian.ambient"), - ENTITY_ELDER_GUARDIAN_AMBIENT_LAND("entity.elder_guardian.ambient_land"), - ENTITY_ELDER_GUARDIAN_CURSE("entity.elder_guardian.curse"), - ENTITY_ELDER_GUARDIAN_DEATH("entity.elder_guardian.death"), - ENTITY_ELDER_GUARDIAN_DEATH_LAND("entity.elder_guardian.death_land"), - ENTITY_ELDER_GUARDIAN_FLOP("entity.elder_guardian.flop"), - ENTITY_ELDER_GUARDIAN_HURT("entity.elder_guardian.hurt"), - ENTITY_ELDER_GUARDIAN_HURT_LAND("entity.elder_guardian.hurt_land"), - ENTITY_ENDERMAN_AMBIENT("entity.enderman.ambient"), - ENTITY_ENDERMAN_DEATH("entity.enderman.death"), - ENTITY_ENDERMAN_HURT("entity.enderman.hurt"), - ENTITY_ENDERMAN_SCREAM("entity.enderman.scream"), - ENTITY_ENDERMAN_STARE("entity.enderman.stare"), - ENTITY_ENDERMAN_TELEPORT("entity.enderman.teleport"), - ENTITY_ENDERMITE_AMBIENT("entity.endermite.ambient"), - ENTITY_ENDERMITE_DEATH("entity.endermite.death"), - ENTITY_ENDERMITE_HURT("entity.endermite.hurt"), - ENTITY_ENDERMITE_STEP("entity.endermite.step"), - ENTITY_ENDER_DRAGON_AMBIENT("entity.ender_dragon.ambient"), - ENTITY_ENDER_DRAGON_DEATH("entity.ender_dragon.death"), - ENTITY_ENDER_DRAGON_FLAP("entity.ender_dragon.flap"), - ENTITY_ENDER_DRAGON_GROWL("entity.ender_dragon.growl"), - ENTITY_ENDER_DRAGON_HURT("entity.ender_dragon.hurt"), - ENTITY_ENDER_DRAGON_SHOOT("entity.ender_dragon.shoot"), - ENTITY_ENDER_EYE_DEATH("entity.ender_eye.death"), - ENTITY_ENDER_EYE_LAUNCH("entity.ender_eye.launch"), - ENTITY_ENDER_PEARL_THROW("entity.ender_pearl.throw"), - ENTITY_EVOKER_AMBIENT("entity.evoker.ambient"), - ENTITY_EVOKER_CAST_SPELL("entity.evoker.cast_spell"), - ENTITY_EVOKER_CELEBRATE("entity.evoker.celebrate"), - ENTITY_EVOKER_DEATH("entity.evoker.death"), - ENTITY_EVOKER_FANGS_ATTACK("entity.evoker_fangs.attack"), - ENTITY_EVOKER_HURT("entity.evoker.hurt"), - ENTITY_EVOKER_PREPARE_ATTACK("entity.evoker.prepare_attack"), - ENTITY_EVOKER_PREPARE_SUMMON("entity.evoker.prepare_summon"), - ENTITY_EVOKER_PREPARE_WOLOLO("entity.evoker.prepare_wololo"), - ENTITY_EXPERIENCE_BOTTLE_THROW("entity.experience_bottle.throw"), - ENTITY_EXPERIENCE_ORB_PICKUP("entity.experience_orb.pickup"), - ENTITY_FIREWORK_ROCKET_BLAST("entity.firework_rocket.blast"), - ENTITY_FIREWORK_ROCKET_BLAST_FAR("entity.firework_rocket.blast_far"), - ENTITY_FIREWORK_ROCKET_LARGE_BLAST("entity.firework_rocket.large_blast"), - ENTITY_FIREWORK_ROCKET_LARGE_BLAST_FAR("entity.firework_rocket.large_blast_far"), - ENTITY_FIREWORK_ROCKET_LAUNCH("entity.firework_rocket.launch"), - ENTITY_FIREWORK_ROCKET_SHOOT("entity.firework_rocket.shoot"), - ENTITY_FIREWORK_ROCKET_TWINKLE("entity.firework_rocket.twinkle"), - ENTITY_FIREWORK_ROCKET_TWINKLE_FAR("entity.firework_rocket.twinkle_far"), - ENTITY_FISHING_BOBBER_RETRIEVE("entity.fishing_bobber.retrieve"), - ENTITY_FISHING_BOBBER_SPLASH("entity.fishing_bobber.splash"), - ENTITY_FISHING_BOBBER_THROW("entity.fishing_bobber.throw"), - ENTITY_FISH_SWIM("entity.fish.swim"), - ENTITY_FOX_AGGRO("entity.fox.aggro"), - ENTITY_FOX_AMBIENT("entity.fox.ambient"), - ENTITY_FOX_BITE("entity.fox.bite"), - ENTITY_FOX_DEATH("entity.fox.death"), - ENTITY_FOX_EAT("entity.fox.eat"), - ENTITY_FOX_HURT("entity.fox.hurt"), - ENTITY_FOX_SCREECH("entity.fox.screech"), - ENTITY_FOX_SLEEP("entity.fox.sleep"), - ENTITY_FOX_SNIFF("entity.fox.sniff"), - ENTITY_FOX_SPIT("entity.fox.spit"), - ENTITY_GENERIC_BIG_FALL("entity.generic.big_fall"), - ENTITY_GENERIC_BURN("entity.generic.burn"), - ENTITY_GENERIC_DEATH("entity.generic.death"), - ENTITY_GENERIC_DRINK("entity.generic.drink"), - ENTITY_GENERIC_EAT("entity.generic.eat"), - ENTITY_GENERIC_EXPLODE("entity.generic.explode"), - ENTITY_GENERIC_EXTINGUISH_FIRE("entity.generic.extinguish_fire"), - ENTITY_GENERIC_HURT("entity.generic.hurt"), - ENTITY_GENERIC_SMALL_FALL("entity.generic.small_fall"), - ENTITY_GENERIC_SPLASH("entity.generic.splash"), - ENTITY_GENERIC_SWIM("entity.generic.swim"), - ENTITY_GHAST_AMBIENT("entity.ghast.ambient"), - ENTITY_GHAST_DEATH("entity.ghast.death"), - ENTITY_GHAST_HURT("entity.ghast.hurt"), - ENTITY_GHAST_SCREAM("entity.ghast.scream"), - ENTITY_GHAST_SHOOT("entity.ghast.shoot"), - ENTITY_GHAST_WARN("entity.ghast.warn"), - ENTITY_GUARDIAN_AMBIENT("entity.guardian.ambient"), - ENTITY_GUARDIAN_AMBIENT_LAND("entity.guardian.ambient_land"), - ENTITY_GUARDIAN_ATTACK("entity.guardian.attack"), - ENTITY_GUARDIAN_DEATH("entity.guardian.death"), - ENTITY_GUARDIAN_DEATH_LAND("entity.guardian.death_land"), - ENTITY_GUARDIAN_FLOP("entity.guardian.flop"), - ENTITY_GUARDIAN_HURT("entity.guardian.hurt"), - ENTITY_GUARDIAN_HURT_LAND("entity.guardian.hurt_land"), - ENTITY_HORSE_AMBIENT("entity.horse.ambient"), - ENTITY_HORSE_ANGRY("entity.horse.angry"), - ENTITY_HORSE_ARMOR("entity.horse.armor"), - ENTITY_HORSE_BREATHE("entity.horse.breathe"), - ENTITY_HORSE_DEATH("entity.horse.death"), - ENTITY_HORSE_EAT("entity.horse.eat"), - ENTITY_HORSE_GALLOP("entity.horse.gallop"), - ENTITY_HORSE_HURT("entity.horse.hurt"), - ENTITY_HORSE_JUMP("entity.horse.jump"), - ENTITY_HORSE_LAND("entity.horse.land"), - ENTITY_HORSE_SADDLE("entity.horse.saddle"), - ENTITY_HORSE_STEP("entity.horse.step"), - ENTITY_HORSE_STEP_WOOD("entity.horse.step_wood"), - ENTITY_HOSTILE_BIG_FALL("entity.hostile.big_fall"), - ENTITY_HOSTILE_DEATH("entity.hostile.death"), - ENTITY_HOSTILE_HURT("entity.hostile.hurt"), - ENTITY_HOSTILE_SMALL_FALL("entity.hostile.small_fall"), - ENTITY_HOSTILE_SPLASH("entity.hostile.splash"), - ENTITY_HOSTILE_SWIM("entity.hostile.swim"), - ENTITY_HUSK_AMBIENT("entity.husk.ambient"), - ENTITY_HUSK_CONVERTED_TO_ZOMBIE("entity.husk.converted_to_zombie"), - ENTITY_HUSK_DEATH("entity.husk.death"), - ENTITY_HUSK_HURT("entity.husk.hurt"), - ENTITY_HUSK_STEP("entity.husk.step"), - ENTITY_ILLUSIONER_AMBIENT("entity.illusioner.ambient"), - ENTITY_ILLUSIONER_CAST_SPELL("entity.illusioner.cast_spell"), - ENTITY_ILLUSIONER_DEATH("entity.illusioner.death"), - ENTITY_ILLUSIONER_HURT("entity.illusioner.hurt"), - ENTITY_ILLUSIONER_MIRROR_MOVE("entity.illusioner.mirror_move"), - ENTITY_ILLUSIONER_PREPARE_BLINDNESS("entity.illusioner.prepare_blindness"), - ENTITY_ILLUSIONER_PREPARE_MIRROR("entity.illusioner.prepare_mirror"), - ENTITY_IRON_GOLEM_ATTACK("entity.iron_golem.attack"), - ENTITY_IRON_GOLEM_DEATH("entity.iron_golem.death"), - ENTITY_IRON_GOLEM_HURT("entity.iron_golem.hurt"), - ENTITY_IRON_GOLEM_STEP("entity.iron_golem.step"), - ENTITY_ITEM_BREAK("entity.item.break"), - ENTITY_ITEM_FRAME_ADD_ITEM("entity.item_frame.add_item"), - ENTITY_ITEM_FRAME_BREAK("entity.item_frame.break"), - ENTITY_ITEM_FRAME_PLACE("entity.item_frame.place"), - ENTITY_ITEM_FRAME_REMOVE_ITEM("entity.item_frame.remove_item"), - ENTITY_ITEM_FRAME_ROTATE_ITEM("entity.item_frame.rotate_item"), - ENTITY_ITEM_PICKUP("entity.item.pickup"), - ENTITY_LEASH_KNOT_BREAK("entity.leash_knot.break"), - ENTITY_LEASH_KNOT_PLACE("entity.leash_knot.place"), - ENTITY_LIGHTNING_BOLT_IMPACT("entity.lightning_bolt.impact"), - ENTITY_LIGHTNING_BOLT_THUNDER("entity.lightning_bolt.thunder"), - ENTITY_LINGERING_POTION_THROW("entity.lingering_potion.throw"), - ENTITY_LLAMA_AMBIENT("entity.llama.ambient"), - ENTITY_LLAMA_ANGRY("entity.llama.angry"), - ENTITY_LLAMA_CHEST("entity.llama.chest"), - ENTITY_LLAMA_DEATH("entity.llama.death"), - ENTITY_LLAMA_EAT("entity.llama.eat"), - ENTITY_LLAMA_HURT("entity.llama.hurt"), - ENTITY_LLAMA_SPIT("entity.llama.spit"), - ENTITY_LLAMA_STEP("entity.llama.step"), - ENTITY_LLAMA_SWAG("entity.llama.swag"), - ENTITY_MAGMA_CUBE_DEATH("entity.magma_cube.death"), - ENTITY_MAGMA_CUBE_DEATH_SMALL("entity.magma_cube.death_small"), - ENTITY_MAGMA_CUBE_HURT("entity.magma_cube.hurt"), - ENTITY_MAGMA_CUBE_HURT_SMALL("entity.magma_cube.hurt_small"), - ENTITY_MAGMA_CUBE_JUMP("entity.magma_cube.jump"), - ENTITY_MAGMA_CUBE_SQUISH("entity.magma_cube.squish"), - ENTITY_MAGMA_CUBE_SQUISH_SMALL("entity.magma_cube.squish_small"), - ENTITY_MINECART_INSIDE("entity.minecart.inside"), - ENTITY_MINECART_RIDING("entity.minecart.riding"), - ENTITY_MOOSHROOM_CONVERT("entity.mooshroom.convert"), - ENTITY_MOOSHROOM_EAT("entity.mooshroom.eat"), - ENTITY_MOOSHROOM_MILK("entity.mooshroom.milk"), - ENTITY_MOOSHROOM_SHEAR("entity.mooshroom.shear"), - ENTITY_MOOSHROOM_SUSPICIOUS_MILK("entity.mooshroom.suspicious_milk"), - ENTITY_MULE_AMBIENT("entity.mule.ambient"), - ENTITY_MULE_CHEST("entity.mule.chest"), - ENTITY_MULE_DEATH("entity.mule.death"), - ENTITY_MULE_HURT("entity.mule.hurt"), - ENTITY_OCELOT_AMBIENT("entity.ocelot.ambient"), - ENTITY_OCELOT_DEATH("entity.ocelot.death"), - ENTITY_OCELOT_HURT("entity.ocelot.hurt"), - ENTITY_PAINTING_BREAK("entity.painting.break"), - ENTITY_PAINTING_PLACE("entity.painting.place"), - ENTITY_PANDA_AGGRESSIVE_AMBIENT("entity.panda.aggressive_ambient"), - ENTITY_PANDA_AMBIENT("entity.panda.ambient"), - ENTITY_PANDA_BITE("entity.panda.bite"), - ENTITY_PANDA_CANT_BREED("entity.panda.cant_breed"), - ENTITY_PANDA_DEATH("entity.panda.death"), - ENTITY_PANDA_EAT("entity.panda.eat"), - ENTITY_PANDA_HURT("entity.panda.hurt"), - ENTITY_PANDA_PRE_SNEEZE("entity.panda.pre_sneeze"), - ENTITY_PANDA_SNEEZE("entity.panda.sneeze"), - ENTITY_PANDA_STEP("entity.panda.step"), - ENTITY_PANDA_WORRIED_AMBIENT("entity.panda.worried_ambient"), - ENTITY_PARROT_AMBIENT("entity.parrot.ambient"), - ENTITY_PARROT_DEATH("entity.parrot.death"), - ENTITY_PARROT_EAT("entity.parrot.eat"), - ENTITY_PARROT_FLY("entity.parrot.fly"), - ENTITY_PARROT_HURT("entity.parrot.hurt"), - ENTITY_PARROT_IMITATE_BLAZE("entity.parrot.imitate.blaze"), - ENTITY_PARROT_IMITATE_CREEPER("entity.parrot.imitate.creeper"), - ENTITY_PARROT_IMITATE_DROWNED("entity.parrot.imitate.drowned"), - ENTITY_PARROT_IMITATE_ELDER_GUARDIAN("entity.parrot.imitate.elder_guardian"), - ENTITY_PARROT_IMITATE_ENDERMAN("entity.parrot.imitate.enderman"), - ENTITY_PARROT_IMITATE_ENDERMITE("entity.parrot.imitate.endermite"), - ENTITY_PARROT_IMITATE_ENDER_DRAGON("entity.parrot.imitate.ender_dragon"), - ENTITY_PARROT_IMITATE_EVOKER("entity.parrot.imitate.evoker"), - ENTITY_PARROT_IMITATE_GHAST("entity.parrot.imitate.ghast"), - ENTITY_PARROT_IMITATE_GUARDIAN("entity.parrot.imitate.guardian"), - ENTITY_PARROT_IMITATE_HUSK("entity.parrot.imitate.husk"), - ENTITY_PARROT_IMITATE_ILLUSIONER("entity.parrot.imitate.illusioner"), - ENTITY_PARROT_IMITATE_MAGMA_CUBE("entity.parrot.imitate.magma_cube"), - ENTITY_PARROT_IMITATE_PANDA("entity.parrot.imitate.panda"), - ENTITY_PARROT_IMITATE_PHANTOM("entity.parrot.imitate.phantom"), - ENTITY_PARROT_IMITATE_PILLAGER("entity.parrot.imitate.pillager"), - ENTITY_PARROT_IMITATE_POLAR_BEAR("entity.parrot.imitate.polar_bear"), - ENTITY_PARROT_IMITATE_RAVAGER("entity.parrot.imitate.ravager"), - ENTITY_PARROT_IMITATE_SHULKER("entity.parrot.imitate.shulker"), - ENTITY_PARROT_IMITATE_SILVERFISH("entity.parrot.imitate.silverfish"), - ENTITY_PARROT_IMITATE_SKELETON("entity.parrot.imitate.skeleton"), - ENTITY_PARROT_IMITATE_SLIME("entity.parrot.imitate.slime"), - ENTITY_PARROT_IMITATE_SPIDER("entity.parrot.imitate.spider"), - ENTITY_PARROT_IMITATE_STRAY("entity.parrot.imitate.stray"), - ENTITY_PARROT_IMITATE_VEX("entity.parrot.imitate.vex"), - ENTITY_PARROT_IMITATE_VINDICATOR("entity.parrot.imitate.vindicator"), - ENTITY_PARROT_IMITATE_WITCH("entity.parrot.imitate.witch"), - ENTITY_PARROT_IMITATE_WITHER("entity.parrot.imitate.wither"), - ENTITY_PARROT_IMITATE_WITHER_SKELETON("entity.parrot.imitate.wither_skeleton"), - ENTITY_PARROT_IMITATE_WOLF("entity.parrot.imitate.wolf"), - ENTITY_PARROT_IMITATE_ZOMBIE("entity.parrot.imitate.zombie"), - ENTITY_PARROT_IMITATE_ZOMBIE_PIGMAN("entity.parrot.imitate.zombie_pigman"), - ENTITY_PARROT_IMITATE_ZOMBIE_VILLAGER("entity.parrot.imitate.zombie_villager"), - ENTITY_PARROT_STEP("entity.parrot.step"), - ENTITY_PHANTOM_AMBIENT("entity.phantom.ambient"), - ENTITY_PHANTOM_BITE("entity.phantom.bite"), - ENTITY_PHANTOM_DEATH("entity.phantom.death"), - ENTITY_PHANTOM_FLAP("entity.phantom.flap"), - ENTITY_PHANTOM_HURT("entity.phantom.hurt"), - ENTITY_PHANTOM_SWOOP("entity.phantom.swoop"), - ENTITY_PIG_AMBIENT("entity.pig.ambient"), - ENTITY_PIG_DEATH("entity.pig.death"), - ENTITY_PIG_HURT("entity.pig.hurt"), - ENTITY_PIG_SADDLE("entity.pig.saddle"), - ENTITY_PIG_STEP("entity.pig.step"), - ENTITY_PILLAGER_AMBIENT("entity.pillager.ambient"), - ENTITY_PILLAGER_CELEBRATE("entity.pillager.celebrate"), - ENTITY_PILLAGER_DEATH("entity.pillager.death"), - ENTITY_PILLAGER_HURT("entity.pillager.hurt"), - ENTITY_PLAYER_ATTACK_CRIT("entity.player.attack.crit"), - ENTITY_PLAYER_ATTACK_KNOCKBACK("entity.player.attack.knockback"), - ENTITY_PLAYER_ATTACK_NODAMAGE("entity.player.attack.nodamage"), - ENTITY_PLAYER_ATTACK_STRONG("entity.player.attack.strong"), - ENTITY_PLAYER_ATTACK_SWEEP("entity.player.attack.sweep"), - ENTITY_PLAYER_ATTACK_WEAK("entity.player.attack.weak"), - ENTITY_PLAYER_BIG_FALL("entity.player.big_fall"), - ENTITY_PLAYER_BREATH("entity.player.breath"), - ENTITY_PLAYER_BURP("entity.player.burp"), - ENTITY_PLAYER_DEATH("entity.player.death"), - ENTITY_PLAYER_HURT("entity.player.hurt"), - ENTITY_PLAYER_HURT_DROWN("entity.player.hurt_drown"), - ENTITY_PLAYER_HURT_ON_FIRE("entity.player.hurt_on_fire"), - ENTITY_PLAYER_HURT_SWEET_BERRY_BUSH("entity.player.hurt_sweet_berry_bush"), - ENTITY_PLAYER_LEVELUP("entity.player.levelup"), - ENTITY_PLAYER_SMALL_FALL("entity.player.small_fall"), - ENTITY_PLAYER_SPLASH("entity.player.splash"), - ENTITY_PLAYER_SPLASH_HIGH_SPEED("entity.player.splash.high_speed"), - ENTITY_PLAYER_SWIM("entity.player.swim"), - ENTITY_POLAR_BEAR_AMBIENT("entity.polar_bear.ambient"), - ENTITY_POLAR_BEAR_AMBIENT_BABY("entity.polar_bear.ambient_baby"), - ENTITY_POLAR_BEAR_DEATH("entity.polar_bear.death"), - ENTITY_POLAR_BEAR_HURT("entity.polar_bear.hurt"), - ENTITY_POLAR_BEAR_STEP("entity.polar_bear.step"), - ENTITY_POLAR_BEAR_WARNING("entity.polar_bear.warning"), - ENTITY_PUFFER_FISH_AMBIENT("entity.puffer_fish.ambient"), - ENTITY_PUFFER_FISH_BLOW_OUT("entity.puffer_fish.blow_out"), - ENTITY_PUFFER_FISH_BLOW_UP("entity.puffer_fish.blow_up"), - ENTITY_PUFFER_FISH_DEATH("entity.puffer_fish.death"), - ENTITY_PUFFER_FISH_FLOP("entity.puffer_fish.flop"), - ENTITY_PUFFER_FISH_HURT("entity.puffer_fish.hurt"), - ENTITY_PUFFER_FISH_STING("entity.puffer_fish.sting"), - ENTITY_RABBIT_AMBIENT("entity.rabbit.ambient"), - ENTITY_RABBIT_ATTACK("entity.rabbit.attack"), - ENTITY_RABBIT_DEATH("entity.rabbit.death"), - ENTITY_RABBIT_HURT("entity.rabbit.hurt"), - ENTITY_RABBIT_JUMP("entity.rabbit.jump"), - ENTITY_RAVAGER_AMBIENT("entity.ravager.ambient"), - ENTITY_RAVAGER_ATTACK("entity.ravager.attack"), - ENTITY_RAVAGER_CELEBRATE("entity.ravager.celebrate"), - ENTITY_RAVAGER_DEATH("entity.ravager.death"), - ENTITY_RAVAGER_HURT("entity.ravager.hurt"), - ENTITY_RAVAGER_ROAR("entity.ravager.roar"), - ENTITY_RAVAGER_STEP("entity.ravager.step"), - ENTITY_RAVAGER_STUNNED("entity.ravager.stunned"), - ENTITY_SALMON_AMBIENT("entity.salmon.ambient"), - ENTITY_SALMON_DEATH("entity.salmon.death"), - ENTITY_SALMON_FLOP("entity.salmon.flop"), - ENTITY_SALMON_HURT("entity.salmon.hurt"), - ENTITY_SHEEP_AMBIENT("entity.sheep.ambient"), - ENTITY_SHEEP_DEATH("entity.sheep.death"), - ENTITY_SHEEP_HURT("entity.sheep.hurt"), - ENTITY_SHEEP_SHEAR("entity.sheep.shear"), - ENTITY_SHEEP_STEP("entity.sheep.step"), - ENTITY_SHULKER_AMBIENT("entity.shulker.ambient"), - ENTITY_SHULKER_BULLET_HIT("entity.shulker_bullet.hit"), - ENTITY_SHULKER_BULLET_HURT("entity.shulker_bullet.hurt"), - ENTITY_SHULKER_CLOSE("entity.shulker.close"), - ENTITY_SHULKER_DEATH("entity.shulker.death"), - ENTITY_SHULKER_HURT("entity.shulker.hurt"), - ENTITY_SHULKER_HURT_CLOSED("entity.shulker.hurt_closed"), - ENTITY_SHULKER_OPEN("entity.shulker.open"), - ENTITY_SHULKER_SHOOT("entity.shulker.shoot"), - ENTITY_SHULKER_TELEPORT("entity.shulker.teleport"), - ENTITY_SILVERFISH_AMBIENT("entity.silverfish.ambient"), - ENTITY_SILVERFISH_DEATH("entity.silverfish.death"), - ENTITY_SILVERFISH_HURT("entity.silverfish.hurt"), - ENTITY_SILVERFISH_STEP("entity.silverfish.step"), - ENTITY_SKELETON_AMBIENT("entity.skeleton.ambient"), - ENTITY_SKELETON_DEATH("entity.skeleton.death"), - ENTITY_SKELETON_HORSE_AMBIENT("entity.skeleton_horse.ambient"), - ENTITY_SKELETON_HORSE_AMBIENT_WATER("entity.skeleton_horse.ambient_water"), - ENTITY_SKELETON_HORSE_DEATH("entity.skeleton_horse.death"), - ENTITY_SKELETON_HORSE_GALLOP_WATER("entity.skeleton_horse.gallop_water"), - ENTITY_SKELETON_HORSE_HURT("entity.skeleton_horse.hurt"), - ENTITY_SKELETON_HORSE_JUMP_WATER("entity.skeleton_horse.jump_water"), - ENTITY_SKELETON_HORSE_STEP_WATER("entity.skeleton_horse.step_water"), - ENTITY_SKELETON_HORSE_SWIM("entity.skeleton_horse.swim"), - ENTITY_SKELETON_HURT("entity.skeleton.hurt"), - ENTITY_SKELETON_SHOOT("entity.skeleton.shoot"), - ENTITY_SKELETON_STEP("entity.skeleton.step"), - ENTITY_SLIME_ATTACK("entity.slime.attack"), - ENTITY_SLIME_DEATH("entity.slime.death"), - ENTITY_SLIME_DEATH_SMALL("entity.slime.death_small"), - ENTITY_SLIME_HURT("entity.slime.hurt"), - ENTITY_SLIME_HURT_SMALL("entity.slime.hurt_small"), - ENTITY_SLIME_JUMP("entity.slime.jump"), - ENTITY_SLIME_JUMP_SMALL("entity.slime.jump_small"), - ENTITY_SLIME_SQUISH("entity.slime.squish"), - ENTITY_SLIME_SQUISH_SMALL("entity.slime.squish_small"), - ENTITY_SNOWBALL_THROW("entity.snowball.throw"), - ENTITY_SNOW_GOLEM_AMBIENT("entity.snow_golem.ambient"), - ENTITY_SNOW_GOLEM_DEATH("entity.snow_golem.death"), - ENTITY_SNOW_GOLEM_HURT("entity.snow_golem.hurt"), - ENTITY_SNOW_GOLEM_SHOOT("entity.snow_golem.shoot"), - ENTITY_SPIDER_AMBIENT("entity.spider.ambient"), - ENTITY_SPIDER_DEATH("entity.spider.death"), - ENTITY_SPIDER_HURT("entity.spider.hurt"), - ENTITY_SPIDER_STEP("entity.spider.step"), - ENTITY_SPLASH_POTION_BREAK("entity.splash_potion.break"), - ENTITY_SPLASH_POTION_THROW("entity.splash_potion.throw"), - ENTITY_SQUID_AMBIENT("entity.squid.ambient"), - ENTITY_SQUID_DEATH("entity.squid.death"), - ENTITY_SQUID_HURT("entity.squid.hurt"), - ENTITY_SQUID_SQUIRT("entity.squid.squirt"), - ENTITY_STRAY_AMBIENT("entity.stray.ambient"), - ENTITY_STRAY_DEATH("entity.stray.death"), - ENTITY_STRAY_HURT("entity.stray.hurt"), - ENTITY_STRAY_STEP("entity.stray.step"), - ENTITY_TNT_PRIMED("entity.tnt.primed"), - ENTITY_TROPICAL_FISH_AMBIENT("entity.tropical_fish.ambient"), - ENTITY_TROPICAL_FISH_DEATH("entity.tropical_fish.death"), - ENTITY_TROPICAL_FISH_FLOP("entity.tropical_fish.flop"), - ENTITY_TROPICAL_FISH_HURT("entity.tropical_fish.hurt"), - ENTITY_TURTLE_AMBIENT_LAND("entity.turtle.ambient_land"), - ENTITY_TURTLE_DEATH("entity.turtle.death"), - ENTITY_TURTLE_DEATH_BABY("entity.turtle.death_baby"), - ENTITY_TURTLE_EGG_BREAK("entity.turtle.egg_break"), - ENTITY_TURTLE_EGG_CRACK("entity.turtle.egg_crack"), - ENTITY_TURTLE_EGG_HATCH("entity.turtle.egg_hatch"), - ENTITY_TURTLE_HURT("entity.turtle.hurt"), - ENTITY_TURTLE_HURT_BABY("entity.turtle.hurt_baby"), - ENTITY_TURTLE_LAY_EGG("entity.turtle.lay_egg"), - ENTITY_TURTLE_SHAMBLE("entity.turtle.shamble"), - ENTITY_TURTLE_SHAMBLE_BABY("entity.turtle.shamble_baby"), - ENTITY_TURTLE_SWIM("entity.turtle.swim"), - ENTITY_VEX_AMBIENT("entity.vex.ambient"), - ENTITY_VEX_CHARGE("entity.vex.charge"), - ENTITY_VEX_DEATH("entity.vex.death"), - ENTITY_VEX_HURT("entity.vex.hurt"), - ENTITY_VILLAGER_AMBIENT("entity.villager.ambient"), - ENTITY_VILLAGER_CELEBRATE("entity.villager.celebrate"), - ENTITY_VILLAGER_DEATH("entity.villager.death"), - ENTITY_VILLAGER_HURT("entity.villager.hurt"), - ENTITY_VILLAGER_NO("entity.villager.no"), - ENTITY_VILLAGER_TRADE("entity.villager.trade"), - ENTITY_VILLAGER_WORK_ARMORER("entity.villager.work_armorer"), - ENTITY_VILLAGER_WORK_BUTCHER("entity.villager.work_butcher"), - ENTITY_VILLAGER_WORK_CARTOGRAPHER("entity.villager.work_cartographer"), - ENTITY_VILLAGER_WORK_CLERIC("entity.villager.work_cleric"), - ENTITY_VILLAGER_WORK_FARMER("entity.villager.work_farmer"), - ENTITY_VILLAGER_WORK_FISHERMAN("entity.villager.work_fisherman"), - ENTITY_VILLAGER_WORK_FLETCHER("entity.villager.work_fletcher"), - ENTITY_VILLAGER_WORK_LEATHERWORKER("entity.villager.work_leatherworker"), - ENTITY_VILLAGER_WORK_LIBRARIAN("entity.villager.work_librarian"), - ENTITY_VILLAGER_WORK_MASON("entity.villager.work_mason"), - ENTITY_VILLAGER_WORK_SHEPHERD("entity.villager.work_shepherd"), - ENTITY_VILLAGER_WORK_TOOLSMITH("entity.villager.work_toolsmith"), - ENTITY_VILLAGER_WORK_WEAPONSMITH("entity.villager.work_weaponsmith"), - ENTITY_VILLAGER_YES("entity.villager.yes"), - ENTITY_VINDICATOR_AMBIENT("entity.vindicator.ambient"), - ENTITY_VINDICATOR_CELEBRATE("entity.vindicator.celebrate"), - ENTITY_VINDICATOR_DEATH("entity.vindicator.death"), - ENTITY_VINDICATOR_HURT("entity.vindicator.hurt"), - ENTITY_WANDERING_TRADER_AMBIENT("entity.wandering_trader.ambient"), - ENTITY_WANDERING_TRADER_DEATH("entity.wandering_trader.death"), - ENTITY_WANDERING_TRADER_DISAPPEARED("entity.wandering_trader.disappeared"), - ENTITY_WANDERING_TRADER_DRINK_MILK("entity.wandering_trader.drink_milk"), - ENTITY_WANDERING_TRADER_DRINK_POTION("entity.wandering_trader.drink_potion"), - ENTITY_WANDERING_TRADER_HURT("entity.wandering_trader.hurt"), - ENTITY_WANDERING_TRADER_NO("entity.wandering_trader.no"), - ENTITY_WANDERING_TRADER_REAPPEARED("entity.wandering_trader.reappeared"), - ENTITY_WANDERING_TRADER_TRADE("entity.wandering_trader.trade"), - ENTITY_WANDERING_TRADER_YES("entity.wandering_trader.yes"), - ENTITY_WITCH_AMBIENT("entity.witch.ambient"), - ENTITY_WITCH_CELEBRATE("entity.witch.celebrate"), - ENTITY_WITCH_DEATH("entity.witch.death"), - ENTITY_WITCH_DRINK("entity.witch.drink"), - ENTITY_WITCH_HURT("entity.witch.hurt"), - ENTITY_WITCH_THROW("entity.witch.throw"), - ENTITY_WITHER_AMBIENT("entity.wither.ambient"), - ENTITY_WITHER_BREAK_BLOCK("entity.wither.break_block"), - ENTITY_WITHER_DEATH("entity.wither.death"), - ENTITY_WITHER_HURT("entity.wither.hurt"), - ENTITY_WITHER_SHOOT("entity.wither.shoot"), - ENTITY_WITHER_SKELETON_AMBIENT("entity.wither_skeleton.ambient"), - ENTITY_WITHER_SKELETON_DEATH("entity.wither_skeleton.death"), - ENTITY_WITHER_SKELETON_HURT("entity.wither_skeleton.hurt"), - ENTITY_WITHER_SKELETON_STEP("entity.wither_skeleton.step"), - ENTITY_WITHER_SPAWN("entity.wither.spawn"), - ENTITY_WOLF_AMBIENT("entity.wolf.ambient"), - ENTITY_WOLF_DEATH("entity.wolf.death"), - ENTITY_WOLF_GROWL("entity.wolf.growl"), - ENTITY_WOLF_HOWL("entity.wolf.howl"), - ENTITY_WOLF_HURT("entity.wolf.hurt"), - ENTITY_WOLF_PANT("entity.wolf.pant"), - ENTITY_WOLF_SHAKE("entity.wolf.shake"), - ENTITY_WOLF_STEP("entity.wolf.step"), - ENTITY_WOLF_WHINE("entity.wolf.whine"), - ENTITY_ZOMBIE_AMBIENT("entity.zombie.ambient"), - ENTITY_ZOMBIE_ATTACK_IRON_DOOR("entity.zombie.attack_iron_door"), - ENTITY_ZOMBIE_ATTACK_WOODEN_DOOR("entity.zombie.attack_wooden_door"), - ENTITY_ZOMBIE_BREAK_WOODEN_DOOR("entity.zombie.break_wooden_door"), - ENTITY_ZOMBIE_CONVERTED_TO_DROWNED("entity.zombie.converted_to_drowned"), - ENTITY_ZOMBIE_DEATH("entity.zombie.death"), - ENTITY_ZOMBIE_DESTROY_EGG("entity.zombie.destroy_egg"), - ENTITY_ZOMBIE_HORSE_AMBIENT("entity.zombie_horse.ambient"), - ENTITY_ZOMBIE_HORSE_DEATH("entity.zombie_horse.death"), - ENTITY_ZOMBIE_HORSE_HURT("entity.zombie_horse.hurt"), - ENTITY_ZOMBIE_HURT("entity.zombie.hurt"), - ENTITY_ZOMBIE_INFECT("entity.zombie.infect"), - ENTITY_ZOMBIE_PIGMAN_AMBIENT("entity.zombie_pigman.ambient"), - ENTITY_ZOMBIE_PIGMAN_ANGRY("entity.zombie_pigman.angry"), - ENTITY_ZOMBIE_PIGMAN_DEATH("entity.zombie_pigman.death"), - ENTITY_ZOMBIE_PIGMAN_HURT("entity.zombie_pigman.hurt"), - ENTITY_ZOMBIE_STEP("entity.zombie.step"), - ENTITY_ZOMBIE_VILLAGER_AMBIENT("entity.zombie_villager.ambient"), - ENTITY_ZOMBIE_VILLAGER_CONVERTED("entity.zombie_villager.converted"), - ENTITY_ZOMBIE_VILLAGER_CURE("entity.zombie_villager.cure"), - ENTITY_ZOMBIE_VILLAGER_DEATH("entity.zombie_villager.death"), - ENTITY_ZOMBIE_VILLAGER_HURT("entity.zombie_villager.hurt"), - ENTITY_ZOMBIE_VILLAGER_STEP("entity.zombie_villager.step"), - EVENT_RAID_HORN("event.raid.horn"), - ITEM_ARMOR_EQUIP_CHAIN("item.armor.equip_chain"), - ITEM_ARMOR_EQUIP_DIAMOND("item.armor.equip_diamond"), - ITEM_ARMOR_EQUIP_ELYTRA("item.armor.equip_elytra"), - ITEM_ARMOR_EQUIP_GENERIC("item.armor.equip_generic"), - ITEM_ARMOR_EQUIP_GOLD("item.armor.equip_gold"), - ITEM_ARMOR_EQUIP_IRON("item.armor.equip_iron"), - ITEM_ARMOR_EQUIP_LEATHER("item.armor.equip_leather"), - ITEM_ARMOR_EQUIP_TURTLE("item.armor.equip_turtle"), - ITEM_AXE_STRIP("item.axe.strip"), - ITEM_BOOK_PAGE_TURN("item.book.page_turn"), - ITEM_BOOK_PUT("item.book.put"), - ITEM_BOTTLE_EMPTY("item.bottle.empty"), - ITEM_BOTTLE_FILL("item.bottle.fill"), - ITEM_BOTTLE_FILL_DRAGONBREATH("item.bottle.fill_dragonbreath"), - ITEM_BUCKET_EMPTY("item.bucket.empty"), - ITEM_BUCKET_EMPTY_FISH("item.bucket.empty_fish"), - ITEM_BUCKET_EMPTY_LAVA("item.bucket.empty_lava"), - ITEM_BUCKET_FILL("item.bucket.fill"), - ITEM_BUCKET_FILL_FISH("item.bucket.fill_fish"), - ITEM_BUCKET_FILL_LAVA("item.bucket.fill_lava"), - ITEM_CHORUS_FRUIT_TELEPORT("item.chorus_fruit.teleport"), - ITEM_CROP_PLANT("item.crop.plant"), - ITEM_CROSSBOW_HIT("item.crossbow.hit"), - ITEM_CROSSBOW_LOADING_END("item.crossbow.loading_end"), - ITEM_CROSSBOW_LOADING_MIDDLE("item.crossbow.loading_middle"), - ITEM_CROSSBOW_LOADING_START("item.crossbow.loading_start"), - ITEM_CROSSBOW_QUICK_CHARGE_1("item.crossbow.quick_charge_1"), - ITEM_CROSSBOW_QUICK_CHARGE_2("item.crossbow.quick_charge_2"), - ITEM_CROSSBOW_QUICK_CHARGE_3("item.crossbow.quick_charge_3"), - ITEM_CROSSBOW_SHOOT("item.crossbow.shoot"), - ITEM_ELYTRA_FLYING("item.elytra.flying"), - ITEM_FIRECHARGE_USE("item.firecharge.use"), - ITEM_FLINTANDSTEEL_USE("item.flintandsteel.use"), - ITEM_HOE_TILL("item.hoe.till"), - ITEM_NETHER_WART_PLANT("item.nether_wart.plant"), - ITEM_SHIELD_BLOCK("item.shield.block"), - ITEM_SHIELD_BREAK("item.shield.break"), - ITEM_SHOVEL_FLATTEN("item.shovel.flatten"), - ITEM_SWEET_BERRIES_PICK_FROM_BUSH("item.sweet_berries.pick_from_bush"), - ITEM_TOTEM_USE("item.totem.use"), - ITEM_TRIDENT_HIT("item.trident.hit"), - ITEM_TRIDENT_HIT_GROUND("item.trident.hit_ground"), - ITEM_TRIDENT_RETURN("item.trident.return"), - ITEM_TRIDENT_RIPTIDE_1("item.trident.riptide_1"), - ITEM_TRIDENT_RIPTIDE_2("item.trident.riptide_2"), - ITEM_TRIDENT_RIPTIDE_3("item.trident.riptide_3"), - ITEM_TRIDENT_THROW("item.trident.throw"), - ITEM_TRIDENT_THUNDER("item.trident.thunder"), - MUSIC_CREATIVE("music.creative"), - MUSIC_CREDITS("music.credits"), - MUSIC_DISC_11("music_disc.11"), - MUSIC_DISC_13("music_disc.13"), - MUSIC_DISC_BLOCKS("music_disc.blocks"), - MUSIC_DISC_CAT("music_disc.cat"), - MUSIC_DISC_CHIRP("music_disc.chirp"), - MUSIC_DISC_FAR("music_disc.far"), - MUSIC_DISC_MALL("music_disc.mall"), - MUSIC_DISC_MELLOHI("music_disc.mellohi"), - MUSIC_DISC_STAL("music_disc.stal"), - MUSIC_DISC_STRAD("music_disc.strad"), - MUSIC_DISC_WAIT("music_disc.wait"), - MUSIC_DISC_WARD("music_disc.ward"), - MUSIC_DRAGON("music.dragon"), - MUSIC_END("music.end"), - MUSIC_GAME("music.game"), - MUSIC_MENU("music.menu"), - MUSIC_NETHER("music.nether"), - MUSIC_UNDER_WATER("music.under_water"), - UI_BUTTON_CLICK("ui.button.click"), - UI_CARTOGRAPHY_TABLE_TAKE_RESULT("ui.cartography_table.take_result"), - UI_LOOM_SELECT_PATTERN("ui.loom.select_pattern"), - UI_LOOM_TAKE_RESULT("ui.loom.take_result"), - UI_STONECUTTER_SELECT_RECIPE("ui.stonecutter.select_recipe"), - UI_STONECUTTER_TAKE_RESULT("ui.stonecutter.take_result"), - UI_TOAST_CHALLENGE_COMPLETE("ui.toast.challenge_complete"), - UI_TOAST_IN("ui.toast.in"), - UI_TOAST_OUT("ui.toast.out"), - WEATHER_RAIN("weather.rain"), - WEATHER_RAIN_ABOVE("weather.rain.above"); - private final String minecraftKey; - - // Paper start - cancellable death event - public static CraftSound getBySoundEffect(final SoundEffect effect) { - MinecraftKey key = IRegistry.SOUND_EVENT.getKey(effect); - Preconditions.checkArgument(key != null, "Key for sound effect %s not found?", effect.toString()); - - return valueOf(key.getKey().replace('.', '_').toUpperCase(java.util.Locale.ENGLISH)); - } - - public static Sound getSoundByEffect(final SoundEffect effect) { - return Sound.valueOf(getBySoundEffect(effect).name()); - } - - public static SoundEffect getSoundEffect(final Sound sound) { - return getSoundEffect(getSound(sound)); - } - // Paper end - CraftSound(String minecraftKey) { - this.minecraftKey = minecraftKey; - } - - public static String getSound(final Sound sound) { - Validate.notNull(sound, "Sound cannot be null"); - - return CraftSound.valueOf(sound.name()).minecraftKey; - } - - public static SoundEffect getSoundEffect(String s) { - SoundEffect effect = IRegistry.SOUND_EVENT.get(new MinecraftKey(s)); - Preconditions.checkArgument(effect != null, "Sound effect %s does not exist", s); - - return effect; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java b/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java deleted file mode 100644 index 4536b70dc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java +++ /dev/null @@ -1,189 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Preconditions; -import com.google.common.collect.BiMap; -import com.google.common.collect.ImmutableBiMap; -import net.minecraft.server.Block; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.IRegistry; -import net.minecraft.server.Item; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.StatisticList; -import org.bukkit.Material; -import org.bukkit.Statistic; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.entity.EntityType; - -public enum CraftStatistic { - DAMAGE_DEALT(StatisticList.DAMAGE_DEALT), - DAMAGE_TAKEN(StatisticList.DAMAGE_TAKEN), - DEATHS(StatisticList.DEATHS), - MOB_KILLS(StatisticList.MOB_KILLS), - PLAYER_KILLS(StatisticList.PLAYER_KILLS), - FISH_CAUGHT(StatisticList.FISH_CAUGHT), - ANIMALS_BRED(StatisticList.ANIMALS_BRED), - LEAVE_GAME(StatisticList.LEAVE_GAME), - JUMP(StatisticList.JUMP), - DROP_COUNT(StatisticList.DROP), - DROP(new MinecraftKey("dropped")), - PICKUP(new MinecraftKey("picked_up")), - PLAY_ONE_MINUTE(StatisticList.PLAY_ONE_MINUTE), - WALK_ONE_CM(StatisticList.WALK_ONE_CM), - WALK_ON_WATER_ONE_CM(StatisticList.WALK_ON_WATER_ONE_CM), - FALL_ONE_CM(StatisticList.FALL_ONE_CM), - SNEAK_TIME(StatisticList.SNEAK_TIME), - CLIMB_ONE_CM(StatisticList.CLIMB_ONE_CM), - FLY_ONE_CM(StatisticList.FLY_ONE_CM), - WALK_UNDER_WATER_ONE_CM(StatisticList.WALK_UNDER_WATER_ONE_CM), - MINECART_ONE_CM(StatisticList.MINECART_ONE_CM), - BOAT_ONE_CM(StatisticList.BOAT_ONE_CM), - PIG_ONE_CM(StatisticList.PIG_ONE_CM), - HORSE_ONE_CM(StatisticList.HORSE_ONE_CM), - SPRINT_ONE_CM(StatisticList.SPRINT_ONE_CM), - CROUCH_ONE_CM(StatisticList.CROUCH_ONE_CM), - AVIATE_ONE_CM(StatisticList.AVIATE_ONE_CM), - MINE_BLOCK(new MinecraftKey("mined")), - USE_ITEM(new MinecraftKey("used")), - BREAK_ITEM(new MinecraftKey("broken")), - CRAFT_ITEM(new MinecraftKey("crafted")), - KILL_ENTITY(new MinecraftKey("killed")), - ENTITY_KILLED_BY(new MinecraftKey("killed_by")), - TIME_SINCE_DEATH(StatisticList.TIME_SINCE_DEATH), - TALKED_TO_VILLAGER(StatisticList.TALKED_TO_VILLAGER), - TRADED_WITH_VILLAGER(StatisticList.TRADED_WITH_VILLAGER), - CAKE_SLICES_EATEN(StatisticList.EAT_CAKE_SLICE), - CAULDRON_FILLED(StatisticList.FILL_CAULDRON), - CAULDRON_USED(StatisticList.USE_CAULDRON), - ARMOR_CLEANED(StatisticList.CLEAN_ARMOR), - BANNER_CLEANED(StatisticList.CLEAN_BANNER), - BREWINGSTAND_INTERACTION(StatisticList.INTERACT_WITH_BREWINGSTAND), - BEACON_INTERACTION(StatisticList.INTERACT_WITH_BEACON), - DROPPER_INSPECTED(StatisticList.INSPECT_DROPPER), - HOPPER_INSPECTED(StatisticList.INSPECT_HOPPER), - DISPENSER_INSPECTED(StatisticList.INSPECT_DISPENSER), - NOTEBLOCK_PLAYED(StatisticList.PLAY_NOTEBLOCK), - NOTEBLOCK_TUNED(StatisticList.TUNE_NOTEBLOCK), - FLOWER_POTTED(StatisticList.POT_FLOWER), - TRAPPED_CHEST_TRIGGERED(StatisticList.TRIGGER_TRAPPED_CHEST), - ENDERCHEST_OPENED(StatisticList.OPEN_ENDERCHEST), - ITEM_ENCHANTED(StatisticList.ENCHANT_ITEM), - RECORD_PLAYED(StatisticList.PLAY_RECORD), - FURNACE_INTERACTION(StatisticList.INTERACT_WITH_FURNACE), - CRAFTING_TABLE_INTERACTION(StatisticList.INTERACT_WITH_CRAFTING_TABLE), - CHEST_OPENED(StatisticList.OPEN_CHEST), - SLEEP_IN_BED(StatisticList.SLEEP_IN_BED), - SHULKER_BOX_OPENED(StatisticList.OPEN_SHULKER_BOX), - TIME_SINCE_REST(StatisticList.TIME_SINCE_REST), - SWIM_ONE_CM(StatisticList.SWIM_ONE_CM), - DAMAGE_DEALT_ABSORBED(StatisticList.DAMAGE_DEALT_ABSORBED), - DAMAGE_DEALT_RESISTED(StatisticList.DAMAGE_DEALT_RESISTED), - DAMAGE_BLOCKED_BY_SHIELD(StatisticList.DAMAGE_BLOCKED_BY_SHIELD), - DAMAGE_ABSORBED(StatisticList.DAMAGE_ABSORBED), - DAMAGE_RESISTED(StatisticList.DAMAGE_RESISTED), - CLEAN_SHULKER_BOX(StatisticList.CLEAN_SHULKER_BOX), - OPEN_BARREL(StatisticList.OPEN_BARREL), - INTERACT_WITH_BLAST_FURNACE(StatisticList.INTERACT_WITH_BLAST_FURNACE), - INTERACT_WITH_SMOKER(StatisticList.INTERACT_WITH_SMOKER), - INTERACT_WITH_LECTERN(StatisticList.INTERACT_WITH_LECTERN), - INTERACT_WITH_CAMPFIRE(StatisticList.INTERACT_WITH_CAMPFIRE), - INTERACT_WITH_CARTOGRAPHY_TABLE(StatisticList.INTERACT_WITH_CARTOGRAPHY_TABLE), - INTERACT_WITH_LOOM(StatisticList.INTERACT_WITH_LOOM), - INTERACT_WITH_STONECUTTER(StatisticList.INTERACT_WITH_STONECUTTER), - BELL_RING(StatisticList.BELL_RING), - RAID_TRIGGER(StatisticList.RAID_TRIGGER), - RAID_WIN(StatisticList.RAID_WIN); - private final MinecraftKey minecraftKey; - private final org.bukkit.Statistic bukkit; - private static final BiMap statistics; - - static { - ImmutableBiMap.Builder statisticBuilder = ImmutableBiMap.builder(); - for (CraftStatistic statistic : CraftStatistic.values()) { - statisticBuilder.put(statistic.minecraftKey, statistic.bukkit); - } - - statistics = statisticBuilder.build(); - } - - private CraftStatistic(MinecraftKey minecraftKey) { - this.minecraftKey = minecraftKey; - - this.bukkit = org.bukkit.Statistic.valueOf(this.name()); - Preconditions.checkState(bukkit != null, "Bukkit statistic %s does not exist", this.name()); - } - - public static org.bukkit.Statistic getBukkitStatistic(net.minecraft.server.Statistic statistic) { - IRegistry statRegistry = statistic.getWrapper().getRegistry(); - MinecraftKey nmsKey = IRegistry.STATS.getKey(statistic.getWrapper()); - - if (statRegistry == IRegistry.CUSTOM_STAT) { - nmsKey = (MinecraftKey) statistic.b(); - } - - return statistics.get(nmsKey); - } - - public static net.minecraft.server.Statistic getNMSStatistic(org.bukkit.Statistic bukkit) { - Preconditions.checkArgument(bukkit.getType() == Statistic.Type.UNTYPED, "This method only accepts untyped statistics"); - - net.minecraft.server.Statistic nms = StatisticList.CUSTOM.b(statistics.inverse().get(bukkit)); - Preconditions.checkArgument(nms != null, "NMS Statistic %s does not exist", bukkit); - - return nms; - } - - public static net.minecraft.server.Statistic getMaterialStatistic(org.bukkit.Statistic stat, Material material) { - try { - if (stat == Statistic.MINE_BLOCK) { - return StatisticList.BLOCK_MINED.b(CraftMagicNumbers.getBlock(material)); - } - if (stat == Statistic.CRAFT_ITEM) { - return StatisticList.ITEM_CRAFTED.b(CraftMagicNumbers.getItem(material)); - } - if (stat == Statistic.USE_ITEM) { - return StatisticList.ITEM_USED.b(CraftMagicNumbers.getItem(material)); - } - if (stat == Statistic.BREAK_ITEM) { - return StatisticList.ITEM_BROKEN.b(CraftMagicNumbers.getItem(material)); - } - if (stat == Statistic.PICKUP) { - return StatisticList.ITEM_PICKED_UP.b(CraftMagicNumbers.getItem(material)); - } - if (stat == Statistic.DROP) { - return StatisticList.ITEM_DROPPED.b(CraftMagicNumbers.getItem(material)); - } - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - return null; - } - - public static net.minecraft.server.Statistic getEntityStatistic(org.bukkit.Statistic stat, EntityType entity) { - if (entity.getName() != null) { - EntityTypes nmsEntity = IRegistry.ENTITY_TYPE.get(new MinecraftKey(entity.getName())); - - if (stat == org.bukkit.Statistic.KILL_ENTITY) { - return net.minecraft.server.StatisticList.ENTITY_KILLED.b(nmsEntity); - } - if (stat == org.bukkit.Statistic.ENTITY_KILLED_BY) { - return net.minecraft.server.StatisticList.ENTITY_KILLED_BY.b(nmsEntity); - } - } - return null; - } - - public static EntityType getEntityTypeFromStatistic(net.minecraft.server.Statistic> statistic) { - MinecraftKey name = EntityTypes.getName(statistic.b()); - return EntityType.fromName(name.getKey()); - } - - public static Material getMaterialFromStatistic(net.minecraft.server.Statistic statistic) { - if (statistic.b() instanceof Item) { - return CraftMagicNumbers.getMaterial((Item) statistic.b()); - } - if (statistic.b() instanceof Block) { - return CraftMagicNumbers.getMaterial((Block) statistic.b()); - } - return null; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java deleted file mode 100644 index f33d9c8b4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java +++ /dev/null @@ -1,2405 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -import it.unimi.dsi.fastutil.objects.ObjectSortedSet; -import net.minecraft.server.AxisAlignedBB; -import net.minecraft.server.BiomeBase; -import net.minecraft.server.BlockChorusFlower; -import net.minecraft.server.BlockDiodeAbstract; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.Blocks; -import net.minecraft.server.ChunkCoordIntPair; -import net.minecraft.server.ChunkMapDistance; -import net.minecraft.server.ChunkStatus; -import net.minecraft.server.EntityAreaEffectCloud; -import net.minecraft.server.EntityArmorStand; -import net.minecraft.server.EntityArrow; -import net.minecraft.server.EntityBoat; -import net.minecraft.server.EntityEgg; -import net.minecraft.server.EntityEnderSignal; -import net.minecraft.server.EntityEvokerFangs; -import net.minecraft.server.EntityExperienceOrb; -import net.minecraft.server.EntityFallingBlock; -import net.minecraft.server.EntityFireball; -import net.minecraft.server.EntityFireworks; -import net.minecraft.server.EntityHanging; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.EntityInsentient; -import net.minecraft.server.EntityItem; -import net.minecraft.server.EntityItemFrame; -import net.minecraft.server.EntityLeash; -import net.minecraft.server.EntityLightning; -import net.minecraft.server.EntityMinecartChest; -import net.minecraft.server.EntityMinecartCommandBlock; -import net.minecraft.server.EntityMinecartFurnace; -import net.minecraft.server.EntityMinecartHopper; -import net.minecraft.server.EntityMinecartMobSpawner; -import net.minecraft.server.EntityMinecartRideable; -import net.minecraft.server.EntityMinecartTNT; -import net.minecraft.server.EntityPainting; -import net.minecraft.server.EntityPotion; -import net.minecraft.server.EntitySnowball; -import net.minecraft.server.EntityTNTPrimed; -import net.minecraft.server.EntityTippedArrow; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.EntityZombie; -import net.minecraft.server.EnumDifficulty; -import net.minecraft.server.EnumDirection; -import net.minecraft.server.EnumMobSpawn; -import net.minecraft.server.ExceptionWorldConflict; -import net.minecraft.server.Explosion; -import net.minecraft.server.GameRules; -import net.minecraft.server.GroupDataEntity; -import net.minecraft.server.HeightMap; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IChunkAccess; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.MovingObjectPosition; -import net.minecraft.server.PacketPlayOutCustomSoundEffect; -import net.minecraft.server.PacketPlayOutUpdateTime; -import net.minecraft.server.PacketPlayOutWorldEvent; -import net.minecraft.server.PersistentRaid; -import net.minecraft.server.PlayerChunk; -import net.minecraft.server.ProtoChunkExtension; -import net.minecraft.server.RayTrace; -import net.minecraft.server.SoundCategory; -import net.minecraft.server.Ticket; -import net.minecraft.server.TicketType; -import net.minecraft.server.Unit; -import net.minecraft.server.Vec3D; -import net.minecraft.server.WorldGenFeatureEmptyConfiguration; -import net.minecraft.server.WorldGenHugeMushroomConfiguration; -import net.minecraft.server.WorldGenerator; -import net.minecraft.server.WorldServer; -import org.apache.commons.lang.Validate; -import org.bukkit.BlockChangeDelegate; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.ChunkSnapshot; -import org.bukkit.Difficulty; -import org.bukkit.Effect; -import org.bukkit.FluidCollisionMode; -import org.bukkit.GameRule; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.Sound; -import org.bukkit.StructureType; -import org.bukkit.TreeType; -import org.bukkit.Raid; -import org.bukkit.World; -import org.bukkit.WorldBorder; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.block.CraftBlockState; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.entity.CraftEntity; -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.BlockMetadataStore; -import org.bukkit.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftRayTraceResult; -import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.AbstractHorse; -import org.bukkit.entity.AbstractVillager; -import org.bukkit.entity.Ambient; -import org.bukkit.entity.AreaEffectCloud; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Bat; -import org.bukkit.entity.Blaze; -import org.bukkit.entity.Boat; -import org.bukkit.entity.Cat; -import org.bukkit.entity.CaveSpider; -import org.bukkit.entity.ChestedHorse; -import org.bukkit.entity.Chicken; -import org.bukkit.entity.Cod; -import org.bukkit.entity.ComplexLivingEntity; -import org.bukkit.entity.Cow; -import org.bukkit.entity.Creeper; -import org.bukkit.entity.Dolphin; -import org.bukkit.entity.Donkey; -import org.bukkit.entity.DragonFireball; -import org.bukkit.entity.Drowned; -import org.bukkit.entity.Egg; -import org.bukkit.entity.ElderGuardian; -import org.bukkit.entity.EnderCrystal; -import org.bukkit.entity.EnderDragon; -import org.bukkit.entity.EnderPearl; -import org.bukkit.entity.EnderSignal; -import org.bukkit.entity.Enderman; -import org.bukkit.entity.Endermite; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Evoker; -import org.bukkit.entity.EvokerFangs; -import org.bukkit.entity.ExperienceOrb; -import org.bukkit.entity.FallingBlock; -import org.bukkit.entity.Fireball; -import org.bukkit.entity.Firework; -import org.bukkit.entity.Fish; -import org.bukkit.entity.Fox; -import org.bukkit.entity.Ghast; -import org.bukkit.entity.Giant; -import org.bukkit.entity.Golem; -import org.bukkit.entity.Guardian; -import org.bukkit.entity.Hanging; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.Husk; -import org.bukkit.entity.Illager; -import org.bukkit.entity.Illusioner; -import org.bukkit.entity.IronGolem; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.LeashHitch; -import org.bukkit.entity.LightningStrike; -import org.bukkit.entity.LingeringPotion; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Llama; -import org.bukkit.entity.LlamaSpit; -import org.bukkit.entity.MagmaCube; -import org.bukkit.entity.Minecart; -import org.bukkit.entity.Mule; -import org.bukkit.entity.MushroomCow; -import org.bukkit.entity.Ocelot; -import org.bukkit.entity.Painting; -import org.bukkit.entity.Panda; -import org.bukkit.entity.Parrot; -import org.bukkit.entity.Phantom; -import org.bukkit.entity.Pig; -import org.bukkit.entity.PigZombie; -import org.bukkit.entity.Pillager; -import org.bukkit.entity.Player; -import org.bukkit.entity.PolarBear; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.PufferFish; -import org.bukkit.entity.Rabbit; -import org.bukkit.entity.Ravager; -import org.bukkit.entity.Salmon; -import org.bukkit.entity.Sheep; -import org.bukkit.entity.Shulker; -import org.bukkit.entity.ShulkerBullet; -import org.bukkit.entity.Silverfish; -import org.bukkit.entity.Skeleton; -import org.bukkit.entity.SkeletonHorse; -import org.bukkit.entity.Slime; -import org.bukkit.entity.SmallFireball; -import org.bukkit.entity.Snowball; -import org.bukkit.entity.Snowman; -import org.bukkit.entity.SpectralArrow; -import org.bukkit.entity.Spellcaster; -import org.bukkit.entity.Spider; -import org.bukkit.entity.Squid; -import org.bukkit.entity.Stray; -import org.bukkit.entity.TNTPrimed; -import org.bukkit.entity.Tameable; -import org.bukkit.entity.ThrownExpBottle; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.entity.TippedArrow; -import org.bukkit.entity.TraderLlama; -import org.bukkit.entity.Trident; -import org.bukkit.entity.TropicalFish; -import org.bukkit.entity.Turtle; -import org.bukkit.entity.Vex; -import org.bukkit.entity.Villager; -import org.bukkit.entity.Vindicator; -import org.bukkit.entity.WanderingTrader; -import org.bukkit.entity.Witch; -import org.bukkit.entity.Wither; -import org.bukkit.entity.WitherSkeleton; -import org.bukkit.entity.WitherSkull; -import org.bukkit.entity.Wolf; -import org.bukkit.entity.Zombie; -import org.bukkit.entity.ZombieHorse; -import org.bukkit.entity.ZombieVillager; -import org.bukkit.entity.minecart.CommandMinecart; -import org.bukkit.entity.minecart.ExplosiveMinecart; -import org.bukkit.entity.minecart.HopperMinecart; -import org.bukkit.entity.minecart.PoweredMinecart; -import org.bukkit.entity.minecart.SpawnerMinecart; -import org.bukkit.entity.minecart.StorageMinecart; -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.material.MaterialData; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.messaging.StandardMessenger; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionType; -import org.bukkit.util.BoundingBox; -import org.bukkit.util.Consumer; -import org.bukkit.util.RayTraceResult; -import org.bukkit.util.Vector; - -public class CraftWorld implements World { - public static final int CUSTOM_DIMENSION_OFFSET = 10; - - private final WorldServer world; - private WorldBorder worldBorder; - private Environment environment; - private final CraftServer server = (CraftServer) Bukkit.getServer(); - private final ChunkGenerator generator; - private final List populators = new ArrayList(); - private final BlockMetadataStore blockMetadata = new BlockMetadataStore(this); - private int monsterSpawn = -1; - private int animalSpawn = -1; - private int waterAnimalSpawn = -1; - private int ambientSpawn = -1; - - // Paper start - Provide fast information methods - public int getEntityCount() { - int ret = 0; - for (net.minecraft.server.Entity entity : world.entitiesById.values()) { - if (entity.isChunkLoaded()) { - ++ret; - } - } - return ret; - } - public int getTileEntityCount() { - // We don't use the full world tile entity list, so we must iterate chunks - Long2ObjectLinkedOpenHashMap chunks = world.getChunkProvider().playerChunkMap.visibleChunks; - int size = 0; - for (net.minecraft.server.PlayerChunk playerchunk : chunks.values()) { - net.minecraft.server.Chunk chunk = playerchunk.getChunk(); - if (chunk == null) { - continue; - } - size += chunk.tileEntities.size(); - } - return size; - } - public int getTickableTileEntityCount() { - return world.tileEntityListTick.size(); - } - public int getChunkCount() { - int ret = 0; - - for (PlayerChunk chunkHolder : world.getChunkProvider().playerChunkMap.visibleChunks.values()) { - if (chunkHolder.getChunk() != null) { - ++ret; - } - } - - return ret; - } - public int getPlayerCount() { - return world.players.size(); - } - // Paper end - - private static final Random rand = new Random(); - - public CraftWorld(WorldServer world, ChunkGenerator gen, Environment env) { - this.world = world; - this.generator = gen; - - environment = env; - } - - @Override - public Block getBlockAt(int x, int y, int z) { - return CraftBlock.at(world, new BlockPosition(x, y, z)); - } - - @Override - public int getHighestBlockYAt(int x, int z) { - if (!isChunkLoaded(x >> 4, z >> 4)) { - getChunkAt(x >> 4, z >> 4); // Transient load for this tick - } - - return world.getHighestBlockYAt(HeightMap.Type.MOTION_BLOCKING, new BlockPosition(x, 0, z)).getY(); - } - - // Paper start - Implement heightmap api - @Override - public int getHighestBlockYAt(final int x, final int z, final com.destroystokyo.paper.HeightmapType heightmap) throws UnsupportedOperationException { - this.getChunkAt(x >> 4, z >> 4); // heightmap will ret 0 on unloaded areas - - switch (heightmap) { - case LIGHT_BLOCKING: - throw new UnsupportedOperationException(); // TODO - //return this.world.getHighestBlockY(HeightMap.Type.LIGHT_BLOCKING, x, z); - case ANY: - return this.world.getHighestBlockY(HeightMap.Type.WORLD_SURFACE, x, z); - case SOLID: - return this.world.getHighestBlockY(HeightMap.Type.OCEAN_FLOOR, x, z); - case SOLID_OR_LIQUID: - return this.world.getHighestBlockY(HeightMap.Type.MOTION_BLOCKING, x, z); - case SOLID_OR_LIQUID_NO_LEAVES: - return this.world.getHighestBlockY(HeightMap.Type.MOTION_BLOCKING_NO_LEAVES, x, z); - default: - throw new UnsupportedOperationException(); - } - } - // Paper end - - @Override - public Location getSpawnLocation() { - BlockPosition spawn = world.getSpawn(); - return new Location(this, spawn.getX(), spawn.getY(), spawn.getZ()); - } - - @Override - public boolean setSpawnLocation(Location location) { - Preconditions.checkArgument(location != null, "location"); - - return equals(location.getWorld()) ? setSpawnLocation(location.getBlockX(), location.getBlockY(), location.getBlockZ()) : false; - } - - @Override - 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; - } - } - - @Override - public Chunk getChunkAt(int x, int z) { - return this.world.getChunkProvider().getChunkAt(x, z, true).bukkitChunk; - } - - @Override - public Chunk getChunkAt(Block block) { - return getChunkAt(block.getX() >> 4, block.getZ() >> 4); - } - - @Override - public boolean isChunkLoaded(int x, int z) { - return world.getChunkProvider().getChunkAtIfLoadedImmediately(x, z) != null; // Paper - } - - @Override - public boolean isChunkGenerated(int x, int z) { - // Paper start - Fix this method - if (!Bukkit.isPrimaryThread()) { - return CompletableFuture.supplyAsync(() -> { - return CraftWorld.this.isChunkGenerated(x, z); - }, world.getChunkProvider().serverThreadQueue).join(); - } - IChunkAccess chunk = world.getChunkProvider().getChunkAtImmediately(x, z); - if (chunk == null) { - chunk = world.getChunkProvider().playerChunkMap.getUnloadingChunk(x, z); - } - if (chunk != null) { - return chunk instanceof ProtoChunkExtension || chunk instanceof net.minecraft.server.Chunk; - } - try { - return world.getChunkProvider().playerChunkMap.getChunkStatusOnDisk(new ChunkCoordIntPair(x, z)) == ChunkStatus.FULL; - // Paper end - } catch (IOException ex) { - throw new RuntimeException(ex); - } - } - - @Override - public Chunk[] getLoadedChunks() { - Long2ObjectLinkedOpenHashMap chunks = world.getChunkProvider().playerChunkMap.visibleChunks; - return chunks.values().stream().map(PlayerChunk::getFullChunk).filter(Objects::nonNull).map(net.minecraft.server.Chunk::getBukkitChunk).toArray(Chunk[]::new); - } - - @Override - public void loadChunk(int x, int z) { - loadChunk(x, z, true); - } - - @Override - public boolean unloadChunk(Chunk chunk) { - return unloadChunk(chunk.getX(), chunk.getZ()); - } - - @Override - public boolean unloadChunk(int x, int z) { - return unloadChunk(x, z, true); - } - - @Override - public boolean unloadChunk(int x, int z, boolean save) { - return unloadChunk0(x, z, save); - } - - @Override - public boolean unloadChunkRequest(int x, int z) { - org.spigotmc.AsyncCatcher.catchOp("chunk unload"); // Spigot - net.minecraft.server.IChunkAccess chunk = world.getChunkProvider().getChunkAt(x, z, ChunkStatus.FULL, false); - if (chunk != null) { - world.getChunkProvider().removeTicket(TicketType.PLUGIN, chunk.getPos(), 1, Unit.INSTANCE); - } - - return true; - } - - private boolean unloadChunk0(int x, int z, boolean save) { - org.spigotmc.AsyncCatcher.catchOp("chunk unload"); // Spigot - net.minecraft.server.Chunk chunk = (net.minecraft.server.Chunk) world.getChunkProvider().getChunkAt(x, z, ChunkStatus.FULL, false); - if (chunk == null) { - return true; - } - - chunk.mustNotSave = !save; - unloadChunkRequest(x, z); - - world.getChunkProvider().purgeUnload(); - return !isChunkLoaded(x, z); - } - - @Override - public boolean regenerateChunk(int x, int z) { - org.spigotmc.AsyncCatcher.catchOp("chunk regenerate"); // Spigot - throw new UnsupportedOperationException("Not supported in this Minecraft version! Unless you can fix it, this is not a bug :)"); - /* - if (!unloadChunk0(x, z, false)) { - return false; - } - - final long chunkKey = ChunkCoordIntPair.pair(x, z); - world.getChunkProvider().unloadQueue.remove(chunkKey); - - net.minecraft.server.Chunk chunk = world.getChunkProvider().generateChunk(x, z); - PlayerChunk playerChunk = world.getPlayerChunkMap().getChunk(x, z); - if (playerChunk != null) { - playerChunk.chunk = chunk; - } - - if (chunk != null) { - refreshChunk(x, z); - } - - return chunk != null; - */ - } - - @Override - 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(new BlockPosition(px + (idx / height), ((idx % height) * 16), pz), Blocks.AIR.getBlockData(), Blocks.STONE.getBlockData(), 3); - } - world.notify(new BlockPosition(px + 15, (height * 16) - 1, pz + 15), Blocks.AIR.getBlockData(), Blocks.STONE.getBlockData(), 3); - - return true; - } - - @Override - public boolean isChunkInUse(int x, int z) { - return isChunkLoaded(x, z); - } - - @Override - public boolean loadChunk(int x, int z, boolean generate) { - org.spigotmc.AsyncCatcher.catchOp("chunk load"); // Spigot - // Paper start - Optimize this method - ChunkCoordIntPair chunkPos = new ChunkCoordIntPair(x, z); - - if (!generate) { - - IChunkAccess immediate = world.getChunkProvider().getChunkAtImmediately(x, z); - if (immediate == null) { - immediate = world.getChunkProvider().playerChunkMap.getUnloadingChunk(x, z); - } - if (immediate != null) { - if (!(immediate instanceof ProtoChunkExtension) && !(immediate instanceof net.minecraft.server.Chunk)) { - return false; // not full status - } - world.getChunkProvider().addTicket(TicketType.PLUGIN, chunkPos, 1, Unit.INSTANCE); - world.getChunkAt(x, z); // make sure we're at ticket level 32 or lower - return true; - } - - ChunkStatus status = world.getChunkProvider().playerChunkMap.getStatusOnDiskNoLoad(x, z); // Paper - async io - move to own method - - // Paper start - async io - if (status == ChunkStatus.EMPTY) { - // does not exist on disk - return false; - } - - if (status == null) { // at this stage we don't know what it is on disk - IChunkAccess chunk = world.getChunkProvider().getChunkAt(x, z, ChunkStatus.EMPTY, true); - if (!(chunk instanceof ProtoChunkExtension) && !(chunk instanceof net.minecraft.server.Chunk)) { - return false; - } - } else if (status != ChunkStatus.FULL) { - return false; // not full status on disk - } - // Paper end - - // fall through to load - // we do this so we do not re-read the chunk data on disk - } - - world.getChunkProvider().addTicket(TicketType.PLUGIN, chunkPos, 1, Unit.INSTANCE); - world.getChunkProvider().getChunkAt(x, z, ChunkStatus.FULL, true); - return true; - // Paper end - } - - @Override - public boolean isChunkLoaded(Chunk chunk) { - return isChunkLoaded(chunk.getX(), chunk.getZ()); - } - - @Override - public void loadChunk(Chunk chunk) { - loadChunk(chunk.getX(), chunk.getZ()); - ((CraftChunk) getChunkAt(chunk.getX(), chunk.getZ())).getHandle().bukkitChunk = chunk; - } - - @Override - public boolean addPluginChunkTicket(int x, int z, Plugin plugin) { - Preconditions.checkArgument(plugin != null, "null plugin"); - Preconditions.checkArgument(plugin.isEnabled(), "plugin is not enabled"); - - ChunkMapDistance chunkDistanceManager = this.world.getChunkProvider().playerChunkMap.chunkDistanceManager; - - if (chunkDistanceManager.addTicketAtLevel(TicketType.PLUGIN_TICKET, new ChunkCoordIntPair(x, z), 31, plugin)) { // keep in-line with force loading, add at level 31 - this.getChunkAt(x, z); // ensure loaded - return true; - } - - return false; - } - - @Override - public boolean removePluginChunkTicket(int x, int z, Plugin plugin) { - Preconditions.checkNotNull(plugin, "null plugin"); - - ChunkMapDistance chunkDistanceManager = this.world.getChunkProvider().playerChunkMap.chunkDistanceManager; - return chunkDistanceManager.removeTicketAtLevel(TicketType.PLUGIN_TICKET, new ChunkCoordIntPair(x, z), 31, plugin); // keep in-line with force loading, remove at level 31 - } - - @Override - public void removePluginChunkTickets(Plugin plugin) { - Preconditions.checkNotNull(plugin, "null plugin"); - - ChunkMapDistance chunkDistanceManager = this.world.getChunkProvider().playerChunkMap.chunkDistanceManager; - chunkDistanceManager.removeAllTicketsFor(TicketType.PLUGIN_TICKET, 31, plugin); // keep in-line with force loading, remove at level 31 - } - - @Override - public Collection getPluginChunkTickets(int x, int z) { - ChunkMapDistance chunkDistanceManager = this.world.getChunkProvider().playerChunkMap.chunkDistanceManager; - ObjectSortedSet> tickets = chunkDistanceManager.tickets.get(ChunkCoordIntPair.pair(x, z)); - - if (tickets == null) { - return Collections.emptyList(); - } - - ImmutableList.Builder ret = ImmutableList.builder(); - for (Ticket ticket : tickets) { - if (ticket.getTicketType() == TicketType.PLUGIN_TICKET) { - ret.add((Plugin) ticket.identifier); - } - } - - return ret.build(); - } - - @Override - public Map> getPluginChunkTickets() { - Map> ret = new HashMap<>(); - ChunkMapDistance chunkDistanceManager = this.world.getChunkProvider().playerChunkMap.chunkDistanceManager; - - for (Long2ObjectMap.Entry>> chunkTickets : chunkDistanceManager.tickets.long2ObjectEntrySet()) { - long chunkKey = chunkTickets.getLongKey(); - ObjectSortedSet> tickets = chunkTickets.getValue(); - - Chunk chunk = null; - for (Ticket ticket : tickets) { - if (ticket.getTicketType() != TicketType.PLUGIN_TICKET) { - continue; - } - - if (chunk == null) { - chunk = this.getChunkAt(ChunkCoordIntPair.getX(chunkKey), ChunkCoordIntPair.getZ(chunkKey)); - } - - ret.computeIfAbsent((Plugin) ticket.identifier, (key) -> ImmutableList.builder()).add(chunk); - } - } - - return ret.entrySet().stream().collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, (entry) -> entry.getValue().build())); - } - - @Override - public boolean isChunkForceLoaded(int x, int z) { - return getHandle().getForceLoadedChunks().contains(ChunkCoordIntPair.pair(x, z)); - } - - @Override - public void setChunkForceLoaded(int x, int z, boolean forced) { - getHandle().setForceLoaded(x, z, forced); - } - - @Override - public Collection getForceLoadedChunks() { - Set chunks = new HashSet<>(); - - for (long coord : getHandle().getForceLoadedChunks()) { - chunks.add(getChunkAt(ChunkCoordIntPair.getX(coord), ChunkCoordIntPair.getZ(coord))); - } - - return Collections.unmodifiableCollection(chunks); - } - - public WorldServer getHandle() { - return world; - } - - @Override - public org.bukkit.entity.Item dropItem(Location loc, ItemStack item) { - Validate.notNull(item, "Cannot drop a Null item."); - EntityItem entity = new EntityItem(world, loc.getX(), loc.getY(), loc.getZ(), CraftItemStack.asNMSCopy(item)); - entity.pickupDelay = 10; - world.addEntity(entity, SpawnReason.CUSTOM); - // 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); - } - - @Override - public org.bukkit.entity.Item dropItemNaturally(Location loc, ItemStack item) { - double xs = (world.random.nextFloat() * 0.5F) + 0.25D; - double ys = (world.random.nextFloat() * 0.5F) + 0.25D; - double zs = (world.random.nextFloat() * 0.5F) + 0.25D; - loc = loc.clone(); - loc.setX(loc.getX() + xs); - loc.setY(loc.getY() + ys); - loc.setZ(loc.getZ() + zs); - return dropItem(loc, item); - } - - @Override - public Arrow spawnArrow(Location loc, Vector velocity, float speed, float spread) { - return spawnArrow(loc, velocity, speed, spread, Arrow.class); - } - - @Override - public T spawnArrow(Location loc, Vector velocity, float speed, float spread, Class clazz) { - Validate.notNull(loc, "Can not spawn arrow with a null location"); - Validate.notNull(velocity, "Can not spawn arrow with a null velocity"); - Validate.notNull(clazz, "Can not spawn an arrow with no class"); - - EntityArrow arrow; - if (TippedArrow.class.isAssignableFrom(clazz)) { - arrow = EntityTypes.ARROW.a(world); - ((EntityTippedArrow) arrow).setType(CraftPotionUtil.fromBukkit(new PotionData(PotionType.WATER, false, false))); - } else if (SpectralArrow.class.isAssignableFrom(clazz)) { - arrow = EntityTypes.SPECTRAL_ARROW.a(world); - } else if (Trident.class.isAssignableFrom(clazz)){ - arrow = EntityTypes.TRIDENT.a(world); - } else { - arrow = EntityTypes.ARROW.a(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 (T) arrow.getBukkitEntity(); - } - - @Override - public Entity spawnEntity(Location loc, EntityType entityType) { - return spawn(loc, entityType.getEntityClass()); - } - - @Override - public LightningStrike strikeLightning(Location loc) { - EntityLightning lightning = new EntityLightning(world, loc.getX(), loc.getY(), loc.getZ(), false); - world.strikeLightning(lightning); - return new CraftLightningStrike(server, lightning); - } - - @Override - 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); - } - - @Override - public boolean generateTree(Location loc, TreeType type) { - BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); - - net.minecraft.server.WorldGenerator gen; - net.minecraft.server.WorldGenFeatureConfiguration conf = new WorldGenFeatureEmptyConfiguration(); - switch (type) { - case BIG_TREE: - gen = WorldGenerator.FANCY_TREE; - break; - case BIRCH: - gen = WorldGenerator.BIRCH_TREE; - break; - case REDWOOD: - gen = WorldGenerator.SPRUCE_TREE; - break; - case TALL_REDWOOD: - gen = WorldGenerator.PINE_TREE; - break; - case JUNGLE: - gen = WorldGenerator.MEGA_JUNGLE_TREE; - break; - case SMALL_JUNGLE: - gen = WorldGenerator.JUNGLE_TREE; - break; - case COCOA_TREE: - gen = WorldGenerator.MEGA_JUNGLE_TREE; - break; - case JUNGLE_BUSH: - gen = WorldGenerator.JUNGLE_GROUND_BUSH; - break; - case RED_MUSHROOM: - gen = WorldGenerator.HUGE_RED_MUSHROOM; - conf = new WorldGenHugeMushroomConfiguration(true); - break; - case BROWN_MUSHROOM: - gen = WorldGenerator.HUGE_BROWN_MUSHROOM; - conf = new WorldGenHugeMushroomConfiguration(true); - break; - case SWAMP: - gen = WorldGenerator.SWAMP_TREE; - break; - case ACACIA: - gen = WorldGenerator.SAVANNA_TREE; - break; - case DARK_OAK: - gen = WorldGenerator.DARK_OAK_TREE; - break; - case MEGA_REDWOOD: - gen = WorldGenerator.MEGA_PINE_TREE; - break; - case TALL_BIRCH: - gen = WorldGenerator.SUPER_BIRCH_TREE; - break; - case CHORUS_PLANT: - ((BlockChorusFlower) Blocks.CHORUS_FLOWER).a(world, pos, rand, 8); - return true; - case TREE: - default: - gen = WorldGenerator.NORMAL_TREE; - break; - } - - return gen.generate(world, world.worldProvider.getChunkGenerator(), rand, pos, conf); - } - - @Override - 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) { - BlockPosition position = ((CraftBlockState) blockstate).getPosition(); - net.minecraft.server.IBlockData oldBlock = world.getType(position); - int flag = ((CraftBlockState) blockstate).getFlag(); - delegate.setBlockData(blockstate.getX(), blockstate.getY(), blockstate.getZ(), blockstate.getBlockData()); - net.minecraft.server.IBlockData newBlock = world.getType(position); - world.notifyAndUpdatePhysics(position, null, oldBlock, newBlock, newBlock, flag); - } - world.capturedBlockStates.clear(); - return true; - } else { - world.capturedBlockStates.clear(); - return false; - } - } - - @Override - public String getName() { - return world.worldData.getName(); - } - - @Deprecated - public long getId() { - return world.worldData.getSeed(); - } - - @Override - public UUID getUID() { - return world.getDataManager().getUUID(); - } - - @Override - public String toString() { - return "CraftWorld{name=" + getName() + '}'; - } - - @Override - public long getTime() { - long time = getFullTime() % 24000; - if (time < 0) time += 24000; - return time; - } - - @Override - public void setTime(long time) { - long margin = (time - getFullTime()) % 24000; - if (margin < 0) margin += 24000; - setFullTime(getFullTime() + margin); - } - - @Override - public long getFullTime() { - return world.getDayTime(); - } - - @Override - 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(GameRules.DO_DAYLIGHT_CYCLE))); - } - } - - // Paper start - @Override - public boolean isDayTime() { - return getHandle().isDayTime(); - } - // Paper end - - @Override - public boolean createExplosion(double x, double y, double z, float power) { - return createExplosion(x, y, z, power, false, true); - } - - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire) { - return createExplosion(x, y, z, power, setFire, true); - } - - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { - return createExplosion(x, y, z, power, setFire, breakBlocks, null); - } - - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source) { - return !world.createExplosion(source == null ? null : ((CraftEntity) source).getHandle(), x, y, z, power, setFire, breakBlocks ? Explosion.Effect.BREAK : Explosion.Effect.NONE).wasCanceled; - } - // Paper start - public boolean createExplosion(Entity source, Location loc, float power, boolean setFire, boolean breakBlocks) { - return !world.createExplosion(source != null ? ((org.bukkit.craftbukkit.entity.CraftEntity) source).getHandle() : null, loc.getX(), loc.getY(), loc.getZ(), power, setFire, breakBlocks ? Explosion.Effect.BREAK : Explosion.Effect.NONE).wasCanceled; - } - // Paper end - - @Override - public boolean createExplosion(Location loc, float power) { - return createExplosion(loc, power, false); - } - - @Override - public boolean createExplosion(Location loc, float power, boolean setFire) { - return createExplosion(loc, power, setFire, true); - } - - @Override - public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks) { - return createExplosion(loc, power, setFire, breakBlocks, null); - } - - @Override - public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks, Entity source) { - Preconditions.checkArgument(loc != null, "Location is null"); - Preconditions.checkArgument(this.equals(loc.getWorld()), "Location not in world"); - - return createExplosion(loc.getX(), loc.getY(), loc.getZ(), power, setFire, breakBlocks, source); - } - - @Override - public Environment getEnvironment() { - return environment; - } - - @Override - public Block getBlockAt(Location location) { - return getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - - @Override - public int getHighestBlockYAt(Location location) { - return getHighestBlockYAt(location.getBlockX(), location.getBlockZ()); - } - - @Override - public Chunk getChunkAt(Location location) { - return getChunkAt(location.getBlockX() >> 4, location.getBlockZ() >> 4); - } - - @Override - public ChunkGenerator getGenerator() { - return generator; - } - - @Override - public List getPopulators() { - return populators; - } - - @Override - public Block getHighestBlockAt(int x, int z) { - return getBlockAt(x, getHighestBlockYAt(x, z), z); - } - - @Override - public Block getHighestBlockAt(Location location) { - return getHighestBlockAt(location.getBlockX(), location.getBlockZ()); - } - - @Override - public Biome getBiome(int x, int z) { - return CraftBlock.biomeBaseToBiome(this.world.getBiome(new BlockPosition(x, 0, z))); - } - - @Override - public void setBiome(int x, int z, Biome bio) { - BiomeBase bb = CraftBlock.biomeToBiomeBase(bio); - if (this.world.isLoaded(new BlockPosition(x, 0, z))) { - net.minecraft.server.Chunk chunk = this.world.getChunkAtWorldCoords(new BlockPosition(x, 0, z)); - - if (chunk != null) { - BiomeBase[] biomevals = chunk.getBiomeIndex(); - biomevals[((z & 0xF) << 4) | (x & 0xF)] = bb; - - chunk.markDirty(); // SPIGOT-2890 - } - } - } - - @Override - public double getTemperature(int x, int z) { - return this.world.getBiome(new BlockPosition(x, 0, z)).getTemperature(); - } - - @Override - public double getHumidity(int x, int z) { - return this.world.getBiome(new BlockPosition(x, 0, z)).getHumidity(); - } - - @Override - public List getEntities() { - List list = new ArrayList(); - - for (Object o : world.entitiesById.values()) { - if (o instanceof net.minecraft.server.Entity) { - net.minecraft.server.Entity mcEnt = (net.minecraft.server.Entity) o; - if (mcEnt.shouldBeRemoved) continue; // Paper - Entity bukkitEntity = mcEnt.getBukkitEntity(); - - // Assuming that bukkitEntity isn't null - if (bukkitEntity != null && bukkitEntity.isValid()) { - list.add(bukkitEntity); - } - } - } - - return list; - } - - @Override - public List getLivingEntities() { - List list = new ArrayList(); - - for (Object o : world.entitiesById.values()) { - if (o instanceof net.minecraft.server.Entity) { - net.minecraft.server.Entity mcEnt = (net.minecraft.server.Entity) o; - if (mcEnt.shouldBeRemoved) continue; // Paper - Entity bukkitEntity = mcEnt.getBukkitEntity(); - - // Assuming that bukkitEntity isn't null - if (bukkitEntity != null && bukkitEntity instanceof LivingEntity && bukkitEntity.isValid()) { - list.add((LivingEntity) bukkitEntity); - } - } - } - - return list; - } - - @Override - @SuppressWarnings("unchecked") - @Deprecated - public Collection getEntitiesByClass(Class... classes) { - return (Collection)getEntitiesByClasses(classes); - } - - @Override - @SuppressWarnings("unchecked") - public Collection getEntitiesByClass(Class clazz) { - Collection list = new ArrayList(); - - for (Object entity: world.entitiesById.values()) { - if (entity instanceof net.minecraft.server.Entity) { - if (((net.minecraft.server.Entity) entity).shouldBeRemoved) continue; // Paper - Entity bukkitEntity = ((net.minecraft.server.Entity) entity).getBukkitEntity(); - - if (bukkitEntity == null) { - continue; - } - - Class bukkitClass = bukkitEntity.getClass(); - - if (clazz.isAssignableFrom(bukkitClass) && bukkitEntity.isValid()) { - list.add((T) bukkitEntity); - } - } - } - - return list; - } - - @Override - public Collection getEntitiesByClasses(Class... classes) { - Collection list = new ArrayList(); - - for (Object entity: world.entitiesById.values()) { - if (entity instanceof net.minecraft.server.Entity) { - if (((net.minecraft.server.Entity) entity).shouldBeRemoved) continue; // Paper - Entity bukkitEntity = ((net.minecraft.server.Entity) entity).getBukkitEntity(); - - if (bukkitEntity == null) { - continue; - } - - Class bukkitClass = bukkitEntity.getClass(); - - for (Class clazz : classes) { - if (clazz.isAssignableFrom(bukkitClass)) { - if (bukkitEntity.isValid()) { - list.add(bukkitEntity); - } - break; - } - } - } - } - - return list; - } - - @Override - public Collection getNearbyEntities(Location location, double x, double y, double z) { - return this.getNearbyEntities(location, x, y, z, null); - } - - @Override - public Collection getNearbyEntities(Location location, double x, double y, double z, Predicate filter) { - Validate.notNull(location, "Location is null!"); - Validate.isTrue(this.equals(location.getWorld()), "Location is from different world!"); - - BoundingBox aabb = BoundingBox.of(location, x, y, z); - return this.getNearbyEntities(aabb, filter); - } - - @Override - public Collection getNearbyEntities(BoundingBox boundingBox) { - return this.getNearbyEntities(boundingBox, null); - } - - @Override - public Collection getNearbyEntities(BoundingBox boundingBox, Predicate filter) { - org.spigotmc.AsyncCatcher.catchOp("getNearbyEntities"); // Spigot - Validate.notNull(boundingBox, "Bounding box is null!"); - - AxisAlignedBB bb = new AxisAlignedBB(boundingBox.getMinX(), boundingBox.getMinY(), boundingBox.getMinZ(), boundingBox.getMaxX(), boundingBox.getMaxY(), boundingBox.getMaxZ()); - List entityList = getHandle().getEntities((net.minecraft.server.Entity) null, bb, null); - List bukkitEntityList = new ArrayList(entityList.size()); - - for (net.minecraft.server.Entity entity : entityList) { - Entity bukkitEntity = entity.getBukkitEntity(); - if (filter == null || filter.test(bukkitEntity)) { - bukkitEntityList.add(bukkitEntity); - } - } - - return bukkitEntityList; - } - - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance) { - return this.rayTraceEntities(start, direction, maxDistance, null); - } - - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize) { - return this.rayTraceEntities(start, direction, maxDistance, raySize, null); - } - - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, Predicate filter) { - return this.rayTraceEntities(start, direction, maxDistance, 0.0D, filter); - } - - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate filter) { - Validate.notNull(start, "Start location is null!"); - Validate.isTrue(this.equals(start.getWorld()), "Start location is from different world!"); - start.checkFinite(); - - Validate.notNull(direction, "Direction is null!"); - direction.checkFinite(); - - Validate.isTrue(direction.lengthSquared() > 0, "Direction's magnitude is 0!"); - - if (maxDistance < 0.0D) { - return null; - } - - Vector startPos = start.toVector(); - Vector dir = direction.clone().normalize().multiply(maxDistance); - BoundingBox aabb = BoundingBox.of(startPos, startPos).expandDirectional(dir).expand(raySize); - Collection entities = this.getNearbyEntities(aabb, filter); - - Entity nearestHitEntity = null; - RayTraceResult nearestHitResult = null; - double nearestDistanceSq = Double.MAX_VALUE; - - for (Entity entity : entities) { - BoundingBox boundingBox = entity.getBoundingBox().expand(raySize); - RayTraceResult hitResult = boundingBox.rayTrace(startPos, direction, maxDistance); - - if (hitResult != null) { - double distanceSq = startPos.distanceSquared(hitResult.getHitPosition()); - - if (distanceSq < nearestDistanceSq) { - nearestHitEntity = entity; - nearestHitResult = hitResult; - nearestDistanceSq = distanceSq; - } - } - } - - return (nearestHitEntity == null) ? null : new RayTraceResult(nearestHitResult.getHitPosition(), nearestHitEntity, nearestHitResult.getHitBlockFace()); - } - - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance) { - return this.rayTraceBlocks(start, direction, maxDistance, FluidCollisionMode.NEVER, false); - } - - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) { - return this.rayTraceBlocks(start, direction, maxDistance, fluidCollisionMode, false); - } - - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) { - Validate.notNull(start, "Start location is null!"); - Validate.isTrue(this.equals(start.getWorld()), "Start location is from different world!"); - start.checkFinite(); - - Validate.notNull(direction, "Direction is null!"); - direction.checkFinite(); - - Validate.isTrue(direction.lengthSquared() > 0, "Direction's magnitude is 0!"); - Validate.notNull(fluidCollisionMode, "Fluid collision mode is null!"); - - if (maxDistance < 0.0D) { - return null; - } - - Vector dir = direction.clone().normalize().multiply(maxDistance); - Vec3D startPos = new Vec3D(start.getX(), start.getY(), start.getZ()); - Vec3D endPos = new Vec3D(start.getX() + dir.getX(), start.getY() + dir.getY(), start.getZ() + dir.getZ()); - MovingObjectPosition nmsHitResult = this.getHandle().rayTrace(new RayTrace(startPos, endPos, ignorePassableBlocks ? RayTrace.BlockCollisionOption.COLLIDER : RayTrace.BlockCollisionOption.OUTLINE, CraftFluidCollisionMode.toNMS(fluidCollisionMode), null)); - - return CraftRayTraceResult.fromNMS(this, nmsHitResult); - } - - @Override - public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks, double raySize, Predicate filter) { - RayTraceResult blockHit = this.rayTraceBlocks(start, direction, maxDistance, fluidCollisionMode, ignorePassableBlocks); - Vector startVec = null; - double blockHitDistance = maxDistance; - - // limiting the entity search range if we found a block hit: - if (blockHit != null) { - startVec = start.toVector(); - blockHitDistance = startVec.distance(blockHit.getHitPosition()); - } - - RayTraceResult entityHit = this.rayTraceEntities(start, direction, blockHitDistance, raySize, filter); - if (blockHit == null) { - return entityHit; - } - - if (entityHit == null) { - return blockHit; - } - - // Cannot be null as blockHit == null returns above - double entityHitDistanceSquared = startVec.distanceSquared(entityHit.getHitPosition()); - if (entityHitDistanceSquared < (blockHitDistance * blockHitDistance)) { - return entityHit; - } - - return blockHit; - } - - @Override - public List getPlayers() { - List list = new ArrayList(world.getPlayers().size()); - - for (EntityHuman human : world.getPlayers()) { - HumanEntity bukkitEntity = human.getBukkitEntity(); - - if ((bukkitEntity != null) && (bukkitEntity instanceof Player)) { - list.add((Player) bukkitEntity); - } - } - - return list; - } - - // Paper start - getEntity by UUID API - @Override - public Entity getEntity(UUID uuid) { - Validate.notNull(uuid, "UUID cannot be null"); - net.minecraft.server.Entity entity = world.getEntity(uuid); - return entity == null ? null : entity.getBukkitEntity(); - } - // Paper end - - @Override - public void save() { - org.spigotmc.AsyncCatcher.catchOp("world save"); // Spigot - this.server.checkSaveState(); - try { - boolean oldSave = world.savingDisabled; - - world.savingDisabled = false; - world.save(null, false, false); - - world.savingDisabled = oldSave; - } catch (ExceptionWorldConflict ex) { - ex.printStackTrace(); - } - } - - @Override - public boolean isAutoSave() { - return !world.savingDisabled; - } - - @Override - public void setAutoSave(boolean value) { - world.savingDisabled = !value; - } - - @Override - public void setDifficulty(Difficulty difficulty) { - this.getHandle().worldData.setDifficulty(EnumDifficulty.getById(difficulty.getValue())); - } - - @Override - public Difficulty getDifficulty() { - return Difficulty.getByValue(this.getHandle().getDifficulty().ordinal()); - } - - public BlockMetadataStore getBlockMetadata() { - return blockMetadata; - } - - @Override - public boolean hasStorm() { - return world.worldData.hasStorm(); - } - - @Override - public void setStorm(boolean hasStorm) { - world.worldData.setStorm(hasStorm); - setWeatherDuration(0); // Reset weather duration (legacy behaviour) - } - - @Override - public int getWeatherDuration() { - return world.worldData.getWeatherDuration(); - } - - @Override - public void setWeatherDuration(int duration) { - world.worldData.setWeatherDuration(duration); - } - - @Override - public boolean isThundering() { - return world.worldData.isThundering(); - } - - @Override - public void setThundering(boolean thundering) { - world.worldData.setThundering(thundering); - setThunderDuration(0); // Reset weather duration (legacy behaviour) - } - - @Override - public int getThunderDuration() { - return world.worldData.getThunderDuration(); - } - - @Override - public void setThunderDuration(int duration) { - world.worldData.setThunderDuration(duration); - } - - @Override - public long getSeed() { - return world.worldData.getSeed(); - } - - @Override - public boolean getPVP() { - return world.pvpMode; - } - - @Override - public void setPVP(boolean pvp) { - world.pvpMode = pvp; - } - - public void playEffect(Player player, Effect effect, int data) { - playEffect(player.getLocation(), effect, data, 0); - } - - @Override - public void playEffect(Location location, Effect effect, int data) { - playEffect(location, effect, data, 64); - } - - @Override - public void playEffect(Location loc, Effect effect, T data) { - playEffect(loc, effect, data, 64); - } - - @Override - public void playEffect(Location loc, Effect effect, T data, int radius) { - if (data != null) { - Validate.isTrue(effect.getData() != null && effect.getData().isAssignableFrom(data.getClass()), "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, radius); - } - - @Override - public void playEffect(Location location, Effect effect, int data, int radius) { - Validate.notNull(location, "Location cannot be null"); - Validate.notNull(effect, "Effect cannot be null"); - Validate.notNull(location.getWorld(), "World cannot be null"); - int packetData = effect.getId(); - PacketPlayOutWorldEvent packet = new PacketPlayOutWorldEvent(packetData, new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()), data, false); - 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 T spawn(Location location, Class clazz) throws IllegalArgumentException { - return spawn(location, clazz, null, SpawnReason.CUSTOM); - } - - @Override - public T spawn(Location location, Class clazz, Consumer function) throws IllegalArgumentException { - return spawn(location, clazz, function, SpawnReason.CUSTOM); - } - - @Override - public FallingBlock spawnFallingBlock(Location location, MaterialData data) throws IllegalArgumentException { - Validate.notNull(data, "MaterialData cannot be null"); - return spawnFallingBlock(location, data.getItemType(), data.getData()); - } - - @Override - 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"); - - EntityFallingBlock entity = new EntityFallingBlock(world, location.getX(), location.getY(), location.getZ(), CraftMagicNumbers.getBlock(material).getBlockData()); - entity.ticksLived = 1; - - world.addEntity(entity, SpawnReason.CUSTOM); - return (FallingBlock) entity.getBukkitEntity(); - } - - @Override - public FallingBlock spawnFallingBlock(Location location, BlockData data) throws IllegalArgumentException { - Validate.notNull(location, "Location cannot be null"); - Validate.notNull(data, "Material cannot be null"); - - EntityFallingBlock entity = new EntityFallingBlock(world, location.getX(), location.getY(), location.getZ(), ((CraftBlockData) data).getState()); - entity.ticksLived = 1; - - world.addEntity(entity, SpawnReason.CUSTOM); - return (FallingBlock) entity.getBukkitEntity(); - } - - @SuppressWarnings("unchecked") - 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); - entity.setPositionRotation(x, y, z, yaw, pitch); - // Paper start - } else if (org.bukkit.entity.Item.class.isAssignableFrom(clazz)) { - entity = new EntityItem(world, x, y, z, new net.minecraft.server.ItemStack(net.minecraft.server.Item.getItemOf(net.minecraft.server.Blocks.DIRT))); - // Paper end - } else if (FallingBlock.class.isAssignableFrom(clazz)) { - entity = new EntityFallingBlock(world, x, y, z, world.getType(new BlockPosition(x, y, z))); - } 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 (AbstractArrow.class.isAssignableFrom(clazz)) { - if (TippedArrow.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ARROW.a(world); - ((EntityTippedArrow) entity).setType(CraftPotionUtil.fromBukkit(new PotionData(PotionType.WATER, false, false))); - } else if (SpectralArrow.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SPECTRAL_ARROW.a(world); - } else if (Trident.class.isAssignableFrom(clazz)) { - entity = EntityTypes.TRIDENT.a(world); - } else { - entity = EntityTypes.ARROW.a(world); - } - entity.setPositionRotation(x, y, z, 0, 0); - } else if (ThrownExpBottle.class.isAssignableFrom(clazz)) { - entity = EntityTypes.EXPERIENCE_BOTTLE.a(world); - entity.setPositionRotation(x, y, z, 0, 0); - } else if (EnderPearl.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ENDER_PEARL.a(world); - entity.setPositionRotation(x, y, z, 0, 0); - } else if (ThrownPotion.class.isAssignableFrom(clazz)) { - if (LingeringPotion.class.isAssignableFrom(clazz)) { - entity = new EntityPotion(world, x, y, z); - ((EntityPotion) entity).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.LINGERING_POTION, 1))); - } else { - entity = new EntityPotion(world, x, y, z); - ((EntityPotion) entity).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.SPLASH_POTION, 1))); - } - } else if (Fireball.class.isAssignableFrom(clazz)) { - if (SmallFireball.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SMALL_FIREBALL.a(world); - } else if (WitherSkull.class.isAssignableFrom(clazz)) { - entity = EntityTypes.WITHER_SKULL.a(world); - } else if (DragonFireball.class.isAssignableFrom(clazz)) { - entity = EntityTypes.DRAGON_FIREBALL.a(world); - } else { - entity = EntityTypes.FIREBALL.a(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 (ShulkerBullet.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SHULKER_BULLET.a(world); - entity.setPositionRotation(x, y, z, yaw, pitch); - } else if (LlamaSpit.class.isAssignableFrom(clazz)) { - entity = EntityTypes.LLAMA_SPIT.a(world); - entity.setPositionRotation(x, y, z, yaw, pitch); - } - } 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 if (CommandMinecart.class.isAssignableFrom(clazz)) { - entity = new EntityMinecartCommandBlock(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 = EntityTypes.END_CRYSTAL.a(world); - entity.setPositionRotation(x, y, z, 0, 0); - } else if (LivingEntity.class.isAssignableFrom(clazz)) { - if (Chicken.class.isAssignableFrom(clazz)) { - entity = EntityTypes.CHICKEN.a(world); - } else if (Cow.class.isAssignableFrom(clazz)) { - if (MushroomCow.class.isAssignableFrom(clazz)) { - entity = EntityTypes.MOOSHROOM.a(world); - } else { - entity = EntityTypes.COW.a(world); - } - } else if (Golem.class.isAssignableFrom(clazz)) { - if (Snowman.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SNOW_GOLEM.a(world); - } else if (IronGolem.class.isAssignableFrom(clazz)) { - entity = EntityTypes.IRON_GOLEM.a(world); - } else if (Shulker.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SHULKER.a(world); - } - } else if (Creeper.class.isAssignableFrom(clazz)) { - entity = EntityTypes.CREEPER.a(world); - } else if (Ghast.class.isAssignableFrom(clazz)) { - entity = EntityTypes.GHAST.a(world); - } else if (Pig.class.isAssignableFrom(clazz)) { - entity = EntityTypes.PIG.a(world); - } else if (Player.class.isAssignableFrom(clazz)) { - // need a net server handler for this one - } else if (Sheep.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SHEEP.a(world); - } else if (AbstractHorse.class.isAssignableFrom(clazz)) { - if (ChestedHorse.class.isAssignableFrom(clazz)) { - if (Donkey.class.isAssignableFrom(clazz)) { - entity = EntityTypes.DONKEY.a(world); - } else if (Mule.class.isAssignableFrom(clazz)) { - entity = EntityTypes.MULE.a(world); - } else if (Llama.class.isAssignableFrom(clazz)) { - if (TraderLlama.class.isAssignableFrom(clazz)) { - entity = EntityTypes.TRADER_LLAMA.a(world); - } else { - entity = EntityTypes.LLAMA.a(world); - } - } - } else if (SkeletonHorse.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SKELETON_HORSE.a(world); - } else if (ZombieHorse.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ZOMBIE_HORSE.a(world); - } else { - entity = EntityTypes.HORSE.a(world); - } - } else if (Skeleton.class.isAssignableFrom(clazz)) { - if (Stray.class.isAssignableFrom(clazz)){ - entity = EntityTypes.STRAY.a(world); - } else if (WitherSkeleton.class.isAssignableFrom(clazz)) { - entity = EntityTypes.WITHER_SKELETON.a(world); - } else { - entity = EntityTypes.SKELETON.a(world); - } - } else if (Slime.class.isAssignableFrom(clazz)) { - if (MagmaCube.class.isAssignableFrom(clazz)) { - entity = EntityTypes.MAGMA_CUBE.a(world); - } else { - entity = EntityTypes.SLIME.a(world); - } - } else if (Spider.class.isAssignableFrom(clazz)) { - if (CaveSpider.class.isAssignableFrom(clazz)) { - entity = EntityTypes.CAVE_SPIDER.a(world); - } else { - entity = EntityTypes.SPIDER.a(world); - } - } else if (Squid.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SQUID.a(world); - } else if (Tameable.class.isAssignableFrom(clazz)) { - if (Wolf.class.isAssignableFrom(clazz)) { - entity = EntityTypes.WOLF.a(world); - } else if (Parrot.class.isAssignableFrom(clazz)) { - entity = EntityTypes.PARROT.a(world); - } else if (Cat.class.isAssignableFrom(clazz)) { - entity = EntityTypes.CAT.a(world); - } - } else if (PigZombie.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ZOMBIE_PIGMAN.a(world); - } else if (Zombie.class.isAssignableFrom(clazz)) { - if (Husk.class.isAssignableFrom(clazz)) { - entity = EntityTypes.HUSK.a(world); - } else if (ZombieVillager.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ZOMBIE_VILLAGER.a(world); - } else if (Drowned.class.isAssignableFrom(clazz)) { - entity = EntityTypes.DROWNED.a(world); - } else { - entity = new EntityZombie(world); - } - } else if (Giant.class.isAssignableFrom(clazz)) { - entity = EntityTypes.GIANT.a(world); - } else if (Silverfish.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SILVERFISH.a(world); - } else if (Enderman.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ENDERMAN.a(world); - } else if (Blaze.class.isAssignableFrom(clazz)) { - entity = EntityTypes.BLAZE.a(world); - } else if (AbstractVillager.class.isAssignableFrom(clazz)) { - if (Villager.class.isAssignableFrom(clazz)) { - entity = EntityTypes.VILLAGER.a(world); - } else if (WanderingTrader.class.isAssignableFrom(clazz)) { - entity = EntityTypes.WANDERING_TRADER.a(world); - } - } else if (Witch.class.isAssignableFrom(clazz)) { - entity = EntityTypes.WITCH.a(world); - } else if (Wither.class.isAssignableFrom(clazz)) { - entity = EntityTypes.WITHER.a(world); - } else if (ComplexLivingEntity.class.isAssignableFrom(clazz)) { - if (EnderDragon.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ENDER_DRAGON.a(world); - } - } else if (Ambient.class.isAssignableFrom(clazz)) { - if (Bat.class.isAssignableFrom(clazz)) { - entity = EntityTypes.BAT.a(world); - } - } else if (Rabbit.class.isAssignableFrom(clazz)) { - entity = EntityTypes.RABBIT.a(world); - } else if (Endermite.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ENDERMITE.a(world); - } else if (Guardian.class.isAssignableFrom(clazz)) { - if (ElderGuardian.class.isAssignableFrom(clazz)){ - entity = EntityTypes.ELDER_GUARDIAN.a(world); - } else { - entity = EntityTypes.GUARDIAN.a(world); - } - } else if (ArmorStand.class.isAssignableFrom(clazz)) { - entity = new EntityArmorStand(world, x, y, z); - } else if (PolarBear.class.isAssignableFrom(clazz)) { - entity = EntityTypes.POLAR_BEAR.a(world); - } else if (Vex.class.isAssignableFrom(clazz)) { - entity = EntityTypes.VEX.a(world); - } else if (Illager.class.isAssignableFrom(clazz)) { - if (Spellcaster.class.isAssignableFrom(clazz)) { - if (Evoker.class.isAssignableFrom(clazz)) { - entity = EntityTypes.EVOKER.a(world); - } else if (Illusioner.class.isAssignableFrom(clazz)) { - entity = EntityTypes.ILLUSIONER.a(world); - } - } else if (Vindicator.class.isAssignableFrom(clazz)) { - entity = EntityTypes.VINDICATOR.a(world); - } else if (Pillager.class.isAssignableFrom(clazz)) { - entity = EntityTypes.PILLAGER.a(world); - } - } else if (Turtle.class.isAssignableFrom(clazz)) { - entity = EntityTypes.TURTLE.a(world); - } else if (Phantom.class.isAssignableFrom(clazz)) { - entity = EntityTypes.PHANTOM.a(world); - } else if (Fish.class.isAssignableFrom(clazz)) { - if (Cod.class.isAssignableFrom(clazz)) { - entity = EntityTypes.COD.a(world); - } else if (PufferFish.class.isAssignableFrom(clazz)) { - entity = EntityTypes.PUFFERFISH.a(world); - } else if (Salmon.class.isAssignableFrom(clazz)) { - entity = EntityTypes.SALMON.a(world); - } else if (TropicalFish.class.isAssignableFrom(clazz)) { - entity = EntityTypes.TROPICAL_FISH.a(world); - } - } else if (Dolphin.class.isAssignableFrom(clazz)) { - entity = EntityTypes.DOLPHIN.a(world); - } else if (Ocelot.class.isAssignableFrom(clazz)) { - entity = EntityTypes.OCELOT.a(world); - } else if (Ravager.class.isAssignableFrom(clazz)) { - entity = EntityTypes.RAVAGER.a(world); - } else if (Panda.class.isAssignableFrom(clazz)) { - entity = EntityTypes.PANDA.a(world); - } else if (Fox.class.isAssignableFrom(clazz)) { - entity = EntityTypes.FOX.a(world); - } - - if (entity != null) { - entity.setLocation(x, y, z, yaw, pitch); - entity.setHeadRotation(yaw); // SPIGOT-3587 - } - } else if (Hanging.class.isAssignableFrom(clazz)) { - 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; - } - - // Paper start - In addition to d65a2576e40e58c8e446b330febe6799d13a604f do not check UP/DOWN for non item frames - // BlockFace[] faces = new BlockFace[]{BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.UP, BlockFace.DOWN}; - BlockFace[] faces = (ItemFrame.class.isAssignableFrom(clazz)) - ? new BlockFace[]{BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.UP, BlockFace.DOWN} - : new BlockFace[]{BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH}; - // Paper end - final BlockPosition pos = new BlockPosition(x, y, z); - for (BlockFace dir : faces) { - IBlockData nmsBlock = world.getType(pos.shift(CraftBlock.blockFaceToNotch(dir))); - if (nmsBlock.getMaterial().isBuildable() || BlockDiodeAbstract.isDiode(nmsBlock)) { - boolean taken = false; - AxisAlignedBB bb = (ItemFrame.class.isAssignableFrom(clazz)) - ? EntityItemFrame.calculateBoundingBox(null, pos, CraftBlock.blockFaceToNotch(dir).opposite(), width, height) - : EntityHanging.calculateBoundingBox(null, pos, CraftBlock.blockFaceToNotch(dir).opposite(), width, height); - List 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; - } - } - } - - if (LeashHitch.class.isAssignableFrom(clazz)) { - entity = new EntityLeash(world, new BlockPosition(x, y, z)); - entity.attachedToPlayer = true; - } else { - // No valid face found - Preconditions.checkArgument(face != BlockFace.SELF, "Cannot spawn hanging entity for %s at %s (no free face)", clazz.getName(), location); - - EnumDirection dir = CraftBlock.blockFaceToNotch(face).opposite(); - if (Painting.class.isAssignableFrom(clazz)) { - entity = new EntityPainting(world, new BlockPosition(x, y, z), dir); - } else if (ItemFrame.class.isAssignableFrom(clazz)) { - entity = new EntityItemFrame(world, new BlockPosition(x, y, z), dir); - } - } - - if (entity != null && !((EntityHanging) entity).survives()) { - throw new IllegalArgumentException("Cannot spawn hanging entity for " + clazz.getName() + " at " + location); - } - } else if (TNTPrimed.class.isAssignableFrom(clazz)) { - entity = new EntityTNTPrimed(world, x, y, z, null); - } else if (ExperienceOrb.class.isAssignableFrom(clazz)) { - entity = new EntityExperienceOrb(world, x, y, z, 0, org.bukkit.entity.ExperienceOrb.SpawnReason.CUSTOM, null, null); // Paper - } else if (LightningStrike.class.isAssignableFrom(clazz)) { - entity = new EntityLightning(world, x, y, z, false); - } else if (Firework.class.isAssignableFrom(clazz)) { - entity = new EntityFireworks(world, x, y, z, net.minecraft.server.ItemStack.a); - } else if (AreaEffectCloud.class.isAssignableFrom(clazz)) { - entity = new EntityAreaEffectCloud(world, x, y, z); - } else if (EvokerFangs.class.isAssignableFrom(clazz)) { - entity = new EntityEvokerFangs(world, x, y, z, (float) Math.toRadians(yaw), 0, null); - } - - if (entity != null) { - // Spigot start - if (entity instanceof net.minecraft.server.EntityOcelot) - { - ( (net.minecraft.server.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 { - return addEntity(entity, reason, null); - } - - @SuppressWarnings("unchecked") - public T addEntity(net.minecraft.server.Entity entity, SpawnReason reason, Consumer function) throws IllegalArgumentException { - Preconditions.checkArgument(entity != null, "Cannot spawn null entity"); - - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(getHandle(), getHandle().getDamageScaler(new BlockPosition(entity)), EnumMobSpawn.COMMAND, (GroupDataEntity) null, null); - } - - if (function != null) { - function.accept((T) entity.getBukkitEntity()); - } - - world.addEntity(entity, reason); - return (T) entity.getBukkitEntity(); - } - - public T spawn(Location location, Class clazz, Consumer function, SpawnReason reason) throws IllegalArgumentException { - net.minecraft.server.Entity entity = createEntity(location, clazz); - - return addEntity(entity, reason, function); - } - - @Override - public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTempRain) { - return CraftChunk.getEmptyChunkSnapshot(x, z, this, includeBiome, includeBiomeTempRain); - } - - @Override - public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals) { - world.setSpawnFlags(allowMonsters, allowAnimals); - } - - @Override - public boolean getAllowAnimals() { - return world.getChunkProvider().allowAnimals; - } - - @Override - public boolean getAllowMonsters() { - return world.getChunkProvider().allowMonsters; - } - - @Override - public int getMaxHeight() { - return world.getBuildHeight(); - } - - @Override - public int getSeaLevel() { - return world.getSeaLevel(); - } - - @Override - public boolean getKeepSpawnInMemory() { - return world.keepSpawnInMemory; - } - - @Override - public void setKeepSpawnInMemory(boolean keepLoaded) { - // Paper start - Configurable spawn radius - if (keepLoaded == world.keepSpawnInMemory) { - // do nothing, nothing has changed - return; - } - world.keepSpawnInMemory = keepLoaded; - // Grab the worlds spawn chunk - BlockPosition prevSpawn = this.world.getSpawn(); - if (keepLoaded) { - world.addTicketsForSpawn(world.paperConfig.keepLoadedRange, prevSpawn); - } else { - // TODO: doesn't work well if spawn changed.... // paper - resolved - world.removeTicketsForSpawn(world.paperConfig.keepLoadedRange, prevSpawn); - } - // Paper end - } - - @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(); - } - - @Override - public File getWorldFolder() { - return world.getDataManager().getDirectory(); - } - - @Override - 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); - } - } - - @Override - public Set getListeningPluginChannels() { - Set result = new HashSet(); - - for (Player player : getPlayers()) { - result.addAll(player.getListeningPluginChannels()); - } - - return result; - } - - @Override - public org.bukkit.WorldType getWorldType() { - return org.bukkit.WorldType.getByName(world.getWorldData().getType().name()); - } - - @Override - public boolean canGenerateStructures() { - return world.getWorldData().shouldGenerateMapFeatures(); - } - - @Override - public long getTicksPerAnimalSpawns() { - return world.ticksPerAnimalSpawns; - } - - @Override - public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns) { - world.ticksPerAnimalSpawns = ticksPerAnimalSpawns; - } - - @Override - public long getTicksPerMonsterSpawns() { - return world.ticksPerMonsterSpawns; - } - - @Override - public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns) { - world.ticksPerMonsterSpawns = ticksPerMonsterSpawns; - } - - @Override - public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - server.getWorldMetadata().setMetadata(this, metadataKey, newMetadataValue); - } - - @Override - public List getMetadata(String metadataKey) { - return server.getWorldMetadata().getMetadata(this, metadataKey); - } - - @Override - public boolean hasMetadata(String metadataKey) { - return server.getWorldMetadata().hasMetadata(this, metadataKey); - } - - @Override - public void removeMetadata(String metadataKey, Plugin owningPlugin) { - server.getWorldMetadata().removeMetadata(this, metadataKey, owningPlugin); - } - - @Override - public int getMonsterSpawnLimit() { - if (monsterSpawn < 0) { - return server.getMonsterSpawnLimit(); - } - - return monsterSpawn; - } - - @Override - public void setMonsterSpawnLimit(int limit) { - monsterSpawn = limit; - } - - @Override - public int getAnimalSpawnLimit() { - if (animalSpawn < 0) { - return server.getAnimalSpawnLimit(); - } - - return animalSpawn; - } - - @Override - public void setAnimalSpawnLimit(int limit) { - animalSpawn = limit; - } - - @Override - public int getWaterAnimalSpawnLimit() { - if (waterAnimalSpawn < 0) { - return server.getWaterAnimalSpawnLimit(); - } - - return waterAnimalSpawn; - } - - @Override - public void setWaterAnimalSpawnLimit(int limit) { - waterAnimalSpawn = limit; - } - - @Override - public int getAmbientSpawnLimit() { - if (ambientSpawn < 0) { - return server.getAmbientSpawnLimit(); - } - - return ambientSpawn; - } - - @Override - public void setAmbientSpawnLimit(int limit) { - ambientSpawn = limit; - } - - @Override - public void playSound(Location loc, Sound sound, float volume, float pitch) { - playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); - } - - @Override - public void playSound(Location loc, String sound, float volume, float pitch) { - playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); - } - - @Override - public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (loc == null || sound == null || category == null) return; - - double x = loc.getX(); - double y = loc.getY(); - double z = loc.getZ(); - - getHandle().playSound(null, x, y, z, CraftSound.getSoundEffect(CraftSound.getSound(sound)), SoundCategory.valueOf(category.name()), volume, pitch); - } - - @Override - public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (loc == null || sound == null || category == null) return; - - double x = loc.getX(); - double y = loc.getY(); - double z = loc.getZ(); - - PacketPlayOutCustomSoundEffect packet = new PacketPlayOutCustomSoundEffect(new MinecraftKey(sound), SoundCategory.valueOf(category.name()), new Vec3D(x, y, z), volume, pitch); - world.getMinecraftServer().getPlayerList().sendPacketNearby(null, x, y, z, volume > 1.0F ? 16.0F * volume : 16.0D, this.world, packet); // Paper - this.world.dimension -> this.world - } - - private static Map> gamerules; - public static synchronized Map> getGameRulesNMS() { - if (gamerules != null) { - return gamerules; - } - - Map> gamerules = new HashMap<>(); - GameRules.a(new GameRules.GameRuleVisitor() { - @Override - public > void a(GameRules.GameRuleKey gamerules_gamerulekey, GameRules.GameRuleDefinition gamerules_gameruledefinition) { - gamerules.put(gamerules_gamerulekey.a(), gamerules_gamerulekey); - } - }); - - return CraftWorld.gamerules = gamerules; - } - - private static Map> gameruleDefinitions; - public static synchronized Map> getGameRuleDefinitions() { - if (gameruleDefinitions != null) { - return gameruleDefinitions; - } - - Map> gameruleDefinitions = new HashMap<>(); - GameRules.a(new GameRules.GameRuleVisitor() { - @Override - public > void a(GameRules.GameRuleKey gamerules_gamerulekey, GameRules.GameRuleDefinition gamerules_gameruledefinition) { - gameruleDefinitions.put(gamerules_gamerulekey.a(), gamerules_gameruledefinition); - } - }); - - return CraftWorld.gameruleDefinitions = gameruleDefinitions; - } - - @Override - public String getGameRuleValue(String rule) { - // In method contract for some reason - if (rule == null) { - return null; - } - - GameRules.GameRuleValue value = getHandle().getGameRules().get(getGameRulesNMS().get(rule)); - return value != null ? value.toString() : ""; - } - - @Override - public boolean setGameRuleValue(String rule, String value) { - // No null values allowed - if (rule == null || value == null) return false; - - if (!isGameRule(rule)) return false; - - GameRules.GameRuleValue handle = getHandle().getGameRules().get(getGameRulesNMS().get(rule)); - handle.setValue(value); - handle.onChange(getHandle().getMinecraftServer()); - return true; - } - - @Override - public String[] getGameRules() { - return getGameRulesNMS().keySet().toArray(new String[getGameRulesNMS().size()]); - } - - @Override - public boolean isGameRule(String rule) { - Validate.isTrue(rule != null && !rule.isEmpty(), "Rule cannot be null nor empty"); - return getGameRulesNMS().containsKey(rule); - } - - @Override - public T getGameRuleValue(GameRule rule) { - Validate.notNull(rule, "GameRule cannot be null"); - return convert(rule, getHandle().getGameRules().get(getGameRulesNMS().get(rule.getName()))); - } - - @Override - public T getGameRuleDefault(GameRule rule) { - Validate.notNull(rule, "GameRule cannot be null"); - return convert(rule, getGameRuleDefinitions().get(rule.getName()).getValue()); - } - - @Override - public boolean setGameRule(GameRule rule, T newValue) { - Validate.notNull(rule, "GameRule cannot be null"); - Validate.notNull(newValue, "GameRule value cannot be null"); - - if (!isGameRule(rule.getName())) return false; - - GameRules.GameRuleValue handle = getHandle().getGameRules().get(getGameRulesNMS().get(rule.getName())); - handle.setValue(newValue.toString()); - handle.onChange(getHandle().getMinecraftServer()); - return true; - } - - private T convert(GameRule rule, GameRules.GameRuleValue value) { - if (value == null) { - return null; - } - - if (value instanceof GameRules.GameRuleBoolean) { - return rule.getType().cast(((GameRules.GameRuleBoolean) value).a()); - } else if (value instanceof GameRules.GameRuleInt) { - return rule.getType().cast(value.getIntValue()); - } else { - throw new IllegalArgumentException("Invalid GameRule type (" + value + ") for GameRule " + rule.getName()); - } - } - - @Override - public WorldBorder getWorldBorder() { - if (this.worldBorder == null) { - this.worldBorder = new CraftWorldBorder(this); - } - - return this.worldBorder; - } - - @Override - public void spawnParticle(Particle particle, Location location, int count) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count) { - spawnParticle(particle, x, y, z, count, null); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, T data) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, data); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) { - spawnParticle(particle, x, y, z, count, 0, 0, 0, data); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) { - spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, null); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, data); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) { - spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, 1, data); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) { - spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, null); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data, false); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data, force); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - // Paper start - Particle API Expansion - spawnParticle(particle, null, null, x, y, z, count, offsetX, offsetY, offsetZ, extra, data, force); - } - public void spawnParticle(Particle particle, List receivers, Player sender, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - // Paper end - if (data != null && !particle.getDataType().isInstance(data)) { - throw new IllegalArgumentException("data should be " + particle.getDataType() + " got " + data.getClass()); - } - getHandle().sendParticles( - receivers == null ? getHandle().players : receivers.stream().map(player -> ((CraftPlayer) player).getHandle()).collect(java.util.stream.Collectors.toList()), // Paper - Particle API Expansion - sender != null ? ((CraftPlayer) sender).getHandle() : null, // Sender // Paper - Particle API Expansion - CraftParticle.toNMS(particle, data), // Particle - x, y, z, // Position - count, // Count - offsetX, offsetY, offsetZ, // Random offset - extra, // Speed? - force - ); - - } - - @Override - public Location locateNearestStructure(Location origin, StructureType structureType, int radius, boolean findUnexplored) { - BlockPosition originPos = new BlockPosition(origin.getX(), origin.getY(), origin.getZ()); - BlockPosition nearest = getHandle().getChunkProvider().getChunkGenerator().findNearestMapFeature(getHandle(), structureType.getName(), originPos, radius, findUnexplored); - return (nearest == null) ? null : new Location(this, nearest.getX(), nearest.getY(), nearest.getZ()); - } - - @Override - public Raid locateNearestRaid(Location location, int radius) { - Validate.notNull(location, "Location cannot be null"); - Validate.isTrue(radius >= 0, "Radius cannot be negative"); - - PersistentRaid persistentRaid = world.C(); // PAIL rename getPersistentRaid - net.minecraft.server.Raid raid = persistentRaid.a(new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()), radius * radius); // PAIL rename getNearbyRaid - return (raid == null) ? null : new CraftRaid(raid); - } - - @Override - public List getRaids() { - PersistentRaid persistentRaid = world.C(); // PAIL rename getPersistentRaid - return persistentRaid.a.values().stream().map(CraftRaid::new).collect(Collectors.toList()); - } - - // Paper start - @Override - public CompletableFuture getChunkAtAsync(int x, int z, boolean gen) { - if (Bukkit.isPrimaryThread()) { - net.minecraft.server.Chunk immediate = this.world.getChunkProvider().getChunkAtIfLoadedImmediately(x, z); - if (immediate != null) { - return CompletableFuture.completedFuture(immediate.bukkitChunk); - } - } - - CompletableFuture ret = new CompletableFuture<>(); - this.world.getChunkProvider().getChunkAtAsynchronously(x, z, gen, (net.minecraft.server.Chunk chunk) -> { - ret.complete(chunk == null ? null : chunk.bukkitChunk); - }); - - return ret; - } - // Paper end - - // Spigot start - @Override - public int getViewDistance() { - return world.spigotConfig.viewDistance; - } - // Spigot end - - // Spigot start - private final Spigot spigot = new Spigot() - { - - @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 ); - } - }; - - public Spigot spigot() - { - return spigot; - } - // Spigot end -} diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java b/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java deleted file mode 100644 index 044d46ac8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.bukkit.craftbukkit; - -import com.google.common.base.Preconditions; -import net.minecraft.server.BlockPosition; -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); - } - - @Override - public boolean isInside(Location location) { - Preconditions.checkArgument(location != null, "location"); - - return location.getWorld().equals(this.world) && this.handle.a(new BlockPosition(location.getX(), location.getY(), location.getZ())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/LoggerOutputStream.java b/src/main/java/org/bukkit/craftbukkit/LoggerOutputStream.java deleted file mode 100644 index 93526ab60..000000000 --- a/src/main/java/org/bukkit/craftbukkit/LoggerOutputStream.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit.craftbukkit; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Logger; - -public class LoggerOutputStream extends ByteArrayOutputStream { - private final String separator = System.getProperty("line.separator"); - private final Logger logger; - private final Level level; - - public LoggerOutputStream(Logger logger, Level level) { - super(); - this.logger = logger; - this.level = level; - } - - @Override - public void flush() throws IOException { - synchronized (this) { - super.flush(); - String record = this.toString(); - super.reset(); - - if ((record.length() > 0) && (!record.equals(separator))) { - logger.log(level, record); - } - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/Main.java b/src/main/java/org/bukkit/craftbukkit/Main.java deleted file mode 100644 index 008fb8444..000000000 --- a/src/main/java/org/bukkit/craftbukkit/Main.java +++ /dev/null @@ -1,253 +0,0 @@ -package org.bukkit.craftbukkit; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; -import joptsimple.OptionParser; -import joptsimple.OptionSet; -import net.minecraft.server.MinecraftServer; -import net.minecrell.terminalconsole.TerminalConsoleAppender; // Paper - -public class Main { - public static boolean useJline = true; - public static boolean useConsole = true; - - public static void main(String[] args) { - // Todo: Installation script - 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("forceUpgrade"), "Whether to force a world upgrade"); - acceptsAll(asList("eraseCache"), "Whether to force cache erase during world upgrade"); - - 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 - - // Paper Start - acceptsAll(asList("paper", "paper-settings"), "File for paper settings") - .withRequiredArg() - .ofType(File.class) - .defaultsTo(new File("paper.yml")) - .describedAs("Yml file"); - // Paper end - - // Paper start - acceptsAll(asList("server-name"), "Name of the server") - .withRequiredArg() - .ofType(String.class) - .defaultsTo("Unknown Server") - .describedAs("Name"); - // Paper end - } - }; - - OptionSet options = null; - - try { - options = parser.parse(args); - } catch (joptsimple.OptionException ex) { - Logger.getLogger(Main.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage()); - } - - 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; - } - - float javaVersion = Float.parseFloat(System.getProperty("java.class.version")); - if (javaVersion > 57.0) { - System.err.println("Unsupported Java detected (" + javaVersion + "). Only up to Java 13 is supported."); - return; - } - - try { - // Paper start - Handled by TerminalConsoleAppender - /* - // This trick bypasses Maven Shade's clever rewriting of our getProperty call when using String literals - String jline_UnsupportedTerminal = new String(new char[] {'j','l','i','n','e','.','U','n','s','u','p','p','o','r','t','e','d','T','e','r','m','i','n','a','l'}); - String jline_terminal = new String(new char[] {'j','l','i','n','e','.','t','e','r','m','i','n','a','l'}); - - useJline = !(jline_UnsupportedTerminal).equals(System.getProperty(jline_terminal)); - - if (options.has("nojline")) { - System.setProperty("user.language", "en"); - useJline = false; - } - - if (useJline) { - AnsiConsole.systemInstall(); - } else { - // This ensures the terminal literal will always match the jline implementation - System.setProperty(jline.TerminalFactory.JLINE_TERMINAL, jline.UnsupportedTerminal.class.getName()); - } - */ - - if (options.has("nojline")) { - System.setProperty(TerminalConsoleAppender.JLINE_OVERRIDE_PROPERTY, "false"); - useJline = false; - } - // Paper end - - if (options.has("noconsole")) { - useConsole = false; - useJline = false; // Paper - System.setProperty(TerminalConsoleAppender.JLINE_OVERRIDE_PROPERTY, "false"); // Paper - } - - if (Main.class.getPackage().getImplementationVendor() != null && System.getProperty("IReallyKnowWhatIAmDoingISwear") == null) { - Date buildDate = new SimpleDateFormat("yyyyMMdd-HHmm").parse(Main.class.getPackage().getImplementationVendor()); - - Calendar deadline = Calendar.getInstance(); - deadline.add(Calendar.DAY_OF_YEAR, -21); - if (buildDate.before(deadline.getTime())) { - // Paper start - This is some stupid bullshit - System.err.println("*** Warning, you've not updated in a while! ***"); - System.err.println("*** Please download a new build as per instructions from https://papermc.io/downloads ***"); // Paper - //System.err.println("*** Server will start in 20 seconds ***"); - //Thread.sleep(TimeUnit.SECONDS.toMillis(20)); - // Paper End - } - } - - // Paper start - Log Java and OS versioning to help with debugging plugin issues - java.lang.management.RuntimeMXBean runtimeMX = java.lang.management.ManagementFactory.getRuntimeMXBean(); - java.lang.management.OperatingSystemMXBean osMX = java.lang.management.ManagementFactory.getOperatingSystemMXBean(); - if (runtimeMX != null && osMX != null) { - String javaInfo = "Java " + runtimeMX.getSpecVersion() + " (" + runtimeMX.getVmName() + " " + runtimeMX.getVmVersion() + ")"; - String osInfo = "Host: " + osMX.getName() + " " + osMX.getVersion() + " (" + osMX.getArch() + ")"; - - System.out.println("System Info: " + javaInfo + " " + osInfo); - } else { - System.out.println("Unable to read system info"); - } - // Paper end - System.setProperty( "library.jansi.version", "Paper" ); // 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); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/Overridden.java b/src/main/java/org/bukkit/craftbukkit/Overridden.java deleted file mode 100644 index 1c19c69f8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/Overridden.java +++ /dev/null @@ -1,14 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancement.java b/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancement.java deleted file mode 100644 index a5aadf285..000000000 --- a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancement.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.advancement; - -import java.util.Collection; -import java.util.Collections; -import net.minecraft.server.Advancement; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; - -public class CraftAdvancement implements org.bukkit.advancement.Advancement { - - private final Advancement handle; - - public CraftAdvancement(Advancement handle) { - this.handle = handle; - } - - public Advancement getHandle() { - return handle; - } - - @Override - public NamespacedKey getKey() { - return CraftNamespacedKey.fromMinecraft(handle.getName()); - } - - @Override - public Collection getCriteria() { - return Collections.unmodifiableCollection(handle.getCriteria().keySet()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementProgress.java b/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementProgress.java deleted file mode 100644 index 60fc5aff8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/advancement/CraftAdvancementProgress.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.bukkit.craftbukkit.advancement; - -import com.google.common.collect.Lists; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import net.minecraft.server.AdvancementDataPlayer; -import net.minecraft.server.CriterionProgress; -import org.bukkit.advancement.Advancement; -import org.bukkit.advancement.AdvancementProgress; - -public class CraftAdvancementProgress implements AdvancementProgress { - - private final CraftAdvancement advancement; - private final AdvancementDataPlayer playerData; - private final net.minecraft.server.AdvancementProgress handle; - - public CraftAdvancementProgress(CraftAdvancement advancement, AdvancementDataPlayer player, net.minecraft.server.AdvancementProgress handle) { - this.advancement = advancement; - this.playerData = player; - this.handle = handle; - } - - @Override - public Advancement getAdvancement() { - return advancement; - } - - @Override - public boolean isDone() { - return handle.isDone(); - } - - @Override - public boolean awardCriteria(String criteria) { - return playerData.grantCriteria(advancement.getHandle(), criteria); - } - - @Override - public boolean revokeCriteria(String criteria) { - return playerData.revokeCritera(advancement.getHandle(), criteria); - } - - @Override - public Date getDateAwarded(String criteria) { - CriterionProgress criterion = handle.getCriterionProgress(criteria); - return (criterion == null) ? null : criterion.getDate(); - } - - @Override - public Collection getRemainingCriteria() { - return Collections.unmodifiableCollection(Lists.newArrayList(handle.getRemainingCriteria())); - } - - @Override - public Collection getAwardedCriteria() { - return Collections.unmodifiableCollection(Lists.newArrayList(handle.getAwardedCriteria())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeInstance.java b/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeInstance.java deleted file mode 100644 index f9da97c07..000000000 --- a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeInstance.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.bukkit.craftbukkit.attribute; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeInstance; -import org.bukkit.attribute.AttributeModifier; - -public class CraftAttributeInstance implements AttributeInstance { - - private final net.minecraft.server.AttributeInstance handle; - private final Attribute attribute; - - public CraftAttributeInstance(net.minecraft.server.AttributeInstance handle, Attribute attribute) { - this.handle = handle; - this.attribute = attribute; - } - - @Override - public Attribute getAttribute() { - return attribute; - } - - @Override - public double getBaseValue() { - return handle.getBaseValue(); - } - - @Override - public void setBaseValue(double d) { - handle.setValue(d); - } - - @Override - public Collection getModifiers() { - List result = new ArrayList(); - for (net.minecraft.server.AttributeModifier nms : handle.getModifiers()) { - result.add(convert(nms)); - } - - return result; - } - - @Override - public void addModifier(AttributeModifier modifier) { - Preconditions.checkArgument(modifier != null, "modifier"); - handle.addModifier(convert(modifier)); - } - - @Override - public void removeModifier(AttributeModifier modifier) { - Preconditions.checkArgument(modifier != null, "modifier"); - handle.removeModifier(convert(modifier)); - } - - @Override - public double getValue() { - return handle.getValue(); - } - - @Override - public double getDefaultValue() { - return handle.getAttribute().getDefault(); - } - - public static net.minecraft.server.AttributeModifier convert(AttributeModifier bukkit) { - return new net.minecraft.server.AttributeModifier(bukkit.getUniqueId(), bukkit.getName(), bukkit.getAmount(), net.minecraft.server.AttributeModifier.Operation.values()[bukkit.getOperation().ordinal()]); - } - - public static AttributeModifier convert(net.minecraft.server.AttributeModifier nms) { - return new AttributeModifier(nms.getUniqueId(), nms.getName(), nms.getAmount(), AttributeModifier.Operation.values()[nms.getOperation().ordinal()]); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeMap.java b/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeMap.java deleted file mode 100644 index 77e584b12..000000000 --- a/src/main/java/org/bukkit/craftbukkit/attribute/CraftAttributeMap.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bukkit.craftbukkit.attribute; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Preconditions; -import java.util.Locale; -import net.minecraft.server.AttributeMapBase; -import org.apache.commons.lang3.EnumUtils; -import org.bukkit.attribute.Attributable; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeInstance; - -public class CraftAttributeMap implements Attributable { - - private final AttributeMapBase handle; - - public CraftAttributeMap(AttributeMapBase handle) { - this.handle = handle; - } - - @Override - public AttributeInstance getAttribute(Attribute attribute) { - Preconditions.checkArgument(attribute != null, "attribute"); - net.minecraft.server.AttributeInstance nms = handle.a(toMinecraft(attribute.name())); - - return (nms == null) ? null : new CraftAttributeInstance(nms, attribute); - } - - public static String toMinecraft(String bukkit) { - int first = bukkit.indexOf('_'); - int second = bukkit.indexOf('_', first + 1); - - StringBuilder sb = new StringBuilder(bukkit.toLowerCase(java.util.Locale.ENGLISH)); - - sb.setCharAt(first, '.'); - if (second != -1) { - sb.deleteCharAt(second); - sb.setCharAt(second, bukkit.charAt(second + 1)); - } - - return sb.toString(); - } - - public static String toMinecraft(Attribute attribute) { - return toMinecraft(attribute.name()); - } - - public static Attribute fromMinecraft(String nms) { - String[] split = nms.split("\\.", 2); - - String generic = split[0]; - String descriptor = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, split[1]); // movementSpeed -> MOVEMENT_SPEED - String fin = generic + "_" + descriptor; - return EnumUtils.getEnum(Attribute.class, fin.toUpperCase(Locale.ROOT)); // so we can return null without throwing exceptions - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java deleted file mode 100644 index 754205636..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.List; -import net.minecraft.server.BlockBannerAbstract; -import net.minecraft.server.EnumColor; -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; - -public class CraftBanner extends CraftBlockEntityState implements Banner { - - private DyeColor base; - private List patterns; - - public CraftBanner(final Block block) { - super(block, TileEntityBanner.class); - } - - public CraftBanner(final Material material, final TileEntityBanner te) { - super(material, te); - } - - @Override - public void load(TileEntityBanner banner) { - super.load(banner); - - base = DyeColor.getByWoolData((byte) ((BlockBannerAbstract) this.data.getBlock()).getColor().getColorIndex()); - patterns = new ArrayList(); - - if (banner.patterns != null) { - for (int i = 0; i < banner.patterns.size(); i++) { - NBTTagCompound p = (NBTTagCompound) banner.patterns.get(i); - patterns.add(new Pattern(DyeColor.getByWoolData((byte) p.getInt("Color")), PatternType.getByIdentifier(p.getString("Pattern")))); - } - } - } - - @Override - public DyeColor getBaseColor() { - return this.base; - } - - @Override - public void setBaseColor(DyeColor color) { - Preconditions.checkArgument(color != null, "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 void applyTo(TileEntityBanner banner) { - super.applyTo(banner); - - banner.color = EnumColor.fromColorIndex(base.getWoolData()); - - NBTTagList newPatterns = new NBTTagList(); - - for (Pattern p : patterns) { - NBTTagCompound compound = new NBTTagCompound(); - compound.setInt("Color", p.getColor().getWoolData()); - compound.setString("Pattern", p.getPattern().getIdentifier()); - newPatterns.add(compound); - } - banner.patterns = newPatterns; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBarrel.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBarrel.java deleted file mode 100644 index cb5ac0f09..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBarrel.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityBarrel; -import org.bukkit.Material; -import org.bukkit.block.Barrel; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.inventory.CraftInventory; -import org.bukkit.inventory.Inventory; - -public class CraftBarrel extends CraftLootable implements Barrel { - - public CraftBarrel(Block block) { - super(block, TileEntityBarrel.class); - } - - public CraftBarrel(Material material, TileEntityBarrel te) { - super(material, te); - } - - @Override - public Inventory getSnapshotInventory() { - return new CraftInventory(this.getSnapshot()); - } - - @Override - public Inventory getInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventory(this.getTileEntity()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java deleted file mode 100644 index 21ebceafb..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import java.util.ArrayList; -import java.util.Collection; -import net.minecraft.server.ChestLock; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.MobEffectList; -import net.minecraft.server.TileEntity; -import net.minecraft.server.TileEntityBeacon; -import org.bukkit.Material; -import org.bukkit.block.Beacon; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -public class CraftBeacon extends CraftBlockEntityState implements Beacon { - - public CraftBeacon(final Block block) { - super(block, TileEntityBeacon.class); - } - - public CraftBeacon(final Material material, final TileEntityBeacon te) { - super(material, te); - } - - @Override - public Collection getEntitiesInRange() { - TileEntity tileEntity = this.getTileEntityFromWorld(); - if (tileEntity instanceof TileEntityBeacon) { - TileEntityBeacon beacon = (TileEntityBeacon) tileEntity; - - Collection nms = beacon.getHumansInRange(); - Collection bukkit = new ArrayList(nms.size()); - - for (EntityHuman human : nms) { - bukkit.add(human.getBukkitEntity()); - } - - return bukkit; - } - - // block is no longer a beacon - return new ArrayList(); - } - - @Override - public int getTier() { - return this.getSnapshot().levels; - } - - @Override - public PotionEffect getPrimaryEffect() { - return this.getSnapshot().getPrimaryEffect(); - } - - @Override - public void setPrimaryEffect(PotionEffectType effect) { - this.getSnapshot().primaryEffect = (effect != null) ? MobEffectList.fromId(effect.getId()) : null; - } - - @Override - public PotionEffect getSecondaryEffect() { - return this.getSnapshot().getSecondaryEffect(); - } - - @Override - public void setSecondaryEffect(PotionEffectType effect) { - this.getSnapshot().secondaryEffect = (effect != null) ? MobEffectList.fromId(effect.getId()) : null; - } - - @Override - public String getCustomName() { - TileEntityBeacon beacon = this.getSnapshot(); - return beacon.customName != null ? CraftChatMessage.fromComponent(beacon.customName) : null; - } - - @Override - public void setCustomName(String name) { - this.getSnapshot().setCustomName(CraftChatMessage.fromStringOrNull(name)); - } - - @Override - public boolean isLocked() { - return !this.getSnapshot().chestLock.key.isEmpty(); - } - - @Override - public String getLock() { - return this.getSnapshot().chestLock.key; - } - - @Override - public void setLock(String key) { - this.getSnapshot().chestLock = (key == null) ? ChestLock.a : new ChestLock(key); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBed.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBed.java deleted file mode 100644 index 100ed8a8f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBed.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityBed; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.block.Bed; -import org.bukkit.block.Block; - -public class CraftBed extends CraftBlockEntityState implements Bed { - - public CraftBed(Block block) { - super(block, TileEntityBed.class); - } - - public CraftBed(Material material, TileEntityBed te) { - super(material, te); - } - - @Override - public DyeColor getColor() { - switch (getType()) { - case BLACK_BED: - return DyeColor.BLACK; - case BLUE_BED: - return DyeColor.BLUE; - case BROWN_BED: - return DyeColor.BROWN; - case CYAN_BED: - return DyeColor.CYAN; - case GRAY_BED: - return DyeColor.GRAY; - case GREEN_BED: - return DyeColor.GREEN; - case LIGHT_BLUE_BED: - return DyeColor.LIGHT_BLUE; - case LIGHT_GRAY_BED: - return DyeColor.LIGHT_GRAY; - case LIME_BED: - return DyeColor.LIME; - case MAGENTA_BED: - return DyeColor.MAGENTA; - case ORANGE_BED: - return DyeColor.ORANGE; - case PINK_BED: - return DyeColor.PINK; - case PURPLE_BED: - return DyeColor.PURPLE; - case RED_BED: - return DyeColor.RED; - case WHITE_BED: - return DyeColor.WHITE; - case YELLOW_BED: - return DyeColor.YELLOW; - default: - throw new IllegalArgumentException("Unknown DyeColor for " + getType()); - } - } - - @Override - public void setColor(DyeColor color) { - throw new UnsupportedOperationException("Must set block type to appropriate bed colour"); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBell.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBell.java deleted file mode 100644 index bf5d0c3a1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBell.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityBell; -import org.bukkit.Material; -import org.bukkit.block.Block; - -public class CraftBell extends CraftBlockEntityState { - - public CraftBell(Block block) { - super(block, TileEntityBell.class); - } - - public CraftBell(Material material, TileEntityBell te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlastFurnace.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlastFurnace.java deleted file mode 100644 index 6a6a89848..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlastFurnace.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityBlastFurnace; -import org.bukkit.Material; -import org.bukkit.block.BlastFurnace; -import org.bukkit.block.Block; - -public class CraftBlastFurnace extends CraftFurnace implements BlastFurnace { - - public CraftBlastFurnace(Block block) { - super(block, TileEntityBlastFurnace.class); - } - - public CraftBlastFurnace(Material material, TileEntityBlastFurnace te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java deleted file mode 100644 index fc65cef63..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java +++ /dev/null @@ -1,699 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import com.google.common.base.Preconditions; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; -import net.minecraft.server.AxisAlignedBB; -import net.minecraft.server.BiomeBase; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.BlockRedstoneWire; -import net.minecraft.server.BlockTileEntity; -import net.minecraft.server.Blocks; -import net.minecraft.server.EnumDirection; -import net.minecraft.server.EnumSkyBlock; -import net.minecraft.server.GeneratorAccess; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.MovingObjectPosition; -import net.minecraft.server.RayTrace; -import net.minecraft.server.TileEntity; -import net.minecraft.server.Vec3D; -import net.minecraft.server.VoxelShape; -import net.minecraft.server.WorldServer; -import org.apache.commons.lang.Validate; -import org.bukkit.Chunk; -import org.bukkit.FluidCollisionMode; -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.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.block.PistonMoveReaction; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.CraftFluidCollisionMode; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftRayTraceResult; -import org.bukkit.inventory.ItemStack; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.plugin.Plugin; -import org.bukkit.util.BlockVector; -import org.bukkit.util.BoundingBox; -import org.bukkit.util.RayTraceResult; -import org.bukkit.util.Vector; - -public class CraftBlock implements Block { - private final net.minecraft.server.GeneratorAccess world; - private final BlockPosition position; - - public CraftBlock(GeneratorAccess world, BlockPosition position) { - this.world = world; - this.position = position.immutableCopy(); - } - - public static CraftBlock at(GeneratorAccess world, BlockPosition position) { - return new CraftBlock(world, position); - } - - private net.minecraft.server.Block getNMSBlock() { - return getNMS().getBlock(); - } - - public net.minecraft.server.IBlockData getNMS() { - return world.getType(position); - } - - public BlockPosition getPosition() { - return position; - } - - @Override - public World getWorld() { - return world.getMinecraftWorld().getWorld(); - } - - public CraftWorld getCraftWorld() { - return (CraftWorld) getWorld(); - } - - @Override - public Location getLocation() { - return new Location(getWorld(), position.getX(), position.getY(), position.getZ()); - } - - @Override - public Location getLocation(Location loc) { - if (loc != null) { - loc.setWorld(getWorld()); - loc.setX(position.getX()); - loc.setY(position.getY()); - loc.setZ(position.getZ()); - loc.setYaw(0); - loc.setPitch(0); - } - - return loc; - } - - public BlockVector getVector() { - return new BlockVector(getX(), getY(), getZ()); - } - - @Override - public int getX() { - return position.getX(); - } - - @Override - public int getY() { - return position.getY(); - } - - @Override - public int getZ() { - return position.getZ(); - } - - @Override - public Chunk getChunk() { - return getWorld().getChunkAt(this); - } - - 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) { - world.setTypeAndData(position, CraftMagicNumbers.getBlock(getType(), data), flag); - } - - private IBlockData getData0() { - return world.getType(position); - } - - @Override - public byte getData() { - IBlockData blockData = world.getType(position); - return CraftMagicNumbers.toLegacyData(blockData); - } - - @Override - public BlockData getBlockData() { - return CraftBlockData.fromData(getData0()); - } - - @Override - public void setType(final Material type) { - setType(type, true); - } - - @Override - public void setType(Material type, boolean applyPhysics) { - Preconditions.checkArgument(type != null, "Material cannot be null"); - setBlockData(type.createBlockData(), applyPhysics); - } - - @Override - public void setBlockData(BlockData data) { - setBlockData(data, true); - } - - @Override - public void setBlockData(BlockData data, boolean applyPhysics) { - Preconditions.checkArgument(data != null, "BlockData cannot be null"); - setTypeAndData(((CraftBlockData) data).getState(), applyPhysics); - } - - public boolean setTypeAndData(final IBlockData blockData, final boolean applyPhysics) { - // SPIGOT-611: need to do this to prevent glitchiness. Easier to handle this here (like /setblock) than to fix weirdness in tile entity cleanup - if (!blockData.isAir() && blockData.getBlock() instanceof BlockTileEntity && blockData.getBlock() != getNMSBlock()) { - // SPIGOT-4612: faster - just clear tile - if (world instanceof net.minecraft.server.World) { - ((net.minecraft.server.World) world).removeTileEntity(position); - } else { - world.setTypeAndData(position, Blocks.AIR.getBlockData(), 0); - } - } - - if (applyPhysics) { - return world.setTypeAndData(position, blockData, 3); - } else { - IBlockData old = world.getType(position); - boolean success = world.setTypeAndData(position, blockData, 2 | 16 | 1024); // NOTIFY | NO_OBSERVER | NO_PLACE (custom) - if (success) { - world.getMinecraftWorld().notify( - position, - old, - blockData, - 3 - ); - } - return success; - } - } - - @Override - public Material getType() { - return CraftMagicNumbers.getMaterial(world.getType(position).getBlock()); - } - - @Override - public byte getLightLevel() { - return (byte) world.getMinecraftWorld().getLightLevel(position); - } - - @Override - public byte getLightFromSky() { - return (byte) world.getBrightness(EnumSkyBlock.SKY, position); - } - - @Override - public byte getLightFromBlocks() { - return (byte) world.getBrightness(EnumSkyBlock.BLOCK, position); - } - - - public Block getFace(final BlockFace face) { - return getRelative(face, 1); - } - - public Block getFace(final BlockFace face, final int distance) { - return getRelative(face, distance); - } - - @Override - public Block getRelative(final int modX, final int modY, final int modZ) { - return getWorld().getBlockAt(getX() + modX, getY() + modY, getZ() + modZ); - } - - @Override - public Block getRelative(BlockFace face) { - return getRelative(face, 1); - } - - @Override - public Block getRelative(BlockFace face, int distance) { - return getRelative(face.getModX() * distance, face.getModY() * distance, face.getModZ() * distance); - } - - @Override - 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{pos=" + position + ",type=" + getType() + ",data=" + getNMS() + ",fluid=" + world.getFluid(position) + '}'; - } - - 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; - } - } - - @Override - public BlockState getState() { - // Paper start - allow disabling the use of snapshots - return getState(true); - } - public BlockState getState(boolean useSnapshot) { - boolean prev = CraftBlockEntityState.DISABLE_SNAPSHOT; - CraftBlockEntityState.DISABLE_SNAPSHOT = !useSnapshot; - try { - return getState0(); - } finally { - CraftBlockEntityState.DISABLE_SNAPSHOT = prev; - } - } - public BlockState getState0() { - // Paper end - Material material = getType(); - - switch (material) { - case ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case OAK_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_SIGN: - case SPRUCE_WALL_SIGN: - return new CraftSign(this); - case CHEST: - case TRAPPED_CHEST: - return new CraftChest(this); - case FURNACE: - return new CraftFurnaceFurnace(this); - case DISPENSER: - return new CraftDispenser(this); - case DROPPER: - return new CraftDropper(this); - case END_GATEWAY: - return new CraftEndGateway(this); - case HOPPER: - return new CraftHopper(this); - case SPAWNER: - return new CraftCreatureSpawner(this); - case JUKEBOX: - return new CraftJukebox(this); - case BREWING_STAND: - return new CraftBrewingStand(this); - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return new CraftSkull(this); - case COMMAND_BLOCK: - case CHAIN_COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - return new CraftCommandBlock(this); - case BEACON: - return new CraftBeacon(this); - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - return new CraftBanner(this); - case STRUCTURE_BLOCK: - return new CraftStructureBlock(this); - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - return new CraftShulkerBox(this); - case ENCHANTING_TABLE: - return new CraftEnchantingTable(this); - case ENDER_CHEST: - return new CraftEnderChest(this); - case DAYLIGHT_DETECTOR: - return new CraftDaylightDetector(this); - case COMPARATOR: - return new CraftComparator(this); - case BLACK_BED: - case BLUE_BED: - case BROWN_BED: - case CYAN_BED: - case GRAY_BED: - case GREEN_BED: - case LIGHT_BLUE_BED: - case LIGHT_GRAY_BED: - case LIME_BED: - case MAGENTA_BED: - case ORANGE_BED: - case PINK_BED: - case PURPLE_BED: - case RED_BED: - case WHITE_BED: - case YELLOW_BED: - return new CraftBed(this); - case CONDUIT: - return new CraftConduit(this); - case BARREL: - return new CraftBarrel(this); - case BELL: - return new CraftBell(this); - case BLAST_FURNACE: - return new CraftBlastFurnace(this); - case CAMPFIRE: - return new CraftCampfire(this); - case JIGSAW: - return new CraftJigsaw(this); - case LECTERN: - return new CraftLectern(this); - case SMOKER: - return new CraftSmoker(this); - default: - TileEntity tileEntity = world.getTileEntity(position); - if (tileEntity != null) { - // block with unhandled TileEntity: - return new CraftBlockEntityState(this, (Class) tileEntity.getClass()); - } else { - // Block without TileEntity: - return new CraftBlockState(this); - } - } - } - - @Override - public Biome getBiome() { - return getWorld().getBiome(getX(), getZ()); - } - - @Override - public void setBiome(Biome bio) { - getWorld().setBiome(getX(), getZ(), bio); - } - - public static Biome biomeBaseToBiome(BiomeBase base) { - if (base == null) { - return null; - } - - return Biome.valueOf(IRegistry.BIOME.getKey(base).getKey().toUpperCase(java.util.Locale.ENGLISH)); - } - - public static BiomeBase biomeToBiomeBase(Biome bio) { - if (bio == null) { - return null; - } - - return IRegistry.BIOME.get(new MinecraftKey(bio.name().toLowerCase(java.util.Locale.ENGLISH))); - } - - @Override - public double getTemperature() { - return world.getBiome(position).getAdjustedTemperature(position); - } - - @Override - public double getHumidity() { - return getWorld().getHumidity(getX(), getZ()); - } - - @Override - public boolean isBlockPowered() { - return world.getMinecraftWorld().getBlockPower(position) > 0; - } - - @Override - public boolean isBlockIndirectlyPowered() { - return world.getMinecraftWorld().isBlockIndirectlyPowered(position); - } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof CraftBlock)) return false; - CraftBlock other = (CraftBlock) o; - - return this.position.equals(other.position) && this.getWorld().equals(other.getWorld()); - } - - @Override - public int hashCode() { - return this.position.hashCode() ^ this.getWorld().hashCode(); - } - - @Override - public boolean isBlockFacePowered(BlockFace face) { - return world.getMinecraftWorld().isBlockFacePowered(position, blockFaceToNotch(face)); - } - - @Override - public boolean isBlockFaceIndirectlyPowered(BlockFace face) { - int power = world.getMinecraftWorld().getBlockFacePower(position, blockFaceToNotch(face)); - - Block relative = getRelative(face); - if (relative.getType() == Material.REDSTONE_WIRE) { - return Math.max(power, relative.getData()) > 0; - } - - return power > 0; - } - - @Override - public int getBlockPower(BlockFace face) { - int power = 0; - BlockRedstoneWire wire = (BlockRedstoneWire) Blocks.REDSTONE_WIRE; - net.minecraft.server.World world = this.world.getMinecraftWorld(); - int x = getX(); - int y = getY(); - int z = getZ(); - if ((face == BlockFace.DOWN || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x, y - 1, z), EnumDirection.DOWN)) power = wire.getPower(power, world.getType(new BlockPosition(x, y - 1, z))); - if ((face == BlockFace.UP || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x, y + 1, z), EnumDirection.UP)) power = wire.getPower(power, world.getType(new BlockPosition(x, y + 1, z))); - if ((face == BlockFace.EAST || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x + 1, y, z), EnumDirection.EAST)) power = wire.getPower(power, world.getType(new BlockPosition(x + 1, y, z))); - if ((face == BlockFace.WEST || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x - 1, y, z), EnumDirection.WEST)) power = wire.getPower(power, world.getType(new BlockPosition(x - 1, y, z))); - if ((face == BlockFace.NORTH || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x, y, z - 1), EnumDirection.NORTH)) power = wire.getPower(power, world.getType(new BlockPosition(x, y, z - 1))); - if ((face == BlockFace.SOUTH || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x, y, z + 1), EnumDirection.SOUTH)) power = wire.getPower(power, world.getType(new BlockPosition(x, y, z + 1))); - return power > 0 ? power : (face == BlockFace.SELF ? isBlockIndirectlyPowered() : isBlockFaceIndirectlyPowered(face)) ? 15 : 0; - } - - @Override - public int getBlockPower() { - return getBlockPower(BlockFace.SELF); - } - - @Override - public boolean isEmpty() { - return getNMS().isAir(); - } - - @Override - public boolean isLiquid() { - return getNMS().getMaterial().isLiquid(); - } - - @Override - public PistonMoveReaction getPistonMoveReaction() { - return PistonMoveReaction.getById(getNMS().getPushReaction().ordinal()); - } - - @Override - public boolean breakNaturally() { - return breakNaturally(new ItemStack(Material.AIR)); - } - - @Override - public boolean breakNaturally(ItemStack item) { - // Order matters here, need to drop before setting to air so skulls can get their data - net.minecraft.server.Block block = this.getNMSBlock(); - boolean result = false; - - if (block != null && block != Blocks.AIR) { - net.minecraft.server.Block.dropItems(getNMS(), world.getMinecraftWorld(), position, world.getTileEntity(position), null, CraftItemStack.asNMSCopy(item)); - result = true; - } - - return setTypeAndData(Blocks.AIR.getBlockData(), true) && result; - } - - @Override - public Collection getDrops() { - return getDrops(new ItemStack(Material.AIR)); - } - - @Override - public Collection getDrops(ItemStack item) { - return net.minecraft.server.Block.getDrops(getNMS(), (WorldServer) world.getMinecraftWorld(), position, world.getTileEntity(position), null, CraftItemStack.asNMSCopy(item)) - .stream().map(CraftItemStack::asBukkitCopy).collect(Collectors.toList()); - } - - @Override - public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - getCraftWorld().getBlockMetadata().setMetadata(this, metadataKey, newMetadataValue); - } - - @Override - public List getMetadata(String metadataKey) { - return getCraftWorld().getBlockMetadata().getMetadata(this, metadataKey); - } - - @Override - public boolean hasMetadata(String metadataKey) { - return getCraftWorld().getBlockMetadata().hasMetadata(this, metadataKey); - } - - @Override - public void removeMetadata(String metadataKey, Plugin owningPlugin) { - getCraftWorld().getBlockMetadata().removeMetadata(this, metadataKey, owningPlugin); - } - - @Override - public boolean isPassable() { - return this.getData0().getCollisionShape(world, position).isEmpty(); - } - - @Override - public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) { - Validate.notNull(start, "Start location is null!"); - Validate.isTrue(this.getWorld().equals(start.getWorld()), "Start location is from different world!"); - start.checkFinite(); - - Validate.notNull(direction, "Direction is null!"); - direction.checkFinite(); - Validate.isTrue(direction.lengthSquared() > 0, "Direction's magnitude is 0!"); - - Validate.notNull(fluidCollisionMode, "Fluid collision mode is null!"); - if (maxDistance < 0.0D) { - return null; - } - - Vector dir = direction.clone().normalize().multiply(maxDistance); - Vec3D startPos = new Vec3D(start.getX(), start.getY(), start.getZ()); - Vec3D endPos = new Vec3D(start.getX() + dir.getX(), start.getY() + dir.getY(), start.getZ() + dir.getZ()); - - MovingObjectPosition nmsHitResult = world.rayTraceBlock(new RayTrace(startPos, endPos, RayTrace.BlockCollisionOption.OUTLINE, CraftFluidCollisionMode.toNMS(fluidCollisionMode), null), position); - return CraftRayTraceResult.fromNMS(this.getWorld(), nmsHitResult); - } - - @Override - public BoundingBox getBoundingBox() { - VoxelShape shape = getData0().getShape(world, position); - - if (shape.isEmpty()) { - return new BoundingBox(); // Return an empty bounding box if the block has no dimension - } - - AxisAlignedBB aabb = shape.getBoundingBox(); - return new BoundingBox(getX() + aabb.minX, getY() + aabb.minY, getZ() + aabb.minZ, getX() + aabb.maxX, getY() + aabb.maxY, getZ() + aabb.maxZ); - } - - // Paper start - @Override - public com.destroystokyo.paper.block.BlockSoundGroup getSoundGroup() { - return new com.destroystokyo.paper.block.CraftBlockSoundGroup(getNMSBlock().getBlockData().getStepSound()); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockEntityState.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockEntityState.java deleted file mode 100644 index 3e22d558e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockEntityState.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import com.google.common.base.Preconditions; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.TileEntity; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.TileState; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.persistence.PersistentDataContainer; - -public class CraftBlockEntityState extends CraftBlockState implements TileState { - - private final Class tileEntityClass; - private final T tileEntity; - private final T snapshot; - - public CraftBlockEntityState(Block block, Class tileEntityClass) { - super(block); - - try {// Paper - show location on failure - - this.tileEntityClass = tileEntityClass; - - // get tile entity from block: - CraftWorld world = (CraftWorld) this.getWorld(); - this.tileEntity = tileEntityClass.cast(world.getHandle().getTileEntity(this.getPosition())); - Preconditions.checkState(this.tileEntity != null, "Tile is null, asynchronous access? " + block); - - // Paper start - this.snapshotDisabled = DISABLE_SNAPSHOT; - if (DISABLE_SNAPSHOT) { - this.snapshot = this.tileEntity; - } else { - this.snapshot = this.createSnapshot(this.tileEntity); - } - // copy tile entity data: - if(this.snapshot != null) { - this.load(this.snapshot); - } - // Paper end - // Paper start - show location on failure - } catch (Throwable thr) { - if (thr instanceof ThreadDeath) { - throw (ThreadDeath)thr; - } - throw new RuntimeException("Failed to read BlockState at: world: " + block.getWorld().getName() + " location: (" + block.getX() + ", " + block.getY() + ", " + block.getZ() + ")", thr); - } - // Paper end - } - - public final boolean snapshotDisabled; // Paper - public static boolean DISABLE_SNAPSHOT = false; // Paper - - public CraftBlockEntityState(Material material, T tileEntity) { - super(material); - - this.tileEntityClass = (Class) tileEntity.getClass(); - this.tileEntity = tileEntity; - // Paper start - this.snapshotDisabled = DISABLE_SNAPSHOT; - if (DISABLE_SNAPSHOT) { - this.snapshot = this.tileEntity; - } else { - this.snapshot = this.createSnapshot(this.tileEntity); - } - // copy tile entity data: - if(this.snapshot != null) { - this.load(this.snapshot); - } - // Paper end - } - - private T createSnapshot(T tileEntity) { - if (tileEntity == null) { - return null; - } - - NBTTagCompound nbtTagCompound = tileEntity.save(new NBTTagCompound()); - T snapshot = (T) TileEntity.create(nbtTagCompound); - - return snapshot; - } - - // copies the TileEntity-specific data, retains the position - private void copyData(T from, T to) { - BlockPosition pos = to.getPosition(); - NBTTagCompound nbtTagCompound = from.save(new NBTTagCompound()); - to.load(nbtTagCompound); - - // reset the original position: - to.setPosition(pos); - } - - // gets the wrapped TileEntity - public T getTileEntity() { // Paper - protected -> public - return tileEntity; - } - - // gets the cloned TileEntity which is used to store the captured data - protected T getSnapshot() { - return snapshot; - } - - // gets the current TileEntity from the world at this position - protected TileEntity getTileEntityFromWorld() { - requirePlaced(); - - return ((CraftWorld) this.getWorld()).getHandle().getTileEntity(this.getPosition()); - } - - // gets the NBT data of the TileEntity represented by this block state - public NBTTagCompound getSnapshotNBT() { - // update snapshot - applyTo(snapshot); - - return snapshot.save(new NBTTagCompound()); - } - - // copies the data of the given tile entity to this block state - protected void load(T tileEntity) { - if (tileEntity != null && tileEntity != snapshot) { - copyData(tileEntity, snapshot); - } - } - - // applies the TileEntity data of this block state to the given TileEntity - protected void applyTo(T tileEntity) { - if (tileEntity != null && tileEntity != snapshot) { - copyData(snapshot, tileEntity); - } - } - - protected boolean isApplicable(TileEntity tileEntity) { - return tileEntityClass.isInstance(tileEntity); - } - - @Override - public boolean update(boolean force, boolean applyPhysics) { - boolean result = super.update(force, applyPhysics); - - if (result && this.isPlaced()) { - TileEntity tile = getTileEntityFromWorld(); - - if (isApplicable(tile)) { - applyTo(tileEntityClass.cast(tile)); - tile.update(); - } - } - - return result; - } - - @Override - public PersistentDataContainer getPersistentDataContainer() { - return this.getSnapshot().persistentDataContainer; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java deleted file mode 100644 index 0cb5582b1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java +++ /dev/null @@ -1,297 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import com.google.common.base.Preconditions; -import java.util.List; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.GeneratorAccess; -import net.minecraft.server.IBlockData; -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.data.BlockData; -import org.bukkit.craftbukkit.CraftChunk; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.material.Attachable; -import org.bukkit.material.MaterialData; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.plugin.Plugin; - -public class CraftBlockState implements BlockState { - private final CraftWorld world; - private final CraftChunk chunk; - private final BlockPosition position; - protected IBlockData data; - protected int flag; - - public CraftBlockState(final Block block) { - this.world = (CraftWorld) block.getWorld(); - this.position = ((CraftBlock) block).getPosition(); - this.data = ((CraftBlock) block).getNMS(); - this.chunk = (CraftChunk) block.getChunk(); - this.flag = 3; - } - - public CraftBlockState(final Block block, int flag) { - this(block); - this.flag = flag; - } - - public CraftBlockState(Material material) { - world = null; - data = CraftMagicNumbers.getBlock(material).getBlockData(); - chunk = null; - position = BlockPosition.ZERO; - } - - public static CraftBlockState getBlockState(GeneratorAccess world, net.minecraft.server.BlockPosition pos) { - return new CraftBlockState(CraftBlock.at(world, pos)); - } - - public static CraftBlockState getBlockState(net.minecraft.server.World world, net.minecraft.server.BlockPosition pos, int flag) { - return new CraftBlockState(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), flag); - } - - @Override - public World getWorld() { - requirePlaced(); - return world; - } - - @Override - public int getX() { - return position.getX(); - } - - @Override - public int getY() { - return position.getY(); - } - - @Override - public int getZ() { - return position.getZ(); - } - - @Override - public Chunk getChunk() { - requirePlaced(); - return chunk; - } - - public void setData(IBlockData data) { - this.data = data; - } - - public BlockPosition getPosition() { - return this.position; - } - - public IBlockData getHandle() { - return this.data; - } - - @Override - public BlockData getBlockData() { - return CraftBlockData.fromData(data); - } - - @Override - public void setBlockData(BlockData data) { - Preconditions.checkArgument(data != null, "BlockData cannot be null"); - this.data = ((CraftBlockData) data).getState(); - } - - @Override - public void setData(final MaterialData data) { - Material mat = CraftMagicNumbers.getMaterial(this.data).getItemType(); - - if ((mat == null) || (mat.getData() == null)) { - this.data = CraftMagicNumbers.getBlock(data); - } else { - if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) { - this.data = CraftMagicNumbers.getBlock(data); - } else { - throw new IllegalArgumentException("Provided data is not of type " - + mat.getData().getName() + ", found " + data.getClass().getName()); - } - } - } - - @Override - public MaterialData getData() { - return CraftMagicNumbers.getMaterial(data); - } - - @Override - public void setType(final Material type) { - Preconditions.checkArgument(type != null, "Material cannot be null"); - Preconditions.checkArgument(type.isBlock(), "Material must be a block!"); - - if (this.getType() != type) { - this.data = CraftMagicNumbers.getBlock(type).getBlockData(); - } - } - - @Override - public Material getType() { - return CraftMagicNumbers.getMaterial(data.getBlock()); - } - - public void setFlag(int flag) { - this.flag = flag; - } - - public int getFlag() { - return flag; - } - - @Override - public byte getLightLevel() { - return getBlock().getLightLevel(); - } - - @Override - public CraftBlock getBlock() { - requirePlaced(); - return CraftBlock.at(world.getHandle(), position); - } - - @Override - public boolean update() { - return update(false); - } - - @Override - public boolean update(boolean force) { - return update(force, true); - } - - @Override - public boolean update(boolean force, boolean applyPhysics) { - if (!isPlaced()) { - return true; - } - CraftBlock block = getBlock(); - - if (block.getType() != getType()) { - if (!force) { - return false; - } - } - - IBlockData newBlock = this.data; - block.setTypeAndData(newBlock, applyPhysics); - world.getHandle().notify( - position, - block.getNMS(), - newBlock, - 3 - ); - - // Update levers etc - if (false && applyPhysics && getData() instanceof Attachable) { // Call does not map to new API - world.getHandle().applyPhysics(position.shift(CraftBlock.blockFaceToNotch(((Attachable) getData()).getAttachedFace())), newBlock.getBlock()); - } - - return true; - } - - @Override - public byte getRawData() { - return CraftMagicNumbers.toLegacyData(data); - } - - @Override - public Location getLocation() { - return new Location(world, getX(), getY(), getZ()); - } - - @Override - public Location getLocation(Location loc) { - if (loc != null) { - loc.setWorld(world); - loc.setX(getX()); - loc.setY(getY()); - loc.setZ(getZ()); - loc.setYaw(0); - loc.setPitch(0); - } - - return loc; - } - - @Override - public void setRawData(byte data) { - this.data = CraftMagicNumbers.getBlock(getType(), data); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final CraftBlockState other = (CraftBlockState) obj; - if (this.world != other.world && (this.world == null || !this.world.equals(other.world))) { - return false; - } - if (this.position != other.position && (this.position == null || !this.position.equals(other.position))) { - return false; - } - if (this.data != other.data && (this.data == null || !this.data.equals(other.data))) { - return false; - } - return true; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 73 * hash + (this.world != null ? this.world.hashCode() : 0); - hash = 73 * hash + (this.position != null ? this.position.hashCode() : 0); - hash = 73 * hash + (this.data != null ? this.data.hashCode() : 0); - return hash; - } - - @Override - public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - requirePlaced(); - chunk.getCraftWorld().getBlockMetadata().setMetadata(getBlock(), metadataKey, newMetadataValue); - } - - @Override - public List getMetadata(String metadataKey) { - requirePlaced(); - return chunk.getCraftWorld().getBlockMetadata().getMetadata(getBlock(), metadataKey); - } - - @Override - public boolean hasMetadata(String metadataKey) { - requirePlaced(); - return chunk.getCraftWorld().getBlockMetadata().hasMetadata(getBlock(), metadataKey); - } - - @Override - 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"); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java deleted file mode 100644 index 37b6ad55c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java +++ /dev/null @@ -1,53 +0,0 @@ -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.inventory.CraftInventoryBrewer; -import org.bukkit.inventory.BrewerInventory; - -public class CraftBrewingStand extends CraftContainer implements BrewingStand { - - public CraftBrewingStand(Block block) { - super(block, TileEntityBrewingStand.class); - } - - public CraftBrewingStand(final Material material, final TileEntityBrewingStand te) { - super(material, te); - } - - @Override - public BrewerInventory getSnapshotInventory() { - return new CraftInventoryBrewer(this.getSnapshot()); - } - - @Override - public BrewerInventory getInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventoryBrewer(this.getTileEntity()); - } - - @Override - public int getBrewingTime() { - return this.getSnapshot().brewTime; - } - - @Override - public void setBrewingTime(int brewTime) { - this.getSnapshot().brewTime = brewTime; - } - - @Override - public int getFuelLevel() { - return this.getSnapshot().fuelLevel; - } - - @Override - public void setFuelLevel(int level) { - this.getSnapshot().fuelLevel = level; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCampfire.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCampfire.java deleted file mode 100644 index 95d10dd9f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftCampfire.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityCampfire; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Campfire; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.inventory.ItemStack; - -public class CraftCampfire extends CraftBlockEntityState implements Campfire { - - public CraftCampfire(Block block) { - super(block, TileEntityCampfire.class); - } - - public CraftCampfire(Material material, TileEntityCampfire te) { - super(material, te); - } - - @Override - public int getSize() { - return getSnapshot().getItems().size(); - } - - @Override - public ItemStack getItem(int index) { - net.minecraft.server.ItemStack item = getSnapshot().getItems().get(index); - return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); - } - - @Override - public void setItem(int index, ItemStack item) { - getSnapshot().getItems().set(index, CraftItemStack.asNMSCopy(item)); - } - - @Override - public int getCookTime(int index) { - return getSnapshot().cookingTimes[index]; - } - - @Override - public void setCookTime(int index, int cookTime) { - getSnapshot().cookingTimes[index] = cookTime; - } - - @Override - public int getCookTimeTotal(int index) { - return getSnapshot().cookingTotalTimes[index]; - } - - @Override - public void setCookTimeTotal(int index, int cookTimeTotal) { - getSnapshot().cookingTotalTimes[index] = cookTimeTotal; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java b/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java deleted file mode 100644 index 019fa7118..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.BlockChest; -import net.minecraft.server.Blocks; -import net.minecraft.server.ITileInventory; -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; -import com.destroystokyo.paper.loottable.PaperLootableBlockInventory; // Paper - -public class CraftChest extends CraftLootable implements Chest, PaperLootableBlockInventory { // Paper - - public CraftChest(final Block block) { - super(block, TileEntityChest.class); - } - - public CraftChest(final Material material, final TileEntityChest te) { - super(material, te); - } - - @Override - public Inventory getSnapshotInventory() { - return new CraftInventory(this.getSnapshot()); - } - - @Override - public Inventory getBlockInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventory(this.getTileEntity()); - } - - @Override - public Inventory getInventory() { - CraftInventory inventory = (CraftInventory) this.getBlockInventory(); - if (!isPlaced()) { - return inventory; - } - - // The logic here is basically identical to the logic in BlockChest.interact - CraftWorld world = (CraftWorld) this.getWorld(); - - BlockChest blockChest = (BlockChest) (this.getType() == Material.CHEST ? Blocks.CHEST : Blocks.TRAPPED_CHEST); - ITileInventory nms = blockChest.getInventory(data, world.getHandle(), this.getPosition()); - - if (nms instanceof BlockChest.DoubleInventory) { - inventory = new CraftInventoryDoubleChest((BlockChest.DoubleInventory) nms); - } - return inventory; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java deleted file mode 100644 index 5c9bfe951..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java +++ /dev/null @@ -1,57 +0,0 @@ -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.util.CraftChatMessage; - -public class CraftCommandBlock extends CraftBlockEntityState implements CommandBlock { - - private String command; - private String name; - - public CraftCommandBlock(Block block) { - super(block, TileEntityCommand.class); - } - - public CraftCommandBlock(final Material material, final TileEntityCommand te) { - super(material, te); - } - - @Override - public void load(TileEntityCommand commandBlock) { - super.load(commandBlock); - - command = commandBlock.getCommandBlock().getCommand(); - name = CraftChatMessage.fromComponent(commandBlock.getCommandBlock().getName()); - } - - @Override - public String getCommand() { - return command; - } - - @Override - public void setCommand(String command) { - this.command = command != null ? command : ""; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name != null ? name : "@"; - } - - @Override - public void applyTo(TileEntityCommand commandBlock) { - super.applyTo(commandBlock); - - commandBlock.getCommandBlock().setCommand(command); - commandBlock.getCommandBlock().setName(CraftChatMessage.fromStringOrNull(name)); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftComparator.java b/src/main/java/org/bukkit/craftbukkit/block/CraftComparator.java deleted file mode 100644 index 2e6a738ac..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftComparator.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityComparator; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Comparator; - -public class CraftComparator extends CraftBlockEntityState implements Comparator { - - public CraftComparator(final Block block) { - super(block, TileEntityComparator.class); - } - - public CraftComparator(final Material material, final TileEntityComparator te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftConduit.java b/src/main/java/org/bukkit/craftbukkit/block/CraftConduit.java deleted file mode 100644 index 5116a3765..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftConduit.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityConduit; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Conduit; - -public class CraftConduit extends CraftBlockEntityState implements Conduit { - - public CraftConduit(Block block) { - super(block, TileEntityConduit.class); - } - - public CraftConduit(Material material, TileEntityConduit te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java b/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java deleted file mode 100644 index 36ba813e5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.ChestLock; -import net.minecraft.server.TileEntityContainer; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Container; -import org.bukkit.craftbukkit.util.CraftChatMessage; - -public abstract class CraftContainer extends CraftBlockEntityState implements Container { - - public CraftContainer(Block block, Class tileEntityClass) { - super(block, tileEntityClass); - } - - public CraftContainer(final Material material, T tileEntity) { - super(material, tileEntity); - } - - @Override - public boolean isLocked() { - return !this.getSnapshot().chestLock.key.isEmpty(); - } - - @Override - public String getLock() { - return this.getSnapshot().chestLock.key; - } - - @Override - public void setLock(String key) { - this.getSnapshot().chestLock = (key == null) ? ChestLock.a : new ChestLock(key); - } - - @Override - public String getCustomName() { - T container = this.getSnapshot(); - return container.customName != null ? CraftChatMessage.fromComponent(container.getCustomName()) : null; - } - - @Override - public void setCustomName(String name) { - this.getSnapshot().setCustomName(CraftChatMessage.fromStringOrNull(name)); - } - - @Override - public void applyTo(T container) { - super.applyTo(container); - - if (this.getSnapshot().customName == null) { - container.setCustomName(null); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java deleted file mode 100644 index e78e3804b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import com.google.common.base.Preconditions; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.TileEntityMobSpawner; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.CreatureSpawner; -import org.bukkit.entity.EntityType; - -public class CraftCreatureSpawner extends CraftBlockEntityState implements CreatureSpawner { - - public CraftCreatureSpawner(final Block block) { - super(block, TileEntityMobSpawner.class); - } - - public CraftCreatureSpawner(final Material material, TileEntityMobSpawner te) { - super(material, te); - } - - @Override - public EntityType getSpawnedType() { - MinecraftKey key = this.getSnapshot().getSpawner().getMobName(); - return (key == null) ? EntityType.PIG : EntityType.fromName(key.getKey()); - } - - @Override - public void setSpawnedType(EntityType entityType) { - if (entityType == null || entityType.getName() == null) { - throw new IllegalArgumentException("Can't spawn EntityType " + entityType + " from mobspawners!"); - } - - this.getSnapshot().getSpawner().setMobName(EntityTypes.a(entityType.getName()).get()); - } - - @Override - public String getCreatureTypeName() { - return this.getSnapshot().getSpawner().getMobName().getKey(); - } - - @Override - public void setCreatureTypeByName(String creatureType) { - // Verify input - EntityType type = EntityType.fromName(creatureType); - if (type == null) { - return; - } - setSpawnedType(type); - } - - @Override - public int getDelay() { - return this.getSnapshot().getSpawner().spawnDelay; - } - - @Override - public void setDelay(int delay) { - this.getSnapshot().getSpawner().spawnDelay = delay; - } - - @Override - public int getMinSpawnDelay() { - return this.getSnapshot().getSpawner().minSpawnDelay; - } - - @Override - public void setMinSpawnDelay(int spawnDelay) { - Preconditions.checkArgument(spawnDelay <= getMaxSpawnDelay(), "Minimum Spawn Delay must be less than or equal to Maximum Spawn Delay"); - this.getSnapshot().getSpawner().minSpawnDelay = spawnDelay; - } - - @Override - public int getMaxSpawnDelay() { - return this.getSnapshot().getSpawner().maxSpawnDelay; - } - - @Override - public void setMaxSpawnDelay(int spawnDelay) { - Preconditions.checkArgument(spawnDelay > 0, "Maximum Spawn Delay must be greater than 0."); - Preconditions.checkArgument(spawnDelay >= getMinSpawnDelay(), "Maximum Spawn Delay must be greater than or equal to Minimum Spawn Delay"); - this.getSnapshot().getSpawner().maxSpawnDelay = spawnDelay; - } - - @Override - public int getMaxNearbyEntities() { - return this.getSnapshot().getSpawner().maxNearbyEntities; - } - - @Override - public void setMaxNearbyEntities(int maxNearbyEntities) { - this.getSnapshot().getSpawner().maxNearbyEntities = maxNearbyEntities; - } - - @Override - public int getSpawnCount() { - return this.getSnapshot().getSpawner().spawnCount; - } - - @Override - public void setSpawnCount(int count) { - this.getSnapshot().getSpawner().spawnCount = count; - } - - @Override - public int getRequiredPlayerRange() { - return this.getSnapshot().getSpawner().requiredPlayerRange; - } - - @Override - public void setRequiredPlayerRange(int requiredPlayerRange) { - this.getSnapshot().getSpawner().requiredPlayerRange = requiredPlayerRange; - } - - @Override - public int getSpawnRange() { - return this.getSnapshot().getSpawner().spawnRange; - } - - @Override - public void setSpawnRange(int spawnRange) { - this.getSnapshot().getSpawner().spawnRange = spawnRange; - } - - // Paper start - @Override - public boolean isActivated() { - return this.getSnapshot().getSpawner().isActivated(); - } - - @Override - public void resetTimer() { - this.getSnapshot().getSpawner().resetTimer(); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftDaylightDetector.java b/src/main/java/org/bukkit/craftbukkit/block/CraftDaylightDetector.java deleted file mode 100644 index 1c9b84c69..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftDaylightDetector.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityLightDetector; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.DaylightDetector; - -public class CraftDaylightDetector extends CraftBlockEntityState implements DaylightDetector { - - public CraftDaylightDetector(final Block block) { - super(block, TileEntityLightDetector.class); - } - - public CraftDaylightDetector(final Material material, final TileEntityLightDetector te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java b/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java deleted file mode 100644 index ab31963f7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.BlockDispenser; -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 CraftLootable implements Dispenser { - - public CraftDispenser(final Block block) { - super(block, TileEntityDispenser.class); - } - - public CraftDispenser(final Material material, final TileEntityDispenser te) { - super(material, te); - } - - @Override - public Inventory getSnapshotInventory() { - return new CraftInventory(this.getSnapshot()); - } - - @Override - public Inventory getInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventory(this.getTileEntity()); - } - - @Override - public BlockProjectileSource getBlockProjectileSource() { - Block block = getBlock(); - - if (block.getType() != Material.DISPENSER) { - return null; - } - - return new CraftBlockProjectileSource((TileEntityDispenser) this.getTileEntityFromWorld()); - } - - @Override - public boolean dispense() { - Block block = getBlock(); - - if (block.getType() == Material.DISPENSER) { - CraftWorld world = (CraftWorld) this.getWorld(); - BlockDispenser dispense = (BlockDispenser) Blocks.DISPENSER; - - dispense.dispense(world.getHandle(), this.getPosition()); - return true; - } else { - return false; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java b/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java deleted file mode 100644 index 12d65bf6c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.BlockDropper; -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 CraftLootable implements Dropper { - - public CraftDropper(final Block block) { - super(block, TileEntityDropper.class); - } - - public CraftDropper(final Material material, TileEntityDropper te) { - super(material, te); - } - - @Override - public Inventory getSnapshotInventory() { - return new CraftInventory(this.getSnapshot()); - } - - @Override - public Inventory getInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventory(this.getTileEntity()); - } - - @Override - public void drop() { - Block block = getBlock(); - - if (block.getType() == Material.DROPPER) { - CraftWorld world = (CraftWorld) this.getWorld(); - BlockDropper drop = (BlockDropper) Blocks.DROPPER; - - drop.dispense(world.getHandle(), this.getPosition()); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java b/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java deleted file mode 100644 index 3a782294c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityEnchantTable; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.EnchantingTable; -import org.bukkit.craftbukkit.util.CraftChatMessage; - -public class CraftEnchantingTable extends CraftBlockEntityState implements EnchantingTable { - - public CraftEnchantingTable(final Block block) { - super(block, TileEntityEnchantTable.class); - } - - public CraftEnchantingTable(final Material material, final TileEntityEnchantTable te) { - super(material, te); - } - - @Override - public String getCustomName() { - TileEntityEnchantTable enchant = this.getSnapshot(); - return enchant.hasCustomName() ? CraftChatMessage.fromComponent(enchant.getCustomName()) : null; - } - - @Override - public void setCustomName(String name) { - this.getSnapshot().setCustomName(CraftChatMessage.fromStringOrNull(name)); - } - - @Override - public void applyTo(TileEntityEnchantTable enchantingTable) { - super.applyTo(enchantingTable); - - if (!this.getSnapshot().hasCustomName()) { - enchantingTable.setCustomName(null); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftEndGateway.java b/src/main/java/org/bukkit/craftbukkit/block/CraftEndGateway.java deleted file mode 100644 index 54287744e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftEndGateway.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import java.util.Objects; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.TileEntityEndGateway; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.EndGateway; - -public class CraftEndGateway extends CraftBlockEntityState implements EndGateway { - - public CraftEndGateway(Block block) { - super(block, TileEntityEndGateway.class); - } - - public CraftEndGateway(final Material material, TileEntityEndGateway te) { - super(material, te); - } - - @Override - public Location getExitLocation() { - BlockPosition pos = this.getSnapshot().exitPortal; - return pos == null ? null : new Location(this.isPlaced() ? this.getWorld() : null, pos.getX(), pos.getY(), pos.getZ()); - } - - @Override - public void setExitLocation(Location location) { - if (location == null) { - this.getSnapshot().exitPortal = null; - } else if (!Objects.equals(location.getWorld(), this.isPlaced() ? this.getWorld() : null)) { - throw new IllegalArgumentException("Cannot set exit location to different world"); - } else { - this.getSnapshot().exitPortal = new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - } - - @Override - public boolean isExactTeleport() { - return this.getSnapshot().exactTeleport; - } - - @Override - public void setExactTeleport(boolean exact) { - this.getSnapshot().exactTeleport = exact; - } - - @Override - public long getAge() { - return this.getSnapshot().age; - } - - @Override - public void setAge(long age) { - this.getSnapshot().age = age; - } - - @Override - public void applyTo(TileEntityEndGateway endGateway) { - super.applyTo(endGateway); - - if (this.getSnapshot().exitPortal == null) { - endGateway.exitPortal = null; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftEnderChest.java b/src/main/java/org/bukkit/craftbukkit/block/CraftEnderChest.java deleted file mode 100644 index 2004ee2f3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftEnderChest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityEnderChest; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.EnderChest; - -public class CraftEnderChest extends CraftBlockEntityState implements EnderChest { - - public CraftEnderChest(final Block block) { - super(block, TileEntityEnderChest.class); - } - - public CraftEnderChest(final Material material, final TileEntityEnderChest te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java b/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java deleted file mode 100644 index 1ce10ea04..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.BlockFurnace; -import net.minecraft.server.TileEntityFurnace; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Furnace; -import org.bukkit.craftbukkit.inventory.CraftInventoryFurnace; -import org.bukkit.inventory.FurnaceInventory; - -public class CraftFurnace extends CraftContainer implements Furnace { - - public CraftFurnace(Block block, Class tileEntityClass) { - super(block, tileEntityClass); - } - - public CraftFurnace(final Material material, final T te) { - super(material, te); - } - - @Override - public FurnaceInventory getSnapshotInventory() { - return new CraftInventoryFurnace(this.getSnapshot()); - } - - @Override - public FurnaceInventory getInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventoryFurnace(this.getTileEntity()); - } - - @Override - public short getBurnTime() { - return (short) this.getSnapshot().burnTime; - } - - @Override - public void setBurnTime(short burnTime) { - this.getSnapshot().burnTime = burnTime; - // SPIGOT-844: Allow lighting and relighting using this API - this.data = this.data.set(BlockFurnace.LIT, burnTime > 0); - } - - @Override - public short getCookTime() { - return (short) this.getSnapshot().cookTime; - } - - @Override - public void setCookTime(short cookTime) { - this.getSnapshot().cookTime = cookTime; - } - - @Override - public int getCookTimeTotal() { - return this.getSnapshot().cookTimeTotal; - } - - @Override - public void setCookTimeTotal(int cookTimeTotal) { - this.getSnapshot().cookTimeTotal = cookTimeTotal; - } - - // Paper start - cook speed multiplier API - @Override - public double getCookSpeedMultiplier() { - return this.getSnapshot().cookSpeedMultiplier; - } - - @Override - public void setCookSpeedMultiplier(double multiplier) { - com.google.common.base.Preconditions.checkArgument(multiplier >= 0, "Furnace speed multiplier cannot be negative"); - com.google.common.base.Preconditions.checkArgument(multiplier <= 200, "Furnace speed multiplier cannot more than 200"); - this.getSnapshot().cookSpeedMultiplier = multiplier; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftFurnaceFurnace.java b/src/main/java/org/bukkit/craftbukkit/block/CraftFurnaceFurnace.java deleted file mode 100644 index fd8b91c1b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftFurnaceFurnace.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityFurnaceFurnace; -import org.bukkit.Material; -import org.bukkit.block.Block; - -public class CraftFurnaceFurnace extends CraftFurnace { - - public CraftFurnaceFurnace(Block block) { - super(block, TileEntityFurnaceFurnace.class); - } - - public CraftFurnaceFurnace(Material material, TileEntityFurnaceFurnace te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java b/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java deleted file mode 100644 index 6566554ab..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java +++ /dev/null @@ -1,33 +0,0 @@ -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.inventory.CraftInventory; -import org.bukkit.inventory.Inventory; - -public class CraftHopper extends CraftLootable implements Hopper { - - public CraftHopper(final Block block) { - super(block, TileEntityHopper.class); - } - - public CraftHopper(final Material material, final TileEntityHopper te) { - super(material, te); - } - - @Override - public Inventory getSnapshotInventory() { - return new CraftInventory(this.getSnapshot()); - } - - @Override - public Inventory getInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventory(this.getTileEntity()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftJigsaw.java b/src/main/java/org/bukkit/craftbukkit/block/CraftJigsaw.java deleted file mode 100644 index bbce44c48..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftJigsaw.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityJigsaw; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Jigsaw; - -public class CraftJigsaw extends CraftBlockEntityState implements Jigsaw { - - public CraftJigsaw(Block block) { - super(block, TileEntityJigsaw.class); - } - - public CraftJigsaw(Material material, TileEntityJigsaw te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java b/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java deleted file mode 100644 index b527cf98c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.BlockJukeBox; -import net.minecraft.server.Blocks; -import net.minecraft.server.ItemStack; -import net.minecraft.server.TileEntity; -import net.minecraft.server.TileEntityJukeBox; -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.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; - -public class CraftJukebox extends CraftBlockEntityState implements Jukebox { - - public CraftJukebox(final Block block) { - super(block, TileEntityJukeBox.class); - } - - public CraftJukebox(final Material material, TileEntityJukeBox te) { - super(material, te); - } - - @Override - public boolean update(boolean force, boolean applyPhysics) { - boolean result = super.update(force, applyPhysics); - - if (result && this.isPlaced() && this.getType() == Material.JUKEBOX) { - CraftWorld world = (CraftWorld) this.getWorld(); - Material record = this.getPlaying(); - if (record == Material.AIR) { - world.getHandle().setTypeAndData(this.getPosition(), Blocks.JUKEBOX.getBlockData().set(BlockJukeBox.HAS_RECORD, false), 3); - } else { - world.getHandle().setTypeAndData(this.getPosition(), Blocks.JUKEBOX.getBlockData().set(BlockJukeBox.HAS_RECORD, true), 3); - } - world.playEffect(this.getLocation(), Effect.RECORD_PLAY, record); - } - - return result; - } - - @Override - public Material getPlaying() { - return getRecord().getType(); - } - - @Override - public void setPlaying(Material record) { - if (record == null || CraftMagicNumbers.getItem(record) == null) { - record = Material.AIR; - } - - setRecord(new org.bukkit.inventory.ItemStack(record)); - } - - @Override - public org.bukkit.inventory.ItemStack getRecord() { - ItemStack record = this.getSnapshot().getRecord(); - return CraftItemStack.asBukkitCopy(record); - } - - @Override - public void setRecord(org.bukkit.inventory.ItemStack record) { - ItemStack nms = CraftItemStack.asNMSCopy(record); - this.getSnapshot().setRecord(nms); - if (nms.isEmpty()) { - this.data = this.data.set(BlockJukeBox.HAS_RECORD, false); - } else { - this.data = this.data.set(BlockJukeBox.HAS_RECORD, true); - } - } - - @Override - public boolean isPlaying() { - return getHandle().get(BlockJukeBox.HAS_RECORD); - } - - @Override - public boolean eject() { - requirePlaced(); - TileEntity tileEntity = this.getTileEntityFromWorld(); - if (!(tileEntity instanceof TileEntityJukeBox)) return false; - - TileEntityJukeBox jukebox = (TileEntityJukeBox) tileEntity; - boolean result = !jukebox.getRecord().isEmpty(); - CraftWorld world = (CraftWorld) this.getWorld(); - ((BlockJukeBox) Blocks.JUKEBOX).dropRecord(world.getHandle(), getPosition()); - return result; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftLectern.java b/src/main/java/org/bukkit/craftbukkit/block/CraftLectern.java deleted file mode 100644 index bb57b750b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftLectern.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntityLectern; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Lectern; -import org.bukkit.craftbukkit.inventory.CraftInventoryLectern; -import org.bukkit.inventory.Inventory; - -public class CraftLectern extends CraftBlockEntityState implements Lectern { - - public CraftLectern(Block block) { - super(block, TileEntityLectern.class); - } - - public CraftLectern(Material material, TileEntityLectern te) { - super(material, te); - } - - @Override - public int getPage() { - return getSnapshot().getPage(); - } - - @Override - public void setPage(int page) { - getSnapshot().setPage(page); - } - - @Override - public Inventory getSnapshotInventory() { - return new CraftInventoryLectern(this.getSnapshot().inventory); - } - - @Override - public Inventory getInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventoryLectern(this.getTileEntity().inventory); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftLootable.java b/src/main/java/org/bukkit/craftbukkit/block/CraftLootable.java deleted file mode 100644 index 678aa09d4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftLootable.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import com.destroystokyo.paper.loottable.PaperLootableBlockInventory; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.TileEntityLootable; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.Nameable; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.loot.LootTable; -import org.bukkit.loot.Lootable; - -public abstract class CraftLootable extends CraftContainer implements Nameable, Lootable, PaperLootableBlockInventory { // Paper - - public CraftLootable(Block block, Class tileEntityClass) { - super(block, tileEntityClass); - } - - public CraftLootable(Material material, T tileEntity) { - super(material, tileEntity); - } - - @Override - public void applyTo(T lootable) { - super.applyTo(lootable); - - if (this.getSnapshot().lootTable == null) { - lootable.setLootTable((MinecraftKey) null, 0L); - } - } - - @Override - public LootTable getLootTable() { - if (getSnapshot().lootTable == null) { - return null; - } - - MinecraftKey key = getSnapshot().lootTable; - return Bukkit.getLootTable(CraftNamespacedKey.fromMinecraft(key)); - } - - @Override - public void setLootTable(LootTable table) { - setLootTable(table, getSeed()); - } - - @Override - public long getSeed() { - return getSnapshot().lootTableSeed; - } - - @Override - public void setSeed(long seed) { - setLootTable(getLootTable(), seed); - } - - public void setLootTable(LootTable table, long seed) { // Paper - public - MinecraftKey key = (table == null) ? null : CraftNamespacedKey.toMinecraft(table.getKey()); - getSnapshot().setLootTable(key, seed); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftShulkerBox.java b/src/main/java/org/bukkit/craftbukkit/block/CraftShulkerBox.java deleted file mode 100644 index c029a1244..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftShulkerBox.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.BlockShulkerBox; -import net.minecraft.server.TileEntityShulkerBox; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.ShulkerBox; -import org.bukkit.craftbukkit.inventory.CraftInventory; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.Inventory; - -public class CraftShulkerBox extends CraftLootable implements ShulkerBox { - - public CraftShulkerBox(final Block block) { - super(block, TileEntityShulkerBox.class); - } - - public CraftShulkerBox(final Material material, final TileEntityShulkerBox te) { - super(material, te); - } - - @Override - public Inventory getSnapshotInventory() { - return new CraftInventory(this.getSnapshot()); - } - - @Override - public Inventory getInventory() { - if (!this.isPlaced()) { - return this.getSnapshotInventory(); - } - - return new CraftInventory(this.getTileEntity()); - } - - @Override - public DyeColor getColor() { - net.minecraft.server.Block block = CraftMagicNumbers.getBlock(this.getType()); - - return DyeColor.getByWoolData((byte) ((BlockShulkerBox) block).color.getColorIndex()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java deleted file mode 100644 index af15656cc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.EnumColor; -import net.minecraft.server.IChatBaseComponent; -import net.minecraft.server.TileEntitySign; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; -import org.bukkit.craftbukkit.util.CraftChatMessage; - -public class CraftSign extends CraftBlockEntityState implements Sign { - - private String[] lines; - private boolean editable; - - public CraftSign(final Block block) { - super(block, TileEntitySign.class); - if (lines == null) { lines = new String[]{"", "", "", ""}; } // Paper - } - - public CraftSign(final Material material, final TileEntitySign te) { - super(material, te); - if (lines == null) { lines = new String[]{"", "", "", ""}; } // Paper - } - - @Override - public void load(TileEntitySign sign) { - super.load(sign); - - lines = new String[sign.lines.length]; - System.arraycopy(revertComponents(sign.lines), 0, lines, 0, lines.length); - editable = sign.isEditable; - } - - @Override - public String[] getLines() { - return lines; - } - - @Override - public String getLine(int index) throws IndexOutOfBoundsException { - return lines[index]; - } - - @Override - public void setLine(int index, String line) throws IndexOutOfBoundsException { - lines[index] = line; - } - - @Override - public boolean isEditable() { - return this.editable; - } - - @Override - public void setEditable(boolean editable) { - this.editable = editable; - } - - @Override - public DyeColor getColor() { - return DyeColor.getByWoolData((byte) getSnapshot().getColor().getColorIndex()); - } - - @Override - public void setColor(DyeColor color) { - getSnapshot().setColor(EnumColor.fromColorIndex(color.getWoolData())); - } - - @Override - public void applyTo(TileEntitySign sign) { - super.applyTo(sign); - - IChatBaseComponent[] newLines = sanitizeLines(lines); - System.arraycopy(newLines, 0, sign.lines, 0, 4); - sign.isEditable = editable; - } - - 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); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java deleted file mode 100644 index 2dd2f476f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java +++ /dev/null @@ -1,181 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import com.destroystokyo.paper.profile.CraftPlayerProfile; -import com.destroystokyo.paper.profile.PlayerProfile; -import com.google.common.base.Preconditions; -import com.mojang.authlib.GameProfile; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.TileEntitySkull; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.SkullType; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.Skull; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Rotatable; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import javax.annotation.Nullable; - -public class CraftSkull extends CraftBlockEntityState implements Skull { - - private static final int MAX_OWNER_LENGTH = 16; - private GameProfile profile; - - public CraftSkull(final Block block) { - super(block, TileEntitySkull.class); - } - - public CraftSkull(final Material material, final TileEntitySkull te) { - super(material, te); - } - - @Override - public void load(TileEntitySkull skull) { - super.load(skull); - - profile = skull.gameProfile; - } - - 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; - case DRAGON: - return 5; - } - } - - @Override - public boolean hasOwner() { - return profile != null; - } - - @Override - public String getOwner() { - return hasOwner() ? profile.getName() : null; - } - - @Override - 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; - } - - this.profile = profile; - return true; - } - - @Override - public OfflinePlayer getOwningPlayer() { - if (profile != null) { - if (profile.getId() != null) { - return Bukkit.getOfflinePlayer(profile.getId()); - } - - if (profile.getName() != null) { - return Bukkit.getOfflinePlayer(profile.getName()); - } - } - - return null; - } - - @Override - public void setOwningPlayer(OfflinePlayer player) { - Preconditions.checkNotNull(player, "player"); - - if (player instanceof CraftPlayer) { - this.profile = ((CraftPlayer) player).getProfile(); - } else { - this.profile = new GameProfile(player.getUniqueId(), player.getName()); - } - } - - // Paper start - @Override - public void setPlayerProfile(PlayerProfile profile) { - Preconditions.checkNotNull(profile, "profile"); - this.profile = CraftPlayerProfile.asAuthlibCopy(profile); - } - - @Nullable - @Override - public PlayerProfile getPlayerProfile() { - return profile != null ? CraftPlayerProfile.asBukkitCopy(profile) : null; - } - // Paper end - - @Override - public BlockFace getRotation() { - BlockData blockData = getBlockData(); - return (blockData instanceof Rotatable) ? ((Rotatable) blockData).getRotation() : ((Directional) blockData).getFacing(); - } - - @Override - public void setRotation(BlockFace rotation) { - BlockData blockData = getBlockData(); - if (blockData instanceof Rotatable) { - ((Rotatable) blockData).setRotation(rotation); - } else { - ((Directional) blockData).setFacing(rotation); - } - setBlockData(blockData); - } - - @Override - public SkullType getSkullType() { - switch (getType()) { - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - return SkullType.SKELETON; - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - return SkullType.WITHER; - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return SkullType.ZOMBIE; - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - return SkullType.PLAYER; - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - return SkullType.CREEPER; - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - return SkullType.DRAGON; - default: - throw new IllegalArgumentException("Unknown SkullType for " + getType()); - } - } - - @Override - public void setSkullType(SkullType skullType) { - throw new UnsupportedOperationException("Must change block type"); - } - - @Override - public void applyTo(TileEntitySkull skull) { - super.applyTo(skull); - - if (getSkullType() == SkullType.PLAYER) { - skull.setGameProfile(profile); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSmoker.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSmoker.java deleted file mode 100644 index 40bfcad46..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftSmoker.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import net.minecraft.server.TileEntitySmoker; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Smoker; - -public class CraftSmoker extends CraftFurnace implements Smoker { - - public CraftSmoker(Block block) { - super(block, TileEntitySmoker.class); - } - - public CraftSmoker(Material material, TileEntitySmoker te) { - super(material, te); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java b/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java deleted file mode 100644 index 86095fbe7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java +++ /dev/null @@ -1,187 +0,0 @@ -package org.bukkit.craftbukkit.block; - -import com.google.common.base.Preconditions; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.BlockPropertyStructureMode; -import net.minecraft.server.EnumBlockMirror; -import net.minecraft.server.EnumBlockRotation; -import net.minecraft.server.TileEntityStructure; -import org.apache.commons.lang3.Validate; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Structure; -import org.bukkit.block.structure.Mirror; -import org.bukkit.block.structure.StructureRotation; -import org.bukkit.block.structure.UsageMode; -import org.bukkit.craftbukkit.entity.CraftLivingEntity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.util.BlockVector; - -public class CraftStructureBlock extends CraftBlockEntityState implements Structure { - - private static final int MAX_SIZE = 32; - - public CraftStructureBlock(Block block) { - super(block, TileEntityStructure.class); - } - - public CraftStructureBlock(Material material, TileEntityStructure structure) { - super(material, structure); - } - - @Override - public String getStructureName() { - return getSnapshot().getStructureName(); - } - - @Override - public void setStructureName(String name) { - Preconditions.checkArgument(name != null, "Structure Name cannot be null"); - getSnapshot().setStructureName(name); - } - - @Override - public String getAuthor() { - return getSnapshot().author; - } - - @Override - public void setAuthor(String author) { - Preconditions.checkArgument(author != null && !author.isEmpty(), "Author name cannot be null nor empty"); - getSnapshot().author = author; - } - - @Override - public void setAuthor(LivingEntity entity) { - Preconditions.checkArgument(entity != null, "Structure Block author entity cannot be null"); - getSnapshot().setAuthor(((CraftLivingEntity) entity).getHandle()); - } - - @Override - public BlockVector getRelativePosition() { - return new BlockVector(getSnapshot().relativePosition.getX(), getSnapshot().relativePosition.getY(), getSnapshot().relativePosition.getZ()); - } - - @Override - public void setRelativePosition(BlockVector vector) { - Validate.isTrue(isBetween(vector.getBlockX(), -MAX_SIZE, MAX_SIZE), "Structure Size (X) must be between -" + MAX_SIZE + " and " + MAX_SIZE); - Validate.isTrue(isBetween(vector.getBlockY(), -MAX_SIZE, MAX_SIZE), "Structure Size (Y) must be between -" + MAX_SIZE + " and " + MAX_SIZE); - Validate.isTrue(isBetween(vector.getBlockZ(), -MAX_SIZE, MAX_SIZE), "Structure Size (Z) must be between -" + MAX_SIZE + " and " + MAX_SIZE); - getSnapshot().relativePosition = new BlockPosition(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); - } - - @Override - public BlockVector getStructureSize() { - return new BlockVector(getSnapshot().size.getX(), getSnapshot().size.getY(), getSnapshot().size.getZ()); - } - - @Override - public void setStructureSize(BlockVector vector) { - Validate.isTrue(isBetween(vector.getBlockX(), 0, MAX_SIZE), "Structure Size (X) must be between 0 and " + MAX_SIZE); - Validate.isTrue(isBetween(vector.getBlockY(), 0, MAX_SIZE), "Structure Size (Y) must be between 0 and " + MAX_SIZE); - Validate.isTrue(isBetween(vector.getBlockZ(), 0, MAX_SIZE), "Structure Size (Z) must be between 0 and " + MAX_SIZE); - getSnapshot().size = new BlockPosition(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); - } - - @Override - public void setMirror(Mirror mirror) { - getSnapshot().mirror = EnumBlockMirror.valueOf(mirror.name()); - } - - @Override - public Mirror getMirror() { - return Mirror.valueOf(getSnapshot().mirror.name()); - } - - @Override - public void setRotation(StructureRotation rotation) { - getSnapshot().rotation = EnumBlockRotation.valueOf(rotation.name()); - } - - @Override - public StructureRotation getRotation() { - return StructureRotation.valueOf(getSnapshot().rotation.name()); - } - - @Override - public void setUsageMode(UsageMode mode) { - getSnapshot().setUsageMode(BlockPropertyStructureMode.valueOf(mode.name())); - } - - @Override - public UsageMode getUsageMode() { - return UsageMode.valueOf(getSnapshot().getUsageMode().name()); - } - - @Override - public void setIgnoreEntities(boolean flag) { - getSnapshot().ignoreEntities = flag; - } - - @Override - public boolean isIgnoreEntities() { - return getSnapshot().ignoreEntities; - } - - @Override - public void setShowAir(boolean showAir) { - getSnapshot().showAir = showAir; - } - - @Override - public boolean isShowAir() { - return getSnapshot().showAir; - } - - @Override - public void setBoundingBoxVisible(boolean showBoundingBox) { - getSnapshot().showBoundingBox = showBoundingBox; - } - - @Override - public boolean isBoundingBoxVisible() { - return getSnapshot().showBoundingBox; - } - - @Override - public void setIntegrity(float integrity) { - Validate.isTrue(isBetween(integrity, 0.0f, 1.0f), "Integrity must be between 0.0f and 1.0f"); - getSnapshot().integrity = integrity; - } - - @Override - public float getIntegrity() { - return getSnapshot().integrity; - } - - @Override - public void setSeed(long seed) { - getSnapshot().seed = seed; - } - - @Override - public long getSeed() { - return getSnapshot().seed; - } - - @Override - public void setMetadata(String metadata) { - Validate.notNull(metadata, "Structure metadata cannot be null"); - if (getUsageMode() == UsageMode.DATA) { - getSnapshot().metadata = metadata; - } - } - - @Override - public String getMetadata() { - return getSnapshot().metadata; - } - - private static boolean isBetween(int num, int min, int max) { - return num >= min && num <= max; - } - - private static boolean isBetween(float num, float min, float max) { - return num >= min && num <= max; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAgeable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAgeable.java deleted file mode 100644 index e311e66bd..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAgeable.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Ageable; - -public abstract class CraftAgeable extends CraftBlockData implements Ageable { - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger("age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAnaloguePowerable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAnaloguePowerable.java deleted file mode 100644 index 60a247ced..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAnaloguePowerable.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.AnaloguePowerable; - -public abstract class CraftAnaloguePowerable extends CraftBlockData implements AnaloguePowerable { - - private static final net.minecraft.server.BlockStateInteger POWER = getInteger("power"); - - @Override - public int getPower() { - return get(POWER); - } - - @Override - public void setPower(int power) { - set(POWER, power); - } - - @Override - public int getMaximumPower() { - return getMax(POWER); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAttachable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftAttachable.java deleted file mode 100644 index 657cf0734..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftAttachable.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Attachable; - -public abstract class CraftAttachable extends CraftBlockData implements Attachable { - - private static final net.minecraft.server.BlockStateBoolean ATTACHED = getBoolean("attached"); - - @Override - public boolean isAttached() { - return get(ATTACHED); - } - - @Override - public void setAttached(boolean attached) { - set(ATTACHED, attached); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBisected.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftBisected.java deleted file mode 100644 index 969b670ea..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBisected.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Bisected; - -public class CraftBisected extends CraftBlockData implements Bisected { - - private static final net.minecraft.server.BlockStateEnum HALF = getEnum("half"); - - @Override - public Half getHalf() { - return get(HALF, Half.class); - } - - @Override - public void setHalf(Half half) { - set(HALF, half); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBlockData.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftBlockData.java deleted file mode 100644 index 839e645b6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftBlockData.java +++ /dev/null @@ -1,564 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.ImmutableSet; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; -import net.minecraft.server.ArgumentBlock; -import net.minecraft.server.Block; -import net.minecraft.server.BlockDataAbstract; -import net.minecraft.server.BlockStateBoolean; -import net.minecraft.server.BlockStateEnum; -import net.minecraft.server.BlockStateInteger; -import net.minecraft.server.EnumDirection; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IBlockState; -import net.minecraft.server.INamable; -import net.minecraft.server.IRegistry; -import net.minecraft.server.NBTTagCompound; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; - -public class CraftBlockData implements BlockData { - - private IBlockData state; - private Map, Comparable> parsedStates; - - protected CraftBlockData() { - throw new AssertionError("Template Constructor"); - } - - protected CraftBlockData(IBlockData state) { - this.state = state; - } - - @Override - public Material getMaterial() { - return CraftMagicNumbers.getMaterial(state.getBlock()); - } - - public IBlockData getState() { - return state; - } - - /** - * Get a given BlockStateEnum's value as its Bukkit counterpart. - * - * @param nms the NMS state to convert - * @param bukkit the Bukkit class - * @param the type - * @return the matching Bukkit type - */ - protected > B get(BlockStateEnum nms, Class bukkit) { - return toBukkit(state.get(nms), bukkit); - } - - /** - * Convert all values from the given BlockStateEnum to their appropriate - * Bukkit counterpart. - * - * @param nms the NMS state to get values from - * @param bukkit the bukkit class to convert the values to - * @param the bukkit class type - * @return an immutable Set of values in their appropriate Bukkit type - */ - @SuppressWarnings("unchecked") - protected > Set getValues(BlockStateEnum nms, Class bukkit) { - ImmutableSet.Builder values = ImmutableSet.builder(); - - for (Enum e : nms.getValues()) { - values.add(toBukkit(e, bukkit)); - } - - return values.build(); - } - - /** - * Set a given {@link BlockStateEnum} with the matching enum from Bukkit. - * - * @param nms the NMS BlockStateEnum to set - * @param bukkit the matching Bukkit Enum - * @param the Bukkit type - * @param the NMS type - */ - protected , N extends Enum & INamable> void set(BlockStateEnum nms, Enum bukkit) { - this.parsedStates = null; - this.state = this.state.set(nms, toNMS(bukkit, nms.b())); - } - - @Override - public BlockData merge(BlockData data) { - CraftBlockData craft = (CraftBlockData) data; - Preconditions.checkArgument(craft.parsedStates != null, "Data not created via string parsing"); - Preconditions.checkArgument(this.state.getBlock() == craft.state.getBlock(), "States have different types (got %s, expected %s)", data, this); - - CraftBlockData clone = (CraftBlockData) this.clone(); - clone.parsedStates = null; - - for (IBlockState parsed : craft.parsedStates.keySet()) { - clone.state = clone.state.set(parsed, craft.state.get(parsed)); - } - - return clone; - } - - @Override - public boolean matches(BlockData data) { - if (data == null) { - return false; - } - if (!(data instanceof CraftBlockData)) { - return false; - } - - CraftBlockData craft = (CraftBlockData) data; - if (this.state.getBlock() != craft.state.getBlock()) { - return false; - } - - // Fastpath an exact match - boolean exactMatch = this.equals(data); - - // If that failed, do a merge and check - if (!exactMatch && craft.parsedStates != null) { - return this.merge(data).equals(this); - } - - return exactMatch; - } - - private static final Map, Enum>> classMappings = new HashMap<>(); - - /** - * Convert an NMS Enum (usually a BlockStateEnum) to its appropriate Bukkit - * enum from the given class. - * - * @throws IllegalStateException if the Enum could not be converted - */ - @SuppressWarnings("unchecked") - private static > B toBukkit(Enum nms, Class bukkit) { - Enum converted; - BiMap, Enum> nmsToBukkit = classMappings.get(nms.getClass()); - - if (nmsToBukkit != null) { - converted = nmsToBukkit.get(nms); - if (converted != null) { - return (B) converted; - } - } - - if (nms instanceof EnumDirection) { - converted = CraftBlock.notchToBlockFace((EnumDirection) nms); - } else { - converted = bukkit.getEnumConstants()[nms.ordinal()]; - } - - Preconditions.checkState(converted != null, "Could not convert enum %s->%s", nms, bukkit); - - if (nmsToBukkit == null) { - nmsToBukkit = HashBiMap.create(); - classMappings.put(nms.getClass(), nmsToBukkit); - } - - nmsToBukkit.put(nms, converted); - - return (B) converted; - } - - /** - * Convert a given Bukkit enum to its matching NMS enum type. - * - * @param bukkit the Bukkit enum to convert - * @param nms the NMS class - * @return the matching NMS type - * @throws IllegalStateException if the Enum could not be converted - */ - @SuppressWarnings("unchecked") - private static & INamable> N toNMS(Enum bukkit, Class nms) { - Enum converted; - BiMap, Enum> nmsToBukkit = classMappings.get(nms); - - if (nmsToBukkit != null) { - converted = nmsToBukkit.inverse().get(bukkit); - if (converted != null) { - return (N) converted; - } - } - - if (bukkit instanceof BlockFace) { - converted = CraftBlock.blockFaceToNotch((BlockFace) bukkit); - } else { - converted = nms.getEnumConstants()[bukkit.ordinal()]; - } - - Preconditions.checkState(converted != null, "Could not convert enum %s->%s", nms, bukkit); - - if (nmsToBukkit == null) { - nmsToBukkit = HashBiMap.create(); - classMappings.put(nms, nmsToBukkit); - } - - nmsToBukkit.put(converted, bukkit); - - return (N) converted; - } - - /** - * Get the current value of a given state. - * - * @param ibs the state to check - * @param the type - * @return the current value of the given state - */ - protected > T get(IBlockState ibs) { - // Straight integer or boolean getter - return this.state.get(ibs); - } - - /** - * Set the specified state's value. - * - * @param ibs the state to set - * @param v the new value - * @param the state's type - * @param the value's type. Must match the state's type. - */ - public , V extends T> void set(IBlockState ibs, V v) { - // Straight integer or boolean setter - this.parsedStates = null; - this.state = this.state.set(ibs, v); - } - - @Override - public String getAsString() { - return toString(((BlockDataAbstract) state).getStateMap()); - } - - @Override - public String getAsString(boolean hideUnspecified) { - return (hideUnspecified && parsedStates != null) ? toString(parsedStates) : getAsString(); - } - - @Override - public BlockData clone() { - try { - return (BlockData) super.clone(); - } catch (CloneNotSupportedException ex) { - throw new AssertionError("Clone not supported", ex); - } - } - - @Override - public String toString() { - return "CraftBlockData{" + state.toString() + "}"; - } - - // Mimicked from BlockDataAbstract#toString() - public String toString(Map, Comparable> states) { - StringBuilder stateString = new StringBuilder(IRegistry.BLOCK.getKey(state.getBlock()).toString()); - - if (!states.isEmpty()) { - stateString.append('['); - stateString.append(states.entrySet().stream().map(BlockDataAbstract.STATE_TO_VALUE).collect(Collectors.joining(","))); - stateString.append(']'); - } - - return stateString.toString(); - } - - public NBTTagCompound toStates() { - NBTTagCompound compound = new NBTTagCompound(); - - for (Map.Entry, Comparable> entry : state.getStateMap().entrySet()) { - IBlockState iblockstate = (IBlockState) entry.getKey(); - - compound.setString(iblockstate.a(), iblockstate.a(entry.getValue())); - } - - return compound; - } - - @Override - public boolean equals(Object obj) { - return obj instanceof CraftBlockData && state.equals(((CraftBlockData) obj).state); - } - - @Override - public int hashCode() { - return state.hashCode(); - } - - protected static BlockStateBoolean getBoolean(String name) { - throw new AssertionError("Template Method"); - } - - protected static BlockStateBoolean getBoolean(String name, boolean optional) { - throw new AssertionError("Template Method"); - } - - protected static BlockStateEnum getEnum(String name) { - throw new AssertionError("Template Method"); - } - - protected static BlockStateInteger getInteger(String name) { - throw new AssertionError("Template Method"); - } - - protected static BlockStateBoolean getBoolean(Class block, String name) { - return (BlockStateBoolean) getState(block, name, false); - } - - protected static BlockStateBoolean getBoolean(Class block, String name, boolean optional) { - return (BlockStateBoolean) getState(block, name, optional); - } - - protected static BlockStateEnum getEnum(Class block, String name) { - return (BlockStateEnum) getState(block, name, false); - } - - protected static BlockStateInteger getInteger(Class block, String name) { - return (BlockStateInteger) getState(block, name, false); - } - - /** - * Get a specified {@link IBlockState} from a given block's class with a - * given name - * - * @param block the class to retrieve the state from - * @param name the name of the state to retrieve - * @param optional if the state can be null - * @return the specified state or null - * @throws IllegalStateException if the state is null and {@code optional} - * is false. - */ - private static IBlockState getState(Class block, String name, boolean optional) { - IBlockState state = null; - - for (Block instance : IRegistry.BLOCK) { - if (instance.getClass() == block) { - if (state == null) { - state = instance.getStates().a(name); - } else { - IBlockState newState = instance.getStates().a(name); - - Preconditions.checkState(state == newState, "State mistmatch %s,%s", state, newState); - } - } - } - - Preconditions.checkState(optional || state != null, "Null state for %s,%s", block, name); - - return state; - } - - /** - * Get the minimum value allowed by the BlockStateInteger. - * - * @param state the state to check - * @return the minimum value allowed - */ - protected static int getMin(BlockStateInteger state) { - return state.min; - } - - /** - * Get the maximum value allowed by the BlockStateInteger. - * - * @param state the state to check - * @return the maximum value allowed - */ - protected static int getMax(BlockStateInteger state) { - return state.max; - } - - // - private static final Map, Function> MAP = new HashMap<>(); - - static { - // - register(net.minecraft.server.BlockAnvil.class, org.bukkit.craftbukkit.block.impl.CraftAnvil::new); - register(net.minecraft.server.BlockBamboo.class, org.bukkit.craftbukkit.block.impl.CraftBamboo::new); - register(net.minecraft.server.BlockBanner.class, org.bukkit.craftbukkit.block.impl.CraftBanner::new); - register(net.minecraft.server.BlockBannerWall.class, org.bukkit.craftbukkit.block.impl.CraftBannerWall::new); - register(net.minecraft.server.BlockBarrel.class, org.bukkit.craftbukkit.block.impl.CraftBarrel::new); - register(net.minecraft.server.BlockBed.class, org.bukkit.craftbukkit.block.impl.CraftBed::new); - register(net.minecraft.server.BlockBeetroot.class, org.bukkit.craftbukkit.block.impl.CraftBeetroot::new); - register(net.minecraft.server.BlockBell.class, org.bukkit.craftbukkit.block.impl.CraftBell::new); - register(net.minecraft.server.BlockBlastFurnace.class, org.bukkit.craftbukkit.block.impl.CraftBlastFurnace::new); - register(net.minecraft.server.BlockBrewingStand.class, org.bukkit.craftbukkit.block.impl.CraftBrewingStand::new); - register(net.minecraft.server.BlockBubbleColumn.class, org.bukkit.craftbukkit.block.impl.CraftBubbleColumn::new); - register(net.minecraft.server.BlockCactus.class, org.bukkit.craftbukkit.block.impl.CraftCactus::new); - register(net.minecraft.server.BlockCake.class, org.bukkit.craftbukkit.block.impl.CraftCake::new); - register(net.minecraft.server.BlockCampfire.class, org.bukkit.craftbukkit.block.impl.CraftCampfire::new); - register(net.minecraft.server.BlockCarrots.class, org.bukkit.craftbukkit.block.impl.CraftCarrots::new); - register(net.minecraft.server.BlockCauldron.class, org.bukkit.craftbukkit.block.impl.CraftCauldron::new); - register(net.minecraft.server.BlockChest.class, org.bukkit.craftbukkit.block.impl.CraftChest::new); - register(net.minecraft.server.BlockChestTrapped.class, org.bukkit.craftbukkit.block.impl.CraftChestTrapped::new); - register(net.minecraft.server.BlockChorusFlower.class, org.bukkit.craftbukkit.block.impl.CraftChorusFlower::new); - register(net.minecraft.server.BlockChorusFruit.class, org.bukkit.craftbukkit.block.impl.CraftChorusFruit::new); - register(net.minecraft.server.BlockCobbleWall.class, org.bukkit.craftbukkit.block.impl.CraftCobbleWall::new); - register(net.minecraft.server.BlockCocoa.class, org.bukkit.craftbukkit.block.impl.CraftCocoa::new); - register(net.minecraft.server.BlockCommand.class, org.bukkit.craftbukkit.block.impl.CraftCommand::new); - register(net.minecraft.server.BlockComposter.class, org.bukkit.craftbukkit.block.impl.CraftComposter::new); - register(net.minecraft.server.BlockConduit.class, org.bukkit.craftbukkit.block.impl.CraftConduit::new); - register(net.minecraft.server.BlockCoralDead.class, org.bukkit.craftbukkit.block.impl.CraftCoralDead::new); - register(net.minecraft.server.BlockCoralFan.class, org.bukkit.craftbukkit.block.impl.CraftCoralFan::new); - register(net.minecraft.server.BlockCoralFanAbstract.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanAbstract::new); - register(net.minecraft.server.BlockCoralFanWall.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanWall::new); - register(net.minecraft.server.BlockCoralFanWallAbstract.class, org.bukkit.craftbukkit.block.impl.CraftCoralFanWallAbstract::new); - register(net.minecraft.server.BlockCoralPlant.class, org.bukkit.craftbukkit.block.impl.CraftCoralPlant::new); - register(net.minecraft.server.BlockCrops.class, org.bukkit.craftbukkit.block.impl.CraftCrops::new); - register(net.minecraft.server.BlockDaylightDetector.class, org.bukkit.craftbukkit.block.impl.CraftDaylightDetector::new); - register(net.minecraft.server.BlockDirtSnow.class, org.bukkit.craftbukkit.block.impl.CraftDirtSnow::new); - register(net.minecraft.server.BlockDispenser.class, org.bukkit.craftbukkit.block.impl.CraftDispenser::new); - register(net.minecraft.server.BlockDoor.class, org.bukkit.craftbukkit.block.impl.CraftDoor::new); - register(net.minecraft.server.BlockDropper.class, org.bukkit.craftbukkit.block.impl.CraftDropper::new); - register(net.minecraft.server.BlockEndRod.class, org.bukkit.craftbukkit.block.impl.CraftEndRod::new); - register(net.minecraft.server.BlockEnderChest.class, org.bukkit.craftbukkit.block.impl.CraftEnderChest::new); - register(net.minecraft.server.BlockEnderPortalFrame.class, org.bukkit.craftbukkit.block.impl.CraftEnderPortalFrame::new); - register(net.minecraft.server.BlockFence.class, org.bukkit.craftbukkit.block.impl.CraftFence::new); - register(net.minecraft.server.BlockFenceGate.class, org.bukkit.craftbukkit.block.impl.CraftFenceGate::new); - register(net.minecraft.server.BlockFire.class, org.bukkit.craftbukkit.block.impl.CraftFire::new); - register(net.minecraft.server.BlockFloorSign.class, org.bukkit.craftbukkit.block.impl.CraftFloorSign::new); - register(net.minecraft.server.BlockFluids.class, org.bukkit.craftbukkit.block.impl.CraftFluids::new); - register(net.minecraft.server.BlockFurnaceFurace.class, org.bukkit.craftbukkit.block.impl.CraftFurnaceFurace::new); - register(net.minecraft.server.BlockGlazedTerracotta.class, org.bukkit.craftbukkit.block.impl.CraftGlazedTerracotta::new); - register(net.minecraft.server.BlockGrass.class, org.bukkit.craftbukkit.block.impl.CraftGrass::new); - register(net.minecraft.server.BlockGrindstone.class, org.bukkit.craftbukkit.block.impl.CraftGrindstone::new); - register(net.minecraft.server.BlockHay.class, org.bukkit.craftbukkit.block.impl.CraftHay::new); - register(net.minecraft.server.BlockHopper.class, org.bukkit.craftbukkit.block.impl.CraftHopper::new); - register(net.minecraft.server.BlockHugeMushroom.class, org.bukkit.craftbukkit.block.impl.CraftHugeMushroom::new); - register(net.minecraft.server.BlockIceFrost.class, org.bukkit.craftbukkit.block.impl.CraftIceFrost::new); - register(net.minecraft.server.BlockIronBars.class, org.bukkit.craftbukkit.block.impl.CraftIronBars::new); - register(net.minecraft.server.BlockJigsaw.class, org.bukkit.craftbukkit.block.impl.CraftJigsaw::new); - register(net.minecraft.server.BlockJukeBox.class, org.bukkit.craftbukkit.block.impl.CraftJukeBox::new); - register(net.minecraft.server.BlockKelp.class, org.bukkit.craftbukkit.block.impl.CraftKelp::new); - register(net.minecraft.server.BlockLadder.class, org.bukkit.craftbukkit.block.impl.CraftLadder::new); - register(net.minecraft.server.BlockLantern.class, org.bukkit.craftbukkit.block.impl.CraftLantern::new); - register(net.minecraft.server.BlockLeaves.class, org.bukkit.craftbukkit.block.impl.CraftLeaves::new); - register(net.minecraft.server.BlockLectern.class, org.bukkit.craftbukkit.block.impl.CraftLectern::new); - register(net.minecraft.server.BlockLever.class, org.bukkit.craftbukkit.block.impl.CraftLever::new); - register(net.minecraft.server.BlockLogAbstract.class, org.bukkit.craftbukkit.block.impl.CraftLogAbstract::new); - register(net.minecraft.server.BlockLoom.class, org.bukkit.craftbukkit.block.impl.CraftLoom::new); - register(net.minecraft.server.BlockMinecartDetector.class, org.bukkit.craftbukkit.block.impl.CraftMinecartDetector::new); - register(net.minecraft.server.BlockMinecartTrack.class, org.bukkit.craftbukkit.block.impl.CraftMinecartTrack::new); - register(net.minecraft.server.BlockMycel.class, org.bukkit.craftbukkit.block.impl.CraftMycel::new); - register(net.minecraft.server.BlockNetherWart.class, org.bukkit.craftbukkit.block.impl.CraftNetherWart::new); - register(net.minecraft.server.BlockNote.class, org.bukkit.craftbukkit.block.impl.CraftNote::new); - register(net.minecraft.server.BlockObserver.class, org.bukkit.craftbukkit.block.impl.CraftObserver::new); - register(net.minecraft.server.BlockPiston.class, org.bukkit.craftbukkit.block.impl.CraftPiston::new); - register(net.minecraft.server.BlockPistonExtension.class, org.bukkit.craftbukkit.block.impl.CraftPistonExtension::new); - register(net.minecraft.server.BlockPistonMoving.class, org.bukkit.craftbukkit.block.impl.CraftPistonMoving::new); - register(net.minecraft.server.BlockPortal.class, org.bukkit.craftbukkit.block.impl.CraftPortal::new); - register(net.minecraft.server.BlockPotatoes.class, org.bukkit.craftbukkit.block.impl.CraftPotatoes::new); - register(net.minecraft.server.BlockPoweredRail.class, org.bukkit.craftbukkit.block.impl.CraftPoweredRail::new); - register(net.minecraft.server.BlockPressurePlateBinary.class, org.bukkit.craftbukkit.block.impl.CraftPressurePlateBinary::new); - register(net.minecraft.server.BlockPressurePlateWeighted.class, org.bukkit.craftbukkit.block.impl.CraftPressurePlateWeighted::new); - register(net.minecraft.server.BlockPumpkinCarved.class, org.bukkit.craftbukkit.block.impl.CraftPumpkinCarved::new); - register(net.minecraft.server.BlockRedstoneComparator.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneComparator::new); - register(net.minecraft.server.BlockRedstoneLamp.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneLamp::new); - register(net.minecraft.server.BlockRedstoneOre.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneOre::new); - register(net.minecraft.server.BlockRedstoneTorch.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneTorch::new); - register(net.minecraft.server.BlockRedstoneTorchWall.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneTorchWall::new); - register(net.minecraft.server.BlockRedstoneWire.class, org.bukkit.craftbukkit.block.impl.CraftRedstoneWire::new); - register(net.minecraft.server.BlockReed.class, org.bukkit.craftbukkit.block.impl.CraftReed::new); - register(net.minecraft.server.BlockRepeater.class, org.bukkit.craftbukkit.block.impl.CraftRepeater::new); - register(net.minecraft.server.BlockRotatable.class, org.bukkit.craftbukkit.block.impl.CraftRotatable::new); - register(net.minecraft.server.BlockSapling.class, org.bukkit.craftbukkit.block.impl.CraftSapling::new); - register(net.minecraft.server.BlockScaffolding.class, org.bukkit.craftbukkit.block.impl.CraftScaffolding::new); - register(net.minecraft.server.BlockSeaPickle.class, org.bukkit.craftbukkit.block.impl.CraftSeaPickle::new); - register(net.minecraft.server.BlockShulkerBox.class, org.bukkit.craftbukkit.block.impl.CraftShulkerBox::new); - register(net.minecraft.server.BlockSkull.class, org.bukkit.craftbukkit.block.impl.CraftSkull::new); - register(net.minecraft.server.BlockSkullPlayer.class, org.bukkit.craftbukkit.block.impl.CraftSkullPlayer::new); - register(net.minecraft.server.BlockSkullPlayerWall.class, org.bukkit.craftbukkit.block.impl.CraftSkullPlayerWall::new); - register(net.minecraft.server.BlockSkullWall.class, org.bukkit.craftbukkit.block.impl.CraftSkullWall::new); - register(net.minecraft.server.BlockSmoker.class, org.bukkit.craftbukkit.block.impl.CraftSmoker::new); - register(net.minecraft.server.BlockSnow.class, org.bukkit.craftbukkit.block.impl.CraftSnow::new); - register(net.minecraft.server.BlockSoil.class, org.bukkit.craftbukkit.block.impl.CraftSoil::new); - register(net.minecraft.server.BlockStainedGlassPane.class, org.bukkit.craftbukkit.block.impl.CraftStainedGlassPane::new); - register(net.minecraft.server.BlockStairs.class, org.bukkit.craftbukkit.block.impl.CraftStairs::new); - register(net.minecraft.server.BlockStem.class, org.bukkit.craftbukkit.block.impl.CraftStem::new); - register(net.minecraft.server.BlockStemAttached.class, org.bukkit.craftbukkit.block.impl.CraftStemAttached::new); - register(net.minecraft.server.BlockStepAbstract.class, org.bukkit.craftbukkit.block.impl.CraftStepAbstract::new); - register(net.minecraft.server.BlockStoneButton.class, org.bukkit.craftbukkit.block.impl.CraftStoneButton::new); - register(net.minecraft.server.BlockStonecutter.class, org.bukkit.craftbukkit.block.impl.CraftStonecutter::new); - register(net.minecraft.server.BlockStructure.class, org.bukkit.craftbukkit.block.impl.CraftStructure::new); - register(net.minecraft.server.BlockSweetBerryBush.class, org.bukkit.craftbukkit.block.impl.CraftSweetBerryBush::new); - register(net.minecraft.server.BlockTNT.class, org.bukkit.craftbukkit.block.impl.CraftTNT::new); - register(net.minecraft.server.BlockTallPlant.class, org.bukkit.craftbukkit.block.impl.CraftTallPlant::new); - register(net.minecraft.server.BlockTallPlantFlower.class, org.bukkit.craftbukkit.block.impl.CraftTallPlantFlower::new); - register(net.minecraft.server.BlockTallSeaGrass.class, org.bukkit.craftbukkit.block.impl.CraftTallSeaGrass::new); - register(net.minecraft.server.BlockTorchWall.class, org.bukkit.craftbukkit.block.impl.CraftTorchWall::new); - register(net.minecraft.server.BlockTrapdoor.class, org.bukkit.craftbukkit.block.impl.CraftTrapdoor::new); - register(net.minecraft.server.BlockTripwire.class, org.bukkit.craftbukkit.block.impl.CraftTripwire::new); - register(net.minecraft.server.BlockTripwireHook.class, org.bukkit.craftbukkit.block.impl.CraftTripwireHook::new); - register(net.minecraft.server.BlockTurtleEgg.class, org.bukkit.craftbukkit.block.impl.CraftTurtleEgg::new); - register(net.minecraft.server.BlockVine.class, org.bukkit.craftbukkit.block.impl.CraftVine::new); - register(net.minecraft.server.BlockWallSign.class, org.bukkit.craftbukkit.block.impl.CraftWallSign::new); - register(net.minecraft.server.BlockWitherSkull.class, org.bukkit.craftbukkit.block.impl.CraftWitherSkull::new); - register(net.minecraft.server.BlockWitherSkullWall.class, org.bukkit.craftbukkit.block.impl.CraftWitherSkullWall::new); - register(net.minecraft.server.BlockWoodButton.class, org.bukkit.craftbukkit.block.impl.CraftWoodButton::new); - // - } - - private static void register(Class nms, Function bukkit) { - Preconditions.checkState(MAP.put(nms, bukkit) == null, "Duplicate mapping %s->%s", nms, bukkit); - } - - public static CraftBlockData newData(Material material, String data) { - Preconditions.checkArgument(material == null || material.isBlock(), "Cannot get data for not block %s", material); - - IBlockData blockData; - Block block = CraftMagicNumbers.getBlock(material); - Map, Comparable> parsed = null; - - // Data provided, use it - if (data != null) { - try { - // Material provided, force that material in - if (block != null) { - data = IRegistry.BLOCK.getKey(block) + data; - } - - StringReader reader = new StringReader(data); - ArgumentBlock arg = new ArgumentBlock(reader, false).a(false); - Preconditions.checkArgument(!reader.canRead(), "Spurious trailing data: " + data); - - blockData = arg.getBlockData(); - parsed = arg.getStateMap(); - } catch (CommandSyntaxException ex) { - throw new IllegalArgumentException("Could not parse data: " + data, ex); - } - } else { - blockData = block.getBlockData(); - } - - CraftBlockData craft = fromData(blockData); - craft.parsedStates = parsed; - return craft; - } - - // Paper start - optimize creating BlockData to not need a map lookup - static { - // Initialize cached data for all IBlockData instances after registration - Block.REGISTRY_ID.iterator().forEachRemaining(IBlockData::createCraftBlockData); - } - public static CraftBlockData fromData(IBlockData data) { - return data.createCraftBlockData(); - } - - public static CraftBlockData createData(IBlockData data) { - // Paper end - return MAP.getOrDefault(data.getBlock().getClass(), CraftBlockData::new).apply(data); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftDirectional.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftDirectional.java deleted file mode 100644 index 7b3ec8811..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftDirectional.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Directional; - -public abstract class CraftDirectional extends CraftBlockData implements Directional { - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum("facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftLevelled.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftLevelled.java deleted file mode 100644 index 3d4afa748..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftLevelled.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Levelled; - -public abstract class CraftLevelled extends CraftBlockData implements Levelled { - - private static final net.minecraft.server.BlockStateInteger LEVEL = getInteger("level"); - - @Override - public int getLevel() { - return get(LEVEL); - } - - @Override - public void setLevel(int level) { - set(LEVEL, level); - } - - @Override - public int getMaximumLevel() { - return getMax(LEVEL); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftLightable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftLightable.java deleted file mode 100644 index cfe4b26e4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftLightable.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Lightable; - -public abstract class CraftLightable extends CraftBlockData implements Lightable { - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean("lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftMultipleFacing.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftMultipleFacing.java deleted file mode 100644 index 5d2cc2a9f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftMultipleFacing.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.MultipleFacing; - -public abstract class CraftMultipleFacing extends CraftBlockData implements MultipleFacing { - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean("north", true), getBoolean("east", true), getBoolean("south", true), getBoolean("west", true), getBoolean("up", true), getBoolean("down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftOpenable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftOpenable.java deleted file mode 100644 index 31abd411e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftOpenable.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Openable; - -public abstract class CraftOpenable extends CraftBlockData implements Openable { - - private static final net.minecraft.server.BlockStateBoolean OPEN = getBoolean("open"); - - @Override - public boolean isOpen() { - return get(OPEN); - } - - @Override - public void setOpen(boolean open) { - set(OPEN, open); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftOrientable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftOrientable.java deleted file mode 100644 index 72cc0aa97..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftOrientable.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Orientable; - -public class CraftOrientable extends CraftBlockData implements Orientable { - - private static final net.minecraft.server.BlockStateEnum AXIS = getEnum("axis"); - - @Override - public org.bukkit.Axis getAxis() { - return get(AXIS, org.bukkit.Axis.class); - } - - @Override - public void setAxis(org.bukkit.Axis axis) { - set(AXIS, axis); - } - - @Override - public java.util.Set getAxes() { - return getValues(AXIS, org.bukkit.Axis.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftPowerable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftPowerable.java deleted file mode 100644 index f932cf17f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftPowerable.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Powerable; - -public abstract class CraftPowerable extends CraftBlockData implements Powerable { - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean("powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftRail.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftRail.java deleted file mode 100644 index 5ee64559b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftRail.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Rail; - -public abstract class CraftRail extends CraftBlockData implements Rail { - - private static final net.minecraft.server.BlockStateEnum SHAPE = getEnum("shape"); - - @Override - public Shape getShape() { - return get(SHAPE, Shape.class); - } - - @Override - public void setShape(Shape shape) { - set(SHAPE, shape); - } - - @Override - public java.util.Set getShapes() { - return getValues(SHAPE, Shape.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftRotatable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftRotatable.java deleted file mode 100644 index 78668da5b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftRotatable.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Rotatable; - -public abstract class CraftRotatable extends CraftBlockData implements Rotatable { - - private static final net.minecraft.server.BlockStateInteger ROTATION = getInteger("rotation"); - - @Override - public org.bukkit.block.BlockFace getRotation() { - int data = get(ROTATION); - switch (data) { - case 0x0: - return org.bukkit.block.BlockFace.SOUTH; - case 0x1: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_WEST; - case 0x2: - return org.bukkit.block.BlockFace.SOUTH_WEST; - case 0x3: - return org.bukkit.block.BlockFace.WEST_SOUTH_WEST; - case 0x4: - return org.bukkit.block.BlockFace.WEST; - case 0x5: - return org.bukkit.block.BlockFace.WEST_NORTH_WEST; - case 0x6: - return org.bukkit.block.BlockFace.NORTH_WEST; - case 0x7: - return org.bukkit.block.BlockFace.NORTH_NORTH_WEST; - case 0x8: - return org.bukkit.block.BlockFace.NORTH; - case 0x9: - return org.bukkit.block.BlockFace.NORTH_NORTH_EAST; - case 0xA: - return org.bukkit.block.BlockFace.NORTH_EAST; - case 0xB: - return org.bukkit.block.BlockFace.EAST_NORTH_EAST; - case 0xC: - return org.bukkit.block.BlockFace.EAST; - case 0xD: - return org.bukkit.block.BlockFace.EAST_SOUTH_EAST; - case 0xE: - return org.bukkit.block.BlockFace.SOUTH_EAST; - case 0xF: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_EAST; - default: - throw new IllegalArgumentException("Unknown rotation " + data); - } - } - - @Override - public void setRotation(org.bukkit.block.BlockFace rotation) { - int val; - switch (rotation) { - case SOUTH: - val = 0x0; - break; - case SOUTH_SOUTH_WEST: - val = 0x1; - break; - case SOUTH_WEST: - val = 0x2; - break; - case WEST_SOUTH_WEST: - val = 0x3; - break; - case WEST: - val = 0x4; - break; - case WEST_NORTH_WEST: - val = 0x5; - break; - case NORTH_WEST: - val = 0x6; - break; - case NORTH_NORTH_WEST: - val = 0x7; - break; - case NORTH: - val = 0x8; - break; - case NORTH_NORTH_EAST: - val = 0x9; - break; - case NORTH_EAST: - val = 0xA; - break; - case EAST_NORTH_EAST: - val = 0xB; - break; - case EAST: - val = 0xC; - break; - case EAST_SOUTH_EAST: - val = 0xD; - break; - case SOUTH_EAST: - val = 0xE; - break; - case SOUTH_SOUTH_EAST: - val = 0xF; - break; - default: - throw new IllegalArgumentException("Illegal rotation " + rotation); - } - set(ROTATION, val); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftSnowable.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftSnowable.java deleted file mode 100644 index e59c3d230..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftSnowable.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Snowable; - -public abstract class CraftSnowable extends CraftBlockData implements Snowable { - - private static final net.minecraft.server.BlockStateBoolean SNOWY = getBoolean("snowy"); - - @Override - public boolean isSnowy() { - return get(SNOWY); - } - - @Override - public void setSnowy(boolean snowy) { - set(SNOWY, snowy); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/CraftWaterlogged.java b/src/main/java/org/bukkit/craftbukkit/block/data/CraftWaterlogged.java deleted file mode 100644 index 4e1a672fc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/CraftWaterlogged.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.bukkit.craftbukkit.block.data; - -import org.bukkit.block.data.Waterlogged; - -public abstract class CraftWaterlogged extends CraftBlockData implements Waterlogged { - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean("waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBamboo.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBamboo.java deleted file mode 100644 index 65485a9ed..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBamboo.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Bamboo; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftBamboo extends CraftBlockData implements Bamboo { - - private static final net.minecraft.server.BlockStateEnum LEAVES = getEnum("leaves"); - - @Override - public Leaves getLeaves() { - return get(LEAVES, Leaves.class); - } - - @Override - public void setLeaves(Leaves leaves) { - set(LEAVES, leaves); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBed.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBed.java deleted file mode 100644 index f86ed2591..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBed.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Bed; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftBed extends CraftBlockData implements Bed { - - private static final net.minecraft.server.BlockStateEnum PART = getEnum("part"); - private static final net.minecraft.server.BlockStateBoolean OCCUPIED = getBoolean("occupied"); - - @Override - public Part getPart() { - return get(PART, Part.class); - } - - @Override - public void setPart(Part part) { - set(PART, part); - } - - @Override - public boolean isOccupied() { - return get(OCCUPIED); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBell.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBell.java deleted file mode 100644 index a94dd1cee..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBell.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Bell; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftBell extends CraftBlockData implements Bell { - - private static final net.minecraft.server.BlockStateEnum ATTACHMENT = getEnum("attachment"); - - @Override - public Attachment getAttachment() { - return get(ATTACHMENT, Attachment.class); - } - - @Override - public void setAttachment(Attachment leaves) { - set(ATTACHMENT, leaves); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrewingStand.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrewingStand.java deleted file mode 100644 index 9349e02fe..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBrewingStand.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.BrewingStand; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftBrewingStand extends CraftBlockData implements BrewingStand { - - private static final net.minecraft.server.BlockStateBoolean[] HAS_BOTTLE = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean("has_bottle_0"), getBoolean("has_bottle_1"), getBoolean("has_bottle_2") - }; - - @Override - public boolean hasBottle(int bottle) { - return get(HAS_BOTTLE[bottle]); - } - - @Override - public void setBottle(int bottle, boolean has) { - set(HAS_BOTTLE[bottle], has); - } - - @Override - public java.util.Set getBottles() { - com.google.common.collect.ImmutableSet.Builder bottles = com.google.common.collect.ImmutableSet.builder(); - - for (int index = 0; index < getMaximumBottles(); index++) { - if (hasBottle(index)) { - bottles.add(index); - } - } - - return bottles.build(); - } - - @Override - public int getMaximumBottles() { - return HAS_BOTTLE.length; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBubbleColumn.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBubbleColumn.java deleted file mode 100644 index eedb51022..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftBubbleColumn.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.BubbleColumn; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftBubbleColumn extends CraftBlockData implements BubbleColumn { - - private static final net.minecraft.server.BlockStateBoolean DRAG = getBoolean("drag"); - - @Override - public boolean isDrag() { - return get(DRAG); - } - - @Override - public void setDrag(boolean drag) { - set(DRAG, drag); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCake.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCake.java deleted file mode 100644 index aae60937b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCake.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Cake; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftCake extends CraftBlockData implements Cake { - - private static final net.minecraft.server.BlockStateInteger BITES = getInteger("bites"); - - @Override - public int getBites() { - return get(BITES); - } - - @Override - public void setBites(int bites) { - set(BITES, bites); - } - - @Override - public int getMaximumBites() { - return getMax(BITES); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCampfire.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCampfire.java deleted file mode 100644 index 99250172b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCampfire.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Campfire; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftCampfire extends CraftBlockData implements Campfire { - - private static final net.minecraft.server.BlockStateBoolean SIGNAL_FIRE = getBoolean("signal_fire"); - - @Override - public boolean isSignalFire() { - return get(SIGNAL_FIRE); - } - - @Override - public void setSignalFire(boolean signalFire) { - set(SIGNAL_FIRE, signalFire); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChest.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChest.java deleted file mode 100644 index 70473ef42..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftChest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Chest; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftChest extends CraftBlockData implements Chest { - - private static final net.minecraft.server.BlockStateEnum TYPE = getEnum("type"); - - @Override - public Type getType() { - return get(TYPE, Type.class); - } - - @Override - public void setType(Type type) { - set(TYPE, type); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCommandBlock.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCommandBlock.java deleted file mode 100644 index ddb9ac5e0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftCommandBlock.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.CommandBlock; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftCommandBlock extends CraftBlockData implements CommandBlock { - - private static final net.minecraft.server.BlockStateBoolean CONDITIONAL = getBoolean("conditional"); - - @Override - public boolean isConditional() { - return get(CONDITIONAL); - } - - @Override - public void setConditional(boolean conditional) { - set(CONDITIONAL, conditional); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftComparator.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftComparator.java deleted file mode 100644 index 4f3130a5f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftComparator.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Comparator; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftComparator extends CraftBlockData implements Comparator { - - private static final net.minecraft.server.BlockStateEnum MODE = getEnum("mode"); - - @Override - public Mode getMode() { - return get(MODE, Mode.class); - } - - @Override - public void setMode(Mode mode) { - set(MODE, mode); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDaylightDetector.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDaylightDetector.java deleted file mode 100644 index 842fe51f9..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDaylightDetector.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.DaylightDetector; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftDaylightDetector extends CraftBlockData implements DaylightDetector { - - private static final net.minecraft.server.BlockStateBoolean INVERTED = getBoolean("inverted"); - - @Override - public boolean isInverted() { - return get(INVERTED); - } - - @Override - public void setInverted(boolean inverted) { - set(INVERTED, inverted); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDispenser.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDispenser.java deleted file mode 100644 index 5d43240e7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDispenser.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Dispenser; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftDispenser extends CraftBlockData implements Dispenser { - - private static final net.minecraft.server.BlockStateBoolean TRIGGERED = getBoolean("triggered"); - - @Override - public boolean isTriggered() { - return get(TRIGGERED); - } - - @Override - public void setTriggered(boolean triggered) { - set(TRIGGERED, triggered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDoor.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDoor.java deleted file mode 100644 index 3fc75dd2a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftDoor.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Door; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftDoor extends CraftBlockData implements Door { - - private static final net.minecraft.server.BlockStateEnum HINGE = getEnum("hinge"); - - @Override - public Hinge getHinge() { - return get(HINGE, Hinge.class); - } - - @Override - public void setHinge(Hinge hinge) { - set(HINGE, hinge); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftEndPortalFrame.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftEndPortalFrame.java deleted file mode 100644 index 84cd1d039..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftEndPortalFrame.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.EndPortalFrame; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftEndPortalFrame extends CraftBlockData implements EndPortalFrame { - - private static final net.minecraft.server.BlockStateBoolean EYE = getBoolean("eye"); - - @Override - public boolean hasEye() { - return get(EYE); - } - - @Override - public void setEye(boolean eye) { - set(EYE, eye); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftFarmland.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftFarmland.java deleted file mode 100644 index 515ee588c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftFarmland.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Farmland; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftFarmland extends CraftBlockData implements Farmland { - - private static final net.minecraft.server.BlockStateInteger MOISTURE = getInteger("moisture"); - - @Override - public int getMoisture() { - return get(MOISTURE); - } - - @Override - public void setMoisture(int moisture) { - set(MOISTURE, moisture); - } - - @Override - public int getMaximumMoisture() { - return getMax(MOISTURE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftGate.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftGate.java deleted file mode 100644 index 1f6ad5d98..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftGate.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Gate; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftGate extends CraftBlockData implements Gate { - - private static final net.minecraft.server.BlockStateBoolean IN_WALL = getBoolean("in_wall"); - - @Override - public boolean isInWall() { - return get(IN_WALL); - } - - @Override - public void setInWall(boolean inWall) { - set(IN_WALL, inWall); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHopper.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHopper.java deleted file mode 100644 index 055629fde..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftHopper.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Hopper; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftHopper extends CraftBlockData implements Hopper { - - private static final net.minecraft.server.BlockStateBoolean ENABLED = getBoolean("enabled"); - - @Override - public boolean isEnabled() { - return get(ENABLED); - } - - @Override - public void setEnabled(boolean enabled) { - set(ENABLED, enabled); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJukebox.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJukebox.java deleted file mode 100644 index c1fe52e1b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftJukebox.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Jukebox; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftJukebox extends CraftBlockData implements Jukebox { - - private static final net.minecraft.server.BlockStateBoolean HAS_RECORD = getBoolean("has_record"); - - @Override - public boolean hasRecord() { - return get(HAS_RECORD); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLantern.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLantern.java deleted file mode 100644 index 01bdf9d80..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLantern.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Lantern; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftLantern extends CraftBlockData implements Lantern { - - private static final net.minecraft.server.BlockStateBoolean HANGING = getBoolean("hanging"); - - @Override - public boolean isHanging() { - return get(HANGING); - } - - @Override - public void setHanging(boolean hanging) { - set(HANGING, hanging); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLeaves.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLeaves.java deleted file mode 100644 index a233f5550..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLeaves.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Leaves; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public class CraftLeaves extends CraftBlockData implements Leaves { - - private static final net.minecraft.server.BlockStateInteger DISTANCE = getInteger("distance"); - private static final net.minecraft.server.BlockStateBoolean PERSISTENT = getBoolean("persistent"); - - @Override - public boolean isPersistent() { - return get(PERSISTENT); - } - - @Override - public void setPersistent(boolean persistent) { - set(PERSISTENT, persistent); - } - - @Override - public int getDistance() { - return get(DISTANCE); - } - - @Override - public void setDistance(int distance) { - set(DISTANCE, distance); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLectern.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLectern.java deleted file mode 100644 index 1ecdf4718..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftLectern.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Lectern; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftLectern extends CraftBlockData implements Lectern { - - private static final net.minecraft.server.BlockStateBoolean HAS_BOOK = getBoolean("has_book"); - - @Override - public boolean hasBook() { - return get(HAS_BOOK); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftNoteBlock.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftNoteBlock.java deleted file mode 100644 index 51814a497..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftNoteBlock.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.NoteBlock; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftNoteBlock extends CraftBlockData implements NoteBlock { - - private static final net.minecraft.server.BlockStateEnum INSTRUMENT = getEnum("instrument"); - private static final net.minecraft.server.BlockStateInteger NOTE = getInteger("note"); - - @Override - public org.bukkit.Instrument getInstrument() { - return get(INSTRUMENT, org.bukkit.Instrument.class); - } - - @Override - public void setInstrument(org.bukkit.Instrument instrument) { - set(INSTRUMENT, instrument); - } - - @Override - public org.bukkit.Note getNote() { - return new org.bukkit.Note(get(NOTE)); - } - - @Override - public void setNote(org.bukkit.Note note) { - set(NOTE, (int) note.getId()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPiston.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPiston.java deleted file mode 100644 index 8cebb751e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPiston.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Piston; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftPiston extends CraftBlockData implements Piston { - - private static final net.minecraft.server.BlockStateBoolean EXTENDED = getBoolean("extended"); - - @Override - public boolean isExtended() { - return get(EXTENDED); - } - - @Override - public void setExtended(boolean extended) { - set(EXTENDED, extended); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPistonHead.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPistonHead.java deleted file mode 100644 index 3fb24d4b8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftPistonHead.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.PistonHead; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftPistonHead extends CraftBlockData implements PistonHead { - - private static final net.minecraft.server.BlockStateBoolean SHORT = getBoolean("short"); - - @Override - public boolean isShort() { - return get(SHORT); - } - - @Override - public void setShort(boolean _short) { - set(SHORT, _short); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRedstoneWire.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRedstoneWire.java deleted file mode 100644 index c5ec1c55d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRedstoneWire.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.RedstoneWire; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftRedstoneWire extends CraftBlockData implements RedstoneWire { - - private static final net.minecraft.server.BlockStateEnum NORTH = getEnum("north"); - private static final net.minecraft.server.BlockStateEnum EAST = getEnum("east"); - private static final net.minecraft.server.BlockStateEnum SOUTH = getEnum("south"); - private static final net.minecraft.server.BlockStateEnum WEST = getEnum("west"); - - @Override - public Connection getFace(org.bukkit.block.BlockFace face) { - switch (face) { - case NORTH: - return get(NORTH, Connection.class); - case EAST: - return get(EAST, Connection.class); - case SOUTH: - return get(SOUTH, Connection.class); - case WEST: - return get(WEST, Connection.class); - default: - throw new IllegalArgumentException("Cannot have face " + face); - } - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, Connection connection) { - switch (face) { - case NORTH: - set(NORTH, connection); - break; - case EAST: - set(EAST, connection); - break; - case SOUTH: - set(SOUTH, connection); - break; - case WEST: - set(WEST, connection); - break; - default: - throw new IllegalArgumentException("Cannot have face " + face); - } - } - - @Override - public java.util.Set getAllowedFaces() { - return com.google.common.collect.ImmutableSet.of(org.bukkit.block.BlockFace.NORTH, org.bukkit.block.BlockFace.EAST, org.bukkit.block.BlockFace.SOUTH, org.bukkit.block.BlockFace.WEST); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRepeater.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRepeater.java deleted file mode 100644 index 482a4ed75..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftRepeater.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Repeater; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftRepeater extends CraftBlockData implements Repeater { - - private static final net.minecraft.server.BlockStateInteger DELAY = getInteger("delay"); - private static final net.minecraft.server.BlockStateBoolean LOCKED = getBoolean("locked"); - - @Override - public int getDelay() { - return get(DELAY); - } - - @Override - public void setDelay(int delay) { - set(DELAY, delay); - } - - @Override - public int getMinimumDelay() { - return getMin(DELAY); - } - - @Override - public int getMaximumDelay() { - return getMax(DELAY); - } - - @Override - public boolean isLocked() { - return get(LOCKED); - } - - @Override - public void setLocked(boolean locked) { - set(LOCKED, locked); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSapling.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSapling.java deleted file mode 100644 index dd96acff1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSapling.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Sapling; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftSapling extends CraftBlockData implements Sapling { - - private static final net.minecraft.server.BlockStateInteger STAGE = getInteger("stage"); - - @Override - public int getStage() { - return get(STAGE); - } - - @Override - public void setStage(int stage) { - set(STAGE, stage); - } - - @Override - public int getMaximumStage() { - return getMax(STAGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftScaffolding.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftScaffolding.java deleted file mode 100644 index fe896908c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftScaffolding.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Scaffolding; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftScaffolding extends CraftBlockData implements Scaffolding { - - private static final net.minecraft.server.BlockStateBoolean BOTTOM = getBoolean("bottom"); - private static final net.minecraft.server.BlockStateInteger DISTANCE = getInteger("distance"); - - @Override - public boolean isBottom() { - return get(BOTTOM); - } - - @Override - public void setBottom(boolean bottom) { - set(BOTTOM, bottom); - } - - @Override - public int getDistance() { - return get(DISTANCE); - } - - @Override - public void setDistance(int distance) { - set(DISTANCE, distance); - } - - @Override - public int getMaximumDistance() { - return getMax(DISTANCE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSeaPickle.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSeaPickle.java deleted file mode 100644 index dc138d9c7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSeaPickle.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.SeaPickle; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftSeaPickle extends CraftBlockData implements SeaPickle { - - private static final net.minecraft.server.BlockStateInteger PICKLES = getInteger("pickles"); - - @Override - public int getPickles() { - return get(PICKLES); - } - - @Override - public void setPickles(int pickles) { - set(PICKLES, pickles); - } - - @Override - public int getMinimumPickles() { - return getMin(PICKLES); - } - - @Override - public int getMaximumPickles() { - return getMax(PICKLES); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSlab.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSlab.java deleted file mode 100644 index 1fde489e5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSlab.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Slab; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftSlab extends CraftBlockData implements Slab { - - private static final net.minecraft.server.BlockStateEnum TYPE = getEnum("type"); - - @Override - public Type getType() { - return get(TYPE, Type.class); - } - - @Override - public void setType(Type type) { - set(TYPE, type); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSnow.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSnow.java deleted file mode 100644 index 879a5d679..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSnow.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Snow; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public class CraftSnow extends CraftBlockData implements Snow { - - private static final net.minecraft.server.BlockStateInteger LAYERS = getInteger("layers"); - - @Override - public int getLayers() { - return get(LAYERS); - } - - @Override - public void setLayers(int layers) { - set(LAYERS, layers); - } - - @Override - public int getMinimumLayers() { - return getMin(LAYERS); - } - - @Override - public int getMaximumLayers() { - return getMax(LAYERS); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStairs.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStairs.java deleted file mode 100644 index c6ccd382f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStairs.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Stairs; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftStairs extends CraftBlockData implements Stairs { - - private static final net.minecraft.server.BlockStateEnum SHAPE = getEnum("shape"); - - @Override - public Shape getShape() { - return get(SHAPE, Shape.class); - } - - @Override - public void setShape(Shape shape) { - set(SHAPE, shape); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStructureBlock.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStructureBlock.java deleted file mode 100644 index 8b8a82bd3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftStructureBlock.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.StructureBlock; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftStructureBlock extends CraftBlockData implements StructureBlock { - - private static final net.minecraft.server.BlockStateEnum MODE = getEnum("mode"); - - @Override - public Mode getMode() { - return get(MODE, Mode.class); - } - - @Override - public void setMode(Mode mode) { - set(MODE, mode); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSwitch.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSwitch.java deleted file mode 100644 index 2761b3710..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftSwitch.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Switch; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftSwitch extends CraftBlockData implements Switch { - - private static final net.minecraft.server.BlockStateEnum FACE = getEnum("face"); - - @Override - public Face getFace() { - return get(FACE, Face.class); - } - - @Override - public void setFace(Face face) { - set(FACE, face); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTNT.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTNT.java deleted file mode 100644 index 18662a805..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTNT.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.TNT; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftTNT extends CraftBlockData implements TNT { - - private static final net.minecraft.server.BlockStateBoolean UNSTABLE = getBoolean("unstable"); - - @Override - public boolean isUnstable() { - return get(UNSTABLE); - } - - @Override - public void setUnstable(boolean unstable) { - set(UNSTABLE, unstable); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTechnicalPiston.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTechnicalPiston.java deleted file mode 100644 index e42fe0d67..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTechnicalPiston.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.TechnicalPiston; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftTechnicalPiston extends CraftBlockData implements TechnicalPiston { - - private static final net.minecraft.server.BlockStateEnum TYPE = getEnum("type"); - - @Override - public Type getType() { - return get(TYPE, Type.class); - } - - @Override - public void setType(Type type) { - set(TYPE, type); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTripwire.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTripwire.java deleted file mode 100644 index 55bacd2e5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTripwire.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.Tripwire; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftTripwire extends CraftBlockData implements Tripwire { - - private static final net.minecraft.server.BlockStateBoolean DISARMED = getBoolean("disarmed"); - - @Override - public boolean isDisarmed() { - return get(DISARMED); - } - - @Override - public void setDisarmed(boolean disarmed) { - set(DISARMED, disarmed); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTurtleEgg.java b/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTurtleEgg.java deleted file mode 100644 index dca37886e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTurtleEgg.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.craftbukkit.block.data.type; - -import org.bukkit.block.data.type.TurtleEgg; -import org.bukkit.craftbukkit.block.data.CraftBlockData; - -public abstract class CraftTurtleEgg extends CraftBlockData implements TurtleEgg { - - private static final net.minecraft.server.BlockStateInteger EGGS = getInteger("eggs"); - private static final net.minecraft.server.BlockStateInteger HATCH = getInteger("hatch"); - - @Override - public int getEggs() { - return get(EGGS); - } - - @Override - public void setEggs(int eggs) { - set(EGGS, eggs); - } - - @Override - public int getMinimumEggs() { - return getMin(EGGS); - } - - @Override - public int getMaximumEggs() { - return getMax(EGGS); - } - - @Override - public int getHatch() { - return get(HATCH); - } - - @Override - public void setHatch(int hatch) { - set(HATCH, hatch); - } - - @Override - public int getMaximumHatch() { - return getMax(HATCH); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAnvil.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAnvil.java deleted file mode 100644 index 3010e8fe1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftAnvil.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftAnvil extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftAnvil() { - super(); - } - - public CraftAnvil(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockAnvil.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBamboo.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBamboo.java deleted file mode 100644 index 3c650d4f8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBamboo.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBamboo extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Bamboo, org.bukkit.block.data.Ageable, org.bukkit.block.data.type.Sapling { - - public CraftBamboo() { - super(); - } - - public CraftBamboo(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftBamboo - - private static final net.minecraft.server.BlockStateEnum LEAVES = getEnum(net.minecraft.server.BlockBamboo.class, "leaves"); - - @Override - public Leaves getLeaves() { - return get(LEAVES, Leaves.class); - } - - @Override - public void setLeaves(Leaves leaves) { - set(LEAVES, leaves); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockBamboo.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } - - // org.bukkit.craftbukkit.block.data.type.CraftSapling - - private static final net.minecraft.server.BlockStateInteger STAGE = getInteger(net.minecraft.server.BlockBamboo.class, "stage"); - - @Override - public int getStage() { - return get(STAGE); - } - - @Override - public void setStage(int stage) { - set(STAGE, stage); - } - - @Override - public int getMaximumStage() { - return getMax(STAGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBanner.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBanner.java deleted file mode 100644 index d95c548bc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBanner.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBanner extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Rotatable { - - public CraftBanner() { - super(); - } - - public CraftBanner(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftRotatable - - private static final net.minecraft.server.BlockStateInteger ROTATION = getInteger(net.minecraft.server.BlockBanner.class, "rotation"); - - @Override - public org.bukkit.block.BlockFace getRotation() { - int data = get(ROTATION); - switch (data) { - case 0x0: - return org.bukkit.block.BlockFace.SOUTH; - case 0x1: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_WEST; - case 0x2: - return org.bukkit.block.BlockFace.SOUTH_WEST; - case 0x3: - return org.bukkit.block.BlockFace.WEST_SOUTH_WEST; - case 0x4: - return org.bukkit.block.BlockFace.WEST; - case 0x5: - return org.bukkit.block.BlockFace.WEST_NORTH_WEST; - case 0x6: - return org.bukkit.block.BlockFace.NORTH_WEST; - case 0x7: - return org.bukkit.block.BlockFace.NORTH_NORTH_WEST; - case 0x8: - return org.bukkit.block.BlockFace.NORTH; - case 0x9: - return org.bukkit.block.BlockFace.NORTH_NORTH_EAST; - case 0xA: - return org.bukkit.block.BlockFace.NORTH_EAST; - case 0xB: - return org.bukkit.block.BlockFace.EAST_NORTH_EAST; - case 0xC: - return org.bukkit.block.BlockFace.EAST; - case 0xD: - return org.bukkit.block.BlockFace.EAST_SOUTH_EAST; - case 0xE: - return org.bukkit.block.BlockFace.SOUTH_EAST; - case 0xF: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_EAST; - default: - throw new IllegalArgumentException("Unknown rotation " + data); - } - } - - @Override - public void setRotation(org.bukkit.block.BlockFace rotation) { - int val; - switch (rotation) { - case SOUTH: - val = 0x0; - break; - case SOUTH_SOUTH_WEST: - val = 0x1; - break; - case SOUTH_WEST: - val = 0x2; - break; - case WEST_SOUTH_WEST: - val = 0x3; - break; - case WEST: - val = 0x4; - break; - case WEST_NORTH_WEST: - val = 0x5; - break; - case NORTH_WEST: - val = 0x6; - break; - case NORTH_NORTH_WEST: - val = 0x7; - break; - case NORTH: - val = 0x8; - break; - case NORTH_NORTH_EAST: - val = 0x9; - break; - case NORTH_EAST: - val = 0xA; - break; - case EAST_NORTH_EAST: - val = 0xB; - break; - case EAST: - val = 0xC; - break; - case EAST_SOUTH_EAST: - val = 0xD; - break; - case SOUTH_EAST: - val = 0xE; - break; - case SOUTH_SOUTH_EAST: - val = 0xF; - break; - default: - throw new IllegalArgumentException("Illegal rotation " + rotation); - } - set(ROTATION, val); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBannerWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBannerWall.java deleted file mode 100644 index 48215035f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBannerWall.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBannerWall extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftBannerWall() { - super(); - } - - public CraftBannerWall(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockBannerWall.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrel.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrel.java deleted file mode 100644 index 81919c941..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBarrel.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBarrel extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftBarrel() { - super(); - } - - public CraftBarrel(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockBarrel.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBed.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBed.java deleted file mode 100644 index c625c964e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBed.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBed extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Bed, org.bukkit.block.data.Directional { - - public CraftBed() { - super(); - } - - public CraftBed(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftBed - - private static final net.minecraft.server.BlockStateEnum PART = getEnum(net.minecraft.server.BlockBed.class, "part"); - private static final net.minecraft.server.BlockStateBoolean OCCUPIED = getBoolean(net.minecraft.server.BlockBed.class, "occupied"); - - @Override - public Part getPart() { - return get(PART, Part.class); - } - - @Override - public void setPart(Part part) { - set(PART, part); - } - - @Override - public boolean isOccupied() { - return get(OCCUPIED); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockBed.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeetroot.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeetroot.java deleted file mode 100644 index 4e9a27f47..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBeetroot.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBeetroot extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftBeetroot() { - super(); - } - - public CraftBeetroot(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockBeetroot.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBell.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBell.java deleted file mode 100644 index 526af161b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBell.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBell extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Bell, org.bukkit.block.data.Directional { - - public CraftBell() { - super(); - } - - public CraftBell(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftBell - - private static final net.minecraft.server.BlockStateEnum ATTACHMENT = getEnum(net.minecraft.server.BlockBell.class, "attachment"); - - @Override - public Attachment getAttachment() { - return get(ATTACHMENT, Attachment.class); - } - - @Override - public void setAttachment(Attachment leaves) { - set(ATTACHMENT, leaves); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockBell.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBlastFurnace.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBlastFurnace.java deleted file mode 100644 index 8e223604f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBlastFurnace.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBlastFurnace extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Furnace, org.bukkit.block.data.Directional, org.bukkit.block.data.Lightable { - - public CraftBlastFurnace() { - super(); - } - - public CraftBlastFurnace(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockBlastFurnace.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftLightable - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean(net.minecraft.server.BlockBlastFurnace.class, "lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrewingStand.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrewingStand.java deleted file mode 100644 index fe0e7dec6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBrewingStand.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBrewingStand extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.BrewingStand { - - public CraftBrewingStand() { - super(); - } - - public CraftBrewingStand(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftBrewingStand - - private static final net.minecraft.server.BlockStateBoolean[] HAS_BOTTLE = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockBrewingStand.class, "has_bottle_0"), getBoolean(net.minecraft.server.BlockBrewingStand.class, "has_bottle_1"), getBoolean(net.minecraft.server.BlockBrewingStand.class, "has_bottle_2") - }; - - @Override - public boolean hasBottle(int bottle) { - return get(HAS_BOTTLE[bottle]); - } - - @Override - public void setBottle(int bottle, boolean has) { - set(HAS_BOTTLE[bottle], has); - } - - @Override - public java.util.Set getBottles() { - com.google.common.collect.ImmutableSet.Builder bottles = com.google.common.collect.ImmutableSet.builder(); - - for (int index = 0; index < getMaximumBottles(); index++) { - if (hasBottle(index)) { - bottles.add(index); - } - } - - return bottles.build(); - } - - @Override - public int getMaximumBottles() { - return HAS_BOTTLE.length; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBubbleColumn.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBubbleColumn.java deleted file mode 100644 index 574a5b9a7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftBubbleColumn.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftBubbleColumn extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.BubbleColumn { - - public CraftBubbleColumn() { - super(); - } - - public CraftBubbleColumn(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftBubbleColumn - - private static final net.minecraft.server.BlockStateBoolean DRAG = getBoolean(net.minecraft.server.BlockBubbleColumn.class, "drag"); - - @Override - public boolean isDrag() { - return get(DRAG); - } - - @Override - public void setDrag(boolean drag) { - set(DRAG, drag); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCactus.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCactus.java deleted file mode 100644 index e62f4dd17..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCactus.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCactus extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftCactus() { - super(); - } - - public CraftCactus(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockCactus.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCake.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCake.java deleted file mode 100644 index fee523abe..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCake.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCake extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Cake { - - public CraftCake() { - super(); - } - - public CraftCake(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftCake - - private static final net.minecraft.server.BlockStateInteger BITES = getInteger(net.minecraft.server.BlockCake.class, "bites"); - - @Override - public int getBites() { - return get(BITES); - } - - @Override - public void setBites(int bites) { - set(BITES, bites); - } - - @Override - public int getMaximumBites() { - return getMax(BITES); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCampfire.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCampfire.java deleted file mode 100644 index 9761b082e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCampfire.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCampfire extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Campfire, org.bukkit.block.data.Directional, org.bukkit.block.data.Lightable, org.bukkit.block.data.Waterlogged { - - public CraftCampfire() { - super(); - } - - public CraftCampfire(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftCampfire - - private static final net.minecraft.server.BlockStateBoolean SIGNAL_FIRE = getBoolean(net.minecraft.server.BlockCampfire.class, "signal_fire"); - - @Override - public boolean isSignalFire() { - return get(SIGNAL_FIRE); - } - - @Override - public void setSignalFire(boolean signalFire) { - set(SIGNAL_FIRE, signalFire); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockCampfire.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftLightable - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean(net.minecraft.server.BlockCampfire.class, "lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockCampfire.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCarrots.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCarrots.java deleted file mode 100644 index 9ab29636e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCarrots.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCarrots extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftCarrots() { - super(); - } - - public CraftCarrots(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockCarrots.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCauldron.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCauldron.java deleted file mode 100644 index 5ddeb7158..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCauldron.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCauldron extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Levelled { - - public CraftCauldron() { - super(); - } - - public CraftCauldron(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftLevelled - - private static final net.minecraft.server.BlockStateInteger LEVEL = getInteger(net.minecraft.server.BlockCauldron.class, "level"); - - @Override - public int getLevel() { - return get(LEVEL); - } - - @Override - public void setLevel(int level) { - set(LEVEL, level); - } - - @Override - public int getMaximumLevel() { - return getMax(LEVEL); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChest.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChest.java deleted file mode 100644 index 44f3a5328..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChest.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftChest extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Chest, org.bukkit.block.data.Directional, org.bukkit.block.data.Waterlogged { - - public CraftChest() { - super(); - } - - public CraftChest(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftChest - - private static final net.minecraft.server.BlockStateEnum TYPE = getEnum(net.minecraft.server.BlockChest.class, "type"); - - @Override - public Type getType() { - return get(TYPE, Type.class); - } - - @Override - public void setType(Type type) { - set(TYPE, type); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockChest.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockChest.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChestTrapped.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChestTrapped.java deleted file mode 100644 index cc8f88baa..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChestTrapped.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftChestTrapped extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Chest, org.bukkit.block.data.Directional, org.bukkit.block.data.Waterlogged { - - public CraftChestTrapped() { - super(); - } - - public CraftChestTrapped(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftChest - - private static final net.minecraft.server.BlockStateEnum TYPE = getEnum(net.minecraft.server.BlockChestTrapped.class, "type"); - - @Override - public Type getType() { - return get(TYPE, Type.class); - } - - @Override - public void setType(Type type) { - set(TYPE, type); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockChestTrapped.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockChestTrapped.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFlower.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFlower.java deleted file mode 100644 index af1e85bcd..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFlower.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftChorusFlower extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftChorusFlower() { - super(); - } - - public CraftChorusFlower(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockChorusFlower.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFruit.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFruit.java deleted file mode 100644 index 27ae41a92..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftChorusFruit.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftChorusFruit extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.MultipleFacing { - - public CraftChorusFruit() { - super(); - } - - public CraftChorusFruit(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockChorusFruit.class, "north", true), getBoolean(net.minecraft.server.BlockChorusFruit.class, "east", true), getBoolean(net.minecraft.server.BlockChorusFruit.class, "south", true), getBoolean(net.minecraft.server.BlockChorusFruit.class, "west", true), getBoolean(net.minecraft.server.BlockChorusFruit.class, "up", true), getBoolean(net.minecraft.server.BlockChorusFruit.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCobbleWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCobbleWall.java deleted file mode 100644 index b1acc7c44..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCobbleWall.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCobbleWall extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Fence, org.bukkit.block.data.MultipleFacing, org.bukkit.block.data.Waterlogged { - - public CraftCobbleWall() { - super(); - } - - public CraftCobbleWall(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockCobbleWall.class, "north", true), getBoolean(net.minecraft.server.BlockCobbleWall.class, "east", true), getBoolean(net.minecraft.server.BlockCobbleWall.class, "south", true), getBoolean(net.minecraft.server.BlockCobbleWall.class, "west", true), getBoolean(net.minecraft.server.BlockCobbleWall.class, "up", true), getBoolean(net.minecraft.server.BlockCobbleWall.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockCobbleWall.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCocoa.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCocoa.java deleted file mode 100644 index 79b2b52ca..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCocoa.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCocoa extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Cocoa, org.bukkit.block.data.Ageable, org.bukkit.block.data.Directional { - - public CraftCocoa() { - super(); - } - - public CraftCocoa(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockCocoa.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockCocoa.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCommand.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCommand.java deleted file mode 100644 index ed1684a63..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCommand extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.CommandBlock, org.bukkit.block.data.Directional { - - public CraftCommand() { - super(); - } - - public CraftCommand(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftCommandBlock - - private static final net.minecraft.server.BlockStateBoolean CONDITIONAL = getBoolean(net.minecraft.server.BlockCommand.class, "conditional"); - - @Override - public boolean isConditional() { - return get(CONDITIONAL); - } - - @Override - public void setConditional(boolean conditional) { - set(CONDITIONAL, conditional); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockCommand.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftComposter.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftComposter.java deleted file mode 100644 index 536628624..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftComposter.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftComposter extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Levelled { - - public CraftComposter() { - super(); - } - - public CraftComposter(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftLevelled - - private static final net.minecraft.server.BlockStateInteger LEVEL = getInteger(net.minecraft.server.BlockComposter.class, "level"); - - @Override - public int getLevel() { - return get(LEVEL); - } - - @Override - public void setLevel(int level) { - set(LEVEL, level); - } - - @Override - public int getMaximumLevel() { - return getMax(LEVEL); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftConduit.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftConduit.java deleted file mode 100644 index ec2c91526..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftConduit.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftConduit extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Waterlogged { - - public CraftConduit() { - super(); - } - - public CraftConduit(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockConduit.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralDead.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralDead.java deleted file mode 100644 index 450f6658d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralDead.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCoralDead extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Waterlogged { - - public CraftCoralDead() { - super(); - } - - public CraftCoralDead(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockCoralDead.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFan.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFan.java deleted file mode 100644 index dde1a04bd..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFan.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCoralFan extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Waterlogged { - - public CraftCoralFan() { - super(); - } - - public CraftCoralFan(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockCoralFan.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanAbstract.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanAbstract.java deleted file mode 100644 index f1eddf70a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanAbstract.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCoralFanAbstract extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Waterlogged { - - public CraftCoralFanAbstract() { - super(); - } - - public CraftCoralFanAbstract(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockCoralFanAbstract.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWall.java deleted file mode 100644 index 8b89b6b41..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWall.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCoralFanWall extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.CoralWallFan, org.bukkit.block.data.Directional, org.bukkit.block.data.Waterlogged { - - public CraftCoralFanWall() { - super(); - } - - public CraftCoralFanWall(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockCoralFanWall.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockCoralFanWall.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWallAbstract.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWallAbstract.java deleted file mode 100644 index 320f2f216..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralFanWallAbstract.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCoralFanWallAbstract extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.CoralWallFan, org.bukkit.block.data.Directional, org.bukkit.block.data.Waterlogged { - - public CraftCoralFanWallAbstract() { - super(); - } - - public CraftCoralFanWallAbstract(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockCoralFanWallAbstract.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockCoralFanWallAbstract.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralPlant.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralPlant.java deleted file mode 100644 index 4fb0fa98d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCoralPlant.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCoralPlant extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Waterlogged { - - public CraftCoralPlant() { - super(); - } - - public CraftCoralPlant(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockCoralPlant.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrops.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrops.java deleted file mode 100644 index 61921a2a5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrops.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftCrops extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftCrops() { - super(); - } - - public CraftCrops(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockCrops.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDaylightDetector.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDaylightDetector.java deleted file mode 100644 index ffed5c9a3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDaylightDetector.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftDaylightDetector extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.DaylightDetector, org.bukkit.block.data.AnaloguePowerable { - - public CraftDaylightDetector() { - super(); - } - - public CraftDaylightDetector(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftDaylightDetector - - private static final net.minecraft.server.BlockStateBoolean INVERTED = getBoolean(net.minecraft.server.BlockDaylightDetector.class, "inverted"); - - @Override - public boolean isInverted() { - return get(INVERTED); - } - - @Override - public void setInverted(boolean inverted) { - set(INVERTED, inverted); - } - - // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - - private static final net.minecraft.server.BlockStateInteger POWER = getInteger(net.minecraft.server.BlockDaylightDetector.class, "power"); - - @Override - public int getPower() { - return get(POWER); - } - - @Override - public void setPower(int power) { - set(POWER, power); - } - - @Override - public int getMaximumPower() { - return getMax(POWER); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDirtSnow.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDirtSnow.java deleted file mode 100644 index 7c3857e92..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDirtSnow.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftDirtSnow extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Snowable { - - public CraftDirtSnow() { - super(); - } - - public CraftDirtSnow(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftSnowable - - private static final net.minecraft.server.BlockStateBoolean SNOWY = getBoolean(net.minecraft.server.BlockDirtSnow.class, "snowy"); - - @Override - public boolean isSnowy() { - return get(SNOWY); - } - - @Override - public void setSnowy(boolean snowy) { - set(SNOWY, snowy); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDispenser.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDispenser.java deleted file mode 100644 index cea8f941e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDispenser.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftDispenser extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Dispenser, org.bukkit.block.data.Directional { - - public CraftDispenser() { - super(); - } - - public CraftDispenser(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftDispenser - - private static final net.minecraft.server.BlockStateBoolean TRIGGERED = getBoolean(net.minecraft.server.BlockDispenser.class, "triggered"); - - @Override - public boolean isTriggered() { - return get(TRIGGERED); - } - - @Override - public void setTriggered(boolean triggered) { - set(TRIGGERED, triggered); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockDispenser.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDoor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDoor.java deleted file mode 100644 index ec8639bf1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDoor.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftDoor extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Door, org.bukkit.block.data.Bisected, org.bukkit.block.data.Directional, org.bukkit.block.data.Openable, org.bukkit.block.data.Powerable { - - public CraftDoor() { - super(); - } - - public CraftDoor(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftDoor - - private static final net.minecraft.server.BlockStateEnum HINGE = getEnum(net.minecraft.server.BlockDoor.class, "hinge"); - - @Override - public Hinge getHinge() { - return get(HINGE, Hinge.class); - } - - @Override - public void setHinge(Hinge hinge) { - set(HINGE, hinge); - } - - // org.bukkit.craftbukkit.block.data.CraftBisected - - private static final net.minecraft.server.BlockStateEnum HALF = getEnum(net.minecraft.server.BlockDoor.class, "half"); - - @Override - public Half getHalf() { - return get(HALF, Half.class); - } - - @Override - public void setHalf(Half half) { - set(HALF, half); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockDoor.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftOpenable - - private static final net.minecraft.server.BlockStateBoolean OPEN = getBoolean(net.minecraft.server.BlockDoor.class, "open"); - - @Override - public boolean isOpen() { - return get(OPEN); - } - - @Override - public void setOpen(boolean open) { - set(OPEN, open); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockDoor.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDropper.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDropper.java deleted file mode 100644 index 82486f1b0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftDropper.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftDropper extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Dispenser, org.bukkit.block.data.Directional { - - public CraftDropper() { - super(); - } - - public CraftDropper(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftDispenser - - private static final net.minecraft.server.BlockStateBoolean TRIGGERED = getBoolean(net.minecraft.server.BlockDropper.class, "triggered"); - - @Override - public boolean isTriggered() { - return get(TRIGGERED); - } - - @Override - public void setTriggered(boolean triggered) { - set(TRIGGERED, triggered); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockDropper.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEndRod.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEndRod.java deleted file mode 100644 index d72c9d050..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEndRod.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftEndRod extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftEndRod() { - super(); - } - - public CraftEndRod(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockEndRod.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderChest.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderChest.java deleted file mode 100644 index 2f8380807..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderChest.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftEnderChest extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.EnderChest, org.bukkit.block.data.Directional, org.bukkit.block.data.Waterlogged { - - public CraftEnderChest() { - super(); - } - - public CraftEnderChest(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockEnderChest.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockEnderChest.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderPortalFrame.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderPortalFrame.java deleted file mode 100644 index f57cbbeca..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftEnderPortalFrame.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftEnderPortalFrame extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.EndPortalFrame, org.bukkit.block.data.Directional { - - public CraftEnderPortalFrame() { - super(); - } - - public CraftEnderPortalFrame(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftEndPortalFrame - - private static final net.minecraft.server.BlockStateBoolean EYE = getBoolean(net.minecraft.server.BlockEnderPortalFrame.class, "eye"); - - @Override - public boolean hasEye() { - return get(EYE); - } - - @Override - public void setEye(boolean eye) { - set(EYE, eye); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockEnderPortalFrame.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFence.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFence.java deleted file mode 100644 index 1333b997f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFence.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftFence extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Fence, org.bukkit.block.data.MultipleFacing, org.bukkit.block.data.Waterlogged { - - public CraftFence() { - super(); - } - - public CraftFence(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockFence.class, "north", true), getBoolean(net.minecraft.server.BlockFence.class, "east", true), getBoolean(net.minecraft.server.BlockFence.class, "south", true), getBoolean(net.minecraft.server.BlockFence.class, "west", true), getBoolean(net.minecraft.server.BlockFence.class, "up", true), getBoolean(net.minecraft.server.BlockFence.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockFence.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFenceGate.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFenceGate.java deleted file mode 100644 index 4fc294452..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFenceGate.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftFenceGate extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Gate, org.bukkit.block.data.Directional, org.bukkit.block.data.Openable, org.bukkit.block.data.Powerable { - - public CraftFenceGate() { - super(); - } - - public CraftFenceGate(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftGate - - private static final net.minecraft.server.BlockStateBoolean IN_WALL = getBoolean(net.minecraft.server.BlockFenceGate.class, "in_wall"); - - @Override - public boolean isInWall() { - return get(IN_WALL); - } - - @Override - public void setInWall(boolean inWall) { - set(IN_WALL, inWall); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockFenceGate.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftOpenable - - private static final net.minecraft.server.BlockStateBoolean OPEN = getBoolean(net.minecraft.server.BlockFenceGate.class, "open"); - - @Override - public boolean isOpen() { - return get(OPEN); - } - - @Override - public void setOpen(boolean open) { - set(OPEN, open); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockFenceGate.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFire.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFire.java deleted file mode 100644 index a58093552..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFire.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftFire extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Fire, org.bukkit.block.data.Ageable, org.bukkit.block.data.MultipleFacing { - - public CraftFire() { - super(); - } - - public CraftFire(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockFire.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockFire.class, "north", true), getBoolean(net.minecraft.server.BlockFire.class, "east", true), getBoolean(net.minecraft.server.BlockFire.class, "south", true), getBoolean(net.minecraft.server.BlockFire.class, "west", true), getBoolean(net.minecraft.server.BlockFire.class, "up", true), getBoolean(net.minecraft.server.BlockFire.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFloorSign.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFloorSign.java deleted file mode 100644 index aa52ec777..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFloorSign.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftFloorSign extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Sign, org.bukkit.block.data.Rotatable, org.bukkit.block.data.Waterlogged { - - public CraftFloorSign() { - super(); - } - - public CraftFloorSign(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftRotatable - - private static final net.minecraft.server.BlockStateInteger ROTATION = getInteger(net.minecraft.server.BlockFloorSign.class, "rotation"); - - @Override - public org.bukkit.block.BlockFace getRotation() { - int data = get(ROTATION); - switch (data) { - case 0x0: - return org.bukkit.block.BlockFace.SOUTH; - case 0x1: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_WEST; - case 0x2: - return org.bukkit.block.BlockFace.SOUTH_WEST; - case 0x3: - return org.bukkit.block.BlockFace.WEST_SOUTH_WEST; - case 0x4: - return org.bukkit.block.BlockFace.WEST; - case 0x5: - return org.bukkit.block.BlockFace.WEST_NORTH_WEST; - case 0x6: - return org.bukkit.block.BlockFace.NORTH_WEST; - case 0x7: - return org.bukkit.block.BlockFace.NORTH_NORTH_WEST; - case 0x8: - return org.bukkit.block.BlockFace.NORTH; - case 0x9: - return org.bukkit.block.BlockFace.NORTH_NORTH_EAST; - case 0xA: - return org.bukkit.block.BlockFace.NORTH_EAST; - case 0xB: - return org.bukkit.block.BlockFace.EAST_NORTH_EAST; - case 0xC: - return org.bukkit.block.BlockFace.EAST; - case 0xD: - return org.bukkit.block.BlockFace.EAST_SOUTH_EAST; - case 0xE: - return org.bukkit.block.BlockFace.SOUTH_EAST; - case 0xF: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_EAST; - default: - throw new IllegalArgumentException("Unknown rotation " + data); - } - } - - @Override - public void setRotation(org.bukkit.block.BlockFace rotation) { - int val; - switch (rotation) { - case SOUTH: - val = 0x0; - break; - case SOUTH_SOUTH_WEST: - val = 0x1; - break; - case SOUTH_WEST: - val = 0x2; - break; - case WEST_SOUTH_WEST: - val = 0x3; - break; - case WEST: - val = 0x4; - break; - case WEST_NORTH_WEST: - val = 0x5; - break; - case NORTH_WEST: - val = 0x6; - break; - case NORTH_NORTH_WEST: - val = 0x7; - break; - case NORTH: - val = 0x8; - break; - case NORTH_NORTH_EAST: - val = 0x9; - break; - case NORTH_EAST: - val = 0xA; - break; - case EAST_NORTH_EAST: - val = 0xB; - break; - case EAST: - val = 0xC; - break; - case EAST_SOUTH_EAST: - val = 0xD; - break; - case SOUTH_EAST: - val = 0xE; - break; - case SOUTH_SOUTH_EAST: - val = 0xF; - break; - default: - throw new IllegalArgumentException("Illegal rotation " + rotation); - } - set(ROTATION, val); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockFloorSign.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFluids.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFluids.java deleted file mode 100644 index 21c30c7c7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFluids.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftFluids extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Levelled { - - public CraftFluids() { - super(); - } - - public CraftFluids(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftLevelled - - private static final net.minecraft.server.BlockStateInteger LEVEL = getInteger(net.minecraft.server.BlockFluids.class, "level"); - - @Override - public int getLevel() { - return get(LEVEL); - } - - @Override - public void setLevel(int level) { - set(LEVEL, level); - } - - @Override - public int getMaximumLevel() { - return getMax(LEVEL); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFurnaceFurace.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFurnaceFurace.java deleted file mode 100644 index 49d4b885e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftFurnaceFurace.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftFurnaceFurace extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Furnace, org.bukkit.block.data.Directional, org.bukkit.block.data.Lightable { - - public CraftFurnaceFurace() { - super(); - } - - public CraftFurnaceFurace(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockFurnaceFurace.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftLightable - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean(net.minecraft.server.BlockFurnaceFurace.class, "lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlazedTerracotta.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlazedTerracotta.java deleted file mode 100644 index 89cc7f95f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGlazedTerracotta.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftGlazedTerracotta extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftGlazedTerracotta() { - super(); - } - - public CraftGlazedTerracotta(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockGlazedTerracotta.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrass.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrass.java deleted file mode 100644 index 08fcfb0b4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrass.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftGrass extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Snowable { - - public CraftGrass() { - super(); - } - - public CraftGrass(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftSnowable - - private static final net.minecraft.server.BlockStateBoolean SNOWY = getBoolean(net.minecraft.server.BlockGrass.class, "snowy"); - - @Override - public boolean isSnowy() { - return get(SNOWY); - } - - @Override - public void setSnowy(boolean snowy) { - set(SNOWY, snowy); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrindstone.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrindstone.java deleted file mode 100644 index f4c08558e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftGrindstone.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftGrindstone extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftGrindstone() { - super(); - } - - public CraftGrindstone(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockGrindstone.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHay.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHay.java deleted file mode 100644 index db7d61ad6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHay.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftHay extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Orientable { - - public CraftHay() { - super(); - } - - public CraftHay(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftOrientable - - private static final net.minecraft.server.BlockStateEnum AXIS = getEnum(net.minecraft.server.BlockHay.class, "axis"); - - @Override - public org.bukkit.Axis getAxis() { - return get(AXIS, org.bukkit.Axis.class); - } - - @Override - public void setAxis(org.bukkit.Axis axis) { - set(AXIS, axis); - } - - @Override - public java.util.Set getAxes() { - return getValues(AXIS, org.bukkit.Axis.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHopper.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHopper.java deleted file mode 100644 index f13115177..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHopper.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftHopper extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Hopper, org.bukkit.block.data.Directional { - - public CraftHopper() { - super(); - } - - public CraftHopper(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftHopper - - private static final net.minecraft.server.BlockStateBoolean ENABLED = getBoolean(net.minecraft.server.BlockHopper.class, "enabled"); - - @Override - public boolean isEnabled() { - return get(ENABLED); - } - - @Override - public void setEnabled(boolean enabled) { - set(ENABLED, enabled); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockHopper.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHugeMushroom.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHugeMushroom.java deleted file mode 100644 index fb6e20507..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftHugeMushroom.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftHugeMushroom extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.MultipleFacing { - - public CraftHugeMushroom() { - super(); - } - - public CraftHugeMushroom(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockHugeMushroom.class, "north", true), getBoolean(net.minecraft.server.BlockHugeMushroom.class, "east", true), getBoolean(net.minecraft.server.BlockHugeMushroom.class, "south", true), getBoolean(net.minecraft.server.BlockHugeMushroom.class, "west", true), getBoolean(net.minecraft.server.BlockHugeMushroom.class, "up", true), getBoolean(net.minecraft.server.BlockHugeMushroom.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIceFrost.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIceFrost.java deleted file mode 100644 index 7b297dc22..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIceFrost.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftIceFrost extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftIceFrost() { - super(); - } - - public CraftIceFrost(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockIceFrost.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIronBars.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIronBars.java deleted file mode 100644 index cf6da2dfe..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftIronBars.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftIronBars extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Fence, org.bukkit.block.data.MultipleFacing, org.bukkit.block.data.Waterlogged { - - public CraftIronBars() { - super(); - } - - public CraftIronBars(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockIronBars.class, "north", true), getBoolean(net.minecraft.server.BlockIronBars.class, "east", true), getBoolean(net.minecraft.server.BlockIronBars.class, "south", true), getBoolean(net.minecraft.server.BlockIronBars.class, "west", true), getBoolean(net.minecraft.server.BlockIronBars.class, "up", true), getBoolean(net.minecraft.server.BlockIronBars.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockIronBars.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJigsaw.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJigsaw.java deleted file mode 100644 index 10f0094b7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJigsaw.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftJigsaw extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftJigsaw() { - super(); - } - - public CraftJigsaw(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockJigsaw.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJukeBox.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJukeBox.java deleted file mode 100644 index b87801f3a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftJukeBox.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftJukeBox extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Jukebox { - - public CraftJukeBox() { - super(); - } - - public CraftJukeBox(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftJukebox - - private static final net.minecraft.server.BlockStateBoolean HAS_RECORD = getBoolean(net.minecraft.server.BlockJukeBox.class, "has_record"); - - @Override - public boolean hasRecord() { - return get(HAS_RECORD); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftKelp.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftKelp.java deleted file mode 100644 index e9ba8ade4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftKelp.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftKelp extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftKelp() { - super(); - } - - public CraftKelp(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockKelp.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLadder.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLadder.java deleted file mode 100644 index 2c7f396fa..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLadder.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftLadder extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Ladder, org.bukkit.block.data.Directional, org.bukkit.block.data.Waterlogged { - - public CraftLadder() { - super(); - } - - public CraftLadder(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockLadder.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockLadder.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLantern.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLantern.java deleted file mode 100644 index 8e279de3e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLantern.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftLantern extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Lantern { - - public CraftLantern() { - super(); - } - - public CraftLantern(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftLantern - - private static final net.minecraft.server.BlockStateBoolean HANGING = getBoolean(net.minecraft.server.BlockLantern.class, "hanging"); - - @Override - public boolean isHanging() { - return get(HANGING); - } - - @Override - public void setHanging(boolean hanging) { - set(HANGING, hanging); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLeaves.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLeaves.java deleted file mode 100644 index 2e2f091b9..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLeaves.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftLeaves extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Leaves { - - public CraftLeaves() { - super(); - } - - public CraftLeaves(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftLeaves - - private static final net.minecraft.server.BlockStateInteger DISTANCE = getInteger(net.minecraft.server.BlockLeaves.class, "distance"); - private static final net.minecraft.server.BlockStateBoolean PERSISTENT = getBoolean(net.minecraft.server.BlockLeaves.class, "persistent"); - - @Override - public boolean isPersistent() { - return get(PERSISTENT); - } - - @Override - public void setPersistent(boolean persistent) { - set(PERSISTENT, persistent); - } - - @Override - public int getDistance() { - return get(DISTANCE); - } - - @Override - public void setDistance(int distance) { - set(DISTANCE, distance); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLectern.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLectern.java deleted file mode 100644 index f7fa832ed..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLectern.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftLectern extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Lectern, org.bukkit.block.data.Directional, org.bukkit.block.data.Powerable { - - public CraftLectern() { - super(); - } - - public CraftLectern(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftLectern - - private static final net.minecraft.server.BlockStateBoolean HAS_BOOK = getBoolean(net.minecraft.server.BlockLectern.class, "has_book"); - - @Override - public boolean hasBook() { - return get(HAS_BOOK); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockLectern.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockLectern.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLever.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLever.java deleted file mode 100644 index a8b030f2f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLever.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftLever extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Switch, org.bukkit.block.data.Directional, org.bukkit.block.data.Powerable { - - public CraftLever() { - super(); - } - - public CraftLever(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftSwitch - - private static final net.minecraft.server.BlockStateEnum FACE = getEnum(net.minecraft.server.BlockLever.class, "face"); - - @Override - public Face getFace() { - return get(FACE, Face.class); - } - - @Override - public void setFace(Face face) { - set(FACE, face); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockLever.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockLever.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLogAbstract.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLogAbstract.java deleted file mode 100644 index efa404902..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLogAbstract.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftLogAbstract extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Orientable { - - public CraftLogAbstract() { - super(); - } - - public CraftLogAbstract(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftOrientable - - private static final net.minecraft.server.BlockStateEnum AXIS = getEnum(net.minecraft.server.BlockLogAbstract.class, "axis"); - - @Override - public org.bukkit.Axis getAxis() { - return get(AXIS, org.bukkit.Axis.class); - } - - @Override - public void setAxis(org.bukkit.Axis axis) { - set(AXIS, axis); - } - - @Override - public java.util.Set getAxes() { - return getValues(AXIS, org.bukkit.Axis.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLoom.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLoom.java deleted file mode 100644 index e0e56dc95..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftLoom.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftLoom extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftLoom() { - super(); - } - - public CraftLoom(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockLoom.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartDetector.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartDetector.java deleted file mode 100644 index 9ad25f9fe..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartDetector.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftMinecartDetector extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.RedstoneRail, org.bukkit.block.data.Powerable, org.bukkit.block.data.Rail { - - public CraftMinecartDetector() { - super(); - } - - public CraftMinecartDetector(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockMinecartDetector.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } - - // org.bukkit.craftbukkit.block.data.CraftRail - - private static final net.minecraft.server.BlockStateEnum SHAPE = getEnum(net.minecraft.server.BlockMinecartDetector.class, "shape"); - - @Override - public Shape getShape() { - return get(SHAPE, Shape.class); - } - - @Override - public void setShape(Shape shape) { - set(SHAPE, shape); - } - - @Override - public java.util.Set getShapes() { - return getValues(SHAPE, Shape.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartTrack.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartTrack.java deleted file mode 100644 index 127681a63..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMinecartTrack.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftMinecartTrack extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Rail { - - public CraftMinecartTrack() { - super(); - } - - public CraftMinecartTrack(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftRail - - private static final net.minecraft.server.BlockStateEnum SHAPE = getEnum(net.minecraft.server.BlockMinecartTrack.class, "shape"); - - @Override - public Shape getShape() { - return get(SHAPE, Shape.class); - } - - @Override - public void setShape(Shape shape) { - set(SHAPE, shape); - } - - @Override - public java.util.Set getShapes() { - return getValues(SHAPE, Shape.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMycel.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMycel.java deleted file mode 100644 index ca9d60f3a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftMycel.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftMycel extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Snowable { - - public CraftMycel() { - super(); - } - - public CraftMycel(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftSnowable - - private static final net.minecraft.server.BlockStateBoolean SNOWY = getBoolean(net.minecraft.server.BlockMycel.class, "snowy"); - - @Override - public boolean isSnowy() { - return get(SNOWY); - } - - @Override - public void setSnowy(boolean snowy) { - set(SNOWY, snowy); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNetherWart.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNetherWart.java deleted file mode 100644 index 449d0f6f5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNetherWart.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftNetherWart extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftNetherWart() { - super(); - } - - public CraftNetherWart(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockNetherWart.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNote.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNote.java deleted file mode 100644 index 03a736bd7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftNote.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftNote extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.NoteBlock, org.bukkit.block.data.Powerable { - - public CraftNote() { - super(); - } - - public CraftNote(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftNoteBlock - - private static final net.minecraft.server.BlockStateEnum INSTRUMENT = getEnum(net.minecraft.server.BlockNote.class, "instrument"); - private static final net.minecraft.server.BlockStateInteger NOTE = getInteger(net.minecraft.server.BlockNote.class, "note"); - - @Override - public org.bukkit.Instrument getInstrument() { - return get(INSTRUMENT, org.bukkit.Instrument.class); - } - - @Override - public void setInstrument(org.bukkit.Instrument instrument) { - set(INSTRUMENT, instrument); - } - - @Override - public org.bukkit.Note getNote() { - return new org.bukkit.Note(get(NOTE)); - } - - @Override - public void setNote(org.bukkit.Note note) { - set(NOTE, (int) note.getId()); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockNote.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftObserver.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftObserver.java deleted file mode 100644 index ba3a4f072..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftObserver.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftObserver extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Observer, org.bukkit.block.data.Directional, org.bukkit.block.data.Powerable { - - public CraftObserver() { - super(); - } - - public CraftObserver(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockObserver.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockObserver.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiston.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiston.java deleted file mode 100644 index f16404f49..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPiston.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPiston extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Piston, org.bukkit.block.data.Directional { - - public CraftPiston() { - super(); - } - - public CraftPiston(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftPiston - - private static final net.minecraft.server.BlockStateBoolean EXTENDED = getBoolean(net.minecraft.server.BlockPiston.class, "extended"); - - @Override - public boolean isExtended() { - return get(EXTENDED); - } - - @Override - public void setExtended(boolean extended) { - set(EXTENDED, extended); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockPiston.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonExtension.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonExtension.java deleted file mode 100644 index 038e58433..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonExtension.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPistonExtension extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.PistonHead, org.bukkit.block.data.type.TechnicalPiston, org.bukkit.block.data.Directional { - - public CraftPistonExtension() { - super(); - } - - public CraftPistonExtension(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftPistonHead - - private static final net.minecraft.server.BlockStateBoolean SHORT = getBoolean(net.minecraft.server.BlockPistonExtension.class, "short"); - - @Override - public boolean isShort() { - return get(SHORT); - } - - @Override - public void setShort(boolean _short) { - set(SHORT, _short); - } - - // org.bukkit.craftbukkit.block.data.type.CraftTechnicalPiston - - private static final net.minecraft.server.BlockStateEnum TYPE = getEnum(net.minecraft.server.BlockPistonExtension.class, "type"); - - @Override - public Type getType() { - return get(TYPE, Type.class); - } - - @Override - public void setType(Type type) { - set(TYPE, type); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockPistonExtension.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonMoving.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonMoving.java deleted file mode 100644 index 38b098e0a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPistonMoving.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPistonMoving extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.TechnicalPiston, org.bukkit.block.data.Directional { - - public CraftPistonMoving() { - super(); - } - - public CraftPistonMoving(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftTechnicalPiston - - private static final net.minecraft.server.BlockStateEnum TYPE = getEnum(net.minecraft.server.BlockPistonMoving.class, "type"); - - @Override - public Type getType() { - return get(TYPE, Type.class); - } - - @Override - public void setType(Type type) { - set(TYPE, type); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockPistonMoving.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPortal.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPortal.java deleted file mode 100644 index 7701ca85d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPortal.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPortal extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Orientable { - - public CraftPortal() { - super(); - } - - public CraftPortal(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftOrientable - - private static final net.minecraft.server.BlockStateEnum AXIS = getEnum(net.minecraft.server.BlockPortal.class, "axis"); - - @Override - public org.bukkit.Axis getAxis() { - return get(AXIS, org.bukkit.Axis.class); - } - - @Override - public void setAxis(org.bukkit.Axis axis) { - set(AXIS, axis); - } - - @Override - public java.util.Set getAxes() { - return getValues(AXIS, org.bukkit.Axis.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPotatoes.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPotatoes.java deleted file mode 100644 index c09a9c78c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPotatoes.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPotatoes extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftPotatoes() { - super(); - } - - public CraftPotatoes(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockPotatoes.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPoweredRail.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPoweredRail.java deleted file mode 100644 index ea904ef00..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPoweredRail.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPoweredRail extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.RedstoneRail, org.bukkit.block.data.Powerable, org.bukkit.block.data.Rail { - - public CraftPoweredRail() { - super(); - } - - public CraftPoweredRail(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockPoweredRail.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } - - // org.bukkit.craftbukkit.block.data.CraftRail - - private static final net.minecraft.server.BlockStateEnum SHAPE = getEnum(net.minecraft.server.BlockPoweredRail.class, "shape"); - - @Override - public Shape getShape() { - return get(SHAPE, Shape.class); - } - - @Override - public void setShape(Shape shape) { - set(SHAPE, shape); - } - - @Override - public java.util.Set getShapes() { - return getValues(SHAPE, Shape.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateBinary.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateBinary.java deleted file mode 100644 index 806ad2565..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateBinary.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPressurePlateBinary extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Powerable { - - public CraftPressurePlateBinary() { - super(); - } - - public CraftPressurePlateBinary(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockPressurePlateBinary.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateWeighted.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateWeighted.java deleted file mode 100644 index 840506640..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPressurePlateWeighted.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPressurePlateWeighted extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.AnaloguePowerable { - - public CraftPressurePlateWeighted() { - super(); - } - - public CraftPressurePlateWeighted(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - - private static final net.minecraft.server.BlockStateInteger POWER = getInteger(net.minecraft.server.BlockPressurePlateWeighted.class, "power"); - - @Override - public int getPower() { - return get(POWER); - } - - @Override - public void setPower(int power) { - set(POWER, power); - } - - @Override - public int getMaximumPower() { - return getMax(POWER); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPumpkinCarved.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPumpkinCarved.java deleted file mode 100644 index b258e7449..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftPumpkinCarved.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftPumpkinCarved extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftPumpkinCarved() { - super(); - } - - public CraftPumpkinCarved(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockPumpkinCarved.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneComparator.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneComparator.java deleted file mode 100644 index 2456e3071..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneComparator.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftRedstoneComparator extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Comparator, org.bukkit.block.data.Directional, org.bukkit.block.data.Powerable { - - public CraftRedstoneComparator() { - super(); - } - - public CraftRedstoneComparator(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftComparator - - private static final net.minecraft.server.BlockStateEnum MODE = getEnum(net.minecraft.server.BlockRedstoneComparator.class, "mode"); - - @Override - public Mode getMode() { - return get(MODE, Mode.class); - } - - @Override - public void setMode(Mode mode) { - set(MODE, mode); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockRedstoneComparator.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockRedstoneComparator.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneLamp.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneLamp.java deleted file mode 100644 index 7769c93c8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneLamp.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftRedstoneLamp extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Lightable { - - public CraftRedstoneLamp() { - super(); - } - - public CraftRedstoneLamp(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftLightable - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean(net.minecraft.server.BlockRedstoneLamp.class, "lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneOre.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneOre.java deleted file mode 100644 index effe08ead..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneOre.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftRedstoneOre extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Lightable { - - public CraftRedstoneOre() { - super(); - } - - public CraftRedstoneOre(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftLightable - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean(net.minecraft.server.BlockRedstoneOre.class, "lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorch.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorch.java deleted file mode 100644 index d9d142016..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorch.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftRedstoneTorch extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Lightable { - - public CraftRedstoneTorch() { - super(); - } - - public CraftRedstoneTorch(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftLightable - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean(net.minecraft.server.BlockRedstoneTorch.class, "lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorchWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorchWall.java deleted file mode 100644 index 8125b4004..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneTorchWall.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftRedstoneTorchWall extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.RedstoneWallTorch, org.bukkit.block.data.Directional, org.bukkit.block.data.Lightable { - - public CraftRedstoneTorchWall() { - super(); - } - - public CraftRedstoneTorchWall(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockRedstoneTorchWall.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftLightable - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean(net.minecraft.server.BlockRedstoneTorchWall.class, "lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneWire.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneWire.java deleted file mode 100644 index 45f66eb40..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRedstoneWire.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftRedstoneWire extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.RedstoneWire, org.bukkit.block.data.AnaloguePowerable { - - public CraftRedstoneWire() { - super(); - } - - public CraftRedstoneWire(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftRedstoneWire - - private static final net.minecraft.server.BlockStateEnum NORTH = getEnum(net.minecraft.server.BlockRedstoneWire.class, "north"); - private static final net.minecraft.server.BlockStateEnum EAST = getEnum(net.minecraft.server.BlockRedstoneWire.class, "east"); - private static final net.minecraft.server.BlockStateEnum SOUTH = getEnum(net.minecraft.server.BlockRedstoneWire.class, "south"); - private static final net.minecraft.server.BlockStateEnum WEST = getEnum(net.minecraft.server.BlockRedstoneWire.class, "west"); - - @Override - public Connection getFace(org.bukkit.block.BlockFace face) { - switch (face) { - case NORTH: - return get(NORTH, Connection.class); - case EAST: - return get(EAST, Connection.class); - case SOUTH: - return get(SOUTH, Connection.class); - case WEST: - return get(WEST, Connection.class); - default: - throw new IllegalArgumentException("Cannot have face " + face); - } - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, Connection connection) { - switch (face) { - case NORTH: - set(NORTH, connection); - break; - case EAST: - set(EAST, connection); - break; - case SOUTH: - set(SOUTH, connection); - break; - case WEST: - set(WEST, connection); - break; - default: - throw new IllegalArgumentException("Cannot have face " + face); - } - } - - @Override - public java.util.Set getAllowedFaces() { - return com.google.common.collect.ImmutableSet.of(org.bukkit.block.BlockFace.NORTH, org.bukkit.block.BlockFace.EAST, org.bukkit.block.BlockFace.SOUTH, org.bukkit.block.BlockFace.WEST); - } - - // org.bukkit.craftbukkit.block.data.CraftAnaloguePowerable - - private static final net.minecraft.server.BlockStateInteger POWER = getInteger(net.minecraft.server.BlockRedstoneWire.class, "power"); - - @Override - public int getPower() { - return get(POWER); - } - - @Override - public void setPower(int power) { - set(POWER, power); - } - - @Override - public int getMaximumPower() { - return getMax(POWER); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftReed.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftReed.java deleted file mode 100644 index 138b8701b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftReed.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftReed extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftReed() { - super(); - } - - public CraftReed(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockReed.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRepeater.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRepeater.java deleted file mode 100644 index 97724f682..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRepeater.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftRepeater extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Repeater, org.bukkit.block.data.Directional, org.bukkit.block.data.Powerable { - - public CraftRepeater() { - super(); - } - - public CraftRepeater(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftRepeater - - private static final net.minecraft.server.BlockStateInteger DELAY = getInteger(net.minecraft.server.BlockRepeater.class, "delay"); - private static final net.minecraft.server.BlockStateBoolean LOCKED = getBoolean(net.minecraft.server.BlockRepeater.class, "locked"); - - @Override - public int getDelay() { - return get(DELAY); - } - - @Override - public void setDelay(int delay) { - set(DELAY, delay); - } - - @Override - public int getMinimumDelay() { - return getMin(DELAY); - } - - @Override - public int getMaximumDelay() { - return getMax(DELAY); - } - - @Override - public boolean isLocked() { - return get(LOCKED); - } - - @Override - public void setLocked(boolean locked) { - set(LOCKED, locked); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockRepeater.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockRepeater.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRotatable.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRotatable.java deleted file mode 100644 index c44f23e64..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftRotatable.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftRotatable extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Orientable { - - public CraftRotatable() { - super(); - } - - public CraftRotatable(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftOrientable - - private static final net.minecraft.server.BlockStateEnum AXIS = getEnum(net.minecraft.server.BlockRotatable.class, "axis"); - - @Override - public org.bukkit.Axis getAxis() { - return get(AXIS, org.bukkit.Axis.class); - } - - @Override - public void setAxis(org.bukkit.Axis axis) { - set(AXIS, axis); - } - - @Override - public java.util.Set getAxes() { - return getValues(AXIS, org.bukkit.Axis.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSapling.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSapling.java deleted file mode 100644 index 0654c9e7b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSapling.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSapling extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Sapling { - - public CraftSapling() { - super(); - } - - public CraftSapling(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftSapling - - private static final net.minecraft.server.BlockStateInteger STAGE = getInteger(net.minecraft.server.BlockSapling.class, "stage"); - - @Override - public int getStage() { - return get(STAGE); - } - - @Override - public void setStage(int stage) { - set(STAGE, stage); - } - - @Override - public int getMaximumStage() { - return getMax(STAGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftScaffolding.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftScaffolding.java deleted file mode 100644 index 857e4d1fc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftScaffolding.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftScaffolding extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Scaffolding, org.bukkit.block.data.Waterlogged { - - public CraftScaffolding() { - super(); - } - - public CraftScaffolding(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftScaffolding - - private static final net.minecraft.server.BlockStateBoolean BOTTOM = getBoolean(net.minecraft.server.BlockScaffolding.class, "bottom"); - private static final net.minecraft.server.BlockStateInteger DISTANCE = getInteger(net.minecraft.server.BlockScaffolding.class, "distance"); - - @Override - public boolean isBottom() { - return get(BOTTOM); - } - - @Override - public void setBottom(boolean bottom) { - set(BOTTOM, bottom); - } - - @Override - public int getDistance() { - return get(DISTANCE); - } - - @Override - public void setDistance(int distance) { - set(DISTANCE, distance); - } - - @Override - public int getMaximumDistance() { - return getMax(DISTANCE); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockScaffolding.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSeaPickle.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSeaPickle.java deleted file mode 100644 index a0078bd8b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSeaPickle.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSeaPickle extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.SeaPickle, org.bukkit.block.data.Waterlogged { - - public CraftSeaPickle() { - super(); - } - - public CraftSeaPickle(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftSeaPickle - - private static final net.minecraft.server.BlockStateInteger PICKLES = getInteger(net.minecraft.server.BlockSeaPickle.class, "pickles"); - - @Override - public int getPickles() { - return get(PICKLES); - } - - @Override - public void setPickles(int pickles) { - set(PICKLES, pickles); - } - - @Override - public int getMinimumPickles() { - return getMin(PICKLES); - } - - @Override - public int getMaximumPickles() { - return getMax(PICKLES); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockSeaPickle.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftShulkerBox.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftShulkerBox.java deleted file mode 100644 index 631f5cffb..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftShulkerBox.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftShulkerBox extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftShulkerBox() { - super(); - } - - public CraftShulkerBox(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockShulkerBox.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkull.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkull.java deleted file mode 100644 index 5677a9f0b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkull.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSkull extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Rotatable { - - public CraftSkull() { - super(); - } - - public CraftSkull(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftRotatable - - private static final net.minecraft.server.BlockStateInteger ROTATION = getInteger(net.minecraft.server.BlockSkull.class, "rotation"); - - @Override - public org.bukkit.block.BlockFace getRotation() { - int data = get(ROTATION); - switch (data) { - case 0x0: - return org.bukkit.block.BlockFace.SOUTH; - case 0x1: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_WEST; - case 0x2: - return org.bukkit.block.BlockFace.SOUTH_WEST; - case 0x3: - return org.bukkit.block.BlockFace.WEST_SOUTH_WEST; - case 0x4: - return org.bukkit.block.BlockFace.WEST; - case 0x5: - return org.bukkit.block.BlockFace.WEST_NORTH_WEST; - case 0x6: - return org.bukkit.block.BlockFace.NORTH_WEST; - case 0x7: - return org.bukkit.block.BlockFace.NORTH_NORTH_WEST; - case 0x8: - return org.bukkit.block.BlockFace.NORTH; - case 0x9: - return org.bukkit.block.BlockFace.NORTH_NORTH_EAST; - case 0xA: - return org.bukkit.block.BlockFace.NORTH_EAST; - case 0xB: - return org.bukkit.block.BlockFace.EAST_NORTH_EAST; - case 0xC: - return org.bukkit.block.BlockFace.EAST; - case 0xD: - return org.bukkit.block.BlockFace.EAST_SOUTH_EAST; - case 0xE: - return org.bukkit.block.BlockFace.SOUTH_EAST; - case 0xF: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_EAST; - default: - throw new IllegalArgumentException("Unknown rotation " + data); - } - } - - @Override - public void setRotation(org.bukkit.block.BlockFace rotation) { - int val; - switch (rotation) { - case SOUTH: - val = 0x0; - break; - case SOUTH_SOUTH_WEST: - val = 0x1; - break; - case SOUTH_WEST: - val = 0x2; - break; - case WEST_SOUTH_WEST: - val = 0x3; - break; - case WEST: - val = 0x4; - break; - case WEST_NORTH_WEST: - val = 0x5; - break; - case NORTH_WEST: - val = 0x6; - break; - case NORTH_NORTH_WEST: - val = 0x7; - break; - case NORTH: - val = 0x8; - break; - case NORTH_NORTH_EAST: - val = 0x9; - break; - case NORTH_EAST: - val = 0xA; - break; - case EAST_NORTH_EAST: - val = 0xB; - break; - case EAST: - val = 0xC; - break; - case EAST_SOUTH_EAST: - val = 0xD; - break; - case SOUTH_EAST: - val = 0xE; - break; - case SOUTH_SOUTH_EAST: - val = 0xF; - break; - default: - throw new IllegalArgumentException("Illegal rotation " + rotation); - } - set(ROTATION, val); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayer.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayer.java deleted file mode 100644 index 6e6e0033f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayer.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSkullPlayer extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Rotatable { - - public CraftSkullPlayer() { - super(); - } - - public CraftSkullPlayer(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftRotatable - - private static final net.minecraft.server.BlockStateInteger ROTATION = getInteger(net.minecraft.server.BlockSkullPlayer.class, "rotation"); - - @Override - public org.bukkit.block.BlockFace getRotation() { - int data = get(ROTATION); - switch (data) { - case 0x0: - return org.bukkit.block.BlockFace.SOUTH; - case 0x1: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_WEST; - case 0x2: - return org.bukkit.block.BlockFace.SOUTH_WEST; - case 0x3: - return org.bukkit.block.BlockFace.WEST_SOUTH_WEST; - case 0x4: - return org.bukkit.block.BlockFace.WEST; - case 0x5: - return org.bukkit.block.BlockFace.WEST_NORTH_WEST; - case 0x6: - return org.bukkit.block.BlockFace.NORTH_WEST; - case 0x7: - return org.bukkit.block.BlockFace.NORTH_NORTH_WEST; - case 0x8: - return org.bukkit.block.BlockFace.NORTH; - case 0x9: - return org.bukkit.block.BlockFace.NORTH_NORTH_EAST; - case 0xA: - return org.bukkit.block.BlockFace.NORTH_EAST; - case 0xB: - return org.bukkit.block.BlockFace.EAST_NORTH_EAST; - case 0xC: - return org.bukkit.block.BlockFace.EAST; - case 0xD: - return org.bukkit.block.BlockFace.EAST_SOUTH_EAST; - case 0xE: - return org.bukkit.block.BlockFace.SOUTH_EAST; - case 0xF: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_EAST; - default: - throw new IllegalArgumentException("Unknown rotation " + data); - } - } - - @Override - public void setRotation(org.bukkit.block.BlockFace rotation) { - int val; - switch (rotation) { - case SOUTH: - val = 0x0; - break; - case SOUTH_SOUTH_WEST: - val = 0x1; - break; - case SOUTH_WEST: - val = 0x2; - break; - case WEST_SOUTH_WEST: - val = 0x3; - break; - case WEST: - val = 0x4; - break; - case WEST_NORTH_WEST: - val = 0x5; - break; - case NORTH_WEST: - val = 0x6; - break; - case NORTH_NORTH_WEST: - val = 0x7; - break; - case NORTH: - val = 0x8; - break; - case NORTH_NORTH_EAST: - val = 0x9; - break; - case NORTH_EAST: - val = 0xA; - break; - case EAST_NORTH_EAST: - val = 0xB; - break; - case EAST: - val = 0xC; - break; - case EAST_SOUTH_EAST: - val = 0xD; - break; - case SOUTH_EAST: - val = 0xE; - break; - case SOUTH_SOUTH_EAST: - val = 0xF; - break; - default: - throw new IllegalArgumentException("Illegal rotation " + rotation); - } - set(ROTATION, val); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayerWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayerWall.java deleted file mode 100644 index d2b3ce935..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullPlayerWall.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSkullPlayerWall extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftSkullPlayerWall() { - super(); - } - - public CraftSkullPlayerWall(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockSkullPlayerWall.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullWall.java deleted file mode 100644 index 020e5b715..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSkullWall.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSkullWall extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftSkullWall() { - super(); - } - - public CraftSkullWall(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockSkullWall.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmoker.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmoker.java deleted file mode 100644 index c14aed35c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSmoker.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSmoker extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Furnace, org.bukkit.block.data.Directional, org.bukkit.block.data.Lightable { - - public CraftSmoker() { - super(); - } - - public CraftSmoker(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockSmoker.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftLightable - - private static final net.minecraft.server.BlockStateBoolean LIT = getBoolean(net.minecraft.server.BlockSmoker.class, "lit"); - - @Override - public boolean isLit() { - return get(LIT); - } - - @Override - public void setLit(boolean lit) { - set(LIT, lit); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnow.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnow.java deleted file mode 100644 index d4f0bfa80..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSnow.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSnow extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Snow { - - public CraftSnow() { - super(); - } - - public CraftSnow(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftSnow - - private static final net.minecraft.server.BlockStateInteger LAYERS = getInteger(net.minecraft.server.BlockSnow.class, "layers"); - - @Override - public int getLayers() { - return get(LAYERS); - } - - @Override - public void setLayers(int layers) { - set(LAYERS, layers); - } - - @Override - public int getMinimumLayers() { - return getMin(LAYERS); - } - - @Override - public int getMaximumLayers() { - return getMax(LAYERS); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSoil.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSoil.java deleted file mode 100644 index 09cfa4671..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSoil.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSoil extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Farmland { - - public CraftSoil() { - super(); - } - - public CraftSoil(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftFarmland - - private static final net.minecraft.server.BlockStateInteger MOISTURE = getInteger(net.minecraft.server.BlockSoil.class, "moisture"); - - @Override - public int getMoisture() { - return get(MOISTURE); - } - - @Override - public void setMoisture(int moisture) { - set(MOISTURE, moisture); - } - - @Override - public int getMaximumMoisture() { - return getMax(MOISTURE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStainedGlassPane.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStainedGlassPane.java deleted file mode 100644 index 0eb5c6607..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStainedGlassPane.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftStainedGlassPane extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.GlassPane, org.bukkit.block.data.MultipleFacing, org.bukkit.block.data.Waterlogged { - - public CraftStainedGlassPane() { - super(); - } - - public CraftStainedGlassPane(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockStainedGlassPane.class, "north", true), getBoolean(net.minecraft.server.BlockStainedGlassPane.class, "east", true), getBoolean(net.minecraft.server.BlockStainedGlassPane.class, "south", true), getBoolean(net.minecraft.server.BlockStainedGlassPane.class, "west", true), getBoolean(net.minecraft.server.BlockStainedGlassPane.class, "up", true), getBoolean(net.minecraft.server.BlockStainedGlassPane.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockStainedGlassPane.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStairs.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStairs.java deleted file mode 100644 index 804a90f21..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStairs.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftStairs extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Stairs, org.bukkit.block.data.Bisected, org.bukkit.block.data.Directional, org.bukkit.block.data.Waterlogged { - - public CraftStairs() { - super(); - } - - public CraftStairs(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftStairs - - private static final net.minecraft.server.BlockStateEnum SHAPE = getEnum(net.minecraft.server.BlockStairs.class, "shape"); - - @Override - public Shape getShape() { - return get(SHAPE, Shape.class); - } - - @Override - public void setShape(Shape shape) { - set(SHAPE, shape); - } - - // org.bukkit.craftbukkit.block.data.CraftBisected - - private static final net.minecraft.server.BlockStateEnum HALF = getEnum(net.minecraft.server.BlockStairs.class, "half"); - - @Override - public Half getHalf() { - return get(HALF, Half.class); - } - - @Override - public void setHalf(Half half) { - set(HALF, half); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockStairs.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockStairs.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStem.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStem.java deleted file mode 100644 index 2a91e9582..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStem.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftStem extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftStem() { - super(); - } - - public CraftStem(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockStem.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStemAttached.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStemAttached.java deleted file mode 100644 index c6d9223d1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStemAttached.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftStemAttached extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftStemAttached() { - super(); - } - - public CraftStemAttached(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockStemAttached.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStepAbstract.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStepAbstract.java deleted file mode 100644 index 922d41b1a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStepAbstract.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftStepAbstract extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Slab, org.bukkit.block.data.Waterlogged { - - public CraftStepAbstract() { - super(); - } - - public CraftStepAbstract(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftSlab - - private static final net.minecraft.server.BlockStateEnum TYPE = getEnum(net.minecraft.server.BlockStepAbstract.class, "type"); - - @Override - public Type getType() { - return get(TYPE, Type.class); - } - - @Override - public void setType(Type type) { - set(TYPE, type); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockStepAbstract.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStoneButton.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStoneButton.java deleted file mode 100644 index 84097d5ef..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStoneButton.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftStoneButton extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Switch, org.bukkit.block.data.Directional, org.bukkit.block.data.Powerable { - - public CraftStoneButton() { - super(); - } - - public CraftStoneButton(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftSwitch - - private static final net.minecraft.server.BlockStateEnum FACE = getEnum(net.minecraft.server.BlockStoneButton.class, "face"); - - @Override - public Face getFace() { - return get(FACE, Face.class); - } - - @Override - public void setFace(Face face) { - set(FACE, face); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockStoneButton.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockStoneButton.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStonecutter.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStonecutter.java deleted file mode 100644 index 7a2789eb7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStonecutter.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftStonecutter extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftStonecutter() { - super(); - } - - public CraftStonecutter(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockStonecutter.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStructure.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStructure.java deleted file mode 100644 index f2435d34e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftStructure.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftStructure extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.StructureBlock { - - public CraftStructure() { - super(); - } - - public CraftStructure(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftStructureBlock - - private static final net.minecraft.server.BlockStateEnum MODE = getEnum(net.minecraft.server.BlockStructure.class, "mode"); - - @Override - public Mode getMode() { - return get(MODE, Mode.class); - } - - @Override - public void setMode(Mode mode) { - set(MODE, mode); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSweetBerryBush.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSweetBerryBush.java deleted file mode 100644 index 2733a067e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftSweetBerryBush.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftSweetBerryBush extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable { - - public CraftSweetBerryBush() { - super(); - } - - public CraftSweetBerryBush(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAgeable - - private static final net.minecraft.server.BlockStateInteger AGE = getInteger(net.minecraft.server.BlockSweetBerryBush.class, "age"); - - @Override - public int getAge() { - return get(AGE); - } - - @Override - public void setAge(int age) { - set(AGE, age); - } - - @Override - public int getMaximumAge() { - return getMax(AGE); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTNT.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTNT.java deleted file mode 100644 index cf9c33b82..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTNT.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTNT extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.TNT { - - public CraftTNT() { - super(); - } - - public CraftTNT(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftTNT - - private static final net.minecraft.server.BlockStateBoolean UNSTABLE = getBoolean(net.minecraft.server.BlockTNT.class, "unstable"); - - @Override - public boolean isUnstable() { - return get(UNSTABLE); - } - - @Override - public void setUnstable(boolean unstable) { - set(UNSTABLE, unstable); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlant.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlant.java deleted file mode 100644 index 0ed0ad0cf..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlant.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTallPlant extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Bisected { - - public CraftTallPlant() { - super(); - } - - public CraftTallPlant(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftBisected - - private static final net.minecraft.server.BlockStateEnum HALF = getEnum(net.minecraft.server.BlockTallPlant.class, "half"); - - @Override - public Half getHalf() { - return get(HALF, Half.class); - } - - @Override - public void setHalf(Half half) { - set(HALF, half); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlantFlower.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlantFlower.java deleted file mode 100644 index 3ae8201c4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallPlantFlower.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTallPlantFlower extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Bisected { - - public CraftTallPlantFlower() { - super(); - } - - public CraftTallPlantFlower(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftBisected - - private static final net.minecraft.server.BlockStateEnum HALF = getEnum(net.minecraft.server.BlockTallPlantFlower.class, "half"); - - @Override - public Half getHalf() { - return get(HALF, Half.class); - } - - @Override - public void setHalf(Half half) { - set(HALF, half); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallSeaGrass.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallSeaGrass.java deleted file mode 100644 index d51e3ec4d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTallSeaGrass.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTallSeaGrass extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Bisected { - - public CraftTallSeaGrass() { - super(); - } - - public CraftTallSeaGrass(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftBisected - - private static final net.minecraft.server.BlockStateEnum HALF = getEnum(net.minecraft.server.BlockTallSeaGrass.class, "half"); - - @Override - public Half getHalf() { - return get(HALF, Half.class); - } - - @Override - public void setHalf(Half half) { - set(HALF, half); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchWall.java deleted file mode 100644 index d98f21aaf..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTorchWall.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTorchWall extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftTorchWall() { - super(); - } - - public CraftTorchWall(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockTorchWall.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrapdoor.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrapdoor.java deleted file mode 100644 index 2ec18b29c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTrapdoor.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTrapdoor extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.TrapDoor, org.bukkit.block.data.Bisected, org.bukkit.block.data.Directional, org.bukkit.block.data.Openable, org.bukkit.block.data.Powerable, org.bukkit.block.data.Waterlogged { - - public CraftTrapdoor() { - super(); - } - - public CraftTrapdoor(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftBisected - - private static final net.minecraft.server.BlockStateEnum HALF = getEnum(net.minecraft.server.BlockTrapdoor.class, "half"); - - @Override - public Half getHalf() { - return get(HALF, Half.class); - } - - @Override - public void setHalf(Half half) { - set(HALF, half); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockTrapdoor.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftOpenable - - private static final net.minecraft.server.BlockStateBoolean OPEN = getBoolean(net.minecraft.server.BlockTrapdoor.class, "open"); - - @Override - public boolean isOpen() { - return get(OPEN); - } - - @Override - public void setOpen(boolean open) { - set(OPEN, open); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockTrapdoor.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockTrapdoor.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwire.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwire.java deleted file mode 100644 index e39e79c42..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwire.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTripwire extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Tripwire, org.bukkit.block.data.Attachable, org.bukkit.block.data.MultipleFacing, org.bukkit.block.data.Powerable { - - public CraftTripwire() { - super(); - } - - public CraftTripwire(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftTripwire - - private static final net.minecraft.server.BlockStateBoolean DISARMED = getBoolean(net.minecraft.server.BlockTripwire.class, "disarmed"); - - @Override - public boolean isDisarmed() { - return get(DISARMED); - } - - @Override - public void setDisarmed(boolean disarmed) { - set(DISARMED, disarmed); - } - - // org.bukkit.craftbukkit.block.data.CraftAttachable - - private static final net.minecraft.server.BlockStateBoolean ATTACHED = getBoolean(net.minecraft.server.BlockTripwire.class, "attached"); - - @Override - public boolean isAttached() { - return get(ATTACHED); - } - - @Override - public void setAttached(boolean attached) { - set(ATTACHED, attached); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockTripwire.class, "north", true), getBoolean(net.minecraft.server.BlockTripwire.class, "east", true), getBoolean(net.minecraft.server.BlockTripwire.class, "south", true), getBoolean(net.minecraft.server.BlockTripwire.class, "west", true), getBoolean(net.minecraft.server.BlockTripwire.class, "up", true), getBoolean(net.minecraft.server.BlockTripwire.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockTripwire.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwireHook.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwireHook.java deleted file mode 100644 index bd7b43ade..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTripwireHook.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTripwireHook extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.TripwireHook, org.bukkit.block.data.Attachable, org.bukkit.block.data.Directional, org.bukkit.block.data.Powerable { - - public CraftTripwireHook() { - super(); - } - - public CraftTripwireHook(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftAttachable - - private static final net.minecraft.server.BlockStateBoolean ATTACHED = getBoolean(net.minecraft.server.BlockTripwireHook.class, "attached"); - - @Override - public boolean isAttached() { - return get(ATTACHED); - } - - @Override - public void setAttached(boolean attached) { - set(ATTACHED, attached); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockTripwireHook.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockTripwireHook.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTurtleEgg.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTurtleEgg.java deleted file mode 100644 index 64812ad12..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftTurtleEgg.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftTurtleEgg extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.TurtleEgg { - - public CraftTurtleEgg() { - super(); - } - - public CraftTurtleEgg(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftTurtleEgg - - private static final net.minecraft.server.BlockStateInteger EGGS = getInteger(net.minecraft.server.BlockTurtleEgg.class, "eggs"); - private static final net.minecraft.server.BlockStateInteger HATCH = getInteger(net.minecraft.server.BlockTurtleEgg.class, "hatch"); - - @Override - public int getEggs() { - return get(EGGS); - } - - @Override - public void setEggs(int eggs) { - set(EGGS, eggs); - } - - @Override - public int getMinimumEggs() { - return getMin(EGGS); - } - - @Override - public int getMaximumEggs() { - return getMax(EGGS); - } - - @Override - public int getHatch() { - return get(HATCH); - } - - @Override - public void setHatch(int hatch) { - set(HATCH, hatch); - } - - @Override - public int getMaximumHatch() { - return getMax(HATCH); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVine.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVine.java deleted file mode 100644 index 90e025cef..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftVine.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftVine extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.MultipleFacing { - - public CraftVine() { - super(); - } - - public CraftVine(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftMultipleFacing - - private static final net.minecraft.server.BlockStateBoolean[] FACES = new net.minecraft.server.BlockStateBoolean[]{ - getBoolean(net.minecraft.server.BlockVine.class, "north", true), getBoolean(net.minecraft.server.BlockVine.class, "east", true), getBoolean(net.minecraft.server.BlockVine.class, "south", true), getBoolean(net.minecraft.server.BlockVine.class, "west", true), getBoolean(net.minecraft.server.BlockVine.class, "up", true), getBoolean(net.minecraft.server.BlockVine.class, "down", true) - }; - - @Override - public boolean hasFace(org.bukkit.block.BlockFace face) { - return get(FACES[face.ordinal()]); - } - - @Override - public void setFace(org.bukkit.block.BlockFace face, boolean has) { - set(FACES[face.ordinal()], has); - } - - @Override - public java.util.Set getFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null && get(FACES[i])) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } - - @Override - public java.util.Set getAllowedFaces() { - com.google.common.collect.ImmutableSet.Builder faces = com.google.common.collect.ImmutableSet.builder(); - - for (int i = 0; i < FACES.length; i++) { - if (FACES[i] != null) { - faces.add(org.bukkit.block.BlockFace.values()[i]); - } - } - - return faces.build(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallSign.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallSign.java deleted file mode 100644 index ffa7e3c4b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWallSign.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftWallSign extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.WallSign, org.bukkit.block.data.Directional, org.bukkit.block.data.Waterlogged { - - public CraftWallSign() { - super(); - } - - public CraftWallSign(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockWallSign.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftWaterlogged - - private static final net.minecraft.server.BlockStateBoolean WATERLOGGED = getBoolean(net.minecraft.server.BlockWallSign.class, "waterlogged"); - - @Override - public boolean isWaterlogged() { - return get(WATERLOGGED); - } - - @Override - public void setWaterlogged(boolean waterlogged) { - set(WATERLOGGED, waterlogged); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkull.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkull.java deleted file mode 100644 index 0aec1dbed..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkull.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftWitherSkull extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Rotatable { - - public CraftWitherSkull() { - super(); - } - - public CraftWitherSkull(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftRotatable - - private static final net.minecraft.server.BlockStateInteger ROTATION = getInteger(net.minecraft.server.BlockWitherSkull.class, "rotation"); - - @Override - public org.bukkit.block.BlockFace getRotation() { - int data = get(ROTATION); - switch (data) { - case 0x0: - return org.bukkit.block.BlockFace.SOUTH; - case 0x1: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_WEST; - case 0x2: - return org.bukkit.block.BlockFace.SOUTH_WEST; - case 0x3: - return org.bukkit.block.BlockFace.WEST_SOUTH_WEST; - case 0x4: - return org.bukkit.block.BlockFace.WEST; - case 0x5: - return org.bukkit.block.BlockFace.WEST_NORTH_WEST; - case 0x6: - return org.bukkit.block.BlockFace.NORTH_WEST; - case 0x7: - return org.bukkit.block.BlockFace.NORTH_NORTH_WEST; - case 0x8: - return org.bukkit.block.BlockFace.NORTH; - case 0x9: - return org.bukkit.block.BlockFace.NORTH_NORTH_EAST; - case 0xA: - return org.bukkit.block.BlockFace.NORTH_EAST; - case 0xB: - return org.bukkit.block.BlockFace.EAST_NORTH_EAST; - case 0xC: - return org.bukkit.block.BlockFace.EAST; - case 0xD: - return org.bukkit.block.BlockFace.EAST_SOUTH_EAST; - case 0xE: - return org.bukkit.block.BlockFace.SOUTH_EAST; - case 0xF: - return org.bukkit.block.BlockFace.SOUTH_SOUTH_EAST; - default: - throw new IllegalArgumentException("Unknown rotation " + data); - } - } - - @Override - public void setRotation(org.bukkit.block.BlockFace rotation) { - int val; - switch (rotation) { - case SOUTH: - val = 0x0; - break; - case SOUTH_SOUTH_WEST: - val = 0x1; - break; - case SOUTH_WEST: - val = 0x2; - break; - case WEST_SOUTH_WEST: - val = 0x3; - break; - case WEST: - val = 0x4; - break; - case WEST_NORTH_WEST: - val = 0x5; - break; - case NORTH_WEST: - val = 0x6; - break; - case NORTH_NORTH_WEST: - val = 0x7; - break; - case NORTH: - val = 0x8; - break; - case NORTH_NORTH_EAST: - val = 0x9; - break; - case NORTH_EAST: - val = 0xA; - break; - case EAST_NORTH_EAST: - val = 0xB; - break; - case EAST: - val = 0xC; - break; - case EAST_SOUTH_EAST: - val = 0xD; - break; - case SOUTH_EAST: - val = 0xE; - break; - case SOUTH_SOUTH_EAST: - val = 0xF; - break; - default: - throw new IllegalArgumentException("Illegal rotation " + rotation); - } - set(ROTATION, val); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkullWall.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkullWall.java deleted file mode 100644 index fa9597da2..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWitherSkullWall.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftWitherSkullWall extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Directional { - - public CraftWitherSkullWall() { - super(); - } - - public CraftWitherSkullWall(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockWitherSkullWall.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWoodButton.java b/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWoodButton.java deleted file mode 100644 index 799714178..000000000 --- a/src/main/java/org/bukkit/craftbukkit/block/impl/CraftWoodButton.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Automatically generated file, changes will be lost. - */ -package org.bukkit.craftbukkit.block.impl; - -public final class CraftWoodButton extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.type.Switch, org.bukkit.block.data.Directional, org.bukkit.block.data.Powerable { - - public CraftWoodButton() { - super(); - } - - public CraftWoodButton(net.minecraft.server.IBlockData state) { - super(state); - } - - // org.bukkit.craftbukkit.block.data.type.CraftSwitch - - private static final net.minecraft.server.BlockStateEnum FACE = getEnum(net.minecraft.server.BlockWoodButton.class, "face"); - - @Override - public Face getFace() { - return get(FACE, Face.class); - } - - @Override - public void setFace(Face face) { - set(FACE, face); - } - - // org.bukkit.craftbukkit.block.data.CraftDirectional - - private static final net.minecraft.server.BlockStateEnum FACING = getEnum(net.minecraft.server.BlockWoodButton.class, "facing"); - - @Override - public org.bukkit.block.BlockFace getFacing() { - return get(FACING, org.bukkit.block.BlockFace.class); - } - - @Override - public void setFacing(org.bukkit.block.BlockFace facing) { - set(FACING, facing); - } - - @Override - public java.util.Set getFaces() { - return getValues(FACING, org.bukkit.block.BlockFace.class); - } - - // org.bukkit.craftbukkit.block.data.CraftPowerable - - private static final net.minecraft.server.BlockStateBoolean POWERED = getBoolean(net.minecraft.server.BlockWoodButton.class, "powered"); - - @Override - public boolean isPowered() { - return get(POWERED); - } - - @Override - public void setPowered(boolean powered) { - set(POWERED, powered); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/boss/CraftBossBar.java b/src/main/java/org/bukkit/craftbukkit/boss/CraftBossBar.java deleted file mode 100644 index d1033d73d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/boss/CraftBossBar.java +++ /dev/null @@ -1,227 +0,0 @@ -package org.bukkit.craftbukkit.boss; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Supplier; -import net.minecraft.server.BossBattle; -import net.minecraft.server.BossBattleServer; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.PacketPlayOutBoss; -import org.bukkit.boss.BarColor; -import org.bukkit.boss.BarFlag; -import org.bukkit.boss.BarStyle; -import org.bukkit.boss.BossBar; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.entity.Player; - -public class CraftBossBar implements BossBar { - - private final BossBattleServer handle; - private Map flags; - - public CraftBossBar(String title, BarColor color, BarStyle style, BarFlag... flags) { - handle = new BossBattleServer( - CraftChatMessage.fromString(title, true)[0], - convertColor(color), - convertStyle(style) - ); - - this.initialize(); - - for (BarFlag flag : flags) { - this.addFlag(flag); - } - - this.setColor(color); - this.setStyle(style); - } - - public CraftBossBar(BossBattleServer bossBattleServer) { - this.handle = bossBattleServer; - this.initialize(); - } - - private void initialize() { - this.flags = new HashMap<>(); - this.flags.put(BarFlag.DARKEN_SKY, new FlagContainer(handle::isDarkenSky, handle::setDarkenSky)); - this.flags.put(BarFlag.PLAY_BOSS_MUSIC, new FlagContainer(handle::isPlayMusic, handle::setPlayMusic)); - this.flags.put(BarFlag.CREATE_FOG, new FlagContainer(handle::isCreateFog, handle::setCreateFog)); - } - - private BarColor convertColor(BossBattle.BarColor color) { - BarColor bukkitColor = BarColor.valueOf(color.name()); - return (bukkitColor == null) ? BarColor.WHITE : bukkitColor; - } - - private BossBattle.BarColor convertColor(BarColor color) { - BossBattle.BarColor nmsColor = BossBattle.BarColor.valueOf(color.name()); - return (nmsColor == null) ? BossBattle.BarColor.WHITE : nmsColor; - } - - private BossBattle.BarStyle convertStyle(BarStyle style) { - switch (style) { - default: - case SOLID: - return BossBattle.BarStyle.PROGRESS; - case SEGMENTED_6: - return BossBattle.BarStyle.NOTCHED_6; - case SEGMENTED_10: - return BossBattle.BarStyle.NOTCHED_10; - case SEGMENTED_12: - return BossBattle.BarStyle.NOTCHED_12; - case SEGMENTED_20: - return BossBattle.BarStyle.NOTCHED_20; - } - } - - private BarStyle convertStyle(BossBattle.BarStyle style) { - switch (style) { - default: - case PROGRESS: - return BarStyle.SOLID; - case NOTCHED_6: - return BarStyle.SEGMENTED_6; - case NOTCHED_10: - return BarStyle.SEGMENTED_10; - case NOTCHED_12: - return BarStyle.SEGMENTED_12; - case NOTCHED_20: - return BarStyle.SEGMENTED_20; - } - } - - @Override - public String getTitle() { - return CraftChatMessage.fromComponent(handle.title); - } - - @Override - public void setTitle(String title) { - handle.title = CraftChatMessage.fromString(title, true)[0]; - handle.sendUpdate(PacketPlayOutBoss.Action.UPDATE_NAME); - } - - @Override - public BarColor getColor() { - return convertColor(handle.color); - } - - @Override - public void setColor(BarColor color) { - handle.color = convertColor(color); - handle.sendUpdate(PacketPlayOutBoss.Action.UPDATE_STYLE); - } - - @Override - public BarStyle getStyle() { - return convertStyle(handle.style); - } - - @Override - public void setStyle(BarStyle style) { - handle.style = convertStyle(style); - handle.sendUpdate(PacketPlayOutBoss.Action.UPDATE_STYLE); - } - - @Override - public void addFlag(BarFlag flag) { - FlagContainer flagContainer = flags.get(flag); - if (flagContainer != null) { - flagContainer.set.accept(true); - } - } - - @Override - public void removeFlag(BarFlag flag) { - FlagContainer flagContainer = flags.get(flag); - if (flagContainer != null) { - flagContainer.set.accept(false); - } - } - - @Override - public boolean hasFlag(BarFlag flag) { - FlagContainer flagContainer = flags.get(flag); - if (flagContainer != null) { - return flagContainer.get.get(); - } - return false; - } - - @Override - public void setProgress(double progress) { - Preconditions.checkArgument(progress >= 0.0 && progress <= 1.0, "Progress must be between 0.0 and 1.0 (%s)", progress); - handle.setProgress((float) progress); - } - - @Override - public double getProgress() { - return handle.getProgress(); - } - - @Override - public void addPlayer(Player player) { - handle.addPlayer(((CraftPlayer) player).getHandle()); - } - - @Override - public void removePlayer(Player player) { - handle.removePlayer(((CraftPlayer) player).getHandle()); - } - - @Override - public List getPlayers() { - ImmutableList.Builder players = ImmutableList.builder(); - for (EntityPlayer p : handle.getPlayers()) { - players.add(p.getBukkitEntity()); - } - return players.build(); - } - - @Override - public void setVisible(boolean visible) { - handle.setVisible(visible); - } - - @Override - public boolean isVisible() { - return handle.visible; - } - - @Override - public void show() { - handle.setVisible(true); - } - - @Override - public void hide() { - handle.setVisible(false); - } - - @Override - public void removeAll() { - for (Player player : getPlayers()) { - removePlayer(player); - } - } - - private class FlagContainer { - - private Supplier get; - private Consumer set; - - private FlagContainer(Supplier get, Consumer set) { - this.get = get; - this.set = set; - } - } - - public BossBattleServer getHandle() { - return handle; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/boss/CraftKeyedBossbar.java b/src/main/java/org/bukkit/craftbukkit/boss/CraftKeyedBossbar.java deleted file mode 100644 index e6ad94022..000000000 --- a/src/main/java/org/bukkit/craftbukkit/boss/CraftKeyedBossbar.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.boss; - -import net.minecraft.server.BossBattleCustom; -import org.bukkit.NamespacedKey; -import org.bukkit.boss.KeyedBossBar; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; - -public class CraftKeyedBossbar extends CraftBossBar implements KeyedBossBar { - - public CraftKeyedBossbar(BossBattleCustom bossBattleCustom) { - super(bossBattleCustom); - } - - @Override - public NamespacedKey getKey() { - return CraftNamespacedKey.fromMinecraft(getHandle().getKey()); - } - - @Override - public BossBattleCustom getHandle() { - return (BossBattleCustom) super.getHandle(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/command/BukkitCommandWrapper.java b/src/main/java/org/bukkit/craftbukkit/command/BukkitCommandWrapper.java deleted file mode 100644 index 5f33c9e52..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/BukkitCommandWrapper.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bukkit.craftbukkit.command; - -import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.arguments.StringArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.builder.RequiredArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.suggestion.SuggestionProvider; -import com.mojang.brigadier.suggestion.Suggestions; -import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import com.mojang.brigadier.tree.LiteralCommandNode; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.function.Predicate; -import net.minecraft.server.CommandListenerWrapper; -import org.bukkit.command.Command; -import org.bukkit.craftbukkit.CraftServer; - -public class BukkitCommandWrapper implements com.mojang.brigadier.Command, Predicate, SuggestionProvider { - - private final CraftServer server; - private final Command command; - - public BukkitCommandWrapper(CraftServer server, Command command) { - this.server = server; - this.command = command; - } - - public LiteralCommandNode register(CommandDispatcher dispatcher, String label) { - return dispatcher.register( - LiteralArgumentBuilder.literal(label).requires(this).executes(this) - .then(RequiredArgumentBuilder.argument("args", StringArgumentType.greedyString()).suggests(this).executes(this)) - ); - } - - @Override - public boolean test(CommandListenerWrapper wrapper) { - return command.testPermissionSilent(wrapper.getBukkitSender()); - } - - @Override - public int run(CommandContext context) throws CommandSyntaxException { - return server.dispatchCommand(context.getSource().getBukkitSender(), context.getInput()) ? 1 : 0; - } - - @Override - public CompletableFuture getSuggestions(CommandContext context, SuggestionsBuilder builder) throws CommandSyntaxException { - List results = server.tabComplete(context.getSource().getBukkitSender(), builder.getInput(), context.getSource().getWorld(), context.getSource().getPosition(), true); - - // Defaults to sub nodes, but we have just one giant args node, so offset accordingly - builder = builder.createOffset(builder.getInput().lastIndexOf(' ') + 1); - - for (String s : results) { - builder.suggest(s); - } - - return builder.buildFuture(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java b/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java deleted file mode 100644 index a51202ed5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.bukkit.craftbukkit.command; - -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.logging.Level; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.util.Waitable; - -// Paper start - JLine update -import net.minecraft.server.DedicatedServer; // Paper -import org.jline.reader.Candidate; -import org.jline.reader.Completer; -import org.jline.reader.LineReader; -import org.jline.reader.ParsedLine; -// Paper end -import org.bukkit.event.server.TabCompleteEvent; - -public class ConsoleCommandCompleter implements Completer { - private final DedicatedServer server; // Paper - CraftServer -> DedicatedServer - - public ConsoleCommandCompleter(DedicatedServer server) { // Paper - CraftServer -> DedicatedServer - this.server = server; - } - - // Paper start - Change method signature for JLine update - @Override - public void complete(LineReader reader, ParsedLine line, List candidates) { - final CraftServer server = this.server.server; - final String buffer = line.line(); - // Async Tab Complete - com.destroystokyo.paper.event.server.AsyncTabCompleteEvent event; - java.util.List completions = new java.util.ArrayList<>(); - event = new com.destroystokyo.paper.event.server.AsyncTabCompleteEvent(server.getConsoleSender(), completions, - buffer, true, null); - event.callEvent(); - completions = event.isCancelled() ? com.google.common.collect.ImmutableList.of() : event.getCompletions(); - - if (event.isCancelled() || event.isHandled()) { - // Still fire sync event with the provided completions, if someone is listening - if (!event.isCancelled() && TabCompleteEvent.getHandlerList().getRegisteredListeners().length > 0) { - List finalCompletions = completions; - Waitable> syncCompletions = new Waitable>() { - @Override - protected List evaluate() { - org.bukkit.event.server.TabCompleteEvent syncEvent = new org.bukkit.event.server.TabCompleteEvent(server.getConsoleSender(), buffer, finalCompletions); - return syncEvent.callEvent() ? syncEvent.getCompletions() : com.google.common.collect.ImmutableList.of(); - } - }; - server.getServer().processQueue.add(syncCompletions); - try { - completions = syncCompletions.get(); - } catch (InterruptedException | ExecutionException e1) { - e1.printStackTrace(); - } - } - - if (!completions.isEmpty()) { - candidates.addAll(completions.stream().map(Candidate::new).collect(java.util.stream.Collectors.toList())); - } - return; - } - - // Paper end - Waitable> waitable = new Waitable>() { - @Override - protected List evaluate() { - List offers = server.getCommandMap().tabComplete(server.getConsoleSender(), buffer); - - TabCompleteEvent tabEvent = new TabCompleteEvent(server.getConsoleSender(), buffer, (offers == null) ? Collections.EMPTY_LIST : offers); - server.getPluginManager().callEvent(tabEvent); - - return tabEvent.isCancelled() ? Collections.EMPTY_LIST : tabEvent.getCompletions(); - } - }; - server.getServer().processQueue.add(waitable); // Paper - Remove "this." - try { - List offers = waitable.get(); - if (offers == null) { - return; // Paper - Method returns void - } - - // Paper start - JLine update - for (String completion : offers) { - if (completion.isEmpty()) { - continue; - } - - candidates.add(new Candidate(completion)); - } - // Paper end - - // Paper start - JLine handles cursor now - /* - final int lastSpace = buffer.lastIndexOf(' '); - if (lastSpace == -1) { - return cursor - buffer.length(); - } else { - return cursor - (buffer.length() - lastSpace - 1); - } - */ - // Paper end - } catch (ExecutionException e) { - server.getLogger().log(Level.WARNING, "Unhandled exception when tab completing", e); // Paper - Remove "this." - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java deleted file mode 100644 index 5beb2ad62..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.craftbukkit.command; - -import net.minecraft.server.CommandListenerWrapper; -import net.minecraft.server.IChatBaseComponent; -import net.minecraft.server.TileEntity; -import org.bukkit.block.Block; -import org.bukkit.command.BlockCommandSender; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.util.CraftChatMessage; - -/** - * Represents input from a command block - */ -public class CraftBlockCommandSender extends ServerCommandSender implements BlockCommandSender { - private final CommandListenerWrapper block; - private final TileEntity tile; - - public CraftBlockCommandSender(CommandListenerWrapper commandBlockListenerAbstract, TileEntity tile) { - super(); - this.block = commandBlockListenerAbstract; - this.tile = tile; - } - - @Override - public Block getBlock() { - return CraftBlock.at(tile.getWorld(), tile.getPosition()); - } - - @Override - public void sendMessage(String message) { - for (IChatBaseComponent component : CraftChatMessage.fromString(message)) { - block.base.sendMessage(component); - } - } - - @Override - public void sendMessage(String[] messages) { - for (String message : messages) { - sendMessage(message); - } - } - - @Override - public String getName() { - return block.getName(); - } - - @Override - public boolean isOp() { - return true; - } - - @Override - public void setOp(boolean value) { - throw new UnsupportedOperationException("Cannot change operator status of a block"); - } - - public CommandListenerWrapper getWrapper() { - return block; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftCommandMap.java b/src/main/java/org/bukkit/craftbukkit/command/CraftCommandMap.java deleted file mode 100644 index 2fd69c0f9..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftCommandMap.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.command; - -import java.util.Map; -import org.bukkit.Server; -import org.bukkit.command.Command; -import org.bukkit.command.SimpleCommandMap; - -public class CraftCommandMap extends SimpleCommandMap { - - public CraftCommandMap(Server server) { - super(server); - } - - public Map getKnownCommands() { - return knownCommands; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java deleted file mode 100644 index bfd21a072..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java +++ /dev/null @@ -1,77 +0,0 @@ -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; - -/** - * Represents CLI input from a console - */ -public class CraftConsoleCommandSender extends ServerCommandSender implements ConsoleCommandSender { - - protected final ConversationTracker conversationTracker = new ConversationTracker(); - - protected CraftConsoleCommandSender() { - super(); - } - - @Override - public void sendMessage(String message) { - sendRawMessage(message); - } - - @Override - public void sendRawMessage(String message) { - System.out.println(ChatColor.stripColor(message)); - } - - @Override - public void sendMessage(String[] messages) { - for (String message : messages) { - sendMessage(message); - } - } - - @Override - public String getName() { - return "CONSOLE"; - } - - @Override - public boolean isOp() { - return true; - } - - @Override - public void setOp(boolean value) { - throw new UnsupportedOperationException("Cannot change operator status of server console"); - } - - @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(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java deleted file mode 100644 index 228e88a6e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.craftbukkit.command; - -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.RemoteControlCommandListener; -import org.bukkit.command.RemoteConsoleCommandSender; - -public class CraftRemoteConsoleCommandSender extends ServerCommandSender implements RemoteConsoleCommandSender { - - private final RemoteControlCommandListener listener; - - public CraftRemoteConsoleCommandSender(RemoteControlCommandListener listener) { - this.listener = listener; - } - - @Override - public void sendMessage(String message) { - listener.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); - } - } - - @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/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java deleted file mode 100644 index ce2c5c38c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java +++ /dev/null @@ -1,132 +0,0 @@ - -package org.bukkit.craftbukkit.command; - -import java.util.Set; -import net.minecraft.server.CommandListenerWrapper; -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; - -public class ProxiedNativeCommandSender implements ProxiedCommandSender { - - private final CommandListenerWrapper orig; - private final CommandSender caller; - private final CommandSender callee; - - public ProxiedNativeCommandSender(CommandListenerWrapper orig, CommandSender caller, CommandSender callee) { - this.orig = orig; - this.caller = caller; - this.callee = callee; - } - - public CommandListenerWrapper 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); - } - - @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); - } - - // Spigot start - @Override - public Spigot spigot() - { - return getCaller().spigot(); - } - // Spigot end -} diff --git a/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java deleted file mode 100644 index 9776746a0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.bukkit.craftbukkit.command; - -import java.util.Set; -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; - -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); - } - } - - @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(); - } - - public boolean isPlayer() { - return false; - } - - @Override - public Server getServer() { - return Bukkit.getServer(); - } - - // Spigot start - private final Spigot spigot = new Spigot() - { - @Override - public void sendMessage(net.md_5.bungee.api.chat.BaseComponent component) - { - ServerCommandSender.this.sendMessage(net.md_5.bungee.api.chat.TextComponent.toLegacyText(component)); - } - - @Override - public void sendMessage(net.md_5.bungee.api.chat.BaseComponent... components) - { - ServerCommandSender.this.sendMessage(net.md_5.bungee.api.chat.TextComponent.toLegacyText(components)); - } - }; - - @Override - public Spigot spigot() - { - return spigot; - } - // Spigot end -} diff --git a/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java b/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java deleted file mode 100644 index a3ae4a9ff..000000000 --- a/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.bukkit.craftbukkit.command; - -import com.google.common.base.Joiner; -import com.mojang.brigadier.ParseResults; -import com.mojang.brigadier.tree.CommandNode; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import net.minecraft.server.CommandDispatcher; -import net.minecraft.server.CommandListenerWrapper; -import net.minecraft.server.DedicatedServer; -import net.minecraft.server.EntityMinecartCommandBlock; -import net.minecraft.server.MinecraftServer; -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.command.BlockCommandSender; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.command.ProxiedCommandSender; -import org.bukkit.command.RemoteConsoleCommandSender; -import org.bukkit.command.defaults.BukkitCommand; -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; - -public final class VanillaCommandWrapper extends BukkitCommand { - - private final CommandDispatcher dispatcher; - public final CommandNode vanillaCommand; - - public VanillaCommandWrapper(CommandDispatcher dispatcher, CommandNode vanillaCommand) { - super(vanillaCommand.getName(), "A Mojang provided command.", vanillaCommand.getUsageText(), Collections.EMPTY_LIST); - this.dispatcher = dispatcher; - this.vanillaCommand = vanillaCommand; - this.setPermission(getPermission(vanillaCommand)); - } - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!testPermission(sender)) return true; - - CommandListenerWrapper icommandlistener = getListener(sender); - dispatcher.a(icommandlistener, toDispatcher(args, getName()), toDispatcher(args, commandLabel)); - return true; - } - - @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"); - - CommandListenerWrapper icommandlistener = getListener(sender); - ParseResults parsed = dispatcher.a().parse(toDispatcher(args, getName()), icommandlistener); - - List results = new ArrayList<>(); - dispatcher.a().getCompletionSuggestions(parsed).thenAccept((suggestions) -> { - suggestions.getList().forEach((s) -> results.add(s.getText())); - }); - - return results; - } - - public static CommandListenerWrapper getListener(CommandSender sender) { - if (sender instanceof Player) { - return ((CraftPlayer) sender).getHandle().getCommandListener(); - } - if (sender instanceof BlockCommandSender) { - return ((CraftBlockCommandSender) sender).getWrapper(); - } - if (sender instanceof CommandMinecart) { - return ((EntityMinecartCommandBlock) ((CraftMinecartCommand) sender).getHandle()).getCommandBlock().getWrapper(); - } - if (sender instanceof RemoteConsoleCommandSender) { - return ((DedicatedServer) MinecraftServer.getServer()).remoteControlCommandListener.getWrapper(); - } - if (sender instanceof ConsoleCommandSender) { - return ((CraftServer) sender.getServer()).getServer().getServerCommandListener(); - } - if (sender instanceof ProxiedCommandSender) { - return ((ProxiedNativeCommandSender) sender).getHandle(); - } - - throw new IllegalArgumentException("Cannot make " + sender + " a vanilla command listener"); - } - - public static String getPermission(CommandNode vanillaCommand) { - return "minecraft.command." + ((vanillaCommand.getRedirect() == null) ? vanillaCommand.getName() : vanillaCommand.getRedirect().getName()); - } - - private String toDispatcher(String[] args, String name) { - return "/" + name + ((args.length > 0) ? " " + Joiner.on(' ').join(args) : ""); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java b/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java deleted file mode 100644 index 72127dde5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.bukkit.craftbukkit.conversations; - -import java.util.LinkedList; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.conversations.Conversation; -import org.bukkit.conversations.ConversationAbandonedEvent; -import org.bukkit.conversations.ManuallyAbandonedConversationCanceller; - -/** - */ -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); - } - if (conversationQueue.contains(conversation)) { - 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()) { - Conversation conversation = conversationQueue.getFirst(); - try { - conversation.acceptInput(input); - } catch (Throwable t) { - conversation.getContext().getPlugin().getLogger().log(Level.WARNING, - String.format("Plugin %s generated an exception whilst handling conversation input", - conversation.getContext().getPlugin().getDescription().getFullName() - ), t); - } - } - } - - public synchronized boolean isConversing() { - return !conversationQueue.isEmpty(); - } - - public synchronized boolean isConversingModaly() { - return isConversing() && conversationQueue.getFirst().isModal(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java b/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java deleted file mode 100644 index 64ceeda1a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.bukkit.craftbukkit.enchantments; - -import net.minecraft.server.EnchantmentBinding; -import net.minecraft.server.EnchantmentVanishing; -import net.minecraft.server.IRegistry; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -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(CraftNamespacedKey.fromMinecraft(IRegistry.ENCHANTMENT.getKey(target))); - this.target = target; - } - - @Override - public int getMaxLevel() { - return target.getMaxLevel(); - } - - @Override - public int getStartLevel() { - return target.getStartLevel(); - } - - @Override - public EnchantmentTarget getItemTarget() { - switch (target.itemTarget) { - 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_CHEST: - 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; - case BREAKABLE: - return EnchantmentTarget.BREAKABLE; - case WEARABLE: - return EnchantmentTarget.WEARABLE; - case TRIDENT: - return EnchantmentTarget.TRIDENT; - case CROSSBOW: - return EnchantmentTarget.CROSSBOW; - default: - return null; - } - } - - @Override - public boolean isTreasure() { - return target.isTreasure(); - } - - @Override - public boolean isCursed() { - return target instanceof EnchantmentBinding || target instanceof EnchantmentVanishing; - } - - @Override - public boolean canEnchantItem(ItemStack item) { - return target.canEnchant(CraftItemStack.asNMSCopy(item)); - } - - @Override - public String getName() { - // PAIL: migration paths - switch (IRegistry.ENCHANTMENT.a(target)) { - 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 9: - return "FROST_WALKER"; - case 10: - return "BINDING_CURSE"; - case 11: - return "DAMAGE_ALL"; - case 12: - return "DAMAGE_UNDEAD"; - case 13: - return "DAMAGE_ARTHROPODS"; - case 14: - return "KNOCKBACK"; - case 15: - return "FIRE_ASPECT"; - case 16: - return "LOOT_BONUS_MOBS"; - case 17: - return "SWEEPING_EDGE"; - case 18: - return "DIG_SPEED"; - case 19: - return "SILK_TOUCH"; - case 20: - return "DURABILITY"; - case 21: - return "LOOT_BONUS_BLOCKS"; - case 22: - return "ARROW_DAMAGE"; - case 23: - return "ARROW_KNOCKBACK"; - case 24: - return "ARROW_FIRE"; - case 25: - return "ARROW_INFINITE"; - case 26: - return "LUCK"; - case 27: - return "LURE"; - case 28: - return "LOYALTY"; - case 29: - return "IMPALING"; - case 30: - return "RIPTIDE"; - case 31: - return "CHANNELING"; - case 32: - return "MULTISHOT"; - case 33: - return "QUICK_CHARGE"; - case 34: - return "PIERCING"; - case 35: - return "MENDING"; - case 36: - return "VANISHING_CURSE"; - default: - return "UNKNOWN_ENCHANT_" + IRegistry.ENCHANTMENT.a(target); - } - } - - 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.isCompatible(ench.target); - } - - public net.minecraft.server.Enchantment getHandle() { - return target; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/AbstractProjectile.java b/src/main/java/org/bukkit/craftbukkit/entity/AbstractProjectile.java deleted file mode 100644 index 47b3fe555..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/AbstractProjectile.java +++ /dev/null @@ -1,25 +0,0 @@ -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; - } - - @Override - public boolean doesBounce() { - return doesBounce; - } - - @Override - public void setBounce(boolean doesBounce) { - this.doesBounce = doesBounce; - } - -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java deleted file mode 100644 index 1aea5f3f0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import java.util.UUID; -import net.minecraft.server.EntityHorse; -import net.minecraft.server.EntityHorseAbstract; -import org.apache.commons.lang.Validate; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.inventory.CraftInventoryAbstractHorse; -import org.bukkit.craftbukkit.inventory.CraftSaddledInventory; -import org.bukkit.entity.AbstractHorse; -import org.bukkit.entity.AnimalTamer; -import org.bukkit.entity.Horse; -import org.bukkit.inventory.AbstractHorseInventory; - -public abstract class CraftAbstractHorse extends CraftAnimals implements AbstractHorse { - - public CraftAbstractHorse(CraftServer server, EntityHorseAbstract entity) { - super(server, entity); - } - - @Override - public EntityHorseAbstract getHandle() { - return (EntityHorseAbstract) entity; - } - - @Override - public void setVariant(Horse.Variant variant) { - throw new UnsupportedOperationException("Not supported."); - } - - @Override - public int getDomestication() { - return getHandle().getTemper(); - } - - @Override - 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); - } - - @Override - public int getMaxDomestication() { - return getHandle().getMaxDomestication(); - } - - @Override - public void setMaxDomestication(int value) { - Validate.isTrue(value > 0, "Max domestication cannot be zero or less"); - getHandle().maxDomestication = value; - } - - @Override - public double getJumpStrength() { - return getHandle().getJumpStrength(); - } - - @Override - 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().isTamed(); - } - - @Override - public void setTamed(boolean tamed) { - getHandle().setTamed(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 getOwnerUniqueId() { - return getOwnerUUID(); - } - public UUID getOwnerUUID() { - return getHandle().getOwnerUUID(); - } - - public void setOwnerUUID(UUID uuid) { - getHandle().setOwnerUUID(uuid); - } - - @Override - public AbstractHorseInventory getInventory() { - return new CraftSaddledInventory(getHandle().inventoryChest); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractVillager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractVillager.java deleted file mode 100644 index 18520fec0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractVillager.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import java.util.List; -import net.minecraft.server.EntityVillager; -import net.minecraft.server.EntityVillagerAbstract; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.inventory.CraftInventory; -import org.bukkit.craftbukkit.inventory.CraftMerchant; -import org.bukkit.entity.AbstractVillager; -import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.MerchantRecipe; - -public class CraftAbstractVillager extends CraftAgeable implements AbstractVillager, InventoryHolder { - - public CraftAbstractVillager(CraftServer server, EntityVillagerAbstract entity) { - super(server, entity); - } - - @Override - public EntityVillagerAbstract getHandle() { - return (EntityVillager) entity; - } - - @Override - public String toString() { - return "CraftAbstractVillager"; - } - - @Override - public Inventory getInventory() { - return new CraftInventory(getHandle().getInventory()); - } - - private CraftMerchant getMerchant() { - return getHandle().getCraftMerchant(); - } - - @Override - public List getRecipes() { - return getMerchant().getRecipes(); - } - - @Override - public void setRecipes(List recipes) { - this.getMerchant().setRecipes(recipes); - } - - @Override - public MerchantRecipe getRecipe(int i) { - return getMerchant().getRecipe(i); - } - - @Override - public void setRecipe(int i, MerchantRecipe merchantRecipe) { - getMerchant().setRecipe(i, merchantRecipe); - } - - @Override - public int getRecipeCount() { - return getMerchant().getRecipeCount(); - } - - @Override - public boolean isTrading() { - return getTrader() != null; - } - - @Override - public HumanEntity getTrader() { - return getMerchant().getTrader(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java deleted file mode 100644 index f9ac60e24..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java +++ /dev/null @@ -1,75 +0,0 @@ -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); - } - - @Override - public int getAge() { - return getHandle().getAge(); - } - - @Override - public void setAge(int age) { - getHandle().setAgeRaw(age); - } - - @Override - public void setAgeLock(boolean lock) { - getHandle().ageLocked = lock; - } - - @Override - public boolean getAgeLock() { - return getHandle().ageLocked; - } - - @Override - public void setBaby() { - if (isAdult()) { - setAge(-24000); - } - } - - @Override - public void setAdult() { - if (!isAdult()) { - setAge(0); - } - } - - @Override - public boolean isAdult() { - return getAge() >= 0; - } - - - @Override - public boolean canBreed() { - return getAge() == 0; - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java deleted file mode 100644 index a482c2aab..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java +++ /dev/null @@ -1,27 +0,0 @@ -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 CraftMob implements Ambient { - public CraftAmbient(CraftServer server, EntityAmbient entity) { - super(server, entity); - } - - @Override - public EntityAmbient getHandle() { - return (EntityAmbient) entity; - } - - @Override - public String toString() { - return "CraftAmbient"; - } - - @Override - public EntityType getType() { - return EntityType.UNKNOWN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java deleted file mode 100644 index 599db583b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import java.util.UUID; -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"; - } - - @Override - public UUID getBreedCause() { - return getHandle().breedCause; - } - - @Override - public void setBreedCause(UUID uuid) { - getHandle().breedCause = uuid; - } - - @Override - public boolean isLoveMode() { - return getHandle().isInLove(); - } - - @Override - public void setLoveModeTicks(int ticks) { - Preconditions.checkArgument(ticks >= 0, "Love mode ticks must be positive or 0"); - getHandle().setLoveTicks(ticks); - } - - @Override - public int getLoveModeTicks() { - return getHandle().loveTicks; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java deleted file mode 100644 index ab6cbf560..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java +++ /dev/null @@ -1,231 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.collect.ImmutableList; -import java.util.List; -import net.minecraft.server.EntityAreaEffectCloud; -import net.minecraft.server.EntityLiving; -import net.minecraft.server.MobEffect; -import net.minecraft.server.MobEffectList; -import org.apache.commons.lang.Validate; -import org.bukkit.Color; -import org.bukkit.Particle; -import org.bukkit.craftbukkit.CraftParticle; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.entity.AreaEffectCloud; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.projectiles.ProjectileSource; - -public class CraftAreaEffectCloud extends CraftEntity implements AreaEffectCloud { - - public CraftAreaEffectCloud(CraftServer server, EntityAreaEffectCloud entity) { - super(server, entity); - } - - @Override - public EntityAreaEffectCloud getHandle() { - return (EntityAreaEffectCloud) super.getHandle(); - } - - @Override - public String toString() { - return "CraftAreaEffectCloud"; - } - - @Override - public EntityType getType() { - return EntityType.AREA_EFFECT_CLOUD; - } - - @Override - public int getDuration() { - return getHandle().getDuration(); - } - - @Override - public void setDuration(int duration) { - getHandle().setDuration(duration); - } - - @Override - public int getWaitTime() { - return getHandle().waitTime; - } - - @Override - public void setWaitTime(int waitTime) { - getHandle().setWaitTime(waitTime); - } - - @Override - public int getReapplicationDelay() { - return getHandle().reapplicationDelay; - } - - @Override - public void setReapplicationDelay(int delay) { - getHandle().reapplicationDelay = delay; - } - - @Override - public int getDurationOnUse() { - return getHandle().durationOnUse; - } - - @Override - public void setDurationOnUse(int duration) { - getHandle().durationOnUse = duration; - } - - @Override - public float getRadius() { - return getHandle().getRadius(); - } - - @Override - public void setRadius(float radius) { - getHandle().setRadius(radius); - } - - @Override - public float getRadiusOnUse() { - return getHandle().radiusOnUse; - } - - @Override - public void setRadiusOnUse(float radius) { - getHandle().setRadiusOnUse(radius); - } - - @Override - public float getRadiusPerTick() { - return getHandle().radiusPerTick; - } - - @Override - public void setRadiusPerTick(float radius) { - getHandle().setRadiusPerTick(radius); - } - - @Override - public Particle getParticle() { - return CraftParticle.toBukkit(getHandle().getParticle()); - } - - @Override - public void setParticle(Particle particle) { - setParticle(particle, null); - } - - @Override - public void setParticle(Particle particle, T data) { - getHandle().setParticle(CraftParticle.toNMS(particle, data)); - } - - @Override - public Color getColor() { - return Color.fromRGB(getHandle().getColor()); - } - - @Override - public void setColor(Color color) { - getHandle().setColor(color.asRGB()); - } - - @Override - public boolean addCustomEffect(PotionEffect effect, boolean override) { - int effectId = effect.getType().getId(); - MobEffect existing = null; - for (MobEffect mobEffect : getHandle().effects) { - if (MobEffectList.getId(mobEffect.getMobEffect()) == effectId) { - existing = mobEffect; - } - } - if (existing != null) { - if (!override) { - return false; - } - getHandle().effects.remove(existing); - } - getHandle().addEffect(CraftPotionUtil.fromBukkit(effect)); - getHandle().refreshEffects(); - return true; - } - - @Override - public void clearCustomEffects() { - getHandle().effects.clear(); - getHandle().refreshEffects(); - } - - @Override - public List getCustomEffects() { - ImmutableList.Builder builder = ImmutableList.builder(); - for (MobEffect effect : getHandle().effects) { - builder.add(CraftPotionUtil.toBukkit(effect)); - } - return builder.build(); - } - - @Override - public boolean hasCustomEffect(PotionEffectType type) { - for (MobEffect effect : getHandle().effects) { - if (CraftPotionUtil.equals(effect.getMobEffect(), type)) { - return true; - } - } - return false; - } - - @Override - public boolean hasCustomEffects() { - return !getHandle().effects.isEmpty(); - } - - @Override - public boolean removeCustomEffect(PotionEffectType effect) { - int effectId = effect.getId(); - MobEffect existing = null; - for (MobEffect mobEffect : getHandle().effects) { - if (MobEffectList.getId(mobEffect.getMobEffect()) == effectId) { - existing = mobEffect; - } - } - if (existing == null) { - return false; - } - getHandle().effects.remove(existing); - getHandle().refreshEffects(); - return true; - } - - @Override - public void setBasePotionData(PotionData data) { - Validate.notNull(data, "PotionData cannot be null"); - getHandle().setType(CraftPotionUtil.fromBukkit(data)); - } - - @Override - public PotionData getBasePotionData() { - return CraftPotionUtil.toBukkit(getHandle().getType()); - } - - @Override - public ProjectileSource getSource() { - EntityLiving source = getHandle().getSource(); - return (source == null) ? null : (LivingEntity) source.getBukkitEntity(); - } - - @Override - public void setSource(ProjectileSource shooter) { - if (shooter instanceof CraftLivingEntity) { - getHandle().setSource((EntityLiving) ((CraftLivingEntity) shooter).getHandle()); - } else { - getHandle().setSource((EntityLiving) null); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java deleted file mode 100644 index 73714d71a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java +++ /dev/null @@ -1,312 +0,0 @@ -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 - @Deprecated // Paper - public ItemStack getItemInHand() { - return getEquipment().getItemInHand(); - } - - @Override - @Deprecated // Paper - 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 void setGravity(boolean gravity) { - super.setGravity(gravity); - // Armor stands are special - getHandle().noclip = !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() { - return getHandle().isMarker(); - } - - @Override - public void setMarker(boolean marker) { - getHandle().setMarker(marker); - } - - // Paper start - @Override - public boolean canMove() { - return getHandle().canMove; - } - - @Override - public void setCanMove(boolean move) { - getHandle().canMove = move; - } - - @Override - public ItemStack getItem(org.bukkit.inventory.EquipmentSlot slot) { - com.google.common.base.Preconditions.checkNotNull(slot, "slot"); - return getHandle().getEquipment(org.bukkit.craftbukkit.CraftEquipmentSlot.getNMS(slot)).asBukkitMirror(); - } - - @Override - public void setItem(org.bukkit.inventory.EquipmentSlot slot, ItemStack item) { - com.google.common.base.Preconditions.checkNotNull(slot, "slot"); - switch (slot) { - case HAND: - getEquipment().setItemInMainHand(item); - return; - case OFF_HAND: - getEquipment().setItemInOffHand(item); - return; - case FEET: - setBoots(item); - return; - case LEGS: - setLeggings(item); - break; - case CHEST: - setChestplate(item); - return; - case HEAD: - setHelmet(item); - return; - } - throw new UnsupportedOperationException(slot.name()); - } - - @Override - public java.util.Set getDisabledSlots() { - java.util.Set disabled = new java.util.HashSet<>(); - for (org.bukkit.inventory.EquipmentSlot slot : org.bukkit.inventory.EquipmentSlot.values()) { - if (this.isSlotDisabled(slot)) { - disabled.add(slot); - } - } - return disabled; - } - - @Override - public void setDisabledSlots(org.bukkit.inventory.EquipmentSlot... slots) { - int disabled = 0; - for (org.bukkit.inventory.EquipmentSlot slot : slots) { - if (slot == org.bukkit.inventory.EquipmentSlot.OFF_HAND) continue; - net.minecraft.server.EnumItemSlot nmsSlot = org.bukkit.craftbukkit.CraftEquipmentSlot.getNMS(slot); - disabled += (1 << nmsSlot.c()) + (1 << (nmsSlot.c() + 8)) + (1 << (nmsSlot.c() + 16)); - } - getHandle().setDisabledSlots(disabled); - } - - @Override - public void addDisabledSlots(org.bukkit.inventory.EquipmentSlot... slots) { - java.util.Set disabled = getDisabledSlots(); - java.util.Collections.addAll(disabled, slots); - setDisabledSlots(disabled.toArray(new org.bukkit.inventory.EquipmentSlot[0])); - } - - @Override - public void removeDisabledSlots(org.bukkit.inventory.EquipmentSlot... slots) { - java.util.Set disabled = getDisabledSlots(); - for (final org.bukkit.inventory.EquipmentSlot slot : slots) disabled.remove(slot); - setDisabledSlots(disabled.toArray(new org.bukkit.inventory.EquipmentSlot[0])); - } - - @Override - public boolean isSlotDisabled(org.bukkit.inventory.EquipmentSlot slot) { - return getHandle().isSlotDisabled(org.bukkit.craftbukkit.CraftEquipmentSlot.getNMS(slot)); - } - - @Override - public boolean canTick() { - return this.getHandle().canTick; - } - - @Override - public void setCanTick(final boolean tick) { - this.getHandle().canTick = tick; - this.getHandle().canTickSetByAPI = true; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java deleted file mode 100644 index 29d23db41..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.EntityArrow; -import org.apache.commons.lang.Validate; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.projectiles.ProjectileSource; - -public class CraftArrow extends AbstractProjectile implements AbstractArrow { - - public CraftArrow(CraftServer server, EntityArrow entity) { - super(server, entity); - } - - @Override - public void setKnockbackStrength(int knockbackStrength) { - Validate.isTrue(knockbackStrength >= 0, "Knockback cannot be negative"); - getHandle().setKnockbackStrength(knockbackStrength); - } - - @Override - public int getKnockbackStrength() { - return getHandle().knockbackStrength; - } - - @Override - public double getDamage() { - return getHandle().getDamage(); - } - - @Override - public void setDamage(double damage) { - Preconditions.checkArgument(damage >= 0, "Damage must be positive"); - getHandle().setDamage(damage); - } - - @Override - public int getPierceLevel() { - return getHandle().getPierceLevel(); - } - - @Override - public void setPierceLevel(int pierceLevel) { - Preconditions.checkArgument(0 <= pierceLevel && pierceLevel <= Byte.MAX_VALUE, "Pierce level out of range, expected 0 < level < 127"); - - getHandle().setPierceLevel((byte) pierceLevel); - } - - @Override - public boolean isCritical() { - return getHandle().isCritical(); - } - - @Override - public void setCritical(boolean critical) { - getHandle().setCritical(critical); - } - - @Override - public ProjectileSource getShooter() { - return getHandle().projectileSource; - } - - @Override - public void setShooter(ProjectileSource shooter) { - if (shooter instanceof Entity) { - getHandle().setShooter(((CraftEntity) shooter).getHandle()); - } else { - getHandle().setShooter(null); - } - getHandle().projectileSource = shooter; - } - - @Override - public boolean isInBlock() { - return getHandle().inGround; - } - - @Override - public Block getAttachedBlock() { - if (!isInBlock()) { - return null; - } - - BlockPosition pos = getHandle().getChunkCoordinates(); - return getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); - } - - @Override - public PickupStatus getPickupStatus() { - return PickupStatus.values()[getHandle().fromPlayer.ordinal()]; - } - - @Override - public void setPickupStatus(PickupStatus status) { - Preconditions.checkNotNull(status, "status"); - getHandle().fromPlayer = EntityArrow.PickupStatus.a(status.ordinal()); - } - - @Override - public void setTicksLived(int value) { - super.setTicksLived(value); - - // Second field for EntityArrow - getHandle().despawnCounter = value; - } - - @Override - public EntityArrow getHandle() { - return (EntityArrow) entity; - } - - @Override - public String toString() { - return "CraftArrow"; - } - - @Override - public EntityType getType() { - return EntityType.UNKNOWN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java deleted file mode 100644 index e7061d9d7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java +++ /dev/null @@ -1,37 +0,0 @@ -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"; - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java deleted file mode 100644 index 089419ede..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.BLAZE; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java deleted file mode 100644 index 271950903..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityBoat; -import org.bukkit.TreeSpecies; -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); - } - - @Override - public TreeSpecies getWoodType() { - return getTreeSpecies(getHandle().getType()); - } - - @Override - public void setWoodType(TreeSpecies species) { - getHandle().setType(getBoatType(species)); - } - - @Override - public double getMaxSpeed() { - return getHandle().maxSpeed; - } - - @Override - public void setMaxSpeed(double speed) { - if (speed >= 0D) { - getHandle().maxSpeed = speed; - } - } - - @Override - public double getOccupiedDeceleration() { - return getHandle().occupiedDeceleration; - } - - @Override - public void setOccupiedDeceleration(double speed) { - if (speed >= 0D) { - getHandle().occupiedDeceleration = speed; - } - } - - @Override - public double getUnoccupiedDeceleration() { - return getHandle().unoccupiedDeceleration; - } - - @Override - public void setUnoccupiedDeceleration(double speed) { - getHandle().unoccupiedDeceleration = speed; - } - - @Override - public boolean getWorkOnLand() { - return getHandle().landBoats; - } - - @Override - public void setWorkOnLand(boolean workOnLand) { - getHandle().landBoats = workOnLand; - } - - @Override - public EntityBoat getHandle() { - return (EntityBoat) entity; - } - - @Override - public String toString() { - return "CraftBoat"; - } - - @Override - public EntityType getType() { - return EntityType.BOAT; - } - - public static TreeSpecies getTreeSpecies(EntityBoat.EnumBoatType boatType) { - switch (boatType) { - case SPRUCE: - return TreeSpecies.REDWOOD; - case BIRCH: - return TreeSpecies.BIRCH; - case JUNGLE: - return TreeSpecies.JUNGLE; - case ACACIA: - return TreeSpecies.ACACIA; - case DARK_OAK: - return TreeSpecies.DARK_OAK; - case OAK: - default: - return TreeSpecies.GENERIC; - } - } - - public static EntityBoat.EnumBoatType getBoatType(TreeSpecies species) { - switch (species) { - case REDWOOD: - return EntityBoat.EnumBoatType.SPRUCE; - case BIRCH: - return EntityBoat.EnumBoatType.BIRCH; - case JUNGLE: - return EntityBoat.EnumBoatType.JUNGLE; - case ACACIA: - return EntityBoat.EnumBoatType.ACACIA; - case DARK_OAK: - return EntityBoat.EnumBoatType.DARK_OAK; - case GENERIC: - default: - return EntityBoat.EnumBoatType.OAK; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCat.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCat.java deleted file mode 100644 index 836110b00..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCat.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.EntityCat; -import net.minecraft.server.EnumColor; -import org.bukkit.DyeColor; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Cat; -import org.bukkit.entity.EntityType; - -public class CraftCat extends CraftTameableAnimal implements Cat { - - public CraftCat(CraftServer server, EntityCat entity) { - super(server, entity); - } - - @Override - public EntityCat getHandle() { - return (EntityCat) super.getHandle(); - } - - @Override - public EntityType getType() { - return EntityType.CAT; - } - - @Override - public String toString() { - return "CraftCat"; - } - - @Override - public Type getCatType() { - return Type.values()[getHandle().getCatType()]; - } - - @Override - public void setCatType(Type type) { - Preconditions.checkArgument(type != null, "Cannot have null Type"); - - getHandle().setCatType(type.ordinal()); - } - - @Override - public DyeColor getCollarColor() { - return DyeColor.getByWoolData((byte) getHandle().getCollarColor().getColorIndex()); - } - - @Override - public void setCollarColor(DyeColor color) { - getHandle().setCollarColor(EnumColor.fromColorIndex(color.getWoolData())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java deleted file mode 100644 index fceb2b2fb..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.CAVE_SPIDER; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftChestedHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftChestedHorse.java deleted file mode 100644 index 39620e06e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftChestedHorse.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityHorseChestedAbstract; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.ChestedHorse; - -public abstract class CraftChestedHorse extends CraftAbstractHorse implements ChestedHorse { - - public CraftChestedHorse(CraftServer server, EntityHorseChestedAbstract entity) { - super(server, entity); - } - - @Override - public EntityHorseChestedAbstract getHandle() { - return (EntityHorseChestedAbstract) super.getHandle(); - } - - @Override - public boolean isCarryingChest() { - return getHandle().isCarryingChest(); - } - - @Override - public void setCarryingChest(boolean chest) { - if (chest == isCarryingChest()) return; - getHandle().setCarryingChest(chest); - getHandle().loadChest(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java deleted file mode 100644 index 47fcf1b1a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java +++ /dev/null @@ -1,28 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.CHICKEN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCod.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCod.java deleted file mode 100644 index 9cda680c0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCod.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityCod; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Cod; -import org.bukkit.entity.EntityType; - -public class CraftCod extends CraftFish implements Cod { - - public CraftCod(CraftServer server, EntityCod entity) { - super(server, entity); - } - - @Override - public EntityCod getHandle() { - return (EntityCod) super.getHandle(); - } - - @Override - public String toString() { - return "CraftCod"; - } - - @Override - public EntityType getType() { - return EntityType.COD; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexLivingEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexLivingEntity.java deleted file mode 100644 index 4947249da..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexLivingEntity.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityInsentient; -import net.minecraft.server.EntityLiving; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.ComplexLivingEntity; - -public abstract class CraftComplexLivingEntity extends CraftMob implements ComplexLivingEntity { // Paper - public CraftComplexLivingEntity(CraftServer server, EntityInsentient entity) { // Paper - super(server, entity); - } - - @Override - public EntityInsentient getHandle() { // Paper - return (EntityInsentient) entity; // Paper - } - - @Override - public String toString() { - return "CraftComplexLivingEntity"; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java deleted file mode 100644 index c1829a0d0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java +++ /dev/null @@ -1,50 +0,0 @@ -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); - } - - @Override - 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 boolean isValid() { - return getParent().isValid(); - } - - @Override - public EntityComplexPart getHandle() { - return (EntityComplexPart) entity; - } - - @Override - public String toString() { - return "CraftComplexPart"; - } - - @Override - public EntityType getType() { - return EntityType.UNKNOWN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java deleted file mode 100644 index 31bfa02e8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java +++ /dev/null @@ -1,28 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.COW; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java deleted file mode 100644 index 73db6101b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityCreature; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Creature; - -public class CraftCreature extends CraftMob implements Creature { - public CraftCreature(CraftServer server, EntityCreature entity) { - super(server, entity); - } - - @Override - public EntityCreature getHandle() { - return (EntityCreature) entity; - } - - @Override - public String toString() { - return "CraftCreature"; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java deleted file mode 100644 index 075a5e77e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -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); - } - - @Override - public boolean isPowered() { - return getHandle().isPowered(); - } - - @Override - 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 void setMaxFuseTicks(int ticks) { - Preconditions.checkArgument(ticks >= 0, "ticks < 0"); - - getHandle().maxFuseTicks = ticks; - } - - @Override - public int getMaxFuseTicks() { - return getHandle().maxFuseTicks; - } - - @Override - public void setExplosionRadius(int radius) { - Preconditions.checkArgument(radius >= 0, "radius < 0"); - - getHandle().explosionRadius = radius; - } - - @Override - public int getExplosionRadius() { - return getHandle().explosionRadius; - } - - @Override - public void explode() { - getHandle().explode(); - } - - @Override - public void ignite() { - getHandle().ignite(); - } - - @Override - public EntityCreeper getHandle() { - return (EntityCreeper) entity; - } - - @Override - public String toString() { - return "CraftCreeper"; - } - - @Override - public EntityType getType() { - return EntityType.CREEPER; - } - - // Paper start - public void setIgnited(boolean ignited) { - getHandle().setIgnited(ignited); - } - - public boolean isIgnited() { - return getHandle().isIgnited(); - } - - public int getFuseTicks() { - return getHandle().fuseTicks; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDolphin.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDolphin.java deleted file mode 100644 index 0399e6f51..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDolphin.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityDolphin; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Dolphin; -import org.bukkit.entity.EntityType; - -public class CraftDolphin extends CraftWaterMob implements Dolphin { - - public CraftDolphin(CraftServer server, EntityDolphin entity) { - super(server, entity); - } - - @Override - public EntityDolphin getHandle() { - return (EntityDolphin) super.getHandle(); - } - - @Override - public String toString() { - return "CraftDolphin"; - } - - @Override - public EntityType getType() { - return EntityType.DOLPHIN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDonkey.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDonkey.java deleted file mode 100644 index b4d74414a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDonkey.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityHorseDonkey; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Donkey; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Horse.Variant; - -public class CraftDonkey extends CraftChestedHorse implements Donkey { - - public CraftDonkey(CraftServer server, EntityHorseDonkey entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftDonkey"; - } - - @Override - public EntityType getType() { - return EntityType.DONKEY; - } - - @Override - public Variant getVariant() { - return Variant.DONKEY; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDragonFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDragonFireball.java deleted file mode 100644 index 4a48b16d5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDragonFireball.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityDragonFireball; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.DragonFireball; -import org.bukkit.entity.EntityType; - -public class CraftDragonFireball extends CraftFireball implements DragonFireball { - public CraftDragonFireball(CraftServer server, EntityDragonFireball entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftDragonFireball"; - } - - @Override - public EntityType getType() { - return EntityType.DRAGON_FIREBALL; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftDrowned.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftDrowned.java deleted file mode 100644 index 6e41dfd92..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftDrowned.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityDrowned; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Drowned; -import org.bukkit.entity.EntityType; - -public class CraftDrowned extends CraftZombie implements Drowned { - - public CraftDrowned(CraftServer server, EntityDrowned entity) { - super(server, entity); - } - - @Override - public EntityDrowned getHandle() { - return (EntityDrowned) entity; - } - - @Override - public String toString() { - return "CraftDrowned"; - } - - @Override - public EntityType getType() { - return EntityType.DROWNED; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java deleted file mode 100644 index 1d0f43038..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.EGG; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftElderGuardian.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftElderGuardian.java deleted file mode 100644 index 34df49bbd..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftElderGuardian.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityGuardianElder; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.ElderGuardian; -import org.bukkit.entity.EntityType; - -public class CraftElderGuardian extends CraftGuardian implements ElderGuardian { - - public CraftElderGuardian(CraftServer server, EntityGuardianElder entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftElderGuardian"; - } - - @Override - public EntityType getType() { - return EntityType.ELDER_GUARDIAN; - } - - @Override - public boolean isElder() { - return true; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java deleted file mode 100644 index 46d8e36ac..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.BlockPosition; -import net.minecraft.server.EntityEnderCrystal; -import org.bukkit.Location; -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 boolean isShowingBottom() { - return getHandle().isShowingBottom(); - } - - @Override - public void setShowingBottom(boolean showing) { - getHandle().setShowingBottom(showing); - } - - @Override - public Location getBeamTarget() { - BlockPosition pos = getHandle().getBeamTarget(); - return pos == null ? null : new Location(getWorld(), pos.getX(), pos.getY(), pos.getZ()); - } - - @Override - public void setBeamTarget(Location location) { - if (location == null) { - getHandle().setBeamTarget((BlockPosition) null); - } else if (location.getWorld() != getWorld()) { - throw new IllegalArgumentException("Cannot set beam target location to different world"); - } else { - getHandle().setBeamTarget(new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ())); - } - } - - @Override - public EntityEnderCrystal getHandle() { - return (EntityEnderCrystal) entity; - } - - @Override - public String toString() { - return "CraftEnderCrystal"; - } - - @Override - public EntityType getType() { - return EntityType.ENDER_CRYSTAL; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java deleted file mode 100644 index ee95e4e33..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSet.Builder; -import java.util.Set; -import net.minecraft.server.DragonControllerPhase; -import net.minecraft.server.EntityComplexPart; -import net.minecraft.server.EntityEnderDragon; -import org.bukkit.boss.BossBar; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.boss.CraftBossBar; -import org.bukkit.entity.ComplexEntityPart; -import org.bukkit.entity.EnderDragon; -import org.bukkit.entity.EntityType; - -public class CraftEnderDragon extends CraftComplexLivingEntity implements EnderDragon { - - private BossBar bossBar; - - public CraftEnderDragon(CraftServer server, EntityEnderDragon entity) { - super(server, entity); - - if (entity.getEnderDragonBattle() != null) { - this.bossBar = new CraftBossBar(entity.getEnderDragonBattle().bossBattle); - } - } - - @Override - 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"; - } - - @Override - public EntityType getType() { - return EntityType.ENDER_DRAGON; - } - - @Override - public Phase getPhase() { - return Phase.values()[getHandle().getDataWatcher().get(EntityEnderDragon.PHASE)]; - } - - @Override - public void setPhase(Phase phase) { - getHandle().getDragonControllerManager().setControllerPhase(getMinecraftPhase(phase)); - } - - public static Phase getBukkitPhase(DragonControllerPhase phase) { - return Phase.values()[phase.b()]; - } - - public static DragonControllerPhase getMinecraftPhase(Phase phase) { - return DragonControllerPhase.getById(phase.ordinal()); - } - - @Override - public BossBar getBossBar() { - return bossBar; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java deleted file mode 100644 index e6d050099..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java +++ /dev/null @@ -1,73 +0,0 @@ -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; - -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"; - } - - @Override - public void damage(double amount) { - getParent().damage(amount); - } - - @Override - public void damage(double amount, Entity source) { - getParent().damage(amount, source); - } - - @Override - public double getHealth() { - return getParent().getHealth(); - } - - @Override - public void setHealth(double health) { - getParent().setHealth(health); - } - - @Override - public double getAbsorptionAmount() { - return getParent().getAbsorptionAmount(); - } - - @Override - public void setAbsorptionAmount(double amount) { - getParent().setAbsorptionAmount(amount); - } - - @Override - public double getMaxHealth() { - return getParent().getMaxHealth(); - } - - @Override - public void setMaxHealth(double health) { - getParent().setMaxHealth(health); - } - - @Override - public void resetMaxHealth() { - getParent().resetMaxHealth(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java deleted file mode 100644 index 32221ead3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.ENDER_PEARL; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java deleted file mode 100644 index d771fdc6e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.EntityEnderSignal; -import org.bukkit.Location; -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"; - } - - @Override - public EntityType getType() { - return EntityType.ENDER_SIGNAL; - } - - @Override - public Location getTargetLocation() { - return new Location(getWorld(), getHandle().targetX, getHandle().targetY, getHandle().targetZ, getHandle().yaw, getHandle().pitch); - } - - @Override - public void setTargetLocation(Location location) { - Preconditions.checkArgument(getWorld().equals(location.getWorld()), "Cannot target EnderSignal across worlds"); - getHandle().a(new BlockPosition(location.getX(), location.getY(), location.getZ())); - } - - @Override - public boolean getDropItem() { - return getHandle().shouldDropItem; - } - - @Override - public void setDropItem(boolean shouldDropItem) { - getHandle().shouldDropItem = shouldDropItem; - } - - @Override - public int getDespawnTimer() { - return getHandle().despawnTimer; - } - - @Override - public void setDespawnTimer(int time) { - getHandle().despawnTimer = time; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java deleted file mode 100644 index 0c5f35934..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityEnderman; -import net.minecraft.server.IBlockData; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -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); - } - - @Override public boolean teleportRandomly() { return getHandle().teleportRandomly(); } // Paper - @Override - public MaterialData getCarriedMaterial() { - IBlockData blockData = getHandle().getCarried(); - return (blockData == null) ? Material.AIR.getNewData((byte) 0) : CraftMagicNumbers.getMaterial(blockData); - } - - @Override - public BlockData getCarriedBlock() { - IBlockData blockData = getHandle().getCarried(); - return (blockData == null) ? null : CraftBlockData.fromData(blockData); - } - - @Override - public void setCarriedMaterial(MaterialData data) { - getHandle().setCarried(CraftMagicNumbers.getBlock(data)); - } - - @Override - public void setCarriedBlock(BlockData blockData) { - getHandle().setCarried(blockData == null ? null : ((CraftBlockData) blockData).getState()); - } - - @Override - public EntityEnderman getHandle() { - return (EntityEnderman) entity; - } - - @Override - public String toString() { - return "CraftEnderman"; - } - - @Override - public EntityType getType() { - return EntityType.ENDERMAN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java deleted file mode 100644 index 31c5d97ee..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java +++ /dev/null @@ -1,38 +0,0 @@ -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 EntityEndermite getHandle() { - return (EntityEndermite) super.getHandle(); - } - - @Override - public String toString() { - return "CraftEndermite"; - } - - @Override - public EntityType getType() { - return EntityType.ENDERMITE; - } - - @Override - public boolean isPlayerSpawned() { - return getHandle().isPlayerSpawned(); - } - - @Override - public void setPlayerSpawned(boolean playerSpawned) { - getHandle().setPlayerSpawned(playerSpawned); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java deleted file mode 100644 index 31db42e9f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java +++ /dev/null @@ -1,1063 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import net.minecraft.server.AxisAlignedBB; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.DamageSource; -import net.minecraft.server.Entity; -import net.minecraft.server.EntityAmbient; -import net.minecraft.server.EntityAnimal; -import net.minecraft.server.EntityAreaEffectCloud; -import net.minecraft.server.EntityArmorStand; -import net.minecraft.server.EntityArrow; -import net.minecraft.server.EntityBat; -import net.minecraft.server.EntityBlaze; -import net.minecraft.server.EntityBoat; -import net.minecraft.server.EntityCat; -import net.minecraft.server.EntityCaveSpider; -import net.minecraft.server.EntityChicken; -import net.minecraft.server.EntityCod; -import net.minecraft.server.EntityComplexPart; -import net.minecraft.server.EntityCow; -import net.minecraft.server.EntityCreature; -import net.minecraft.server.EntityCreeper; -import net.minecraft.server.EntityDolphin; -import net.minecraft.server.EntityDragonFireball; -import net.minecraft.server.EntityDrowned; -import net.minecraft.server.EntityEgg; -import net.minecraft.server.EntityEnderCrystal; -import net.minecraft.server.EntityEnderDragon; -import net.minecraft.server.EntityEnderPearl; -import net.minecraft.server.EntityEnderSignal; -import net.minecraft.server.EntityEnderman; -import net.minecraft.server.EntityEndermite; -import net.minecraft.server.EntityEvoker; -import net.minecraft.server.EntityEvokerFangs; -import net.minecraft.server.EntityExperienceOrb; -import net.minecraft.server.EntityFallingBlock; -import net.minecraft.server.EntityFireball; -import net.minecraft.server.EntityFireworks; -import net.minecraft.server.EntityFish; -import net.minecraft.server.EntityFishingHook; -import net.minecraft.server.EntityFlying; -import net.minecraft.server.EntityFox; -import net.minecraft.server.EntityGhast; -import net.minecraft.server.EntityGiantZombie; -import net.minecraft.server.EntityGolem; -import net.minecraft.server.EntityGuardian; -import net.minecraft.server.EntityGuardianElder; -import net.minecraft.server.EntityHanging; -import net.minecraft.server.EntityHorse; -import net.minecraft.server.EntityHorseAbstract; -import net.minecraft.server.EntityHorseChestedAbstract; -import net.minecraft.server.EntityHorseDonkey; -import net.minecraft.server.EntityHorseMule; -import net.minecraft.server.EntityHorseSkeleton; -import net.minecraft.server.EntityHorseZombie; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.EntityIllagerAbstract; -import net.minecraft.server.EntityIllagerIllusioner; -import net.minecraft.server.EntityIllagerWizard; -import net.minecraft.server.EntityIronGolem; -import net.minecraft.server.EntityItem; -import net.minecraft.server.EntityItemFrame; -import net.minecraft.server.EntityLargeFireball; -import net.minecraft.server.EntityLeash; -import net.minecraft.server.EntityLightning; -import net.minecraft.server.EntityLiving; -import net.minecraft.server.EntityLlama; -import net.minecraft.server.EntityLlamaSpit; -import net.minecraft.server.EntityLlamaTrader; -import net.minecraft.server.EntityMagmaCube; -import net.minecraft.server.EntityMinecartAbstract; -import net.minecraft.server.EntityMinecartChest; -import net.minecraft.server.EntityMinecartCommandBlock; -import net.minecraft.server.EntityMinecartFurnace; -import net.minecraft.server.EntityMinecartHopper; -import net.minecraft.server.EntityMinecartMobSpawner; -import net.minecraft.server.EntityMinecartRideable; -import net.minecraft.server.EntityMinecartTNT; -import net.minecraft.server.EntityMonster; -import net.minecraft.server.EntityMushroomCow; -import net.minecraft.server.EntityOcelot; -import net.minecraft.server.EntityPainting; -import net.minecraft.server.EntityPanda; -import net.minecraft.server.EntityParrot; -import net.minecraft.server.EntityPhantom; -import net.minecraft.server.EntityPig; -import net.minecraft.server.EntityPigZombie; -import net.minecraft.server.EntityPillager; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.EntityPolarBear; -import net.minecraft.server.EntityPotion; -import net.minecraft.server.EntityProjectile; -import net.minecraft.server.EntityPufferFish; -import net.minecraft.server.EntityRabbit; -import net.minecraft.server.EntityRavager; -import net.minecraft.server.EntitySalmon; -import net.minecraft.server.EntitySheep; -import net.minecraft.server.EntityShulker; -import net.minecraft.server.EntityShulkerBullet; -import net.minecraft.server.EntitySilverfish; -import net.minecraft.server.EntitySkeletonAbstract; -import net.minecraft.server.EntitySkeletonStray; -import net.minecraft.server.EntitySkeletonWither; -import net.minecraft.server.EntitySlime; -import net.minecraft.server.EntitySmallFireball; -import net.minecraft.server.EntitySnowball; -import net.minecraft.server.EntitySnowman; -import net.minecraft.server.EntitySpectralArrow; -import net.minecraft.server.EntitySpider; -import net.minecraft.server.EntitySquid; -import net.minecraft.server.EntityTNTPrimed; -import net.minecraft.server.EntityTameableAnimal; -import net.minecraft.server.EntityThrownExpBottle; -import net.minecraft.server.EntityThrownTrident; -import net.minecraft.server.EntityTippedArrow; -import net.minecraft.server.EntityTropicalFish; -import net.minecraft.server.EntityTurtle; -import net.minecraft.server.EntityVex; -import net.minecraft.server.EntityVillager; -import net.minecraft.server.EntityVillagerAbstract; -import net.minecraft.server.EntityVillagerTrader; -import net.minecraft.server.EntityVindicator; -import net.minecraft.server.EntityWaterAnimal; -import net.minecraft.server.EntityWitch; -import net.minecraft.server.EntityWither; -import net.minecraft.server.EntityWitherSkull; -import net.minecraft.server.EntityWolf; -import net.minecraft.server.EntityZombie; -import net.minecraft.server.EntityZombieHusk; -import net.minecraft.server.EntityZombieVillager; -import net.minecraft.server.EnumChatFormat; -import net.minecraft.server.IChatBaseComponent; -import net.minecraft.server.NBTTagCompound; -import org.bukkit.Chunk; // Paper -import org.bukkit.EntityEffect; -import org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.World; -import org.bukkit.block.BlockFace; -import org.bukkit.block.PistonMoveReaction; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer; -import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.craftbukkit.util.CraftVector; -import org.bukkit.entity.Pose; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.permissions.PermissibleBase; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionAttachment; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.permissions.ServerOperator; -import org.bukkit.plugin.Plugin; -import org.bukkit.util.BoundingBox; -import org.bukkit.util.NumberConversions; -import org.bukkit.util.Vector; - -public abstract class CraftEntity implements org.bukkit.entity.Entity { - private static PermissibleBase perm; - private static final CraftPersistentDataTypeRegistry DATA_TYPE_REGISTRY = new CraftPersistentDataTypeRegistry(); - - protected final CraftServer server; - protected Entity entity; - private EntityDamageEvent lastDamageEvent; - private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(DATA_TYPE_REGISTRY); - - public CraftEntity(final CraftServer server, final Entity entity) { - this.server = server; - this.entity = entity; - } - - @Override - public Chunk getChunk() { - net.minecraft.server.Chunk currentChunk = entity.getCurrentChunk(); - return currentChunk != null ? currentChunk.bukkitChunk : getLocation().getChunk(); - } - - public static CraftEntity getEntity(CraftServer server, Entity entity) { - /** - * Order is *EXTREMELY* important -- keep it right! =D - */ - 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 if (entity instanceof EntityFish) { - if (entity instanceof EntityCod) { return new CraftCod(server, (EntityCod) entity); } - else if (entity instanceof EntityPufferFish) { return new CraftPufferFish(server, (EntityPufferFish) entity); } - else if (entity instanceof EntitySalmon) { return new CraftSalmon(server, (EntitySalmon) entity); } - else if (entity instanceof EntityTropicalFish) { return new CraftTropicalFish(server, (EntityTropicalFish) entity); } - else { return new CraftFish(server, (EntityFish) entity); } - } - else if (entity instanceof EntityDolphin) { return new CraftDolphin(server, (EntityDolphin) 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 EntityCat) { return new CraftCat(server, (EntityCat) entity); } - else if (entity instanceof EntityParrot) { return new CraftParrot(server, (EntityParrot) entity); } - } - else if (entity instanceof EntitySheep) { return new CraftSheep(server, (EntitySheep) entity); } - else if (entity instanceof EntityHorseAbstract) { - if (entity instanceof EntityHorseChestedAbstract){ - if (entity instanceof EntityHorseDonkey) { return new CraftDonkey(server, (EntityHorseDonkey) entity); } - else if (entity instanceof EntityHorseMule) { return new CraftMule(server, (EntityHorseMule) entity); } - else if (entity instanceof EntityLlamaTrader) { return new CraftTraderLlama(server, (EntityLlamaTrader) entity); } - else if (entity instanceof EntityLlama) { return new CraftLlama(server, (EntityLlama) entity); } - } else if (entity instanceof EntityHorse) { return new CraftHorse(server, (EntityHorse) entity); } - else if (entity instanceof EntityHorseSkeleton) { return new CraftSkeletonHorse(server, (EntityHorseSkeleton) entity); } - else if (entity instanceof EntityHorseZombie) { return new CraftZombieHorse(server, (EntityHorseZombie) entity); } - } - else if (entity instanceof EntityRabbit) { return new CraftRabbit(server, (EntityRabbit) entity); } - else if (entity instanceof EntityPolarBear) { return new CraftPolarBear(server, (EntityPolarBear) entity); } - else if (entity instanceof EntityTurtle) { return new CraftTurtle(server, (EntityTurtle) entity); } - else if (entity instanceof EntityOcelot) { return new CraftOcelot(server, (EntityOcelot) entity); } - else if (entity instanceof EntityPanda) { return new CraftPanda(server, (EntityPanda) entity); } - else if (entity instanceof EntityFox) { return new CraftFox(server, (EntityFox) 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 if (entity instanceof EntityZombieHusk) { return new CraftHusk(server, (EntityZombieHusk) entity); } - else if (entity instanceof EntityZombieVillager) { return new CraftVillagerZombie(server, (EntityZombieVillager) entity); } - else if (entity instanceof EntityDrowned) { return new CraftDrowned(server, (EntityDrowned) 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 EntitySkeletonAbstract) { - if (entity instanceof EntitySkeletonStray) { return new CraftStray(server, (EntitySkeletonStray) entity); } - else if (entity instanceof EntitySkeletonWither) { return new CraftWitherSkeleton(server, (EntitySkeletonWither) entity); } - else { return new CraftSkeleton(server, (EntitySkeletonAbstract) 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) { - if (entity instanceof EntityGuardianElder) { return new CraftElderGuardian(server, (EntityGuardianElder) entity); } - else { return new CraftGuardian(server, (EntityGuardian) entity); } - } - else if (entity instanceof EntityVex) { return new CraftVex(server, (EntityVex) entity); } - else if (entity instanceof EntityIllagerAbstract) { - if (entity instanceof EntityIllagerWizard) { - if (entity instanceof EntityEvoker) { return new CraftEvoker(server, (EntityEvoker) entity); } - else if (entity instanceof EntityIllagerIllusioner) { return new CraftIllusioner(server, (EntityIllagerIllusioner) entity); } - else { return new CraftSpellcaster(server, (EntityIllagerWizard) entity); } - } - else if (entity instanceof EntityVindicator) { return new CraftVindicator(server, (EntityVindicator) entity); } - else if (entity instanceof EntityPillager) { return new CraftPillager(server, (EntityPillager) entity); } - else { return new CraftIllager(server, (EntityIllagerAbstract) entity); } - } - else if (entity instanceof EntityRavager) { return new CraftRavager(server, (EntityRavager) 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 EntityShulker) { return new CraftShulker(server, (EntityShulker) entity); } - } - else if (entity instanceof EntityVillagerAbstract) { - if (entity instanceof EntityVillager) { return new CraftVillager(server, (EntityVillager) entity); } - else if (entity instanceof EntityVillagerTrader) { return new CraftWanderingTrader(server, (EntityVillagerTrader) entity); } - else { return new CraftAbstractVillager(server, (EntityVillagerAbstract) 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 if (entity instanceof EntityPhantom) { return new CraftPhantom(server, (EntityPhantom) 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 EntityTippedArrow) { return new CraftTippedArrow(server, (EntityTippedArrow) entity); } - else if (entity instanceof EntitySpectralArrow) { return new CraftSpectralArrow(server, (EntitySpectralArrow) entity); } - else if (entity instanceof EntityArrow) { - if (entity instanceof EntityThrownTrident) { return new CraftTrident(server, (EntityThrownTrident) entity); } - else { 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 EntityFallingBlock) { return new CraftFallingBlock(server, (EntityFallingBlock) 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 if (entity instanceof EntityDragonFireball) { return new CraftDragonFireball(server, (EntityDragonFireball) 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 CraftFishHook(server, (EntityFishingHook) entity); } - else if (entity instanceof EntityItem) { return new CraftItem(server, (EntityItem) entity); } - else if (entity instanceof EntityLightning) { return new CraftLightningStrike(server, (EntityLightning) 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 EntityTNTPrimed) { return new CraftTNTPrimed(server, (EntityTNTPrimed) entity); } - else if (entity instanceof EntityFireworks) { return new CraftFirework(server, (EntityFireworks) entity); } - else if (entity instanceof EntityShulkerBullet) { return new CraftShulkerBullet(server, (EntityShulkerBullet) entity); } - else if (entity instanceof EntityAreaEffectCloud) { return new CraftAreaEffectCloud(server, (EntityAreaEffectCloud) entity); } - else if (entity instanceof EntityEvokerFangs) { return new CraftEvokerFangs(server, (EntityEvokerFangs) entity); } - else if (entity instanceof EntityLlamaSpit) { return new CraftLlamaSpit(server, (EntityLlamaSpit) entity); } - - throw new AssertionError("Unknown entity " + (entity == null ? null : entity.getClass())); - } - - @Override - public Location getLocation() { - return new Location(getWorld(), entity.locX, entity.locY, entity.locZ, entity.getBukkitYaw(), entity.pitch); - } - - @Override - 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.getBukkitYaw()); - loc.setPitch(entity.pitch); - } - - return loc; - } - - @Override - public Vector getVelocity() { - return CraftVector.toBukkit(entity.getMot()); - } - - @Override - public void setVelocity(Vector velocity) { - Preconditions.checkArgument(velocity != null, "velocity"); - velocity.checkFinite(); - // Paper start - Warn server owners when plugins try to set super high velocities - if (!(this instanceof org.bukkit.entity.Projectile) && isUnsafeVelocity(velocity)) { - CraftServer.excessiveVelEx = new Exception("Excessive velocity set detected: tried to set velocity of entity " + entity.getName() + " id #" + getEntityId() + " to (" + velocity.getX() + "," + velocity.getY() + "," + velocity.getZ() + ")."); - } - // Paper end - - entity.setMot(CraftVector.toNMS(velocity)); - entity.velocityChanged = true; - } - - // Paper start - /** - * Checks if the given velocity is not necessarily safe in all situations. - * This function returning true does not mean the velocity is dangerous or to be avoided, only that it may be - * a detriment to performance on the server. - * - * It is not to be used as a hard rule of any sort. - * Paper only uses it to warn server owners in watchdog crashes. - * - * @param vel incoming velocity to check - * @return if the velocity has the potential to be a performance detriment - */ - private static boolean isUnsafeVelocity(Vector vel) { - final double x = vel.getX(); - final double y = vel.getY(); - final double z = vel.getZ(); - - if (x > 4 || x < -4 || y > 4 || y < -4 || z > 4 || z < -4) { - return true; - } - - return false; - } - // Paper end - - @Override - public double getHeight() { - return getHandle().getHeight(); - } - - @Override - public double getWidth() { - return getHandle().getWidth(); - } - - @Override - public BoundingBox getBoundingBox() { - AxisAlignedBB bb = getHandle().getBoundingBox(); - return new BoundingBox(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); - } - - @Override - public boolean isOnGround() { - if (entity instanceof EntityArrow) { - return ((EntityArrow) entity).inGround; - } - return entity.onGround; - } - - @Override - public World getWorld() { - return entity.world.getWorld(); - } - - @Override - public void setRotation(float yaw, float pitch) { - NumberConversions.checkFinite(pitch, "pitch not finite"); - NumberConversions.checkFinite(yaw, "yaw not finite"); - - yaw = Location.normalizeYaw(yaw); - pitch = Location.normalizePitch(pitch); - - entity.yaw = yaw; - entity.pitch = pitch; - entity.lastYaw = yaw; - entity.lastPitch = pitch; - entity.setHeadRotation(yaw); - } - - @Override - public boolean teleport(Location location) { - return teleport(location, TeleportCause.PLUGIN); - } - - @Override - public boolean teleport(Location location, TeleportCause cause) { - Preconditions.checkArgument(location != null, "location"); - location.checkFinite(); - - if (entity.isVehicle() || entity.dead) { - return false; - } - - // If this entity is riding another entity, we must dismount before teleporting. - entity.stopRiding(); - - // Let the server handle cross world teleports - if (!location.getWorld().equals(getWorld())) { - entity.teleportTo(((CraftWorld) location.getWorld()).getHandle().getWorldProvider().getDimensionManager(), new BlockPosition(location.getX(), location.getY(), location.getZ())); - return true; - } - - // entity.setLocation() throws no event, and so cannot be cancelled - entity.setLocation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); - // SPIGOT-619: Force sync head rotation also - entity.setHeadRotation(location.getYaw()); - ((net.minecraft.server.WorldServer) entity.world).chunkCheck(entity); // Spigot - register to new chunk - - return true; - } - - @Override - public boolean teleport(org.bukkit.entity.Entity destination) { - return teleport(destination.getLocation()); - } - - @Override - public boolean teleport(org.bukkit.entity.Entity destination, TeleportCause cause) { - return teleport(destination.getLocation(), cause); - } - - @Override - public List getNearbyEntities(double x, double y, double z) { - org.spigotmc.AsyncCatcher.catchOp("getNearbyEntities"); // Spigot - List notchEntityList = entity.world.getEntities(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; - } - - @Override - public int getEntityId() { - return entity.getId(); - } - - @Override - public int getFireTicks() { - return entity.fireTicks; - } - - @Override - public int getMaxFireTicks() { - return entity.getMaxFireTicks(); - } - - @Override - public void setFireTicks(int ticks) { - entity.fireTicks = ticks; - } - - @Override - public void remove() { - entity.die(); - } - - @Override - public boolean isDead() { - return !entity.isAlive(); - } - - @Override - public boolean isValid() { - return entity.isAlive() && entity.valid && entity.isChunkLoaded(); - } - - @Override - public Server getServer() { - return server; - } - - @Override - public boolean isPersistent() { - return entity.persist; - } - - @Override - public void setPersistent(boolean persistent) { - entity.persist = persistent; - } - - public Vector getMomentum() { - return getVelocity(); - } - - public void setMomentum(Vector value) { - setVelocity(value); - } - - @Override - public org.bukkit.entity.Entity getPassenger() { - return isEmpty() ? null : getHandle().passengers.get(0).getBukkitEntity(); - } - - @Override - public boolean setPassenger(org.bukkit.entity.Entity passenger) { - Preconditions.checkArgument(!this.equals(passenger), "Entity cannot ride itself."); - if (passenger instanceof CraftEntity) { - eject(); - return ((CraftEntity) passenger).getHandle().startRiding(getHandle()); - } else { - return false; - } - } - - @Override - public List getPassengers() { - return Lists.newArrayList(Lists.transform(getHandle().passengers, new Function() { - @Override - public org.bukkit.entity.Entity apply(Entity input) { - return input.getBukkitEntity(); - } - })); - } - - @Override - public boolean addPassenger(org.bukkit.entity.Entity passenger) { - Preconditions.checkArgument(passenger != null, "passenger == null"); - - return ((CraftEntity) passenger).getHandle().a(getHandle(), true); - } - - @Override - public boolean removePassenger(org.bukkit.entity.Entity passenger) { - Preconditions.checkArgument(passenger != null, "passenger == null"); - - ((CraftEntity) passenger).getHandle().stopRiding(); - return true; - } - - @Override - public boolean isEmpty() { - return !getHandle().isVehicle(); - } - - @Override - public boolean eject() { - if (isEmpty()) { - return false; - } - - getHandle().ejectPassengers(); - return true; - } - - @Override - public float getFallDistance() { - return getHandle().fallDistance; - } - - @Override - public void setFallDistance(float distance) { - getHandle().fallDistance = distance; - } - - @Override - public void setLastDamageCause(EntityDamageEvent event) { - lastDamageEvent = event; - } - - @Override - public EntityDamageEvent getLastDamageCause() { - return lastDamageEvent; - } - - @Override - public UUID getUniqueId() { - return getHandle().getUniqueID(); - } - - @Override - public int getTicksLived() { - return getHandle().ticksLived; - } - - @Override - 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; - } - - @Override - public void playEffect(EntityEffect type) { - Preconditions.checkArgument(type != null, "type"); - - if (type.getApplicable().isInstance(this)) { - 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.getHandle() == other.getHandle()); // Paper - while logically the same, this is clearer - } - - // Paper - Fix hashCode. entity ID's are not static. - // A CraftEntity can change reference to a new entity with a new ID, and hash codes should never change - @Override - public int hashCode() { - return getUniqueId().hashCode(); - // Paper end - } - - @Override - public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - server.getEntityMetadata().setMetadata(this, metadataKey, newMetadataValue); - } - - @Override - public List getMetadata(String metadataKey) { - return server.getEntityMetadata().getMetadata(this, metadataKey); - } - - @Override - public boolean hasMetadata(String metadataKey) { - return server.getEntityMetadata().hasMetadata(this, metadataKey); - } - - @Override - public void removeMetadata(String metadataKey, Plugin owningPlugin) { - server.getEntityMetadata().removeMetadata(this, metadataKey, owningPlugin); - } - - @Override - public boolean isInsideVehicle() { - return getHandle().isPassenger(); - } - - @Override - public boolean leaveVehicle() { - if (!isInsideVehicle()) { - return false; - } - - getHandle().stopRiding(); - return true; - } - - @Override - public org.bukkit.entity.Entity getVehicle() { - if (!isInsideVehicle()) { - return null; - } - - return getHandle().getVehicle().getBukkitEntity(); - } - - @Override - public void setCustomName(String name) { - // sane limit for name length - if (name != null && name.length() > 256) { - name = name.substring(0, 256); - } - - getHandle().setCustomName(CraftChatMessage.fromStringOrNull(name)); - } - - @Override - public String getCustomName() { - IChatBaseComponent name = getHandle().getCustomName(); - - if (name == null) { - return null; - } - - return CraftChatMessage.fromComponent(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 CraftChatMessage.fromComponent(getHandle().getDisplayName(), EnumChatFormat.WHITE); - } - - @Override - public boolean isPermissionSet(String name) { - return getPermissibleBase().isPermissionSet(name); - } - - @Override - public boolean isPermissionSet(Permission perm) { - return CraftEntity.getPermissibleBase().isPermissionSet(perm); - } - - @Override - public boolean hasPermission(String name) { - return getPermissibleBase().hasPermission(name); - } - - @Override - public boolean hasPermission(Permission perm) { - return getPermissibleBase().hasPermission(perm); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { - return getPermissibleBase().addAttachment(plugin, name, value); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin) { - return getPermissibleBase().addAttachment(plugin); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { - return getPermissibleBase().addAttachment(plugin, name, value, ticks); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, int ticks) { - return getPermissibleBase().addAttachment(plugin, ticks); - } - - @Override - public void removeAttachment(PermissionAttachment attachment) { - getPermissibleBase().removeAttachment(attachment); - } - - @Override - public void recalculatePermissions() { - getPermissibleBase().recalculatePermissions(); - } - - @Override - public Set getEffectivePermissions() { - return getPermissibleBase().getEffectivePermissions(); - } - - @Override - public boolean isOp() { - return getPermissibleBase().isOp(); - } - - @Override - public void setOp(boolean value) { - getPermissibleBase().setOp(value); - } - - @Override - public void setGlowing(boolean flag) { - getHandle().glowing = flag; - Entity e = getHandle(); - if (e.getFlag(6) != flag) { - e.setFlag(6, flag); - } - } - - @Override - public boolean isGlowing() { - return getHandle().glowing; - } - - @Override - public void setInvulnerable(boolean flag) { - getHandle().setInvulnerable(flag); - } - - @Override - public boolean isInvulnerable() { - return getHandle().isInvulnerable(DamageSource.GENERIC); - } - - @Override - public boolean isSilent() { - return getHandle().isSilent(); - } - - @Override - public void setSilent(boolean flag) { - getHandle().setSilent(flag); - } - - @Override - public boolean hasGravity() { - return !getHandle().isNoGravity(); - } - - @Override - public void setGravity(boolean gravity) { - getHandle().setNoGravity(!gravity); - } - - @Override - public int getPortalCooldown() { - return getHandle().portalCooldown; - } - - @Override - public void setPortalCooldown(int cooldown) { - getHandle().portalCooldown = cooldown; - } - - @Override - public Set getScoreboardTags() { - return getHandle().getScoreboardTags(); - } - - @Override - public boolean addScoreboardTag(String tag) { - return getHandle().addScoreboardTag(tag); - } - - @Override - public boolean removeScoreboardTag(String tag) { - return getHandle().removeScoreboardTag(tag); - } - - @Override - public PistonMoveReaction getPistonMoveReaction() { - return PistonMoveReaction.getById(getHandle().getPushReaction().ordinal()); - } - - @Override - public BlockFace getFacing() { - // Use this method over getDirection because it handles boats and minecarts. - return CraftBlock.notchToBlockFace(getHandle().getAdjustedDirection()); - } - - @Override - public CraftPersistentDataContainer getPersistentDataContainer() { - return persistentDataContainer; - } - - @Override - public Pose getPose() { - return Pose.values()[getHandle().getPose().ordinal()]; - } - - public void storeBukkitValues(NBTTagCompound c) { - if (!this.persistentDataContainer.isEmpty()) { - c.set("BukkitValues", this.persistentDataContainer.toTagCompound()); - } - } - - public void readBukkitValues(NBTTagCompound c) { - NBTTagCompound base = c.getCompound("BukkitValues"); - if (base != null) { - this.persistentDataContainer.putAll(base); - } - } - - protected NBTTagCompound save() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - nbttagcompound.setString("id", getHandle().getSaveID()); - getHandle().save(nbttagcompound); - - return nbttagcompound; - } - - private static PermissibleBase getPermissibleBase() { - if (perm == null) { - perm = new PermissibleBase(new ServerOperator() { - - @Override - public boolean isOp() { - return false; - } - - @Override - public void setOp(boolean value) { - - } - }); - } - return perm; - } - - // Spigot start - private final Spigot spigot = new Spigot() - { - @Override - public boolean isInvulnerable() - { - return getHandle().isInvulnerable(net.minecraft.server.DamageSource.GENERIC); - } - - @Override - public void sendMessage(net.md_5.bungee.api.chat.BaseComponent component) - { - } - - @Override - public void sendMessage(net.md_5.bungee.api.chat.BaseComponent... components) - { - } - }; - - public Spigot spigot() - { - return spigot; - } - // Spigot end - - // Paper start - @Override - public Location getOrigin() { - Location origin = getHandle().origin; - return origin == null ? null : origin.clone(); - } - - @Override - public boolean fromMobSpawner() { - return getHandle().spawnedViaMobSpawner; - } - - @Override - public org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason getEntitySpawnReason() { - return getHandle().spawnReason; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEvoker.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEvoker.java deleted file mode 100644 index 0636d2647..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEvoker.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityEvoker; -import net.minecraft.server.EntityIllagerWizard; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Evoker; - -public class CraftEvoker extends CraftSpellcaster implements Evoker { - - public CraftEvoker(CraftServer server, EntityEvoker entity) { - super(server, entity); - } - - @Override - public EntityEvoker getHandle() { - return (EntityEvoker) super.getHandle(); - } - - @Override - public String toString() { - return "CraftEvoker"; - } - - @Override - public EntityType getType() { - return EntityType.EVOKER; - } - - @Override - public Evoker.Spell getCurrentSpell() { - return Evoker.Spell.values()[getHandle().getSpell().ordinal()]; - } - - @Override - public void setCurrentSpell(Evoker.Spell spell) { - getHandle().setSpell(spell == null ? EntityIllagerWizard.Spell.NONE : EntityIllagerWizard.Spell.a(spell.ordinal())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEvokerFangs.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEvokerFangs.java deleted file mode 100644 index 14e0accf8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEvokerFangs.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityEvokerFangs; -import net.minecraft.server.EntityLiving; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.EvokerFangs; -import org.bukkit.entity.LivingEntity; - -public class CraftEvokerFangs extends CraftEntity implements EvokerFangs { - - public CraftEvokerFangs(CraftServer server, EntityEvokerFangs entity) { - super(server, entity); - } - - @Override - public EntityEvokerFangs getHandle() { - return (EntityEvokerFangs) super.getHandle(); - } - - @Override - public String toString() { - return "CraftEvokerFangs"; - } - - @Override - public EntityType getType() { - return EntityType.EVOKER_FANGS; - } - - @Override - public LivingEntity getOwner() { - EntityLiving owner = getHandle().getOwner(); - - return (owner == null) ? null : (LivingEntity) owner.getBukkitEntity(); - } - - @Override - public void setOwner(LivingEntity owner) { - getHandle().a(owner == null ? null : ((CraftLivingEntity) owner).getHandle()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java deleted file mode 100644 index fbad04567..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java +++ /dev/null @@ -1,49 +0,0 @@ -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); - } - - @Override - public int getExperience() { - return getHandle().value; - } - - @Override - public void setExperience(int value) { - getHandle().value = value; - } - - // Paper start - public java.util.UUID getTriggerEntityId() { - return getHandle().triggerEntityId; - } - public java.util.UUID getSourceEntityId() { - return getHandle().sourceEntityId; - } - public SpawnReason getSpawnReason() { - return getHandle().spawnReason; - } - // Paper end - - @Override - public EntityExperienceOrb getHandle() { - return (EntityExperienceOrb) entity; - } - - @Override - public String toString() { - return "CraftExperienceOrb"; - } - - @Override - public EntityType getType() { - return EntityType.EXPERIENCE_ORB; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingBlock.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingBlock.java deleted file mode 100644 index 7a6676b4a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingBlock.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityFallingBlock; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.FallingBlock; - -public class CraftFallingBlock extends CraftEntity implements FallingBlock { - - public CraftFallingBlock(CraftServer server, EntityFallingBlock entity) { - super(server, entity); - } - - @Override - public EntityFallingBlock getHandle() { - return (EntityFallingBlock) entity; - } - - @Override - public String toString() { - return "CraftFallingBlock"; - } - - @Override - public EntityType getType() { - return EntityType.FALLING_BLOCK; - } - - @Override - public Material getMaterial() { - return CraftMagicNumbers.getMaterial(getHandle().getBlock()).getItemType(); - } - - @Override - public BlockData getBlockData() { - return CraftBlockData.fromData(getHandle().getBlock()); - } - - @Override - public boolean getDropItem() { - return getHandle().dropItem; - } - - @Override - public void setDropItem(boolean drop) { - getHandle().dropItem = drop; - } - - @Override - public boolean canHurtEntities() { - return getHandle().hurtEntities; - } - - @Override - public void setHurtEntities(boolean hurtEntities) { - getHandle().hurtEntities = hurtEntities; - } - - @Override - public void setTicksLived(int value) { - super.setTicksLived(value); - - // Second field for EntityFallingBlock - getHandle().ticksLived = value; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java deleted file mode 100644 index f392f801b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java +++ /dev/null @@ -1,83 +0,0 @@ -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.projectiles.ProjectileSource; -import org.bukkit.util.Vector; - -public class CraftFireball extends AbstractProjectile implements Fireball { - public CraftFireball(CraftServer server, EntityFireball entity) { - super(server, entity); - } - - @Override - public float getYield() { - return getHandle().bukkitYield; - } - - @Override - public boolean isIncendiary() { - return getHandle().isIncendiary; - } - - @Override - public void setIsIncendiary(boolean isIncendiary) { - getHandle().isIncendiary = isIncendiary; - } - - @Override - public void setYield(float yield) { - getHandle().bukkitYield = yield; - } - - @Override - public ProjectileSource getShooter() { - return getHandle().projectileSource; - } - - @Override - public void setShooter(ProjectileSource shooter) { - if (shooter instanceof CraftLivingEntity) { - getHandle().shooter = ((CraftLivingEntity) shooter).getHandle(); - } else { - getHandle().shooter = null; - } - getHandle().projectileSource = shooter; - } - - @Override - public Vector getDirection() { - return new Vector(getHandle().dirX, getHandle().dirY, getHandle().dirZ); - } - - @Override - 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"; - } - - @Override - public EntityType getType() { - return EntityType.UNKNOWN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java deleted file mode 100644 index 219a1e4c0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import java.util.Random; -import net.minecraft.server.EntityFireworks; -import net.minecraft.server.EntityLiving; -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.entity.LivingEntity; -import org.bukkit.inventory.meta.FireworkMeta; - -import java.util.UUID; - -public class CraftFirework extends CraftEntity implements Firework { - - private final Random random = new Random(); - private final CraftItemStack item; - - public CraftFirework(CraftServer server, EntityFireworks entity) { - super(server, entity); - - ItemStack item = getHandle().getDataWatcher().get(EntityFireworks.FIREWORK_ITEM); - - if (item.isEmpty()) { - item = new ItemStack(Items.FIREWORK_ROCKET); - getHandle().getDataWatcher().set(EntityFireworks.FIREWORK_ITEM, item); - } - - this.item = CraftItemStack.asCraftMirror(item); - - // Ensure the item is a firework... - if (this.item.getType() != Material.FIREWORK_ROCKET) { - this.item.setType(Material.FIREWORK_ROCKET); - } - } - - @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().markDirty(EntityFireworks.FIREWORK_ITEM); - } - - @Override - public void detonate() { - getHandle().expectedLifespan = 0; - } - - @Override - public boolean isShotAtAngle() { - return getHandle().i(); - } - - @Override - public void setShotAtAngle(boolean shotAtAngle) { - getHandle().getDataWatcher().set(EntityFireworks.d, shotAtAngle); - } - - // Paper start - @Override - public UUID getSpawningEntity() { - return getHandle().spawningEntity; - } - - @Override - public LivingEntity getBoostedEntity() { - EntityLiving boostedEntity = getHandle().getBoostedEntity(); - return boostedEntity != null ? (LivingEntity) boostedEntity.getBukkitEntity() : null; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java deleted file mode 100644 index 6169119cf..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityFish; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Fish; - -public class CraftFish extends CraftWaterMob implements Fish { - - public CraftFish(CraftServer server, EntityFish entity) { - super(server, entity); - } - - @Override - public EntityFish getHandle() { - return (EntityFish) entity; - } - - @Override - public String toString() { - return "CraftFish"; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java deleted file mode 100644 index 9eb980137..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.BlockPosition; -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.FishHook; -import org.bukkit.projectiles.ProjectileSource; - -public class CraftFishHook extends AbstractProjectile implements FishHook { - private double biteChance = -1; - - public CraftFishHook(CraftServer server, EntityFishingHook entity) { - super(server, entity); - } - - @Override - public ProjectileSource getShooter() { - if (getHandle().owner != null) { - return getHandle().owner.getBukkitEntity(); - } - - return null; - } - - @Override - 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 "CraftFishingHook"; - } - - @Override - public EntityType getType() { - return EntityType.FISHING_HOOK; - } - - @Override - public double getBiteChance() { - EntityFishingHook hook = getHandle(); - - if (this.biteChance == -1) { - if (hook.world.isRainingAt(new BlockPosition(MathHelper.floor(hook.locX), MathHelper.floor(hook.locY) + 1, MathHelper.floor(hook.locZ)))) { - return 1/300.0; - } - return 1/500.0; - } - return this.biteChance; - } - - @Override - public void setBiteChance(double chance) { - Validate.isTrue(chance >= 0 && chance <= 1, "The bite chance must be between 0 and 1."); - this.biteChance = chance; - } - - // Paper start - @Override - public void remove() { - super.remove(); - if (getHandle().owner != null) { - getHandle().owner.hookedFish = null; - } - } - // Paper end - -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java deleted file mode 100644 index 6b0c33b39..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityFlying; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Flying; - -public class CraftFlying extends CraftMob 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/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java deleted file mode 100644 index 2e2c253f4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.EntityFox; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Fox; - -public class CraftFox extends CraftAnimals implements Fox { - - public CraftFox(CraftServer server, EntityFox entity) { - super(server, entity); - } - - @Override - public EntityFox getHandle() { - return (EntityFox) super.getHandle(); - } - - @Override - public EntityType getType() { - return EntityType.FOX; - } - - @Override - public String toString() { - return "CraftFox"; - } - - @Override - public Type getFoxType() { - return Type.values()[getHandle().getFoxType().ordinal()]; - } - - @Override - public void setFoxType(Type type) { - Preconditions.checkArgument(type != null, "type"); - - getHandle().setFoxType(EntityFox.Type.values()[type.ordinal()]); - } - - @Override - public boolean isCrouching() { - return getHandle().isCrouching(); - } - - @Override - public void setCrouching(boolean crouching) { - getHandle().setCrouching(crouching); - } - - @Override - public boolean isSitting() { - return getHandle().isSitting(); - } - - @Override - public void setSitting(boolean sitting) { - getHandle().setSitting(sitting); - } - - @Override - public void setSleeping(boolean sleeping) { - getHandle().setSleeping(sleeping); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java deleted file mode 100644 index cac82ce76..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java +++ /dev/null @@ -1,28 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.GHAST; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java deleted file mode 100644 index ecbead90a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java +++ /dev/null @@ -1,28 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.GIANT; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java deleted file mode 100644 index 1fef5e029..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java +++ /dev/null @@ -1,21 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java deleted file mode 100644 index fd4f774f0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityGuardian; -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 false; - } - - @Override - public void setElder(boolean shouldBeElder) { - throw new UnsupportedOperationException("Not supported."); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java deleted file mode 100644 index 54a9f39d2..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java +++ /dev/null @@ -1,74 +0,0 @@ -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.craftbukkit.block.CraftBlock; -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); - } - - @Override - public BlockFace getAttachedFace() { - return getFacing().getOppositeFace(); - } - - @Override - public void setFacingDirection(BlockFace face) { - setFacingDirection(face, false); - } - - @Override - public boolean setFacingDirection(BlockFace face, boolean force) { - EntityHanging hanging = getHandle(); - EnumDirection dir = hanging.getDirection(); - 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; - } - - @Override - public BlockFace getFacing() { - EnumDirection direction = this.getHandle().getDirection(); - if (direction == null) return BlockFace.SELF; - return CraftBlock.notchToBlockFace(direction); - } - - @Override - public EntityHanging getHandle() { - return (EntityHanging) entity; - } - - @Override - public String toString() { - return "CraftHanging"; - } - - @Override - public EntityType getType() { - return EntityType.UNKNOWN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java deleted file mode 100644 index 98ef44c30..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -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.EntityType; -import org.bukkit.entity.Horse; -import org.bukkit.inventory.HorseInventory; - -public class CraftHorse extends CraftAbstractHorse implements Horse { - - public CraftHorse(CraftServer server, EntityHorse entity) { - super(server, entity); - } - - @Override - public EntityHorse getHandle() { - return (EntityHorse) super.getHandle(); - } - - @Override - public Variant getVariant() { - return Variant.HORSE; - } - - @Override - public Color getColor() { - return Color.values()[getHandle().getVariant() & 0xFF]; - } - - @Override - public void setColor(Color color) { - Validate.notNull(color, "Color cannot be null"); - getHandle().setVariant(color.ordinal() & 0xFF | getStyle().ordinal() << 8); - } - - @Override - public Style getStyle() { - return Style.values()[getHandle().getVariant() >>> 8]; - } - - @Override - public void setStyle(Style style) { - Validate.notNull(style, "Style cannot be null"); - getHandle().setVariant(getColor().ordinal() & 0xFF | style.ordinal() << 8); - } - - @Override - public boolean isCarryingChest() { - return false; - } - - @Override - public void setCarryingChest(boolean chest) { - throw new UnsupportedOperationException("Not supported."); - } - - @Override - public HorseInventory getInventory() { - return new CraftInventoryHorse(getHandle().inventoryChest); - } - - @Override - public String toString() { - return "CraftHorse{variant=" + getVariant() + ", owner=" + getOwner() + '}'; - } - - @Override - public EntityType getType() { - return EntityType.HORSE; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java deleted file mode 100644 index 81cf5f47a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java +++ /dev/null @@ -1,785 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Optional; -import java.util.Set; -import net.minecraft.server.BlockBed; -import net.minecraft.server.BlockEnchantmentTable; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.BlockWorkbench; -import net.minecraft.server.Blocks; -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.Container; -import net.minecraft.server.Containers; -import net.minecraft.server.CraftingManager; -import net.minecraft.server.Entity; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.EntityMinecartHopper; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.EnumMainHand; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IChatBaseComponent; -import net.minecraft.server.IInventory; -import net.minecraft.server.IMerchant; -import net.minecraft.server.IRecipe; -import net.minecraft.server.ITileInventory; -import net.minecraft.server.ItemCooldown; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.PacketPlayInCloseWindow; -import net.minecraft.server.PacketPlayOutOpenWindow; -import net.minecraft.server.TileEntity; -import net.minecraft.server.TileEntityBarrel; -import net.minecraft.server.TileEntityBeacon; -import net.minecraft.server.TileEntityBlastFurnace; -import net.minecraft.server.TileEntityBrewingStand; -import net.minecraft.server.TileEntityDispenser; -import net.minecraft.server.TileEntityDropper; -import net.minecraft.server.TileEntityFurnaceFurnace; -import net.minecraft.server.TileEntityHopper; -import net.minecraft.server.TileEntityLectern; -import net.minecraft.server.TileEntityShulkerBox; -import net.minecraft.server.TileEntitySmoker; -import net.minecraft.server.Vec3D; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.event.CraftEventFactory; -import org.bukkit.craftbukkit.inventory.CraftContainer; -import org.bukkit.craftbukkit.inventory.CraftInventory; -import org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest; -import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer; -import org.bukkit.craftbukkit.inventory.CraftInventoryView; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.inventory.CraftMerchantCustom; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.Villager; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.EntityEquipment; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.MainHand; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.PlayerInventory; -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; - -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()); - } - - @Override - public PlayerInventory getInventory() { - return inventory; - } - - @Override - public EntityEquipment getEquipment() { - return inventory; - } - - @Override - public Inventory getEnderChest() { - return enderChest; - } - - @Override - public MainHand getMainHand() { - return getHandle().getMainHand()== EnumMainHand.LEFT ? MainHand.LEFT : MainHand.RIGHT; - } - - @Override - public ItemStack getItemInHand() { - return getInventory().getItemInHand(); - } - - @Override - public void setItemInHand(ItemStack item) { - getInventory().setItemInHand(item); - } - - @Override - public ItemStack getItemOnCursor() { - return CraftItemStack.asCraftMirror(getHandle().inventory.getCarried()); - } - - @Override - 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 - } - } - - @Override - public int getSleepTicks() { - return getHandle().sleepTicks; - } - - @Override - public Location getBedSpawnLocation() { - World world = getServer().getWorld(getHandle().spawnWorld); - BlockPosition bed = getHandle().getBed(); - - if (world != null && bed != null) { - Optional spawnLoc = EntityHuman.getBed(((CraftWorld) world).getHandle(), bed, getHandle().isRespawnForced()); - if (spawnLoc.isPresent()) { - Vec3D vec = spawnLoc.get(); - return new Location(world, vec.x, vec.y, vec.z); - } - } - 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 boolean sleep(Location location, boolean force) { - Preconditions.checkArgument(location != null, "Location cannot be null"); - Preconditions.checkArgument(location.getWorld() != null, "Location needs to be in a world"); - Preconditions.checkArgument(location.getWorld().equals(getWorld()), "Cannot sleep across worlds"); - - BlockPosition blockposition = new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - IBlockData iblockdata = getHandle().world.getType(blockposition); - if (!(iblockdata.getBlock() instanceof BlockBed)) { - return false; - } - - if (getHandle().sleep(blockposition, force).left().isPresent()) { - return false; - } - - // From BlockBed - iblockdata = (IBlockData) iblockdata.set(BlockBed.OCCUPIED, true); - getHandle().world.setTypeAndData(blockposition, iblockdata, 4); - - return true; - } - - @Override - public void wakeup(boolean setSpawnLocation) { - Preconditions.checkState(isSleeping(), "Cannot wakeup if not sleeping"); - - getHandle().wakeup(true, true, setSpawnLocation); - } - - @Override - public Location getBedLocation() { - Preconditions.checkState(isSleeping(), "Not sleeping"); - - BlockPosition bed = getHandle().getBed(); - return new Location(getWorld(), bed.getX(), bed.getY(), bed.getZ()); - } - - @Override - public String getName() { - return getHandle().getName(); - } - - @Override - public boolean isOp() { - return op; - } - - @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 void setOp(boolean value) { - this.op = value; - perm.recalculatePermissions(); - } - - @Override - public Set getEffectivePermissions() { - return perm.getEffectivePermissions(); - } - - @Override - public GameMode getGameMode() { - return mode; - } - - @Override - 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() + '}'; - } - - @Override - public InventoryView getOpenInventory() { - return getHandle().activeContainer.getBukkitView(); - } - - @Override - public InventoryView openInventory(Inventory inventory) { - if(!(getHandle() instanceof EntityPlayer)) return null; - EntityPlayer player = (EntityPlayer) getHandle(); - InventoryType type = inventory.getType(); - Container formerContainer = getHandle().activeContainer; - - ITileInventory iinventory = null; - if (inventory instanceof CraftInventoryDoubleChest) { - iinventory = ((CraftInventoryDoubleChest) inventory).tile; - } else if (inventory instanceof CraftInventory) { - CraftInventory craft = (CraftInventory) inventory; - if (craft.getInventory() instanceof ITileInventory) { - iinventory = (ITileInventory) craft.getInventory(); - } - } - - if (iinventory instanceof ITileInventory) { - if (iinventory instanceof TileEntity) { - TileEntity te = (TileEntity) iinventory; - if (!te.hasWorld()) { - te.setWorld(getHandle().world); - } - } - } - - switch (type) { - case PLAYER: - case CHEST: - case ENDER_CHEST: - if (iinventory instanceof ITileInventory) { - getHandle().openContainer((ITileInventory) iinventory); - } else { - Containers customSize; - switch (inventory.getSize()) { - case 9: - customSize = Containers.GENERIC_9X1; - break; - case 18: - customSize = Containers.GENERIC_9X2; - break; - case 27: - customSize = Containers.GENERIC_9X3; - break; - case 36: - case 41: // PLAYER - customSize = Containers.GENERIC_9X4; - break; - case 45: - customSize = Containers.GENERIC_9X5; - break; - case 54: - customSize = Containers.GENERIC_9X6; - break; - default: - throw new IllegalArgumentException("Unsupported custom inventory size " + inventory.getSize()); - } - openCustomInventory(inventory, player, customSize); - } - break; - case DISPENSER: - if (iinventory instanceof TileEntityDispenser) { - getHandle().openContainer((TileEntityDispenser) iinventory); - } else { - openCustomInventory(inventory, player, Containers.GENERIC_3X3); - } - break; - case DROPPER: - if (iinventory instanceof TileEntityDropper) { - getHandle().openContainer((TileEntityDropper) iinventory); - } else { - openCustomInventory(inventory, player, Containers.GENERIC_3X3); - } - break; - case FURNACE: - if (iinventory instanceof TileEntityFurnaceFurnace) { - getHandle().openContainer((TileEntityFurnaceFurnace) iinventory); - } else { - openCustomInventory(inventory, player, Containers.FURNACE); - } - break; - case WORKBENCH: - openCustomInventory(inventory, player, Containers.CRAFTING); - break; - case BREWING: - if (iinventory instanceof TileEntityBrewingStand) { - getHandle().openContainer((TileEntityBrewingStand) iinventory); - } else { - openCustomInventory(inventory, player, Containers.BREWING_STAND); - } - break; - case ENCHANTING: - openCustomInventory(inventory, player, Containers.ENCHANTMENT); - break; - case HOPPER: - if (iinventory instanceof TileEntityHopper) { - getHandle().openContainer((TileEntityHopper) iinventory); - } else if (iinventory instanceof EntityMinecartHopper) { - getHandle().openContainer((EntityMinecartHopper) iinventory); - } else { - openCustomInventory(inventory, player, Containers.HOPPER); - } - break; - case BEACON: - if (iinventory instanceof TileEntityBeacon) { - getHandle().openContainer((TileEntityBeacon) iinventory); - } else { - openCustomInventory(inventory, player, Containers.BEACON); - } - break; - case ANVIL: - if (iinventory instanceof ITileInventory) { - getHandle().openContainer((ITileInventory) iinventory); - } else { - openCustomInventory(inventory, player, Containers.ANVIL); - } - break; - case SHULKER_BOX: - if (iinventory instanceof TileEntityShulkerBox) { - getHandle().openContainer((TileEntityShulkerBox) iinventory); - } else { - openCustomInventory(inventory, player, Containers.SHULKER_BOX); - } - break; - case BARREL: - if (iinventory instanceof TileEntityBarrel) { - getHandle().openContainer((TileEntityBarrel) iinventory); - } else { - openCustomInventory(inventory, player, Containers.GENERIC_9X3); - } - break; - case BLAST_FURNACE: - if (iinventory instanceof TileEntityBlastFurnace) { - getHandle().openContainer((TileEntityBlastFurnace) iinventory); - } else { - openCustomInventory(inventory, player, Containers.BLAST_FURNACE); - } - break; - case LECTERN: - if (iinventory instanceof TileEntityLectern) { - getHandle().openContainer((TileEntityLectern) iinventory); - } else { - openCustomInventory(inventory, player, Containers.LECTERN); - } - break; - case SMOKER: - if (iinventory instanceof TileEntitySmoker) { - getHandle().openContainer((TileEntitySmoker) iinventory); - } else { - openCustomInventory(inventory, player, Containers.SMOKER); - } - break; - case STONECUTTER: - openCustomInventory(inventory, player, Containers.STONECUTTER); - break; - case LOOM: - openCustomInventory(inventory, player, Containers.LOOM); - break; - case CARTOGRAPHY: - openCustomInventory(inventory, player, Containers.CARTOGRAPHY); - break; - case GRINDSTONE: - openCustomInventory(inventory, player, Containers.GRINDSTONE); - break; - case CREATIVE: - case CRAFTING: - case MERCHANT: - default: - 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, Containers windowType) { - if (player.playerConnection == null) return; - Preconditions.checkArgument(windowType != null, "Unknown windowType"); - Container container = new CraftContainer(inventory, this.getHandle(), player.nextContainerCounter()); - - container = CraftEventFactory.callInventoryOpenEvent(player, container); - if(container == null) return; - - String title = container.getBukkitView().getTitle(); - - player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(container.windowId, windowType, new ChatComponentText(title))); - getHandle().activeContainer = container; - getHandle().activeContainer.addSlotListener(player); - } - - @Override - public InventoryView openWorkbench(Location location, boolean force) { - if (!force) { - Block block = location.getBlock(); - if (block.getType() != Material.CRAFTING_TABLE) { - return null; - } - } - if (location == null) { - location = getLocation(); - } - getHandle().openContainer(((BlockWorkbench) Blocks.CRAFTING_TABLE).getInventory(null, getHandle().world, new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()))); - if (force) { - getHandle().activeContainer.checkReachable = false; - } - return getHandle().activeContainer.getBukkitView(); - } - - @Override - public InventoryView openEnchanting(Location location, boolean force) { - if (!force) { - Block block = location.getBlock(); - if (block.getType() != Material.ENCHANTING_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. - BlockPosition pos = new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - getHandle().openContainer(((BlockEnchantmentTable) Blocks.ENCHANTING_TABLE).getInventory(null, getHandle().world, pos)); - - if (force) { - getHandle().activeContainer.checkReachable = false; - } - return getHandle().activeContainer.getBukkitView(); - } - - @Override - 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, this.getHandle(), player.nextContainerCounter()); - } - - // Trigger an INVENTORY_OPEN event - container = CraftEventFactory.callInventoryOpenEvent(player, container); - if (container == null) { - return; - } - - // Now open the window - InventoryType type = inventory.getType(); - Containers windowType = CraftContainer.getNotchInventoryType(type); - String title = inventory.getTitle(); - player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(container.windowId, windowType, new ChatComponentText(title))); - player.activeContainer = container; - player.activeContainer.addSlotListener(player); - } - - @Override - public InventoryView openMerchant(Villager villager, boolean force) { - Preconditions.checkNotNull(villager, "villager cannot be null"); - - return this.openMerchant((Merchant) villager, force); - } - - @Override - public InventoryView openMerchant(Merchant merchant, boolean force) { - Preconditions.checkNotNull(merchant, "merchant cannot be null"); - - if (!force && merchant.isTrading()) { - return null; - } else if (merchant.isTrading()) { - // we're not supposed to have multiple people using the same merchant, so we have to close it. - merchant.getTrader().closeInventory(); - } - - IMerchant mcMerchant; - IChatBaseComponent name; - int level = 1; // note: using level 0 with active 'is-regular-villager'-flag allows hiding the name suffix - if (merchant instanceof CraftAbstractVillager) { - mcMerchant = ((CraftAbstractVillager) merchant).getHandle(); - name = ((CraftAbstractVillager) merchant).getHandle().getScoreboardDisplayName(); - if (merchant instanceof CraftVillager) { - level = ((CraftVillager) merchant).getHandle().getVillagerData().getLevel(); - } - } else if (merchant instanceof CraftMerchantCustom) { - mcMerchant = ((CraftMerchantCustom) merchant).getMerchant(); - name = ((CraftMerchantCustom) merchant).getMerchant().getScoreboardDisplayName(); - } else { - throw new IllegalArgumentException("Can't open merchant " + merchant.toString()); - } - - mcMerchant.setTradingPlayer(this.getHandle()); - mcMerchant.openTrade(this.getHandle(), name, level); - - return this.getHandle().activeContainer.getBukkitView(); - } - - @Override - public void closeInventory() { - // Paper start - getHandle().closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason.PLUGIN); - } - public void closeInventory(org.bukkit.event.inventory.InventoryCloseEvent.Reason reason) { - getHandle().closeInventory(reason); - } - // Paper end - - @Override - public boolean isBlocking() { - return getHandle().isBlocking(); - } - - @Override - public boolean isHandRaised() { - return getHandle().isHandRaised(); - } - - @Override - public boolean setWindowProperty(InventoryView.Property prop, int value) { - return false; - } - - @Override - public int getExpToLevel() { - return getHandle().getExpToLevel(); - } - - @Override - public boolean hasCooldown(Material material) { - Preconditions.checkArgument(material != null, "material"); - - return getHandle().getCooldownTracker().hasCooldown(CraftMagicNumbers.getItem(material)); - } - - @Override - public int getCooldown(Material material) { - Preconditions.checkArgument(material != null, "material"); - - ItemCooldown.Info cooldown = getHandle().getCooldownTracker().cooldowns.get(CraftMagicNumbers.getItem(material)); - return (cooldown == null) ? 0 : Math.max(0, cooldown.endTick - getHandle().getCooldownTracker().currentTick); - } - - @Override - public void setCooldown(Material material, int ticks) { - Preconditions.checkArgument(material != null, "material"); - Preconditions.checkArgument(ticks >= 0, "Cannot have negative cooldown"); - - getHandle().getCooldownTracker().setCooldown(CraftMagicNumbers.getItem(material), ticks); - } - - // Paper start - @Override - public org.bukkit.entity.Entity releaseLeftShoulderEntity() { - if (!getHandle().getShoulderEntityLeft().isEmpty()) { - Entity entity = getHandle().releaseLeftShoulderEntity(); - if (entity != null) { - return entity.getBukkitEntity(); - } - } - - return null; - } - - @Override - public org.bukkit.entity.Entity releaseRightShoulderEntity() { - if (!getHandle().getShoulderEntityRight().isEmpty()) { - Entity entity = getHandle().releaseRightShoulderEntity(); - if (entity != null) { - return entity.getBukkitEntity(); - } - } - - return null; - } - // Paper end - - @Override - public boolean discoverRecipe(NamespacedKey recipe) { - return discoverRecipes(Arrays.asList(recipe)) != 0; - } - - @Override - public int discoverRecipes(Collection recipes) { - return getHandle().discoverRecipes(bukkitKeysToMinecraftRecipes(recipes)); - } - - @Override - public boolean undiscoverRecipe(NamespacedKey recipe) { - return undiscoverRecipes(Arrays.asList(recipe)) != 0; - } - - @Override - public int undiscoverRecipes(Collection recipes) { - return getHandle().undiscoverRecipes(bukkitKeysToMinecraftRecipes(recipes)); - } - - private Collection> bukkitKeysToMinecraftRecipes(Collection recipeKeys) { - Collection> recipes = new ArrayList<>(); - CraftingManager manager = getHandle().world.getMinecraftServer().getCraftingManager(); - - for (NamespacedKey recipeKey : recipeKeys) { - Optional> recipe = manager.a(CraftNamespacedKey.toMinecraft(recipeKey)); - if (!recipe.isPresent()) { - continue; - } - - recipes.add(recipe.get()); - } - - return recipes; - } - - @Override - public org.bukkit.entity.Entity getShoulderEntityLeft() { - if (!getHandle().getShoulderEntityLeft().isEmpty()) { - Optional shoulder = EntityTypes.a(getHandle().getShoulderEntityLeft(), getHandle().world); - - return (!shoulder.isPresent()) ? null : shoulder.get().getBukkitEntity(); - } - - return null; - } - - @Override - public void setShoulderEntityLeft(org.bukkit.entity.Entity entity) { - getHandle().setShoulderEntityLeft(entity == null ? new NBTTagCompound() : ((CraftEntity) entity).save()); - if (entity != null) { - entity.remove(); - } - } - - @Override - public org.bukkit.entity.Entity getShoulderEntityRight() { - if (!getHandle().getShoulderEntityRight().isEmpty()) { - Optional shoulder = EntityTypes.a(getHandle().getShoulderEntityRight(), getHandle().world); - - return (!shoulder.isPresent()) ? null : shoulder.get().getBukkitEntity(); - } - - return null; - } - - @Override - public void setShoulderEntityRight(org.bukkit.entity.Entity entity) { - getHandle().setShoulderEntityRight(entity == null ? new NBTTagCompound() : ((CraftEntity) entity).save()); - if (entity != null) { - entity.remove(); - } - } - - // Paper start - Add method to open already placed sign - @Override - public void openSign(org.bukkit.block.Sign sign) { - org.apache.commons.lang.Validate.isTrue(sign.getWorld().equals(this.getWorld()), "Sign must be in the same world as player is in"); - org.bukkit.craftbukkit.block.CraftSign craftSign = (org.bukkit.craftbukkit.block.CraftSign) sign; - net.minecraft.server.TileEntitySign teSign = craftSign.getTileEntity(); - // Make sign editable temporarily, will be set back to false in PlayerConnection later - teSign.isEditable = true; - - getHandle().openSign(teSign); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHusk.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHusk.java deleted file mode 100644 index 46425820b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHusk.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityZombieHusk; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Husk; - -public class CraftHusk extends CraftZombie implements Husk { - - public CraftHusk(CraftServer server, EntityZombieHusk entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftHusk"; - } - - @Override - public EntityType getType() { - return EntityType.HUSK; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftIllager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftIllager.java deleted file mode 100644 index 9bdd1f1d4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftIllager.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityIllagerAbstract; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Illager; - -public class CraftIllager extends CraftRaider implements Illager { - - public CraftIllager(CraftServer server, EntityIllagerAbstract entity) { - super(server, entity); - } - - @Override - public EntityIllagerAbstract getHandle() { - return (EntityIllagerAbstract) super.getHandle(); - } - - @Override - public String toString() { - return "CraftIllager"; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftIllusioner.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftIllusioner.java deleted file mode 100644 index f31d3eed3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftIllusioner.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.destroystokyo.paper.entity.CraftRangedEntity; -import net.minecraft.server.EntityIllagerIllusioner; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Illusioner; - -public class CraftIllusioner extends CraftSpellcaster implements Illusioner, CraftRangedEntity { // Paper - - public CraftIllusioner(CraftServer server, EntityIllagerIllusioner entity) { - super(server, entity); - } - - @Override - public EntityIllagerIllusioner getHandle() { - return (EntityIllagerIllusioner) super.getHandle(); - } - - @Override - public String toString() { - return "CraftIllusioner"; - } - - @Override - public EntityType getType() { - return EntityType.ILLUSIONER; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java deleted file mode 100644 index 9ca8eeff5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java +++ /dev/null @@ -1,37 +0,0 @@ -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"; - } - - @Override - public boolean isPlayerCreated() { - return getHandle().isPlayerCreated(); - } - - @Override - public void setPlayerCreated(boolean playerCreated) { - getHandle().setPlayerCreated(playerCreated); - } - - @Override - public EntityType getType() { - return EntityType.IRON_GOLEM; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java deleted file mode 100644 index cb756b1ba..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java +++ /dev/null @@ -1,97 +0,0 @@ -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; - -// Paper start -import javax.annotation.Nullable; -import java.util.UUID; -// Paper end - -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); - } - - @Override - public ItemStack getItemStack() { - return CraftItemStack.asCraftMirror(item.getItemStack()); - } - - @Override - public void setItemStack(ItemStack stack) { - item.setItemStack(CraftItemStack.asNMSCopy(stack)); - } - - @Override - public int getPickupDelay() { - return item.pickupDelay; - } - - @Override - public void setPickupDelay(int delay) { - item.pickupDelay = Math.min(delay, Short.MAX_VALUE); - } - - @Override - public void setTicksLived(int value) { - super.setTicksLived(value); - - // Second field for EntityItem - item.age = value; - } - - // Paper Start - public boolean canMobPickup() { - return item.canMobPickup; - } - - public void setCanMobPickup(boolean canMobPickup) { - item.canMobPickup = canMobPickup; - } - - @Nullable - @Override - public UUID getOwner() { - return item.getOwner(); - } - - @Override - public void setOwner(@Nullable UUID owner) { - item.setOwner(owner); - } - - @Nullable - @Override - public UUID getThrower() { - return item.getThrower(); - } - - @Override - public void setThrower(@Nullable UUID thrower) { - item.setThrower(thrower); - } - // Paper End - - @Override - public String toString() { - return "CraftItem"; - } - - @Override - public EntityType getType() { - return EntityType.DROPPED_ITEM; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java deleted file mode 100644 index 9ad180d94..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java +++ /dev/null @@ -1,145 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.BlockPosition; -import net.minecraft.server.EntityHanging; -import net.minecraft.server.EntityItemFrame; -import net.minecraft.server.EnumDirection; -import net.minecraft.server.ItemStack; -import net.minecraft.server.WorldServer; -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.block.CraftBlock; -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); - } - - @Override - public boolean setFacingDirection(BlockFace face, boolean force) { - EntityHanging hanging = getHandle(); - EnumDirection oldDir = hanging.getDirection(); - EnumDirection newDir = CraftBlock.blockFaceToNotch(face); - - getHandle().setDirection(newDir); - if (!force && !hanging.survives()) { - hanging.setDirection(oldDir); - 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, true, false); // Paper - fix itemframe sound - world.addEntity(frame); - this.entity = frame; - } - - @Override - public void setItem(org.bukkit.inventory.ItemStack item) { - setItem(item, true); - } - - @Override - public void setItem(org.bukkit.inventory.ItemStack item, boolean playSound) { - getHandle().setItem(CraftItemStack.asNMSCopy(item), true, playSound); - } - - @Override - public org.bukkit.inventory.ItemStack getItem() { - return CraftItemStack.asBukkitCopy(getHandle().getItem()); - } - - @Override - 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()); - } - } - - @Override - 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() + "}"; - } - - @Override - public EntityType getType() { - return EntityType.ITEM_FRAME; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java deleted file mode 100644 index 9ab8f6606..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java +++ /dev/null @@ -1,33 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.FIREBALL; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java deleted file mode 100644 index 7114b5156..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.LEASH_HITCH; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java deleted file mode 100644 index e41de11c1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java +++ /dev/null @@ -1,48 +0,0 @@ -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); - } - - @Override - public boolean isEffect() { - return ((EntityLightning) super.getHandle()).isEffect; - } - - @Override - public EntityLightning getHandle() { - return (EntityLightning) entity; - } - - @Override - public String toString() { - return "CraftLightningStrike"; - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java deleted file mode 100644 index b27fd44dc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java +++ /dev/null @@ -1,715 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Sets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import net.minecraft.server.DamageSource; -import net.minecraft.server.EntityArmorStand; -import net.minecraft.server.EntityArrow; -import net.minecraft.server.EntityDragonFireball; -import net.minecraft.server.EntityEgg; -import net.minecraft.server.EntityEnderPearl; -import net.minecraft.server.EntityFireball; -import net.minecraft.server.EntityFishingHook; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.EntityInsentient; -import net.minecraft.server.EntityLargeFireball; -import net.minecraft.server.EntityLiving; -import net.minecraft.server.EntityLlamaSpit; -import net.minecraft.server.EntityPotion; -import net.minecraft.server.EntityProjectile; -import net.minecraft.server.EntityShulkerBullet; -import net.minecraft.server.EntitySmallFireball; -import net.minecraft.server.EntitySnowball; -import net.minecraft.server.EntitySpectralArrow; -import net.minecraft.server.EntityThrownExpBottle; -import net.minecraft.server.EntityThrownTrident; -import net.minecraft.server.EntityTippedArrow; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.EntityWither; -import net.minecraft.server.EntityWitherSkull; -import net.minecraft.server.GenericAttributes; -import net.minecraft.server.MobEffect; -import net.minecraft.server.MobEffectList; -import org.apache.commons.lang.Validate; -import org.bukkit.FluidCollisionMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeInstance; -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.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.craftbukkit.entity.memory.CraftMemoryKey; -import org.bukkit.craftbukkit.entity.memory.CraftMemoryMapper; -import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.DragonFireball; -import org.bukkit.entity.Egg; -import org.bukkit.entity.EnderPearl; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Fireball; -import org.bukkit.entity.FishHook; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.LingeringPotion; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.LlamaSpit; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.ShulkerBullet; -import org.bukkit.entity.SmallFireball; -import org.bukkit.entity.Snowball; -import org.bukkit.entity.SpectralArrow; -import org.bukkit.entity.ThrownExpBottle; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.entity.TippedArrow; -import org.bukkit.entity.Trident; -import org.bukkit.entity.WitherSkull; -import org.bukkit.entity.memory.MemoryKey; -import org.bukkit.event.entity.EntityPotionEffectEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.inventory.EntityEquipment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionType; -import org.bukkit.util.BlockIterator; -import org.bukkit.util.RayTraceResult; -import org.bukkit.util.Vector; - -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); - } - } - - @Override - public double getHealth() { - return Math.min(Math.max(0, getHandle().getHealth()), getMaxHealth()); - } - - @Override - public void setHealth(double health) { - health = (float) health; - if ((health < 0) || (health > getMaxHealth())) { - // Paper - Be more informative - throw new IllegalArgumentException("Health must be between 0 and " + getMaxHealth() + ", but was " + health - + ". (attribute base value: " + this.getHandle().getAttributeInstance(GenericAttributes.MAX_HEALTH).getBaseValue() - + (this instanceof CraftPlayer ? ", player: " + this.getName() + ')' : ')')); - } - - getHandle().setHealth((float) health); - - if (health == 0) { - getHandle().die(DamageSource.GENERIC); - } - } - - @Override - public double getAbsorptionAmount() { - return getHandle().getAbsorptionHearts(); - } - - @Override - public void setAbsorptionAmount(double amount) { - Preconditions.checkArgument(amount >= 0 && Double.isFinite(amount), "amount < 0 or non-finite"); - - getHandle().setAbsorptionHearts((float) amount); - } - - @Override - public double getMaxHealth() { - return getHandle().getMaxHealth(); - } - - @Override - public void setMaxHealth(double amount) { - Validate.isTrue(amount > 0, "Max health must be greater than 0"); - - getHandle().getAttributeInstance(GenericAttributes.MAX_HEALTH).setValue(amount); - - if (getHealth() > amount) { - setHealth(amount); - } - } - - @Override - public void resetMaxHealth() { - setMaxHealth(getHandle().getAttributeInstance(GenericAttributes.MAX_HEALTH).getAttribute().getDefault()); - } - - @Override - public double getEyeHeight() { - return getHandle().getHeadHeight(); - } - - @Override - public double getEyeHeight(boolean ignorePose) { - return getEyeHeight(); - } - - private List getLineOfSight(Set transparent, int maxDistance, int maxLength) { - if (transparent == null) { - transparent = Sets.newHashSet(Material.AIR, Material.CAVE_AIR, Material.VOID_AIR); - } - 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.contains(material)) { - break; - } - } - return blocks; - } - - @Override - public List getLineOfSight(Set transparent, int maxDistance) { - return getLineOfSight(transparent, maxDistance, 0); - } - - @Override - public Block getTargetBlock(Set transparent, int maxDistance) { - List blocks = getLineOfSight(transparent, maxDistance, 1); - return blocks.get(0); - } - - // Paper start - @Override - public Block getTargetBlock(int maxDistance, com.destroystokyo.paper.block.TargetBlockInfo.FluidMode fluidMode) { - net.minecraft.server.MovingObjectPosition rayTrace = getHandle().getRayTrace(maxDistance, net.minecraft.server.MCUtil.getNMSFluidCollisionOption(fluidMode)); - return !(rayTrace instanceof net.minecraft.server.MovingObjectPositionBlock) ? null : org.bukkit.craftbukkit.block.CraftBlock.at(getHandle().world, ((net.minecraft.server.MovingObjectPositionBlock)rayTrace).getBlockPosition()); - } - - @Override - public org.bukkit.block.BlockFace getTargetBlockFace(int maxDistance, com.destroystokyo.paper.block.TargetBlockInfo.FluidMode fluidMode) { - net.minecraft.server.MovingObjectPosition rayTrace = getHandle().getRayTrace(maxDistance, net.minecraft.server.MCUtil.getNMSFluidCollisionOption(fluidMode)); - return !(rayTrace instanceof net.minecraft.server.MovingObjectPositionBlock) ? null : net.minecraft.server.MCUtil.toBukkitBlockFace(((net.minecraft.server.MovingObjectPositionBlock)rayTrace).getDirection()); - } - - @Override - public com.destroystokyo.paper.block.TargetBlockInfo getTargetBlockInfo(int maxDistance, com.destroystokyo.paper.block.TargetBlockInfo.FluidMode fluidMode) { - net.minecraft.server.MovingObjectPosition rayTrace = getHandle().getRayTrace(maxDistance, net.minecraft.server.MCUtil.getNMSFluidCollisionOption(fluidMode)); - return !(rayTrace instanceof net.minecraft.server.MovingObjectPositionBlock) ? null : - new com.destroystokyo.paper.block.TargetBlockInfo(org.bukkit.craftbukkit.block.CraftBlock.at(getHandle().world, ((net.minecraft.server.MovingObjectPositionBlock)rayTrace).getBlockPosition()), - net.minecraft.server.MCUtil.toBukkitBlockFace(((net.minecraft.server.MovingObjectPositionBlock)rayTrace).getDirection())); - } - - public Entity getTargetEntity(int maxDistance, boolean ignoreBlocks) { - net.minecraft.server.MovingObjectPositionEntity rayTrace = rayTraceEntity(maxDistance, ignoreBlocks); - return rayTrace == null ? null : rayTrace.getEntity().getBukkitEntity(); - } - - public com.destroystokyo.paper.entity.TargetEntityInfo getTargetEntityInfo(int maxDistance, boolean ignoreBlocks) { - net.minecraft.server.MovingObjectPositionEntity rayTrace = rayTraceEntity(maxDistance, ignoreBlocks); - return rayTrace == null ? null : new com.destroystokyo.paper.entity.TargetEntityInfo(rayTrace.getEntity().getBukkitEntity(), new org.bukkit.util.Vector(rayTrace.getPos().x, rayTrace.getPos().y, rayTrace.getPos().z)); - } - - public net.minecraft.server.MovingObjectPositionEntity rayTraceEntity(int maxDistance, boolean ignoreBlocks) { - net.minecraft.server.MovingObjectPositionEntity rayTrace = getHandle().getTargetEntity(maxDistance); - if (rayTrace == null) { - return null; - } - if (!ignoreBlocks) { - net.minecraft.server.MovingObjectPosition rayTraceBlocks = getHandle().getRayTrace(maxDistance, net.minecraft.server.RayTrace.FluidCollisionOption.NONE); - if (rayTraceBlocks != null) { - net.minecraft.server.Vec3D eye = getHandle().getEyePosition(1.0F); - if (eye.distanceSquared(rayTraceBlocks.getPos()) <= eye.distanceSquared(rayTrace.getPos())) { - return null; - } - } - } - return rayTrace; - } - // Paper end - - @Override - public List getLastTwoTargetBlocks(Set transparent, int maxDistance) { - return getLineOfSight(transparent, maxDistance, 2); - } - - @Override - public Block getTargetBlockExact(int maxDistance) { - return this.getTargetBlockExact(maxDistance, FluidCollisionMode.NEVER); - } - - @Override - public Block getTargetBlockExact(int maxDistance, FluidCollisionMode fluidCollisionMode) { - RayTraceResult hitResult = this.rayTraceBlocks(maxDistance, fluidCollisionMode); - return (hitResult != null ? hitResult.getHitBlock() : null); - } - - @Override - public RayTraceResult rayTraceBlocks(double maxDistance) { - return this.rayTraceBlocks(maxDistance, FluidCollisionMode.NEVER); - } - - @Override - public RayTraceResult rayTraceBlocks(double maxDistance, FluidCollisionMode fluidCollisionMode) { - Location eyeLocation = this.getEyeLocation(); - Vector direction = eyeLocation.getDirection(); - return this.getWorld().rayTraceBlocks(eyeLocation, direction, maxDistance, fluidCollisionMode, false); - } - - @Override - public int getRemainingAir() { - return getHandle().getAirTicks(); - } - - @Override - public void setRemainingAir(int ticks) { - getHandle().setAirTicks(ticks); - } - - @Override - public int getMaximumAir() { - return getHandle().maxAirTicks; - } - - @Override - public void setMaximumAir(int ticks) { - getHandle().maxAirTicks = ticks; - } - - @Override - public void damage(double amount) { - damage(amount, null); - } - - @Override - 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); - } - - @Override - public Location getEyeLocation() { - Location loc = getLocation(); - loc.setY(loc.getY() + getEyeHeight()); - return loc; - } - - @Override - public int getMaximumNoDamageTicks() { - return getHandle().maxNoDamageTicks; - } - - @Override - public void setMaximumNoDamageTicks(int ticks) { - getHandle().maxNoDamageTicks = ticks; - } - - @Override - public double getLastDamage() { - return getHandle().lastDamage; - } - - @Override - public void setLastDamage(double damage) { - getHandle().lastDamage = (float) damage; - } - - @Override - public int getNoDamageTicks() { - return getHandle().noDamageTicks; - } - - @Override - public void setNoDamageTicks(int ticks) { - getHandle().noDamageTicks = ticks; - } - - @Override - public EntityLiving getHandle() { - return (EntityLiving) entity; - } - - public void setHandle(final EntityLiving entity) { - super.setHandle(entity); - } - - @Override - public String toString() { - return "CraftLivingEntity{" + "id=" + getEntityId() + '}'; - } - - @Override - public Player getKiller() { - return getHandle().killer == null ? null : (Player) getHandle().killer.getBukkitEntity(); - } - - // Paper start - @Override - public void setKiller(Player killer) { - net.minecraft.server.EntityPlayer entityPlayer = killer == null ? null : ((CraftPlayer) killer).getHandle(); - getHandle().killer = entityPlayer; - getHandle().lastDamager = entityPlayer; - getHandle().lastDamageByPlayerTime = entityPlayer == null ? 0 : 100; // 100 value taken from EntityLiving#damageEntity - } - // Paper end - - @Override - public boolean addPotionEffect(PotionEffect effect) { - return addPotionEffect(effect, false); - } - - @Override - public boolean addPotionEffect(PotionEffect effect, boolean force) { - if (hasPotionEffect(effect.getType())) { - if (!force) { - return false; - } - removePotionEffect(effect.getType()); - } - getHandle().addEffect(new MobEffect(MobEffectList.fromId(effect.getType().getId()), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()), EntityPotionEffectEvent.Cause.PLUGIN); - return true; - } - - @Override - public boolean addPotionEffects(Collection effects) { - boolean success = true; - for (PotionEffect effect : effects) { - success &= addPotionEffect(effect); - } - return success; - } - - @Override - public boolean hasPotionEffect(PotionEffectType type) { - return getHandle().hasEffect(MobEffectList.fromId(type.getId())); - } - - @Override - public PotionEffect getPotionEffect(PotionEffectType type) { - MobEffect handle = getHandle().getEffect(MobEffectList.fromId(type.getId())); - return (handle == null) ? null : new PotionEffect(PotionEffectType.getById(MobEffectList.getId(handle.getMobEffect())), handle.getDuration(), handle.getAmplifier(), handle.isAmbient(), handle.isShowParticles()); - } - - @Override - public void removePotionEffect(PotionEffectType type) { - getHandle().removeEffect(MobEffectList.fromId(type.getId()), EntityPotionEffectEvent.Cause.PLUGIN); - } - - @Override - public Collection getActivePotionEffects() { - List effects = new ArrayList(); - for (MobEffect handle : getHandle().effects.values()) { - effects.add(new PotionEffect(PotionEffectType.getById(MobEffectList.getId(handle.getMobEffect())), handle.getDuration(), handle.getAmplifier(), handle.isAmbient(), handle.isShowParticles())); - } - return effects; - } - - @Override - public T launchProjectile(Class projectile) { - return launchProjectile(projectile, null); - } - - @Override - @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()); - ((EntityProjectile) launch).a(getHandle(), getHandle().pitch, getHandle().yaw, 0.0F, 1.5F, 1.0F); // ItemSnowball - } else if (Egg.class.isAssignableFrom(projectile)) { - launch = new EntityEgg(world, getHandle()); - ((EntityProjectile) launch).a(getHandle(), getHandle().pitch, getHandle().yaw, 0.0F, 1.5F, 1.0F); // ItemEgg - } else if (EnderPearl.class.isAssignableFrom(projectile)) { - launch = new EntityEnderPearl(world, getHandle()); - ((EntityProjectile) launch).a(getHandle(), getHandle().pitch, getHandle().yaw, 0.0F, 1.5F, 1.0F); // ItemEnderPearl - } else if (AbstractArrow.class.isAssignableFrom(projectile)) { - if (TippedArrow.class.isAssignableFrom(projectile)) { - launch = new EntityTippedArrow(world, getHandle()); - ((EntityTippedArrow) launch).setType(CraftPotionUtil.fromBukkit(new PotionData(PotionType.WATER, false, false))); - } else if (SpectralArrow.class.isAssignableFrom(projectile)) { - launch = new EntitySpectralArrow(world, getHandle()); - } else if (Trident.class.isAssignableFrom(projectile)) { - launch = new EntityThrownTrident(world, getHandle(), new net.minecraft.server.ItemStack(net.minecraft.server.Items.TRIDENT)); - } else { - launch = new EntityTippedArrow(world, getHandle()); - } - ((EntityArrow) launch).a(getHandle(), getHandle().pitch, getHandle().yaw, 0.0F, 3.0F, 1.0F); // ItemBow - } else if (ThrownPotion.class.isAssignableFrom(projectile)) { - if (LingeringPotion.class.isAssignableFrom(projectile)) { - launch = new EntityPotion(world, getHandle()); - ((EntityPotion) launch).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.LINGERING_POTION, 1))); - } else { - launch = new EntityPotion(world, getHandle()); - ((EntityPotion) launch).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.SPLASH_POTION, 1))); - } - ((EntityProjectile) launch).a(getHandle(), getHandle().pitch, getHandle().yaw, -20.0F, 0.5F, 1.0F); // ItemSplashPotion - } else if (ThrownExpBottle.class.isAssignableFrom(projectile)) { - launch = new EntityThrownExpBottle(world, getHandle()); - ((EntityProjectile) launch).a(getHandle(), getHandle().pitch, getHandle().yaw, -20.0F, 0.7F, 1.0F); // ItemExpBottle - } else if (FishHook.class.isAssignableFrom(projectile) && getHandle() instanceof EntityHuman) { - launch = new EntityFishingHook((EntityHuman) getHandle(), world, 0, 0); - } 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 if (DragonFireball.class.isAssignableFrom(projectile)) { - launch = new EntityDragonFireball(world, getHandle(), direction.getX(), direction.getY(), direction.getZ()); - } else { - launch = new EntityLargeFireball(world, getHandle(), direction.getX(), direction.getY(), direction.getZ()); - } - - ((EntityFireball) launch).projectileSource = this; - launch.setPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); - } else if (LlamaSpit.class.isAssignableFrom(projectile)) { - Location location = getEyeLocation(); - Vector direction = location.getDirection(); - - launch = EntityTypes.LLAMA_SPIT.a(world); - - ((EntityLlamaSpit) launch).shooter = getHandle(); - ((EntityLlamaSpit) launch).shoot(direction.getX(), direction.getY(), direction.getZ(), 1.5F, 10.0F); // EntityLlama - launch.setPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); - } else if (ShulkerBullet.class.isAssignableFrom(projectile)) { - Location location = getEyeLocation(); - - launch = new EntityShulkerBullet(world, getHandle(), null, null); - 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(); - } - - @Override - public EntityType getType() { - return EntityType.UNKNOWN; - } - - @Override - public boolean hasLineOfSight(Entity other) { - return getHandle().hasLineOfSight(((CraftEntity) other).getHandle()); - } - - @Override - public boolean getRemoveWhenFarAway() { - return getHandle() instanceof EntityInsentient && !((EntityInsentient) getHandle()).persistent; - } - - @Override - public void setRemoveWhenFarAway(boolean remove) { - if (getHandle() instanceof EntityInsentient) { - ((EntityInsentient) getHandle()).persistent = !remove; - } - } - - @Override - public EntityEquipment getEquipment() { - return equipment; - } - - @Override - public void setCanPickupItems(boolean pickup) { - getHandle().canPickUpLoot = pickup; - } - - @Override - public boolean getCanPickupItems() { - return getHandle().canPickUpLoot; - } - - @Override - public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) { - if (getHealth() == 0) { - return false; - } - - return super.teleport(location, cause); - } - - @Override - public boolean isLeashed() { - if (!(getHandle() instanceof EntityInsentient)) { - return false; - } - return ((EntityInsentient) getHandle()).getLeashHolder() != null; - } - - @Override - 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; - } - - @Override - 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; - } - - @Override - public boolean isGliding() { - return getHandle().getFlag(7); - } - - @Override - public void setGliding(boolean gliding) { - getHandle().setFlag(7, gliding); - } - - @Override - public boolean isSwimming() { - return getHandle().isSwimming(); - } - - @Override - public void setSwimming(boolean swimming) { - getHandle().setSwimming(swimming); - } - - @Override - public boolean isRiptiding() { - return getHandle().isRiptiding(); - } - - @Override - public boolean isSleeping() { - return getHandle().isSleeping(); - } - - @Override - public AttributeInstance getAttribute(Attribute attribute) { - return getHandle().craftAttributes.getAttribute(attribute); - } - - @Override - public void setAI(boolean ai) { - if (this.getHandle() instanceof EntityInsentient) { - ((EntityInsentient) this.getHandle()).setNoAI(!ai); - } - } - - @Override - public boolean hasAI() { - return (this.getHandle() instanceof EntityInsentient) ? !((EntityInsentient) this.getHandle()).isNoAI(): false; - } - - @Override - public void setCollidable(boolean collidable) { - getHandle().collides = collidable; - } - - @Override - public boolean isCollidable() { - return getHandle().collides; - } - - @Override - public T getMemory(MemoryKey memoryKey) { - return (T) getHandle().getBehaviorController().getMemory(CraftMemoryKey.fromMemoryKey(memoryKey)).map(CraftMemoryMapper::fromNms).orElse(null); - } - - @Override - public void setMemory(MemoryKey memoryKey, T t) { - getHandle().getBehaviorController().setMemory(CraftMemoryKey.fromMemoryKey(memoryKey), CraftMemoryMapper.toNms(t)); - } - - // Paper start - @Override - public int getArrowsStuck() { - return getHandle().getArrowCount(); - } - - @Override - public void setArrowsStuck(int arrows) { - getHandle().setArrowCount(arrows); - } - - @Override - public int getShieldBlockingDelay() { - return getHandle().getShieldBlockingDelay(); - } - - @Override - public void setShieldBlockingDelay(int delay) { - getHandle().setShieldBlockingDelay(delay); - } - - @Override - public ItemStack getActiveItem() { - return getHandle().activeItem.asBukkitMirror(); - } - - @Override - public int getItemUseRemainingTime() { - return getHandle().getItemUseRemainingTime(); - } - - @Override - public int getHandRaisedTime() { - return getHandle().getHandRaisedTime(); - } - - @Override - public boolean isHandRaised() { - return getHandle().isHandRaised(); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLlama.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLlama.java deleted file mode 100644 index 3f94c5a92..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLlama.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.destroystokyo.paper.entity.CraftRangedEntity; -import com.google.common.base.Preconditions; -import net.minecraft.server.EntityLlama; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.inventory.CraftInventoryLlama; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Horse; -import org.bukkit.entity.Llama; -import org.bukkit.inventory.LlamaInventory; - -public class CraftLlama extends CraftChestedHorse implements Llama, CraftRangedEntity { // Paper - - public CraftLlama(CraftServer server, EntityLlama entity) { - super(server, entity); - } - - @Override - public EntityLlama getHandle() { - return (EntityLlama) super.getHandle(); - } - - @Override - public Color getColor() { - return Color.values()[getHandle().getVariant()]; - } - - @Override - public void setColor(Color color) { - Preconditions.checkArgument(color != null, "color"); - - getHandle().setVariant(color.ordinal()); - } - - @Override - public LlamaInventory getInventory() { - return new CraftInventoryLlama(getHandle().inventoryChest); - } - - @Override - public int getStrength() { - return getHandle().getStrength(); - } - - @Override - public void setStrength(int strength) { - Preconditions.checkArgument(1 <= strength && strength <= 5, "strength must be [1,5]"); - if (strength == getStrength()) return; - getHandle().setStrength(strength); - getHandle().loadChest(); - } - - @Override - public Horse.Variant getVariant() { - return Horse.Variant.LLAMA; - } - - @Override - public String toString() { - return "CraftLlama"; - } - - @Override - public EntityType getType() { - return EntityType.LLAMA; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftLlamaSpit.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftLlamaSpit.java deleted file mode 100644 index 68d10c23a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftLlamaSpit.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityLlamaSpit; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LlamaSpit; -import org.bukkit.projectiles.ProjectileSource; - -public class CraftLlamaSpit extends AbstractProjectile implements LlamaSpit { - - public CraftLlamaSpit(CraftServer server, EntityLlamaSpit entity) { - super(server, entity); - } - - @Override - public EntityLlamaSpit getHandle() { - return (EntityLlamaSpit) super.getHandle(); - } - - @Override - public String toString() { - return "CraftLlamaSpit"; - } - - @Override - public EntityType getType() { - return EntityType.LLAMA_SPIT; - } - - @Override - public ProjectileSource getShooter() { - return (getHandle().shooter != null) ? (ProjectileSource) getHandle().shooter.getBukkitEntity() : null; - } - - @Override - public void setShooter(ProjectileSource source) { - getHandle().shooter = (source != null) ? ((CraftLivingEntity) source).getHandle() : null; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java deleted file mode 100644 index 5e005c9e4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java +++ /dev/null @@ -1,28 +0,0 @@ -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); - } - - @Override - public EntityMagmaCube getHandle() { - return (EntityMagmaCube) entity; - } - - @Override - public String toString() { - return "CraftMagmaCube"; - } - - @Override - public EntityType getType() { - return EntityType.MAGMA_CUBE; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java deleted file mode 100644 index 2d82ea40a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.Blocks; -import net.minecraft.server.EntityMinecartAbstract; -import net.minecraft.server.IBlockData; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.entity.Minecart; -import org.bukkit.material.MaterialData; -import org.bukkit.util.Vector; - -public abstract class CraftMinecart extends CraftVehicle implements Minecart { - public CraftMinecart(CraftServer server, EntityMinecartAbstract entity) { - super(server, entity); - } - - @Override - public void setDamage(double damage) { - getHandle().setDamage((float) damage); - } - - @Override - public double getDamage() { - return getHandle().getDamage(); - } - - @Override - public double getMaxSpeed() { - return getHandle().maxSpeed; - } - - @Override - public void setMaxSpeed(double speed) { - if (speed >= 0D) { - getHandle().maxSpeed = speed; - } - } - - @Override - public boolean isSlowWhenEmpty() { - return getHandle().slowWhenEmpty; - } - - @Override - public void setSlowWhenEmpty(boolean slow) { - getHandle().slowWhenEmpty = slow; - } - - @Override - public Vector getFlyingVelocityMod() { - return getHandle().getFlyingVelocityMod(); - } - - @Override - public void setFlyingVelocityMod(Vector flying) { - getHandle().setFlyingVelocityMod(flying); - } - - @Override - public Vector getDerailedVelocityMod() { - return getHandle().getDerailedVelocityMod(); - } - - @Override - public void setDerailedVelocityMod(Vector derailed) { - getHandle().setDerailedVelocityMod(derailed); - } - - @Override - public EntityMinecartAbstract getHandle() { - return (EntityMinecartAbstract) entity; - } - - @Override - public void setDisplayBlock(MaterialData material) { - if(material != null) { - IBlockData block = CraftMagicNumbers.getBlock(material); - 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); - } - } - - @Override - public void setDisplayBlockData(BlockData blockData) { - if (blockData != null) { - IBlockData block = ((CraftBlockData) blockData).getState(); - 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); - } - } - - @Override - public MaterialData getDisplayBlock() { - IBlockData blockData = getHandle().getDisplayBlock(); - return CraftMagicNumbers.getMaterial(blockData); - } - - @Override - public BlockData getDisplayBlockData() { - IBlockData blockData = getHandle().getDisplayBlock(); - return CraftBlockData.fromData(blockData); - } - - @Override - public void setDisplayBlockOffset(int offset) { - getHandle().setDisplayBlockOffset(offset); - } - - @Override - public int getDisplayBlockOffset() { - return getHandle().getDisplayBlockOffset(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java deleted file mode 100644 index ab4807b2c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.destroystokyo.paper.loottable.PaperLootableEntityInventory; // Paper -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.minecart.StorageMinecart; -import org.bukkit.inventory.Inventory; - -@SuppressWarnings("deprecation") -public class CraftMinecartChest extends CraftMinecartContainer implements StorageMinecart, PaperLootableEntityInventory { // Paper - private final CraftInventory inventory; - - public CraftMinecartChest(CraftServer server, EntityMinecartChest entity) { - super(server, entity); - inventory = new CraftInventory(entity); - } - - @Override - public Inventory getInventory() { - return inventory; - } - - @Override - public String toString() { - return "CraftMinecartChest{" + "inventory=" + inventory + '}'; - } - - @Override - public EntityType getType() { - return EntityType.MINECART_CHEST; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java deleted file mode 100644 index 89affac56..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java +++ /dev/null @@ -1,137 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import java.util.Set; -import net.minecraft.server.EntityMinecartCommandBlock; -import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.util.CraftChatMessage; -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; - -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 EntityMinecartCommandBlock getHandle() { - return (EntityMinecartCommandBlock) entity; - } - - @Override - public String getCommand() { - return getHandle().getCommandBlock().getCommand(); - } - - @Override - public void setCommand(String command) { - getHandle().getCommandBlock().setCommand(command != null ? command : ""); - getHandle().getDataWatcher().set(EntityMinecartCommandBlock.COMMAND, getHandle().getCommandBlock().getCommand()); - } - - @Override - public void setName(String name) { - getHandle().getCommandBlock().setName(CraftChatMessage.fromStringOrNull(name)); - } - - @Override - public String toString() { - return "CraftMinecartCommand"; - } - - @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 CraftChatMessage.fromComponent(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/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartContainer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartContainer.java deleted file mode 100644 index fcc978784..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartContainer.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityMinecartAbstract; -import net.minecraft.server.EntityMinecartContainer; -import net.minecraft.server.MinecraftKey; -import org.bukkit.Bukkit; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.loot.LootTable; -import org.bukkit.loot.Lootable; - -public abstract class CraftMinecartContainer extends CraftMinecart implements Lootable { - - public CraftMinecartContainer(CraftServer server, EntityMinecartAbstract entity) { - super(server, entity); - } - - @Override - public EntityMinecartContainer getHandle() { - return (EntityMinecartContainer) entity; - } - - @Override - public void setLootTable(LootTable table) { - setLootTable(table, getSeed()); - } - - @Override - public LootTable getLootTable() { - MinecraftKey nmsTable = getHandle().lootTable; - if (nmsTable == null) { - return null; // return empty loot table? - } - - NamespacedKey key = CraftNamespacedKey.fromMinecraft(nmsTable); - return Bukkit.getLootTable(key); - } - - @Override - public void setSeed(long seed) { - setLootTable(getLootTable(), seed); - } - - @Override - public long getSeed() { - return getHandle().lootTableSeed; - } - - public void setLootTable(LootTable table, long seed) { // Paper - MinecraftKey newKey = (table == null) ? null : CraftNamespacedKey.toMinecraft(table.getKey()); - getHandle().setLootTable(newKey, seed); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java deleted file mode 100644 index b024359c9..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityMinecartFurnace; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.minecart.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"; - } - - @Override - public EntityType getType() { - return EntityType.MINECART_FURNACE; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java deleted file mode 100644 index f5b31237f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.destroystokyo.paper.loottable.PaperLootableEntityInventory; // Paper -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; - -public final class CraftMinecartHopper extends CraftMinecartContainer implements HopperMinecart, PaperLootableEntityInventory { // Paper - private final CraftInventory inventory; - - public CraftMinecartHopper(CraftServer server, EntityMinecartHopper entity) { - super(server, entity); - inventory = new CraftInventory(entity); - } - - @Override - public String toString() { - return "CraftMinecartHopper{" + "inventory=" + inventory + '}'; - } - - @Override - public EntityType getType() { - return EntityType.MINECART_HOPPER; - } - - @Override - public Inventory getInventory() { - return inventory; - } - - @Override - public boolean isEnabled() { - return ((EntityMinecartHopper) getHandle()).isEnabled(); - } - - @Override - public void setEnabled(boolean enabled) { - ((EntityMinecartHopper) getHandle()).setEnabled(enabled); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java deleted file mode 100644 index b6c86c01f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java +++ /dev/null @@ -1,22 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.MINECART_MOB_SPAWNER; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java deleted file mode 100644 index 1c2b32fc4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java +++ /dev/null @@ -1,22 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.MINECART; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java deleted file mode 100644 index 02c5589bc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java +++ /dev/null @@ -1,22 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.MINECART_TNT; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMob.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMob.java deleted file mode 100644 index 56c233872..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMob.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityInsentient; -import org.bukkit.Bukkit; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Mob; -import org.bukkit.loot.LootTable; - -public abstract class CraftMob extends CraftLivingEntity implements Mob { - public CraftMob(CraftServer server, EntityInsentient entity) { - super(server, entity); - paperPathfinder = new com.destroystokyo.paper.entity.PaperPathfinder(entity); // Paper - } - - private final com.destroystokyo.paper.entity.PaperPathfinder paperPathfinder; // Paper - @Override public com.destroystokyo.paper.entity.Pathfinder getPathfinder() { return paperPathfinder; } // Paper - @Override - public void setTarget(LivingEntity target) { - EntityInsentient entity = getHandle(); - if (target == null) { - entity.setGoalTarget(null, null, false); - } else if (target instanceof CraftLivingEntity) { - entity.setGoalTarget(((CraftLivingEntity) target).getHandle(), null, false); - } - } - - @Override - public CraftLivingEntity getTarget() { - if (getHandle().getGoalTarget() == null) return null; - - return (CraftLivingEntity) getHandle().getGoalTarget().getBukkitEntity(); - } - - @Override - public EntityInsentient getHandle() { - return (EntityInsentient) entity; - } - - @Override - public String toString() { - return "CraftMob"; - } - - @Override - public void setLootTable(LootTable table) { - getHandle().lootTableKey = (table == null) ? null : CraftNamespacedKey.toMinecraft(table.getKey()); - } - - @Override - public LootTable getLootTable() { - if (getHandle().lootTableKey == null) { - getHandle().lootTableKey = getHandle().getLootTable(); - } - - NamespacedKey key = CraftNamespacedKey.fromMinecraft(getHandle().lootTableKey); - return Bukkit.getLootTable(key); - } - - @Override - public void setSeed(long seed) { - getHandle().lootTableSeed = seed; - } - - @Override - public long getSeed() { - return getHandle().lootTableSeed; - } - - // Paper start - @Override - public boolean isInDaylight() { - return getHandle().isInDaylight(); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java deleted file mode 100644 index 6bfb4bc35..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java +++ /dev/null @@ -1,22 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/entity/CraftMule.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMule.java deleted file mode 100644 index cf9b3ac18..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMule.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityHorseMule; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Horse.Variant; -import org.bukkit.entity.Mule; - -public class CraftMule extends CraftChestedHorse implements Mule { - - public CraftMule(CraftServer server, EntityHorseMule entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftMule"; - } - - @Override - public EntityType getType() { - return EntityType.MULE; - } - - @Override - public Variant getVariant() { - return Variant.MULE; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java deleted file mode 100644 index 1ca04ec4e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -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 Variant getVariant() { - return Variant.values()[getHandle().getVariant().ordinal()]; - } - - @Override - public void setVariant(Variant variant) { - Preconditions.checkArgument(variant != null, "variant"); - - getHandle().setVariant(EntityMushroomCow.Type.values()[variant.ordinal()]); - } - - @Override - public String toString() { - return "CraftMushroomCow"; - } - - @Override - public EntityType getType() { - return EntityType.MUSHROOM_COW; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java deleted file mode 100644 index cbd2b6f54..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityOcelot; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Ocelot; - -public class CraftOcelot extends CraftAnimals implements Ocelot { - public CraftOcelot(CraftServer server, EntityOcelot ocelot) { - super(server, ocelot); - } - - @Override - public EntityOcelot getHandle() { - return (EntityOcelot) entity; - } - - @Override - public Type getCatType() { - return Type.WILD_OCELOT; - } - - @Override - public void setCatType(Type type) { - throw new UnsupportedOperationException("Cats are now a different entity!"); - } - - @Override - public String toString() { - return "CraftOcelot"; - } - - @Override - public EntityType getType() { - return EntityType.OCELOT; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java deleted file mode 100644 index 7960839b2..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityPainting; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.Paintings; -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); - } - - @Override - public Art getArt() { - Paintings art = getHandle().art; - return CraftArt.NotchToBukkit(art); - } - - @Override - public boolean setArt(Art art) { - return setArt(art, false); - } - - @Override - public boolean setArt(Art art, boolean force) { - EntityPainting painting = this.getHandle(); - Paintings oldArt = painting.art; - painting.art = CraftArt.BukkitToNotch(art); - painting.setDirection(painting.getDirection()); - if (!force && !painting.survives()) { - // Revert painting since it doesn't fit - painting.art = oldArt; - painting.setDirection(painting.getDirection()); - return false; - } - this.update(); - return true; - } - - @Override - 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 = EntityTypes.PAINTING.a(world); - painting.blockPosition = getHandle().blockPosition; - painting.art = getHandle().art; - painting.setDirection(getHandle().getDirection()); - 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() + "}"; - } - - @Override - public EntityType getType() { - return EntityType.PAINTING; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPanda.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPanda.java deleted file mode 100644 index feab3601d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPanda.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.EntityPanda; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Panda; - -public class CraftPanda extends CraftAnimals implements Panda { - - public CraftPanda(CraftServer server, EntityPanda entity) { - super(server, entity); - } - - @Override - public EntityPanda getHandle() { - return (EntityPanda) super.getHandle(); - } - - @Override - public EntityType getType() { - return EntityType.PANDA; - } - - @Override - public String toString() { - return "CraftPanda"; - } - - @Override - public Gene getMainGene() { - return fromNms(getHandle().getMainGene()); - } - - @Override - public void setMainGene(Gene gene) { - getHandle().setMainGene(toNms(gene)); - } - - @Override - public Gene getHiddenGene() { - return fromNms(getHandle().getHiddenGene()); - } - - @Override - public void setHiddenGene(Gene gene) { - getHandle().setHiddenGene(toNms(gene)); - } - - public static Gene fromNms(EntityPanda.Gene gene) { - Preconditions.checkArgument(gene != null, "Gene may not be null"); - - return Gene.values()[gene.ordinal()]; - } - - public static EntityPanda.Gene toNms(Gene gene) { - Preconditions.checkArgument(gene != null, "Gene may not be null"); - - return EntityPanda.Gene.values()[gene.ordinal()]; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftParrot.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftParrot.java deleted file mode 100644 index 5b2405cf2..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftParrot.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.EntityParrot; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Parrot; - -public class CraftParrot extends CraftTameableAnimal implements Parrot { - - public CraftParrot(CraftServer server, EntityParrot parrot) { - super(server, parrot); - } - - @Override - public EntityParrot getHandle() { - return (EntityParrot) entity; - } - - @Override - public Variant getVariant() { - return Variant.values()[getHandle().getVariant()]; - } - - @Override - public void setVariant(Variant variant) { - Preconditions.checkArgument(variant != null, "variant"); - - getHandle().setVariant(variant.ordinal()); - } - - @Override - public String toString() { - return "CraftParrot"; - } - - @Override - public EntityType getType() { - return EntityType.PARROT; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPhantom.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPhantom.java deleted file mode 100644 index 2b9731369..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPhantom.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityPhantom; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Phantom; - -public class CraftPhantom extends CraftFlying implements Phantom { - - public CraftPhantom(CraftServer server, EntityPhantom entity) { - super(server, entity); - } - - @Override - public EntityPhantom getHandle() { - return (EntityPhantom) super.getHandle(); - } - - @Override - public int getSize() { - return getHandle().getSize(); - } - - @Override - public void setSize(int sz) { - getHandle().setSize(sz); - } - - @Override - public String toString() { - return "CraftPhantom"; - } - - @Override - public EntityType getType() { - return EntityType.PHANTOM; - } - - // Paper start - public java.util.UUID getSpawningEntity() { - return getHandle().getSpawningEntity(); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java deleted file mode 100644 index 85fee3f21..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java +++ /dev/null @@ -1,37 +0,0 @@ -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); - } - - @Override - public boolean hasSaddle() { - return getHandle().hasSaddle(); - } - - @Override - public void setSaddle(boolean saddled) { - getHandle().setSaddle(saddled); - } - - @Override - public EntityPig getHandle() { - return (EntityPig) entity; - } - - @Override - public String toString() { - return "CraftPig"; - } - - @Override - public EntityType getType() { - return EntityType.PIG; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java deleted file mode 100644 index 10c12ef5a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java +++ /dev/null @@ -1,63 +0,0 @@ -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); - } - - @Override - public int getAnger() { - return getHandle().angerLevel; - } - - @Override - public void setAnger(int level) { - getHandle().angerLevel = level; - } - - @Override - public void setAngry(boolean angry) { - setAnger(angry ? 400 : 0); - } - - @Override - public boolean isAngry() { - return getAnger() > 0; - } - - @Override - public EntityPigZombie getHandle() { - return (EntityPigZombie) entity; - } - - @Override - public String toString() { - return "CraftPigZombie"; - } - - @Override - public EntityType getType() { - return EntityType.PIG_ZOMBIE; - } - - @Override - public boolean isConverting() { - return false; - } - - @Override - public int getConversionTime() { - throw new UnsupportedOperationException("Not supported by this Entity."); - } - - @Override - public void setConversionTime(int time) { - throw new UnsupportedOperationException("Not supported by this Entity."); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPillager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPillager.java deleted file mode 100644 index d889fe8c3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPillager.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityPillager; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.inventory.CraftInventory; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Pillager; -import org.bukkit.inventory.Inventory; - -public class CraftPillager extends CraftIllager implements Pillager { - - public CraftPillager(CraftServer server, EntityPillager entity) { - super(server, entity); - } - - @Override - public EntityPillager getHandle() { - return (EntityPillager) super.getHandle(); - } - - @Override - public EntityType getType() { - return EntityType.PILLAGER; - } - - @Override - public String toString() { - return "CraftPillager"; - } - - @Override - public Inventory getInventory() { - return new CraftInventory(getHandle().getInventory()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java deleted file mode 100644 index e920545df..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java +++ /dev/null @@ -1,2091 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.destroystokyo.paper.Title; -import com.destroystokyo.paper.profile.CraftPlayerProfile; -import com.destroystokyo.paper.profile.PlayerProfile; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; -import com.google.common.io.BaseEncoding; -import com.mojang.authlib.GameProfile; -import io.netty.buffer.Unpooled; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.ref.WeakReference; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; -import net.minecraft.server.AdvancementDataPlayer; -import net.minecraft.server.AdvancementProgress; -import net.minecraft.server.AttributeInstance; -import net.minecraft.server.AttributeMapServer; -import net.minecraft.server.AttributeModifiable; -import net.minecraft.server.AttributeRanged; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.Container; -import net.minecraft.server.Entity; -import net.minecraft.server.EntityLiving; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.EnumChatFormat; -import net.minecraft.server.EnumColor; -import net.minecraft.server.EnumGamemode; -import net.minecraft.server.IChatBaseComponent; -import net.minecraft.server.MapIcon; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.PacketDataSerializer; -import net.minecraft.server.PacketPlayOutBlockChange; -import net.minecraft.server.PacketPlayOutChat; -import net.minecraft.server.PacketPlayOutCustomPayload; -import net.minecraft.server.PacketPlayOutCustomSoundEffect; -import net.minecraft.server.PacketPlayOutMap; -import net.minecraft.server.PacketPlayOutNamedSoundEffect; -import net.minecraft.server.PacketPlayOutPlayerInfo; -import net.minecraft.server.PacketPlayOutPlayerListHeaderFooter; -import net.minecraft.server.PacketPlayOutSpawnPosition; -import net.minecraft.server.PacketPlayOutStopSound; -import net.minecraft.server.PacketPlayOutTitle; -import net.minecraft.server.PacketPlayOutUpdateAttributes; -import net.minecraft.server.PacketPlayOutUpdateHealth; -import net.minecraft.server.PacketPlayOutWorldEvent; -import net.minecraft.server.PacketPlayOutWorldParticles; -import net.minecraft.server.PlayerChunkMap; -import net.minecraft.server.PlayerConnection; -import net.minecraft.server.TileEntitySign; -import net.minecraft.server.Vec3D; -import net.minecraft.server.WhiteListEntry; -import net.minecraft.server.WorldServer; -import org.apache.commons.lang.NotImplementedException; -import org.apache.commons.lang.Validate; -import org.bukkit.Achievement; -import org.bukkit.BanList; -import org.bukkit.Bukkit; -import org.bukkit.DyeColor; -import org.bukkit.Effect; -import org.bukkit.GameMode; -import org.bukkit.Instrument; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Note; -import org.bukkit.OfflinePlayer; -import org.bukkit.Particle; -import org.bukkit.Sound; -import org.bukkit.Statistic; -import org.bukkit.Statistic.Type; -import org.bukkit.WeatherType; -import org.bukkit.block.data.BlockData; -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.CraftEffect; -import org.bukkit.craftbukkit.CraftOfflinePlayer; -import org.bukkit.craftbukkit.CraftParticle; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftSound; -import org.bukkit.craftbukkit.CraftStatistic; -import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.advancement.CraftAdvancement; -import org.bukkit.craftbukkit.advancement.CraftAdvancementProgress; -import org.bukkit.craftbukkit.block.CraftSign; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -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.PlayerRegisterChannelEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.player.PlayerUnregisterChannelEvent; -import org.bukkit.inventory.InventoryView.Property; -import org.bukkit.inventory.ItemStack; -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 net.md_5.bungee.api.chat.BaseComponent; // Spigot - -@DelegateDeserialization(CraftOfflinePlayer.class) -public class CraftPlayer extends CraftHumanEntity implements Player { - private long firstPlayed = 0; - private long lastPlayed = 0; - private boolean hasPlayedBefore = false; - private final ConversationTracker conversationTracker = new ConversationTracker(); - private final Set channels = new HashSet(); - private final Map>> hiddenPlayers = new HashMap<>(); - private static final WeakHashMap> pluginWeakReferences = new WeakHashMap<>(); - private int hash = 0; - private double health = 20; - private boolean scaledHealth = false; - private double healthScale = 20; - // Paper start - private org.bukkit.event.player.PlayerResourcePackStatusEvent.Status resourcePackStatus; - private String resourcePackHash; - private static final boolean DISABLE_CHANNEL_LIMIT = System.getProperty("paper.disableChannelLimit") != null; // Paper - add a flag to disable the channel limit - private long lastSaveTime; - // Paper end - - public CraftPlayer(CraftServer server, EntityPlayer entity) { - super(server, entity); - - firstPlayed = System.currentTimeMillis(); - } - - public GameProfile getProfile() { - return getHandle().getProfile(); - } - - @Override - public boolean isOp() { - return server.getHandle().isOp(getProfile()); - } - - @Override - public void setOp(boolean value) { - if (value == isOp()) return; - - if (value) { - server.getHandle().addOp(getProfile()); - } else { - server.getHandle().removeOp(getProfile()); - } - - perm.recalculatePermissions(); - } - - @Override - public boolean isOnline() { - return server.getPlayer(getUniqueId()) != null; - } - - @Override - 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; - } - } - - // Paper start - Implement NetworkClient - @Override - public int getProtocolVersion() { - if (getHandle().playerConnection == null) return -1; - return getHandle().playerConnection.networkManager.protocolVersion; - } - - @Override - public InetSocketAddress getVirtualHost() { - if (getHandle().playerConnection == null) return null; - return getHandle().playerConnection.networkManager.virtualHost; - } - // Paper end - - @Override - public double getEyeHeight(boolean ignorePose) { - if (ignorePose) { - return 1.62D; - } else { - return getEyeHeight(); - } - } - - @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 sendActionBar(String message) { - if (getHandle().playerConnection == null || message == null || message.isEmpty()) return; - getHandle().playerConnection.sendPacket(new PacketPlayOutChat(new net.minecraft.server.ChatComponentText(message), net.minecraft.server.ChatMessageType.GAME_INFO)); - } - - @Override - public void sendActionBar(char alternateChar, String message) { - if (message == null || message.isEmpty()) return; - sendActionBar(org.bukkit.ChatColor.translateAlternateColorCodes(alternateChar, message)); - } - - @Override - public void setPlayerListHeaderFooter(BaseComponent[] header, BaseComponent[] footer) { - if (header != null) { - String headerJson = net.md_5.bungee.chat.ComponentSerializer.toString(header); - playerListHeader = net.minecraft.server.ChatBaseComponent.ChatSerializer.jsonToComponent(headerJson); - } else { - playerListHeader = null; - } - - if (footer != null) { - String footerJson = net.md_5.bungee.chat.ComponentSerializer.toString(footer); - playerListFooter = net.minecraft.server.ChatBaseComponent.ChatSerializer.jsonToComponent(footerJson); - } else { - playerListFooter = null; - } - - updatePlayerListHeaderFooter(); - } - - @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, EnumChatFormat.WHITE); - } - - @Override - public void setPlayerListName(String name) { - if (name == null) { - name = getName(); - } - getHandle().listName = name.equals(getName()) ? null : CraftChatMessage.fromStringOrNull(name); - for (EntityPlayer player : (List)server.getHandle().players) { - if (player.getBukkitEntity().canSee(this)) { - player.playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_DISPLAY_NAME, getHandle())); - } - } - } - - private IChatBaseComponent playerListHeader; - private IChatBaseComponent playerListFooter; - - @Override - public String getPlayerListHeader() { - return (playerListHeader == null) ? null : CraftChatMessage.fromComponent(playerListHeader); - } - - @Override - public String getPlayerListFooter() { - return (playerListFooter == null) ? null : CraftChatMessage.fromComponent(playerListFooter); - } - - @Override - public void setPlayerListHeader(String header) { - this.playerListHeader = CraftChatMessage.fromStringOrNull(header, true); - updatePlayerListHeaderFooter(); - } - - @Override - public void setPlayerListFooter(String footer) { - this.playerListFooter = CraftChatMessage.fromStringOrNull(footer, true); - updatePlayerListHeaderFooter(); - } - - @Override - public void setPlayerListHeaderFooter(String header, String footer) { - this.playerListHeader = CraftChatMessage.fromStringOrNull(header, true); - this.playerListFooter = CraftChatMessage.fromStringOrNull(footer, true); - updatePlayerListHeaderFooter(); - } - - private void updatePlayerListHeaderFooter() { - if (getHandle().playerConnection == null) return; - - PacketPlayOutPlayerListHeaderFooter packet = new PacketPlayOutPlayerListHeaderFooter(); - packet.header = (this.playerListHeader == null) ? new ChatComponentText("") : this.playerListHeader; - packet.footer = (this.playerListFooter == null) ? new ChatComponentText("") : this.playerListFooter; - getHandle().playerConnection.sendPacket(packet); - } - - @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 = "basedrum"; - break; - case 2: - instrumentName = "snare"; - break; - case 3: - instrumentName = "hat"; - break; - case 4: - instrumentName = "bass"; - break; - case 5: - instrumentName = "flute"; - break; - case 6: - instrumentName = "bell"; - break; - case 7: - instrumentName = "guitar"; - break; - case 8: - instrumentName = "chime"; - break; - case 9: - instrumentName = "xylophone"; - break; - } - - float f = (float) Math.pow(2.0D, (note - 12.0D) / 12.0D); - getHandle().playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(CraftSound.getSoundEffect("block.note_block." + instrumentName), net.minecraft.server.SoundCategory.RECORDS, 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 = "basedrum"; - break; - case 2: - instrumentName = "snare"; - break; - case 3: - instrumentName = "hat"; - break; - case 4: - instrumentName = "bass"; - break; - case 5: - instrumentName = "flute"; - break; - case 6: - instrumentName = "bell"; - break; - case 7: - instrumentName = "guitar"; - break; - case 8: - instrumentName = "chime"; - break; - case 9: - instrumentName = "xylophone"; - break; - case 10: - instrumentName = "iron_xylophone"; - break; - case 11: - instrumentName = "cow_bell"; - break; - case 12: - instrumentName = "didgeridoo"; - break; - case 13: - instrumentName = "bit"; - break; - case 14: - instrumentName = "banjo"; - break; - case 15: - instrumentName = "pling"; - break; - case 16: - instrumentName = "xylophone"; - break; - } - float f = (float) Math.pow(2.0D, (note.getId() - 12.0D) / 12.0D); - getHandle().playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(CraftSound.getSoundEffect("block.note_block." + instrumentName), net.minecraft.server.SoundCategory.RECORDS, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), 3.0f, f)); - } - - @Override - public void playSound(Location loc, Sound sound, float volume, float pitch) { - playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); - } - - @Override - public void playSound(Location loc, String sound, float volume, float pitch) { - playSound(loc, sound, org.bukkit.SoundCategory.MASTER, volume, pitch); - } - - @Override - public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (loc == null || sound == null || category == null || getHandle().playerConnection == null) return; - - PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(CraftSound.getSoundEffect(CraftSound.getSound(sound)), net.minecraft.server.SoundCategory.valueOf(category.name()), loc.getX(), loc.getY(), loc.getZ(), volume, pitch); - getHandle().playerConnection.sendPacket(packet); - } - - @Override - public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (loc == null || sound == null || category == null || getHandle().playerConnection == null) return; - - PacketPlayOutCustomSoundEffect packet = new PacketPlayOutCustomSoundEffect(new MinecraftKey(sound), net.minecraft.server.SoundCategory.valueOf(category.name()), new Vec3D(loc.getX(), loc.getY(), loc.getZ()), volume, pitch); - getHandle().playerConnection.sendPacket(packet); - } - - @Override - public void stopSound(Sound sound) { - stopSound(sound, null); - } - - @Override - public void stopSound(String sound) { - stopSound(sound, null); - } - - @Override - public void stopSound(Sound sound, org.bukkit.SoundCategory category) { - stopSound(CraftSound.getSound(sound), category); - } - - @Override - public void stopSound(String sound, org.bukkit.SoundCategory category) { - if (getHandle().playerConnection == null) return; - - getHandle().playerConnection.sendPacket(new PacketPlayOutStopSound(new MinecraftKey(sound), category == null ? net.minecraft.server.SoundCategory.MASTER : net.minecraft.server.SoundCategory.valueOf(category.name()))); - } - - @Override - public void playEffect(Location loc, Effect effect, int data) { - if (getHandle().playerConnection == null) return; - - int packetData = effect.getId(); - PacketPlayOutWorldEvent packet = new PacketPlayOutWorldEvent(packetData, new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()), data, false); - getHandle().playerConnection.sendPacket(packet); - } - - @Override - public void playEffect(Location loc, Effect effect, T data) { - if (data != null) { - Validate.isTrue(effect.getData() != null && effect.getData().isAssignableFrom(data.getClass()), "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) { - 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, data); - getHandle().playerConnection.sendPacket(packet); - } - - @Override - public void sendBlockChange(Location loc, BlockData block) { - if (getHandle().playerConnection == null) return; - - PacketPlayOutBlockChange packet = new PacketPlayOutBlockChange(((CraftWorld) loc.getWorld()).getHandle(), new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - - packet.block = ((CraftBlockData) block).getState(); - getHandle().playerConnection.sendPacket(packet); - } - - @Override - public void sendSignChange(Location loc, String[] lines) { - sendSignChange(loc, lines, DyeColor.BLACK); - } - - @Override - public void sendSignChange(Location loc, String[] lines, DyeColor dyeColor) { - if (getHandle().playerConnection == null) { - return; - } - - if (lines == null) { - lines = new String[4]; - } - - Validate.notNull(loc, "Location can not be null"); - Validate.notNull(dyeColor, "DyeColor can not be null"); - if (lines.length < 4) { - throw new IllegalArgumentException("Must have at least 4 lines"); - } - - IChatBaseComponent[] components = CraftSign.sanitizeLines(lines); - TileEntitySign sign = new TileEntitySign(); - sign.setPosition(new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - sign.setColor(EnumColor.fromColorIndex(dyeColor.getWoolData())); - System.arraycopy(components, 0, sign.lines, 0, sign.lines.length); - - getHandle().playerConnection.sendPacket(sign.getUpdatePacket()); - } - - @Override - public boolean sendChunkChange(Location loc, int sx, int sy, int sz, byte[] data) { - if (getHandle().playerConnection == null) return false; - - /* - int x = loc.getBlockX(); - int y = loc.getBlockY(); - int z = loc.getBlockZ(); - - int cx = x >> 4; - int cz = z >> 4; - - if (sx <= 0 || sy <= 0 || sz <= 0) { - return false; - } - - if ((x + sx - 1) >> 4 != cx || (z + sz - 1) >> 4 != cz || y < 0 || y + sy > 128) { - return false; - } - - if (data.length != (sx * sy * sz * 5) / 2) { - return false; - } - - Packet51MapChunk packet = new Packet51MapChunk(x, y, z, sx, sy, sz, data); - - getHandle().playerConnection.sendPacket(packet); - - return true; - */ - - throw new NotImplementedException("Chunk changes do not yet work"); // TODO: Chunk changes. - } - - @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(MapIcon.Type.a(cursor.getRawType()), cursor.getX(), cursor.getY(), cursor.getDirection(), CraftChatMessage.fromStringOrNull(cursor.getCaption()))); - } - } - - PacketPlayOutMap packet = new PacketPlayOutMap(map.getId(), map.getScale().getValue(), true, map.isLocked(), icons, data.buffer, 0, 0, 128, 128); - getHandle().playerConnection.sendPacket(packet); - } - - @Override - public void setRotation(float yaw, float pitch) { - throw new UnsupportedOperationException("Cannot set rotation of players. Consider teleporting instead."); - } - - @Override - public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) { - Preconditions.checkArgument(location != null, "location"); - Preconditions.checkArgument(location.getWorld() != null, "location.world"); - location.checkFinite(); - - EntityPlayer entity = getHandle(); - - if (getHealth() == 0 || entity.dead) { - return false; - } - - if (entity.playerConnection == null) { - return false; - } - - if (entity.isVehicle()) { - 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.stopRiding(); - - // 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(org.bukkit.event.inventory.InventoryCloseEvent.Reason.TELEPORT); // Paper - } - - // Check if the fromWorld and toWorld are the same. - if (fromWorld == toWorld) { - entity.playerConnection.teleport(to); - } else { - server.getHandle().moveToWorld(entity, toWorld.getWorldProvider().getDimensionManager(), true, to, !toWorld.paperConfig.disableTeleportationSuffocationCheck); - } - return true; - } - - // Paper start - Ugly workaround for SPIGOT-1915 & GH-114 - @Override - public boolean setPassenger(org.bukkit.entity.Entity passenger) { - boolean wasSet = super.setPassenger(passenger); - if (wasSet) { - this.getHandle().playerConnection.sendPacket(new net.minecraft.server.PacketPlayOutMount(this.getHandle())); - } - return wasSet; - } - // Paper end - - @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().everyoneSleeping(); - } - - @Override - public boolean isSleepingIgnored() { - return getHandle().fauxSleeping; - } - - @Override - public void awardAchievement(Achievement achievement) { - throw new UnsupportedOperationException("Not supported in this Minecraft version."); - } - - @Override - public void removeAchievement(Achievement achievement) { - throw new UnsupportedOperationException("Not supported in this Minecraft version."); - } - - @Override - public boolean hasAchievement(Achievement achievement) { - throw new UnsupportedOperationException("Not supported in this Minecraft version."); - } - - @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 boolean isWhitelisted() { - return server.getHandle().getWhitelist().isWhitelisted(getProfile()); - } - - @Override - public void setWhitelisted(boolean value) { - if (value) { - server.getHandle().getWhitelist().add(new WhiteListEntry(getProfile())); - } else { - server.getHandle().getWhitelist().remove(getProfile()); - } - } - - @Override - public void setGameMode(GameMode mode) { - if (getHandle().playerConnection == null) return; - - if (mode == null) { - throw new IllegalArgumentException("Mode cannot be null"); - } - - getHandle().a(EnumGamemode.getById(mode.getValue())); - } - - @Override - public GameMode getGameMode() { - return GameMode.getByValue(getHandle().playerInteractManager.getGameMode().getId()); - } - - // Paper start - @Override - public int applyMending(int amount) { - EntityPlayer handle = getHandle(); - // Logic copied from EntityExperienceOrb and remapped to unobfuscated methods/properties - net.minecraft.server.ItemStack itemstack = net.minecraft.server.EnchantmentManager.getRandomEquippedItemWithEnchant(net.minecraft.server.Enchantments.MENDING, handle); - if (!itemstack.isEmpty() && itemstack.getItem().usesDurability()) { - - net.minecraft.server.EntityExperienceOrb orb = net.minecraft.server.EntityTypes.EXPERIENCE_ORB.create(handle.world); - orb.value = amount; - orb.spawnReason = org.bukkit.entity.ExperienceOrb.SpawnReason.CUSTOM; - orb.locX = handle.locX; - orb.locY = handle.locY; - orb.locZ = handle.locZ; - - int i = Math.min(orb.xpToDur(amount), itemstack.getDamage()); - org.bukkit.event.player.PlayerItemMendEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerItemMendEvent(handle, orb, itemstack, i); - i = event.getRepairAmount(); - orb.dead = true; - if (!event.isCancelled()) { - amount -= orb.durToXp(i); - itemstack.setDamage(itemstack.getDamage() - i); - } - } - return amount; - } - - @Override - public void giveExp(int exp, boolean applyMending) { - if (applyMending) { - exp = this.applyMending(exp); - } - // Paper end - 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) { - Preconditions.checkArgument(exp >= 0.0 && exp <= 1.0, "Experience progress must be between 0.0 and 1.0 (%s)", 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; - } - - @Nullable - private static WeakReference getPluginWeakReference(@Nullable Plugin plugin) { - return (plugin == null) ? null : pluginWeakReferences.computeIfAbsent(plugin, WeakReference::new); - } - - @Override - @Deprecated - public void hidePlayer(Player player) { - hidePlayer0(null, player); - } - - @Override - public void hidePlayer(Plugin plugin, Player player) { - Validate.notNull(plugin, "Plugin cannot be null"); - Validate.isTrue(plugin.isEnabled(), "Plugin attempted to hide player while disabled"); - - hidePlayer0(plugin, player); - } - - private void hidePlayer0(@Nullable Plugin plugin, Player player) { - Validate.notNull(player, "hidden player cannot be null"); - if (getHandle().playerConnection == null) return; - if (equals(player)) return; - - Set> hidingPlugins = hiddenPlayers.get(player.getUniqueId()); - if (hidingPlugins != null) { - // Some plugins are already hiding the player. Just mark that this - // plugin wants the player hidden too and end. - hidingPlugins.add(getPluginWeakReference(plugin)); - return; - } - hidingPlugins = new HashSet<>(); - hidingPlugins.add(getPluginWeakReference(plugin)); - hiddenPlayers.put(player.getUniqueId(), hidingPlugins); - - // Remove this player from the hidden player's EntityTrackerEntry - // Paper start - EntityPlayer other = ((CraftPlayer) player).getHandle(); - unregisterPlayer(other); - } - private void unregisterPlayer(EntityPlayer other) { - PlayerChunkMap tracker = ((WorldServer) entity.world).getChunkProvider().playerChunkMap; - // Paper end - PlayerChunkMap.EntityTracker entry = tracker.trackedEntities.get(other.getId()); - if (entry != null) { - entry.clear(getHandle()); - } - - // Remove the hidden player from this player user list, if they're on it - if (other.sentListPacket) { - getHandle().playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, other)); - } - } - - @Override - @Deprecated - public void showPlayer(Player player) { - showPlayer0(null, player); - } - - @Override - public void showPlayer(Plugin plugin, Player player) { - Validate.notNull(plugin, "Plugin cannot be null"); - // Don't require that plugin be enabled. A plugin must be allowed to call - // showPlayer during its onDisable() method. - showPlayer0(plugin, player); - } - - private void showPlayer0(@Nullable Plugin plugin, Player player) { - Validate.notNull(player, "shown player cannot be null"); - if (getHandle().playerConnection == null) return; - if (equals(player)) return; - - Set> hidingPlugins = hiddenPlayers.get(player.getUniqueId()); - if (hidingPlugins == null) { - return; // Player isn't hidden - } - hidingPlugins.remove(getPluginWeakReference(plugin)); - if (!hidingPlugins.isEmpty()) { - return; // Some other plugins still want the player hidden - } - hiddenPlayers.remove(player.getUniqueId()); - - // Paper start - EntityPlayer other = ((CraftPlayer) player).getHandle(); - registerPlayer(other); - } - private void registerPlayer(EntityPlayer other) { - PlayerChunkMap tracker = ((WorldServer) entity.world).getChunkProvider().playerChunkMap; - // Paper end - - getHandle().playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, other)); - - PlayerChunkMap.EntityTracker entry = tracker.trackedEntities.get(other.getId()); - if (entry != null && !entry.trackedPlayers.contains(getHandle())) { - entry.updatePlayer(getHandle()); - } - } - // Paper start - private void reregisterPlayer(EntityPlayer player) { - if (!hiddenPlayers.containsKey(player.getUniqueID())) { - unregisterPlayer(player); - registerPlayer(player); - } - } - public void setPlayerProfile(PlayerProfile profile) { - EntityPlayer self = getHandle(); - self.setProfile(CraftPlayerProfile.asAuthlibCopy(profile)); - List players = server.getServer().getPlayerList().players; - for (EntityPlayer player : players) { - player.getBukkitEntity().reregisterPlayer(self); - } - refreshPlayer(); - } - public PlayerProfile getPlayerProfile() { - return new CraftPlayerProfile(this).clone(); - } - - private void refreshPlayer() { - EntityPlayer handle = getHandle(); - - Location loc = getLocation(); - - PlayerConnection connection = handle.playerConnection; - reregisterPlayer(handle); - - //Respawn the player then update their position and selected slot - connection.sendPacket(new net.minecraft.server.PacketPlayOutRespawn(handle.dimension, handle.world.getWorldData().getType(), handle.playerInteractManager.getGameMode())); - handle.updateAbilities(); - connection.sendPacket(new net.minecraft.server.PacketPlayOutPosition(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch(), new HashSet<>(), 0)); - net.minecraft.server.MinecraftServer.getServer().getPlayerList().updateClient(handle); - - if (this.isOp()) { - this.setOp(false); - this.setOp(true); - } - } - // Paper end - - public void removeDisconnectingPlayer(Player player) { - hiddenPlayers.remove(player.getUniqueId()); - } - - @Override - public boolean canSee(Player player) { - return !hiddenPlayers.containsKey(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; - } - - // Paper start - @Override - public long getLastLogin() { - return getHandle().loginTime; - } - - @Override - public long getLastSeen() { - return isOnline() ? System.currentTimeMillis() : this.lastSaveTime; - } - // Paper end - - 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"); - } - } - } - - public void setExtraData(NBTTagCompound nbttagcompound) { - this.lastSaveTime = System.currentTimeMillis(); // Paper - - 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()); - - // Paper start - persist for use in offline save data - if (!nbttagcompound.hasKey("Paper")) { - nbttagcompound.set("Paper", new NBTTagCompound()); - } - - NBTTagCompound paper = nbttagcompound.getCompound("Paper"); - paper.setLong("LastLogin", handle.loginTime); - paper.setLong("LastSeen", System.currentTimeMillis()); - // Paper end - } - - @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)) { - channel = StandardMessenger.validateAndCorrectChannel(channel); - PacketPlayOutCustomPayload packet = new PacketPlayOutCustomPayload(new MinecraftKey(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"); - } - - @Override - public void setResourcePack(String url, byte[] hash) { - Validate.notNull(url, "Resource pack URL cannot be null"); - Validate.notNull(hash, "Resource pack hash cannot be null"); - Validate.isTrue(hash.length == 20, "Resource pack hash should be 20 bytes long but was " + hash.length); - - getHandle().setResourcePack(url, BaseEncoding.base16().lowerCase().encode(hash)); - } - - public void addChannel(String channel) { - Preconditions.checkState(DISABLE_CHANNEL_LIMIT || channels.size() < 128, "Cannot register channel '%s'. Too many channels registered!", channel); // Paper - flag to disable channel limit - channel = StandardMessenger.validateAndCorrectChannel(channel); - if (channels.add(channel)) { - server.getPluginManager().callEvent(new PlayerRegisterChannelEvent(this, channel)); - } - } - - public void removeChannel(String channel) { - channel = StandardMessenger.validateAndCorrectChannel(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("UTF8")); - 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(new MinecraftKey("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; // Paper - Only refresh abilities if needed - if (!getAllowFlight() && value) { - throw new IllegalArgumentException("Cannot make player fly if getAllowFlight() is false"); - } - - getHandle().abilities.isFlying = value; - if (needsUpdate) getHandle().updateAbilities(); // Paper - 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 = value / 2f; - player.updateAbilities(); - - } - - @Override - public void setWalkSpeed(float value) { - validateSpeed(value); - EntityPlayer player = getHandle(); - player.abilities.walkSpeed = value / 2f; - player.updateAbilities(); - } - - @Override - public float getFlySpeed() { - return (float) 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(this.health, health); - 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"); - } - if (playerConnection.isDisconnected()) { - // throw new IllegalStateException("Cannot set scoreboard for invalid CraftPlayer"); // Spigot - remove this as Mojang's semi asynchronous Netty implementation can lead to races - } - - 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) { - if (Double.isNaN(health)) {return;} // Paper - this.health = health; - } - - public void updateScaledHealth() { - updateScaledHealth(true); - } - - public void updateScaledHealth(boolean sendHealth) { - AttributeMapServer attributemapserver = (AttributeMapServer) getHandle().getAttributeMap(); - Collection set = attributemapserver.c(); // PAIL: Rename - - injectScaledMaxHealth(set, true); - - // SPIGOT-3813: Attributes before health - if (getHandle().playerConnection != null) { - getHandle().playerConnection.sendPacket(new PacketPlayOutUpdateAttributes(getHandle().getId(), set)); - if (sendHealth) { - sendHealthUpdate(); - } - } - getHandle().getDataWatcher().set(EntityLiving.HEALTH, (float) getScaledHealth()); - - getHandle().maxHealthCache = getMaxHealth(); - } - - public void sendHealthUpdate() { - // Paper start - cancellable death event - //getHandle().playerConnection.sendPacket(new PacketPlayOutUpdateHealth(getScaledHealth(), getHandle().getFoodData().getFoodLevel(), getHandle().getFoodData().getSaturationLevel())); - PacketPlayOutUpdateHealth packet = new PacketPlayOutUpdateHealth(getScaledHealth(), getHandle().getFoodData().getFoodLevel(), getHandle().getFoodData().getSaturationLevel()); - if (this.getHandle().queueHealthUpdatePacket) { - this.getHandle().queuedHealthUpdatePacket = packet; - } else { - this.getHandle().playerConnection.sendPacket(packet); - } - // Paper end - } - - public void injectScaledMaxHealth(Collection collection, boolean force) { - if (!scaledHealth && !force) { - return; - } - for (AttributeInstance genericInstance : collection) { - if (genericInstance.getAttribute().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().getSpecatorTarget(); - 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) { - sendTitle(title, subtitle, 10, 70, 20); - } - - @Override - public void sendTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut) { - PacketPlayOutTitle times = new PacketPlayOutTitle(fadeIn, stay, fadeOut); - getHandle().playerConnection.sendPacket(times); - - if (title != null) { - PacketPlayOutTitle packetTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, CraftChatMessage.fromStringOrNull(title)); - getHandle().playerConnection.sendPacket(packetTitle); - } - - if (subtitle != null) { - PacketPlayOutTitle packetSubtitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE, CraftChatMessage.fromStringOrNull(subtitle)); - getHandle().playerConnection.sendPacket(packetSubtitle); - } - } - - @Override - public void resetTitle() { - PacketPlayOutTitle packetReset = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.RESET, null); - getHandle().playerConnection.sendPacket(packetReset); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count) { - spawnParticle(particle, x, y, z, count, null); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, T data) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, data); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) { - spawnParticle(particle, x, y, z, count, 0, 0, 0, data); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) { - spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, null); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, data); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) { - spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, 1, data); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) { - spawnParticle(particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, null); - } - - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - spawnParticle(particle, location.getX(), location.getY(), location.getZ(), count, offsetX, offsetY, offsetZ, extra, data); - } - - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - if (data != null && !particle.getDataType().isInstance(data)) { - throw new IllegalArgumentException("data should be " + particle.getDataType() + " got " + data.getClass()); - } - PacketPlayOutWorldParticles packetplayoutworldparticles = new PacketPlayOutWorldParticles(CraftParticle.toNMS(particle, data), true, (float) x, (float) y, (float) z, (float) offsetX, (float) offsetY, (float) offsetZ, (float) extra, count); - getHandle().playerConnection.sendPacket(packetplayoutworldparticles); - - } - - @Override - public org.bukkit.advancement.AdvancementProgress getAdvancementProgress(org.bukkit.advancement.Advancement advancement) { - Preconditions.checkArgument(advancement != null, "advancement"); - - CraftAdvancement craft = (CraftAdvancement) advancement; - AdvancementDataPlayer data = getHandle().getAdvancementData(); - AdvancementProgress progress = data.getProgress(craft.getHandle()); - - return new CraftAdvancementProgress(craft, data, progress); - } - - @Override - public int getClientViewDistance() { - return (getHandle().clientViewDistance == null) ? Bukkit.getViewDistance() : getHandle().clientViewDistance; - } - - @Override - public String getLocale() { - // Paper start - Locale change event - final String locale = getHandle().locale; - return locale != null ? locale : "en_us"; - // Paper end - } - - // Paper start - public void setAffectsSpawning(boolean affects) { - this.getHandle().affectsSpawning = affects; - } - - @Override - public boolean getAffectsSpawning() { - return this.getHandle().affectsSpawning; - } - - @Override - public void setResourcePack(String url, String hash) { - Validate.notNull(url, "Resource pack URL cannot be null"); - Validate.notNull(hash, "Hash cannot be null"); - this.getHandle().setResourcePack(url, hash); - } - - @Override - public org.bukkit.event.player.PlayerResourcePackStatusEvent.Status getResourcePackStatus() { - return this.resourcePackStatus; - } - - @Override - public String getResourcePackHash() { - return this.resourcePackHash; - } - - @Override - public boolean hasResourcePack() { - return this.resourcePackStatus == org.bukkit.event.player.PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED; - } - - public void setResourcePackStatus(org.bukkit.event.player.PlayerResourcePackStatusEvent.Status status) { - this.resourcePackStatus = status; - } - // Paper end - - @Override - public void updateCommands() { - if (getHandle().playerConnection == null) return; - - getHandle().server.getCommandDispatcher().a(getHandle()); - } - - @Override - public void openBook(ItemStack book) { - Validate.isTrue(book != null, "book == null"); - Validate.isTrue(book.getType() == Material.WRITTEN_BOOK, "Book must be Material.WRITTEN_BOOK"); - - ItemStack hand = getInventory().getItemInMainHand(); - getInventory().setItemInMainHand(book); - getHandle().openBook(org.bukkit.craftbukkit.inventory.CraftItemStack.asNMSCopy(book), net.minecraft.server.EnumHand.MAIN_HAND); - getInventory().setItemInMainHand(hand); - } - - //Paper start - public float getCooldownPeriod() { - return getHandle().getCooldownPeriod(); - } - - public float getCooledAttackStrength(float adjustTicks) { - return getHandle().getCooledAttackStrength(adjustTicks); - } - - public void resetCooldown() { - getHandle().resetCooldown(); - } - - @Override - public void remove() { - if (this.getHandle().getClass().equals(EntityPlayer.class)) { // special case for NMS plugins inheriting - throw new UnsupportedOperationException("Calling Entity#remove on players produces undefined (bad) behavior"); - } else { - super.remove(); - } - } - - @Override - public int getViewDistance() { - throw new NotImplementedException("Per-Player View Distance APIs need further understanding to properly implement"); // TODO - } - - @Override - public void setViewDistance(int viewDistance) { - throw new NotImplementedException("Per-Player View Distance APIs need further understanding to properly implement"); // TODO - } - //Paper end - - // 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 CraftPlayer.this.isCollidable(); - } - - @Override - public void setCollidesWithEntities(boolean collides) { - CraftPlayer.this.setCollidable(collides); - } - - @Override - public void respawn() - { - if ( getHealth() <= 0 && isOnline() ) - { - server.getServer().getPlayerList().moveToWorld( getHandle(), net.minecraft.server.DimensionManager.OVERWORLD, false ); - } - } - - @Override - public String getLocale() - { - return CraftPlayer.this.getLocale(); // Paper - } - - @Override - public Set getHiddenPlayers() - { - Set ret = new HashSet(); - for ( UUID u : hiddenPlayers.keySet() ) - { - ret.add( getServer().getPlayer( u ) ); - } - - return java.util.Collections.unmodifiableSet( ret ); - } - - @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(null, net.minecraft.server.ChatMessageType.SYSTEM); - packet.components = components; - getHandle().playerConnection.sendPacket(packet); - } - - @Override - public void sendMessage(net.md_5.bungee.api.ChatMessageType position, BaseComponent component) { - sendMessage( position, new BaseComponent[] { component } ); - } - - @Override - public void sendMessage(net.md_5.bungee.api.ChatMessageType position, BaseComponent... components) { - if ( getHandle().playerConnection == null ) return; - - PacketPlayOutChat packet = new PacketPlayOutChat(null, net.minecraft.server.ChatMessageType.a((byte) position.ordinal())); - // Action bar doesn't render colours, replace colours with legacy section symbols - if (position == net.md_5.bungee.api.ChatMessageType.ACTION_BAR) { - components = new BaseComponent[]{new net.md_5.bungee.api.chat.TextComponent(BaseComponent.toLegacyText(components))}; - } - packet.components = components; - getHandle().playerConnection.sendPacket(packet); - } - - // Paper start - @Override - public int getPing() - { - return getHandle().ping; - } - // Paper end - }; - - public Player.Spigot spigot() - { - return spigot; - } - // Spigot end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPolarBear.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPolarBear.java deleted file mode 100644 index 21129672c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPolarBear.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityPolarBear; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.PolarBear; - -public class CraftPolarBear extends CraftAnimals implements PolarBear { - - public CraftPolarBear(CraftServer server, EntityPolarBear entity) { - super(server, entity); - } - @Override - public EntityPolarBear getHandle() { - return (EntityPolarBear) entity; - } - - @Override - public String toString() { - return "CraftPolarBear"; - } - - @Override - public EntityType getType() { - return EntityType.POLAR_BEAR; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java deleted file mode 100644 index 649684fc8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityLiving; -import net.minecraft.server.EntityProjectile; -import org.bukkit.craftbukkit.CraftServer; -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); - } - - @Override - public ProjectileSource getShooter() { - return getHandle().projectileSource; - } - - @Override - public void setShooter(ProjectileSource shooter) { - if (shooter instanceof CraftLivingEntity) { - getHandle().shooter = (EntityLiving) ((CraftLivingEntity) shooter).entity; - getHandle().shooterId = ((CraftLivingEntity) shooter).getUniqueId(); - } else { - getHandle().shooter = null; - getHandle().shooterId = null; - } - getHandle().projectileSource = shooter; - } - - @Override - public EntityProjectile getHandle() { - return (EntityProjectile) entity; - } - - @Override - public String toString() { - return "CraftProjectile"; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPufferFish.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPufferFish.java deleted file mode 100644 index 647971d5e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPufferFish.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityPufferFish; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.PufferFish; - -public class CraftPufferFish extends CraftFish implements PufferFish { - - public CraftPufferFish(CraftServer server, EntityPufferFish entity) { - super(server, entity); - } - - @Override - public EntityPufferFish getHandle() { - return (EntityPufferFish) super.getHandle(); - } - - @Override - public int getPuffState() { - return getHandle().getPuffState(); - } - - @Override - public void setPuffState(int state) { - getHandle().setPuffState(state); - } - - @Override - public String toString() { - return "CraftPufferFish"; - } - - @Override - public EntityType getType() { - return EntityType.PUFFERFISH; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java deleted file mode 100644 index a75d7a303..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityRabbit; -import net.minecraft.server.PathfinderGoalSelector; -import net.minecraft.server.World; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; -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. - World world = ((CraftWorld) this.getWorld()).getHandle(); - entity.goalSelector = new PathfinderGoalSelector(world != null && world.getMethodProfiler() != null ? world.getMethodProfiler() : null); - entity.targetSelector = new PathfinderGoalSelector(world != null && world.getMethodProfiler() != null ? world.getMethodProfiler() : 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/src/main/java/org/bukkit/craftbukkit/entity/CraftRaider.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftRaider.java deleted file mode 100644 index f8b92b425..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftRaider.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.EntityRaider; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.entity.Raider; - -public abstract class CraftRaider extends CraftMonster implements Raider { - - public CraftRaider(CraftServer server, EntityRaider entity) { - super(server, entity); - } - - @Override - public EntityRaider getHandle() { - return (EntityRaider) super.getHandle(); - } - - @Override - public String toString() { - return "CraftRaider"; - } - - @Override - public Block getPatrolTarget() { - return getHandle().getPatrolTarget() == null ? null : CraftBlock.at(getHandle().world, getHandle().getPatrolTarget()); - } - - @Override - public void setPatrolTarget(Block block) { - if (block == null) { - getHandle().setPatrolTarget((BlockPosition) null); - } else { - Preconditions.checkArgument(block.getWorld().equals(this.getWorld()), "Block must be in same world"); - - getHandle().setPatrolTarget(new BlockPosition(block.getX(), block.getY(), block.getZ())); - } - } - - @Override - public boolean isPatrolLeader() { - return getHandle().isPatrolLeader(); - } - - @Override - public void setPatrolLeader(boolean leader) { - getHandle().setPatrolLeader(leader); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftRavager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftRavager.java deleted file mode 100644 index 3cb2e6cc5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftRavager.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityRavager; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Ravager; - -public class CraftRavager extends CraftRaider implements Ravager { - - public CraftRavager(CraftServer server, EntityRavager entity) { - super(server, entity); - } - - @Override - public EntityRavager getHandle() { - return (EntityRavager) super.getHandle(); - } - - @Override - public EntityType getType() { - return EntityType.RAVAGER; - } - - @Override - public String toString() { - return "CraftRavager"; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSalmon.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSalmon.java deleted file mode 100644 index 0e4a9ce09..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSalmon.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntitySalmon; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Salmon; - -public class CraftSalmon extends CraftFish implements Salmon { - - public CraftSalmon(CraftServer server, EntitySalmon entity) { - super(server, entity); - } - - @Override - public EntitySalmon getHandle() { - return (EntitySalmon) super.getHandle(); - } - - @Override - public String toString() { - return "CraftSalmon"; - } - - @Override - public EntityType getType() { - return EntityType.SALMON; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java deleted file mode 100644 index fef86120d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java +++ /dev/null @@ -1,49 +0,0 @@ -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); - } - - @Override - public DyeColor getColor() { - return DyeColor.getByWoolData((byte) getHandle().getColor().getColorIndex()); - } - - @Override - public void setColor(DyeColor color) { - getHandle().setColor(EnumColor.fromColorIndex(color.getWoolData())); - } - - @Override - public boolean isSheared() { - return getHandle().isSheared(); - } - - @Override - public void setSheared(boolean flag) { - getHandle().setSheared(flag); - } - - @Override - public EntitySheep getHandle() { - return (EntitySheep) entity; - } - - @Override - public String toString() { - return "CraftSheep"; - } - - @Override - public EntityType getType() { - return EntityType.SHEEP; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftShulker.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftShulker.java deleted file mode 100644 index d18531378..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftShulker.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityShulker; -import org.bukkit.DyeColor; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Shulker; - -public class CraftShulker extends CraftGolem implements Shulker { - - public CraftShulker(CraftServer server, EntityShulker entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftShulker"; - } - - @Override - public EntityType getType() { - return EntityType.SHULKER; - } - - @Override - public EntityShulker getHandle() { - return (EntityShulker) entity; - } - - @Override - public DyeColor getColor() { - return DyeColor.getByWoolData(getHandle().getDataWatcher().get(EntityShulker.COLOR)); - } - - @Override - public void setColor(DyeColor color) { - getHandle().getDataWatcher().set(EntityShulker.COLOR, (color == null) ? 16 : color.getWoolData()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftShulkerBullet.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftShulkerBullet.java deleted file mode 100644 index 8fbdedc86..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftShulkerBullet.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityShulkerBullet; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.ShulkerBullet; -import org.bukkit.projectiles.ProjectileSource; - -public class CraftShulkerBullet extends AbstractProjectile implements ShulkerBullet { - - public CraftShulkerBullet(CraftServer server, EntityShulkerBullet entity) { - super(server, entity); - } - - @Override - public ProjectileSource getShooter() { - return getHandle().projectileSource; - } - - @Override - public void setShooter(ProjectileSource shooter) { - if (shooter instanceof LivingEntity) { - getHandle().setShooter(((CraftLivingEntity) shooter).getHandle()); - } else { - getHandle().setShooter(null); - } - getHandle().projectileSource = shooter; - } - - @Override - public org.bukkit.entity.Entity getTarget() { - return getHandle().getTarget() != null ? getHandle().getTarget().getBukkitEntity() : null; - } - - @Override - public void setTarget(org.bukkit.entity.Entity target) { - getHandle().setTarget(target == null ? null : ((CraftEntity) target).getHandle()); - } - - @Override - public String toString() { - return "CraftShulkerBullet"; - } - - @Override - public EntityType getType() { - return EntityType.SHULKER_BULLET; - } - - @Override - public EntityShulkerBullet getHandle() { - return (EntityShulkerBullet) entity; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java deleted file mode 100644 index 0fe4b0e8c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.SILVERFISH; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java deleted file mode 100644 index 02df66ecf..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.destroystokyo.paper.entity.CraftRangedEntity; -import net.minecraft.server.EntitySkeletonAbstract; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Skeleton; - -public class CraftSkeleton extends CraftMonster implements Skeleton, CraftRangedEntity { // Paper - - public CraftSkeleton(CraftServer server, EntitySkeletonAbstract entity) { - super(server, entity); - } - - @Override - public EntitySkeletonAbstract getHandle() { - return (EntitySkeletonAbstract) entity; - } - - @Override - public String toString() { - return "CraftSkeleton"; - } - - @Override - public EntityType getType() { - return EntityType.SKELETON; - } - - @Override - public SkeletonType getSkeletonType() { - return SkeletonType.NORMAL; - } - - @Override - public void setSkeletonType(SkeletonType type) { - throw new UnsupportedOperationException("Not supported."); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeletonHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeletonHorse.java deleted file mode 100644 index 2a7d1d4ec..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeletonHorse.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityHorseSkeleton; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Horse.Variant; -import org.bukkit.entity.SkeletonHorse; - -public class CraftSkeletonHorse extends CraftAbstractHorse implements SkeletonHorse { - - public CraftSkeletonHorse(CraftServer server, EntityHorseSkeleton entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftSkeletonHorse"; - } - - @Override - public EntityType getType() { - return EntityType.SKELETON_HORSE; - } - - @Override - public Variant getVariant() { - return Variant.SKELETON_HORSE; - } - - // Paper start - @Override - public EntityHorseSkeleton getHandle() { - return (EntityHorseSkeleton) super.getHandle(); - } - - @Override - public int getTrapTime() { - return getHandle().getTrapTime(); - } - - @Override - public boolean isTrap() { - return getHandle().isTrap(); - } - - @Override - public void setTrap(boolean trap) { - getHandle().setTrap(trap); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java deleted file mode 100644 index 6e9f1b66d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java +++ /dev/null @@ -1,48 +0,0 @@ -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 CraftMob implements Slime { - - public CraftSlime(CraftServer server, EntitySlime entity) { - super(server, entity); - } - - @Override - public int getSize() { - return getHandle().getSize(); - } - - @Override - public void setSize(int size) { - getHandle().setSize(size, true); - } - - @Override - public EntitySlime getHandle() { - return (EntitySlime) entity; - } - - @Override - public String toString() { - return "CraftSlime"; - } - - @Override - public EntityType getType() { - return EntityType.SLIME; - } - - // Paper start - public boolean canWander() { - return getHandle().canWander(); - } - - public void setWander(boolean canWander) { - getHandle().setWander(canWander); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java deleted file mode 100644 index 02fac8b4a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.SMALL_FIREBALL; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java deleted file mode 100644 index 222977d79..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.SNOWBALL; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java deleted file mode 100644 index e482b1c9d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.destroystokyo.paper.entity.CraftRangedEntity; -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, CraftRangedEntity { // Paper - public CraftSnowman(CraftServer server, EntitySnowman entity) { - super(server, entity); - } - - @Override - public boolean isDerp() { - return !getHandle().hasPumpkin(); - } - - @Override - public void setDerp(boolean derpMode) { - getHandle().setHasPumpkin(!derpMode); - } - - @Override - public EntitySnowman getHandle() { - return (EntitySnowman) entity; - } - - @Override - public String toString() { - return "CraftSnowman"; - } - - @Override - public EntityType getType() { - return EntityType.SNOWMAN; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpectralArrow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpectralArrow.java deleted file mode 100644 index 3a614edd7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpectralArrow.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntitySpectralArrow; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.SpectralArrow; - -public class CraftSpectralArrow extends CraftArrow implements SpectralArrow { - - public CraftSpectralArrow(CraftServer server, EntitySpectralArrow entity) { - super(server, entity); - } - - @Override - public EntitySpectralArrow getHandle() { - return (EntitySpectralArrow) entity; - } - - @Override - public String toString() { - return "CraftSpectralArrow"; - } - - @Override - public EntityType getType() { - return EntityType.SPECTRAL_ARROW; - } - - @Override - public int getGlowingTicks() { - return getHandle().duration; - } - - @Override - public void setGlowingTicks(int duration) { - getHandle().duration = duration; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpellcaster.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpellcaster.java deleted file mode 100644 index db1ba5b2c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpellcaster.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.EntityIllagerWizard; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.Spellcaster; - -public class CraftSpellcaster extends CraftIllager implements Spellcaster { - - public CraftSpellcaster(CraftServer server, EntityIllagerWizard entity) { - super(server, entity); - } - - @Override - public EntityIllagerWizard getHandle() { - return (EntityIllagerWizard) super.getHandle(); - } - - @Override - public String toString() { - return "CraftSpellcaster"; - } - - @Override - public Spell getSpell() { - return Spell.valueOf(getHandle().getSpell().name()); - } - - @Override - public void setSpell(Spell spell) { - Preconditions.checkArgument(spell != null, "Use Spell.NONE"); - - getHandle().setSpell(EntityIllagerWizard.Spell.a(spell.ordinal())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java deleted file mode 100644 index a3f452aca..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java +++ /dev/null @@ -1,28 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.SPIDER; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java deleted file mode 100644 index 6cb09623e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java +++ /dev/null @@ -1,28 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.SQUID; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftStray.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftStray.java deleted file mode 100644 index 0fcb05bad..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftStray.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntitySkeletonStray; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Stray; - -public class CraftStray extends CraftSkeleton implements Stray { - - public CraftStray(CraftServer server, EntitySkeletonStray entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftStray"; - } - - @Override - public EntityType getType() { - return EntityType.STRAY; - } - - @Override - public SkeletonType getSkeletonType() { - return SkeletonType.STRAY; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java deleted file mode 100644 index 4ef91a37d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java +++ /dev/null @@ -1,67 +0,0 @@ -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); - } - - @Override - public float getYield() { - return getHandle().yield; - } - - @Override - public boolean isIncendiary() { - return getHandle().isIncendiary; - } - - @Override - public void setIsIncendiary(boolean isIncendiary) { - getHandle().isIncendiary = isIncendiary; - } - - @Override - public void setYield(float yield) { - getHandle().yield = yield; - } - - @Override - public int getFuseTicks() { - return getHandle().getFuseTicks(); - } - - @Override - public void setFuseTicks(int fuseTicks) { - getHandle().setFuseTicks(fuseTicks); - } - - @Override - public EntityTNTPrimed getHandle() { - return (EntityTNTPrimed) entity; - } - - @Override - public String toString() { - return "CraftTNTPrimed"; - } - - @Override - public EntityType getType() { - return EntityType.PRIMED_TNT; - } - - @Override - public Entity getSource() { - EntityLiving source = getHandle().getSource(); - - return (source != null) ? source.getBukkitEntity() : null; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java deleted file mode 100644 index 407b95caf..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import java.util.UUID; -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; - -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 getOwnerUniqueId() { - return getOwnerUUID(); - } - public UUID getOwnerUUID() { - try { - return getHandle().getOwnerUUID(); - } catch (IllegalArgumentException ex) { - return null; - } - } - - public void setOwnerUUID(UUID uuid) { - getHandle().setOwnerUUID(uuid); - } - - @Override - public AnimalTamer getOwner() { - if (getOwnerUUID() == null) { - return null; - } - - AnimalTamer owner = getServer().getPlayer(getOwnerUUID()); - if (owner == null) { - owner = getServer().getOfflinePlayer(getOwnerUUID()); - } - - return owner; - } - - @Override - public boolean isTamed() { - return getHandle().isTamed(); - } - - @Override - public void setOwner(AnimalTamer tamer) { - if (tamer != null) { - setTamed(true); - getHandle().setGoalTarget(null, null, false); - setOwnerUUID(tamer.getUniqueId()); - } else { - setTamed(false); - setOwnerUUID(null); - } - } - - @Override - public void setTamed(boolean tame) { - getHandle().setTamed(tame); - if (!tame) { - setOwnerUUID(null); - } - } - - public boolean isSitting() { - return getHandle().isSitting(); - } - - public void setSitting(boolean sitting) { - getHandle().setSitting(sitting); - getHandle().getGoalSit().setSitting(sitting); - } - - @Override - public String toString() { - return getClass().getSimpleName() + "{owner=" + getOwner() + ",tamed=" + isTamed() + "}"; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java deleted file mode 100644 index 338bc530c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java +++ /dev/null @@ -1,27 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.THROWN_EXP_BOTTLE; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java deleted file mode 100644 index 2400f3309..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.collect.ImmutableList; -import java.util.Collection; -import net.minecraft.server.EntityPotion; -import net.minecraft.server.MobEffect; -import net.minecraft.server.PotionUtil; -import org.apache.commons.lang.Validate; -import org.bukkit.Material; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; - -public class CraftThrownPotion extends CraftProjectile implements ThrownPotion { - public CraftThrownPotion(CraftServer server, EntityPotion entity) { - super(server, entity); - } - - @Override - public Collection getEffects() { - ImmutableList.Builder builder = ImmutableList.builder(); - for (MobEffect effect : PotionUtil.getEffects(getHandle().getItem())) { - builder.add(CraftPotionUtil.toBukkit(effect)); - } - return builder.build(); - } - - @Override - public ItemStack getItem() { - return CraftItemStack.asBukkitCopy(getHandle().getItem()); - } - - @Override - 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.LINGERING_POTION || item.getType() == Material.SPLASH_POTION, "ItemStack must be a lingering or splash potion. This item stack was " + item.getType() + "."); - - getHandle().setItem(CraftItemStack.asNMSCopy(item)); - } - - @Override - public EntityPotion getHandle() { - return (EntityPotion) entity; - } - - @Override - public EntityType getType() { - return EntityType.SPLASH_POTION; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTippedArrow.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTippedArrow.java deleted file mode 100644 index ecdaa2b97..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTippedArrow.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.collect.ImmutableList; -import java.util.List; -import net.minecraft.server.EntityTippedArrow; -import net.minecraft.server.MobEffect; -import net.minecraft.server.MobEffectList; -import org.apache.commons.lang.Validate; -import org.bukkit.Color; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.EntityType; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -public class CraftTippedArrow extends CraftArrow implements Arrow { - - public CraftTippedArrow(CraftServer server, EntityTippedArrow entity) { - super(server, entity); - } - - @Override - public EntityTippedArrow getHandle() { - return (EntityTippedArrow) entity; - } - - @Override - public String toString() { - return "CraftTippedArrow"; - } - - @Override - public EntityType getType() { - return EntityType.ARROW; - } - - @Override - public boolean addCustomEffect(PotionEffect effect, boolean override) { - int effectId = effect.getType().getId(); - MobEffect existing = null; - for (MobEffect mobEffect : getHandle().effects) { - if (MobEffectList.getId(mobEffect.getMobEffect()) == effectId) { - existing = mobEffect; - } - } - if (existing != null) { - if (!override) { - return false; - } - getHandle().effects.remove(existing); - } - getHandle().addEffect(CraftPotionUtil.fromBukkit(effect)); - getHandle().refreshEffects(); - return true; - } - - @Override - public void clearCustomEffects() { - getHandle().effects.clear(); - getHandle().refreshEffects(); - } - - @Override - public List getCustomEffects() { - ImmutableList.Builder builder = ImmutableList.builder(); - for (MobEffect effect : getHandle().effects) { - builder.add(CraftPotionUtil.toBukkit(effect)); - } - return builder.build(); - } - - @Override - public boolean hasCustomEffect(PotionEffectType type) { - for (MobEffect effect : getHandle().effects) { - if (CraftPotionUtil.equals(effect.getMobEffect(), type)) { - return true; - } - } - return false; - } - - @Override - public boolean hasCustomEffects() { - return !getHandle().effects.isEmpty(); - } - - @Override - public boolean removeCustomEffect(PotionEffectType effect) { - int effectId = effect.getId(); - MobEffect existing = null; - for (MobEffect mobEffect : getHandle().effects) { - if (MobEffectList.getId(mobEffect.getMobEffect()) == effectId) { - existing = mobEffect; - } - } - if (existing == null) { - return false; - } - getHandle().effects.remove(existing); - getHandle().refreshEffects(); - return true; - } - - @Override - public void setBasePotionData(PotionData data) { - Validate.notNull(data, "PotionData cannot be null"); - getHandle().setType(CraftPotionUtil.fromBukkit(data)); - } - - @Override - public PotionData getBasePotionData() { - return CraftPotionUtil.toBukkit(getHandle().getType()); - } - - @Override - public void setColor(Color color) { - getHandle().setColor(color.asRGB()); - } - - @Override - public Color getColor() { - return Color.fromRGB(getHandle().getColor()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTraderLlama.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTraderLlama.java deleted file mode 100644 index 38a8649c6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTraderLlama.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityLlamaTrader; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.TraderLlama; - -public class CraftTraderLlama extends CraftLlama implements TraderLlama { - - public CraftTraderLlama(CraftServer server, EntityLlamaTrader entity) { - super(server, entity); - } - - @Override - public EntityLlamaTrader getHandle() { - return (EntityLlamaTrader) super.getHandle(); - } - - @Override - public String toString() { - return "CraftTraderLlama"; - } - - @Override - public EntityType getType() { - return EntityType.TRADER_LLAMA; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTrident.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTrident.java deleted file mode 100644 index 0518e6c68..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTrident.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityThrownTrident; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Trident; - -public class CraftTrident extends CraftArrow implements Trident { - - public CraftTrident(CraftServer server, EntityThrownTrident entity) { - super(server, entity); - } - - @Override - public EntityThrownTrident getHandle() { - return (EntityThrownTrident) super.getHandle(); - } - - @Override - public String toString() { - return "CraftTrident"; - } - - @Override - public EntityType getType() { - return EntityType.TRIDENT; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTropicalFish.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTropicalFish.java deleted file mode 100644 index 9243381a2..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTropicalFish.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import java.util.HashMap; -import java.util.Map; -import net.minecraft.server.EntityTropicalFish; -import org.bukkit.DyeColor; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.TropicalFish; - -public class CraftTropicalFish extends CraftFish implements TropicalFish { - - public CraftTropicalFish(CraftServer server, EntityTropicalFish entity) { - super(server, entity); - } - - @Override - public EntityTropicalFish getHandle() { - return (EntityTropicalFish) entity; - } - - @Override - public String toString() { - return "CraftTropicalFish"; - } - - @Override - public EntityType getType() { - return EntityType.TROPICAL_FISH; - } - - @Override - public DyeColor getPatternColor() { - return getPatternColor(getHandle().getVariant()); - } - - @Override - public void setPatternColor(DyeColor color) { - getHandle().setVariant(getData(color, getBodyColor(), getPattern())); - } - - @Override - public DyeColor getBodyColor() { - return getBodyColor(getHandle().getVariant()); - } - - @Override - public void setBodyColor(DyeColor color) { - getHandle().setVariant(getData(getPatternColor(), color, getPattern())); - } - - @Override - public Pattern getPattern() { - return getPattern(getHandle().getVariant()); - } - - @Override - public void setPattern(Pattern pattern) { - getHandle().setVariant(getData(getPatternColor(), getBodyColor(), pattern)); - } - - public static enum CraftPattern { - KOB(0, false), - SUNSTREAK(1, false), - SNOOPER(2, false), - DASHER(3, false), - BRINELY(4, false), - SPOTTY(5, false), - FLOPPER(0, true), - STRIPEY(1, true), - GLITTER(2, true), - BLOCKFISH(3, true), - BETTY(4, true), - CLAYFISH(5, true); - - private final int variant; - private final boolean large; - - // - private static final Map BY_DATA = new HashMap<>(); - - static { - for (CraftPattern type : values()) { - BY_DATA.put(type.getDataValue(), Pattern.values()[type.ordinal()]); - } - } - - public static Pattern fromData(int data) { - return BY_DATA.get(data); - } - - private CraftPattern(int variant, boolean large) { - this.variant = variant; - this.large = large; - } - - public int getDataValue() { - return variant << 8 | ((large) ? 1 : 0); - } - } - - public static int getData(DyeColor patternColor, DyeColor bodyColor, Pattern type) { - return patternColor.getWoolData() << 24 | bodyColor.getWoolData() << 16 | CraftPattern.values()[type.ordinal()].getDataValue(); - } - - public static DyeColor getPatternColor(int data) { - return DyeColor.getByWoolData((byte) ((data >> 24) & 0xFF)); - } - - public static DyeColor getBodyColor(int data) { - return DyeColor.getByWoolData((byte) ((data >> 16) & 0xFF)); - } - - public static Pattern getPattern(int data) { - return CraftPattern.fromData(data & 0xFFFF); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTurtle.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTurtle.java deleted file mode 100644 index 8edcf7af6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTurtle.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityTurtle; -import net.minecraft.server.MCUtil; -import org.bukkit.Location; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Turtle; - -public class CraftTurtle extends CraftAnimals implements Turtle { - - public CraftTurtle(CraftServer server, EntityTurtle entity) { - super(server, entity); - } - - @Override - public EntityTurtle getHandle() { - return (EntityTurtle) super.getHandle(); - } - - @Override - public String toString() { - return "CraftTurtle"; - } - - @Override - public EntityType getType() { - return EntityType.TURTLE; - } - - // Paper start - @Override - public Location getHome() { - return MCUtil.toLocation(getHandle().world, getHandle().getHome()); - } - - @Override - public void setHome(Location location) { - getHandle().setHome(MCUtil.toBlockPosition(location)); - } - - @Override - public boolean isGoingHome() { - return getHandle().isGoingHome(); - } - - @Override - public boolean isDigging() { - return getHandle().isDigging(); - } - - @Override - public boolean hasEgg() { - return getHandle().hasEgg(); - } - - @Override - public void setHasEgg(boolean hasEgg) { - getHandle().setHasEgg(hasEgg); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java deleted file mode 100644 index 8e4af469f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java +++ /dev/null @@ -1,15 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/entity/CraftVex.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVex.java deleted file mode 100644 index 2f7df3074..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVex.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityInsentient; -import net.minecraft.server.EntityVex; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Mob; -import org.bukkit.entity.Vex; - -public class CraftVex extends CraftMonster implements Vex { - - public CraftVex(CraftServer server, EntityVex entity) { - super(server, entity); - } - - @Override - public EntityVex getHandle() { - return (EntityVex) super.getHandle(); - } - - // Paper start - public Mob getSummoner() { - EntityInsentient owner = getHandle().getOwner(); - return owner != null ? (Mob) owner.getBukkitEntity() : null; - } - - public void setSummoner(Mob summoner) { - getHandle().setOwner(summoner == null ? null : ((CraftMob) summoner).getHandle()); - } - // Paper end - - @Override - public String toString() { - return "CraftVex"; - } - - @Override - public EntityType getType() { - return EntityType.VEX; - } - - @Override - public boolean isCharging() { - return getHandle().isCharging(); - } - - @Override - public void setCharging(boolean charging) { - getHandle().setCharging(charging); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java deleted file mode 100644 index f291a8d75..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import java.util.Locale; -import net.minecraft.server.EntityVillager; -import net.minecraft.server.IRegistry; -import net.minecraft.server.VillagerProfession; -import net.minecraft.server.IBlockData; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.BlockBed; -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Villager; - -public class CraftVillager extends CraftAbstractVillager implements Villager { - - public CraftVillager(CraftServer server, EntityVillager entity) { - super(server, entity); - } - - @Override - public EntityVillager getHandle() { - return (EntityVillager) entity; - } - - @Override - public String toString() { - return "CraftVillager"; - } - - @Override - public EntityType getType() { - return EntityType.VILLAGER; - } - - @Override - public Profession getProfession() { - return CraftVillager.nmsToBukkitProfession(getHandle().getVillagerData().getProfession()); - } - - @Override - public void setProfession(Profession profession) { - Validate.notNull(profession); - getHandle().setVillagerData(getHandle().getVillagerData().withProfession(CraftVillager.bukkitToNmsProfession(profession))); - } - - @Override - public Type getVillagerType() { - return Type.valueOf(IRegistry.VILLAGER_TYPE.getKey(getHandle().getVillagerData().getType()).getKey().toUpperCase(Locale.ROOT)); - } - - @Override - public void setVillagerType(Type type) { - Validate.notNull(type); - getHandle().setVillagerData(getHandle().getVillagerData().withType(IRegistry.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())))); - } - - @Override - public int getVillagerLevel() { - return getHandle().getVillagerData().getLevel(); - } - - @Override - public void setVillagerLevel(int level) { - Preconditions.checkArgument(1 <= level && level <= 5, "level must be between [1, 5]"); - - getHandle().setVillagerData(getHandle().getVillagerData().withLevel(level)); - } - - @Override - public int getVillagerExperience() { - return getHandle().getExperience(); - } - - @Override - public void setVillagerExperience(int experience) { - Preconditions.checkArgument(experience >= 0, "Experience must be positive"); - - getHandle().setExperience(experience); - } - - @Override - public boolean sleep(Location location) { - Preconditions.checkArgument(location != null, "Location cannot be null"); - Preconditions.checkArgument(location.getWorld() != null, "Location needs to be in a world"); - Preconditions.checkArgument(location.getWorld().equals(getWorld()), "Cannot sleep across worlds"); - - BlockPosition position = new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - IBlockData iblockdata = getHandle().world.getType(position); - if (!(iblockdata.getBlock() instanceof BlockBed)) { - return false; - } - - getHandle().e(position); // PAIL rename sleep - return true; - } - - @Override - public void wakeup() { - Preconditions.checkState(isSleeping(), "Cannot wakeup if not sleeping"); - - getHandle().dy(); // PAIL rename wakeup - } - - public static Profession nmsToBukkitProfession(VillagerProfession nms) { - return Profession.valueOf(IRegistry.VILLAGER_PROFESSION.getKey(nms).getKey().toUpperCase(Locale.ROOT)); - } - - public static VillagerProfession bukkitToNmsProfession(Profession bukkit) { - return IRegistry.VILLAGER_PROFESSION.get(CraftNamespacedKey.toMinecraft(bukkit.getKey())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java deleted file mode 100644 index 477635444..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import java.util.Locale; -import java.util.UUID; -import net.minecraft.server.EntityZombieVillager; -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.MobEffects; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Villager; -import org.bukkit.entity.ZombieVillager; - -public class CraftVillagerZombie extends CraftZombie implements ZombieVillager { - - public CraftVillagerZombie(CraftServer server, EntityZombieVillager entity) { - super(server, entity); - } - - @Override - public EntityZombieVillager getHandle() { - return (EntityZombieVillager) super.getHandle(); - } - - @Override - public String toString() { - return "CraftVillagerZombie"; - } - - @Override - public EntityType getType() { - return EntityType.ZOMBIE_VILLAGER; - } - - @Override - public Villager.Profession getVillagerProfession() { - return Villager.Profession.valueOf(IRegistry.VILLAGER_PROFESSION.getKey(getHandle().getVillagerData().getProfession()).getKey().toUpperCase(Locale.ROOT)); - } - - @Override - public void setVillagerProfession(Villager.Profession profession) { - Validate.notNull(profession); - getHandle().setVillagerData(getHandle().getVillagerData().withProfession(IRegistry.VILLAGER_PROFESSION.get(new MinecraftKey(profession.name().toLowerCase(Locale.ROOT))))); - } - - @Override - public boolean isConverting() { - return getHandle().isConverting(); - } - - @Override - public int getConversionTime() { - Preconditions.checkState(isConverting(), "Entity not converting"); - - return getHandle().conversionTime; - } - - @Override - public void setConversionTime(int time) { - if (time < 0) { - getHandle().conversionTime = -1; - getHandle().getDataWatcher().set(EntityZombieVillager.CONVERTING, false); - getHandle().persistent = false; // CraftBukkit - SPIGOT-4684 update persistence - getHandle().conversionPlayer = null; - getHandle().removeEffect(MobEffects.INCREASE_DAMAGE, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION); - } else { - getHandle().startConversion((UUID) null, time); - } - } - - @Override - public OfflinePlayer getConversionPlayer() { - return (getHandle().conversionPlayer == null) ? null : Bukkit.getOfflinePlayer(getHandle().conversionPlayer); - } - - @Override - public void setConversionPlayer(OfflinePlayer conversionPlayer) { - if (!this.isConverting()) return; - getHandle().conversionPlayer = (conversionPlayer == null) ? null : conversionPlayer.getUniqueId(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftVindicator.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftVindicator.java deleted file mode 100644 index 5ff957ced..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftVindicator.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityVindicator; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Vindicator; - -public class CraftVindicator extends CraftIllager implements Vindicator { - - public CraftVindicator(CraftServer server, EntityVindicator entity) { - super(server, entity); - } - - @Override - public EntityVindicator getHandle() { - return (EntityVindicator) super.getHandle(); - } - - @Override - public String toString() { - return "CraftVindicator"; - } - - @Override - public EntityType getType() { - return EntityType.VINDICATOR; - } - - // Paper start - public boolean isJohnny() { - return getHandle().isJohnny(); - } - - public void setJohnny(boolean johnny) { - getHandle().setJohnny(johnny); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWanderingTrader.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWanderingTrader.java deleted file mode 100644 index 795e6afd8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWanderingTrader.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityVillagerTrader; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.WanderingTrader; - -public class CraftWanderingTrader extends CraftAbstractVillager implements WanderingTrader { - - public CraftWanderingTrader(CraftServer server, EntityVillagerTrader entity) { - super(server, entity); - } - - @Override - public EntityVillagerTrader getHandle() { - return (EntityVillagerTrader) entity; - } - - @Override - public String toString() { - return "CraftWanderingTrader"; - } - - @Override - public EntityType getType() { - return EntityType.WANDERING_TRADER; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java deleted file mode 100644 index 2be883986..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityWaterAnimal; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.WaterMob; - -public class CraftWaterMob extends CraftCreature 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/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java deleted file mode 100644 index b43a2bbd5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java +++ /dev/null @@ -1,53 +0,0 @@ -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; -// Paper start -import com.destroystokyo.paper.entity.CraftRangedEntity; -import com.google.common.base.Preconditions; -import org.bukkit.Material; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.inventory.ItemStack; -// Paper end - -public class CraftWitch extends CraftRaider implements Witch, CraftRangedEntity { - public CraftWitch(CraftServer server, EntityWitch entity) { - super(server, entity); - } - - @Override - public EntityWitch getHandle() { - return (EntityWitch) entity; - } - - @Override - public String toString() { - return "CraftWitch"; - } - - @Override - public EntityType getType() { - return EntityType.WITCH; - } - - // Paper start - public boolean isDrinkingPotion() { - return getHandle().isDrinkingPotion(); - } - - public int getPotionUseTimeLeft() { - return getHandle().getPotionUseTimeLeft(); - } - - public ItemStack getDrinkingPotion() { - return CraftItemStack.asCraftMirror(getHandle().getItemInMainHand()); - } - - public void setDrinkingPotion(ItemStack potion) { - Preconditions.checkArgument(potion == null || potion.getType().isEmpty() || potion.getType() == Material.POTION, "must be potion, air, or null"); - getHandle().setDrinkingPotion(CraftItemStack.asNMSCopy(potion)); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java deleted file mode 100644 index 03cf6136e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.destroystokyo.paper.entity.CraftRangedEntity; -import net.minecraft.server.EntityWither; -import org.bukkit.boss.BossBar; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.boss.CraftBossBar; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Wither; - -public class CraftWither extends CraftMonster implements Wither, CraftRangedEntity { // Paper - - private BossBar bossBar; - - public CraftWither(CraftServer server, EntityWither entity) { - super(server, entity); - - if (entity.bossBattle != null) { - this.bossBar = new CraftBossBar(entity.bossBattle); - } - } - - @Override - public EntityWither getHandle() { - return (EntityWither) entity; - } - - @Override - public String toString() { - return "CraftWither"; - } - - @Override - public EntityType getType() { - return EntityType.WITHER; - } - - @Override - public BossBar getBossBar() { - return bossBar; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkeleton.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkeleton.java deleted file mode 100644 index 6fb1da7da..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkeleton.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntitySkeletonWither; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.WitherSkeleton; - -public class CraftWitherSkeleton extends CraftSkeleton implements WitherSkeleton { - - public CraftWitherSkeleton(CraftServer server, EntitySkeletonWither entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftWitherSkeleton"; - } - - @Override - public EntityType getType() { - return EntityType.WITHER_SKELETON; - } - - @Override - public SkeletonType getSkeletonType() { - return SkeletonType.WITHER; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java deleted file mode 100644 index 93616809d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java +++ /dev/null @@ -1,37 +0,0 @@ -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"; - } - - @Override - public EntityType getType() { - return EntityType.WITHER_SKULL; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java deleted file mode 100644 index 80244fba3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java +++ /dev/null @@ -1,44 +0,0 @@ -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); - } - - @Override - public boolean isAngry() { - return getHandle().isAngry(); - } - - @Override - public void setAngry(boolean angry) { - getHandle().setAngry(angry); - } - - @Override - public EntityWolf getHandle() { - return (EntityWolf) entity; - } - - @Override - public EntityType getType() { - return EntityType.WOLF; - } - - @Override - public DyeColor getCollarColor() { - return DyeColor.getByWoolData((byte) getHandle().getCollarColor().getColorIndex()); - } - - @Override - public void setCollarColor(DyeColor color) { - getHandle().setCollarColor(EnumColor.fromColorIndex(color.getWoolData())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java deleted file mode 100644 index c4320dbb6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import com.google.common.base.Preconditions; -import net.minecraft.server.EntityZombie; -import net.minecraft.server.EntityZombieVillager; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Villager; -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"; - } - - @Override - public EntityType getType() { - return EntityType.ZOMBIE; - } - - @Override - public boolean isBaby() { - return getHandle().isBaby(); - } - - @Override - public void setBaby(boolean flag) { - getHandle().setBaby(flag); - } - - @Override - public boolean isVillager() { - return getHandle() instanceof EntityZombieVillager; - } - - @Override - public void setVillager(boolean flag) { - throw new UnsupportedOperationException("Not supported."); - } - - @Override - public void setVillagerProfession(Villager.Profession profession) { - throw new UnsupportedOperationException("Not supported."); - } - - @Override - public Villager.Profession getVillagerProfession() { - return null; - } - - @Override - public boolean isConverting() { - return getHandle().isDrownConverting(); - } - - @Override - public int getConversionTime() { - Preconditions.checkState(isConverting(), "Entity not converting"); - - return getHandle().drownedConversionTime; - } - - @Override - public void setConversionTime(int time) { - if (time < 0) { - getHandle().drownedConversionTime = -1; - getHandle().getDataWatcher().set(EntityZombie.DROWN_CONVERTING, false); - } else { - getHandle().startDrownedConversion(time); - } - } - - // Paper start - @Override - public boolean isDrowning() { - return getHandle().isDrowning(); - } - - @Override - public void startDrowning(int drownedConversionTime) { - getHandle().startDrownedConversion(drownedConversionTime); - } - - @Override - public void stopDrowning() { - getHandle().stopDrowning(); - } - - @Override - public boolean shouldBurnInDay() { - return getHandle().shouldBurnInDay(); - } - - @Override - public boolean isArmsRaised() { - return getHandle().isArmsRaisedZombie(); - } - - @Override - public void setArmsRaised(final boolean raised) { - getHandle().setArmsRaisedZombie(raised); - } - - @Override - public void setShouldBurnInDay(boolean shouldBurnInDay) { - getHandle().setShouldBurnInDay(shouldBurnInDay); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftZombieHorse.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftZombieHorse.java deleted file mode 100644 index 5b31b6816..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftZombieHorse.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.entity; - -import net.minecraft.server.EntityHorseZombie; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Horse.Variant; -import org.bukkit.entity.ZombieHorse; - -public class CraftZombieHorse extends CraftAbstractHorse implements ZombieHorse { - - public CraftZombieHorse(CraftServer server, EntityHorseZombie entity) { - super(server, entity); - } - - @Override - public String toString() { - return "CraftZombieHorse"; - } - - @Override - public EntityType getType() { - return EntityType.ZOMBIE_HORSE; - } - - @Override - public Variant getVariant() { - return Variant.UNDEAD_HORSE; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryKey.java b/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryKey.java deleted file mode 100644 index fee6bc588..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryKey.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit.craftbukkit.entity.memory; - -import net.minecraft.server.IRegistry; -import net.minecraft.server.MemoryModuleType; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.entity.memory.MemoryKey; - -public final class CraftMemoryKey { - - private CraftMemoryKey() {} - - public static MemoryModuleType fromMemoryKey(MemoryKey memoryKey) { - return (MemoryModuleType) IRegistry.MEMORY_MODULE_TYPE.get(CraftNamespacedKey.toMinecraft(memoryKey.getKey())); - } - - public static MemoryKey toMemoryKey(MemoryModuleType memoryModuleType) { - return MemoryKey.getByKey(CraftNamespacedKey.fromMinecraft(IRegistry.MEMORY_MODULE_TYPE.getKey(memoryModuleType))); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryMapper.java b/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryMapper.java deleted file mode 100644 index e7eacfc74..000000000 --- a/src/main/java/org/bukkit/craftbukkit/entity/memory/CraftMemoryMapper.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bukkit.craftbukkit.entity.memory; - -import net.minecraft.server.BlockPosition; -import net.minecraft.server.GlobalPos; -import net.minecraft.server.MinecraftSerializableLong; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.CraftWorld; - -public final class CraftMemoryMapper { - - private CraftMemoryMapper() {} - - public static Object fromNms(Object object) { - if (object instanceof GlobalPos) { - return fromNms((GlobalPos) object); - } else if (object instanceof MinecraftSerializableLong) { - return ((MinecraftSerializableLong) object).a(); - } - - throw new UnsupportedOperationException("Do not know how to map " + object); - } - - public static Object toNms(Object object) { - if (object == null) { - return null; - } else if (object instanceof Location) { - return toNms((Location) object); - } else if (object instanceof Long) { - return MinecraftSerializableLong.a((Long) object); - } - - throw new UnsupportedOperationException("Do not know how to map " + object); - } - - public static Location fromNms(GlobalPos globalPos) { - return new org.bukkit.Location(((CraftServer) Bukkit.getServer()).getServer().getWorldServer(globalPos.getDimensionManager()).getWorld(), globalPos.getBlockPosition().getX(), globalPos.getBlockPosition().getY(), globalPos.getBlockPosition().getZ()); - } - - public static GlobalPos toNms(Location location) { - return GlobalPos.create(((CraftWorld) location.getWorld()).getHandle().getWorldProvider().getDimensionManager(), new BlockPosition(location.getX(), location.getY(), location.getZ())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java b/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java deleted file mode 100644 index dc15703fd..000000000 --- a/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java +++ /dev/null @@ -1,1661 +0,0 @@ -package org.bukkit.craftbukkit.event; - -import com.google.common.base.Function; -import com.google.common.base.Functions; -import com.google.common.collect.Lists; -import com.mojang.datafixers.util.Either; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Nullable; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.BlockPropertyInstrument; -import net.minecraft.server.ChatMessage; -import net.minecraft.server.ChatModifier; -import net.minecraft.server.Container; -import net.minecraft.server.ContainerMerchant; -import net.minecraft.server.DamageSource; -import net.minecraft.server.DimensionManager; -import net.minecraft.server.Entity; -import net.minecraft.server.EntityAnimal; -import net.minecraft.server.EntityAreaEffectCloud; -import net.minecraft.server.EntityDamageSource; -import net.minecraft.server.EntityDamageSourceIndirect; -import net.minecraft.server.EntityEnderCrystal; -import net.minecraft.server.EntityEnderDragon; -import net.minecraft.server.EntityExperienceOrb; -import net.minecraft.server.EntityFireworks; -import net.minecraft.server.EntityGhast; -import net.minecraft.server.EntityGolem; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.EntityInsentient; -import net.minecraft.server.EntityItem; -import net.minecraft.server.EntityLiving; -import net.minecraft.server.EntityMonster; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.EntityPotion; -import net.minecraft.server.EntitySheep; -import net.minecraft.server.EntitySlime; -import net.minecraft.server.EntityRaider; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.EntityVillager; -import net.minecraft.server.EntityWaterAnimal; -import net.minecraft.server.EnumDirection; -import net.minecraft.server.EnumHand; -import net.minecraft.server.EnumItemSlot; -import net.minecraft.server.Explosion; -import net.minecraft.server.GeneratorAccess; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IChatBaseComponent; -import net.minecraft.server.IInventory; -import net.minecraft.server.IProjectile; -import net.minecraft.server.ItemActionContext; -import net.minecraft.server.ItemStack; -import net.minecraft.server.Items; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.MobEffect; -import net.minecraft.server.MovingObjectPosition; -import net.minecraft.server.MovingObjectPositionBlock; -import net.minecraft.server.MovingObjectPositionEntity; -import net.minecraft.server.NPC; -import net.minecraft.server.PacketPlayInCloseWindow; -import net.minecraft.server.Raid; -import net.minecraft.server.Unit; -import net.minecraft.server.World; -import net.minecraft.server.WorldServer; -import org.bukkit.Bukkit; -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.craftbukkit.CraftRaid; -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.block.data.CraftBlockData; -import org.bukkit.craftbukkit.entity.CraftEntity; -import org.bukkit.craftbukkit.entity.CraftLivingEntity; -import org.bukkit.craftbukkit.entity.CraftRaider; -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.potion.CraftPotionUtil; -import org.bukkit.craftbukkit.util.CraftDamageSource; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.entity.AbstractHorse; -import org.bukkit.entity.AreaEffectCloud; -import org.bukkit.entity.Bat; -import org.bukkit.entity.Creeper; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.ExperienceOrb; -import org.bukkit.entity.Firework; -import org.bukkit.entity.Item; -import org.bukkit.entity.LightningStrike; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Pig; -import org.bukkit.entity.PigZombie; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.Raider; -import org.bukkit.entity.Sheep; -import org.bukkit.entity.ThrownExpBottle; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.entity.Vehicle; -import org.bukkit.entity.Villager; -import org.bukkit.entity.Villager.Profession; -import org.bukkit.entity.ExperienceOrb; // Paper -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.Event.Result; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockDropItemEvent; -import org.bukkit.event.block.BlockFadeEvent; -import org.bukkit.event.block.BlockFormEvent; -import org.bukkit.event.block.BlockGrowEvent; -import org.bukkit.event.block.BlockIgniteEvent; -import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; -import org.bukkit.event.block.BlockMultiPlaceEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.block.BlockShearEntityEvent; -import org.bukkit.event.block.BlockSpreadEvent; -import org.bukkit.event.block.EntityBlockFormEvent; -import org.bukkit.event.block.FluidLevelChangeEvent; -import org.bukkit.event.block.MoistureChangeEvent; -import org.bukkit.event.block.NotePlayEvent; -import org.bukkit.event.entity.AreaEffectCloudApplyEvent; -import org.bukkit.event.entity.BatToggleSleepEvent; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; -import org.bukkit.event.entity.CreeperPowerEvent; -import org.bukkit.event.entity.EntityBreakDoorEvent; -import org.bukkit.event.entity.EntityBreedEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityDamageByBlockEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.event.entity.EntityPickupItemEvent; -import org.bukkit.event.entity.EntityPlaceEvent; -import org.bukkit.event.entity.EntityPotionEffectEvent; -import org.bukkit.event.entity.EntityShootBowEvent; -import org.bukkit.event.entity.EntitySpawnEvent; -import org.bukkit.event.entity.EntityTameEvent; -import org.bukkit.event.entity.EntityTargetEvent; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.event.entity.EntityToggleGlideEvent; -import org.bukkit.event.entity.EntityToggleSwimEvent; -import org.bukkit.event.entity.EntityTransformEvent; -import org.bukkit.event.entity.ExpBottleEvent; -import org.bukkit.event.entity.FireworkExplodeEvent; -import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.bukkit.event.entity.HorseJumpEvent; -import org.bukkit.event.entity.ItemDespawnEvent; -import org.bukkit.event.entity.ItemMergeEvent; -import org.bukkit.event.entity.ItemSpawnEvent; -import org.bukkit.event.entity.LingeringPotionSplashEvent; -import org.bukkit.event.entity.PigZapEvent; -import org.bukkit.event.entity.PlayerDeathEvent; -import org.bukkit.event.entity.PlayerLeashEntityEvent; -import org.bukkit.event.entity.PotionSplashEvent; -import org.bukkit.event.entity.ProjectileHitEvent; -import org.bukkit.event.entity.ProjectileLaunchEvent; -import org.bukkit.event.entity.VillagerCareerChangeEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryOpenEvent; -import org.bukkit.event.inventory.PrepareAnvilEvent; -import org.bukkit.event.inventory.PrepareItemCraftEvent; -import org.bukkit.event.inventory.TradeSelectEvent; -import org.bukkit.event.player.PlayerBedEnterEvent; -import org.bukkit.event.player.PlayerBedEnterEvent.BedEnterResult; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerBucketFillEvent; -import org.bukkit.event.player.PlayerEditBookEvent; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.event.player.PlayerExpChangeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerItemBreakEvent; -import org.bukkit.event.player.PlayerItemMendEvent; -import org.bukkit.event.player.PlayerLevelChangeEvent; -import org.bukkit.event.player.PlayerRecipeDiscoverEvent; -import org.bukkit.event.player.PlayerStatisticIncrementEvent; -import org.bukkit.event.player.PlayerUnleashEntityEvent; -import org.bukkit.event.server.ServerListPingEvent; -import org.bukkit.event.vehicle.VehicleCreateEvent; -import org.bukkit.event.raid.RaidTriggerEvent; -import org.bukkit.event.raid.RaidFinishEvent; -import org.bukkit.event.raid.RaidStopEvent; -import org.bukkit.event.raid.RaidSpawnWaveEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.InventoryView; -import org.bukkit.inventory.meta.BookMeta; -import org.bukkit.potion.PotionEffect; - -import org.bukkit.event.entity.SpawnerSpawnEvent; // Spigot - -public class CraftEventFactory { - public static final DamageSource MELTING = CraftDamageSource.copyOf(DamageSource.BURN); - public static final DamageSource POISON = CraftDamageSource.copyOf(DamageSource.MAGIC); - 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(World world, Player player, int x, int z) { - int spawnSize = Bukkit.getServer().getSpawnRadius(); - - if (world.getWorldProvider().getDimensionManager() != DimensionManager.OVERWORLD) return true; - if (spawnSize <= 0) return true; - if (((CraftServer) Bukkit.getServer()).getHandle().getOPs().isEmpty()) return true; - if (player.isOp()) return true; - - BlockPosition chunkcoordinates = world.getSpawn(); - - int distanceFromSpawn = Math.max(Math.abs(x - chunkcoordinates.getX()), Math.abs(z - chunkcoordinates.getZ())); - return distanceFromSpawn > spawnSize; - } - - public static T callEvent(T event) { - Bukkit.getServer().getPluginManager().callEvent(event); - return event; - } - - /** - * PlayerBedEnterEvent - */ - public static Either callPlayerBedEnterEvent(EntityHuman player, BlockPosition bed, Either nmsBedResult) { - BedEnterResult bedEnterResult = nmsBedResult.mapBoth(new Function() { - @Override - public BedEnterResult apply(EntityHuman.EnumBedResult t) { - switch (t) { - case NOT_POSSIBLE_HERE: - return BedEnterResult.NOT_POSSIBLE_HERE; - case NOT_POSSIBLE_NOW: - return BedEnterResult.NOT_POSSIBLE_NOW; - case TOO_FAR_AWAY: - return BedEnterResult.TOO_FAR_AWAY; - case NOT_SAFE: - return BedEnterResult.NOT_SAFE; - default: - return BedEnterResult.OTHER_PROBLEM; - } - } - }, t -> BedEnterResult.OK).map(java.util.function.Function.identity(), java.util.function.Function.identity()); - - PlayerBedEnterEvent event = new PlayerBedEnterEvent((Player) player.getBukkitEntity(), CraftBlock.at(player.world, bed), bedEnterResult); - Bukkit.getServer().getPluginManager().callEvent(event); - - Result result = event.useBed(); - if (result == Result.ALLOW) { - return Either.right(Unit.INSTANCE); - } else if (result == Result.DENY) { - return Either.left(EntityHuman.EnumBedResult.OTHER_PROBLEM); - } - - return nmsBedResult; - } - - /** - * Trade Index Change Event - */ - public static TradeSelectEvent callTradeSelectEvent(EntityPlayer player, int newIndex, ContainerMerchant merchant) { - TradeSelectEvent tradeSelectEvent = new TradeSelectEvent(merchant.getBukkitView(), newIndex); - Bukkit.getPluginManager().callEvent(tradeSelectEvent); - return tradeSelectEvent; - } - - /** - * Block place methods - */ - public static BlockMultiPlaceEvent callBlockMultiPlaceEvent(World world, EntityHuman who, EnumHand hand, List blockStates, int clickedX, int clickedY, int clickedZ) { - CraftWorld craftWorld = world.getWorld(); - CraftServer craftServer = world.getServer(); - Player player = (Player) who.getBukkitEntity(); - - Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ); - - boolean canBuild = true; - for (int i = 0; i < blockStates.size(); i++) { - if (!canBuild(world, player, blockStates.get(i).getX(), blockStates.get(i).getZ())) { - canBuild = false; - break; - } - } - - org.bukkit.inventory.ItemStack item; - if (hand == EnumHand.MAIN_HAND) { - item = player.getInventory().getItemInMainHand(); - } else { - item = player.getInventory().getItemInOffHand(); - } - - BlockMultiPlaceEvent event = new BlockMultiPlaceEvent(blockStates, blockClicked, item, player, canBuild); - craftServer.getPluginManager().callEvent(event); - - return event; - } - - public static BlockPlaceEvent callBlockPlaceEvent(World world, EntityHuman who, EnumHand hand, BlockState replacedBlockState, int clickedX, int clickedY, int clickedZ) { - CraftWorld craftWorld = world.getWorld(); - CraftServer craftServer = world.getServer(); - - Player player = (Player) who.getBukkitEntity(); - - Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ); - Block placedBlock = replacedBlockState.getBlock(); - - boolean canBuild = canBuild(world, player, placedBlock.getX(), placedBlock.getZ()); - - org.bukkit.inventory.ItemStack item; - EquipmentSlot equipmentSlot; - if (hand == EnumHand.MAIN_HAND) { - item = player.getInventory().getItemInMainHand(); - equipmentSlot = EquipmentSlot.HAND; - } else { - item = player.getInventory().getItemInOffHand(); - equipmentSlot = EquipmentSlot.OFF_HAND; - } - - BlockPlaceEvent event = new BlockPlaceEvent(placedBlock, replacedBlockState, blockClicked, item, player, canBuild, equipmentSlot); - craftServer.getPluginManager().callEvent(event); - - return event; - } - - public static void handleBlockDropItemEvent(Block block, BlockState state, EntityPlayer player, List items) { - BlockDropItemEvent event = new BlockDropItemEvent(block, state, player.getBukkitEntity(), Lists.transform(items, (item) -> (org.bukkit.entity.Item) item.getBukkitEntity())); - Bukkit.getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - for (EntityItem item : items) { - item.world.addEntity(item); - } - } - } - - public static EntityPlaceEvent callEntityPlaceEvent(ItemActionContext itemactioncontext, Entity entity) { - Player who = (itemactioncontext.getEntity() == null) ? null : (Player) itemactioncontext.getEntity().getBukkitEntity(); - org.bukkit.block.Block blockClicked = CraftBlock.at(itemactioncontext.getWorld(), itemactioncontext.getClickPosition()); - org.bukkit.block.BlockFace blockFace = org.bukkit.craftbukkit.block.CraftBlock.notchToBlockFace(itemactioncontext.getClickedFace()); - - EntityPlaceEvent event = new EntityPlaceEvent(entity.getBukkitEntity(), who, blockClicked, blockFace); - entity.world.getServer().getPluginManager().callEvent(event); - - return event; - } - - /** - * Bucket methods - */ - public static PlayerBucketEmptyEvent callPlayerBucketEmptyEvent(World world, EntityHuman who, BlockPosition changed, BlockPosition clicked, EnumDirection clickedFace, ItemStack itemInHand) { - return (PlayerBucketEmptyEvent) getPlayerBucketEvent(false, world, who, changed, clicked, clickedFace, itemInHand, Items.BUCKET); - } - - public static PlayerBucketFillEvent callPlayerBucketFillEvent(World world, EntityHuman who, BlockPosition changed, BlockPosition clicked, EnumDirection clickedFace, ItemStack itemInHand, net.minecraft.server.Item bucket) { - return (PlayerBucketFillEvent) getPlayerBucketEvent(true, world, who, clicked, changed, clickedFace, itemInHand, bucket); - } - - private static PlayerEvent getPlayerBucketEvent(boolean isFilling, World world, EntityHuman who, BlockPosition changed, BlockPosition clicked, EnumDirection clickedFace, ItemStack itemstack, net.minecraft.server.Item item) { - Player player = (Player) who.getBukkitEntity(); - // Paper start - add EnumHand - return getPlayerBucketEvent(isFilling, world, who, changed, clicked, clickedFace, itemstack, item, null); - } - - public static PlayerBucketEmptyEvent callPlayerBucketEmptyEvent(World world, EntityHuman who, BlockPosition changed, BlockPosition clicked, EnumDirection clickedFace, ItemStack itemstack, EnumHand enumHand) { - return (PlayerBucketEmptyEvent) getPlayerBucketEvent(false, world, who, changed, clicked, clickedFace, itemstack, Items.BUCKET, enumHand); - } - - public static PlayerBucketFillEvent callPlayerBucketFillEvent(World world, EntityHuman who, BlockPosition changed, BlockPosition clicked, EnumDirection clickedFace, ItemStack itemInHand, net.minecraft.server.Item bucket, EnumHand enumHand) { - return (PlayerBucketFillEvent) getPlayerBucketEvent(true, world, who, clicked, changed, clickedFace, itemInHand, bucket, enumHand); - } - - private static PlayerEvent getPlayerBucketEvent(boolean isFilling, World world, EntityHuman who, BlockPosition changed, BlockPosition clicked, EnumDirection clickedFace, ItemStack itemstack, net.minecraft.server.Item item, EnumHand enumHand) { - // Paper end - Player player = (who == null) ? null : (Player) who.getBukkitEntity(); - CraftItemStack itemInHand = CraftItemStack.asNewCraftStack(item); - Material bucket = CraftMagicNumbers.getMaterial(itemstack.getItem()); - - CraftServer craftServer = (CraftServer) player.getServer(); - - Block block = CraftBlock.at(world, changed); - Block blockClicked = CraftBlock.at(world, clicked); - BlockFace blockFace = CraftBlock.notchToBlockFace(clickedFace); - - PlayerEvent event; - if (isFilling) { - event = new PlayerBucketFillEvent(player, block, blockClicked, blockFace, bucket, itemInHand, enumHand == null ? null : enumHand == EnumHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND); // Paper - add enumHand - ((PlayerBucketFillEvent) event).setCancelled(!canBuild(world, player, changed.getX(), changed.getZ())); - } else { - event = new PlayerBucketEmptyEvent(player, block, blockClicked, blockFace, bucket, itemInHand, enumHand == null ? null : enumHand == EnumHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND); // Paper - add enumHand - ((PlayerBucketEmptyEvent) event).setCancelled(!canBuild(world, player, changed.getX(), changed.getZ())); - } - - craftServer.getPluginManager().callEvent(event); - - return event; - } - - /** - * Player Interact event - */ - public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, ItemStack itemstack, EnumHand hand) { - if (action != Action.LEFT_CLICK_AIR && action != Action.RIGHT_CLICK_AIR) { - throw new AssertionError(String.format("%s performing %s with %s", who, action, itemstack)); - } - return callPlayerInteractEvent(who, action, null, EnumDirection.SOUTH, itemstack, hand); - } - - public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, BlockPosition position, EnumDirection direction, ItemStack itemstack, EnumHand hand) { - return callPlayerInteractEvent(who, action, position, direction, itemstack, false, hand); - } - - public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, BlockPosition position, EnumDirection direction, ItemStack itemstack, boolean cancelledBlock, EnumHand hand) { - Player player = (who == null) ? null : (Player) who.getBukkitEntity(); - CraftItemStack itemInHand = CraftItemStack.asCraftMirror(itemstack); - - CraftWorld craftWorld = (CraftWorld) player.getWorld(); - CraftServer craftServer = (CraftServer) player.getServer(); - - Block blockClicked = null; - if (position != null) { - blockClicked = craftWorld.getBlockAt(position.getX(), position.getY(), position.getZ()); - } else { - switch (action) { - case LEFT_CLICK_BLOCK: - action = Action.LEFT_CLICK_AIR; - break; - case RIGHT_CLICK_BLOCK: - action = Action.RIGHT_CLICK_AIR; - break; - } - } - BlockFace blockFace = CraftBlock.notchToBlockFace(direction); - - if (itemInHand.getType() == Material.AIR || itemInHand.getAmount() == 0) { - itemInHand = null; - } - - PlayerInteractEvent event = new PlayerInteractEvent(player, action, itemInHand, blockClicked, blockFace, (hand == null) ? null : ((hand == EnumHand.OFF_HAND) ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND)); - if (cancelledBlock) { - event.setUseInteractedBlock(Event.Result.DENY); - } - craftServer.getPluginManager().callEvent(event); - - return event; - } - - /** - * EntityTransformEvent - */ - public static EntityTransformEvent callEntityTransformEvent(EntityLiving original, EntityLiving coverted, EntityTransformEvent.TransformReason transformReason) { - return callEntityTransformEvent(original, Collections.singletonList(coverted), transformReason); - } - - /** - * EntityTransformEvent - */ - public static EntityTransformEvent callEntityTransformEvent(EntityLiving original, List convertedList, EntityTransformEvent.TransformReason convertType) { - List list = new ArrayList<>(); - for (EntityLiving entityLiving : convertedList) { - list.add(entityLiving.getBukkitEntity()); - } - - EntityTransformEvent event = new EntityTransformEvent(original.getBukkitEntity(), list, convertType); - Bukkit.getPluginManager().callEvent(event); - - return event; - } - - /** - * EntityShootBowEvent - */ - public static EntityShootBowEvent callEntityShootBowEvent(EntityLiving who, ItemStack itemstack, ItemStack arrowItem, IProjectile entityArrow, float force) { // paper - LivingEntity shooter = (LivingEntity) who.getBukkitEntity(); - CraftItemStack itemInHand = CraftItemStack.asCraftMirror(itemstack); - org.bukkit.entity.Entity arrow = ((Entity) entityArrow).getBukkitEntity(); // Paper - - if (itemInHand != null && (itemInHand.getType() == Material.AIR || itemInHand.getAmount() == 0)) { - itemInHand = null; - } - - EntityShootBowEvent event = new EntityShootBowEvent(shooter, itemInHand, CraftItemStack.asCraftMirror(arrowItem), arrow, force); // Paper - Bukkit.getPluginManager().callEvent(event); - - return event; - } - - /** - * VillagerCareerChangeEvent - */ - public static VillagerCareerChangeEvent callVillagerCareerChangeEvent(EntityVillager vilager, Profession future, VillagerCareerChangeEvent.ChangeReason reason) { - VillagerCareerChangeEvent event = new VillagerCareerChangeEvent((Villager) vilager.getBukkitEntity(), future, reason); - Bukkit.getPluginManager().callEvent(event); - - return event; - } - - /** - * BlockDamageEvent - */ - public static BlockDamageEvent callBlockDamageEvent(EntityHuman who, int x, int y, int z, ItemStack itemstack, boolean instaBreak) { - Player player = (who == null) ? null : (Player) who.getBukkitEntity(); - CraftItemStack itemInHand = CraftItemStack.asCraftMirror(itemstack); - - CraftWorld craftWorld = (CraftWorld) player.getWorld(); - CraftServer craftServer = (CraftServer) player.getServer(); - - Block blockClicked = craftWorld.getBlockAt(x, y, z); - - BlockDamageEvent event = new BlockDamageEvent(player, blockClicked, itemInHand, instaBreak); - craftServer.getPluginManager().callEvent(event); - - return event; - } - - public static boolean doEntityAddEventCalling(World world, Entity entity, SpawnReason spawnReason){ - if (entity == null) return false; - - org.bukkit.event.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; - boolean isNpc = entity instanceof NPC; - - if (spawnReason != SpawnReason.CUSTOM) { - if (isAnimal && !world.getWorld().getAllowAnimals() || isMonster && !world.getWorld().getAllowMonsters() || isNpc && !world.getServer().getServer().getSpawnNPCs()) { - 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) { - // Not all projectiles extend EntityProjectile, so check for Bukkit interface instead - event = CraftEventFactory.callProjectileLaunchEvent(entity); - } else if (entity.getBukkitEntity() instanceof org.bukkit.entity.Vehicle){ - event = CraftEventFactory.callVehicleCreateEvent(entity); - // Spigot start - } else if (entity instanceof EntityExperienceOrb) { - EntityExperienceOrb xp = (EntityExperienceOrb) entity; - double radius = world.spigotConfig.expMerge; - if (radius > 0) { - // Paper start - Maximum exp value when merging - Whole section has been tweaked, see comments for specifics - final int maxValue = world.paperConfig.expMergeMaxValue; - final boolean mergeUnconditionally = world.paperConfig.expMergeMaxValue <= 0; - if (mergeUnconditionally || xp.value < maxValue) { // Paper - Skip iteration if unnecessary - - List entities = world.getEntities(entity, entity.getBoundingBox().grow(radius, radius, radius)); - for (Entity e : entities) { - if (e instanceof EntityExperienceOrb) { - EntityExperienceOrb loopItem = (EntityExperienceOrb) e; - // Paper start - if (!loopItem.dead && !(maxValue > 0 && loopItem.value >= maxValue) && new com.destroystokyo.paper.event.entity.ExperienceOrbMergeEvent((org.bukkit.entity.ExperienceOrb) entity.getBukkitEntity(), (org.bukkit.entity.ExperienceOrb) loopItem.getBukkitEntity()).callEvent()) { // Paper - long newTotal = (long)xp.value + (long)loopItem.value; - if ((int) newTotal < 0) continue; // Overflow - if (maxValue > 0 && newTotal > (long)maxValue) { - loopItem.value = (int) (newTotal - maxValue); - xp.value = maxValue; - } else { - xp.value += loopItem.value; - loopItem.die(); - } - // Paper end - } - } - } - - } // Paper end - End iteration skip check - All tweaking ends here - } - // Spigot end - } else if (!(entity instanceof EntityPlayer)) { - event = CraftEventFactory.callEntitySpawnEvent(entity); - } - - if (event != null && (event.isCancelled() || entity.dead)) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.dead = true; - } - for (Entity passenger : entity.getAllPassengers()) { - passenger.dead = true; - } - entity.dead = true; - return false; - } - - return true; - } - - /** - * EntitySpawnEvent - */ - public static EntitySpawnEvent callEntitySpawnEvent(Entity entity) { - org.bukkit.entity.Entity bukkitEntity = entity.getBukkitEntity(); - - EntitySpawnEvent event = new EntitySpawnEvent(bukkitEntity); - bukkitEntity.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); - - 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; - } - - public static LingeringPotionSplashEvent callLingeringPotionSplashEvent(EntityPotion potion, EntityAreaEffectCloud cloud) { - ThrownPotion thrownPotion = (ThrownPotion) potion.getBukkitEntity(); - AreaEffectCloud effectCloud = (AreaEffectCloud) cloud.getBukkitEntity(); - - LingeringPotionSplashEvent event = new LingeringPotionSplashEvent(thrownPotion, effectCloud); - Bukkit.getPluginManager().callEvent(event); - return event; - } - - /** - * BlockFadeEvent - */ - public static BlockFadeEvent callBlockFadeEvent(GeneratorAccess world, BlockPosition pos, IBlockData newBlock) { - CraftBlockState state = CraftBlockState.getBlockState(world, pos); - state.setData(newBlock); - - BlockFadeEvent event = new BlockFadeEvent(state.getBlock(), state); - Bukkit.getPluginManager().callEvent(event); - return event; - } - - public static boolean handleMoistureChangeEvent(World world, BlockPosition pos, IBlockData newBlock, int flag) { - CraftBlockState state = CraftBlockState.getBlockState(world, pos, flag); - state.setData(newBlock); - - MoistureChangeEvent event = new MoistureChangeEvent(state.getBlock(), state); - Bukkit.getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - state.update(true); - } - return !event.isCancelled(); - } - - public static boolean handleBlockSpreadEvent(World world, BlockPosition source, BlockPosition target, IBlockData block) { - return handleBlockSpreadEvent(world, source, target, block, 2); - } - - public static boolean handleBlockSpreadEvent(World world, BlockPosition source, BlockPosition target, IBlockData block, int flag) { - CraftBlockState state = CraftBlockState.getBlockState(world, target, flag); - state.setData(block); - - BlockSpreadEvent event = new BlockSpreadEvent(world.getWorld().getBlockAt(target.getX(), target.getY(), target.getZ()), world.getWorld().getBlockAt(source.getX(), source.getY(), source.getZ()), state); - Bukkit.getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - state.update(true); - } - return !event.isCancelled(); - } - - 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()); - populateFields(victim, event); // Paper - make cancellable - CraftWorld world = (CraftWorld) entity.getWorld(); - Bukkit.getServer().getPluginManager().callEvent(event); - - // Paper start - make cancellable - if (event.isCancelled()) { - return event; - } - playDeathSound(victim, event); - // Paper end - victim.expToDrop = event.getDroppedExp(); - - for (org.bukkit.inventory.ItemStack stack : event.getDrops()) { - if (stack == null || stack.getType() == Material.AIR || stack.getAmount() == 0) continue; - - world.dropItem(entity.getLocation(), stack); - } - - 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); - populateFields(victim, event); // Paper - make cancellable - org.bukkit.World world = entity.getWorld(); - Bukkit.getServer().getPluginManager().callEvent(event); - // Paper start - make cancellable - if (event.isCancelled()) { - return event; - } - playDeathSound(victim, event); - // Paper end - - victim.keepLevel = event.getKeepLevel(); - victim.newLevel = event.getNewLevel(); - victim.newTotalExp = event.getNewTotalExp(); - victim.expToDrop = event.getDroppedExp(); - victim.newExp = event.getNewExp(); - - for (org.bukkit.inventory.ItemStack stack : event.getDrops()) { - if (stack == null || stack.getType() == Material.AIR) continue; - - world.dropItem(entity.getLocation(), stack); - } - - return event; - } - - // Paper start - helper methods for making death event cancellable - // Add information to death event - private static void populateFields(EntityLiving victim, EntityDeathEvent event) { - event.setReviveHealth(event.getEntity().getAttribute(org.bukkit.attribute.Attribute.GENERIC_MAX_HEALTH).getValue()); - event.setShouldPlayDeathSound(!victim.silentDeath && !victim.isSilent()); - net.minecraft.server.SoundEffect soundEffect = victim.getDeathSoundEffect(); - event.setDeathSound(soundEffect != null ? org.bukkit.craftbukkit.CraftSound.getSoundByEffect(soundEffect) : null); - event.setDeathSoundCategory(org.bukkit.SoundCategory.valueOf(victim.getSoundCategory().name())); - event.setDeathSoundVolume(victim.getDeathSoundVolume()); - event.setDeathSoundPitch(victim.getSoundPitch()); - } - - // Play death sound manually - private static void playDeathSound(EntityLiving victim, EntityDeathEvent event) { - if (event.shouldPlayDeathSound() && event.getDeathSound() != null && event.getDeathSoundCategory() != null) { - EntityHuman source = victim instanceof EntityHuman ? (EntityHuman) victim : null; - double x = event.getEntity().getLocation().getX(); - double y = event.getEntity().getLocation().getY(); - double z = event.getEntity().getLocation().getZ(); - net.minecraft.server.SoundEffect soundEffect = org.bukkit.craftbukkit.CraftSound.getSoundEffect(event.getDeathSound()); - net.minecraft.server.SoundCategory soundCategory = net.minecraft.server.SoundCategory.valueOf(event.getDeathSoundCategory().name()); - victim.world.sendSoundEffect(source, x, y, z, soundEffect, soundCategory, event.getDeathSoundVolume(), event.getDeathSoundPitch()); - } - } - // Paper end - /** - * 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 cancelled) { - 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); - } else if (entity instanceof EntityEnderDragon && /*PAIL FIXME ((EntityEnderDragon) entity).target == damager*/ false) { - event = new EntityDamageEvent(entity.getBukkitEntity(), DamageCause.ENTITY_EXPLOSION, modifiers, modifierFunctions); - } 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); - } - event.setCancelled(cancelled); - - callEvent(event); - - if (!event.isCancelled()) { - event.getEntity().setLastDamageCause(event); - } - return event; - } else if (source instanceof EntityDamageSource) { - Entity damager = source.getEntity(); - DamageCause cause = (source.isSweep()) ? DamageCause.ENTITY_SWEEP_ATTACK : 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, cancelled); - } else if (source == DamageSource.OUT_OF_WORLD) { - EntityDamageEvent event = new EntityDamageByBlockEvent(null, entity.getBukkitEntity(), DamageCause.VOID, modifiers, modifierFunctions); - event.setCancelled(cancelled); - callEvent(event); - if (!event.isCancelled()) { - event.getEntity().setLastDamageCause(event); - } - return event; - } else if (source == DamageSource.LAVA) { - EntityDamageEvent event = (new EntityDamageByBlockEvent(null, entity.getBukkitEntity(), DamageCause.LAVA, modifiers, modifierFunctions)); - event.setCancelled(cancelled); - callEvent(event); - if (!event.isCancelled()) { - event.getEntity().setLastDamageCause(event); - } - return event; - } else if (blockDamage != null) { - DamageCause cause = null; - Block damager = blockDamage; - blockDamage = null; - if (source == DamageSource.CACTUS || source == DamageSource.SWEET_BERRY_BUSH) { - cause = DamageCause.CONTACT; - } else if (source == DamageSource.HOT_FLOOR) { - cause = DamageCause.HOT_FLOOR; - } else if (source == DamageSource.MAGIC) { - cause = DamageCause.MAGIC; - } else { - throw new IllegalStateException(String.format("Unhandled damage of %s by %s from %s", entity, damager, source.translationIndex)); - } - EntityDamageEvent event = new EntityDamageByBlockEvent(damager, entity.getBukkitEntity(), cause, modifiers, modifierFunctions); - event.setCancelled(cancelled); - callEvent(event); - if (!event.isCancelled()) { - event.getEntity().setLastDamageCause(event); - } - return event; - } else if (entityDamage != null) { - DamageCause cause = null; - 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 if (source == DamageSource.DRAGON_BREATH) { - cause = DamageCause.DRAGON_BREATH; - } else if (source == DamageSource.MAGIC) { - cause = DamageCause.MAGIC; - } else { - throw new IllegalStateException(String.format("Unhandled damage of %s by %s from %s", entity, damager.getHandle(), source.translationIndex)); - } - EntityDamageEvent event = new EntityDamageByEntityEvent(damager, entity.getBukkitEntity(), cause, modifiers, modifierFunctions); - event.setCancelled(cancelled); - callEvent(event); - 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.FLY_INTO_WALL) { - cause = DamageCause.FLY_INTO_WALL; - } else if (source == DamageSource.CRAMMING) { - cause = DamageCause.CRAMMING; - } else if (source == DamageSource.DRYOUT) { - cause = DamageCause.DRYOUT; - } else if (source == DamageSource.GENERIC) { - cause = DamageCause.CUSTOM; - } - - if (cause != null) { - return callEntityDamageEvent(null, entity, cause, modifiers, modifierFunctions, cancelled); - } - - throw new IllegalStateException(String.format("Unhandled damage of %s from %s", entity, source.translationIndex)); - } - - 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 cancelled) { - EntityDamageEvent event; - if (damager != null) { - event = new EntityDamageByEntityEvent(damager.getBukkitEntity(), damagee.getBukkitEntity(), cause, modifiers, modifierFunctions); - } else { - event = new EntityDamageEvent(damagee.getBukkitEntity(), cause, modifiers, modifierFunctions); - } - event.setCancelled(cancelled); - callEvent(event); - - if (!event.isCancelled()) { - event.getEntity().setLastDamageCause(event); - } - - return event; - } - - private static final Function ZERO = Functions.constant(-0.0); - - 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) { - 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); - } - - // 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) { - return handleNonLivingEntityDamageEvent(entity, source, damage, cancelOnZeroDamage, false); - } - - public static boolean handleNonLivingEntityDamageEvent(Entity entity, DamageSource source, double damage, boolean cancelOnZeroDamage, boolean cancelled) { - 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, cancelled); - - if (event == null) { - return false; - } - 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 PlayerItemMendEvent callPlayerItemMendEvent(EntityHuman entity, EntityExperienceOrb orb, net.minecraft.server.ItemStack nmsMendedItem, int repairAmount) { - Player player = (Player) entity.getBukkitEntity(); - org.bukkit.inventory.ItemStack bukkitStack = CraftItemStack.asCraftMirror(nmsMendedItem); - PlayerItemMendEvent event = new PlayerItemMendEvent(player, bukkitStack, (ExperienceOrb) orb.getBukkitEntity(), repairAmount); - Bukkit.getPluginManager().callEvent(event); - return event; - } - - // Paper start - Add orb - public static PlayerExpChangeEvent callPlayerExpChangeEvent(EntityHuman entity, EntityExperienceOrb entityOrb) { - Player player = (Player) entity.getBukkitEntity(); - ExperienceOrb source = (ExperienceOrb) entityOrb.getBukkitEntity(); - int expAmount = source.getExperience(); - PlayerExpChangeEvent event = new PlayerExpChangeEvent(player, source, expAmount); - Bukkit.getPluginManager().callEvent(event); - return event; - } - // Paper end - - public static boolean handleBlockGrowEvent(World world, BlockPosition pos, IBlockData block) { - return handleBlockGrowEvent(world, pos, block, 3); - } - - public static boolean handleBlockGrowEvent(World world, BlockPosition pos, IBlockData newData, int flag) { - Block block = world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); - CraftBlockState state = (CraftBlockState) block.getState(); - state.setData(newData); - - BlockGrowEvent event = new BlockGrowEvent(block, state); - Bukkit.getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - state.update(true); - } - - return !event.isCancelled(); - } - - public static FluidLevelChangeEvent callFluidLevelChangeEvent(World world, BlockPosition block, IBlockData newData) { - FluidLevelChangeEvent event = new FluidLevelChangeEvent(CraftBlock.at(world, block), CraftBlockData.fromData(newData)); - world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static FoodLevelChangeEvent callFoodLevelChangeEvent(EntityHuman entity, int level) { - return callFoodLevelChangeEvent(entity, level, null); - } - - public static FoodLevelChangeEvent callFoodLevelChangeEvent(EntityHuman entity, int level, ItemStack item) { - FoodLevelChangeEvent event = new FoodLevelChangeEvent(entity.getBukkitEntity(), level, (item == null) ? null : CraftItemStack.asBukkitCopy(item)); - 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; - } - - // Paper start - public static com.destroystokyo.paper.event.entity.EntityZapEvent callEntityZapEvent (Entity entity, Entity lightning, Entity changedEntity) { - com.destroystokyo.paper.event.entity.EntityZapEvent event = new com.destroystokyo.paper.event.entity.EntityZapEvent(entity.getBukkitEntity(), (LightningStrike) lightning.getBukkitEntity(), changedEntity.getBukkitEntity()); - entity.getBukkitEntity().getServer().getPluginManager().callEvent(event); - return event; - } - // Paper end - - public static HorseJumpEvent callHorseJumpEvent(Entity horse, float power) { - HorseJumpEvent event = new HorseJumpEvent((AbstractHorse) horse.getBukkitEntity(), power); - horse.getBukkitEntity().getServer().getPluginManager().callEvent(event); - return event; - } - - public static EntityChangeBlockEvent callEntityChangeBlockEvent(Entity entity, BlockPosition position, IBlockData newBlock) { - return callEntityChangeBlockEvent(entity, position, newBlock, false); - } - - public static EntityChangeBlockEvent callEntityChangeBlockEvent(Entity entity, BlockPosition position, IBlockData newBlock, boolean cancelled) { - Block block = entity.world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()); - - EntityChangeBlockEvent event = new EntityChangeBlockEvent(entity.getBukkitEntity(), block, CraftBlockData.fromData(newBlock)); - event.setCancelled(cancelled); - event.getEntity().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(), (target == null) ? null : (LivingEntity) target.getBukkitEntity(), reason); - entity.getBukkitEntity().getServer().getPluginManager().callEvent(event); - return event; - } - - public static EntityBreakDoorEvent callEntityBreakDoorEvent(Entity entity, BlockPosition pos) { - org.bukkit.entity.Entity entity1 = entity.getBukkitEntity(); - Block block = CraftBlock.at(entity.world, pos); - - 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(IInventory matrix, IInventory resultInventory, ItemStack result, InventoryView lastCraftView, boolean isRepair) { - CraftInventoryCrafting inventory = new CraftInventoryCrafting(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); - } - - // Paper start - public static com.destroystokyo.paper.event.entity.ProjectileCollideEvent callProjectileCollideEvent(Entity entity, MovingObjectPositionEntity position) { - Projectile projectile = (Projectile) entity.getBukkitEntity(); - org.bukkit.entity.Entity collided = position.getEntity().getBukkitEntity(); - com.destroystokyo.paper.event.entity.ProjectileCollideEvent event = new com.destroystokyo.paper.event.entity.ProjectileCollideEvent(projectile, collided); - - if (projectile.getShooter() instanceof Player && collided instanceof Player) { - if (!((Player) projectile.getShooter()).canSee((Player) collided)) { - event.setCancelled(true); - return event; - } - } - - Bukkit.getPluginManager().callEvent(event); - return event; - } - // Paper end - - public static ProjectileLaunchEvent callProjectileLaunchEvent(Entity entity) { - Projectile bukkitEntity = (Projectile) entity.getBukkitEntity(); - ProjectileLaunchEvent event = new ProjectileLaunchEvent(bukkitEntity); - Bukkit.getPluginManager().callEvent(event); - return event; - } - - public static void callProjectileHitEvent(Entity entity, MovingObjectPosition position) { - if (position.getType() == MovingObjectPosition.EnumMovingObjectType.MISS) { - return; - } - - Block hitBlock = null; - BlockFace hitFace = null; - if (position.getType() == MovingObjectPosition.EnumMovingObjectType.BLOCK) { - MovingObjectPositionBlock positionBlock = (MovingObjectPositionBlock) position; - hitBlock = CraftBlock.at(entity.world, positionBlock.getBlockPosition()); - hitFace = CraftBlock.notchToBlockFace(positionBlock.getDirection()); - } - - org.bukkit.entity.Entity hitEntity = null; - if (position.getType() == MovingObjectPosition.EnumMovingObjectType.ENTITY) { - hitEntity = ((MovingObjectPositionEntity) position).getEntity().getBukkitEntity(); - } - - ProjectileHitEvent event = new ProjectileHitEvent((Projectile) entity.getBukkitEntity(), hitEntity, hitBlock, hitFace); - entity.world.getServer().getPluginManager().callEvent(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, BlockPosition pos, int oldCurrent, int newCurrent) { - BlockRedstoneEvent event = new BlockRedstoneEvent(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), oldCurrent, newCurrent); - world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static NotePlayEvent callNotePlayEvent(World world, BlockPosition pos, BlockPropertyInstrument instrument, int note) { - NotePlayEvent event = new NotePlayEvent(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), org.bukkit.Instrument.getByType((byte) instrument.ordinal()), 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, BlockPosition block, BlockPosition source) { - org.bukkit.World bukkitWorld = world.getWorld(); - Block igniter = bukkitWorld.getBlockAt(source.getX(), source.getY(), source.getZ()); - IgniteCause cause; - switch (igniter.getType()) { - case 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(block.getX(), block.getY(), block.getZ()), cause, igniter); - world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static BlockIgniteEvent callBlockIgniteEvent(World world, BlockPosition pos, 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; - case ARROW: - cause = IgniteCause.ARROW; - break; - default: - cause = IgniteCause.FLINT_AND_STEEL; - } - - BlockIgniteEvent event = new BlockIgniteEvent(bukkitWorld.getBlockAt(pos.getX(), pos.getY(), pos.getZ()), cause, bukkitIgniter); - world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static BlockIgniteEvent callBlockIgniteEvent(World world, 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(bukkitWorld.getBlockAt(x, y, z), IgniteCause.EXPLOSION, igniter); - world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static BlockIgniteEvent callBlockIgniteEvent(World world, BlockPosition pos, IgniteCause cause, Entity igniter) { - BlockIgniteEvent event = new BlockIgniteEvent(world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), cause, igniter.getBukkitEntity()); - world.getServer().getPluginManager().callEvent(event); - return event; - } - - // Paper start - - /** - * Incase plugins hooked into this or Spigot adds a new inventory close event. Prefer to pass a reason - * @param human - */ - @Deprecated - public static void handleInventoryCloseEvent(EntityHuman human) { - handleInventoryCloseEvent(human, org.bukkit.event.inventory.InventoryCloseEvent.Reason.UNKNOWN); - } - public static void handleInventoryCloseEvent(EntityHuman human, org.bukkit.event.inventory.InventoryCloseEvent.Reason reason) { - InventoryCloseEvent event = new InventoryCloseEvent(human.activeContainer.getBukkitView(), reason); - // Paper end - human.world.getServer().getPluginManager().callEvent(event); - human.activeContainer.transferTo(human.defaultContainer, human.getBukkitEntity()); - } - - public static ItemStack handleEditBookEvent(EntityPlayer player, EnumItemSlot slot, ItemStack itemInHand, ItemStack newBookItem) { - int itemInHandIndex = (slot == EnumItemSlot.MAINHAND) ? player.inventory.itemInHandIndex : -1; - - PlayerEditBookEvent editBookEvent = new PlayerEditBookEvent(player.getBukkitEntity(), itemInHandIndex, (BookMeta) CraftItemStack.getItemMeta(itemInHand), (BookMeta) CraftItemStack.getItemMeta(newBookItem), newBookItem.getItem() == Items.WRITTEN_BOOK); - player.world.getServer().getPluginManager().callEvent(editBookEvent); - - // 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); - } - } - - return 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.getArgs(); - for (int i = 0; i < oo.length; i++) { - Object o = oo[i]; - if (o instanceof IChatBaseComponent) { - oo[i] = stripEvents((IChatBaseComponent) o); - } - } - } - List ls = c.getSiblings(); - 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 BlockShearEntityEvent callBlockShearEntityEvent(EntitySheep animal, org.bukkit.block.Block dispenser, CraftItemStack is) { - Sheep sheep = (Sheep) animal.getBukkitEntity(); - BlockShearEntityEvent bse = new BlockShearEntityEvent(dispenser, sheep, is); - Bukkit.getPluginManager().callEvent(bse); - return bse; - } - - public static Cancellable handleStatisticsIncrease(EntityHuman entityHuman, net.minecraft.server.Statistic statistic, int current, int incrementation) { - Player player = ((EntityPlayer) entityHuman).getBukkitEntity(); - Event event; - if (true) { - 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 WALK_ON_WATER_ONE_CM: - case WALK_UNDER_WATER_ONE_CM: - case FLY_ONE_CM: - case HORSE_ONE_CM: - case MINECART_ONE_CM: - case PIG_ONE_CM: - case PLAY_ONE_MINUTE: - case SWIM_ONE_CM: - case WALK_ONE_CM: - case SPRINT_ONE_CM: - case CROUCH_ONE_CM: - case TIME_SINCE_DEATH: - case SNEAK_TIME: - // 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((net.minecraft.server.Statistic>) 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; - } - - public static PrepareAnvilEvent callPrepareAnvilEvent(InventoryView view, ItemStack item) { - PrepareAnvilEvent event = new PrepareAnvilEvent(view, CraftItemStack.asCraftMirror(item).clone()); - event.getView().getPlayer().getServer().getPluginManager().callEvent(event); - event.getInventory().setItem(2, event.getResult()); - return event; - } - - /** - * Mob spawner event. - */ - public static SpawnerSpawnEvent callSpawnerSpawnEvent(Entity spawnee, BlockPosition pos) { - org.bukkit.craftbukkit.entity.CraftEntity entity = spawnee.getBukkitEntity(); - BlockState state = entity.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()).getState(); - if (!(state instanceof org.bukkit.block.CreatureSpawner)) { - state = null; - } - - SpawnerSpawnEvent event = new SpawnerSpawnEvent(entity, (org.bukkit.block.CreatureSpawner) state); - entity.getServer().getPluginManager().callEvent(event); - return event; - } - - public static EntityToggleGlideEvent callToggleGlideEvent(EntityLiving entity, boolean gliding) { - EntityToggleGlideEvent event = new EntityToggleGlideEvent((LivingEntity) entity.getBukkitEntity(), gliding); - entity.world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static EntityToggleSwimEvent callToggleSwimEvent(EntityLiving entity, boolean swimming) { - EntityToggleSwimEvent event = new EntityToggleSwimEvent((LivingEntity) entity.getBukkitEntity(), swimming); - entity.world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static AreaEffectCloudApplyEvent callAreaEffectCloudApplyEvent(EntityAreaEffectCloud cloud, List entities) { - AreaEffectCloudApplyEvent event = new AreaEffectCloudApplyEvent((AreaEffectCloud) cloud.getBukkitEntity(), entities); - cloud.world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static VehicleCreateEvent callVehicleCreateEvent(Entity entity) { - Vehicle bukkitEntity = (Vehicle) entity.getBukkitEntity(); - VehicleCreateEvent event = new VehicleCreateEvent(bukkitEntity); - Bukkit.getPluginManager().callEvent(event); - return event; - } - - public static EntityBreedEvent callEntityBreedEvent(EntityLiving child, EntityLiving mother, EntityLiving father, EntityLiving breeder, ItemStack bredWith, int experience) { - org.bukkit.entity.LivingEntity breederEntity = (LivingEntity) (breeder == null ? null : breeder.getBukkitEntity()); - CraftItemStack bredWithStack = bredWith == null ? null : CraftItemStack.asCraftMirror(bredWith).clone(); - - EntityBreedEvent event = new EntityBreedEvent((LivingEntity) child.getBukkitEntity(), (LivingEntity) mother.getBukkitEntity(), (LivingEntity) father.getBukkitEntity(), breederEntity, bredWithStack, experience); - child.world.getServer().getPluginManager().callEvent(event); - return event; - } - - public static BlockPhysicsEvent callBlockPhysicsEvent(GeneratorAccess world, BlockPosition blockposition) { - org.bukkit.block.Block block = CraftBlock.at(world, blockposition); - BlockPhysicsEvent event = new BlockPhysicsEvent(block, block.getBlockData()); - // Suppress during worldgen - if (world instanceof World) { - world.getMinecraftWorld().getMinecraftServer().server.getPluginManager().callEvent(event); - } - return event; - } - - public static boolean handleBlockFormEvent(World world, BlockPosition pos, IBlockData block) { - return handleBlockFormEvent(world, pos, block, 3); - } - - public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(EntityLiving entity, @Nullable MobEffect oldEffect, @Nullable MobEffect newEffect, EntityPotionEffectEvent.Cause cause) { - return callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, true); - } - - public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(EntityLiving entity, @Nullable MobEffect oldEffect, @Nullable MobEffect newEffect, EntityPotionEffectEvent.Cause cause, EntityPotionEffectEvent.Action action) { - return callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, action, true); - } - - public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(EntityLiving entity, @Nullable MobEffect oldEffect, @Nullable MobEffect newEffect, EntityPotionEffectEvent.Cause cause, boolean willOverride) { - EntityPotionEffectEvent.Action action = EntityPotionEffectEvent.Action.CHANGED; - if (oldEffect == null) { - action = EntityPotionEffectEvent.Action.ADDED; - } else if (newEffect == null) { - action = EntityPotionEffectEvent.Action.REMOVED; - } - - return callEntityPotionEffectChangeEvent(entity, oldEffect, newEffect, cause, action, willOverride); - } - - public static EntityPotionEffectEvent callEntityPotionEffectChangeEvent(EntityLiving entity, @Nullable MobEffect oldEffect, @Nullable MobEffect newEffect, EntityPotionEffectEvent.Cause cause, EntityPotionEffectEvent.Action action, boolean willOverride) { - PotionEffect bukkitOldEffect = (oldEffect == null) ? null : CraftPotionUtil.toBukkit(oldEffect); - PotionEffect bukkitNewEffect = (newEffect == null) ? null : CraftPotionUtil.toBukkit(newEffect); - - if (bukkitOldEffect == null && bukkitNewEffect == null) { - throw new IllegalStateException("Old and new potion effect are both null"); - } - - EntityPotionEffectEvent event = new EntityPotionEffectEvent((LivingEntity) entity.getBukkitEntity(), bukkitOldEffect, bukkitNewEffect, cause, action, willOverride); - Bukkit.getPluginManager().callEvent(event); - - return event; - } - - public static boolean handleBlockFormEvent(World world, BlockPosition pos, IBlockData block, @Nullable Entity entity) { - return handleBlockFormEvent(world, pos, block, 3, entity); - } - - public static boolean handleBlockFormEvent(World world, BlockPosition pos, IBlockData block, int flag) { - return handleBlockFormEvent(world, pos, block, flag, null); - } - - public static boolean handleBlockFormEvent(World world, BlockPosition pos, IBlockData block, int flag, @Nullable Entity entity) { - CraftBlockState blockState = CraftBlockState.getBlockState(world, pos, flag); - blockState.setData(block); - - BlockFormEvent event = (entity == null) ? new BlockFormEvent(blockState.getBlock(), blockState) : new EntityBlockFormEvent(entity.getBukkitEntity(), blockState.getBlock(), blockState); - world.getServer().getPluginManager().callEvent(event); - - if (!event.isCancelled()) { - blockState.update(true); - } - - return !event.isCancelled(); - } - - public static boolean handleBatToggleSleepEvent(Entity bat, boolean awake) { - BatToggleSleepEvent event = new BatToggleSleepEvent((Bat) bat.getBukkitEntity(), awake); - Bukkit.getPluginManager().callEvent(event); - return !event.isCancelled(); - } - - public static boolean handlePlayerRecipeListUpdateEvent(EntityHuman who, MinecraftKey recipe) { - PlayerRecipeDiscoverEvent event = new PlayerRecipeDiscoverEvent((Player) who.getBukkitEntity(), CraftNamespacedKey.fromMinecraft(recipe)); - Bukkit.getPluginManager().callEvent(event); - return !event.isCancelled(); - } - - public static EntityPickupItemEvent callEntityPickupItemEvent(Entity who, EntityItem item, int remaining, boolean cancelled) { - EntityPickupItemEvent event = new EntityPickupItemEvent((LivingEntity) who.getBukkitEntity(), (Item) item.getBukkitEntity(), remaining); - event.setCancelled(cancelled); - Bukkit.getPluginManager().callEvent(event); - return event; - } - - /** - * Raid events - */ - public static boolean callRaidTriggerEvent(Raid raid, EntityPlayer player) { - RaidTriggerEvent event = new RaidTriggerEvent(new CraftRaid(raid), raid.i().getWorld(), player.getBukkitEntity()); - Bukkit.getPluginManager().callEvent(event); - return !event.isCancelled(); - } - - public static void callRaidFinishEvent(Raid raid, List players) { - RaidFinishEvent event = new RaidFinishEvent(new CraftRaid(raid), raid.i().getWorld(), players); - Bukkit.getPluginManager().callEvent(event); - } - - public static void callRaidStopEvent(Raid raid, RaidStopEvent.Reason reason) { - RaidStopEvent event = new RaidStopEvent(new CraftRaid(raid), raid.i().getWorld(), reason); - Bukkit.getPluginManager().callEvent(event); - } - - public static void callRaidSpawnWaveEvent(Raid raid, EntityRaider leader, List raiders) { - Raider craftLeader = (CraftRaider) leader.getBukkitEntity(); - List craftRaiders = new ArrayList<>(); - for (EntityRaider entityRaider : raiders) { - craftRaiders.add((Raider) entityRaider.getBukkitEntity()); - } - RaidSpawnWaveEvent event = new RaidSpawnWaveEvent(new CraftRaid(raid), raid.i().getWorld(), craftLeader, craftRaiders); - Bukkit.getPluginManager().callEvent(event); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java b/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java deleted file mode 100644 index 4570ed999..000000000 --- a/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.bukkit.craftbukkit.generator; - -import java.util.HashSet; -import java.util.Set; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.Blocks; -import net.minecraft.server.ChunkSection; -import net.minecraft.server.IBlockData; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.material.MaterialData; - -/** - * 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 ChunkSection[] sections; - private Set tiles; - private World world; // Paper - Anti-Xray - - public CraftChunkData(World world) { - this(world.getMaxHeight()); - this.world = world; // Paper - Anti-Xray - } - - /* pp for tests */ CraftChunkData(int maxHeight) { - if (maxHeight > 256) { - throw new IllegalArgumentException("World height exceeded max chunk height"); - } - this.maxHeight = maxHeight; - sections = new ChunkSection[maxHeight >> 4]; - } - - @Override - public int getMaxHeight() { - return maxHeight; - } - - @Override - public void setBlock(int x, int y, int z, Material material) { - setBlock(x, y, z, material.createBlockData()); - } - - @Override - public void setBlock(int x, int y, int z, MaterialData material) { - setBlock(x, y, z, CraftMagicNumbers.getBlock(material)); - } - - @Override - public void setBlock(int x, int y, int z, BlockData blockData) { - setBlock(x, y, z, ((CraftBlockData) blockData).getState()); - } - - @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.createBlockData()); - } - - @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, CraftMagicNumbers.getBlock(material)); - } - - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockData blockData) { - setRegion(xMin, yMin, zMin, xMax, yMax, zMax, ((CraftBlockData) blockData).getState()); - } - - @Override - public Material getType(int x, int y, int z) { - return CraftMagicNumbers.getMaterial(getTypeId(x, y, z).getBlock()); - } - - @Override - public MaterialData getTypeAndData(int x, int y, int z) { - return CraftMagicNumbers.getMaterial(getTypeId(x, y, z)); - } - - @Override - public BlockData getBlockData(int x, int y, int z) { - return CraftBlockData.fromData(getTypeId(x, y, z)); - } - - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, IBlockData type) { - // 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; - } - for (int y = yMin; y < yMax; y++) { - ChunkSection section = getChunkSection(y, true); - int offsetBase = y & 0xf; - for (int x = xMin; x < xMax; x++) { - for (int z = zMin; z < zMax; z++) { - section.setType(x, offsetBase, z, type); - } - } - } - } - - public IBlockData getTypeId(int x, int y, int z) { - if (x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) { - return Blocks.AIR.getBlockData(); - } - ChunkSection section = getChunkSection(y, false); - if (section == null) { - return Blocks.AIR.getBlockData(); - } else { - return section.getType(x, y & 0xf, z); - } - } - - @Override - public byte getData(int x, int y, int z) { - return CraftMagicNumbers.toLegacyData(getTypeId(x, y, z)); - } - - private void setBlock(int x, int y, int z, IBlockData type) { - if (x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) { - return; - } - ChunkSection section = getChunkSection(y, true); - section.setType(x, y & 0xf, z, type); - - if (type.getBlock().isTileEntity()) { - if (tiles == null) { - tiles = new HashSet<>(); - } - - tiles.add(new BlockPosition(x, y, z)); - } - } - - private ChunkSection getChunkSection(int y, boolean create) { - ChunkSection section = sections[y >> 4]; - if (create && section == null) { - sections[y >> 4] = section = new ChunkSection(y, null, world instanceof org.bukkit.craftbukkit.CraftWorld ? ((org.bukkit.craftbukkit.CraftWorld) world).getHandle() : null, true); // Paper - Anti-Xray - } - return section; - } - - ChunkSection[] getRawChunkData() { - return sections; - } - - Set getTiles() { - return tiles; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java b/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java deleted file mode 100644 index 68d38655f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java +++ /dev/null @@ -1,193 +0,0 @@ -package org.bukkit.craftbukkit.generator; - -import com.google.common.base.Preconditions; -import java.util.List; -import java.util.Random; -import net.minecraft.server.BiomeBase; -import net.minecraft.server.Block; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.ChunkSection; -import net.minecraft.server.EnumCreatureType; -import net.minecraft.server.GeneratorAccess; -import net.minecraft.server.GeneratorSettingsDefault; -import net.minecraft.server.HeightMap; -import net.minecraft.server.IChunkAccess; -import net.minecraft.server.ITileEntity; -import net.minecraft.server.MobSpawnerCat; -import net.minecraft.server.MobSpawnerPatrol; -import net.minecraft.server.MobSpawnerPhantom; -import net.minecraft.server.RegionLimitedWorldAccess; -import net.minecraft.server.StructureGenerator; -import net.minecraft.server.TileEntity; -import net.minecraft.server.VillageSiege; -import net.minecraft.server.World; -import net.minecraft.server.WorldGenFeatureConfiguration; -import net.minecraft.server.WorldGenStage; -import net.minecraft.server.WorldGenerator; -import net.minecraft.server.WorldServer; -import org.bukkit.block.Biome; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.generator.ChunkGenerator.BiomeGrid; -import org.bukkit.generator.ChunkGenerator.ChunkData; - -public class CustomChunkGenerator extends InternalChunkGenerator { - private final ChunkGenerator generator; - private final WorldServer world; - private final long seed; - private final Random random; - private final StructureGenerator strongholdGen = WorldGenerator.STRONGHOLD; - private final MobSpawnerPhantom mobSpawnerPhantom = new MobSpawnerPhantom(); - private final MobSpawnerPatrol mobSpawnerPatrol = new MobSpawnerPatrol(); - private final MobSpawnerCat mobSpawnerCat = new MobSpawnerCat(); - private final VillageSiege villageSiege = new VillageSiege(); - - private static class CustomBiomeGrid implements BiomeGrid { - BiomeBase[] biome; - - @Override - public Biome getBiome(int x, int z) { - return CraftBlock.biomeBaseToBiome(biome[(z << 4) | x]); - } - - @Override - public void setBiome(int x, int z, Biome bio) { - biome[(z << 4) | x] = CraftBlock.biomeToBiomeBase(bio); - } - } - - public CustomChunkGenerator(World world, long seed, ChunkGenerator generator) { - super(world, world.worldProvider.getChunkGenerator().getWorldChunkManager(), new GeneratorSettingsDefault()); - this.world = (WorldServer) world; - this.generator = generator; - this.seed = seed; - - this.random = new Random(seed); - } - - @Override - public void buildBase(IChunkAccess ichunkaccess) { - int x = ichunkaccess.getPos().x; - int z = ichunkaccess.getPos().z; - random.setSeed((long) x * 341873128712L + (long) z * 132897987541L); - - // Get default biome data for chunk - CustomBiomeGrid biomegrid = new CustomBiomeGrid(); - biomegrid.biome = this.getWorldChunkManager().getBiomeBlock(x << 4, z << 4, 16, 16); - - ChunkData data; - if (generator.isParallelCapable()) { - data = generator.generateChunkData(this.world.getWorld(), random, x, z, biomegrid); - } else { - synchronized (this) { - data = generator.generateChunkData(this.world.getWorld(), random, x, z, biomegrid); - } - } - - Preconditions.checkArgument(data instanceof CraftChunkData, "Plugins must use createChunkData(World) rather than implementing ChunkData: %s", data); - CraftChunkData craftData = (CraftChunkData) data; - ChunkSection[] sections = craftData.getRawChunkData(); - - ChunkSection[] csect = ichunkaccess.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; - } - ChunkSection section = sections[sec]; - - csect[sec] = section; - } - - // Set biome grid - ichunkaccess.a(biomegrid.biome); - - if (craftData.getTiles() != null) { - for (BlockPosition pos : craftData.getTiles()) { - int tx = pos.getX(); - int ty = pos.getY(); - int tz = pos.getZ(); - Block block = craftData.getTypeId(tx, ty, tz).getBlock(); - - if (block.isTileEntity()) { - TileEntity tile = ((ITileEntity) block).createTile(world); - ichunkaccess.setTileEntity(new BlockPosition((x << 4) + tx, ty, (z << 4) + tz), tile); - } - } - } - } - - @Override - public void doCarving(IChunkAccess ichunkaccess, WorldGenStage.Features worldgenstage_features) { - } - - @Override - public void buildNoise(GeneratorAccess generatoraccess, IChunkAccess ichunkaccess) { - } - - @Override - public int getBaseHeight(int i, int j, HeightMap.Type heightmap_type) { - return 0; - } - - @Override - public List getMobsFor(EnumCreatureType type, BlockPosition position) { - BiomeBase biomebase = world.getBiome(position); - - return biomebase == null ? null : biomebase.getMobs(type); - } - - @Override - public void addDecorations(RegionLimitedWorldAccess regionlimitedworldaccess) { - } - - @Override - public void addMobs(RegionLimitedWorldAccess regionlimitedworldaccess) { - } - - @Override - public BlockPosition findNearestMapFeature(World world, String type, BlockPosition position, int i, boolean flag) { - return "Stronghold".equals(type) && this.strongholdGen != null ? this.strongholdGen.getNearestGeneratedFeature(world, this, position, i, flag) : null; - } - - @Override - public GeneratorSettingsDefault getSettings() { - return settings; - } - - @Override - public void doMobSpawning(WorldServer worldserver, boolean flag, boolean flag1) { - this.mobSpawnerPhantom.a(worldserver, flag, flag1); - this.mobSpawnerPatrol.a(worldserver, flag, flag1); - this.mobSpawnerCat.a(worldserver, flag, flag1); - this.villageSiege.a(worldserver, flag, flag1); - } - - @Override - public boolean canSpawnStructure(BiomeBase biomebase, StructureGenerator structuregenerator) { - return biomebase.a(structuregenerator); - } - - @Override - public long getSeed() { - return seed; - } - - @Override - public int getSpawnHeight() { - return world.getSeaLevel() + 1; - } - - @Override - public int getGenerationDepth() { - return world.getHeight(); - } - - // Spigot start - public WorldServer getWorld() { - return world; - } - // Spigot end -} diff --git a/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java b/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java deleted file mode 100644 index d98b1be39..000000000 --- a/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.bukkit.craftbukkit.generator; - -import net.minecraft.server.GeneratorAccess; -import net.minecraft.server.GeneratorSettingsDefault; -import net.minecraft.server.WorldChunkManager; - -// Do not implement functions to this class, add to NormalChunkGenerator -public abstract class InternalChunkGenerator extends net.minecraft.server.ChunkGenerator { - - public InternalChunkGenerator(GeneratorAccess generatorAccess, WorldChunkManager worldChunkManager, C c0) { - super(generatorAccess, worldChunkManager, c0); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java b/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java deleted file mode 100644 index 9f2238c9a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java +++ /dev/null @@ -1,46 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java b/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java deleted file mode 100644 index 78b91bb2b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java +++ /dev/null @@ -1,32 +0,0 @@ -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; - } - - @Override - public boolean canSee(CommandSender sender) { - if (sender instanceof ConsoleCommandSender) { - return true; - } - - if (!permissionNode.equals("")) { - return sender.hasPermission(permissionNode); - } else { - return true; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java b/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java deleted file mode 100644 index 77134d74b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.bukkit.craftbukkit.help; - -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import org.bukkit.command.CommandSender; -import org.bukkit.help.HelpMap; -import org.bukkit.help.HelpTopic; -import org.bukkit.help.IndexHelpTopic; - -/** - */ -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/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java b/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java deleted file mode 100644 index 4f0e00ec7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java +++ /dev/null @@ -1,50 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java b/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java deleted file mode 100644 index d3f17d4cd..000000000 --- a/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.bukkit.craftbukkit.help; - -import com.google.common.base.Charsets; -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; -import org.bukkit.ChatColor; -import org.bukkit.Server; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.help.HelpTopic; - -/** - * 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/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java b/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java deleted file mode 100644 index 6133235c1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java +++ /dev/null @@ -1,55 +0,0 @@ -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(); - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopicFactory.java b/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopicFactory.java deleted file mode 100644 index de3ed3c96..000000000 --- a/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopicFactory.java +++ /dev/null @@ -1,16 +0,0 @@ -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 { - - @Override - public HelpTopic createTopic(MultipleCommandAlias multipleCommandAlias) { - return new MultipleCommandAliasHelpTopic(multipleCommandAlias); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java b/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java deleted file mode 100644 index cbf9d190a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java +++ /dev/null @@ -1,239 +0,0 @@ -package org.bukkit.craftbukkit.help; - -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Collections2; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.MultipleCommandAlias; -import org.bukkit.command.PluginCommand; -import org.bukkit.command.PluginIdentifiableCommand; -import org.bukkit.command.defaults.BukkitCommand; -import org.bukkit.craftbukkit.CraftServer; -import org.bukkit.craftbukkit.command.VanillaCommandWrapper; -import org.bukkit.help.GenericCommandHelpTopic; -import org.bukkit.help.HelpMap; -import org.bukkit.help.HelpTopic; -import org.bukkit.help.HelpTopicComparator; -import org.bukkit.help.HelpTopicFactory; -import org.bukkit.help.IndexHelpTopic; - -/** - * 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()); - } - - @Override - public synchronized HelpTopic getHelpTopic(String topicName) { - if (topicName.equals("")) { - return defaultTopic; - } - - if (helpTopics.containsKey(topicName)) { - return helpTopics.get(topicName); - } - - return null; - } - - @Override - public Collection getHelpTopics() { - return helpTopics.values(); - } - - @Override - public synchronized void addTopic(HelpTopic topic) { - // Existing topics take priority - if (!helpTopics.containsKey(topic.getName())) { - helpTopics.put(topic.getName(), topic); - } - } - - @Override - public synchronized void clear() { - helpTopics.clear(); - } - - @Override - 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) { - return "Bukkit"; - } - if (command instanceof PluginIdentifiableCommand) { - return ((PluginIdentifiableCommand)command).getPlugin().getName(); - } - return null; - } - - private boolean commandInIgnoredPlugin(Command command, Set ignoredPlugins) { - if ((command instanceof BukkitCommand) && ignoredPlugins.contains("Bukkit")) { - return true; - } - if (command instanceof PluginIdentifiableCommand && ignoredPlugins.contains(((PluginIdentifiableCommand)command).getPlugin().getName())) { - return true; - } - return false; - } - - @Override - 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 { - - @Override - public boolean apply(HelpTopic topic) { - return topic.getName().charAt(0) == '/'; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlastingRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlastingRecipe.java deleted file mode 100644 index f6e32ca09..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlastingRecipe.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.MinecraftServer; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.BlastingRecipe; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; - -public class CraftBlastingRecipe extends BlastingRecipe implements CraftRecipe { - public CraftBlastingRecipe(NamespacedKey key, ItemStack result, RecipeChoice source, float experience, int cookingTime) { - super(key, result, source, experience, cookingTime); - } - - public static CraftBlastingRecipe fromBukkitRecipe(BlastingRecipe recipe) { - if (recipe instanceof CraftBlastingRecipe) { - return (CraftBlastingRecipe) recipe; - } - CraftBlastingRecipe ret = new CraftBlastingRecipe(recipe.getKey(), recipe.getResult(), recipe.getInputChoice(), recipe.getExperience(), recipe.getCookingTime()); - ret.setGroup(recipe.getGroup()); - return ret; - } - - @Override - public void addToCraftingManager() { - ItemStack result = this.getResult(); - - MinecraftServer.getServer().getCraftingManager().addRecipe(new net.minecraft.server.RecipeBlasting(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), getExperience(), getCookingTime())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlockInventoryHolder.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlockInventoryHolder.java deleted file mode 100644 index d5149c246..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftBlockInventoryHolder.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.BlockPosition; -import net.minecraft.server.GeneratorAccess; -import net.minecraft.server.IInventory; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.inventory.BlockInventoryHolder; -import org.bukkit.inventory.Inventory; - -public class CraftBlockInventoryHolder implements BlockInventoryHolder { - - private final Block block; - private final Inventory inventory; - - public CraftBlockInventoryHolder(GeneratorAccess world, BlockPosition pos, IInventory inv) { - this.block = CraftBlock.at(world, pos); - this.inventory = new CraftInventory(inv); - } - - @Override - public Block getBlock() { - return block; - } - - @Override - public Inventory getInventory() { - return inventory; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftCampfireRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftCampfireRecipe.java deleted file mode 100644 index 5c61cf965..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftCampfireRecipe.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.MinecraftServer; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.CampfireRecipe; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; - -public class CraftCampfireRecipe extends CampfireRecipe implements CraftRecipe { - public CraftCampfireRecipe(NamespacedKey key, ItemStack result, RecipeChoice source, float experience, int cookingTime) { - super(key, result, source, experience, cookingTime); - } - - public static CraftCampfireRecipe fromBukkitRecipe(CampfireRecipe recipe) { - if (recipe instanceof CraftCampfireRecipe) { - return (CraftCampfireRecipe) recipe; - } - CraftCampfireRecipe ret = new CraftCampfireRecipe(recipe.getKey(), recipe.getResult(), recipe.getInputChoice(), recipe.getExperience(), recipe.getCookingTime()); - ret.setGroup(recipe.getGroup()); - return ret; - } - - @Override - public void addToCraftingManager() { - ItemStack result = this.getResult(); - - MinecraftServer.getServer().getCraftingManager().addRecipe(new net.minecraft.server.RecipeCampfire(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), getExperience(), getCookingTime())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java deleted file mode 100644 index ae119756b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java +++ /dev/null @@ -1,276 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.Container; -import net.minecraft.server.ContainerAnvil; -import net.minecraft.server.ContainerBeacon; -import net.minecraft.server.ContainerBlastFurnace; -import net.minecraft.server.ContainerBrewingStand; -import net.minecraft.server.ContainerCartography; -import net.minecraft.server.ContainerChest; -import net.minecraft.server.ContainerDispenser; -import net.minecraft.server.ContainerEnchantTable; -import net.minecraft.server.ContainerFurnaceFurnace; -import net.minecraft.server.ContainerGrindstone; -import net.minecraft.server.ContainerHopper; -import net.minecraft.server.ContainerLectern; -import net.minecraft.server.ContainerLoom; -import net.minecraft.server.ContainerProperties; -import net.minecraft.server.ContainerShulkerBox; -import net.minecraft.server.ContainerSmoker; -import net.minecraft.server.ContainerStonecutter; -import net.minecraft.server.ContainerWorkbench; -import net.minecraft.server.Containers; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.IInventory; -import net.minecraft.server.ItemStack; -import net.minecraft.server.PacketPlayOutOpenWindow; -import net.minecraft.server.PlayerInventory; -import net.minecraft.server.Slot; -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 Container delegate; - private final int cachedSize; - - public CraftContainer(InventoryView view, EntityHuman player, int id) { - super(getNotchInventoryType(view.getType()), id); - this.view = view; - // TODO: Do we need to check that it really is a CraftInventory? - IInventory top = ((CraftInventory) view.getTopInventory()).getInventory(); - PlayerInventory bottom = (PlayerInventory) ((CraftInventory) view.getBottomInventory()).getInventory(); - cachedType = view.getType(); - cachedTitle = view.getTitle(); - cachedSize = getSize(); - setupSlots(top, bottom, player); - } - - public CraftContainer(final Inventory inventory, final EntityHuman player, int id) { - this(new InventoryView() { - @Override - public Inventory getTopInventory() { - return inventory; - } - - @Override - public Inventory getBottomInventory() { - return getPlayer().getInventory(); - } - - @Override - public HumanEntity getPlayer() { - return player.getBukkitEntity(); - } - - @Override - public InventoryType getType() { - return inventory.getType(); - } - - @Override - public String getTitle() { - return inventory instanceof CraftInventoryCustom ? ((CraftInventoryCustom.MinecraftInventory) ((CraftInventory) inventory).getInventory()).getTitle() : inventory.getType().getDefaultTitle(); - } - }, player, 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(); - Containers type = getNotchInventoryType(cachedType); - IInventory top = ((CraftInventory) view.getTopInventory()).getInventory(); - PlayerInventory bottom = (PlayerInventory) ((CraftInventory) view.getBottomInventory()).getInventory(); - this.items.clear(); - this.slots.clear(); - if (typeChanged) { - setupSlots(top, bottom, player.getHandle()); - } - int size = getSize(); - player.getHandle().playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.windowId, type, new ChatComponentText(cachedTitle))); - player.updateInventory(); - } - return true; - } - - public static Containers getNotchInventoryType(InventoryType type) { - switch (type) { - case WORKBENCH: - return Containers.CRAFTING; - case FURNACE: - return Containers.FURNACE; - case DISPENSER: - return Containers.GENERIC_3X3; - case ENCHANTING: - return Containers.ENCHANTMENT; - case BREWING: - return Containers.BREWING_STAND; - case BEACON: - return Containers.BEACON; - case ANVIL: - return Containers.ANVIL; - case HOPPER: - return Containers.HOPPER; - case DROPPER: - return Containers.GENERIC_3X3; - case SHULKER_BOX: - return Containers.SHULKER_BOX; - case BLAST_FURNACE: - return Containers.BLAST_FURNACE; - case LECTERN: - return Containers.LECTERN; - case SMOKER: - return Containers.SMOKER; - case LOOM: - return Containers.LOOM; - case CARTOGRAPHY: - return Containers.CARTOGRAPHY; - case GRINDSTONE: - return Containers.GRINDSTONE; - case STONECUTTER: - return Containers.STONECUTTER; - default: - return Containers.GENERIC_9X3; - } - } - - private void setupSlots(IInventory top, PlayerInventory bottom, EntityHuman entityhuman) { - int windowId = -1; - switch (cachedType) { - case CREATIVE: - break; // TODO: This should be an error? - case PLAYER: - case CHEST: - case ENDER_CHEST: - case BARREL: - delegate = new ContainerChest(Containers.GENERIC_9X3, windowId, bottom, top, top.getSize() / 9); - break; - case DISPENSER: - case DROPPER: - delegate = new ContainerDispenser(windowId, bottom, top); - break; - case FURNACE: - delegate = new ContainerFurnaceFurnace(windowId, bottom, top, new ContainerProperties(4)); - break; - case CRAFTING: // TODO: This should be an error? - case WORKBENCH: - setupWorkbench(top, bottom); // SPIGOT-3812 - manually set up slots so we can use the delegated inventory and not the automatically created one - break; - case ENCHANTING: - delegate = new ContainerEnchantTable(windowId, bottom); - break; - case BREWING: - delegate = new ContainerBrewingStand(windowId, bottom, top, new ContainerProperties(2)); - break; - case HOPPER: - delegate = new ContainerHopper(windowId, bottom, top); - break; - case ANVIL: - delegate = new ContainerAnvil(windowId, bottom); - break; - case BEACON: - delegate = new ContainerBeacon(windowId, bottom); - break; - case SHULKER_BOX: - delegate = new ContainerShulkerBox(windowId, bottom, top); - break; - case BLAST_FURNACE: - delegate = new ContainerBlastFurnace(windowId, bottom, top, new ContainerProperties(4)); - break; - case LECTERN: - delegate = new ContainerLectern(windowId, top, new ContainerProperties(1), bottom); - break; - case SMOKER: - delegate = new ContainerSmoker(windowId, bottom, top, new ContainerProperties(4)); - break; - case LOOM: - delegate = new ContainerLoom(windowId, bottom); - break; - case CARTOGRAPHY: - delegate = new ContainerCartography(windowId, bottom); - break; - case GRINDSTONE: - delegate = new ContainerGrindstone(windowId, bottom); - break; - case STONECUTTER: - delegate = new ContainerStonecutter(windowId, bottom); - break; - } - - if (delegate != null) { - this.items = delegate.items; - this.slots = delegate.slots; - } - - // SPIGOT-4598 - we should still delegate the shift click handler - if (cachedType == InventoryType.WORKBENCH) { - delegate = new ContainerWorkbench(windowId, bottom); - } - } - - 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 - } - - @Override - public ItemStack shiftClick(EntityHuman entityhuman, int i) { - return (delegate != null) ? delegate.shiftClick(entityhuman, i) : super.shiftClick(entityhuman, i); - } - - @Override - public boolean canUse(EntityHuman entity) { - return true; - } - - @Override - public Containers getType() { - return getNotchInventoryType(cachedType); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java deleted file mode 100644 index 3eb2402e7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java +++ /dev/null @@ -1,212 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.EntityInsentient; -import net.minecraft.server.EnumItemSlot; -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 final CraftLivingEntity entity; - - public CraftEntityEquipment(CraftLivingEntity entity) { - this.entity = entity; - } - - @Override - public ItemStack getItemInMainHand() { - return getEquipment(EnumItemSlot.MAINHAND); - } - - @Override - public void setItemInMainHand(ItemStack item) { - setEquipment(EnumItemSlot.MAINHAND, item); - } - - @Override - public ItemStack getItemInOffHand() { - return getEquipment(EnumItemSlot.OFFHAND); - } - - @Override - public void setItemInOffHand(ItemStack item) { - setEquipment(EnumItemSlot.OFFHAND, item); - } - - @Override - public ItemStack getItemInHand() { - return getItemInMainHand(); - } - - @Override - public void setItemInHand(ItemStack stack) { - setItemInMainHand(stack); - } - - @Override - public ItemStack getHelmet() { - return getEquipment(EnumItemSlot.HEAD); - } - - @Override - public void setHelmet(ItemStack helmet) { - setEquipment(EnumItemSlot.HEAD, helmet); - } - - @Override - public ItemStack getChestplate() { - return getEquipment(EnumItemSlot.CHEST); - } - - @Override - public void setChestplate(ItemStack chestplate) { - setEquipment(EnumItemSlot.CHEST, chestplate); - } - - @Override - public ItemStack getLeggings() { - return getEquipment(EnumItemSlot.LEGS); - } - - @Override - public void setLeggings(ItemStack leggings) { - setEquipment(EnumItemSlot.LEGS, leggings); - } - - @Override - public ItemStack getBoots() { - return getEquipment(EnumItemSlot.FEET); - } - - @Override - public void setBoots(ItemStack boots) { - setEquipment(EnumItemSlot.FEET, boots); - } - - @Override - public ItemStack[] getArmorContents() { - ItemStack[] armor = new ItemStack[]{ - getEquipment(EnumItemSlot.FEET), - getEquipment(EnumItemSlot.LEGS), - getEquipment(EnumItemSlot.CHEST), - getEquipment(EnumItemSlot.HEAD), - }; - return armor; - } - - @Override - public void setArmorContents(ItemStack[] items) { - setEquipment(EnumItemSlot.FEET, items.length >= 1 ? items[0] : null); - setEquipment(EnumItemSlot.LEGS, items.length >= 2 ? items[1] : null); - setEquipment(EnumItemSlot.CHEST, items.length >= 3 ? items[2] : null); - setEquipment(EnumItemSlot.HEAD, items.length >= 4 ? items[3] : null); - } - - private ItemStack getEquipment(EnumItemSlot slot) { - return CraftItemStack.asBukkitCopy(entity.getHandle().getEquipment(slot)); - } - - private void setEquipment(EnumItemSlot slot, ItemStack stack) { - entity.getHandle().setSlot(slot, CraftItemStack.asNMSCopy(stack)); - } - - @Override - public void clear() { - for (EnumItemSlot slot : EnumItemSlot.values()) { - setEquipment(slot, null); - } - } - - @Override - public Entity getHolder() { - return entity; - } - - @Override - public float getItemInHandDropChance() { - return getItemInMainHandDropChance(); - } - - @Override - public void setItemInHandDropChance(float chance) { - setItemInMainHandDropChance(chance); - } - - @Override - public float getItemInMainHandDropChance() { - return getDropChance(EnumItemSlot.MAINHAND); - } - - @Override - public void setItemInMainHandDropChance(float chance) { - setDropChance(EnumItemSlot.MAINHAND, chance); - } - - @Override - public float getItemInOffHandDropChance() { - return getDropChance(EnumItemSlot.OFFHAND); - } - - @Override - public void setItemInOffHandDropChance(float chance) { - setDropChance(EnumItemSlot.OFFHAND, chance); - } - - @Override - public float getHelmetDropChance() { - return getDropChance(EnumItemSlot.HEAD); - } - - @Override - public void setHelmetDropChance(float chance) { - setDropChance(EnumItemSlot.HEAD, chance); - } - - @Override - public float getChestplateDropChance() { - return getDropChance(EnumItemSlot.CHEST); - } - - @Override - public void setChestplateDropChance(float chance) { - setDropChance(EnumItemSlot.CHEST, chance); - } - - @Override - public float getLeggingsDropChance() { - return getDropChance(EnumItemSlot.LEGS); - } - - @Override - public void setLeggingsDropChance(float chance) { - setDropChance(EnumItemSlot.LEGS, chance); - } - - @Override - public float getBootsDropChance() { - return getDropChance(EnumItemSlot.FEET); - } - - @Override - public void setBootsDropChance(float chance) { - setDropChance(EnumItemSlot.FEET, chance); - } - - private void setDropChance(EnumItemSlot slot, float chance) { - if (slot == EnumItemSlot.MAINHAND || slot == EnumItemSlot.OFFHAND) { - ((EntityInsentient) entity.getHandle()).dropChanceHand[slot.b()] = chance; - } else { - ((EntityInsentient) entity.getHandle()).dropChanceArmor[slot.b()] = chance; - } - } - - private float getDropChance(EnumItemSlot slot) { - if (slot == EnumItemSlot.MAINHAND || slot == EnumItemSlot.OFFHAND) { - return ((EntityInsentient) entity.getHandle()).dropChanceHand[slot.b()]; - } else { - return ((EntityInsentient) entity.getHandle()).dropChanceArmor[slot.b()]; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java deleted file mode 100644 index fddae1a78..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.MinecraftServer; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.FurnaceRecipe; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; - -public class CraftFurnaceRecipe extends FurnaceRecipe implements CraftRecipe { - public CraftFurnaceRecipe(NamespacedKey key, ItemStack result, RecipeChoice source, float experience, int cookingTime) { - super(key, result, source, experience, cookingTime); - } - - public static CraftFurnaceRecipe fromBukkitRecipe(FurnaceRecipe recipe) { - if (recipe instanceof CraftFurnaceRecipe) { - return (CraftFurnaceRecipe) recipe; - } - CraftFurnaceRecipe ret = new CraftFurnaceRecipe(recipe.getKey(), recipe.getResult(), recipe.getInputChoice(), recipe.getExperience(), recipe.getCookingTime()); - ret.setGroup(recipe.getGroup()); - return ret; - } - - @Override - public void addToCraftingManager() { - ItemStack result = this.getResult(); - - MinecraftServer.getServer().getCraftingManager().addRecipe(new net.minecraft.server.FurnaceRecipe(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), getExperience(), getCookingTime())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java deleted file mode 100644 index 026a0c399..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java +++ /dev/null @@ -1,546 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import net.minecraft.server.IHopper; -import net.minecraft.server.IInventory; -import net.minecraft.server.InventoryCrafting; -import net.minecraft.server.InventoryEnderChest; -import net.minecraft.server.InventoryMerchant; -import net.minecraft.server.PlayerInventory; -import net.minecraft.server.TileEntityBarrel; -import net.minecraft.server.TileEntityBlastFurnace; -import net.minecraft.server.TileEntityBrewingStand; -import net.minecraft.server.TileEntityDispenser; -import net.minecraft.server.TileEntityDropper; -import net.minecraft.server.TileEntityFurnace; -import net.minecraft.server.TileEntityLectern; -import net.minecraft.server.TileEntityShulkerBox; -import net.minecraft.server.TileEntitySmoker; -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.craftbukkit.util.CraftLegacy; -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; - -public class CraftInventory implements Inventory { - protected final IInventory inventory; - - public CraftInventory(IInventory inventory) { - this.inventory = inventory; - } - - public IInventory getInventory() { - return inventory; - } - - @Override - public int getSize() { - return getInventory().getSize(); - } - - @Override - public ItemStack getItem(int index) { - net.minecraft.server.ItemStack item = getInventory().getItem(index); - return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); - } - - protected ItemStack[] asCraftMirror(List mcItems) { - int size = mcItems.size(); - ItemStack[] items = new ItemStack[size]; - - for (int i = 0; i < size; i++) { - net.minecraft.server.ItemStack mcItem = mcItems.get(i); - items[i] = (mcItem.isEmpty()) ? null : CraftItemStack.asCraftMirror(mcItem); - } - - return items; - } - - @Override - public ItemStack[] getStorageContents() { - return getContents(); - } - - @Override - public void setStorageContents(ItemStack[] items) throws IllegalArgumentException { - setContents(items); - } - - @Override - public ItemStack[] getContents() { - List mcItems = getInventory().getContents(); - - return asCraftMirror(mcItems); - } - - @Override - public void setContents(ItemStack[] items) { - if (getSize() < items.length) { - throw new IllegalArgumentException("Invalid inventory size; expected " + getSize() + " or less"); - } - - for (int i = 0; i < getSize(); i++) { - if (i >= items.length) { - setItem(i, null); - } else { - setItem(i, items[i]); - } - } - } - - @Override - public void setItem(int index, ItemStack item) { - getInventory().setItem(index, CraftItemStack.asNMSCopy(item)); - } - - @Override - public boolean contains(Material material) { - Validate.notNull(material, "Material cannot be null"); - material = CraftLegacy.fromLegacy(material); - for (ItemStack item : getStorageContents()) { - if (item != null && item.getType() == material) { - return true; - } - } - return false; - } - - @Override - public boolean contains(ItemStack item) { - if (item == null) { - return false; - } - for (ItemStack i : getStorageContents()) { - if (item.equals(i)) { - return true; - } - } - return false; - } - - @Override - public boolean contains(Material material, int amount) { - Validate.notNull(material, "Material cannot be null"); - material = CraftLegacy.fromLegacy(material); - if (amount <= 0) { - return true; - } - for (ItemStack item : getStorageContents()) { - if (item != null && item.getType()== material) { - if ((amount -= item.getAmount()) <= 0) { - return true; - } - } - } - return false; - } - - @Override - public boolean contains(ItemStack item, int amount) { - if (item == null) { - return false; - } - if (amount <= 0) { - return true; - } - for (ItemStack i : getStorageContents()) { - if (item.equals(i) && --amount <= 0) { - return true; - } - } - return false; - } - - @Override - public boolean containsAtLeast(ItemStack item, int amount) { - if (item == null) { - return false; - } - if (amount <= 0) { - return true; - } - for (ItemStack i : getStorageContents()) { - if (item.isSimilar(i) && (amount -= i.getAmount()) <= 0) { - return true; - } - } - return false; - } - - @Override - public HashMap all(Material material) { - Validate.notNull(material, "Material cannot be null"); - material = CraftLegacy.fromLegacy(material); - HashMap slots = new HashMap(); - - ItemStack[] inventory = getStorageContents(); - for (int i = 0; i < inventory.length; i++) { - ItemStack item = inventory[i]; - if (item != null && item.getType()== material) { - slots.put(i, item); - } - } - return slots; - } - - @Override - public HashMap all(ItemStack item) { - HashMap slots = new HashMap(); - if (item != null) { - ItemStack[] inventory = getStorageContents(); - for (int i = 0; i < inventory.length; i++) { - if (item.equals(inventory[i])) { - slots.put(i, inventory[i]); - } - } - } - return slots; - } - - @Override - public int first(Material material) { - Validate.notNull(material, "Material cannot be null"); - material = CraftLegacy.fromLegacy(material); - ItemStack[] inventory = getStorageContents(); - for (int i = 0; i < inventory.length; i++) { - ItemStack item = inventory[i]; - if (item != null && item.getType()== material) { - return i; - } - } - return -1; - } - - @Override - public int first(ItemStack item) { - return first(item, true); - } - - private int first(ItemStack item, boolean withAmount) { - // Paper start - return first(item, withAmount, getStorageContents()); - } - - private int first(ItemStack item, boolean withAmount, ItemStack[] inventory) { - // Paper end - if (item == null) { - return -1; - } - //ItemStack[] inventory = getStorageContents(); // Paper - let param deal - 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; - } - - @Override - public int firstEmpty() { - ItemStack[] inventory = getStorageContents(); - for (int i = 0; i < inventory.length; i++) { - if (inventory[i] == null) { - return i; - } - } - return -1; - } - - public int firstPartial(Material material) { - Validate.notNull(material, "Material cannot be null"); - material = CraftLegacy.fromLegacy(material); - ItemStack[] inventory = getStorageContents(); - for (int i = 0; i < inventory.length; i++) { - ItemStack item = inventory[i]; - if (item != null && item.getType()== material && item.getAmount() < item.getMaxStackSize()) { - return i; - } - } - return -1; - } - - private int firstPartial(ItemStack item) { - ItemStack[] inventory = getStorageContents(); - 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; - } - - @Override - 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; - } - - @Override - public HashMap removeItem(ItemStack... items) { - // Paper start - return removeItem(false, items); - } - - @Override - public HashMap removeItemAnySlot(ItemStack... items) { - return removeItem(true, items); - } - - private HashMap removeItem(boolean searchEntire, ItemStack... items) { - // Paper end - 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) { - // Paper start - Allow searching entire contents - ItemStack[] toSearch = searchEntire ? getContents() : getStorageContents(); - int first = first(item, false, toSearch); - // Paper end - - // 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(); - } - - @Override - public void remove(Material material) { - Validate.notNull(material, "Material cannot be null"); - material = CraftLegacy.fromLegacy(material); - ItemStack[] items = getStorageContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].getType()== material) { - clear(i); - } - } - } - - @Override - public void remove(ItemStack item) { - ItemStack[] items = getStorageContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].equals(item)) { - clear(i); - } - } - } - - @Override - public void clear(int index) { - setItem(index, null); - } - - @Override - public void clear() { - for (int i = 0; i < getSize(); i++) { - clear(i); - } - } - - @Override - public ListIterator iterator() { - return new InventoryIterator(this); - } - - @Override - 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); - } - - @Override - public List getViewers() { - return this.inventory.getViewers(); - } - - @Override - public InventoryType getType() { - // Thanks to Droppers extending Dispensers, Blast Furnaces & Smokers extending Furnace, 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 TileEntityBlastFurnace) { - return InventoryType.BLAST_FURNACE; - } else if (inventory instanceof TileEntitySmoker) { - return InventoryType.SMOKER; - } 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 (this instanceof CraftInventoryBeacon) { - return InventoryType.BEACON; - } else if (this instanceof CraftInventoryAnvil) { - return InventoryType.ANVIL; - } else if (inventory instanceof IHopper) { - return InventoryType.HOPPER; - } else if (inventory instanceof TileEntityShulkerBox) { - return InventoryType.SHULKER_BOX; - } else if (inventory instanceof TileEntityBarrel) { - return InventoryType.BARREL; - } else if (inventory instanceof TileEntityLectern.LecternInventory) { - return InventoryType.LECTERN; - } else if (this instanceof CraftInventoryLoom) { - return InventoryType.LOOM; - } else if (this instanceof CraftInventoryCartography) { - return InventoryType.CARTOGRAPHY; - } else if (this instanceof CraftInventoryGrindstone) { - return InventoryType.GRINDSTONE; - } else if (this instanceof CraftInventoryStonecutter) { - return InventoryType.STONECUTTER; - } else { - return InventoryType.CHEST; - } - } - - @Override - public InventoryHolder getHolder() { - return inventory.getOwner(); - } - - @Override - public int getMaxStackSize() { - return inventory.getMaxStackSize(); - } - - @Override - 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); - } - - @Override - public Location getLocation() { - return inventory.getLocation(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAbstractHorse.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAbstractHorse.java deleted file mode 100644 index b7793caa2..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAbstractHorse.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.AbstractHorseInventory; -import org.bukkit.inventory.ItemStack; - -public class CraftInventoryAbstractHorse extends CraftInventory implements AbstractHorseInventory { - - public CraftInventoryAbstractHorse(IInventory inventory) { - super(inventory); - } - - @Override - public ItemStack getSaddle() { - return getItem(0); - } - - @Override - public void setSaddle(ItemStack stack) { - setItem(0, stack); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java deleted file mode 100644 index 9374c2706..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.base.Preconditions; -import net.minecraft.server.ContainerAnvil; -import net.minecraft.server.IInventory; -import org.bukkit.Location; -import org.bukkit.inventory.AnvilInventory; - -public class CraftInventoryAnvil extends CraftResultInventory implements AnvilInventory { - - private final Location location; - private final ContainerAnvil container; - - public CraftInventoryAnvil(Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { - super(inventory, resultInventory); - this.location = location; - this.container = container; - } - - @Override - public Location getLocation() { - return location; - } - - @Override - public String getRenameText() { - return container.renameText; - } - - @Override - public int getRepairCost() { - return container.levelCost.get(); - } - - @Override - public void setRepairCost(int i) { - container.levelCost.set(i); - } - - @Override - public int getMaximumRepairCost() { - return container.maximumRepairCost; - } - - @Override - public void setMaximumRepairCost(int levels) { - Preconditions.checkArgument(levels >= 0, "Maximum repair cost must be positive (or 0)"); - container.maximumRepairCost = levels; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java deleted file mode 100644 index 163c572ca..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.BeaconInventory; -import org.bukkit.inventory.ItemStack; - -public class CraftInventoryBeacon extends CraftInventory implements BeaconInventory { - public CraftInventoryBeacon(IInventory beacon) { - super(beacon); - } - - @Override - public void setItem(ItemStack item) { - setItem(0, item); - } - - @Override - public ItemStack getItem() { - return getItem(0); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java deleted file mode 100644 index 5fa833041..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java +++ /dev/null @@ -1,37 +0,0 @@ -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); - } - - @Override - public ItemStack getIngredient() { - return getItem(3); - } - - @Override - public void setIngredient(ItemStack ingredient) { - setItem(3, ingredient); - } - - @Override - public BrewingStand getHolder() { - return (BrewingStand) inventory.getOwner(); - } - - @Override - public ItemStack getFuel() { - return getItem(4); - } - - @Override - public void setFuel(ItemStack fuel) { - setItem(4, fuel); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCartography.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCartography.java deleted file mode 100644 index 9458de90e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCartography.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.CartographyInventory; - -public class CraftInventoryCartography extends CraftResultInventory implements CartographyInventory { - - public CraftInventoryCartography(IInventory inventory, IInventory resultInventory) { - super(inventory, resultInventory); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java deleted file mode 100644 index 25eff35e0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; -import net.minecraft.server.IInventory; -import net.minecraft.server.IRecipe; -import org.bukkit.inventory.CraftingInventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Recipe; - -public class CraftInventoryCrafting extends CraftInventory implements CraftingInventory { - private final IInventory resultInventory; - - public CraftInventoryCrafting(IInventory 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) { - if (getSize() > items.length) { - throw new IllegalArgumentException("Invalid inventory size; expected " + getSize() + " or less"); - } - setContents(items[0], Arrays.copyOfRange(items, 1, items.length)); - } - - @Override - public ItemStack[] getContents() { - ItemStack[] items = new ItemStack[getSize()]; - List mcResultItems = getResultInventory().getContents(); - - int i = 0; - for (i = 0; i < mcResultItems.size(); i++ ) { - items[i] = CraftItemStack.asCraftMirror(mcResultItems.get(i)); - } - - List mcItems = getMatrixInventory().getContents(); - - for (int j = 0; j < mcItems.size(); j++) { - items[i + j] = CraftItemStack.asCraftMirror(mcItems.get(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.isEmpty() ? null : CraftItemStack.asCraftMirror(item); - } else { - net.minecraft.server.ItemStack item = getMatrixInventory().getItem(index - getResultInventory().getSize()); - return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); - } - } - - @Override - public void setItem(int index, ItemStack item) { - if (index < getResultInventory().getSize()) { - getResultInventory().setItem(index, CraftItemStack.asNMSCopy(item)); - } else { - getMatrixInventory().setItem((index - getResultInventory().getSize()), CraftItemStack.asNMSCopy(item)); - } - } - - @Override - public ItemStack[] getMatrix() { - List matrix = getMatrixInventory().getContents(); - - return asCraftMirror(matrix); - } - - @Override - public ItemStack getResult() { - net.minecraft.server.ItemStack item = getResultInventory().getItem(0); - if (!item.isEmpty()) return CraftItemStack.asCraftMirror(item); - return null; - } - - @Override - public void setMatrix(ItemStack[] contents) { - if (getMatrixInventory().getSize() > contents.length) { - throw new IllegalArgumentException("Invalid inventory size; expected " + getMatrixInventory().getSize() + " or less"); - } - - for (int i = 0; i < getMatrixInventory().getSize(); i++) { - if (i < contents.length) { - getMatrixInventory().setItem(i, CraftItemStack.asNMSCopy(contents[i])); - } else { - getMatrixInventory().setItem(i, net.minecraft.server.ItemStack.a); - } - } - } - - @Override - public void setResult(ItemStack item) { - List contents = getResultInventory().getContents(); - contents.set(0, CraftItemStack.asNMSCopy(item)); - } - - @Override - public Recipe getRecipe() { - IRecipe recipe = getInventory().getCurrentRecipe(); - return recipe == null ? null : recipe.toBukkitRecipe(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java deleted file mode 100644 index c7f942454..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.IInventory; -import net.minecraft.server.ItemStack; -import net.minecraft.server.NonNullList; -import org.apache.commons.lang.Validate; -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.InventoryHolder; - -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 NonNullList 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 = NonNullList.a(size, ItemStack.a); - this.title = title; - this.viewers = new ArrayList(); - this.owner = owner; - this.type = InventoryType.CHEST; - } - - @Override - public int getSize() { - return items.size(); - } - - @Override - public ItemStack getItem(int i) { - return items.get(i); - } - - @Override - public ItemStack splitStack(int i, int j) { - ItemStack stack = this.getItem(i); - ItemStack result; - if (stack == ItemStack.a) return stack; - if (stack.getCount() <= j) { - this.setItem(i, ItemStack.a); - result = stack; - } else { - result = CraftItemStack.copyNMSStack(stack, j); - stack.subtract(j); - } - this.update(); - return result; - } - - @Override - public ItemStack splitWithoutUpdate(int i) { - ItemStack stack = this.getItem(i); - ItemStack result; - if (stack == ItemStack.a) return stack; - if (stack.getCount() <= 1) { - this.setItem(i, null); - result = stack; - } else { - result = CraftItemStack.copyNMSStack(stack, 1); - stack.subtract(1); - } - return result; - } - - @Override - public void setItem(int i, ItemStack itemstack) { - items.set(i, itemstack); - if (itemstack != ItemStack.a && this.getMaxStackSize() > 0 && itemstack.getCount() > this.getMaxStackSize()) { - itemstack.setCount(this.getMaxStackSize()); - } - } - - @Override - public int getMaxStackSize() { - return maxStack; - } - - @Override - public void setMaxStackSize(int size) { - maxStack = size; - } - - @Override - public void update() {} - - @Override - public boolean a(EntityHuman entityhuman) { - return true; - } - - @Override - public List getContents() { - 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; - } - - public InventoryType getType() { - return type; - } - - @Override - public InventoryHolder getOwner() { - return owner; - } - - @Override - public boolean b(int i, ItemStack itemstack) { - return true; - } - - @Override - public void startOpen(EntityHuman entityHuman) { - - } - - @Override - public void closeContainer(EntityHuman entityHuman) { - - } - - @Override - public void clear() { - items.clear(); - } - - @Override - public Location getLocation() { - return null; - } - - public String getTitle() { - return title; - } - - @Override - public boolean isNotEmpty() { - Iterator iterator = this.items.iterator(); - - ItemStack itemstack; - - do { - if (!iterator.hasNext()) { - return true; - } - - itemstack = (ItemStack) iterator.next(); - } while (itemstack.isEmpty()); - - return false; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java deleted file mode 100644 index e917db0b0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.BlockChest; -import net.minecraft.server.ITileInventory; -import net.minecraft.server.InventoryLargeChest; -import org.bukkit.Location; -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 { - public ITileInventory tile; - private final CraftInventory left; - private final CraftInventory right; - - public CraftInventoryDoubleChest(BlockChest.DoubleInventory block) { - super(block.inventorylargechest); - this.tile = block; - this.left = new CraftInventory(block.inventorylargechest.left); - this.right = new CraftInventory(block.inventorylargechest.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); - } - } - - @Override - public Inventory getLeftSide() { - return left; - } - - @Override - public Inventory getRightSide() { - return right; - } - - @Override - public void setContents(ItemStack[] items) { - if (getInventory().getSize() < items.length) { - throw new IllegalArgumentException("Invalid inventory size; expected " + getInventory().getSize() + " 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); - } - - @Override - public Location getLocation() { - return getLeftSide().getLocation().add(getRightSide().getLocation()).multiply(0.5); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java deleted file mode 100644 index a61405fe5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.EnchantingInventory; -import org.bukkit.inventory.ItemStack; - -public class CraftInventoryEnchanting extends CraftInventory implements EnchantingInventory { - public CraftInventoryEnchanting(IInventory inventory) { - super(inventory); - } - - @Override - public void setItem(ItemStack item) { - setItem(0,item); - } - - @Override - public ItemStack getItem() { - return getItem(0); - } - - @Override - public void setSecondary(ItemStack item) { - setItem(1, item); - } - - @Override - public ItemStack getSecondary() { - return getItem(1); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java deleted file mode 100644 index 043012545..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java +++ /dev/null @@ -1,47 +0,0 @@ -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); - } - - @Override - public ItemStack getResult() { - return getItem(2); - } - - @Override - public ItemStack getFuel() { - return getItem(1); - } - - @Override - public ItemStack getSmelting() { - return getItem(0); - } - - @Override - public void setFuel(ItemStack stack) { - setItem(1,stack); - } - - @Override - public void setResult(ItemStack stack) { - setItem(2,stack); - } - - @Override - public void setSmelting(ItemStack stack) { - setItem(0,stack); - } - - @Override - public Furnace getHolder() { - return (Furnace) inventory.getOwner(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryGrindstone.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryGrindstone.java deleted file mode 100644 index ce89ce764..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryGrindstone.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.GrindstoneInventory; - -public class CraftInventoryGrindstone extends CraftResultInventory implements GrindstoneInventory { - - public CraftInventoryGrindstone(IInventory inventory, IInventory resultInventory) { - super(inventory, resultInventory); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java deleted file mode 100644 index 9a47a1adc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.HorseInventory; -import org.bukkit.inventory.ItemStack; - -public class CraftInventoryHorse extends CraftSaddledInventory implements HorseInventory { - - public CraftInventoryHorse(IInventory inventory) { - super(inventory); - } - - @Override - public ItemStack getArmor() { - return getItem(1); - } - - @Override - public void setArmor(ItemStack stack) { - setItem(1, stack); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLectern.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLectern.java deleted file mode 100644 index f60ed85ef..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLectern.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.block.Lectern; -import org.bukkit.inventory.LecternInventory; - -public class CraftInventoryLectern extends CraftInventory implements LecternInventory { - - public CraftInventoryLectern(IInventory inventory) { - super(inventory); - } - - @Override - public Lectern getHolder() { - return (Lectern) inventory.getOwner(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLlama.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLlama.java deleted file mode 100644 index c910f5e9c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLlama.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.LlamaInventory; - -public class CraftInventoryLlama extends CraftInventoryAbstractHorse implements LlamaInventory { - - public CraftInventoryLlama(IInventory inventory) { - super(inventory); - } - - @Override - public ItemStack getDecor() { - return getItem(1); - } - - @Override - public void setDecor(ItemStack stack) { - setItem(1, stack); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLoom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLoom.java deleted file mode 100644 index d3c541799..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryLoom.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.LoomInventory; - -public class CraftInventoryLoom extends CraftResultInventory implements LoomInventory { - - public CraftInventoryLoom(IInventory inventory, IInventory resultInventory) { - super(inventory, resultInventory); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java deleted file mode 100644 index 3b40adcf5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IMerchant; -import net.minecraft.server.InventoryMerchant; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.MerchantInventory; -import org.bukkit.inventory.MerchantRecipe; - -public class CraftInventoryMerchant extends CraftInventory implements MerchantInventory { - - private final IMerchant merchant; - - public CraftInventoryMerchant(IMerchant merchant, InventoryMerchant inventory) { - super(inventory); - this.merchant = merchant; - } - - @Override - public int getSelectedRecipeIndex() { - return getInventory().selectedIndex; - } - - @Override - public MerchantRecipe getSelectedRecipe() { - net.minecraft.server.MerchantRecipe nmsRecipe = getInventory().getRecipe(); - return (nmsRecipe == null) ? null : nmsRecipe.asBukkit(); - } - - @Override - public InventoryMerchant getInventory() { - return (InventoryMerchant) inventory; - } - - @Override - public Merchant getMerchant() { - return merchant.getCraftMerchant(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java deleted file mode 100644 index ef4cd7a7b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java +++ /dev/null @@ -1,321 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.base.Preconditions; -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 ItemStack[] getStorageContents() { - return asCraftMirror(getInventory().items); - } - - @Override - public ItemStack getItemInMainHand() { - return CraftItemStack.asCraftMirror(getInventory().getItemInHand()); - } - - @Override - public void setItemInMainHand(ItemStack item) { - setItem(getHeldItemSlot(), item); - } - - @Override - public ItemStack getItemInOffHand() { - return CraftItemStack.asCraftMirror(getInventory().extraSlots.get(0)); - } - - @Override - public void setItemInOffHand(ItemStack item) { - ItemStack[] extra = getExtraContents(); - extra[0] = item; - setExtraContents(extra); - } - - @Override - public ItemStack getItemInHand() { - return getItemInMainHand(); - } - - @Override - public void setItemInHand(ItemStack stack) { - setItemInMainHand(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 += 36; - } else if (index > 39) { - index += 5; // Off hand - } else if (index > 35) { - index = 8 - (index - 36); - } - player.playerConnection.sendPacket(new PacketPlayOutSetSlot(player.defaultContainer.windowId, index, CraftItemStack.asNMSCopy(item))); - } - - @Override - public int getHeldItemSlot() { - return getInventory().itemInHandIndex; - } - - @Override - 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)); - } - - @Override - public ItemStack getHelmet() { - return getItem(getSize() - 2); - } - - @Override - public ItemStack getChestplate() { - return getItem(getSize() - 3); - } - - @Override - public ItemStack getLeggings() { - return getItem(getSize() - 4); - } - - @Override - public ItemStack getBoots() { - return getItem(getSize() - 5); - } - - @Override - public void setHelmet(ItemStack helmet) { - setItem(getSize() - 2, helmet); - } - - @Override - public void setChestplate(ItemStack chestplate) { - setItem(getSize() - 3, chestplate); - } - - @Override - public void setLeggings(ItemStack leggings) { - setItem(getSize() - 4, leggings); - } - - @Override - public void setBoots(ItemStack boots) { - setItem(getSize() - 5, boots); - } - - @Override - public ItemStack[] getArmorContents() { - return asCraftMirror(getInventory().armor); - } - - private void setSlots(ItemStack[] items, int baseSlot, int length) { - if (items == null) { - items = new ItemStack[length]; - } - Preconditions.checkArgument(items.length <= length, "items.length must be < %s", length); - - for (int i = 0; i < length; i++) { - if (i >= items.length) { - setItem(baseSlot + i, null); - } else { - setItem(baseSlot + i, items[i]); - } - } - } - - @Override - public void setStorageContents(ItemStack[] items) throws IllegalArgumentException { - setSlots(items, 0, getInventory().items.size()); - } - - @Override - public void setArmorContents(ItemStack[] items) { - setSlots(items, getInventory().items.size(), getInventory().armor.size()); - } - - @Override - public ItemStack[] getExtraContents() { - return asCraftMirror(getInventory().extraSlots); - } - - @Override - public void setExtraContents(ItemStack[] items) { - setSlots(items, getInventory().items.size() + getInventory().armor.size(), getInventory().extraSlots.size()); - } - - @Override - public HumanEntity getHolder() { - return (HumanEntity) inventory.getOwner(); - } - - @Override - public float getItemInHandDropChance() { - return getItemInMainHandDropChance(); - } - - @Override - public void setItemInHandDropChance(float chance) { - setItemInMainHandDropChance(chance); - } - - @Override - public float getItemInMainHandDropChance() { - return 1; - } - - @Override - public void setItemInMainHandDropChance(float chance) { - throw new UnsupportedOperationException("Cannot set drop chance for PlayerInventory"); - } - - @Override - public float getItemInOffHandDropChance() { - return 1; - } - - @Override - public void setItemInOffHandDropChance(float chance) { - throw new UnsupportedOperationException("Cannot set drop chance for PlayerInventory"); - } - - @Override - public float getHelmetDropChance() { - return 1; - } - - @Override - public void setHelmetDropChance(float chance) { - throw new UnsupportedOperationException("Cannot set drop chance for PlayerInventory"); - } - - @Override - public float getChestplateDropChance() { - return 1; - } - - @Override - public void setChestplateDropChance(float chance) { - throw new UnsupportedOperationException("Cannot set drop chance for PlayerInventory"); - } - - @Override - public float getLeggingsDropChance() { - return 1; - } - - @Override - public void setLeggingsDropChance(float chance) { - throw new UnsupportedOperationException("Cannot set drop chance for PlayerInventory"); - } - - @Override - public float getBootsDropChance() { - return 1; - } - - @Override - public void setBootsDropChance(float chance) { - throw new UnsupportedOperationException("Cannot set drop chance for PlayerInventory"); - } - - // Paper start - @Override - public ItemStack getItem(org.bukkit.inventory.EquipmentSlot slot) { - Preconditions.checkNotNull(slot, "slot"); - switch (slot) { - case HAND: - return this.getItemInMainHand(); - case OFF_HAND: - return this.getItemInOffHand(); - case HEAD: - return this.getHelmet(); - case CHEST: - return this.getChestplate(); - case LEGS: - return this.getLeggings(); - case FEET: - return this.getBoots(); - } - - throw new UnsupportedOperationException(slot.name()); - } - - @Override - public void setItem(org.bukkit.inventory.EquipmentSlot slot, ItemStack stack) { - Preconditions.checkNotNull(slot, "slot"); - switch (slot) { - case HAND: - this.setItemInMainHand(stack); - return; - case OFF_HAND: - this.setItemInOffHand(stack); - return; - case HEAD: - this.setHelmet(stack); - return; - case CHEST: - this.setChestplate(stack); - return; - case LEGS: - this.setLeggings(stack); - return; - case FEET: - this.setBoots(stack); - return; - } - - throw new UnsupportedOperationException(slot.name()); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryStonecutter.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryStonecutter.java deleted file mode 100644 index e4135b679..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryStonecutter.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.StonecutterInventory; - -public class CraftInventoryStonecutter extends CraftResultInventory implements StonecutterInventory { - - public CraftInventoryStonecutter(IInventory inventory, IInventory resultInventory) { - super(inventory, resultInventory); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java deleted file mode 100644 index 4c6492a92..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.Container; -import org.bukkit.GameMode; -import org.bukkit.craftbukkit.entity.CraftHumanEntity; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.inventory.InventoryType; -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 >= 0) { - container.getSlot(slot).set(stack); - } else { - player.getHandle().drop(stack, false); - } - } - - @Override - public ItemStack getItem(int slot) { - if (slot < 0) { - return null; - } - return CraftItemStack.asCraftMirror(container.getSlot(slot).getItem()); - } - - @Override - public String getTitle() { - return CraftChatMessage.fromComponent(container.getTitle()); - } - - public boolean isInTop(int rawSlot) { - return rawSlot < viewing.getSize(); - } - - public Container getHandle() { - return container; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java deleted file mode 100644 index 3cddf254a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java +++ /dev/null @@ -1,354 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableSet; -import java.util.Collection; -import org.apache.commons.lang.Validate; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.ConfigurationSerialization; -import org.bukkit.craftbukkit.util.CraftLegacy; -import org.bukkit.inventory.ItemFactory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -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(CraftMetaItem.SerializableMeta.class); - KNOWN_NBT_ATTRIBUTE_NAMES = ImmutableSet.builder() - .add("generic.armor") - .add("generic.armorToughness") - .add("generic.attackDamage") - .add("generic.followRange") - .add("generic.knockbackResistance") - .add("generic.maxHealth") - .add("generic.movementSpeed") - .add("generic.flyingSpeed") - .add("generic.attackSpeed") - .add("generic.luck") - .add("horse.jumpStrength") - .add("zombie.spawnReinforcements") - .add("generic.attackKnockback") - .build(); - } - - private CraftItemFactory() { - } - - @Override - public boolean isApplicable(ItemMeta meta, ItemStack itemstack) { - if (itemstack == null) { - return false; - } - return isApplicable(meta, itemstack.getType()); - } - - @Override - public boolean isApplicable(ItemMeta meta, Material type) { - type = CraftLegacy.fromLegacy(type); // This may be called from legacy item stacks, try to get the right material - 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); - } - - @Override - public ItemMeta getItemMeta(Material material) { - Validate.notNull(material, "Material cannot be null"); - return getItemMeta(material, null); - } - - private ItemMeta getItemMeta(Material material, CraftMetaItem meta) { - material = CraftLegacy.fromLegacy(material); // This may be called from legacy item stacks, try to get the right material - switch (material) { - case AIR: - return null; - case WRITTEN_BOOK: - return meta instanceof CraftMetaBookSigned ? meta : new CraftMetaBookSigned(meta); - case WRITABLE_BOOK: - return meta != null && meta.getClass().equals(CraftMetaBook.class) ? meta : new CraftMetaBook(meta); - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return meta instanceof CraftMetaSkull ? meta : new CraftMetaSkull(meta); - case LEATHER_HELMET: - case LEATHER_HORSE_ARMOR: - case LEATHER_CHESTPLATE: - case LEATHER_LEGGINGS: - case LEATHER_BOOTS: - return meta instanceof CraftMetaLeatherArmor ? meta : new CraftMetaLeatherArmor(meta); - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - case TIPPED_ARROW: - return meta instanceof CraftMetaPotion ? meta : new CraftMetaPotion(meta); - case FILLED_MAP: - return meta instanceof CraftMetaMap ? meta : new CraftMetaMap(meta); - case FIREWORK_ROCKET: - return meta instanceof CraftMetaFirework ? meta : new CraftMetaFirework(meta); - case FIREWORK_STAR: - return meta instanceof CraftMetaCharge ? meta : new CraftMetaCharge(meta); - case ENCHANTED_BOOK: - return meta instanceof CraftMetaEnchantedBook ? meta : new CraftMetaEnchantedBook(meta); - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - return meta instanceof CraftMetaBanner ? meta : new CraftMetaBanner(meta); - case BAT_SPAWN_EGG: - case BLAZE_SPAWN_EGG: - case CAT_SPAWN_EGG: - case CAVE_SPIDER_SPAWN_EGG: - case CHICKEN_SPAWN_EGG: - case COD_SPAWN_EGG: - case COW_SPAWN_EGG: - case CREEPER_SPAWN_EGG: - case DOLPHIN_SPAWN_EGG: - case DONKEY_SPAWN_EGG: - case DROWNED_SPAWN_EGG: - case ELDER_GUARDIAN_SPAWN_EGG: - case ENDERMAN_SPAWN_EGG: - case ENDERMITE_SPAWN_EGG: - case EVOKER_SPAWN_EGG: - case FOX_SPAWN_EGG: - case GHAST_SPAWN_EGG: - case GUARDIAN_SPAWN_EGG: - case HORSE_SPAWN_EGG: - case HUSK_SPAWN_EGG: - case LLAMA_SPAWN_EGG: - case MAGMA_CUBE_SPAWN_EGG: - case MOOSHROOM_SPAWN_EGG: - case MULE_SPAWN_EGG: - case OCELOT_SPAWN_EGG: - case PANDA_SPAWN_EGG: - case PARROT_SPAWN_EGG: - case PHANTOM_SPAWN_EGG: - case PIG_SPAWN_EGG: - case PILLAGER_SPAWN_EGG: - case POLAR_BEAR_SPAWN_EGG: - case PUFFERFISH_SPAWN_EGG: - case RABBIT_SPAWN_EGG: - case RAVAGER_SPAWN_EGG: - case SALMON_SPAWN_EGG: - case SHEEP_SPAWN_EGG: - case SHULKER_SPAWN_EGG: - case SILVERFISH_SPAWN_EGG: - case SKELETON_HORSE_SPAWN_EGG: - case SKELETON_SPAWN_EGG: - case SLIME_SPAWN_EGG: - case SPIDER_SPAWN_EGG: - case SQUID_SPAWN_EGG: - case STRAY_SPAWN_EGG: - case TRADER_LLAMA_SPAWN_EGG: - case TROPICAL_FISH_SPAWN_EGG: - case TURTLE_SPAWN_EGG: - case VEX_SPAWN_EGG: - case VILLAGER_SPAWN_EGG: - case VINDICATOR_SPAWN_EGG: - case WANDERING_TRADER_SPAWN_EGG: - case WITCH_SPAWN_EGG: - case WITHER_SKELETON_SPAWN_EGG: - case WOLF_SPAWN_EGG: - case ZOMBIE_HORSE_SPAWN_EGG: - case ZOMBIE_PIGMAN_SPAWN_EGG: - case ZOMBIE_SPAWN_EGG: - case ZOMBIE_VILLAGER_SPAWN_EGG: - return meta instanceof CraftMetaSpawnEgg ? meta : new CraftMetaSpawnEgg(meta); - case ARMOR_STAND: - return meta instanceof CraftMetaArmorStand ? meta : new CraftMetaArmorStand(meta); - case KNOWLEDGE_BOOK: - return meta instanceof CraftMetaKnowledgeBook ? meta : new CraftMetaKnowledgeBook(meta); - case FURNACE: - case CHEST: - case TRAPPED_CHEST: - case JUKEBOX: - case DISPENSER: - case DROPPER: - case ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case OAK_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_SIGN: - case SPRUCE_WALL_SIGN: - case SPAWNER: - case BREWING_STAND: - case ENCHANTING_TABLE: - case COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - case CHAIN_COMMAND_BLOCK: - case BEACON: - case DAYLIGHT_DETECTOR: - case HOPPER: - case COMPARATOR: - case SHIELD: - case STRUCTURE_BLOCK: - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - case ENDER_CHEST: - case BARREL: - case BELL: - case BLAST_FURNACE: - case CAMPFIRE: - case JIGSAW: - case LECTERN: - case SMOKER: - return new CraftMetaBlockState(meta, material); - case TROPICAL_FISH_BUCKET: - return meta instanceof CraftMetaTropicalFishBucket ? meta : new CraftMetaTropicalFishBucket(meta); - case CROSSBOW: - return meta instanceof CraftMetaCrossbow ? meta : new CraftMetaCrossbow(meta); - case SUSPICIOUS_STEW: - return meta instanceof CraftMetaSuspiciousStew ? meta : new CraftMetaSuspiciousStew(meta); - default: - return new CraftMetaItem(meta); - } - } - - @Override - 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; - } - - @Override - public ItemMeta asMetaFor(ItemMeta meta, ItemStack stack) { - Validate.notNull(stack, "Stack cannot be null"); - return asMetaFor(meta, stack.getType()); - } - - @Override - 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); - } - - @Override - public Color getDefaultLeatherColor() { - return DEFAULT_LEATHER_COLOR; - } - - @Override - public Material updateMaterial(ItemMeta meta, Material material) throws IllegalArgumentException { - return ((CraftMetaItem) meta).updateMaterial(material); - } - // Paper start - @Override - public ItemStack ensureServerConversions(ItemStack item) { - return CraftItemStack.asCraftMirror(CraftItemStack.asNMSCopy(item)); - } - - @Override - public String getI18NDisplayName(ItemStack item) { - net.minecraft.server.ItemStack nms = null; - if (item instanceof CraftItemStack) { - nms = ((CraftItemStack) item).handle; - } - if (nms == null) { - nms = CraftItemStack.asNMSCopy(item); - } - - return nms != null ? net.minecraft.server.LocaleLanguage.getInstance().translateKey(nms.getItem().getName()) : null; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java deleted file mode 100644 index b1ea5b93d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java +++ /dev/null @@ -1,554 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.bukkit.craftbukkit.inventory.CraftMetaItem.*; -import com.google.common.collect.ImmutableMap; -import java.util.Map; -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.enchantments.CraftEnchantment; -import org.bukkit.craftbukkit.util.CraftLegacy; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.material.MaterialData; - -@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 ? net.minecraft.server.ItemStack.a : stack.handle.cloneItemStack(); - } - if (original == null || original.getType() == Material.AIR) { - return net.minecraft.server.ItemStack.a; - } - - Item item = CraftMagicNumbers.getItem(original.getType(), original.getDurability()); - - if (item == null) { - return net.minecraft.server.ItemStack.a; - } - - net.minecraft.server.ItemStack stack = new net.minecraft.server.ItemStack(item, original.getAmount()); - 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.setCount(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.isEmpty()) { - return new ItemStack(Material.AIR); - } - ItemStack stack = new ItemStack(CraftMagicNumbers.getMaterial(original.getItem()), original.getCount()); - if (hasItemMeta(original)) { - stack.setItemMeta(getItemMeta(original)); - } - return stack; - } - - public static CraftItemStack asCraftMirror(net.minecraft.server.ItemStack original) { - return new CraftItemStack((original == null || original.isEmpty()) ? null : 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); - } - - net.minecraft.server.ItemStack handle; - public net.minecraft.server.ItemStack getHandle() { return handle; } // Paper - - /** - * Mirror - */ - private CraftItemStack(net.minecraft.server.ItemStack item) { - this.handle = item; - } - - private CraftItemStack(ItemStack item) { - this(item.getType(), 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); - } - - @Override - public MaterialData getData() { - return handle != null ? CraftMagicNumbers.getMaterialData(handle.getItem()) : super.getData(); - } - - @Override - public Material getType() { - return handle != null ? CraftMagicNumbers.getMaterial(handle.getItem()) : Material.AIR; - } - - @Override - public void setType(Material type) { - if (getType() == type) { - return; - } else if (type == Material.AIR) { - handle = null; - } else if (CraftMagicNumbers.getItem(type) == null) { // :( - handle = null; - } else if (handle == null) { - handle = new net.minecraft.server.ItemStack(CraftMagicNumbers.getItem(type), 1); - } 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.getCount() : 0; - } - - @Override - public void setAmount(int amount) { - if (handle == null) { - return; - } - - handle.setCount(amount); - if (amount == 0) { - handle = null; - } - } - - @Override - public void setDurability(final short durability) { - // Ignore damage if item is null - if (handle != null) { - handle.setDamage(durability); - } - } - - @Override - public short getDurability() { - if (handle != null) { - return (short) handle.getDamage(); - } else { - return -1; - } - } - - @Override - public int getMaxStackSize() { - return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getItem().getMaxStackSize(); - } - - // Paper start - @Override - public int getMaxItemUseDuration() { - return handle == null ? 0 : handle.getItemUseMaxDuration(); - } - // Paper end - - @Override - public void addUnsafeEnchantment(Enchantment ench, int level) { - Validate.notNull(ench, "Cannot add null enchantment"); - - // Paper start - Replace whole method - final ItemMeta itemMeta = getItemMeta(); - itemMeta.addEnchant(ench, level, true); - setItemMeta(itemMeta); - // Paper end - } - - 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 hasItemMeta() && getItemMeta().hasEnchant(ench); // Paper - use meta - } - - @Override - public int getEnchantmentLevel(Enchantment ench) { - return hasItemMeta() ? getItemMeta().getEnchantLevel(ench) : 0; // Paper - replace entire method with meta - } - - @Override - public int removeEnchantment(Enchantment ench) { - Validate.notNull(ench, "Cannot remove null enchantment"); - - // Paper start - replace entire method - final ItemMeta itemMeta = getItemMeta(); - int level = itemMeta.getEnchantLevel(ench); - if (level > 0) { - itemMeta.removeEnchant(ench); - setItemMeta(itemMeta); - } - return level; - // Paper end - } - - @Override - public Map getEnchantments() { - return hasItemMeta() ? getItemMeta().getEnchants() : ImmutableMap.of(); // Paper - use Item Meta - } - - 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++) { - String id = ((NBTTagCompound) list.get(i)).getString(ENCHANTMENTS_ID.NBT); - int level = 0xffff & ((NBTTagCompound) list.get(i)).getShort(ENCHANTMENTS_LVL.NBT); - - Enchantment enchant = Enchantment.getByKey(CraftNamespacedKey.fromStringOrNull(id)); - if (enchant != null) { - result.put(enchant, 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 WRITABLE_BOOK: - return new CraftMetaBook(item.getTag()); - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return new CraftMetaSkull(item.getTag()); - case LEATHER_HELMET: - case LEATHER_HORSE_ARMOR: - case LEATHER_CHESTPLATE: - case LEATHER_LEGGINGS: - case LEATHER_BOOTS: - return new CraftMetaLeatherArmor(item.getTag()); - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - case TIPPED_ARROW: - return new CraftMetaPotion(item.getTag()); - case FILLED_MAP: - return new CraftMetaMap(item.getTag()); - case FIREWORK_ROCKET: - return new CraftMetaFirework(item.getTag()); - case FIREWORK_STAR: - return new CraftMetaCharge(item.getTag()); - case ENCHANTED_BOOK: - return new CraftMetaEnchantedBook(item.getTag()); - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - return new CraftMetaBanner(item.getTag()); - case BAT_SPAWN_EGG: - case BLAZE_SPAWN_EGG: - case CAT_SPAWN_EGG: - case CAVE_SPIDER_SPAWN_EGG: - case CHICKEN_SPAWN_EGG: - case COD_SPAWN_EGG: - case COW_SPAWN_EGG: - case CREEPER_SPAWN_EGG: - case DOLPHIN_SPAWN_EGG: - case DONKEY_SPAWN_EGG: - case DROWNED_SPAWN_EGG: - case ELDER_GUARDIAN_SPAWN_EGG: - case ENDERMAN_SPAWN_EGG: - case ENDERMITE_SPAWN_EGG: - case EVOKER_SPAWN_EGG: - case FOX_SPAWN_EGG: - case GHAST_SPAWN_EGG: - case GUARDIAN_SPAWN_EGG: - case HORSE_SPAWN_EGG: - case HUSK_SPAWN_EGG: - case LLAMA_SPAWN_EGG: - case MAGMA_CUBE_SPAWN_EGG: - case MOOSHROOM_SPAWN_EGG: - case MULE_SPAWN_EGG: - case OCELOT_SPAWN_EGG: - case PANDA_SPAWN_EGG: - case PARROT_SPAWN_EGG: - case PHANTOM_SPAWN_EGG: - case PIG_SPAWN_EGG: - case PILLAGER_SPAWN_EGG: - case POLAR_BEAR_SPAWN_EGG: - case PUFFERFISH_SPAWN_EGG: - case RABBIT_SPAWN_EGG: - case RAVAGER_SPAWN_EGG: - case SALMON_SPAWN_EGG: - case SHEEP_SPAWN_EGG: - case SHULKER_SPAWN_EGG: - case SILVERFISH_SPAWN_EGG: - case SKELETON_HORSE_SPAWN_EGG: - case SKELETON_SPAWN_EGG: - case SLIME_SPAWN_EGG: - case SPIDER_SPAWN_EGG: - case SQUID_SPAWN_EGG: - case STRAY_SPAWN_EGG: - case TRADER_LLAMA_SPAWN_EGG: - case TROPICAL_FISH_SPAWN_EGG: - case TURTLE_SPAWN_EGG: - case VEX_SPAWN_EGG: - case VILLAGER_SPAWN_EGG: - case VINDICATOR_SPAWN_EGG: - case WANDERING_TRADER_SPAWN_EGG: - case WITCH_SPAWN_EGG: - case WITHER_SKELETON_SPAWN_EGG: - case WOLF_SPAWN_EGG: - case ZOMBIE_HORSE_SPAWN_EGG: - case ZOMBIE_PIGMAN_SPAWN_EGG: - case ZOMBIE_SPAWN_EGG: - case ZOMBIE_VILLAGER_SPAWN_EGG: - return new CraftMetaSpawnEgg(item.getTag()); - case ARMOR_STAND: - return new CraftMetaArmorStand(item.getTag()); - case KNOWLEDGE_BOOK: - return new CraftMetaKnowledgeBook(item.getTag()); - case FURNACE: - case CHEST: - case TRAPPED_CHEST: - case JUKEBOX: - case DISPENSER: - case DROPPER: - case ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case OAK_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_SIGN: - case SPRUCE_WALL_SIGN: - case SPAWNER: - case BREWING_STAND: - case ENCHANTING_TABLE: - case COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - case CHAIN_COMMAND_BLOCK: - case BEACON: - case DAYLIGHT_DETECTOR: - case HOPPER: - case COMPARATOR: - case SHIELD: - case STRUCTURE_BLOCK: - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - case ENDER_CHEST: - case BARREL: - case BELL: - case BLAST_FURNACE: - case CAMPFIRE: - case JIGSAW: - case LECTERN: - case SMOKER: - return new CraftMetaBlockState(item.getTag(), CraftMagicNumbers.getMaterial(item.getItem())); - case TROPICAL_FISH_BUCKET: - return new CraftMetaTropicalFishBucket(item.getTag()); - case CROSSBOW: - return new CraftMetaCrossbow(item.getTag()); - case SUSPICIOUS_STEW: - return new CraftMetaSuspiciousStew(item.getTag()); - default: - return new CraftMetaItem(item.getTag()); - } - } - - static Material getType(net.minecraft.server.ItemStack item) { - return item == null ? Material.AIR : CraftMagicNumbers.getMaterial(item.getItem()); - } - - @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; - - Item oldItem = item.getItem(); - Item newItem = CraftMagicNumbers.getItem(CraftItemFactory.instance().updateMaterial(itemMeta, CraftMagicNumbers.getMaterial(oldItem))); - if (oldItem != newItem) { - item.setItem(newItem); - } - - NBTTagCompound tag = new NBTTagCompound(); - item.setTag(tag); - - ((CraftMetaItem) itemMeta).applyToItem(tag); - item.convertStack(((CraftMetaItem) itemMeta).getVersion()); - - 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; - } - Material comparisonType = CraftLegacy.fromLegacy(that.getType()); // This may be called from legacy item stacks, try to get the right material - if (!(comparisonType == getType() && getDurability() == that.getDurability())) { - return false; - } - return hasItemMeta() ? that.hasItemMeta() && handle.getTag().equals(that.handle.getTag()) : !that.hasItemMeta(); - } - - @Override - public boolean hasItemMeta() { - return hasItemMeta(handle) && (handle.getDamage() != 0 || (handle.getTag() != null && handle.getTag().map.size() >= (handle.getTag().hasKey(CraftMetaItem.DAMAGE.NBT) ? 2 : 1))); // Paper - keep 1.12 CraftBukkit behavior without calling getItemMeta - } - - static boolean hasItemMeta(net.minecraft.server.ItemStack item) { - return !(item == null || item.getTag() == null || item.getTag().isEmpty()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchant.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchant.java deleted file mode 100644 index 50bc720d4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchant.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import java.util.Collections; -import java.util.List; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.IMerchant; -import net.minecraft.server.MerchantRecipeList; -import org.bukkit.entity.HumanEntity; -import org.bukkit.inventory.Merchant; -import org.bukkit.inventory.MerchantRecipe; - -public class CraftMerchant implements Merchant { - - protected final IMerchant merchant; - - public CraftMerchant(IMerchant merchant) { - this.merchant = merchant; - } - - public IMerchant getMerchant() { - return merchant; - } - - @Override - public List getRecipes() { - return Collections.unmodifiableList(Lists.transform(merchant.getOffers(), new Function() { - @Override - public MerchantRecipe apply(net.minecraft.server.MerchantRecipe recipe) { - return recipe.asBukkit(); - } - })); - } - - @Override - public void setRecipes(List recipes) { - MerchantRecipeList recipesList = merchant.getOffers(); - recipesList.clear(); - for (MerchantRecipe recipe : recipes) { - recipesList.add(CraftMerchantRecipe.fromBukkit(recipe).toMinecraft()); - } - } - - @Override - public MerchantRecipe getRecipe(int i) { - return merchant.getOffers().get(i).asBukkit(); - } - - @Override - public void setRecipe(int i, MerchantRecipe merchantRecipe) { - merchant.getOffers().set(i, CraftMerchantRecipe.fromBukkit(merchantRecipe).toMinecraft()); - } - - @Override - public int getRecipeCount() { - return merchant.getOffers().size(); - } - - @Override - public boolean isTrading() { - return getTrader() != null; - } - - @Override - public HumanEntity getTrader() { - EntityHuman eh = merchant.getTrader(); - return eh == null ? null : eh.getBukkitEntity(); - } - - @Override - public int hashCode() { - return merchant.hashCode(); - } - - @Override - public boolean equals(final Object obj) { - return obj instanceof CraftMerchant && ((CraftMerchant) obj).merchant.equals(this.merchant); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java deleted file mode 100644 index b8f2904f1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.IChatBaseComponent; -import net.minecraft.server.IMerchant; -import net.minecraft.server.ItemStack; -import net.minecraft.server.MerchantRecipe; -import net.minecraft.server.MerchantRecipeList; -import net.minecraft.server.SoundEffect; -import net.minecraft.server.SoundEffects; -import net.minecraft.server.World; -import org.apache.commons.lang.Validate; - -public class CraftMerchantCustom extends CraftMerchant { - - public CraftMerchantCustom(String title) { - super(new MinecraftMerchant(title)); - getMerchant().craftMerchant = this; - } - - @Override - public String toString() { - return "CraftMerchantCustom"; - } - - @Override - public MinecraftMerchant getMerchant() { - return (MinecraftMerchant) super.getMerchant(); - } - - public static class MinecraftMerchant implements IMerchant { - - private final IChatBaseComponent title; - private final MerchantRecipeList trades = new MerchantRecipeList(); - private EntityHuman tradingPlayer; - private World tradingWorld; - protected CraftMerchant craftMerchant; - - public MinecraftMerchant(String title) { - Validate.notNull(title, "Title cannot be null"); - this.title = new ChatComponentText(title); - } - - @Override - public CraftMerchant getCraftMerchant() { - return craftMerchant; - } - - @Override - public void setTradingPlayer(EntityHuman entityhuman) { - this.tradingPlayer = entityhuman; - if (entityhuman != null) { - this.tradingWorld = entityhuman.world; - } - } - - @Override - public EntityHuman getTrader() { - return this.tradingPlayer; - } - - @Override - public MerchantRecipeList getOffers() { - return this.trades; - } - - @Override - public void a(MerchantRecipe merchantrecipe) { - // increase recipe's uses - merchantrecipe.increaseUses(); - } - - @Override - public void i(ItemStack itemstack) { - } - - public IChatBaseComponent getScoreboardDisplayName() { - return title; - } - - @Override - public World getWorld() { - return this.tradingWorld; - } - - @Override - public int getExperience() { - return 0; // xp - } - - @Override - public void s(int i) { - } - - @Override - public boolean ea() { - return false; // is-regular-villager flag (hides some gui elements: xp bar, name suffix) - } - - @Override - public SoundEffect eb() { - return SoundEffects.ENTITY_VILLAGER_YES; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantRecipe.java deleted file mode 100644 index ff7c65634..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantRecipe.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.base.Preconditions; -import java.util.List; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.MerchantRecipe; - -public class CraftMerchantRecipe extends MerchantRecipe { - - private final net.minecraft.server.MerchantRecipe handle; - - public CraftMerchantRecipe(net.minecraft.server.MerchantRecipe merchantRecipe) { - super(CraftItemStack.asBukkitCopy(merchantRecipe.sellingItem), 0); - this.handle = merchantRecipe; - addIngredient(CraftItemStack.asBukkitCopy(merchantRecipe.buyingItem1)); - addIngredient(CraftItemStack.asBukkitCopy(merchantRecipe.buyingItem2)); - } - - public CraftMerchantRecipe(ItemStack result, int uses, int maxUses, boolean experienceReward, int experience, float priceMultiplier) { - super(result, uses, maxUses, experienceReward, experience, priceMultiplier); - this.handle = new net.minecraft.server.MerchantRecipe( - net.minecraft.server.ItemStack.a, - net.minecraft.server.ItemStack.a, - CraftItemStack.asNMSCopy(result), - uses, - maxUses, - experience, - priceMultiplier, - this - ); - this.setExperienceReward(experienceReward); - } - - @Override - public int getUses() { - return handle.uses; - } - - @Override - public void setUses(int uses) { - handle.uses = uses; - } - - @Override - public int getMaxUses() { - return handle.maxUses; - } - - @Override - public void setMaxUses(int maxUses) { - handle.maxUses = maxUses; - } - - @Override - public boolean hasExperienceReward() { - return handle.rewardExp; - } - - @Override - public void setExperienceReward(boolean flag) { - handle.rewardExp = flag; - } - - @Override - public int getVillagerExperience() { - return handle.xp; - } - - @Override - public void setVillagerExperience(int villagerExperience) { - handle.xp = villagerExperience; - } - - @Override - public float getPriceMultiplier() { - return handle.priceMultiplier; - } - - @Override - public void setPriceMultiplier(float priceMultiplier) { - handle.priceMultiplier = priceMultiplier; - } - - public net.minecraft.server.MerchantRecipe toMinecraft() { - List ingredients = getIngredients(); - Preconditions.checkState(!ingredients.isEmpty(), "No offered ingredients"); - handle.buyingItem1 = CraftItemStack.asNMSCopy(ingredients.get(0)); - if (ingredients.size() > 1) { - handle.buyingItem2 = CraftItemStack.asNMSCopy(ingredients.get(1)); - } - return handle; - } - - public static CraftMerchantRecipe fromBukkit(MerchantRecipe recipe) { - if (recipe instanceof CraftMerchantRecipe) { - return (CraftMerchantRecipe) recipe; - } else { - CraftMerchantRecipe craft = new CraftMerchantRecipe(recipe.getResult(), recipe.getUses(), recipe.getMaxUses(), recipe.hasExperienceReward(), recipe.getVillagerExperience(), recipe.getPriceMultiplier()); - craft.setIngredients(recipe.getIngredients()); - - return craft; - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmorStand.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmorStand.java deleted file mode 100644 index 3723facca..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaArmorStand.java +++ /dev/null @@ -1,296 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableMap.Builder; -import java.util.Map; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagCompound; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; - -@DelegateDeserialization(CraftMetaItem.SerializableMeta.class) -public class CraftMetaArmorStand extends CraftMetaItem implements com.destroystokyo.paper.inventory.meta.ArmorStandMeta { // Paper - - static final ItemMetaKey ENTITY_TAG = new ItemMetaKey("EntityTag", "entity-tag"); - // Paper start - static final ItemMetaKey INVISIBLE = new ItemMetaKey("Invisible", "invisible"); - static final ItemMetaKey NO_BASE_PLATE = new ItemMetaKey("NoBasePlate", "no-base-plate"); - static final ItemMetaKey SHOW_ARMS = new ItemMetaKey("ShowArms", "show-arms"); - static final ItemMetaKey SMALL = new ItemMetaKey("Small", "small"); - static final ItemMetaKey MARKER = new ItemMetaKey("Marker", "marker"); - - private boolean invisible; - private boolean noBasePlate; - private boolean showArms; - private boolean small; - private boolean marker; - // Paper end - NBTTagCompound entityTag; - - CraftMetaArmorStand(CraftMetaItem meta) { - super(meta); - - // Paper start - if (!(meta instanceof CraftMetaArmorStand)) { - return; - } - - CraftMetaArmorStand standMeta = (CraftMetaArmorStand) meta; - this.invisible = standMeta.invisible; - this.noBasePlate = standMeta.noBasePlate; - this.showArms = standMeta.showArms; - this.small = standMeta.small; - this.marker = standMeta.marker; - // Paper end - } - - CraftMetaArmorStand(NBTTagCompound tag) { - super(tag); - - if (tag.hasKey(ENTITY_TAG.NBT)) { - entityTag = tag.getCompound(ENTITY_TAG.NBT); - - // Paper start - if (entityTag.hasKey(INVISIBLE.NBT)) { - invisible = entityTag.getBoolean(INVISIBLE.NBT); - } - - if (entityTag.hasKey(NO_BASE_PLATE.NBT)) { - noBasePlate = entityTag.getBoolean(NO_BASE_PLATE.NBT); - } - - if (entityTag.hasKey(SHOW_ARMS.NBT)) { - showArms = entityTag.getBoolean(SHOW_ARMS.NBT); - } - - if (entityTag.hasKey(SMALL.NBT)) { - small = entityTag.getBoolean(SMALL.NBT); - } - - if (entityTag.hasKey(MARKER.NBT)) { - marker = entityTag.getBoolean(MARKER.NBT); - } - // Paper end - } - } - - CraftMetaArmorStand(Map map) { - super(map); - - // Paper start - boolean invis = SerializableMeta.getBoolean(map, INVISIBLE.BUKKIT); - boolean noBase = SerializableMeta.getBoolean(map, NO_BASE_PLATE.BUKKIT); - boolean showArms = SerializableMeta.getBoolean(map, SHOW_ARMS.BUKKIT); - boolean small = SerializableMeta.getBoolean(map, SMALL.BUKKIT); - boolean marker = SerializableMeta.getBoolean(map, MARKER.BUKKIT); - - this.invisible = invis; - this.noBasePlate = noBase; - this.showArms = showArms; - this.small = small; - this.marker = marker; - // Paper end - } - - @Override - void deserializeInternal(NBTTagCompound tag, Object context) { - super.deserializeInternal(tag, context); - - if (tag.hasKey(ENTITY_TAG.NBT)) { - entityTag = tag.getCompound(ENTITY_TAG.NBT); - } - } - - @Override - void serializeInternal(Map internalTags) { - if (entityTag != null && !entityTag.isEmpty()) { - internalTags.put(ENTITY_TAG.NBT, entityTag); - } - } - - @Override - void applyToItem(NBTTagCompound tag) { - super.applyToItem(tag); - - // Paper start - if (!isArmorStandEmpty() && entityTag == null) { - entityTag = new NBTTagCompound(); - } - - if (isInvisible()) { - entityTag.setBoolean(INVISIBLE.NBT, invisible); - } - - if (hasNoBasePlate()) { - entityTag.setBoolean(NO_BASE_PLATE.NBT, noBasePlate); - } - - if (shouldShowArms()) { - entityTag.setBoolean(SHOW_ARMS.NBT, showArms); - } - - if (isSmall()) { - entityTag.setBoolean(SMALL.NBT, small); - } - - if (isMarker()) { - entityTag.setBoolean(MARKER.NBT, marker); - } - // Paper end - - if (entityTag != null) { - tag.set(ENTITY_TAG.NBT, entityTag); - } - } - - @Override - boolean applicableTo(Material type) { - switch (type) { - case ARMOR_STAND: - return true; - default: - return false; - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isArmorStandEmpty(); - } - - boolean isArmorStandEmpty() { - return !(isInvisible() || hasNoBasePlate() || shouldShowArms() || isSmall() || isMarker() || entityTag != null); - } - - @Override - boolean equalsCommon(CraftMetaItem meta) { - if (!super.equalsCommon(meta)) { - return false; - } - if (meta instanceof CraftMetaArmorStand) { - CraftMetaArmorStand that = (CraftMetaArmorStand) meta; - - // Paper start - return invisible == that.invisible && - noBasePlate == that.noBasePlate && - showArms == that.showArms && - small == that.small && - marker == that.marker; - // Paper end - } - return true; - } - - @Override - boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaArmorStand || isArmorStandEmpty()); - } - - @Override - int applyHash() { - final int original; - int hash = original = super.applyHash(); - - // Paper start - hash += entityTag != null ? 73 * hash + entityTag.hashCode() : 0; - hash += isInvisible() ? 61 * hash + 1231 : 0; - hash += hasNoBasePlate() ? 61 * hash + 1231 : 0; - hash += shouldShowArms() ? 61 * hash + 1231 : 0; - hash += isSmall() ? 61 * hash + 1231 : 0; - hash += isMarker() ? 61 * hash + 1231 : 0; - // Paper end - - return original != hash ? CraftMetaArmorStand.class.hashCode() ^ hash : hash; - } - - @Override - Builder serialize(Builder builder) { - super.serialize(builder); - - // Paper start - if (isInvisible()) { - builder.put(INVISIBLE.BUKKIT, invisible); - } - - if (hasNoBasePlate()) { - builder.put(NO_BASE_PLATE.BUKKIT, noBasePlate); - } - - if (shouldShowArms()) { - builder.put(SHOW_ARMS.BUKKIT, showArms); - } - - if (isSmall()) { - builder.put(SMALL.BUKKIT, small); - } - - if (isMarker()) { - builder.put(MARKER.BUKKIT, marker); - } - // Paper end - - return builder; - } - - @Override - public CraftMetaArmorStand clone() { - CraftMetaArmorStand clone = (CraftMetaArmorStand) super.clone(); - - if (entityTag != null) { - clone.entityTag = entityTag.clone(); - } - - return clone; - } - - // Paper start - @Override - public boolean isInvisible() { - return invisible; - } - - @Override - public boolean hasNoBasePlate() { - return noBasePlate; - } - - @Override - public boolean shouldShowArms() { - return showArms; - } - - @Override - public boolean isSmall() { - return small; - } - - @Override - public boolean isMarker() { - return marker; - } - - @Override - public void setInvisible(boolean invisible) { - this.invisible = invisible; - } - - @Override - public void setNoBasePlate(boolean noBasePlate) { - this.noBasePlate = noBasePlate; - } - - @Override - public void setShowArms(boolean showArms) { - this.showArms = showArms; - } - - @Override - public void setSmall(boolean small) { - this.small = small; - } - - @Override - public void setMarker(boolean marker) { - this.marker = marker; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java deleted file mode 100644 index 2f72f0ce5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java +++ /dev/null @@ -1,246 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -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.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.BannerMeta; - -@DelegateDeserialization(CraftMetaItem.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.getByWoolData((byte) entityTag.getInt(BASE.NBT)) : null; - - if (entityTag.hasKey(PATTERNS.NBT)) { - NBTTagList patterns = entityTag.getList(PATTERNS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); - for (int i = 0; i < Math.min(patterns.size(), 20); i++) { - NBTTagCompound p = patterns.getCompound(i); - this.patterns.add(new Pattern(DyeColor.getByWoolData((byte) p.getInt(COLOR.NBT)), PatternType.getByIdentifier(p.getString(PATTERN.NBT)))); - } - } - } - - CraftMetaBanner(Map map) { - super(map); - - String baseStr = SerializableMeta.getString(map, BASE.BUKKIT, true); - if (baseStr != null) { - base = DyeColor.legacyValueOf(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.getWoolData()); - } - - NBTTagList newPatterns = new NBTTagList(); - - for (Pattern p : patterns) { - NBTTagCompound compound = new NBTTagCompound(); - compound.setInt(COLOR.NBT, p.getColor().getWoolData()); - 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) { - switch (type) { - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - return true; - default: - return false; - } - } - - @Override - public CraftMetaBanner clone() { - CraftMetaBanner meta = (CraftMetaBanner) super.clone(); - meta.patterns = new ArrayList<>(patterns); - return meta; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java deleted file mode 100644 index 1529f30f7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java +++ /dev/null @@ -1,724 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import net.minecraft.server.EnumColor; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.TileEntity; -import net.minecraft.server.TileEntityBanner; -import net.minecraft.server.TileEntityBarrel; -import net.minecraft.server.TileEntityBeacon; -import net.minecraft.server.TileEntityBell; -import net.minecraft.server.TileEntityBlastFurnace; -import net.minecraft.server.TileEntityBrewingStand; -import net.minecraft.server.TileEntityCampfire; -import net.minecraft.server.TileEntityChest; -import net.minecraft.server.TileEntityCommand; -import net.minecraft.server.TileEntityComparator; -import net.minecraft.server.TileEntityDispenser; -import net.minecraft.server.TileEntityDropper; -import net.minecraft.server.TileEntityEnchantTable; -import net.minecraft.server.TileEntityEndGateway; -import net.minecraft.server.TileEntityEnderChest; -import net.minecraft.server.TileEntityFurnace; -import net.minecraft.server.TileEntityFurnaceFurnace; -import net.minecraft.server.TileEntityHopper; -import net.minecraft.server.TileEntityJigsaw; -import net.minecraft.server.TileEntityJukeBox; -import net.minecraft.server.TileEntityLectern; -import net.minecraft.server.TileEntityLightDetector; -import net.minecraft.server.TileEntityMobSpawner; -import net.minecraft.server.TileEntityShulkerBox; -import net.minecraft.server.TileEntitySign; -import net.minecraft.server.TileEntitySkull; -import net.minecraft.server.TileEntitySmoker; -import net.minecraft.server.TileEntityStructure; -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.CraftBanner; -import org.bukkit.craftbukkit.block.CraftBarrel; -import org.bukkit.craftbukkit.block.CraftBeacon; -import org.bukkit.craftbukkit.block.CraftBell; -import org.bukkit.craftbukkit.block.CraftBlastFurnace; -import org.bukkit.craftbukkit.block.CraftBlockEntityState; -import org.bukkit.craftbukkit.block.CraftBrewingStand; -import org.bukkit.craftbukkit.block.CraftCampfire; -import org.bukkit.craftbukkit.block.CraftChest; -import org.bukkit.craftbukkit.block.CraftCommandBlock; -import org.bukkit.craftbukkit.block.CraftComparator; -import org.bukkit.craftbukkit.block.CraftCreatureSpawner; -import org.bukkit.craftbukkit.block.CraftDaylightDetector; -import org.bukkit.craftbukkit.block.CraftDispenser; -import org.bukkit.craftbukkit.block.CraftDropper; -import org.bukkit.craftbukkit.block.CraftEnchantingTable; -import org.bukkit.craftbukkit.block.CraftEndGateway; -import org.bukkit.craftbukkit.block.CraftEnderChest; -import org.bukkit.craftbukkit.block.CraftFurnace; -import org.bukkit.craftbukkit.block.CraftHopper; -import org.bukkit.craftbukkit.block.CraftJigsaw; -import org.bukkit.craftbukkit.block.CraftJukebox; -import org.bukkit.craftbukkit.block.CraftLectern; -import org.bukkit.craftbukkit.block.CraftShulkerBox; -import org.bukkit.craftbukkit.block.CraftSign; -import org.bukkit.craftbukkit.block.CraftSkull; -import org.bukkit.craftbukkit.block.CraftSmoker; -import org.bukkit.craftbukkit.block.CraftStructureBlock; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.BlockStateMeta; - -@DelegateDeserialization(CraftMetaItem.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) { - 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, CraftMagicNumbers.NBT.TAG_COMPOUND)) { - 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, Object context) { - super.deserializeInternal(tag, context); - - if (tag.hasKeyOfType(BLOCK_ENTITY_TAG.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { - 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 ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case OAK_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_SIGN: - case SPRUCE_WALL_SIGN: - case SPAWNER: - case BREWING_STAND: - case ENCHANTING_TABLE: - case COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - case CHAIN_COMMAND_BLOCK: - case BEACON: - case DAYLIGHT_DETECTOR: - case HOPPER: - case COMPARATOR: - case SHIELD: - case STRUCTURE_BLOCK: - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - case ENDER_CHEST: - case BARREL: - case BELL: - case BLAST_FURNACE: - case CAMPFIRE: - case JIGSAW: - case LECTERN: - case SMOKER: - return true; - } - return false; - } - - @Override - public CraftMetaBlockState clone() { - CraftMetaBlockState meta = (CraftMetaBlockState) super.clone(); - if (blockEntityTag != null) { - meta.blockEntityTag = blockEntityTag.clone(); - } - return meta; - } - - @Override - public boolean hasBlockState() { - return blockEntityTag != null; - } - - @Override - public BlockState getBlockState() { - if (blockEntityTag != null) { - switch (material) { - case SHIELD: - blockEntityTag.setString("id", "banner"); - break; - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - blockEntityTag.setString("id", "shulker_box"); - break; - } - } - TileEntity te = (blockEntityTag == null) ? null : TileEntity.create(blockEntityTag); - - switch (material) { - case ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case OAK_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_SIGN: - case SPRUCE_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 FURNACE: - if (te == null) { - te = new TileEntityFurnaceFurnace(); - } - 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 TileEntityDropper(); - } - return new CraftDropper(material, (TileEntityDropper) te); - case END_GATEWAY: - if (te == null) { - te = new TileEntityEndGateway(); - } - return new CraftEndGateway(material, (TileEntityEndGateway) te); - case HOPPER: - if (te == null) { - te = new TileEntityHopper(); - } - return new CraftHopper(material, (TileEntityHopper) te); - case SPAWNER: - if (te == null) { - te = new TileEntityMobSpawner(); - } - return new CraftCreatureSpawner(material, (TileEntityMobSpawner) te); - case JUKEBOX: - if (te == null) { - te = new TileEntityJukeBox(); - } - return new CraftJukebox(material, (TileEntityJukeBox) te); - case BREWING_STAND: - if (te == null) { - te = new TileEntityBrewingStand(); - } - return new CraftBrewingStand(material, (TileEntityBrewingStand) te); - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - if (te == null) { - te = new TileEntitySkull(); - } - return new CraftSkull(material, (TileEntitySkull) te); - case COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - case CHAIN_COMMAND_BLOCK: - 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 SHIELD: - if (te == null) { - te = new TileEntityBanner(); - } - ((TileEntityBanner) te).color = (blockEntityTag == null) ? EnumColor.WHITE : EnumColor.fromColorIndex(blockEntityTag.getInt(CraftMetaBanner.BASE.NBT)); - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - if (te == null) { - te = new TileEntityBanner(); - } - return new CraftBanner(material == Material.SHIELD ? shieldToBannerHack(blockEntityTag) : material, (TileEntityBanner) te); - case STRUCTURE_BLOCK: - if (te == null) { - te = new TileEntityStructure(); - } - return new CraftStructureBlock(material, (TileEntityStructure) te); - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - if (te == null) { - te = new TileEntityShulkerBox(); - } - return new CraftShulkerBox(material, (TileEntityShulkerBox) te); - case ENCHANTING_TABLE: - if (te == null) { - te = new TileEntityEnchantTable(); - } - return new CraftEnchantingTable(material, (TileEntityEnchantTable) te); - case ENDER_CHEST: - if (te == null){ - te = new TileEntityEnderChest(); - } - return new CraftEnderChest(material, (TileEntityEnderChest) te); - case DAYLIGHT_DETECTOR: - if (te == null){ - te = new TileEntityLightDetector(); - } - return new CraftDaylightDetector(material, (TileEntityLightDetector) te); - case COMPARATOR: - if (te == null){ - te = new TileEntityComparator(); - } - return new CraftComparator(material, (TileEntityComparator) te); - case BARREL: - if (te == null){ - te = new TileEntityBarrel(); - } - return new CraftBarrel(material, (TileEntityBarrel) te); - case BELL: - if (te == null){ - te = new TileEntityBell(); - } - return new CraftBell(material, (TileEntityBell) te); - case BLAST_FURNACE: - if (te == null){ - te = new TileEntityBlastFurnace(); - } - return new CraftBlastFurnace(material, (TileEntityBlastFurnace) te); - case CAMPFIRE: - if (te == null){ - te = new TileEntityCampfire(); - } - return new CraftCampfire(material, (TileEntityCampfire) te); - case JIGSAW: - if (te == null){ - te = new TileEntityJigsaw(); - } - return new CraftJigsaw(material, (TileEntityJigsaw) te); - case LECTERN: - if (te == null){ - te = new TileEntityLectern(); - } - return new CraftLectern(material, (TileEntityLectern) te); - case SMOKER: - if (te == null){ - te = new TileEntitySmoker(); - } - return new CraftSmoker(material, (TileEntitySmoker) te); - default: - throw new IllegalStateException("Missing blockState for " + material); - } - } - - @Override - public void setBlockState(BlockState blockState) { - Validate.notNull(blockState, "blockState must not be null"); - - boolean valid; - switch (material) { - case ACACIA_SIGN: - case ACACIA_WALL_SIGN: - case BIRCH_SIGN: - case BIRCH_WALL_SIGN: - case DARK_OAK_SIGN: - case DARK_OAK_WALL_SIGN: - case JUNGLE_SIGN: - case JUNGLE_WALL_SIGN: - case OAK_SIGN: - case OAK_WALL_SIGN: - case SPRUCE_SIGN: - case SPRUCE_WALL_SIGN: - valid = blockState instanceof CraftSign; - break; - case CHEST: - case TRAPPED_CHEST: - valid = blockState instanceof CraftChest; - break; - case FURNACE: - valid = blockState instanceof CraftFurnace; - break; - case DISPENSER: - valid = blockState instanceof CraftDispenser; - break; - case DROPPER: - valid = blockState instanceof CraftDropper; - break; - case END_GATEWAY: - valid = blockState instanceof CraftEndGateway; - break; - case HOPPER: - valid = blockState instanceof CraftHopper; - break; - case SPAWNER: - valid = blockState instanceof CraftCreatureSpawner; - break; - case JUKEBOX: - valid = blockState instanceof CraftJukebox; - break; - case BREWING_STAND: - valid = blockState instanceof CraftBrewingStand; - break; - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - valid = blockState instanceof CraftSkull; - break; - case COMMAND_BLOCK: - case REPEATING_COMMAND_BLOCK: - case CHAIN_COMMAND_BLOCK: - valid = blockState instanceof CraftCommandBlock; - break; - case BEACON: - valid = blockState instanceof CraftBeacon; - break; - case SHIELD: - case BLACK_BANNER: - case BLACK_WALL_BANNER: - case BLUE_BANNER: - case BLUE_WALL_BANNER: - case BROWN_BANNER: - case BROWN_WALL_BANNER: - case CYAN_BANNER: - case CYAN_WALL_BANNER: - case GRAY_BANNER: - case GRAY_WALL_BANNER: - case GREEN_BANNER: - case GREEN_WALL_BANNER: - case LIGHT_BLUE_BANNER: - case LIGHT_BLUE_WALL_BANNER: - case LIGHT_GRAY_BANNER: - case LIGHT_GRAY_WALL_BANNER: - case LIME_BANNER: - case LIME_WALL_BANNER: - case MAGENTA_BANNER: - case MAGENTA_WALL_BANNER: - case ORANGE_BANNER: - case ORANGE_WALL_BANNER: - case PINK_BANNER: - case PINK_WALL_BANNER: - case PURPLE_BANNER: - case PURPLE_WALL_BANNER: - case RED_BANNER: - case RED_WALL_BANNER: - case WHITE_BANNER: - case WHITE_WALL_BANNER: - case YELLOW_BANNER: - case YELLOW_WALL_BANNER: - valid = blockState instanceof CraftBanner; - break; - case STRUCTURE_BLOCK: - valid = blockState instanceof CraftStructureBlock; - break; - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - valid = blockState instanceof CraftShulkerBox; - break; - case ENCHANTING_TABLE: - valid = blockState instanceof CraftEnchantingTable; - break; - case ENDER_CHEST: - valid = blockState instanceof CraftEnderChest; - break; - case DAYLIGHT_DETECTOR: - valid = blockState instanceof CraftDaylightDetector; - break; - case COMPARATOR: - valid = blockState instanceof CraftComparator; - break; - case BARREL: - valid = blockState instanceof CraftBarrel; - break; - case BELL: - valid = blockState instanceof CraftBell; - break; - case BLAST_FURNACE: - valid = blockState instanceof CraftBlastFurnace; - break; - case CAMPFIRE: - valid = blockState instanceof CraftCampfire; - break; - case JIGSAW: - valid = blockState instanceof CraftJigsaw; - break; - case LECTERN: - valid = blockState instanceof CraftLectern; - break; - case SMOKER: - valid = blockState instanceof CraftSmoker; - break; - default: - valid = false; - break; - } - - Validate.isTrue(valid, "Invalid blockState for " + material); - - blockEntityTag = ((CraftBlockEntityState) blockState).getSnapshotNBT(); - // Set shield base - if (material == Material.SHIELD) { - blockEntityTag.setInt(CraftMetaBanner.BASE.NBT, ((CraftBanner) blockState).getBaseColor().getWoolData()); - } - } - - private static Material shieldToBannerHack(NBTTagCompound tag) { - if (tag == null || !tag.hasKeyOfType(CraftMetaBanner.BASE.NBT, CraftMagicNumbers.NBT.TAG_INT)) { - return Material.WHITE_BANNER; - } - - switch (tag.getInt(CraftMetaBanner.BASE.NBT)) { - case 0: - return Material.WHITE_BANNER; - case 1: - return Material.ORANGE_BANNER; - case 2: - return Material.MAGENTA_BANNER; - case 3: - return Material.LIGHT_BLUE_BANNER; - case 4: - return Material.YELLOW_BANNER; - case 5: - return Material.LIME_BANNER; - case 6: - return Material.PINK_BANNER; - case 7: - return Material.GRAY_BANNER; - case 8: - return Material.LIGHT_GRAY_BANNER; - case 9: - return Material.CYAN_BANNER; - case 10: - return Material.PURPLE_BANNER; - case 11: - return Material.BLUE_BANNER; - case 12: - return Material.BROWN_BANNER; - case 13: - return Material.GREEN_BANNER; - case 14: - return Material.RED_BANNER; - case 15: - return Material.BLACK_BANNER; - default: - throw new IllegalArgumentException("Unknown banner colour"); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java deleted file mode 100644 index 7262920c1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java +++ /dev/null @@ -1,438 +0,0 @@ -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 java.util.ArrayList; -import java.util.List; -import java.util.Map; -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.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.BookMeta; - -// Spigot start -import static org.spigotmc.ValidateUtils.*; -import java.util.AbstractList; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.chat.ComponentSerializer; -// 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_PAGES = 100; - static final int MAX_PAGE_LENGTH = 320; // 256 limit + 64 characters to allow for psuedo colour codes - static final int MAX_TITLE_LENGTH = 32; - private static final boolean OVERRIDE_CHECKS = Boolean.getBoolean("disable.book-limits"); // Paper - Add override - - 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, CraftMagicNumbers.NBT.TAG_STRING); - - for (int i = 0; i < Math.min(pages.size(), MAX_PAGES); 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(page == null ? "" : page.e())); // PAIL getLegacyString - } - 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 WRITABLE_BOOK: - return true; - default: - return false; - } - } - - @Override - public boolean hasAuthor() { - return !Strings.isNullOrEmpty(author); - } - - @Override - public boolean hasTitle() { - return !Strings.isNullOrEmpty(title); - } - - @Override - public boolean hasPages() { - return !pages.isEmpty(); - } - - @Override - public boolean hasGeneration() { - return generation != null; - } - - @Override - public String getTitle() { - return this.title; - } - - @Override - public boolean setTitle(final String title) { - if (title == null) { - this.title = null; - return true; - } else if (title.length() > MAX_TITLE_LENGTH && !OVERRIDE_CHECKS) { // Paper - Add override - return false; - } - - this.title = title; - return true; - } - - @Override - public String getAuthor() { - return this.author; - } - - @Override - public void setAuthor(final String author) { - this.author = author; - } - - @Override - public Generation getGeneration() { - return (generation == null) ? null : Generation.values()[generation]; - } - - @Override - public void setGeneration(Generation generation) { - this.generation = (generation == null) ? null : generation.ordinal(); - } - - @Override - public String getPage(final int page) { - Validate.isTrue(isValidPage(page), "Invalid page number"); - return CraftChatMessage.fromComponent(pages.get(page - 1)); - } - - @Override - 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 && !OVERRIDE_CHECKS ? text.substring(0, MAX_PAGE_LENGTH) : text; - pages.set(page - 1, CraftChatMessage.fromString(newText, true)[0]); - } - - @Override - public void setPages(final String... pages) { - this.pages.clear(); - - addPage(pages); - } - - @Override - public void addPage(final String... pages) { - for (String page : pages) { - if (this.pages.size() >= MAX_PAGES && !OVERRIDE_CHECKS) { - return; - } - - if (page == null) { - page = ""; - } else if (page.length() > MAX_PAGE_LENGTH && !OVERRIDE_CHECKS) { // Paper - Add override - page = page.substring(0, MAX_PAGE_LENGTH); - } - - this.pages.add(CraftChatMessage.fromString(page, true)[0]); - } - } - - @Override - public int getPageCount() { - return pages.size(); - } - - @Override - public List getPages() { - return pages.stream().map(CraftChatMessage::fromComponent).collect(ImmutableList.toImmutableList()); - } - - @Override - 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(); - } - if (hasGeneration()) { - hash = 61 * hash + 19 * this.generation.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()) - && (hasGeneration() ? that.hasGeneration() && this.generation.equals(that.generation) : !that.hasGeneration()); - } - 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; - } - - // Spigot start - private final BookMeta.Spigot spigot = new BookMeta.Spigot() { - - @Override - public BaseComponent[] getPage(final int page) { - Validate.isTrue(isValidPage(page), "Invalid page number"); - return ComponentSerializer.parse(IChatBaseComponent.ChatSerializer.a(pages.get(page - 1))); - } - - @Override - public void setPage(final int page, final BaseComponent... text) { - if (!isValidPage(page)) { - throw new IllegalArgumentException("Invalid page number " + page + "/" + pages.size()); - } - - BaseComponent[] newText = text == null ? new BaseComponent[0] : text; - CraftMetaBook.this.pages.set(page - 1, IChatBaseComponent.ChatSerializer.a(ComponentSerializer.toString(newText))); - } - - @Override - public void setPages(final BaseComponent[]... pages) { - CraftMetaBook.this.pages.clear(); - - addPage(pages); - } - - @Override - public void addPage(final BaseComponent[]... pages) { - for (BaseComponent[] page : pages) { - if (CraftMetaBook.this.pages.size() >= MAX_PAGES) { - return; - } - - if (page == null) { - page = new BaseComponent[0]; - } - - CraftMetaBook.this.pages.add(IChatBaseComponent.ChatSerializer.a(ComponentSerializer.toString(page))); - } - } - - @Override - public List getPages() { - final List copy = ImmutableList.copyOf(CraftMetaBook.this.pages); - return new AbstractList() { - - @Override - public BaseComponent[] get(int index) { - return ComponentSerializer.parse(IChatBaseComponent.ChatSerializer.a(copy.get(index))); - } - - @Override - public int size() { - return copy.size(); - } - }; - } - - @Override - public void setPages(List pages) { - CraftMetaBook.this.pages.clear(); - for (BaseComponent[] page : pages) { - addPage(page); - } - } - }; - - @Override - public BookMeta.Spigot spigot() { - return spigot; - } - // Spigot end -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java deleted file mode 100644 index e6ca5e707..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableMap.Builder; -import java.util.Map; -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.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.BookMeta; - -@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, CraftMagicNumbers.NBT.TAG_STRING); - - for (int i = 0; i < Math.min(pages.size(), MAX_PAGES); 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 WRITABLE_BOOK: - return true; - default: - return false; - } - } - - @Override - public CraftMetaBookSigned clone() { - CraftMetaBookSigned meta = (CraftMetaBookSigned) super.clone(); - return meta; - } - - @Override - int applyHash() { - final int original; - int hash = original = super.applyHash(); - return original != hash ? CraftMetaBookSigned.class.hashCode() ^ hash : hash; - } - - @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/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java deleted file mode 100644 index 62b3dcc23..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableMap.Builder; -import java.util.Map; -import net.minecraft.server.NBTTagCompound; -import org.bukkit.FireworkEffect; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.inventory.meta.FireworkEffectMeta; - -@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)) { - effect = CraftMetaFirework.getEffect(tag.getCompound(EXPLOSION.NBT)); - } - } - - @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) { - switch (type) { - case FIREWORK_STAR: - return true; - default: - return false; - } - } - - @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/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCrossbow.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCrossbow.java deleted file mode 100644 index 15fc0115c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCrossbow.java +++ /dev/null @@ -1,202 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import net.minecraft.server.ItemArrow; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NBTTagList; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.CrossbowMeta; - -@DelegateDeserialization(CraftMetaItem.SerializableMeta.class) -public class CraftMetaCrossbow extends CraftMetaItem implements CrossbowMeta { - - static final ItemMetaKey CHARGED = new ItemMetaKey("Charged", "charged"); - static final ItemMetaKey CHARGED_PROJECTILES = new ItemMetaKey("ChargedProjectiles", "charged-projectiles"); - // - private boolean charged; - private List chargedProjectiles; - - CraftMetaCrossbow(CraftMetaItem meta) { - super(meta); - - if (!(meta instanceof CraftMetaCrossbow)) { - return; - } - - CraftMetaCrossbow crossbow = (CraftMetaCrossbow) meta; - this.charged = crossbow.charged; - - if (crossbow.hasChargedProjectiles()) { - this.chargedProjectiles = new ArrayList<>(crossbow.chargedProjectiles); - } - } - - CraftMetaCrossbow(NBTTagCompound tag) { - super(tag); - - charged = tag.getBoolean(CHARGED.NBT); - - if (tag.hasKeyOfType(CHARGED_PROJECTILES.NBT, CraftMagicNumbers.NBT.TAG_LIST)) { - NBTTagList list = tag.getList(CHARGED_PROJECTILES.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); - - if (list != null && !list.isEmpty()) { - chargedProjectiles = new ArrayList<>(); - - for (int i = 0; i < list.size(); i++) { - NBTTagCompound nbttagcompound1 = list.getCompound(i); - - chargedProjectiles.add(CraftItemStack.asCraftMirror(net.minecraft.server.ItemStack.a(nbttagcompound1))); - } - } - } - } - - CraftMetaCrossbow(Map map) { - super(map); - - Boolean charged = SerializableMeta.getObject(Boolean.class, map, CHARGED.BUKKIT, true); - if (charged != null) { - this.charged = charged; - } - - Iterable projectiles = SerializableMeta.getObject(Iterable.class, map, CHARGED_PROJECTILES.BUKKIT, true); - if (projectiles != null) { - for (Object stack : projectiles) { - if (stack instanceof ItemStack) { - addChargedProjectile((ItemStack) stack); - } - } - } - } - - @Override - void applyToItem(NBTTagCompound tag) { - super.applyToItem(tag); - - tag.setBoolean(CHARGED.NBT, charged); - if (hasChargedProjectiles()) { - NBTTagList list = new NBTTagList(); - - for (ItemStack item : chargedProjectiles) { - NBTTagCompound saved = new NBTTagCompound(); - CraftItemStack.asNMSCopy(item).save(saved); - list.add(saved); - } - - tag.set(CHARGED_PROJECTILES.NBT, list); - } - } - - @Override - boolean applicableTo(Material type) { - switch (type) { - case CROSSBOW: - return true; - default: - return false; - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isCrossbowEmpty(); - } - - boolean isCrossbowEmpty() { - return !(hasChargedProjectiles()); - } - - @Override - public boolean hasChargedProjectiles() { - return chargedProjectiles != null; - } - - @Override - public List getChargedProjectiles() { - return (chargedProjectiles == null) ? null : ImmutableList.copyOf(chargedProjectiles); - } - - @Override - public void setChargedProjectiles(List projectiles) { - chargedProjectiles = null; - charged = false; - - if (projectiles == null) { - return; - } - - for (ItemStack i : projectiles) { - addChargedProjectile(i); - } - } - - @Override - public void addChargedProjectile(ItemStack item) { - Preconditions.checkArgument(item != null, "item"); - Preconditions.checkArgument(item.getType() == Material.FIREWORK_ROCKET || CraftMagicNumbers.getItem(item.getType()) instanceof ItemArrow, "Item %s is not an arrow or firework rocket", item); - - if (chargedProjectiles == null) { - chargedProjectiles = new ArrayList<>(); - } - - charged = true; - chargedProjectiles.add(item); - } - - @Override - boolean equalsCommon(CraftMetaItem meta) { - if (!super.equalsCommon(meta)) { - return false; - } - if (meta instanceof CraftMetaCrossbow) { - CraftMetaCrossbow that = (CraftMetaCrossbow) meta; - - return this.charged == that.charged - && (hasChargedProjectiles() ? that.hasChargedProjectiles() && this.chargedProjectiles.equals(that.chargedProjectiles) : !that.hasChargedProjectiles()); - } - return true; - } - - @Override - boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaCrossbow || isCrossbowEmpty()); - } - - @Override - int applyHash() { - final int original; - int hash = original = super.applyHash(); - - if (hasChargedProjectiles()) { - hash = 61 * hash + (this.charged ? 1 : 0); - hash = 61 * hash + chargedProjectiles.hashCode(); - } - - return original != hash ? CraftMetaCrossbow.class.hashCode() ^ hash : hash; - } - - @Override - public CraftMetaCrossbow clone() { - return (CraftMetaCrossbow) super.clone(); - } - - @Override - ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { - super.serialize(builder); - - builder.put(CHARGED.BUKKIT, charged); - if (hasChargedProjectiles()) { - builder.put(CHARGED_PROJECTILES.BUKKIT, chargedProjectiles); - } - - return builder; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java deleted file mode 100644 index f5feea207..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java +++ /dev/null @@ -1,172 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import java.util.HashMap; -import java.util.Map; -import net.minecraft.server.NBTTagCompound; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; - -@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) { - switch (type) { - case ENCHANTED_BOOK: - return true; - default: - return false; - } - } - - @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(); - } - - @Override - public boolean hasStoredEnchant(Enchantment ench) { - return hasStoredEnchants() && enchantments.containsKey(ench); - } - - @Override - public int getStoredEnchantLevel(Enchantment ench) { - Integer level = hasStoredEnchants() ? enchantments.get(ench) : null; - if (level == null) { - return 0; - } - return level; - } - - @Override - public Map getStoredEnchants() { - return hasStoredEnchants() ? ImmutableMap.copyOf(enchantments) : ImmutableMap.of(); - } - - @Override - 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; - } - - @Override - public boolean removeStoredEnchant(Enchantment ench) { - return hasStoredEnchants() && enchantments.remove(ench) != null; - } - - @Override - public boolean hasStoredEnchants() { - return !(enchantments == null || enchantments.isEmpty()); - } - - @Override - public boolean hasConflictingStoredEnchant(Enchantment ench) { - return checkConflictingEnchants(enchantments, ench); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java deleted file mode 100644 index 7a1c4d619..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java +++ /dev/null @@ -1,406 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap.Builder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -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.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.FireworkMeta; - -@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, CraftMagicNumbers.NBT.TAG_COMPOUND); - List effects = this.effects = new ArrayList(fireworkEffects.size()); - - for (int i = 0; i < fireworkEffects.size(); i++) { - try { - effects.add(getEffect((NBTTagCompound) 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))); - - int[] colors = explosion.getIntArray(EXPLOSION_COLORS.NBT); - // People using buggy command generators specify a list rather than an int here, so recover with dummy data. - // Wrong: Colors: [1234] - // Right: Colors: [I;1234] - if (colors.length == 0) { - effect.withColor(Color.WHITE); - } - - for (int color : colors) { - 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 IllegalArgumentException("Unknown effect type " + type); - } - } - - 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 IllegalArgumentException("Unknown effect type " + nbt); - } - } - - 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); - } - - @Override - 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) { - switch(type) { - case FIREWORK_ROCKET: - return true; - default: - return false; - } - } - - @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; - } - - @Override - public void addEffect(FireworkEffect effect) { - Validate.notNull(effect, "Effect cannot be null"); - if (this.effects == null) { - this.effects = new ArrayList(); - } - this.effects.add(effect); - } - - @Override - 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); - } - } - - @Override - public void addEffects(Iterable effects) { - Validate.notNull(effects, "Effects cannot be null"); - safelyAddEffects(effects); - } - - @Override - public List getEffects() { - return this.effects == null ? ImmutableList.of() : ImmutableList.copyOf(this.effects); - } - - @Override - public int getEffectsSize() { - return this.effects == null ? 0 : this.effects.size(); - } - - @Override - public void removeEffect(int index) { - if (this.effects == null) { - throw new IndexOutOfBoundsException("Index: " + index + ", Size: 0"); - } else { - this.effects.remove(index); - } - } - - @Override - public void clearEffects() { - this.effects = null; - } - - @Override - public int getPower() { - return this.power; - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java deleted file mode 100644 index 973727899..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java +++ /dev/null @@ -1,1772 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.ImmutableSortedMap; // Paper -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.collect.SetMultimap; -import com.google.common.collect.Sets; -import com.google.gson.JsonParseException; -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.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; -import java.util.Comparator; // Paper -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.TreeMap; // Paper -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.EnumChatFormat; -import net.minecraft.server.EnumItemSlot; -import net.minecraft.server.GenericAttributes; -import net.minecraft.server.IChatBaseComponent; -import net.minecraft.server.ItemBlock; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTCompressedStreamTools; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NBTTagList; -import net.minecraft.server.NBTTagString; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.lang.Validate; -import org.apache.commons.lang3.EnumUtils; -import org.bukkit.Material; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.block.data.BlockData; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.configuration.serialization.SerializableAs; -import org.bukkit.craftbukkit.CraftEquipmentSlot; -import org.bukkit.craftbukkit.Overridden; -import org.bukkit.craftbukkit.attribute.CraftAttributeInstance; -import org.bukkit.craftbukkit.attribute.CraftAttributeMap; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.ItemMetaKey.Specific; -import org.bukkit.craftbukkit.inventory.tags.DeprecatedCustomTagContainer; -import org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer; -import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftNBTTagConfigSerializer; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.meta.BlockDataMeta; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.Repairable; -import org.bukkit.inventory.meta.tags.CustomItemTagContainer; -import org.bukkit.persistence.PersistentDataContainer; - -// Spigot start -import static org.spigotmc.ValidateUtils.*; -// Spigot end - -// Paper start -import com.destroystokyo.paper.Namespaced; -import com.destroystokyo.paper.NamespacedTag; -import java.util.Collections; -// Paper 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(CraftMetaItem.SerializableMeta.class) -class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { - - 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; - } - } - - @SerializableAs("ItemMeta") - public static 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(CraftMetaArmorStand.class, "ARMOR_STAND") - .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(CraftMetaSpawnEgg.class, "SPAWN_EGG") - .put(CraftMetaEnchantedBook.class, "ENCHANTED") - .put(CraftMetaFirework.class, "FIREWORK") - .put(CraftMetaCharge.class, "FIREWORK_EFFECT") - .put(CraftMetaKnowledgeBook.class, "KNOWLEDGE_BOOK") - .put(CraftMetaTropicalFishBucket.class, "TROPICAL_FISH_BUCKET") - .put(CraftMetaCrossbow.class, "CROSSBOW") - .put(CraftMetaSuspiciousStew.class, "SUSPICIOUS_STEW") - .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 e) { - throw new AssertionError(e); - } catch (final IllegalAccessException e) { - throw new AssertionError(e); - } catch (final InvocationTargetException e) { - throw e.getCause(); - } - } - - @Override - public Map serialize() { - throw new AssertionError(); - } - - 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); - } - } - - static final ItemMetaKey NAME = new ItemMetaKey("Name", "display-name"); - static final ItemMetaKey LOCNAME = new ItemMetaKey("LocName", "loc-name"); - @Specific(Specific.To.NBT) - static final ItemMetaKey DISPLAY = new ItemMetaKey("display"); - static final ItemMetaKey LORE = new ItemMetaKey("Lore", "lore"); - static final ItemMetaKey CUSTOM_MODEL_DATA = new ItemMetaKey("CustomModelData", "custom-model-data"); - static final ItemMetaKey ENCHANTMENTS = new ItemMetaKey("Enchantments", "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"); - static final ItemMetaKey ATTRIBUTES = new ItemMetaKey("AttributeModifiers", "attribute-modifiers"); - @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 ATTRIBUTES_SLOT = new ItemMetaKey("Slot"); - @Specific(Specific.To.NBT) - static final ItemMetaKey HIDEFLAGS = new ItemMetaKey("HideFlags", "ItemFlags"); - @Specific(Specific.To.NBT) - static final ItemMetaKey UNBREAKABLE = new ItemMetaKey("Unbreakable"); - @Specific(Specific.To.NBT) - static final ItemMetaKey DAMAGE = new ItemMetaKey("Damage"); - @Specific(Specific.To.NBT) - static final ItemMetaKey BLOCK_DATA = new ItemMetaKey("BlockStateTag"); - static final ItemMetaKey BUKKIT_CUSTOM_TAG = new ItemMetaKey("PublicBukkitValues"); - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - static final ItemMetaKey CAN_DESTROY = new ItemMetaKey("CanDestroy"); - static final ItemMetaKey CAN_PLACE_ON = new ItemMetaKey("CanPlaceOn"); - // Paper end - - private IChatBaseComponent displayName; - private IChatBaseComponent locName; - private List lore; - private Integer customModelData; - private NBTTagCompound blockData; - private EnchantmentMap enchantments; // Paper - private Multimap attributeModifiers; - private int repairCost; - private int hideFlag; - private boolean unbreakable; - private int damage; - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - private Set placeableKeys = Sets.newHashSet(); - private Set destroyableKeys = Sets.newHashSet(); - // Paper end - - private static final Set HANDLED_TAGS = Sets.newHashSet(); - private static final CraftPersistentDataTypeRegistry DATA_TYPE_REGISTRY = new CraftPersistentDataTypeRegistry(); - - private NBTTagCompound internalTag; - private final Map unhandledTags = new TreeMap<>(); // Paper - private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(DATA_TYPE_REGISTRY); - - private int version = CraftMagicNumbers.INSTANCE.getDataVersion(); // Internal use only - - CraftMetaItem(CraftMetaItem meta) { - if (meta == null) { - return; - } - - this.displayName = meta.displayName; - this.locName = meta.locName; - - if (meta.hasLore()) { - this.lore = new ArrayList(meta.lore); - } - - this.customModelData = meta.customModelData; - this.blockData = meta.blockData; - - if (meta.enchantments != null) { // Spigot - this.enchantments = new EnchantmentMap(meta.enchantments); // Paper - } - - if (meta.hasAttributeModifiers()) { - this.attributeModifiers = LinkedHashMultimap.create(meta.attributeModifiers); - } - - this.repairCost = meta.repairCost; - this.hideFlag = meta.hideFlag; - this.unbreakable = meta.unbreakable; - this.damage = meta.damage; - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - if (meta.hasPlaceableKeys()) { - this.placeableKeys = new java.util.HashSet<>(meta.placeableKeys); - } - - if (meta.hasDestroyableKeys()) { - this.destroyableKeys = new java.util.HashSet<>(meta.destroyableKeys); - } - // Paper end - this.unhandledTags.putAll(meta.unhandledTags); - this.persistentDataContainer.putAll(meta.persistentDataContainer.getRaw()); - - this.internalTag = meta.internalTag; - if (this.internalTag != null) { - deserializeInternal(internalTag, meta); - } - - this.version = meta.version; - } - - CraftMetaItem(NBTTagCompound tag) { - if (tag.hasKey(DISPLAY.NBT)) { - NBTTagCompound display = tag.getCompound(DISPLAY.NBT); - - if (display.hasKey(NAME.NBT)) { - try { - displayName = IChatBaseComponent.ChatSerializer.a( limit( display.getString(NAME.NBT), 1024 ) ); // Spigot - } catch (JsonParseException ex) { - // Ignore (stripped like Vanilla) - } - } - - if (display.hasKey(LOCNAME.NBT)) { - try { - locName = IChatBaseComponent.ChatSerializer.a( limit( display.getString(LOCNAME.NBT), 1024 ) ); // Spigot - } catch (JsonParseException ex) { - // Ignore (stripped like Vanilla) - } - } - - if (display.hasKey(LORE.NBT)) { - NBTTagList list = display.getList(LORE.NBT, CraftMagicNumbers.NBT.TAG_STRING); - lore = new ArrayList(list.size()); - - for (int index = 0; index < list.size(); index++) { - String line = limit( list.getString(index), 8192 ); // Spigot - try { - lore.add(IChatBaseComponent.ChatSerializer.a(line)); - } catch (JsonParseException ex) { - // Ignore (stripped like Vanilla) - } - } - } - } - - if (tag.hasKeyOfType(CUSTOM_MODEL_DATA.NBT, CraftMagicNumbers.NBT.TAG_INT)) { - customModelData = tag.getInt(CUSTOM_MODEL_DATA.NBT); - } - if (tag.hasKeyOfType(BLOCK_DATA.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { - blockData = tag.getCompound(BLOCK_DATA.NBT); - } - - this.enchantments = buildEnchantments(tag, ENCHANTMENTS); - this.attributeModifiers = buildModifiers(tag, ATTRIBUTES); - - if (tag.hasKey(REPAIR.NBT)) { - repairCost = tag.getInt(REPAIR.NBT); - } - - if (tag.hasKey(HIDEFLAGS.NBT)) { - hideFlag = tag.getInt(HIDEFLAGS.NBT); - } - if (tag.hasKey(UNBREAKABLE.NBT)) { - unbreakable = tag.getBoolean(UNBREAKABLE.NBT); - } - if (tag.hasKey(DAMAGE.NBT)) { - damage = tag.getInt(DAMAGE.NBT); - } - if (tag.hasKey(BUKKIT_CUSTOM_TAG.NBT)) { - NBTTagCompound compound = tag.getCompound(BUKKIT_CUSTOM_TAG.NBT); - Set keys = compound.getKeys(); - for (String key : keys) { - persistentDataContainer.put(key, compound.get(key)); - } - } - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - if (tag.hasKey(CAN_DESTROY.NBT)) { - NBTTagList list = tag.getList(CAN_DESTROY.NBT, CraftMagicNumbers.NBT.TAG_STRING); - for (int i = 0; i < list.size(); i++) { - Namespaced namespaced = this.deserializeNamespaced(list.getString(i)); - if (namespaced == null) { - continue; - } - - this.destroyableKeys.add(namespaced); - } - } - - if (tag.hasKey(CAN_PLACE_ON.NBT)) { - NBTTagList list = tag.getList(CAN_PLACE_ON.NBT, CraftMagicNumbers.NBT.TAG_STRING); - for (int i = 0; i < list.size(); i++) { - Namespaced namespaced = this.deserializeNamespaced(list.getString(i)); - if (namespaced == null) { - continue; - } - - this.placeableKeys.add(namespaced); - } - } - // Paper end - - Set keys = tag.getKeys(); - for (String key : keys) { - if (!getHandledTags().contains(key)) { - unhandledTags.put(key, tag.get(key)); - } - } - } - - static EnchantmentMap buildEnchantments(NBTTagCompound tag, ItemMetaKey key) { // Paper - if (!tag.hasKey(key.NBT)) { - return null; - } - - NBTTagList ench = tag.getList(key.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); - EnchantmentMap enchantments = new EnchantmentMap(); // Paper - - for (int i = 0; i < ench.size(); i++) { - String id = ((NBTTagCompound) ench.get(i)).getString(ENCHANTMENTS_ID.NBT); - int level = 0xffff & ((NBTTagCompound) ench.get(i)).getShort(ENCHANTMENTS_LVL.NBT); - - Enchantment enchant = Enchantment.getByKey(CraftNamespacedKey.fromStringOrNull(id)); - if (enchant != null) { - enchantments.put(enchant, level); - } - } - - return enchantments; - } - - static Multimap buildModifiers(NBTTagCompound tag, ItemMetaKey key) { - Multimap modifiers = LinkedHashMultimap.create(); - if (!tag.hasKeyOfType(key.NBT, CraftMagicNumbers.NBT.TAG_LIST)) { - return modifiers; - } - NBTTagList mods = tag.getList(key.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); - int size = mods.size(); - - for (int i = 0; i < size; i++) { - NBTTagCompound entry = mods.getCompound(i); - if (entry.isEmpty()) { - // entry is not an actual NBTTagCompound. getCompound returns empty NBTTagCompound in that case - continue; - } - net.minecraft.server.AttributeModifier nmsModifier = GenericAttributes.a(entry); - if (nmsModifier == null) { - continue; - } - - AttributeModifier attribMod = CraftAttributeInstance.convert(nmsModifier); - - String attributeName = entry.getString(ATTRIBUTES_IDENTIFIER.NBT); - if (attributeName == null || attributeName.isEmpty()) { - continue; - } - - Attribute attribute = CraftAttributeMap.fromMinecraft(attributeName); - if (attribute == null) { - continue; - } - - if (entry.hasKeyOfType(ATTRIBUTES_SLOT.NBT, CraftMagicNumbers.NBT.TAG_STRING)) { - String slotName = entry.getString(ATTRIBUTES_SLOT.NBT); - if (slotName == null || slotName.isEmpty()) { - modifiers.put(attribute, attribMod); - continue; - } - - EquipmentSlot slot = null; - try { - slot = CraftEquipmentSlot.getSlot(EnumItemSlot.fromName(slotName.toLowerCase(Locale.ROOT))); - } catch (IllegalArgumentException ex) { - // SPIGOT-4551 - Slot is invalid, should really match nothing but this is undefined behaviour anyway - } - - if (slot == null) { - modifiers.put(attribute, attribMod); - continue; - } - - attribMod = new AttributeModifier(attribMod.getUniqueId(), attribMod.getName(), attribMod.getAmount(), attribMod.getOperation(), slot); - } - modifiers.put(attribute, attribMod); - } - return modifiers; - } - - CraftMetaItem(Map map) { - setDisplayName(SerializableMeta.getString(map, NAME.BUKKIT, true)); - setLocalizedName(SerializableMeta.getString(map, LOCNAME.BUKKIT, true)); - - Iterable lore = SerializableMeta.getObject(Iterable.class, map, LORE.BUKKIT, true); - if (lore != null) { - safelyAdd(lore, this.lore = new ArrayList(), Integer.MAX_VALUE); - } - - Integer customModelData = SerializableMeta.getObject(Integer.class, map, CUSTOM_MODEL_DATA.BUKKIT, true); - if (customModelData != null) { - setCustomModelData(customModelData); - } - - Map blockData = SerializableMeta.getObject(Map.class, map, BLOCK_DATA.BUKKIT, true); - if (blockData != null) { - this.blockData = (NBTTagCompound) CraftNBTTagConfigSerializer.deserialize(blockData); - } - - enchantments = buildEnchantments(map, ENCHANTMENTS); - attributeModifiers = buildModifiers(map, ATTRIBUTES); - - Integer repairCost = SerializableMeta.getObject(Integer.class, map, REPAIR.BUKKIT, true); - if (repairCost != null) { - setRepairCost(repairCost); - } - - Iterable hideFlags = SerializableMeta.getObject(Iterable.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 - } - } - } - - Boolean unbreakable = SerializableMeta.getObject(Boolean.class, map, UNBREAKABLE.BUKKIT, true); - if (unbreakable != null) { - setUnbreakable(unbreakable); - } - - Integer damage = SerializableMeta.getObject(Integer.class, map, DAMAGE.BUKKIT, true); - if (damage != null) { - setDamage(damage); - } - - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - Iterable canPlaceOnSerialized = SerializableMeta.getObject(Iterable.class, map, CAN_PLACE_ON.BUKKIT, true); - if (canPlaceOnSerialized != null) { - for (Object canPlaceOnElement : canPlaceOnSerialized) { - String canPlaceOnRaw = (String) canPlaceOnElement; - Namespaced value = this.deserializeNamespaced(canPlaceOnRaw); - if (value == null) { - continue; - } - - this.placeableKeys.add(value); - } - } - - Iterable canDestroySerialized = SerializableMeta.getObject(Iterable.class, map, CAN_DESTROY.BUKKIT, true); - if (canDestroySerialized != null) { - for (Object canDestroyElement : canDestroySerialized) { - String canDestroyRaw = (String) canDestroyElement; - Namespaced value = this.deserializeNamespaced(canDestroyRaw); - if (value == null) { - continue; - } - - this.destroyableKeys.add(value); - } - } - // Paper end - - String internal = SerializableMeta.getString(map, "internal", true); - if (internal != null) { - ByteArrayInputStream buf = new ByteArrayInputStream(Base64.decodeBase64(internal)); - try { - internalTag = NBTCompressedStreamTools.a(buf); - deserializeInternal(internalTag, map); - Set keys = internalTag.getKeys(); - for (String key : keys) { - if (!getHandledTags().contains(key)) { - unhandledTags.put(key, internalTag.get(key)); - } - } - } catch (IOException ex) { - Logger.getLogger(CraftMetaItem.class.getName()).log(Level.SEVERE, null, ex); - } - } - - Map nbtMap = SerializableMeta.getObject(Map.class, map, BUKKIT_CUSTOM_TAG.BUKKIT, true); - if (nbtMap != null) { - this.persistentDataContainer.putAll((NBTTagCompound) CraftNBTTagConfigSerializer.deserialize(nbtMap)); - } - } - - void deserializeInternal(NBTTagCompound tag, Object context) { - // SPIGOT-4576: Need to migrate from internal to proper data - if (tag.hasKeyOfType(ATTRIBUTES.NBT, CraftMagicNumbers.NBT.TAG_LIST)) { - this.attributeModifiers = buildModifiers(tag, ATTRIBUTES); - } - } - - static EnchantmentMap buildEnchantments(Map map, ItemMetaKey key) { // Paper - Map ench = SerializableMeta.getObject(Map.class, map, key.BUKKIT, true); - if (ench == null) { - return null; - } - - EnchantmentMap enchantments = new EnchantmentMap(); // Paper - for (Map.Entry entry : ench.entrySet()) { - // Doctor older enchants - String enchantKey = entry.getKey().toString(); - if (enchantKey.equals("SWEEPING")) { - enchantKey = "SWEEPING_EDGE"; - } - - Enchantment enchantment = Enchantment.getByName(enchantKey); - if ((enchantment != null) && (entry.getValue() instanceof Integer)) { - enchantments.put(enchantment, (Integer) entry.getValue()); - } - } - - return enchantments; - } - - static Multimap buildModifiers(Map map, ItemMetaKey key) { - Map mods = SerializableMeta.getObject(Map.class, map, key.BUKKIT, true); - Multimap result = LinkedHashMultimap.create(); - if (mods == null) { - return result; - } - - for (Object obj : mods.keySet()) { - if (!(obj instanceof String)) { - continue; - } - String attributeName = (String) obj; - if (Strings.isNullOrEmpty(attributeName)) { - continue; - } - List list = SerializableMeta.getObject(List.class, mods, attributeName, true); - if (list == null || list.isEmpty()) { - return result; - } - - for (Object o : list) { - if (!(o instanceof AttributeModifier)) { // this catches null - continue; - } - AttributeModifier modifier = (AttributeModifier) o; - Attribute attribute = EnumUtils.getEnum(Attribute.class, attributeName.toUpperCase(Locale.ROOT)); - if (attribute == null) { - continue; - } - - result.put(attribute, modifier); - } - } - return result; - } - - @Overridden - void applyToItem(NBTTagCompound itemTag) { - if (hasDisplayName()) { - setDisplayTag(itemTag, NAME.NBT, new NBTTagString(CraftChatMessage.toJSON(displayName))); - } - if (hasLocalizedName()){ - setDisplayTag(itemTag, LOCNAME.NBT, new NBTTagString(CraftChatMessage.toJSON(locName))); - } - - if (hasLore()) { - setDisplayTag(itemTag, LORE.NBT, createStringList(lore)); - } - - if (hasCustomModelData()) { - itemTag.setInt(CUSTOM_MODEL_DATA.NBT, customModelData); - } - - if (hasBlockData()) { - itemTag.set(BLOCK_DATA.NBT, blockData); - } - - if (hideFlag != 0) { - itemTag.setInt(HIDEFLAGS.NBT, hideFlag); - } - - applyEnchantments(enchantments, itemTag, ENCHANTMENTS); - applyModifiers(attributeModifiers, itemTag, ATTRIBUTES); - - if (hasRepairCost()) { - itemTag.setInt(REPAIR.NBT, repairCost); - } - - if (isUnbreakable()) { - itemTag.setBoolean(UNBREAKABLE.NBT, unbreakable); - } - - if (hasDamage()) { - itemTag.setInt(DAMAGE.NBT, damage); - } - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - if (hasPlaceableKeys()) { - List items = this.placeableKeys.stream() - .map(this::serializeNamespaced) - .collect(java.util.stream.Collectors.toList()); - - itemTag.set(CAN_PLACE_ON.NBT, createNonComponentStringList(items)); - } - - if (hasDestroyableKeys()) { - List items = this.destroyableKeys.stream() - .map(this::serializeNamespaced) - .collect(java.util.stream.Collectors.toList()); - - itemTag.set(CAN_DESTROY.NBT, createNonComponentStringList(items)); - } - // Paper end - - for (Map.Entry e : unhandledTags.entrySet()) { - itemTag.set(e.getKey(), e.getValue()); - } - - if (!persistentDataContainer.isEmpty()) { - NBTTagCompound bukkitCustomCompound = new NBTTagCompound(); - Map rawPublicMap = persistentDataContainer.getRaw(); - - for (Map.Entry nbtBaseEntry : rawPublicMap.entrySet()) { - bukkitCustomCompound.set(nbtBaseEntry.getKey(), nbtBaseEntry.getValue()); - } - itemTag.set(BUKKIT_CUSTOM_TAG.NBT, bukkitCustomCompound); - } - } - - // Paper start - static NBTTagList createNonComponentStringList(List list) { - if (list == null || list.isEmpty()) { - return null; - } - - NBTTagList tagList = new NBTTagList(); - for (String value : list) { - tagList.add(new NBTTagString(value)); - } - - return tagList; - } - // Paper end - - NBTTagList createStringList(List list) { - if (list == null || list.isEmpty()) { - return null; - } - - NBTTagList tagList = new NBTTagList(); - for (IChatBaseComponent value : list) { - // SPIGOT-5342 - horrible hack as 0 version does not go through the Mojang updater - tagList.add(new NBTTagString(version <= 0 || version >= 1803 ? CraftChatMessage.toJSON(value) : CraftChatMessage.fromComponent(value, EnumChatFormat.DARK_PURPLE))); // SPIGOT-4935 - } - - 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.setString(ENCHANTMENTS_ID.NBT, entry.getKey().getKey().toString()); - subtag.setShort(ENCHANTMENTS_LVL.NBT, entry.getValue().shortValue()); - - list.add(subtag); - } - - tag.set(key.NBT, list); - } - - static void applyModifiers(Multimap modifiers, NBTTagCompound tag, ItemMetaKey key) { - if (modifiers == null || modifiers.isEmpty()) { - return; - } - - NBTTagList list = new NBTTagList(); - for (Map.Entry entry : modifiers.entries()) { - if (entry.getKey() == null || entry.getValue() == null) { - continue; - } - net.minecraft.server.AttributeModifier nmsModifier = CraftAttributeInstance.convert(entry.getValue()); - NBTTagCompound sub = GenericAttributes.a(nmsModifier); - if (sub.isEmpty()) { - continue; - } - - String name = CraftAttributeMap.toMinecraft(entry.getKey()); - if (name == null || name.isEmpty()) { - continue; - } - - sub.setString(ATTRIBUTES_IDENTIFIER.NBT, name); // Attribute Name - if (entry.getValue().getSlot() != null) { - EnumItemSlot slot = CraftEquipmentSlot.getNMS(entry.getValue().getSlot()); - if (slot != null) { - sub.setString(ATTRIBUTES_SLOT.NBT, slot.getSlotName()); - } - } - list.add(sub); - } - 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() || hasLocalizedName() || hasEnchants() || hasLore() || hasCustomModelData() || hasBlockData() || hasRepairCost() || !unhandledTags.isEmpty() || !persistentDataContainer.isEmpty() || hideFlag != 0 || isUnbreakable() || hasDamage() || hasAttributeModifiers() || hasPlaceableKeys() || hasDestroyableKeys()); // Paper - Implement an API for CanPlaceOn and CanDestroy NBT values - } - - @Override - public String getDisplayName() { - return CraftChatMessage.fromComponent(displayName, EnumChatFormat.WHITE); - } - - @Override - public final void setDisplayName(String name) { - this.displayName = CraftChatMessage.wrapOrNull(name); - } - - @Override - public boolean hasDisplayName() { - return displayName != null; - } - - @Override - public String getLocalizedName() { - return CraftChatMessage.fromComponent(locName, EnumChatFormat.WHITE); - } - - @Override - public void setLocalizedName(String name) { - this.locName = CraftChatMessage.wrapOrNull(name); - } - - @Override - public boolean hasLocalizedName() { - return locName != null; - } - - @Override - public boolean hasLore() { - return this.lore != null && !this.lore.isEmpty(); - } - - @Override - public boolean hasRepairCost() { - return repairCost > 0; - } - - @Override - public boolean hasEnchant(Enchantment ench) { - Validate.notNull(ench, "Enchantment cannot be null"); - return hasEnchants() && enchantments.containsKey(ench); - } - - @Override - public int getEnchantLevel(Enchantment ench) { - Validate.notNull(ench, "Enchantment cannot be null"); - Integer level = hasEnchants() ? enchantments.get(ench) : null; - if (level == null) { - return 0; - } - return level; - } - - @Override - public Map getEnchants() { - return hasEnchants() ? ImmutableSortedMap.copyOfSorted(enchantments) : ImmutableMap.of(); // Paper - } - - @Override - public boolean addEnchant(Enchantment ench, int level, boolean ignoreRestrictions) { - Validate.notNull(ench, "Enchantment cannot be null"); - if (enchantments == null) { - enchantments = new EnchantmentMap(); // Paper - } - - if (ignoreRestrictions || level >= ench.getStartLevel() && level <= ench.getMaxLevel()) { - Integer old = enchantments.put(ench, level); - return old == null || old != level; - } - return false; - } - - @Override - public boolean removeEnchant(Enchantment ench) { - Validate.notNull(ench, "Enchantment cannot be null"); - // Spigot start - boolean b = hasEnchants() && enchantments.remove( ench ) != null; - if ( enchantments != null && enchantments.isEmpty() ) - { - this.enchantments = null; - } - return b; - // Spigot end - } - - @Override - public boolean hasEnchants() { - return !(enchantments == null || enchantments.isEmpty()); - } - - @Override - 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()); - } - - @Override - public List getLore() { - return this.lore == null ? null : new ArrayList(Lists.transform(this.lore, (line) -> CraftChatMessage.fromComponent(line, EnumChatFormat.DARK_PURPLE))); - } - - @Override - 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); - } - } - } - - @Override - public boolean hasCustomModelData() { - return customModelData != null; - } - - @Override - public int getCustomModelData() { - Preconditions.checkState(hasCustomModelData(), "We don't have CustomModelData! Check hasCustomModelData first!"); - return customModelData; - } - - @Override - public void setCustomModelData(Integer data) { - this.customModelData = data; - } - - @Override - public boolean hasBlockData() { - return this.blockData != null; - } - - @Override - public BlockData getBlockData(Material material) { - return CraftBlockData.fromData(ItemBlock.getBlockState(CraftMagicNumbers.getBlock(material).getBlockData(), blockData)); - } - - @Override - public void setBlockData(BlockData blockData) { - this.blockData = (blockData == null) ? null : ((CraftBlockData) blockData).toStates(); - } - - @Override - public int getRepairCost() { - return repairCost; - } - - @Override - public void setRepairCost(int cost) { // TODO: Does this have limits? - repairCost = cost; - } - - @Override - public boolean isUnbreakable() { - return unbreakable; - } - - @Override - public void setUnbreakable(boolean unbreakable) { - this.unbreakable = unbreakable; - } - - @Override - public boolean hasAttributeModifiers() { - return attributeModifiers != null && !attributeModifiers.isEmpty(); - } - - @Override - public Multimap getAttributeModifiers() { - return hasAttributeModifiers() ? ImmutableMultimap.copyOf(attributeModifiers) : null; - } - - private void checkAttributeList() { - if (attributeModifiers == null) { - attributeModifiers = LinkedHashMultimap.create(); - } - } - - @Override - public Multimap getAttributeModifiers(@Nullable EquipmentSlot slot) { - checkAttributeList(); - SetMultimap result = LinkedHashMultimap.create(); - for (Map.Entry entry : attributeModifiers.entries()) { - if (entry.getValue().getSlot() == null || entry.getValue().getSlot() == slot) { - result.put(entry.getKey(), entry.getValue()); - } - } - return result; - } - - @Override - public Collection getAttributeModifiers(@Nonnull Attribute attribute) { - Preconditions.checkNotNull(attribute, "Attribute cannot be null"); - return attributeModifiers.containsKey(attribute) ? ImmutableList.copyOf(attributeModifiers.get(attribute)) : null; - } - - @Override - public boolean addAttributeModifier(@Nonnull Attribute attribute, @Nonnull AttributeModifier modifier) { - Preconditions.checkNotNull(attribute, "Attribute cannot be null"); - Preconditions.checkNotNull(modifier, "AttributeModifier cannot be null"); - checkAttributeList(); - for (Map.Entry entry : attributeModifiers.entries()) { - Preconditions.checkArgument(!entry.getValue().getUniqueId().equals(modifier.getUniqueId()), "Cannot register AttributeModifier. Modifier is already applied! %s", modifier); - } - return attributeModifiers.put(attribute, modifier); - } - - @Override - public void setAttributeModifiers(@Nullable Multimap attributeModifiers) { - if (attributeModifiers == null || attributeModifiers.isEmpty()) { - this.attributeModifiers = LinkedHashMultimap.create(); - return; - } - - checkAttributeList(); - this.attributeModifiers.clear(); - - Iterator> iterator = attributeModifiers.entries().iterator(); - while (iterator.hasNext()) { - Map.Entry next = iterator.next(); - - if (next.getKey() == null || next.getValue() == null) { - iterator.remove(); - continue; - } - this.attributeModifiers.put(next.getKey(), next.getValue()); - } - } - - @Override - public boolean removeAttributeModifier(@Nonnull Attribute attribute) { - Preconditions.checkNotNull(attribute, "Attribute cannot be null"); - checkAttributeList(); - return !attributeModifiers.removeAll(attribute).isEmpty(); - } - - @Override - public boolean removeAttributeModifier(@Nullable EquipmentSlot slot) { - checkAttributeList(); - int removed = 0; - Iterator> iter = attributeModifiers.entries().iterator(); - - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - // Explicitly match against null because (as of MC 1.13) AttributeModifiers without a - - // set slot are active in any slot. - if (entry.getValue().getSlot() == null || entry.getValue().getSlot() == slot) { - iter.remove(); - ++removed; - } - } - return removed > 0; - } - - @Override - public boolean removeAttributeModifier(@Nonnull Attribute attribute, @Nonnull AttributeModifier modifier) { - Preconditions.checkNotNull(attribute, "Attribute cannot be null"); - Preconditions.checkNotNull(modifier, "AttributeModifier cannot be null"); - checkAttributeList(); - int removed = 0; - Iterator> iter = attributeModifiers.entries().iterator(); - - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - if (entry.getKey() == null || entry.getValue() == null) { - iter.remove(); - ++removed; - continue; // remove all null values while we are here - } - - if (entry.getKey() == attribute && entry.getValue().getUniqueId().equals(modifier.getUniqueId())) { - iter.remove(); - ++removed; - } - } - return removed > 0; - } - - @Override - public CustomItemTagContainer getCustomTagContainer() { - return new DeprecatedCustomTagContainer(this.getPersistentDataContainer()); - } - - @Override - public PersistentDataContainer getPersistentDataContainer() { - return this.persistentDataContainer; - } - - private static boolean compareModifiers(Multimap first, Multimap second) { - if (first == null || second == null) { - return false; - } - for (Map.Entry entry : first.entries()) { - if (!second.containsEntry(entry.getKey(), entry.getValue())) { - return false; - } - } - for (Map.Entry entry : second.entries()) { - if (!first.containsEntry(entry.getKey(), entry.getValue())) { - return false; - } - } - return true; - } - - @Override - public boolean hasDamage() { - return damage > 0; - } - - @Override - public int getDamage() { - return damage; - } - - @Override - public void setDamage(int damage) { - this.damage = damage; - } - - @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.hasLocalizedName()? that.hasLocalizedName()&& this.locName.equals(that.locName) : !that.hasLocalizedName()) - && (this.hasEnchants() ? that.hasEnchants() && this.enchantments.equals(that.enchantments) : !that.hasEnchants()) - && (this.hasLore() ? that.hasLore() && this.lore.equals(that.lore) : !that.hasLore()) - && (this.hasCustomModelData() ? that.hasCustomModelData() && this.customModelData.equals(that.customModelData) : !that.hasCustomModelData()) - && (this.hasBlockData() ? that.hasBlockData() && this.blockData.equals(that.blockData) : !that.hasBlockData()) - && (this.hasRepairCost() ? that.hasRepairCost() && this.repairCost == that.repairCost : !that.hasRepairCost()) - && (this.hasAttributeModifiers() ? that.hasAttributeModifiers() && compareModifiers(this.attributeModifiers, that.attributeModifiers) : !that.hasAttributeModifiers()) - && (this.unhandledTags.equals(that.unhandledTags)) - && (this.persistentDataContainer.equals(that.persistentDataContainer)) - && (this.hideFlag == that.hideFlag) - && (this.isUnbreakable() == that.isUnbreakable()) - && (this.hasDamage() ? that.hasDamage() && this.damage == that.damage : !that.hasDamage()) - && (this.version == that.version) - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - && (this.hasPlaceableKeys() ? that.hasPlaceableKeys() && this.placeableKeys.equals(that.placeableKeys) : !that.hasPlaceableKeys()) - && (this.hasDestroyableKeys() ? that.hasDestroyableKeys() && this.destroyableKeys.equals(that.destroyableKeys) : !that.hasDestroyableKeys()); - // Paper end - } - - /** - * 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 + (hasLocalizedName()? this.locName.hashCode() : 0); - hash = 61 * hash + (hasLore() ? this.lore.hashCode() : 0); - hash = 61 * hash + (hasCustomModelData() ? this.customModelData.hashCode() : 0); - hash = 61 * hash + (hasBlockData() ? this.blockData.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 + (!persistentDataContainer.isEmpty() ? persistentDataContainer.hashCode() : 0); - hash = 61 * hash + hideFlag; - hash = 61 * hash + (isUnbreakable() ? 1231 : 1237); - hash = 61 * hash + (hasDamage() ? this.damage : 0); - hash = 61 * hash + (hasAttributeModifiers() ? this.attributeModifiers.hashCode() : 0); - hash = 61 * hash + version; - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - hash = 61 * hash + (hasPlaceableKeys() ? this.placeableKeys.hashCode() : 0); - hash = 61 * hash + (hasDestroyableKeys() ? this.destroyableKeys.hashCode() : 0); - // Paper end - return hash; - } - - @Overridden - @Override - public CraftMetaItem clone() { - try { - CraftMetaItem clone = (CraftMetaItem) super.clone(); - if (this.lore != null) { - clone.lore = new ArrayList(this.lore); - } - clone.customModelData = this.customModelData; - clone.blockData = this.blockData; - if (this.enchantments != null) { - clone.enchantments = new EnchantmentMap(this.enchantments); // Paper - } - if (this.hasAttributeModifiers()) { - clone.attributeModifiers = LinkedHashMultimap.create(this.attributeModifiers); - } - clone.hideFlag = this.hideFlag; - clone.unbreakable = this.unbreakable; - clone.damage = this.damage; - clone.version = this.version; - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - if (this.placeableKeys != null) { - clone.placeableKeys = Sets.newHashSet(this.placeableKeys); - } - if (this.destroyableKeys != null) { - clone.destroyableKeys = Sets.newHashSet(this.destroyableKeys); - } - // Paper end - return clone; - } catch (CloneNotSupportedException e) { - throw new Error(e); - } - } - - @Override - 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, CraftChatMessage.fromComponent(displayName)); - } - if (hasLocalizedName()) { - builder.put(LOCNAME.BUKKIT, CraftChatMessage.fromComponent(locName)); - } - - if (hasLore()) { - builder.put(LORE.BUKKIT, ImmutableList.copyOf(Lists.transform(lore, CraftChatMessage::fromComponent))); - } - - if (hasCustomModelData()) { - builder.put(CUSTOM_MODEL_DATA.BUKKIT, customModelData); - } - if (hasBlockData()) { - builder.put(BLOCK_DATA.BUKKIT, CraftNBTTagConfigSerializer.serialize(blockData)); - } - - serializeEnchantments(enchantments, builder, ENCHANTMENTS); - serializeModifiers(attributeModifiers, builder, ATTRIBUTES); - - if (hasRepairCost()) { - builder.put(REPAIR.BUKKIT, repairCost); - } - - List hideFlags = new ArrayList(); - for (ItemFlag hideFlagEnum : getItemFlags()) { - hideFlags.add(hideFlagEnum.name()); - } - if (!hideFlags.isEmpty()) { - builder.put(HIDEFLAGS.BUKKIT, hideFlags); - } - - if (isUnbreakable()) { - builder.put(UNBREAKABLE.BUKKIT, unbreakable); - } - - if (hasDamage()) { - builder.put(DAMAGE.BUKKIT, damage); - } - - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - if (hasPlaceableKeys()) { - List cerealPlaceable = this.placeableKeys.stream() - .map(this::serializeNamespaced) - .collect(java.util.stream.Collectors.toList()); - - builder.put(CAN_PLACE_ON.BUKKIT, cerealPlaceable); - } - - if (hasDestroyableKeys()) { - List cerealDestroyable = this.destroyableKeys.stream() - .map(this::serializeNamespaced) - .collect(java.util.stream.Collectors.toList()); - - builder.put(CAN_DESTROY.BUKKIT, cerealDestroyable); - } - // Paper end - - 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.encodeBase64String(buf.toByteArray())); - } catch (IOException ex) { - Logger.getLogger(CraftMetaItem.class.getName()).log(Level.SEVERE, null, ex); - } - } - - if (!persistentDataContainer.isEmpty()) { // Store custom tags, wrapped in their compound - builder.put(BUKKIT_CUSTOM_TAG.BUKKIT, persistentDataContainer.serialize()); - } - - return builder; - } - - void serializeInternal(final Map unhandledTags) { - } - - Material updateMaterial(Material material) { - return material; - } - - 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 serializeModifiers(Multimap modifiers, ImmutableMap.Builder builder, ItemMetaKey key) { - if (modifiers == null || modifiers.isEmpty()) { - return; - } - - Map> mods = new LinkedHashMap<>(); - for (Map.Entry entry : modifiers.entries()) { - if (entry.getKey() == null) { - continue; - } - Collection modCollection = modifiers.get(entry.getKey()); - if (modCollection == null || modCollection.isEmpty()) { - continue; - } - mods.put(entry.getKey().name(), new ArrayList<>(modCollection)); - } - builder.put(key.BUKKIT, mods); - } - - 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(new ChatComponentText("")); - } else { - String page = object.toString(); - - if (page.length() > maxItemLength) { - page = page.substring(0, maxItemLength); - } - - addTo.add(CraftChatMessage.wrapOrEmpty(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 int getVersion() { - return version; - } - - @Override - public void setVersion(int version) { - this.version = version; - } - - public static Set getHandledTags() { - synchronized (HANDLED_TAGS) { - if (HANDLED_TAGS.isEmpty()) { - HANDLED_TAGS.addAll(Arrays.asList( - DISPLAY.NBT, - CUSTOM_MODEL_DATA.NBT, - BLOCK_DATA.NBT, - REPAIR.NBT, - ENCHANTMENTS.NBT, - HIDEFLAGS.NBT, - UNBREAKABLE.NBT, - DAMAGE.NBT, - BUKKIT_CUSTOM_TAG.NBT, - ATTRIBUTES.NBT, - ATTRIBUTES_IDENTIFIER.NBT, - ATTRIBUTES_NAME.NBT, - ATTRIBUTES_VALUE.NBT, - ATTRIBUTES_UUID_HIGH.NBT, - ATTRIBUTES_UUID_LOW.NBT, - ATTRIBUTES_SLOT.NBT, - CraftMetaMap.MAP_SCALING.NBT, - CraftMetaMap.MAP_ID.NBT, - CraftMetaPotion.POTION_EFFECTS.NBT, - CraftMetaPotion.DEFAULT_POTION.NBT, - CraftMetaPotion.POTION_COLOR.NBT, - CraftMetaSkull.SKULL_OWNER.NBT, - CraftMetaSkull.SKULL_PROFILE.NBT, - CraftMetaSpawnEgg.ENTITY_TAG.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, - CraftMetaKnowledgeBook.BOOK_RECIPES.NBT, - CraftMetaTropicalFishBucket.VARIANT.NBT, - CraftMetaCrossbow.CHARGED.NBT, - CraftMetaCrossbow.CHARGED_PROJECTILES.NBT, - CraftMetaSuspiciousStew.EFFECTS.NBT, - // Paper start - CraftMetaArmorStand.ENTITY_TAG.NBT, - CraftMetaArmorStand.INVISIBLE.NBT, - CraftMetaArmorStand.NO_BASE_PLATE.NBT, - CraftMetaArmorStand.SHOW_ARMS.NBT, - CraftMetaArmorStand.SMALL.NBT, - CraftMetaArmorStand.MARKER.NBT, - CAN_DESTROY.NBT, - CAN_PLACE_ON.NBT - // Paper end - )); - } - return HANDLED_TAGS; - } - } - - // Paper start - private static class EnchantmentMap extends TreeMap { - private EnchantmentMap(Map enchantments) { - this(); - putAll(enchantments); - } - - private EnchantmentMap() { - super(Comparator.comparing(o -> o.getKey().toString())); - } - - public EnchantmentMap clone() { - return (EnchantmentMap) super.clone(); - } - } - // Paper end - - // Spigot start - private final Spigot spigot = new Spigot() - { - @Override - public void setUnbreakable(boolean setUnbreakable) - { - CraftMetaItem.this.setUnbreakable(setUnbreakable); - } - - @Override - public boolean isUnbreakable() - { - return CraftMetaItem.this.unbreakable; - } - }; - - @Override - public Spigot spigot() - { - return spigot; - } - // Spigot end - // Paper start - Implement an API for CanPlaceOn and CanDestroy NBT values - @Override - @SuppressWarnings("deprecation") - public Set getCanDestroy() { - return !hasDestroyableKeys() ? Collections.emptySet() : legacyGetMatsFromKeys(this.destroyableKeys); - } - - @Override - @SuppressWarnings("deprecation") - public void setCanDestroy(Set canDestroy) { - Validate.notNull(canDestroy, "Cannot replace with null set!"); - legacyClearAndReplaceKeys(this.destroyableKeys, canDestroy); - } - - @Override - @SuppressWarnings("deprecation") - public Set getCanPlaceOn() { - return !hasPlaceableKeys() ? Collections.emptySet() : legacyGetMatsFromKeys(this.placeableKeys); - } - - @Override - @SuppressWarnings("deprecation") - public void setCanPlaceOn(Set canPlaceOn) { - Validate.notNull(canPlaceOn, "Cannot replace with null set!"); - legacyClearAndReplaceKeys(this.placeableKeys, canPlaceOn); - } - - @Override - public Set getDestroyableKeys() { - return !hasDestroyableKeys() ? Collections.emptySet() : Sets.newHashSet(this.destroyableKeys); - } - - @Override - public void setDestroyableKeys(Collection canDestroy) { - Validate.notNull(canDestroy, "Cannot replace with null collection!"); - Validate.isTrue(ofAcceptableType(canDestroy), "Can only use NamespacedKey or NamespacedTag objects!"); - this.destroyableKeys.clear(); - this.destroyableKeys.addAll(canDestroy); - } - - @Override - public Set getPlaceableKeys() { - return !hasPlaceableKeys() ? Collections.emptySet() : Sets.newHashSet(this.placeableKeys); - } - - @Override - public void setPlaceableKeys(Collection canPlaceOn) { - Validate.notNull(canPlaceOn, "Cannot replace with null collection!"); - Validate.isTrue(ofAcceptableType(canPlaceOn), "Can only use NamespacedKey or NamespacedTag objects!"); - this.placeableKeys.clear(); - this.placeableKeys.addAll(canPlaceOn); - } - - @Override - public boolean hasPlaceableKeys() { - return this.placeableKeys != null && !this.placeableKeys.isEmpty(); - } - - @Override - public boolean hasDestroyableKeys() { - return this.destroyableKeys != null && !this.destroyableKeys.isEmpty(); - } - - @Deprecated - private void legacyClearAndReplaceKeys(Collection toUpdate, Collection beingSet) { - if (beingSet.stream().anyMatch(Material::isLegacy)) { - throw new IllegalArgumentException("Set must not contain any legacy materials!"); - } - - toUpdate.clear(); - toUpdate.addAll(beingSet.stream().map(Material::getKey).collect(java.util.stream.Collectors.toSet())); - } - - @Deprecated - private Set legacyGetMatsFromKeys(Collection names) { - Set mats = Sets.newHashSet(); - for (Namespaced key : names) { - if (!(key instanceof org.bukkit.NamespacedKey)) { - continue; - } - - Material material = Material.matchMaterial(key.toString(), false); - if (material != null) { - mats.add(material); - } - } - - return mats; - } - - private @Nullable Namespaced deserializeNamespaced(String raw) { - boolean isTag = raw.codePointAt(0) == '#'; - net.minecraft.server.ArgumentBlock blockParser = new net.minecraft.server.ArgumentBlock(new com.mojang.brigadier.StringReader(raw), true); - try { - blockParser = blockParser.parse(false); - } catch (com.mojang.brigadier.exceptions.CommandSyntaxException e) { - e.printStackTrace(); - return null; - } - - net.minecraft.server.MinecraftKey key; - if (isTag) { - key = blockParser.getTagKey(); - } else { - key = blockParser.getBlockKey(); - } - - if (key == null) { - return null; - } - - // don't DC the player if something slips through somehow - Namespaced resource = null; - try { - if (isTag) { - resource = new NamespacedTag(key.getNamespace(), key.getKey()); - } else { - resource = CraftNamespacedKey.fromMinecraft(key); - } - } catch (IllegalArgumentException ex) { - org.bukkit.Bukkit.getLogger().warning("Namespaced resource does not validate: " + key.toString()); - ex.printStackTrace(); - } - - return resource; - } - - private @Nonnull String serializeNamespaced(Namespaced resource) { - return resource.toString(); - } - - // not a fan of this - private boolean ofAcceptableType(Collection namespacedResources) { - boolean valid = true; - for (Namespaced resource : namespacedResources) { - if (valid && !(resource instanceof org.bukkit.NamespacedKey || resource instanceof com.destroystokyo.paper.NamespacedTag)) { - valid = false; - } - } - - return valid; - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaKnowledgeBook.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaKnowledgeBook.java deleted file mode 100644 index 2d2d73cc0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaKnowledgeBook.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableMap.Builder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NBTTagList; -import net.minecraft.server.NBTTagString; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.meta.KnowledgeBookMeta; - -@DelegateDeserialization(SerializableMeta.class) -public class CraftMetaKnowledgeBook extends CraftMetaItem implements KnowledgeBookMeta { - - static final ItemMetaKey BOOK_RECIPES = new ItemMetaKey("Recipes"); - static final int MAX_RECIPES = Short.MAX_VALUE; - - protected List recipes = new ArrayList(); - - CraftMetaKnowledgeBook(CraftMetaItem meta) { - super(meta); - - if (meta instanceof CraftMetaKnowledgeBook) { - CraftMetaKnowledgeBook bookMeta = (CraftMetaKnowledgeBook) meta; - this.recipes.addAll(bookMeta.recipes); - } - } - - CraftMetaKnowledgeBook(NBTTagCompound tag) { - super(tag); - - if (tag.hasKey(BOOK_RECIPES.NBT)) { - NBTTagList pages = tag.getList(BOOK_RECIPES.NBT, 8); - - for (int i = 0; i < pages.size(); i++) { - String recipe = pages.getString(i); - - addRecipe(CraftNamespacedKey.fromString(recipe)); - } - } - } - - CraftMetaKnowledgeBook(Map map) { - super(map); - - Iterable pages = SerializableMeta.getObject(Iterable.class, map, BOOK_RECIPES.BUKKIT, true); - if (pages != null) { - for (Object page : pages) { - if (page instanceof String) { - addRecipe(CraftNamespacedKey.fromString((String) page)); - } - } - } - } - - @Override - void applyToItem(NBTTagCompound itemData) { - super.applyToItem(itemData); - - if (hasRecipes()) { - NBTTagList list = new NBTTagList(); - for (NamespacedKey recipe : this.recipes) { - list.add(new NBTTagString(recipe.toString())); - } - itemData.set(BOOK_RECIPES.NBT, list); - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isBookEmpty(); - } - - boolean isBookEmpty() { - return !(hasRecipes()); - } - - @Override - boolean applicableTo(Material type) { - switch (type) { - case KNOWLEDGE_BOOK: - return true; - default: - return false; - } - } - - @Override - public boolean hasRecipes() { - return !recipes.isEmpty(); - } - - @Override - public void addRecipe(NamespacedKey... recipes) { - for (NamespacedKey recipe : recipes) { - if (recipe != null) { - if (this.recipes.size() >= MAX_RECIPES) { - return; - } - - this.recipes.add(recipe); - } - } - } - - @Override - public List getRecipes() { - return Collections.unmodifiableList(recipes); - } - - @Override - public void setRecipes(List recipes) { - this.recipes.clear(); - for (NamespacedKey recipe : recipes) { - addRecipe(recipe); - } - } - - @Override - public CraftMetaKnowledgeBook clone() { - CraftMetaKnowledgeBook meta = (CraftMetaKnowledgeBook) super.clone(); - meta.recipes = new ArrayList(recipes); - return meta; - } - - @Override - int applyHash() { - final int original; - int hash = original = super.applyHash(); - if (hasRecipes()) { - hash = 61 * hash + 17 * this.recipes.hashCode(); - } - return original != hash ? CraftMetaKnowledgeBook.class.hashCode() ^ hash : hash; - } - - @Override - boolean equalsCommon(CraftMetaItem meta) { - if (!super.equalsCommon(meta)) { - return false; - } - if (meta instanceof CraftMetaKnowledgeBook) { - CraftMetaKnowledgeBook that = (CraftMetaKnowledgeBook) meta; - - return (hasRecipes() ? that.hasRecipes() && this.recipes.equals(that.recipes) : !that.hasRecipes()); - } - return true; - } - - @Override - boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaKnowledgeBook || isBookEmpty()); - } - - @Override - Builder serialize(Builder builder) { - super.serialize(builder); - - if (hasRecipes()) { - List recipesString = new ArrayList(); - for (NamespacedKey recipe : recipes) { - recipesString.add(recipe.toString()); - } - builder.put(BOOK_RECIPES.BUKKIT, recipesString); - } - - return builder; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java deleted file mode 100644 index ecb12457a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java +++ /dev/null @@ -1,138 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.bukkit.craftbukkit.inventory.CraftItemFactory.*; -import com.google.common.collect.ImmutableMap.Builder; -import java.util.Map; -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.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; - -@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)) { - try { - color = Color.fromRGB(display.getInt(COLOR.NBT)); - } catch (IllegalArgumentException ex) { - // Invalid colour - } - } - } - } - - 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_HORSE_ARMOR: - case LEATHER_CHESTPLATE: - case LEATHER_LEGGINGS: - case LEATHER_BOOTS: - return true; - default: - return false; - } - } - - @Override - public CraftMetaLeatherArmor clone() { - return (CraftMetaLeatherArmor) super.clone(); - } - - @Override - public Color getColor() { - return color; - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java deleted file mode 100644 index 7489e63a1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java +++ /dev/null @@ -1,280 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NBTTagInt; -import net.minecraft.server.NBTTagString; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.MapMeta; -import org.bukkit.map.MapView; - -@DelegateDeserialization(SerializableMeta.class) -class CraftMetaMap extends CraftMetaItem implements MapMeta { - static final ItemMetaKey MAP_SCALING = new ItemMetaKey("map_is_scaling", "scaling"); - static final ItemMetaKey MAP_LOC_NAME = new ItemMetaKey("LocName", "display-loc-name"); - static final ItemMetaKey MAP_COLOR = new ItemMetaKey("MapColor", "display-map-color"); - static final ItemMetaKey MAP_ID = new ItemMetaKey("map", "map-id"); - static final byte SCALING_EMPTY = (byte) 0; - static final byte SCALING_TRUE = (byte) 1; - static final byte SCALING_FALSE = (byte) 2; - - private Integer mapId; - private byte scaling = SCALING_EMPTY; - private String locName; - private Color color; - - CraftMetaMap(CraftMetaItem meta) { - super(meta); - - if (!(meta instanceof CraftMetaMap)) { - return; - } - - CraftMetaMap map = (CraftMetaMap) meta; - this.mapId = map.mapId; - this.scaling = map.scaling; - this.locName = map.locName; - this.color = map.color; - } - - CraftMetaMap(NBTTagCompound tag) { - super(tag); - - if (tag.hasKeyOfType(MAP_ID.NBT, CraftMagicNumbers.NBT.TAG_ANY_NUMBER)) { - this.mapId = tag.getInt(MAP_ID.NBT); - } - - if (tag.hasKey(MAP_SCALING.NBT)) { - this.scaling = tag.getBoolean(MAP_SCALING.NBT) ? SCALING_TRUE : SCALING_FALSE; - } - - if (tag.hasKey(DISPLAY.NBT)) { - NBTTagCompound display = tag.getCompound(DISPLAY.NBT); - - if (display.hasKey(MAP_LOC_NAME.NBT)) { - locName = display.getString(MAP_LOC_NAME.NBT); - } - - if (display.hasKey(MAP_COLOR.NBT)) { - color = Color.fromRGB(display.getInt(MAP_COLOR.NBT)); - } - } - } - - CraftMetaMap(Map map) { - super(map); - - Integer id = SerializableMeta.getObject(Integer.class, map, MAP_ID.BUKKIT, true); - if (id != null) { - setMapId(id); - } - - Boolean scaling = SerializableMeta.getObject(Boolean.class, map, MAP_SCALING.BUKKIT, true); - if (scaling != null) { - setScaling(scaling); - } - - String locName = SerializableMeta.getString(map, MAP_LOC_NAME.BUKKIT, true); - if (locName != null) { - setLocationName(locName); - } - - Color color = SerializableMeta.getObject(Color.class, map, MAP_COLOR.BUKKIT, true); - if (color != null) { - setColor(color); - } - } - - @Override - void applyToItem(NBTTagCompound tag) { - super.applyToItem(tag); - - if (hasMapId()){ - tag.setInt(MAP_ID.NBT, getMapId()); - } - - if (hasScaling()) { - tag.setBoolean(MAP_SCALING.NBT, isScaling()); - } - - if (hasLocationName()) { - setDisplayTag(tag, MAP_LOC_NAME.NBT, new NBTTagString(getLocationName())); - } - - if (hasColor()) { - setDisplayTag(tag, MAP_COLOR.NBT, new NBTTagInt(color.asRGB())); - } - } - - @Override - boolean applicableTo(Material type) { - switch (type) { - case FILLED_MAP: - return true; - default: - return false; - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isMapEmpty(); - } - - boolean isMapEmpty() { - return !(hasMapId() || hasScaling() | hasLocationName() || hasColor()); - } - - @Override - public boolean hasMapId() { - return mapId != null; - } - - @Override - public int getMapId() { - return mapId; - } - - @Override - public void setMapId(int id) { - this.mapId = id; - } - - @Override - public boolean hasMapView() { - return mapId != null; - } - - @Override - public MapView getMapView() { - Preconditions.checkState(hasMapView(), "Item does not have map associated - check hasMapView() first!"); - return Bukkit.getMap(mapId); - } - - @Override - public void setMapView(MapView map) { - this.mapId = (map != null) ? map.getId() : null; - } - - boolean hasScaling() { - return scaling != SCALING_EMPTY; - } - - @Override - public boolean isScaling() { - return scaling == SCALING_TRUE; - } - - @Override - public void setScaling(boolean scaling) { - this.scaling = scaling ? SCALING_TRUE : SCALING_FALSE; - } - - @Override - public boolean hasLocationName() { - return this.locName != null; - } - - @Override - public String getLocationName() { - return this.locName; - } - - @Override - public void setLocationName(String name) { - this.locName = name; - } - - @Override - public boolean hasColor() { - return this.color != null; - } - - @Override - public Color getColor() { - return this.color; - } - - @Override - public void setColor(Color color) { - this.color = color; - } - - @Override - boolean equalsCommon(CraftMetaItem meta) { - if (!super.equalsCommon(meta)) { - return false; - } - if (meta instanceof CraftMetaMap) { - CraftMetaMap that = (CraftMetaMap) meta; - - return (this.scaling == that.scaling) - && (hasMapId() ? that.hasMapId() && this.mapId.equals(that.mapId) : !that.hasMapId()) - && (hasLocationName() ? that.hasLocationName() && this.locName.equals(that.locName) : !that.hasLocationName()) - && (hasColor() ? that.hasColor() && this.color.equals(that.color) : !that.hasColor()); - } - 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 (hasMapId()) { - hash = 61 * hash + mapId.hashCode(); - } - if (hasScaling()) { - hash ^= 0x22222222 << (isScaling() ? 1 : -1); - } - if (hasLocationName()) { - hash = 61 * hash + locName.hashCode(); - } - if (hasColor()) { - hash = 61 * hash + color.hashCode(); - } - - return original != hash ? CraftMetaMap.class.hashCode() ^ hash : hash; - } - - - @Override - public CraftMetaMap clone() { - return (CraftMetaMap) super.clone(); - } - - @Override - ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { - super.serialize(builder); - - if (hasMapId()) { - builder.put(MAP_ID.BUKKIT, getMapId()); - } - - if (hasScaling()) { - builder.put(MAP_SCALING.BUKKIT, isScaling()); - } - - if (hasLocationName()) { - builder.put(MAP_LOC_NAME.BUKKIT, getLocationName()); - } - - if (hasColor()) { - builder.put(MAP_COLOR.BUKKIT, getColor()); - } - - return builder; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java deleted file mode 100644 index bb921c928..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java +++ /dev/null @@ -1,347 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap.Builder; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NBTTagList; -import org.apache.commons.lang.Validate; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionType; - -@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 SHOW_ICON = new ItemMetaKey("ShowIcon", "has-icon"); - static final ItemMetaKey POTION_EFFECTS = new ItemMetaKey("CustomPotionEffects", "custom-effects"); - static final ItemMetaKey POTION_COLOR = new ItemMetaKey("CustomPotionColor", "custom-color"); - static final ItemMetaKey ID = new ItemMetaKey("Id", "potion-id"); - static final ItemMetaKey DEFAULT_POTION = new ItemMetaKey("Potion", "potion-type"); - - // Having an initial "state" in ItemMeta seems bit dirty but the UNCRAFTABLE potion type - // is treated as the empty form of the meta because it represents an empty potion with no effect - private PotionData type = new PotionData(PotionType.UNCRAFTABLE, false, false); - private List customEffects; - private Color color; - - CraftMetaPotion(CraftMetaItem meta) { - super(meta); - if (!(meta instanceof CraftMetaPotion)) { - return; - } - CraftMetaPotion potionMeta = (CraftMetaPotion) meta; - this.type = potionMeta.type; - this.color = potionMeta.color; - if (potionMeta.hasCustomEffects()) { - this.customEffects = new ArrayList(potionMeta.customEffects); - } - } - - CraftMetaPotion(NBTTagCompound tag) { - super(tag); - if (tag.hasKey(DEFAULT_POTION.NBT)) { - type = CraftPotionUtil.toBukkit(tag.getString(DEFAULT_POTION.NBT)); - } - if (tag.hasKey(POTION_COLOR.NBT)) { - color = Color.fromRGB(tag.getInt(POTION_COLOR.NBT)); - } - if (tag.hasKey(POTION_EFFECTS.NBT)) { - NBTTagList list = tag.getList(POTION_EFFECTS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); - int length = list.size(); - customEffects = new ArrayList(length); - - for (int i = 0; i < length; i++) { - NBTTagCompound effect = list.getCompound(i); - PotionEffectType type = PotionEffectType.getById(effect.getByte(ID.NBT)); - // SPIGOT-4047: Vanilla just disregards these - if (type == null) { - continue; - } - - int amp = effect.getByte(AMPLIFIER.NBT); - int duration = effect.getInt(DURATION.NBT); - boolean ambient = effect.getBoolean(AMBIENT.NBT); - boolean particles = tag.hasKeyOfType(SHOW_PARTICLES.NBT, CraftMagicNumbers.NBT.TAG_BYTE) ? effect.getBoolean(SHOW_PARTICLES.NBT) : true; - boolean icon = tag.hasKeyOfType(SHOW_ICON.NBT, CraftMagicNumbers.NBT.TAG_BYTE) ? effect.getBoolean(SHOW_ICON.NBT) : particles; - customEffects.add(new PotionEffect(type, duration, amp, ambient, particles, icon)); - } - } - } - - CraftMetaPotion(Map map) { - super(map); - type = CraftPotionUtil.toBukkit(SerializableMeta.getString(map, DEFAULT_POTION.BUKKIT, true)); - - Color color = SerializableMeta.getObject(Color.class, map, POTION_COLOR.BUKKIT, true); - if (color != null) { - setColor(color); - } - - 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); - - tag.setString(DEFAULT_POTION.NBT, CraftPotionUtil.fromBukkit(type)); - - if (hasColor()) { - tag.setInt(POTION_COLOR.NBT, color.asRGB()); - } - - 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()); - effectData.setBoolean(SHOW_ICON.NBT, effect.hasIcon()); - effectList.add(effectData); - } - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isPotionEmpty(); - } - - boolean isPotionEmpty() { - return (type.getType() == PotionType.UNCRAFTABLE) && !(hasCustomEffects() || hasColor()); - } - - @Override - boolean applicableTo(Material type) { - switch(type) { - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - case TIPPED_ARROW: - return true; - default: - return false; - } - } - - @Override - public CraftMetaPotion clone() { - CraftMetaPotion clone = (CraftMetaPotion) super.clone(); - clone.type = type; - if (this.customEffects != null) { - clone.customEffects = new ArrayList(this.customEffects); - } - return clone; - } - - @Override - public void setBasePotionData(PotionData data) { - Validate.notNull(data, "PotionData cannot be null"); - this.type = data; - } - - @Override - public PotionData getBasePotionData() { - return type; - } - - @Override - public boolean hasCustomEffects() { - return customEffects != null; - } - - @Override - public List getCustomEffects() { - if (hasCustomEffects()) { - return ImmutableList.copyOf(customEffects); - } - return ImmutableList.of(); - } - - @Override - 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; - } - } - - @Override - 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 (type.equals(effect.getType())) { - iterator.remove(); - changed = true; - } - } - if (customEffects.isEmpty()) { - customEffects = null; - } - return changed; - } - - @Override - public boolean hasCustomEffect(PotionEffectType type) { - Validate.notNull(type, "Potion effect type must not be null"); - return indexOfEffect(type) != -1; - } - - @Override - 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; - } - - @Override - public boolean clearCustomEffects() { - boolean changed = hasCustomEffects(); - customEffects = null; - return changed; - } - - @Override - public boolean hasColor() { - return color != null; - } - - @Override - public Color getColor() { - return color; - } - - @Override - public void setColor(Color color) { - this.color = color; - } - - @Override - int applyHash() { - final int original; - int hash = original = super.applyHash(); - if (type.getType() != PotionType.UNCRAFTABLE) { - hash = 73 * hash + type.hashCode(); - } - if (hasColor()) { - hash = 73 * hash + color.hashCode(); - } - 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 type.equals(that.type) - && (this.hasCustomEffects() ? that.hasCustomEffects() && this.customEffects.equals(that.customEffects) : !that.hasCustomEffects()) - && (this.hasColor() ? that.hasColor() && this.color.equals(that.color) : !that.hasColor()); - } - return true; - } - - @Override - boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaPotion || isPotionEmpty()); - } - - @Override - Builder serialize(Builder builder) { - super.serialize(builder); - if (type.getType() != PotionType.UNCRAFTABLE) { - builder.put(DEFAULT_POTION.BUKKIT, CraftPotionUtil.fromBukkit(type)); - } - - if (hasColor()) { - builder.put(POTION_COLOR.BUKKIT, getColor()); - } - - if (hasCustomEffects()) { - builder.put(POTION_EFFECTS.BUKKIT, ImmutableList.copyOf(this.customEffects)); - } - - return builder; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSkull.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSkull.java deleted file mode 100644 index aee97b9f0..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSkull.java +++ /dev/null @@ -1,235 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableMap.Builder; -import com.mojang.authlib.GameProfile; -import java.util.Map; -import com.destroystokyo.paper.profile.CraftPlayerProfile; -import com.destroystokyo.paper.profile.PlayerProfile; -import net.minecraft.server.GameProfileSerializer; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.TileEntitySkull; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.SkullMeta; - -import javax.annotation.Nullable; -@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, CraftMagicNumbers.NBT.TAG_COMPOUND)) { - profile = GameProfileSerializer.deserialize(tag.getCompound(SKULL_OWNER.NBT)); - } else if (tag.hasKeyOfType(SKULL_OWNER.NBT, CraftMagicNumbers.NBT.TAG_STRING) && !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, Object context) { - super.deserializeInternal(tag, context); - - if (tag.hasKeyOfType(SKULL_PROFILE.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND)) { - 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(NBTTagCompound tag) { - super.applyToItem(tag); - - if (profile != null) { - // Fill in textures - // Must be done sync due to way client handles textures - profile = com.google.common.util.concurrent.Futures.getUnchecked(TileEntitySkull.b(profile, com.google.common.base.Predicates.alwaysTrue(), true)); // Spigot - - NBTTagCompound owner = new NBTTagCompound(); - GameProfileSerializer.serialize(owner, profile); - tag.set(SKULL_OWNER.NBT, owner); - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isSkullEmpty(); - } - - boolean isSkullEmpty() { - return profile == null; - } - - @Override - boolean applicableTo(Material type) { - switch (type) { - case CREEPER_HEAD: - case CREEPER_WALL_HEAD: - case DRAGON_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_HEAD: - case PLAYER_WALL_HEAD: - case SKELETON_SKULL: - case SKELETON_WALL_SKULL: - case WITHER_SKELETON_SKULL: - case WITHER_SKELETON_WALL_SKULL: - case ZOMBIE_HEAD: - case ZOMBIE_WALL_HEAD: - return true; - default: - return false; - } - } - - @Override - public CraftMetaSkull clone() { - return (CraftMetaSkull) super.clone(); - } - - @Override - public boolean hasOwner() { - return profile != null && profile.getName() != null; - } - - @Override - public String getOwner() { - return hasOwner() ? profile.getName() : null; - } - - // Paper start - @Override - public void setPlayerProfile(@Nullable PlayerProfile profile) { - this.profile = (profile == null) ? null : CraftPlayerProfile.asAuthlibCopy(profile); - } - - @Nullable - @Override - public PlayerProfile getPlayerProfile() { - return profile != null ? CraftPlayerProfile.asBukkitCopy(profile) : null; - } - // Paper end - - @Override - public OfflinePlayer getOwningPlayer() { - if (hasOwner()) { - if (profile.getId() != null) { - return Bukkit.getOfflinePlayer(profile.getId()); - } - - if (profile.getName() != null) { - return Bukkit.getOfflinePlayer(profile.getName()); - } - } - - return null; - } - - @Override - public boolean setOwner(String name) { - if (name != null && name.length() > MAX_OWNER_LENGTH) { - return false; - } - - if (name == null) { - profile = null; - } else { - // Paper start - Use Online Players Skull - GameProfile newProfile = null; - net.minecraft.server.EntityPlayer player = net.minecraft.server.MinecraftServer.getServer().getPlayerList().getPlayer(name); - if (player != null) newProfile = player.getProfile(); - if (newProfile == null) newProfile = new GameProfile(null, name); - profile = newProfile; - // Paper end - } - - return true; - } - - @Override - public boolean setOwningPlayer(OfflinePlayer owner) { - if (owner == null) { - profile = null; - } else if (owner instanceof CraftPlayer) { - profile = ((CraftPlayer) owner).getProfile(); - } else { - profile = new GameProfile(owner.getUniqueId(), owner.getName()); - } - - 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/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSpawnEgg.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSpawnEgg.java deleted file mode 100644 index 082f85119..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSpawnEgg.java +++ /dev/null @@ -1,271 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableMap.Builder; -import java.util.Map; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagCompound; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.util.CraftLegacy; -import org.bukkit.entity.EntityType; -import org.bukkit.inventory.meta.SpawnEggMeta; -import org.bukkit.material.MaterialData; - -@DelegateDeserialization(CraftMetaItem.SerializableMeta.class) -public class CraftMetaSpawnEgg extends CraftMetaItem implements SpawnEggMeta { - - static final ItemMetaKey ENTITY_TAG = new ItemMetaKey("EntityTag", "entity-tag"); - @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) - static final ItemMetaKey ENTITY_ID = new ItemMetaKey("id"); - - private EntityType spawnedType; - private NBTTagCompound entityTag; - - CraftMetaSpawnEgg(CraftMetaItem meta) { - super(meta); - - if (!(meta instanceof CraftMetaSpawnEgg)) { - return; - } - - CraftMetaSpawnEgg egg = (CraftMetaSpawnEgg) meta; - this.spawnedType = egg.spawnedType; - - updateMaterial(null); // Trigger type population - } - - CraftMetaSpawnEgg(NBTTagCompound tag) { - super(tag); - - if (tag.hasKey(ENTITY_TAG.NBT)) { - entityTag = tag.getCompound(ENTITY_TAG.NBT); - } - } - - CraftMetaSpawnEgg(Map map) { - super(map); - - String entityType = SerializableMeta.getString(map, ENTITY_ID.BUKKIT, true); - if (entityType != null) { - this.spawnedType = EntityType.fromName(entityType); - } - } - - @Override - void deserializeInternal(NBTTagCompound tag, Object context) { - super.deserializeInternal(tag, context); - - if (tag.hasKey(ENTITY_TAG.NBT)) { - entityTag = tag.getCompound(ENTITY_TAG.NBT); - - if (context instanceof Map) { - Map map = (Map) context; - - // Duplicated from constructor - String entityType = SerializableMeta.getString(map, ENTITY_ID.BUKKIT, true); - if (entityType != null) { - this.spawnedType = EntityType.fromName(entityType); - } - } - - if (this.spawnedType != null) { - // We have a valid spawn type, just remove the ID now - entityTag.remove(ENTITY_ID.NBT); - } - - // Tag still has some other data, lets try our luck with a conversion - if (!entityTag.isEmpty()) { - // SPIGOT-4128: This is hopeless until we start versioning stacks. RIP data. - // entityTag = (NBTTagCompound) MinecraftServer.getServer().dataConverterManager.update(DataConverterTypes.ENTITY, new Dynamic(DynamicOpsNBT.a, entityTag), -1, CraftMagicNumbers.DATA_VERSION).getValue(); - } - - // See if we can read a converted ID tag - if (entityTag.hasKey(ENTITY_ID.NBT)) { - this.spawnedType = EntityType.fromName(new MinecraftKey(entityTag.getString(ENTITY_ID.NBT)).getKey()); - } - } - } - - @Override - void serializeInternal(Map internalTags) { - if (entityTag != null && !entityTag.isEmpty()) { - internalTags.put(ENTITY_TAG.NBT, entityTag); - } - } - - @Override - void applyToItem(NBTTagCompound tag) { - super.applyToItem(tag); - - if (!isSpawnEggEmpty() && entityTag == null) { - entityTag = new NBTTagCompound(); - } - - if (entityTag != null) { - tag.set(ENTITY_TAG.NBT, entityTag); - } - } - - @Override - boolean applicableTo(Material type) { - switch (type) { - case BAT_SPAWN_EGG: - case BLAZE_SPAWN_EGG: - case CAT_SPAWN_EGG: - case CAVE_SPIDER_SPAWN_EGG: - case CHICKEN_SPAWN_EGG: - case COD_SPAWN_EGG: - case COW_SPAWN_EGG: - case CREEPER_SPAWN_EGG: - case DOLPHIN_SPAWN_EGG: - case DONKEY_SPAWN_EGG: - case DROWNED_SPAWN_EGG: - case ELDER_GUARDIAN_SPAWN_EGG: - case ENDERMAN_SPAWN_EGG: - case ENDERMITE_SPAWN_EGG: - case EVOKER_SPAWN_EGG: - case FOX_SPAWN_EGG: - case GHAST_SPAWN_EGG: - case GUARDIAN_SPAWN_EGG: - case HORSE_SPAWN_EGG: - case HUSK_SPAWN_EGG: - case LLAMA_SPAWN_EGG: - case MAGMA_CUBE_SPAWN_EGG: - case MOOSHROOM_SPAWN_EGG: - case MULE_SPAWN_EGG: - case OCELOT_SPAWN_EGG: - case PANDA_SPAWN_EGG: - case PARROT_SPAWN_EGG: - case PHANTOM_SPAWN_EGG: - case PIG_SPAWN_EGG: - case PILLAGER_SPAWN_EGG: - case POLAR_BEAR_SPAWN_EGG: - case PUFFERFISH_SPAWN_EGG: - case RABBIT_SPAWN_EGG: - case RAVAGER_SPAWN_EGG: - case SALMON_SPAWN_EGG: - case SHEEP_SPAWN_EGG: - case SHULKER_SPAWN_EGG: - case SILVERFISH_SPAWN_EGG: - case SKELETON_HORSE_SPAWN_EGG: - case SKELETON_SPAWN_EGG: - case SLIME_SPAWN_EGG: - case SPIDER_SPAWN_EGG: - case SQUID_SPAWN_EGG: - case STRAY_SPAWN_EGG: - case TRADER_LLAMA_SPAWN_EGG: - case TROPICAL_FISH_SPAWN_EGG: - case TURTLE_SPAWN_EGG: - case VEX_SPAWN_EGG: - case VILLAGER_SPAWN_EGG: - case VINDICATOR_SPAWN_EGG: - case WANDERING_TRADER_SPAWN_EGG: - case WITCH_SPAWN_EGG: - case WITHER_SKELETON_SPAWN_EGG: - case WOLF_SPAWN_EGG: - case ZOMBIE_HORSE_SPAWN_EGG: - case ZOMBIE_PIGMAN_SPAWN_EGG: - case ZOMBIE_SPAWN_EGG: - case ZOMBIE_VILLAGER_SPAWN_EGG: - return true; - default: - return false; - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isSpawnEggEmpty(); - } - - boolean isSpawnEggEmpty() { - return !(hasSpawnedType() || entityTag != null); - } - - boolean hasSpawnedType() { - return spawnedType != null; - } - - @Override - public EntityType getSpawnedType() { - throw new UnsupportedOperationException("Must check item type to get spawned type"); - } - - @Override - public void setSpawnedType(EntityType type) { - throw new UnsupportedOperationException("Must change item type to set spawned type"); - } - - @Override - boolean equalsCommon(CraftMetaItem meta) { - if (!super.equalsCommon(meta)) { - return false; - } - if (meta instanceof CraftMetaSpawnEgg) { - CraftMetaSpawnEgg that = (CraftMetaSpawnEgg) meta; - - return hasSpawnedType() ? that.hasSpawnedType() && this.spawnedType.equals(that.spawnedType) : !that.hasSpawnedType() - && entityTag != null ? that.entityTag != null && this.entityTag.equals(that.entityTag) : entityTag == null; - } - return true; - } - - @Override - boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaSpawnEgg || isSpawnEggEmpty()); - } - - @Override - int applyHash() { - final int original; - int hash = original = super.applyHash(); - - if (hasSpawnedType()) { - hash = 73 * hash + spawnedType.hashCode(); - } - if (entityTag != null) { - hash = 73 * hash + entityTag.hashCode(); - } - - return original != hash ? CraftMetaSpawnEgg.class.hashCode() ^ hash : hash; - } - - @Override - Builder serialize(Builder builder) { - super.serialize(builder); - - return builder; - } - - @Override - public CraftMetaSpawnEgg clone() { - CraftMetaSpawnEgg clone = (CraftMetaSpawnEgg) super.clone(); - - clone.spawnedType = spawnedType; - if (entityTag != null) { - clone.entityTag = entityTag.clone(); - } - - return clone; - } - - @Override - final Material updateMaterial(Material material) { - if (spawnedType == null) { - spawnedType = EntityType.fromId(getDamage()); - setDamage(0); - } - - if (spawnedType != null) { - if (entityTag != null) { - // Remove ID tag as it is now in the material - entityTag.remove(ENTITY_ID.NBT); - } - - return CraftLegacy.fromLegacy(new MaterialData(Material.LEGACY_MONSTER_EGG, (byte) spawnedType.getTypeId())); - } - - return super.updateMaterial(material); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java deleted file mode 100644 index 7ebc488fa..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java +++ /dev/null @@ -1,239 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -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.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.meta.SuspiciousStewMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -@DelegateDeserialization(CraftMetaItem.SerializableMeta.class) -public class CraftMetaSuspiciousStew extends CraftMetaItem implements SuspiciousStewMeta { - - static final ItemMetaKey DURATION = new ItemMetaKey("EffectDuration", "duration"); - static final ItemMetaKey EFFECTS = new ItemMetaKey("Effects", "effects"); - static final ItemMetaKey ID = new ItemMetaKey("EffectId", "id"); - - private List customEffects; - - CraftMetaSuspiciousStew(CraftMetaItem meta) { - super(meta); - if (!(meta instanceof CraftMetaSuspiciousStew)) { - return; - } - CraftMetaSuspiciousStew stewMeta = ((CraftMetaSuspiciousStew) meta); - if (stewMeta.hasCustomEffects()) { - this.customEffects = new ArrayList(stewMeta.customEffects); - } - } - - CraftMetaSuspiciousStew(NBTTagCompound tag) { - super(tag); - if (tag.hasKey(EFFECTS.NBT)) { - NBTTagList list = tag.getList(EFFECTS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); - int length = list.size(); - customEffects = new ArrayList(length); - - for (int i = 0; i < length; i++) { - NBTTagCompound effect = list.getCompound(i); - PotionEffectType type = PotionEffectType.getById(effect.getByte(ID.NBT)); - if (type == null) { - continue; - } - int duration = effect.getInt(DURATION.NBT); - customEffects.add(new PotionEffect(type, duration, 0)); - } - } - } - - CraftMetaSuspiciousStew(Map map) { - super(map); - - Iterable rawEffectList = SerializableMeta.getObject(Iterable.class, map, 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(EFFECTS.NBT, effectList); - - for (PotionEffect effect : customEffects) { - NBTTagCompound effectData = new NBTTagCompound(); - effectData.setByte(ID.NBT, ((byte) effect.getType().getId())); - effectData.setInt(DURATION.NBT, effect.getDuration()); - effectList.add(effectData); - } - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isStewEmpty(); - } - - boolean isStewEmpty() { - return !hasCustomEffects(); - } - - @Override - boolean applicableTo(Material type) { - return type == Material.SUSPICIOUS_STEW; - } - - @Override - public CraftMetaSuspiciousStew clone() { - CraftMetaSuspiciousStew clone = ((CraftMetaSuspiciousStew) super.clone()); - if (this.customEffects != null) { - clone.customEffects = new ArrayList(this.customEffects); - } - return clone; - } - - @Override - public boolean hasCustomEffects() { - return customEffects != null; - } - - @Override - public List getCustomEffects() { - if (hasCustomEffects()) { - return ImmutableList.copyOf(customEffects); - } - return ImmutableList.of(); - } - - @Override - 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.getDuration() == effect.getDuration()) { - return false; - } - customEffects.set(index, effect); - return true; - } else { - return false; - } - } else { - if (customEffects == null) { - customEffects = new ArrayList(); - } - customEffects.add(effect); - return true; - } - } - - @Override - 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 (type.equals(effect.getType())) { - iterator.remove(); - changed = true; - } - } - if (customEffects.isEmpty()) { - customEffects = null; - } - return changed; - } - - @Override - public boolean hasCustomEffect(PotionEffectType type) { - Validate.notNull(type, "Potion effect type must not be null"); - return indexOfEffect(type) != -1; - } - - 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; - } - - @Override - 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 ? CraftMetaSuspiciousStew.class.hashCode() ^ hash : hash; - } - - @Override - boolean equalsCommon(CraftMetaItem meta) { - if (!super.equalsCommon(meta)) { - return false; - } - if (meta instanceof CraftMetaSuspiciousStew) { - CraftMetaSuspiciousStew that = (CraftMetaSuspiciousStew) 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 CraftMetaSuspiciousStew || isStewEmpty()); - } - - @Override - Builder serialize(Builder builder) { - super.serialize(builder); - - if (hasCustomEffects()) { - builder.put(EFFECTS.BUKKIT, ImmutableList.copyOf(this.customEffects)); - } - - return builder; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaTropicalFishBucket.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaTropicalFishBucket.java deleted file mode 100644 index eee51f07a..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaTropicalFishBucket.java +++ /dev/null @@ -1,167 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import net.minecraft.server.NBTTagCompound; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.entity.CraftTropicalFish; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.entity.TropicalFish; -import org.bukkit.inventory.meta.TropicalFishBucketMeta; - -@DelegateDeserialization(SerializableMeta.class) -class CraftMetaTropicalFishBucket extends CraftMetaItem implements TropicalFishBucketMeta { - static final ItemMetaKey VARIANT = new ItemMetaKey("BucketVariantTag", "fish-variant"); - - private Integer variant; - - CraftMetaTropicalFishBucket(CraftMetaItem meta) { - super(meta); - - if (!(meta instanceof CraftMetaTropicalFishBucket)) { - return; - } - - CraftMetaTropicalFishBucket bucket = (CraftMetaTropicalFishBucket) meta; - this.variant = bucket.variant; - } - - CraftMetaTropicalFishBucket(NBTTagCompound tag) { - super(tag); - - if (tag.hasKeyOfType(VARIANT.NBT, CraftMagicNumbers.NBT.TAG_INT)) { - this.variant = tag.getInt(VARIANT.NBT); - } - } - - CraftMetaTropicalFishBucket(Map map) { - super(map); - - Integer variant = SerializableMeta.getObject(Integer.class, map, VARIANT.BUKKIT, true); - if (variant != null) { - this.variant = variant; - } - } - - @Override - void applyToItem(NBTTagCompound tag) { - super.applyToItem(tag); - - if (hasVariant()) { - tag.setInt(VARIANT.NBT, variant); - } - } - - @Override - boolean applicableTo(Material type) { - switch (type) { - case TROPICAL_FISH_BUCKET: - return true; - default: - return false; - } - } - - @Override - boolean isEmpty() { - return super.isEmpty() && isBucketEmpty(); - } - - boolean isBucketEmpty() { - return !(hasVariant()); - } - - @Override - public DyeColor getPatternColor() { - return CraftTropicalFish.getPatternColor(variant); - } - - @Override - public void setPatternColor(DyeColor color) { - if (variant == null) { - variant = 0; - } - variant = CraftTropicalFish.getData(color, getPatternColor(), getPattern()); - } - - @Override - public DyeColor getBodyColor() { - return CraftTropicalFish.getBodyColor(variant); - } - - @Override - public void setBodyColor(DyeColor color) { - if (variant == null) { - variant = 0; - } - variant = CraftTropicalFish.getData(getPatternColor(), color, getPattern()); - } - - @Override - public TropicalFish.Pattern getPattern() { - return CraftTropicalFish.getPattern(variant); - } - - @Override - public void setPattern(TropicalFish.Pattern pattern) { - if (variant == null) { - variant = 0; - } - variant = CraftTropicalFish.getData(getPatternColor(), getBodyColor(), pattern); - } - - @Override - public boolean hasVariant() { - return variant != null; - } - - @Override - boolean equalsCommon(CraftMetaItem meta) { - if (!super.equalsCommon(meta)) { - return false; - } - if (meta instanceof CraftMetaTropicalFishBucket) { - CraftMetaTropicalFishBucket that = (CraftMetaTropicalFishBucket) meta; - - return (hasVariant() ? that.hasVariant() && this.variant.equals(that.variant) : !that.hasVariant()); - } - return true; - } - - @Override - boolean notUncommon(CraftMetaItem meta) { - return super.notUncommon(meta) && (meta instanceof CraftMetaTropicalFishBucket || isBucketEmpty()); - } - - @Override - int applyHash() { - final int original; - int hash = original = super.applyHash(); - - if (hasVariant()) { - hash = 61 * hash + variant; - } - - return original != hash ? CraftMetaTropicalFishBucket.class.hashCode() ^ hash : hash; - } - - - @Override - public CraftMetaTropicalFishBucket clone() { - return (CraftMetaTropicalFishBucket) super.clone(); - } - - @Override - ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { - super.serialize(builder); - - if (hasVariant()) { - builder.put(VARIANT.BUKKIT, variant); - } - - return builder; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java deleted file mode 100644 index ef29599a8..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.ArrayList; -import java.util.List; -import net.minecraft.server.RecipeItemStack; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Recipe; -import org.bukkit.inventory.RecipeChoice; - -public interface CraftRecipe extends Recipe { - - void addToCraftingManager(); - - default RecipeItemStack toNMS(RecipeChoice bukkit, boolean requireNotEmpty) { - RecipeItemStack stack; - - if (bukkit == null) { - stack = RecipeItemStack.a; - } else if (bukkit instanceof RecipeChoice.MaterialChoice) { - stack = new RecipeItemStack(((RecipeChoice.MaterialChoice) bukkit).getChoices().stream().map((mat) -> new net.minecraft.server.RecipeItemStack.StackProvider(CraftItemStack.asNMSCopy(new ItemStack(mat))))); - } else if (bukkit instanceof RecipeChoice.ExactChoice) { - stack = new RecipeItemStack(((RecipeChoice.ExactChoice) bukkit).getChoices().stream().map((mat) -> new net.minecraft.server.RecipeItemStack.StackProvider(CraftItemStack.asNMSCopy(mat)))); - stack.exact = true; - } else { - throw new IllegalArgumentException("Unknown recipe stack instance " + bukkit); - } - - stack.buildChoices(); - if (requireNotEmpty && stack.choices.length == 0) { - throw new IllegalArgumentException("Recipe requires at least one non-air choice!"); - } - - return stack; - } - - public static RecipeChoice toBukkit(RecipeItemStack list) { - list.buildChoices(); - - if (list.choices.length == 0) { - return null; - } - - if (list.exact) { - List choices = new ArrayList<>(list.choices.length); - for (net.minecraft.server.ItemStack i : list.choices) { - choices.add(CraftItemStack.asBukkitCopy(i)); - } - - return new RecipeChoice.ExactChoice(choices); - } else { - - List choices = new ArrayList<>(list.choices.length); - for (net.minecraft.server.ItemStack i : list.choices) { - choices.add(CraftMagicNumbers.getMaterial(i.getItem())); - } - - return new RecipeChoice.MaterialChoice(choices); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftResultInventory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftResultInventory.java deleted file mode 100644 index ff7f589a2..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftResultInventory.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; -import org.bukkit.inventory.ItemStack; - -public class CraftResultInventory extends CraftInventory { - - private final IInventory resultInventory; - - public CraftResultInventory(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.isEmpty() ? null : CraftItemStack.asCraftMirror(item); - } else { - net.minecraft.server.ItemStack item = getResultInventory().getItem(slot - getIngredientsInventory().getSize()); - return item.isEmpty() ? null : CraftItemStack.asCraftMirror(item); - } - } - - @Override - public void setItem(int index, ItemStack item) { - if (index < getIngredientsInventory().getSize()) { - getIngredientsInventory().setItem(index, CraftItemStack.asNMSCopy(item)); - } else { - getResultInventory().setItem((index - getIngredientsInventory().getSize()), CraftItemStack.asNMSCopy(item)); - } - } - - @Override - public int getSize() { - return getResultInventory().getSize() + getIngredientsInventory().getSize(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSaddledInventory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftSaddledInventory.java deleted file mode 100644 index 99cfbaf90..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSaddledInventory.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.IInventory; - -import org.bukkit.inventory.AbstractHorseInventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.SaddledHorseInventory; - -public class CraftSaddledInventory extends CraftInventoryAbstractHorse implements SaddledHorseInventory { - - public CraftSaddledInventory(IInventory inventory) { - super(inventory); - } - -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java deleted file mode 100644 index 6dbd249f5..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Map; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.NonNullList; -import net.minecraft.server.RecipeItemStack; -import net.minecraft.server.ShapedRecipes; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; -import org.bukkit.inventory.ShapedRecipe; - -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(NamespacedKey key, ItemStack result) { - super(key, result); - } - - public CraftShapedRecipe(ItemStack result, ShapedRecipes recipe) { - this(CraftNamespacedKey.fromMinecraft(recipe.getKey()), result); - this.recipe = recipe; - } - - public static CraftShapedRecipe fromBukkitRecipe(ShapedRecipe recipe) { - if (recipe instanceof CraftShapedRecipe) { - return (CraftShapedRecipe) recipe; - } - CraftShapedRecipe ret = new CraftShapedRecipe(recipe.getKey(), recipe.getResult()); - ret.setGroup(recipe.getGroup()); - String[] shape = recipe.getShape(); - ret.shape(shape); - Map ingredientMap = recipe.getChoiceMap(); - for (char c : ingredientMap.keySet()) { - RecipeChoice stack = ingredientMap.get(c); - if (stack != null) { - ret.setIngredient(c, stack); - } - } - return ret; - } - - @Override - public void addToCraftingManager() { - String[] shape = this.getShape(); - Map ingred = this.getChoiceMap(); - int width = shape[0].length(); - NonNullList data = NonNullList.a(shape.length * width, RecipeItemStack.a); - - for (int i = 0; i < shape.length; i++) { - String row = shape[i]; - for (int j = 0; j < row.length(); j++) { - data.set(i * width + j, toNMS(ingred.get(row.charAt(j)), false)); - } - } - - MinecraftServer.getServer().getCraftingManager().addRecipe(new ShapedRecipes(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), width, shape.length, data, CraftItemStack.asNMSCopy(this.getResult()))); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java deleted file mode 100644 index 4aba511fe..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.List; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.NonNullList; -import net.minecraft.server.RecipeItemStack; -import net.minecraft.server.ShapelessRecipes; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; -import org.bukkit.inventory.ShapelessRecipe; - -public class CraftShapelessRecipe extends ShapelessRecipe implements CraftRecipe { - // TODO: Could eventually use this to add a matches() method or some such - private ShapelessRecipes recipe; - - public CraftShapelessRecipe(NamespacedKey key, ItemStack result) { - super(key, result); - } - - public CraftShapelessRecipe(ItemStack result, ShapelessRecipes recipe) { - this(CraftNamespacedKey.fromMinecraft(recipe.getKey()), result); - this.recipe = recipe; - } - - public static CraftShapelessRecipe fromBukkitRecipe(ShapelessRecipe recipe) { - if (recipe instanceof CraftShapelessRecipe) { - return (CraftShapelessRecipe) recipe; - } - CraftShapelessRecipe ret = new CraftShapelessRecipe(recipe.getKey(), recipe.getResult()); - ret.setGroup(recipe.getGroup()); - for (RecipeChoice ingred : recipe.getChoiceList()) { - ret.addIngredient(ingred); - } - return ret; - } - - @Override - public void addToCraftingManager() { - List ingred = this.getChoiceList(); - NonNullList data = NonNullList.a(ingred.size(), RecipeItemStack.a); - for (int i = 0; i < ingred.size(); i++) { - data.set(i, toNMS(ingred.get(i), true)); - } - - MinecraftServer.getServer().getCraftingManager().addRecipe(new ShapelessRecipes(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), CraftItemStack.asNMSCopy(this.getResult()), data)); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmokingRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmokingRecipe.java deleted file mode 100644 index 400437e2c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftSmokingRecipe.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.MinecraftServer; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; -import org.bukkit.inventory.SmokingRecipe; - -public class CraftSmokingRecipe extends SmokingRecipe implements CraftRecipe { - public CraftSmokingRecipe(NamespacedKey key, ItemStack result, RecipeChoice source, float experience, int cookingTime) { - super(key, result, source, experience, cookingTime); - } - - public static CraftSmokingRecipe fromBukkitRecipe(SmokingRecipe recipe) { - if (recipe instanceof CraftSmokingRecipe) { - return (CraftSmokingRecipe) recipe; - } - CraftSmokingRecipe ret = new CraftSmokingRecipe(recipe.getKey(), recipe.getResult(), recipe.getInputChoice(), recipe.getExperience(), recipe.getCookingTime()); - ret.setGroup(recipe.getGroup()); - return ret; - } - - @Override - public void addToCraftingManager() { - ItemStack result = this.getResult(); - - MinecraftServer.getServer().getCraftingManager().addRecipe(new net.minecraft.server.RecipeSmoking(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result), getExperience(), getCookingTime())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftStonecuttingRecipe.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftStonecuttingRecipe.java deleted file mode 100644 index 512a0e9d3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftStonecuttingRecipe.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.MinecraftServer; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.RecipeChoice; -import org.bukkit.inventory.StonecuttingRecipe; - -public class CraftStonecuttingRecipe extends StonecuttingRecipe implements CraftRecipe { - public CraftStonecuttingRecipe(NamespacedKey key, ItemStack result, RecipeChoice source) { - super(key, result, source); - } - - public static CraftStonecuttingRecipe fromBukkitRecipe(StonecuttingRecipe recipe) { - if (recipe instanceof CraftStonecuttingRecipe) { - return (CraftStonecuttingRecipe) recipe; - } - CraftStonecuttingRecipe ret = new CraftStonecuttingRecipe(recipe.getKey(), recipe.getResult(), recipe.getInputChoice()); - ret.setGroup(recipe.getGroup()); - return ret; - } - - @Override - public void addToCraftingManager() { - ItemStack result = this.getResult(); - - MinecraftServer.getServer().getCraftingManager().addRecipe(new net.minecraft.server.RecipeStonecutting(CraftNamespacedKey.toMinecraft(this.getKey()), this.getGroup(), toNMS(this.getInputChoice(), true), CraftItemStack.asNMSCopy(result))); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java b/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java deleted file mode 100644 index de558eef3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.ListIterator; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -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; - } - - @Override - public boolean hasNext() { - return nextIndex < inventory.getSize(); - } - - @Override - public ItemStack next() { - lastDirection = true; - return inventory.getItem(nextIndex++); - } - - @Override - public int nextIndex() { - return nextIndex; - } - - @Override - public boolean hasPrevious() { - return nextIndex > 0; - } - - @Override - public ItemStack previous() { - lastDirection = false; - return inventory.getItem(--nextIndex); - } - - @Override - public int previousIndex() { - return nextIndex - 1; - } - - @Override - public void set(ItemStack item) { - if (lastDirection == null) { - throw new IllegalStateException("No current item!"); - } - int i = lastDirection ? nextIndex - 1 : nextIndex; - inventory.setItem(i, item); - } - - @Override - public void add(ItemStack item) { - throw new UnsupportedOperationException("Can't change the size of an inventory!"); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Can't change the size of an inventory!"); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java b/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java deleted file mode 100644 index 1223bfc7f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import java.util.Iterator; -import java.util.Map; -import net.minecraft.server.IRecipe; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.Recipes; -import org.bukkit.inventory.Recipe; - -public class RecipeIterator implements Iterator { - private final Iterator, Object2ObjectLinkedOpenHashMap>>> recipes; - private Iterator> current; - - public RecipeIterator() { - this.recipes = MinecraftServer.getServer().getCraftingManager().recipes.entrySet().iterator(); - } - - @Override - public boolean hasNext() { - return (current != null && current.hasNext()) || recipes.hasNext(); - } - - @Override - public Recipe next() { - if (current == null || !current.hasNext()) { - current = recipes.next().getValue().values().iterator(); - } - - return current.next().toBukkitRecipe(); - } - - @Override - public void remove() { - if (current == null) { - throw new IllegalStateException("next() not yet called"); - } - - current.remove(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java deleted file mode 100644 index b2d113b48..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.bukkit.craftbukkit.inventory.tags; - -import org.apache.commons.lang3.Validate; -import org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer; -import org.bukkit.inventory.meta.tags.CustomItemTagContainer; -import org.bukkit.inventory.meta.tags.ItemTagType; -import org.bukkit.persistence.PersistentDataAdapterContext; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; - -public final class DeprecatedContainerTagType implements PersistentDataType { - - private final ItemTagType deprecated; - - DeprecatedContainerTagType(ItemTagType deprecated) { - this.deprecated = deprecated; - } - - @Override - public Class getPrimitiveType() { - return PersistentDataContainer.class; - } - - @Override - public Class getComplexType() { - return deprecated.getComplexType(); - } - - @Override - public PersistentDataContainer toPrimitive(Z complex, PersistentDataAdapterContext context) { - CustomItemTagContainer deprecated = this.deprecated.toPrimitive(complex, new DeprecatedItemAdapterContext(context)); - Validate.isInstanceOf(DeprecatedCustomTagContainer.class, deprecated, "Could not wrap deprecated API due to foreign CustomItemTagContainer implementation %s", deprecated.getClass().getSimpleName()); - - DeprecatedCustomTagContainer tagContainer = (DeprecatedCustomTagContainer) deprecated; - PersistentDataContainer wrapped = tagContainer.getWrapped(); - Validate.isInstanceOf(CraftPersistentDataContainer.class, wrapped, "Could not wrap deprecated API due to wrong deprecation wrapper %s", deprecated.getClass().getSimpleName()); - - CraftPersistentDataContainer craftTagContainer = (CraftPersistentDataContainer) wrapped; - return new CraftPersistentDataContainer(craftTagContainer.getRaw(), craftTagContainer.getDataTagTypeRegistry()); - } - - @Override - public Z fromPrimitive(PersistentDataContainer primitive, PersistentDataAdapterContext context) { - Validate.isInstanceOf(CraftPersistentDataContainer.class, primitive, "Could not wrap deprecated API due to foreign PersistentMetadataContainer implementation %s", primitive.getClass().getSimpleName()); - - return this.deprecated.fromPrimitive(new DeprecatedCustomTagContainer(primitive), new DeprecatedItemAdapterContext(context)); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedCustomTagContainer.java b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedCustomTagContainer.java deleted file mode 100644 index 3ef217b08..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedCustomTagContainer.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.bukkit.craftbukkit.inventory.tags; - -import java.util.Objects; -import org.bukkit.NamespacedKey; -import org.bukkit.inventory.meta.tags.CustomItemTagContainer; -import org.bukkit.inventory.meta.tags.ItemTagAdapterContext; -import org.bukkit.inventory.meta.tags.ItemTagType; -import org.bukkit.persistence.PersistentDataContainer; - -/** - * The {@link DeprecatedCustomTagContainer} is a simply wrapper implementation - * that wraps the new api to still be usable with the old api parts. - */ -@SuppressWarnings("unchecked") -public final class DeprecatedCustomTagContainer implements CustomItemTagContainer { - - private final PersistentDataContainer wrapped; - - public DeprecatedCustomTagContainer(PersistentDataContainer wrapped) { - this.wrapped = wrapped; - } - - @Override - public void setCustomTag(NamespacedKey key, ItemTagType type, Z value) { - if (Objects.equals(CustomItemTagContainer.class, type.getPrimitiveType())) { - wrapped.set(key, new DeprecatedContainerTagType<>((ItemTagType) type), value); - } else { - wrapped.set(key, new DeprecatedItemTagType<>(type), value); - } - } - - @Override - public boolean hasCustomTag(NamespacedKey key, ItemTagType type) { - if (Objects.equals(CustomItemTagContainer.class, type.getPrimitiveType())) { - return wrapped.has(key, new DeprecatedContainerTagType<>((ItemTagType) type)); - } else { - return wrapped.has(key, new DeprecatedItemTagType<>(type)); - } - } - - @Override - public Z getCustomTag(NamespacedKey key, ItemTagType type) { - if (Objects.equals(CustomItemTagContainer.class, type.getPrimitiveType())) { - return wrapped.get(key, new DeprecatedContainerTagType<>((ItemTagType) type)); - } else { - return wrapped.get(key, new DeprecatedItemTagType<>(type)); - } - } - - @Override - public void removeCustomTag(NamespacedKey key) { - wrapped.remove(key); - } - - @Override - public boolean isEmpty() { - return wrapped.isEmpty(); - } - - @Override - public ItemTagAdapterContext getAdapterContext() { - return new DeprecatedItemAdapterContext(this.wrapped.getAdapterContext()); - } - - public PersistentDataContainer getWrapped() { - return wrapped; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemAdapterContext.java b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemAdapterContext.java deleted file mode 100644 index e8bb75e9f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemAdapterContext.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bukkit.craftbukkit.inventory.tags; - -import org.bukkit.inventory.meta.tags.CustomItemTagContainer; -import org.bukkit.inventory.meta.tags.ItemTagAdapterContext; -import org.bukkit.persistence.PersistentDataAdapterContext; - -public final class DeprecatedItemAdapterContext implements ItemTagAdapterContext { - - private final PersistentDataAdapterContext context; - - public DeprecatedItemAdapterContext(PersistentDataAdapterContext context) { - this.context = context; - } - - /** - * Creates a new and empty tag container instance. - * - * @return the fresh container instance - */ - @Override - public CustomItemTagContainer newTagContainer() { - return new DeprecatedCustomTagContainer(context.newPersistentDataContainer()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemTagType.java b/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemTagType.java deleted file mode 100644 index 3e3d3804e..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedItemTagType.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.bukkit.craftbukkit.inventory.tags; - -import org.bukkit.inventory.meta.tags.ItemTagType; -import org.bukkit.persistence.PersistentDataAdapterContext; -import org.bukkit.persistence.PersistentDataType; - -public final class DeprecatedItemTagType implements PersistentDataType { - - private final ItemTagType deprecated; - - public DeprecatedItemTagType(ItemTagType deprecated) { - this.deprecated = deprecated; - } - - @Override - public Class getPrimitiveType() { - return deprecated.getPrimitiveType(); - } - - @Override - public Class getComplexType() { - return deprecated.getComplexType(); - } - - @Override - public T toPrimitive(Z complex, PersistentDataAdapterContext context) { - return this.deprecated.toPrimitive(complex, new DeprecatedItemAdapterContext(context)); - } - - @Override - public Z fromPrimitive(T primitive, PersistentDataAdapterContext context) { - return this.deprecated.fromPrimitive(primitive, new DeprecatedItemAdapterContext(context)); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftCustomInventoryConverter.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftCustomInventoryConverter.java deleted file mode 100644 index ed4415f6d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftCustomInventoryConverter.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.craftbukkit.inventory.util; - -import org.bukkit.craftbukkit.inventory.CraftInventoryCustom; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; - -public class CraftCustomInventoryConverter implements CraftInventoryCreator.InventoryConverter { - - @Override - public Inventory createInventory(InventoryHolder holder, InventoryType type) { - return new CraftInventoryCustom(holder, type); - } - - @Override - public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { - return new CraftInventoryCustom(owner, type, title); - } - - public Inventory createInventory(InventoryHolder owner, int size) { - return new CraftInventoryCustom(owner, size); - } - - public Inventory createInventory(InventoryHolder owner, int size, String title) { - return new CraftInventoryCustom(owner, size, title); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java deleted file mode 100644 index ae280dd40..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit.craftbukkit.inventory.util; - -import java.util.HashMap; -import java.util.Map; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; - -public final class CraftInventoryCreator { - - public static final CraftInventoryCreator INSTANCE = new CraftInventoryCreator(); - // - private final CraftCustomInventoryConverter DEFAULT_CONVERTER = new CraftCustomInventoryConverter(); - private final Map converterMap = new HashMap<>(); - - private CraftInventoryCreator() { - converterMap.put(InventoryType.CHEST, DEFAULT_CONVERTER); - converterMap.put(InventoryType.DISPENSER, new CraftTileInventoryConverter.Dispenser()); - converterMap.put(InventoryType.DROPPER, new CraftTileInventoryConverter.Dropper()); - converterMap.put(InventoryType.FURNACE, new CraftTileInventoryConverter.Furnace()); - converterMap.put(InventoryType.WORKBENCH, DEFAULT_CONVERTER); - converterMap.put(InventoryType.ENCHANTING, DEFAULT_CONVERTER); - converterMap.put(InventoryType.BREWING, new CraftTileInventoryConverter.BrewingStand()); - converterMap.put(InventoryType.PLAYER, DEFAULT_CONVERTER); - converterMap.put(InventoryType.MERCHANT, DEFAULT_CONVERTER); - converterMap.put(InventoryType.ENDER_CHEST, DEFAULT_CONVERTER); - converterMap.put(InventoryType.ANVIL, DEFAULT_CONVERTER); - converterMap.put(InventoryType.BEACON, DEFAULT_CONVERTER); - converterMap.put(InventoryType.HOPPER, new CraftTileInventoryConverter.Hopper()); - converterMap.put(InventoryType.SHULKER_BOX, DEFAULT_CONVERTER); - converterMap.put(InventoryType.BARREL, DEFAULT_CONVERTER); - converterMap.put(InventoryType.BLAST_FURNACE, new CraftTileInventoryConverter.BlastFurnace()); - converterMap.put(InventoryType.LECTERN, new CraftTileInventoryConverter.Lectern()); - converterMap.put(InventoryType.SMOKER, new CraftTileInventoryConverter.Smoker()); - converterMap.put(InventoryType.LOOM, DEFAULT_CONVERTER); - converterMap.put(InventoryType.CARTOGRAPHY, DEFAULT_CONVERTER); - converterMap.put(InventoryType.GRINDSTONE, DEFAULT_CONVERTER); - converterMap.put(InventoryType.STONECUTTER, DEFAULT_CONVERTER); - } - - public Inventory createInventory(InventoryHolder holder, InventoryType type) { - // Paper start - if (holder != null) { - return DEFAULT_CONVERTER.createInventory(holder, type); - } - //noinspection ConstantConditions // Paper end - return converterMap.get(type).createInventory(holder, type); - } - - public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { - // Paper start - if (holder != null) { - return DEFAULT_CONVERTER.createInventory(holder, type, title); - } - //noinspection ConstantConditions // Paper end - return converterMap.get(type).createInventory(holder, type, title); - } - - public Inventory createInventory(InventoryHolder holder, int size) { - return DEFAULT_CONVERTER.createInventory(holder, size); - } - - public Inventory createInventory(InventoryHolder holder, int size, String title) { - return DEFAULT_CONVERTER.createInventory(holder, size, title); - } - - public interface InventoryConverter { - - Inventory createInventory(InventoryHolder holder, InventoryType type); - - Inventory createInventory(InventoryHolder holder, InventoryType type, String title); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java deleted file mode 100644 index f6fa0650f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java +++ /dev/null @@ -1,139 +0,0 @@ -package org.bukkit.craftbukkit.inventory.util; - -import net.minecraft.server.DimensionManager; -import net.minecraft.server.IInventory; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.TileEntityBlastFurnace; -import net.minecraft.server.TileEntityBrewingStand; -import net.minecraft.server.TileEntityDispenser; -import net.minecraft.server.TileEntityDropper; -import net.minecraft.server.TileEntityFurnace; -import net.minecraft.server.TileEntityFurnaceFurnace; -import net.minecraft.server.TileEntityHopper; -import net.minecraft.server.TileEntityLectern; -import net.minecraft.server.TileEntityLootable; -import net.minecraft.server.TileEntitySmoker; -import org.bukkit.craftbukkit.inventory.CraftInventory; -import org.bukkit.craftbukkit.inventory.CraftInventoryBrewer; -import org.bukkit.craftbukkit.inventory.CraftInventoryFurnace; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; - -public abstract class CraftTileInventoryConverter implements CraftInventoryCreator.InventoryConverter { - - public abstract IInventory getTileEntity(); - - @Override - public Inventory createInventory(InventoryHolder holder, InventoryType type) { - return getInventory(getTileEntity()); - } - - @Override - public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { - IInventory te = getTileEntity(); - if (te instanceof TileEntityLootable) { - ((TileEntityLootable) te).setCustomName(CraftChatMessage.fromStringOrNull(title)); - } - - return getInventory(te); - } - - public Inventory getInventory(IInventory tileEntity) { - return new CraftInventory(tileEntity); - } - - public static class Furnace extends CraftTileInventoryConverter { - - @Override - public IInventory getTileEntity() { - TileEntityFurnace furnace = new TileEntityFurnaceFurnace(); - furnace.setWorld(MinecraftServer.getServer().getWorldServer(DimensionManager.OVERWORLD)); // TODO: customize this if required - return furnace; - } - - @Override - public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { - IInventory tileEntity = getTileEntity(); - ((TileEntityFurnace) tileEntity).setCustomName(CraftChatMessage.fromStringOrNull(title)); - return getInventory(tileEntity); - } - - @Override - public Inventory getInventory(IInventory tileEntity) { - return new CraftInventoryFurnace((TileEntityFurnace) tileEntity); - } - } - - public static class BrewingStand extends CraftTileInventoryConverter { - - @Override - public IInventory getTileEntity() { - return new TileEntityBrewingStand(); - } - - @Override - public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { - // BrewingStand does not extend TileEntityLootable - IInventory tileEntity = getTileEntity(); - if (tileEntity instanceof TileEntityBrewingStand) { - ((TileEntityBrewingStand) tileEntity).setCustomName(CraftChatMessage.fromStringOrNull(title)); - } - return getInventory(tileEntity); - } - - @Override - public Inventory getInventory(IInventory tileEntity) { - return new CraftInventoryBrewer(tileEntity); - } - } - - public static class Dispenser extends CraftTileInventoryConverter { - - @Override - public IInventory getTileEntity() { - return new TileEntityDispenser(); - } - } - - public static class Dropper extends CraftTileInventoryConverter { - - @Override - public IInventory getTileEntity() { - return new TileEntityDropper(); - } - } - - public static class Hopper extends CraftTileInventoryConverter { - - @Override - public IInventory getTileEntity() { - return new TileEntityHopper(); - } - } - - public static class BlastFurnace extends CraftTileInventoryConverter { - - @Override - public IInventory getTileEntity() { - return new TileEntityBlastFurnace(); - } - } - - public static class Lectern extends CraftTileInventoryConverter { - - @Override - public IInventory getTileEntity() { - return new TileEntityLectern().inventory; - } - } - - public static class Smoker extends CraftTileInventoryConverter { - - @Override - public IInventory getTileEntity() { - return new TileEntitySmoker(); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java deleted file mode 100644 index 04b3ab0b4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.bukkit.craftbukkit.map; - -import java.awt.Image; -import java.util.Arrays; -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; - -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); - } - - @Override - public CraftMapView getMapView() { - return mapView; - } - - @Override - public MapCursorCollection getCursors() { - return cursors; - } - - @Override - public void setCursors(MapCursorCollection cursors) { - this.cursors = cursors; - } - - @Override - 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); - } - } - - @Override - public byte getPixel(int x, int y) { - if (x < 0 || y < 0 || x >= 128 || y >= 128) - return 0; - return buffer[y * 128 + x]; - } - - @Override - 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; - } - - @Override - 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]); - } - } - } - - @Override - 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 ex) {} - } - throw new IllegalArgumentException("Text contains unterminated color string"); - } - - 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/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java deleted file mode 100644 index 93b39092c..000000000 --- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bukkit.craftbukkit.map; - -import net.minecraft.server.MapIcon; -import net.minecraft.server.WorldMap; -import org.bukkit.Bukkit; -import org.bukkit.craftbukkit.util.CraftChatMessage; -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; - -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 (Object key : worldMap.decorations.keySet()) { - // If this cursor is for a player check visibility with vanish system - Player other = Bukkit.getPlayerExact((String) key); - if (other != null && !player.canSee(other)) { - continue; - } - - MapIcon decoration = (MapIcon) worldMap.decorations.get(key); - cursors.addCursor(decoration.getX(), decoration.getY(), (byte) (decoration.getRotation() & 15), decoration.getType().a(), true, CraftChatMessage.fromComponent(decoration.getName())); - } - } - -} diff --git a/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java deleted file mode 100644 index f44ef67af..000000000 --- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java +++ /dev/null @@ -1,208 +0,0 @@ -package org.bukkit.craftbukkit.map; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import net.minecraft.server.DimensionManager; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.WorldMap; -import net.minecraft.server.WorldServer; -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; - -public final class CraftMapView implements MapView { - - private final Map renderCache = new HashMap(); - private final List renderers = new ArrayList(); - private final Map> canvases = new HashMap>(); - protected final WorldMap worldMap; - - public CraftMapView(WorldMap worldMap) { - this.worldMap = worldMap; - addRenderer(new CraftMapRenderer(this, worldMap)); - } - - @Override - public int getId() { - String text = worldMap.getId(); - if (text.startsWith("map_")) { - try { - return Integer.parseInt(text.substring("map_".length())); - } - catch (NumberFormatException ex) { - throw new IllegalStateException("Map has non-numeric ID"); - } - } else { - throw new IllegalStateException("Map has invalid ID"); - } - } - - @Override - public boolean isVirtual() { - return renderers.size() > 0 && !(renderers.get(0) instanceof CraftMapRenderer); - } - - @Override - public Scale getScale() { - return Scale.valueOf(worldMap.scale); - } - - @Override - public void setScale(Scale scale) { - worldMap.scale = scale.getValue(); - } - - @Override - public World getWorld() { - DimensionManager dimension = worldMap.map; - WorldServer world = MinecraftServer.getServer().getWorldServer(dimension); - - return (world == null) ? null : world.getWorld(); - } - - @Override - public void setWorld(World world) { - worldMap.map = ((CraftWorld) world).getHandle().getWorldProvider().getDimensionManager(); - } - - @Override - public int getCenterX() { - return worldMap.centerX; - } - - @Override - public int getCenterZ() { - return worldMap.centerZ; - } - - @Override - public void setCenterX(int x) { - worldMap.centerX = x; - } - - @Override - public void setCenterZ(int z) { - worldMap.centerZ = z; - } - - @Override - public List getRenderers() { - return new ArrayList(renderers); - } - - @Override - public void addRenderer(MapRenderer renderer) { - if (!renderers.contains(renderer)) { - renderers.add(renderer); - canvases.put(renderer, new HashMap()); - renderer.initialize(this); - } - } - - @Override - 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.containsKey(null)) { - 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); - try { - renderer.render(this, canvas, player); - } catch (Throwable ex) { - Bukkit.getLogger().log(Level.SEVERE, "Could not render map using renderer " + renderer.getClass().getName(), ex); - } - - byte[] buf = canvas.getBuffer(); - for (int i = 0; i < buf.length; ++i) { - byte color = buf[i]; - // There are 208 valid color id's, 0 -> 127 and -128 -> -49 - if (color >= 0 || color <= -49) render.buffer[i] = color; - } - - for (int i = 0; i < canvas.getCursors().size(); ++i) { - render.cursors.add(canvas.getCursors().getCursor(i)); - } - } - - return render; - } - - @Override - public boolean isTrackingPosition() { - return worldMap.track; - } - - @Override - public void setTrackingPosition(boolean trackingPosition) { - worldMap.track = trackingPosition; - } - - @Override - public boolean isUnlimitedTracking() { - return worldMap.unlimitedTracking; - } - - @Override - public void setUnlimitedTracking(boolean unlimited) { - worldMap.unlimitedTracking = unlimited; - } - - @Override - public boolean isLocked() { - return worldMap.locked; - } - - @Override - public void setLocked(boolean locked) { - worldMap.locked = locked; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/map/RenderData.java b/src/main/java/org/bukkit/craftbukkit/map/RenderData.java deleted file mode 100644 index 5768cd512..000000000 --- a/src/main/java/org/bukkit/craftbukkit/map/RenderData.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bukkit.craftbukkit.map; - -import java.util.ArrayList; -import org.bukkit.map.MapCursor; - -public class RenderData { - - public byte[] buffer; // Paper - public final ArrayList cursors; - - public RenderData() { - this.buffer = new byte[128 * 128]; - this.cursors = new ArrayList(); - } - -} diff --git a/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java b/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java deleted file mode 100644 index 6441d0e04..000000000 --- a/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.bukkit.craftbukkit.metadata; - -import java.util.List; -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; - -/** - * 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 Integer.toString(block.getX()) + ":" + Integer.toString(block.getY()) + ":" + Integer.toString(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/src/main/java/org/bukkit/craftbukkit/metadata/EntityMetadataStore.java b/src/main/java/org/bukkit/craftbukkit/metadata/EntityMetadataStore.java deleted file mode 100644 index 35c484f46..000000000 --- a/src/main/java/org/bukkit/craftbukkit/metadata/EntityMetadataStore.java +++ /dev/null @@ -1,23 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/metadata/PlayerMetadataStore.java b/src/main/java/org/bukkit/craftbukkit/metadata/PlayerMetadataStore.java deleted file mode 100644 index bac5c9e43..000000000 --- a/src/main/java/org/bukkit/craftbukkit/metadata/PlayerMetadataStore.java +++ /dev/null @@ -1,23 +0,0 @@ -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 - * UUID. - * @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.getUniqueId() + ":" + metadataKey; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/metadata/WorldMetadataStore.java b/src/main/java/org/bukkit/craftbukkit/metadata/WorldMetadataStore.java deleted file mode 100644 index dd37ed294..000000000 --- a/src/main/java/org/bukkit/craftbukkit/metadata/WorldMetadataStore.java +++ /dev/null @@ -1,22 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataAdapterContext.java b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataAdapterContext.java deleted file mode 100644 index 6371f6836..000000000 --- a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataAdapterContext.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.persistence; - -import org.bukkit.persistence.PersistentDataAdapterContext; - -public final class CraftPersistentDataAdapterContext implements PersistentDataAdapterContext { - - private final CraftPersistentDataTypeRegistry registry; - - public CraftPersistentDataAdapterContext(CraftPersistentDataTypeRegistry registry) { - this.registry = registry; - } - - /** - * Creates a new and empty tag container instance - * - * @return the fresh container instance - */ - @Override - public CraftPersistentDataContainer newPersistentDataContainer() { - return new CraftPersistentDataContainer(this.registry); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java deleted file mode 100644 index 6c6540dd3..000000000 --- a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.bukkit.craftbukkit.persistence; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagCompound; -import org.apache.commons.lang.Validate; -import org.bukkit.NamespacedKey; -import org.bukkit.craftbukkit.util.CraftNBTTagConfigSerializer; -import org.bukkit.persistence.PersistentDataAdapterContext; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; - -public final class CraftPersistentDataContainer implements PersistentDataContainer { - - private final Map customDataTags = new HashMap<>(); - private final CraftPersistentDataTypeRegistry registry; - private final CraftPersistentDataAdapterContext adapterContext; - - public CraftPersistentDataContainer(Map customTags, CraftPersistentDataTypeRegistry registry) { - this(registry); - this.customDataTags.putAll(customTags); - } - - public CraftPersistentDataContainer(CraftPersistentDataTypeRegistry registry) { - this.registry = registry; - this.adapterContext = new CraftPersistentDataAdapterContext(this.registry); - } - - @Override - public void set(NamespacedKey key, PersistentDataType type, Z value) { - Validate.notNull(key, "The provided key for the custom value was null"); - Validate.notNull(type, "The provided type for the custom value was null"); - Validate.notNull(value, "The provided value for the custom value was null"); - - this.customDataTags.put(key.toString(), registry.wrap(type.getPrimitiveType(), type.toPrimitive(value, adapterContext))); - } - - @Override - public boolean has(NamespacedKey key, PersistentDataType type) { - Validate.notNull(key, "The provided key for the custom value was null"); - Validate.notNull(type, "The provided type for the custom value was null"); - - NBTBase value = this.customDataTags.get(key.toString()); - if (value == null) { - return false; - } - - return registry.isInstanceOf(type.getPrimitiveType(), value); - } - - @Override - public Z get(NamespacedKey key, PersistentDataType type) { - Validate.notNull(key, "The provided key for the custom value was null"); - Validate.notNull(type, "The provided type for the custom value was null"); - - NBTBase value = this.customDataTags.get(key.toString()); - if (value == null) { - return null; - } - - return type.fromPrimitive(registry.extract(type.getPrimitiveType(), value), adapterContext); - } - - @Override - public Z getOrDefault(NamespacedKey key, PersistentDataType type, Z defaultValue) { - Z z = get(key, type); - return z != null ? z : defaultValue; - } - - @Override - public void remove(NamespacedKey key) { - Validate.notNull(key, "The provided key for the custom value was null"); - - this.customDataTags.remove(key.toString()); - } - - @Override - public boolean isEmpty() { - return this.customDataTags.isEmpty(); - } - - @Override - public PersistentDataAdapterContext getAdapterContext() { - return this.adapterContext; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof CraftPersistentDataContainer)) { - return false; - } - - Map myRawMap = getRaw(); - Map theirRawMap = ((CraftPersistentDataContainer) obj).getRaw(); - - return Objects.equals(myRawMap, theirRawMap); - } - - public NBTTagCompound toTagCompound() { - NBTTagCompound tag = new NBTTagCompound(); - for (Entry entry : this.customDataTags.entrySet()) { - tag.set(entry.getKey(), entry.getValue()); - } - return tag; - } - - public void put(String key, NBTBase base) { - this.customDataTags.put(key, base); - } - - public void putAll(Map map) { - this.customDataTags.putAll(map); - } - - public void putAll(NBTTagCompound compound) { - for (String key : compound.getKeys()) { - this.customDataTags.put(key, compound.get(key)); - } - } - - public Map getRaw() { - return this.customDataTags; - } - - public CraftPersistentDataTypeRegistry getDataTagTypeRegistry() { - return registry; - } - - @Override - public int hashCode() { - int hashCode = 3; - hashCode += this.customDataTags.hashCode(); // We will simply add the maps hashcode - return hashCode; - } - - public Map serialize() { - return (Map) CraftNBTTagConfigSerializer.serialize(toTagCompound()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java b/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java deleted file mode 100644 index 0bf63e459..000000000 --- a/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java +++ /dev/null @@ -1,229 +0,0 @@ -package org.bukkit.craftbukkit.persistence; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; -import com.google.common.primitives.Primitives; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagByte; -import net.minecraft.server.NBTTagByteArray; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NBTTagDouble; -import net.minecraft.server.NBTTagFloat; -import net.minecraft.server.NBTTagInt; -import net.minecraft.server.NBTTagIntArray; -import net.minecraft.server.NBTTagLong; -import net.minecraft.server.NBTTagLongArray; -import net.minecraft.server.NBTTagShort; -import net.minecraft.server.NBTTagString; -import org.apache.commons.lang3.Validate; -import org.bukkit.persistence.PersistentDataContainer; - -/** - * This class represents a registry that contains the used adapters for. - */ -public final class CraftPersistentDataTypeRegistry { - - private final Function CREATE_ADAPTER = this::createAdapter; - - private class TagAdapter { - - private final Function builder; - private final Function extractor; - - private final Class primitiveType; - private final Class nbtBaseType; - - public TagAdapter(Class primitiveType, Class nbtBaseType, Function builder, Function extractor) { - this.primitiveType = primitiveType; - this.nbtBaseType = nbtBaseType; - this.builder = builder; - this.extractor = extractor; - } - - /** - * This method will extract the value stored in the tag, according to - * the expected primitive type. - * - * @param base the base to extract from - * - * @return the value stored inside of the tag - * - * @throws ClassCastException if the passed base is not an instanced of - * the defined base type and therefore is not applicable to the - * extractor function - */ - T extract(NBTBase base) { - Validate.isInstanceOf(nbtBaseType, base, "The provided NBTBase was of the type %s. Expected type %s", base.getClass().getSimpleName(), nbtBaseType.getSimpleName()); - return this.extractor.apply(nbtBaseType.cast(base)); - } - - /** - * Builds a tag instance wrapping around the provided value object. - * - * @param value the value to store inside the created tag - * - * @return the new tag instance - * - * @throws ClassCastException if the passed value object is not of the - * defined primitive type and therefore is not applicable to the builder - * function - */ - Z build(Object value) { - Validate.isInstanceOf(primitiveType, value, "The provided value was of the type %s. Expected type %s", value.getClass().getSimpleName(), primitiveType.getSimpleName()); - return this.builder.apply(primitiveType.cast(value)); - } - - /** - * Returns if the tag instance matches the adapters one. - * - * @param base the base to check - * - * @return if the tag was an instance of the set type - */ - boolean isInstance(NBTBase base) { - return this.nbtBaseType.isInstance(base); - } - } - - private final Map adapters = new HashMap<>(); - - /** - * Creates a suitable adapter instance for the primitive class type - * - * @param type the type to create an adapter for - * @param the generic type of that class - * - * @return the created adapter instance - * - * @throws IllegalArgumentException if no suitable tag type adapter for this - * type was found - */ - private TagAdapter createAdapter(Class type) { - if (!Primitives.isWrapperType(type)) { - type = Primitives.wrap(type); //Make sure we will always "switch" over the wrapper types - } - - /* - Primitives - */ - if (Objects.equals(Byte.class, type)) { - return createAdapter(Byte.class, NBTTagByte.class, NBTTagByte::new, NBTTagByte::asByte); - } - if (Objects.equals(Short.class, type)) { - return createAdapter(Short.class, NBTTagShort.class, NBTTagShort::new, NBTTagShort::asShort); - } - if (Objects.equals(Integer.class, type)) { - return createAdapter(Integer.class, NBTTagInt.class, NBTTagInt::new, NBTTagInt::asInt); - } - if (Objects.equals(Long.class, type)) { - return createAdapter(Long.class, NBTTagLong.class, NBTTagLong::new, NBTTagLong::asLong); - } - if (Objects.equals(Float.class, type)) { - return createAdapter(Float.class, NBTTagFloat.class, NBTTagFloat::new, NBTTagFloat::asFloat); - } - if (Objects.equals(Double.class, type)) { - return createAdapter(Double.class, NBTTagDouble.class, NBTTagDouble::new, NBTTagDouble::asDouble); - } - - /* - String - */ - if (Objects.equals(String.class, type)) { - return createAdapter(String.class, NBTTagString.class, NBTTagString::new, NBTTagString::asString); - } - - /* - Primitive Arrays - */ - if (Objects.equals(byte[].class, type)) { - return createAdapter(byte[].class, NBTTagByteArray.class, array -> new NBTTagByteArray(Arrays.copyOf(array, array.length)), n -> Arrays.copyOf(n.getBytes(), n.size())); - } - if (Objects.equals(int[].class, type)) { - return createAdapter(int[].class, NBTTagIntArray.class, array -> new NBTTagIntArray(Arrays.copyOf(array, array.length)), n -> Arrays.copyOf(n.getInts(), n.size())); - } - if (Objects.equals(long[].class, type)) { - return createAdapter(long[].class, NBTTagLongArray.class, array -> new NBTTagLongArray(Arrays.copyOf(array, array.length)), n -> Arrays.copyOf(n.getLongs(), n.size())); - } - - /* - Note that this will map the interface PersistentMetadataContainer directly to the CraftBukkit implementation - Passing any other instance of this form to the tag type registry will throw a ClassCastException as defined in TagAdapter#build - */ - if (Objects.equals(PersistentDataContainer.class, type)) { - return createAdapter(CraftPersistentDataContainer.class, NBTTagCompound.class, CraftPersistentDataContainer::toTagCompound, tag -> { - CraftPersistentDataContainer container = new CraftPersistentDataContainer(this); - for (String key : tag.getKeys()) { - container.put(key, tag.get(key)); - } - return container; - }); - } - - throw new IllegalArgumentException("Could not find a valid TagAdapter implementation for the requested type " + type.getSimpleName()); - } - - private TagAdapter createAdapter(Class primitiveType, Class nbtBaseType, Function builder, Function extractor) { - return new TagAdapter<>(primitiveType, nbtBaseType, builder, extractor); - } - - /** - * Wraps the passed value into a tag instance. - * - * @param type the type of the passed value - * @param value the value to be stored in the tag - * @param the generic type of the value - * - * @return the created tag instance - * - * @throws IllegalArgumentException if no suitable tag type adapter for this - * type was found - */ - public NBTBase wrap(Class type, T value) { - return this.adapters.computeIfAbsent(type, CREATE_ADAPTER).build(value); - } - - /** - * Returns if the tag instance matches the provided primitive type. - * - * @param type the type of the primitive value - * @param base the base instance to check - * @param the generic type of the type - * - * @return if the base stores values of the primitive type passed - * - * @throws IllegalArgumentException if no suitable tag type adapter for this - * type was found - */ - public boolean isInstanceOf(Class type, NBTBase base) { - return this.adapters.computeIfAbsent(type, CREATE_ADAPTER).isInstance(base); - } - - /** - * Extracts the value out of the provided tag. - * - * @param type the type of the value to extract - * @param tag the tag to extract the value from - * @param the generic type of the value stored inside the tag - * - * @return the extracted value - * - * @throws IllegalArgumentException if the passed base is not an instanced - * of the defined base type and therefore is not applicable to the extractor - * function - * @throws IllegalArgumentException if the found object is not of type - * passed - * @throws IllegalArgumentException if no suitable tag type adapter for this - * type was found - */ - public T extract(Class type, NBTBase tag) throws ClassCastException, IllegalArgumentException { - TagAdapter adapter = this.adapters.computeIfAbsent(type, CREATE_ADAPTER); - Validate.isTrue(adapter.isInstance(tag), "`The found tag instance cannot store %s as it is a %s", type.getSimpleName(), tag.getClass().getSimpleName()); - - Object foundValue = adapter.extract(tag); - Validate.isInstanceOf(type, foundValue, "The found object is of the type %s. Expected type %s", foundValue.getClass().getSimpleName(), type.getSimpleName()); - return type.cast(foundValue); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionBrewer.java b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionBrewer.java deleted file mode 100644 index 87d680a87..000000000 --- a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionBrewer.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bukkit.craftbukkit.potion; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Maps; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import net.minecraft.server.MobEffect; -import net.minecraft.server.PotionRegistry; -import org.bukkit.potion.PotionBrewer; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionType; - -public class CraftPotionBrewer implements PotionBrewer { - private static final Map> cache = Maps.newHashMap(); - - @Override - public Collection getEffects(PotionType damage, boolean upgraded, boolean extended) { - if (cache.containsKey(damage)) - return cache.get(damage); - - List mcEffects = PotionRegistry.a(CraftPotionUtil.fromBukkit(new PotionData(damage, extended, upgraded))).a(); - - ImmutableList.Builder builder = new ImmutableList.Builder(); - for (MobEffect effect : mcEffects) { - builder.add(CraftPotionUtil.toBukkit(effect)); - } - - cache.put(damage, builder.build()); - - return cache.get(damage); - } - - @Override - public Collection getEffectsFromDamage(int damage) { - return new ArrayList(); - } - - @Override - public PotionEffect createEffect(PotionEffectType potion, int duration, int amplifier) { - return new PotionEffect(potion, potion.isInstant() ? 1 : (int) (duration * potion.getDurationModifier()), amplifier); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java deleted file mode 100644 index 082b0fdf9..000000000 --- a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.bukkit.craftbukkit.potion; - -import net.minecraft.server.MobEffectList; -import org.bukkit.Color; -import org.bukkit.potion.PotionEffectType; - -public class CraftPotionEffectType extends PotionEffectType { - private final MobEffectList handle; - - public CraftPotionEffectType(MobEffectList handle) { - super(MobEffectList.getId(handle)); - this.handle = handle; - } - - @Override - public double getDurationModifier() { - return 1.0D; - } - - public MobEffectList getHandle() { - return handle; - } - - @Override - public String getName() { - switch (getId()) { - 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"; - case 24: - return "GLOWING"; - case 25: - return "LEVITATION"; - case 26: - return "LUCK"; - case 27: - return "UNLUCK"; - case 28: - return "SLOW_FALLING"; - case 29: - return "CONDUIT_POWER"; - case 30: - return "DOLPHINS_GRACE"; - case 31: - return "BAD_OMEN"; - case 32: - return "HERO_OF_THE_VILLAGE"; - default: - return "UNKNOWN_EFFECT_TYPE_" + getId(); - } - } - - @Override - public boolean isInstant() { - return handle.isInstant(); - } - - @Override - public Color getColor() { - return Color.fromRGB(handle.getColor()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionUtil.java b/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionUtil.java deleted file mode 100644 index c1e0863c4..000000000 --- a/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionUtil.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.bukkit.craftbukkit.potion; - -import com.google.common.base.Preconditions; -import com.google.common.collect.BiMap; -import com.google.common.collect.ImmutableBiMap; -import net.minecraft.server.MobEffect; -import net.minecraft.server.MobEffectList; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionType; - -public class CraftPotionUtil { - - private static final BiMap regular = ImmutableBiMap.builder() - .put(PotionType.UNCRAFTABLE, "empty") - .put(PotionType.WATER, "water") - .put(PotionType.MUNDANE, "mundane") - .put(PotionType.THICK, "thick") - .put(PotionType.AWKWARD, "awkward") - .put(PotionType.NIGHT_VISION, "night_vision") - .put(PotionType.INVISIBILITY, "invisibility") - .put(PotionType.JUMP, "leaping") - .put(PotionType.FIRE_RESISTANCE, "fire_resistance") - .put(PotionType.SPEED, "swiftness") - .put(PotionType.SLOWNESS, "slowness") - .put(PotionType.WATER_BREATHING, "water_breathing") - .put(PotionType.INSTANT_HEAL, "healing") - .put(PotionType.INSTANT_DAMAGE, "harming") - .put(PotionType.POISON, "poison") - .put(PotionType.REGEN, "regeneration") - .put(PotionType.STRENGTH, "strength") - .put(PotionType.WEAKNESS, "weakness") - .put(PotionType.LUCK, "luck") - .put(PotionType.TURTLE_MASTER, "turtle_master") - .put(PotionType.SLOW_FALLING, "slow_falling") - .build(); - private static final BiMap upgradeable = ImmutableBiMap.builder() - .put(PotionType.JUMP, "strong_leaping") - .put(PotionType.SPEED, "strong_swiftness") - .put(PotionType.INSTANT_HEAL, "strong_healing") - .put(PotionType.INSTANT_DAMAGE, "strong_harming") - .put(PotionType.POISON, "strong_poison") - .put(PotionType.REGEN, "strong_regeneration") - .put(PotionType.STRENGTH, "strong_strength") - .put(PotionType.SLOWNESS, "strong_slowness") - .put(PotionType.TURTLE_MASTER, "strong_turtle_master") - .build(); - private static final BiMap extendable = ImmutableBiMap.builder() - .put(PotionType.NIGHT_VISION, "long_night_vision") - .put(PotionType.INVISIBILITY, "long_invisibility") - .put(PotionType.JUMP, "long_leaping") - .put(PotionType.FIRE_RESISTANCE, "long_fire_resistance") - .put(PotionType.SPEED, "long_swiftness") - .put(PotionType.SLOWNESS, "long_slowness") - .put(PotionType.WATER_BREATHING, "long_water_breathing") - .put(PotionType.POISON, "long_poison") - .put(PotionType.REGEN, "long_regeneration") - .put(PotionType.STRENGTH, "long_strength") - .put(PotionType.WEAKNESS, "long_weakness") - .put(PotionType.TURTLE_MASTER, "long_turtle_master") - .put(PotionType.SLOW_FALLING, "long_slow_falling") - .build(); - - public static String fromBukkit(PotionData data) { - String type; - if (data.isUpgraded()) { - type = upgradeable.get(data.getType()); - } else if (data.isExtended()) { - type = extendable.get(data.getType()); - } else { - type = regular.get(data.getType()); - } - Preconditions.checkNotNull(type, "Unknown potion type from data " + data); - - return "minecraft:" + type; - } - - public static PotionData toBukkit(String type) { - if (type == null) { - return new PotionData(PotionType.UNCRAFTABLE, false, false); - } - if (type.startsWith("minecraft:")) { - type = type.substring(10); - } - PotionType potionType = null; - potionType = extendable.inverse().get(type); - if (potionType != null) { - return new PotionData(potionType, true, false); - } - potionType = upgradeable.inverse().get(type); - if (potionType != null) { - return new PotionData(potionType, false, true); - } - potionType = regular.inverse().get(type); - if (potionType != null) { - return new PotionData(potionType, false, false); - } - return new PotionData(PotionType.UNCRAFTABLE, false, false); - } - - public static MobEffect fromBukkit(PotionEffect effect) { - MobEffectList type = MobEffectList.fromId(effect.getType().getId()); - return new MobEffect(type, effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()); - } - - public static PotionEffect toBukkit(MobEffect effect) { - PotionEffectType type = PotionEffectType.getById(MobEffectList.getId(effect.getMobEffect())); - int amp = effect.getAmplifier(); - int duration = effect.getDuration(); - boolean ambient = effect.isAmbient(); - boolean particles = effect.isShowParticles(); - return new PotionEffect(type, duration, amp, ambient, particles); - } - - public static boolean equals(MobEffectList mobEffect, PotionEffectType type) { - PotionEffectType typeV = PotionEffectType.getById(MobEffectList.getId(mobEffect)); - return typeV.equals(type); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java b/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java deleted file mode 100644 index 834fc1783..000000000 --- a/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.bukkit.craftbukkit.projectiles; - -import java.util.Random; -import net.minecraft.server.BlockDispenser; -import net.minecraft.server.EntityArrow; -import net.minecraft.server.EntityEgg; -import net.minecraft.server.EntityEnderPearl; -import net.minecraft.server.EntityFireball; -import net.minecraft.server.EntityPotion; -import net.minecraft.server.EntityProjectile; -import net.minecraft.server.EntitySmallFireball; -import net.minecraft.server.EntitySnowball; -import net.minecraft.server.EntitySpectralArrow; -import net.minecraft.server.EntityThrownExpBottle; -import net.minecraft.server.EntityTippedArrow; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.EnumDirection; -import net.minecraft.server.IPosition; -import net.minecraft.server.IProjectile; -import net.minecraft.server.MathHelper; -import net.minecraft.server.SourceBlock; -import net.minecraft.server.TileEntityDispenser; -import org.apache.commons.lang.Validate; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.craftbukkit.potion.CraftPotionUtil; -import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Egg; -import org.bukkit.entity.EnderPearl; -import org.bukkit.entity.Fireball; -import org.bukkit.entity.LingeringPotion; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.SmallFireball; -import org.bukkit.entity.Snowball; -import org.bukkit.entity.SpectralArrow; -import org.bukkit.entity.ThrownExpBottle; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.entity.TippedArrow; -import org.bukkit.entity.WitherSkull; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionType; -import org.bukkit.projectiles.BlockProjectileSource; -import org.bukkit.util.Vector; - -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 = (EnumDirection) isourceblock.getBlockData().get(BlockDispenser.FACING); - 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, null); - 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)) { - if (LingeringPotion.class.isAssignableFrom(projectile)) { - launch = new EntityPotion(world, iposition.getX(), iposition.getY(), iposition.getZ()); - ((EntityPotion) launch).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.LINGERING_POTION, 1))); - } else { - launch = new EntityPotion(world, iposition.getX(), iposition.getY(), iposition.getZ()); - ((EntityPotion) launch).setItem(CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.SPLASH_POTION, 1))); - } - } else if (AbstractArrow.class.isAssignableFrom(projectile)) { - if (TippedArrow.class.isAssignableFrom(projectile)) { - launch = new EntityTippedArrow(world, iposition.getX(), iposition.getY(), iposition.getZ()); - ((EntityTippedArrow) launch).setType(CraftPotionUtil.fromBukkit(new PotionData(PotionType.WATER, false, false))); - } else if (SpectralArrow.class.isAssignableFrom(projectile)) { - launch = new EntitySpectralArrow(world, iposition.getX(), iposition.getY(), iposition.getZ()); - } else { - launch = new EntityTippedArrow(world, iposition.getX(), iposition.getY(), iposition.getZ()); - } - ((EntityArrow) launch).fromPlayer = EntityArrow.PickupStatus.ALLOWED; - ((EntityArrow) 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, null, d0, d1, d2); - } else if (WitherSkull.class.isAssignableFrom(projectile)) { - launch = EntityTypes.WITHER_SKULL.a(world); - launch.setPosition(d0, d1, d2); - double d6 = (double) 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 = EntityTypes.FIREBALL.a(world); - launch.setPosition(d0, d1, d2); - double d6 = (double) 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; - } - - ((EntityFireball) launch).projectileSource = this; - } - - Validate.notNull(launch, "Projectile not supported"); - - if (launch instanceof IProjectile) { - if (launch instanceof EntityProjectile) { - ((EntityProjectile) launch).projectileSource = this; - } - // Values from DispenseBehaviorProjectile - float a = 6.0F; - float b = 1.1F; - if (launch instanceof EntityPotion || launch instanceof ThrownExpBottle) { - // Values from respective DispenseBehavior classes - a *= 0.5F; - b *= 1.25F; - } - // Copied from DispenseBehaviorProjectile - ((IProjectile) launch).shoot((double) enumdirection.getAdjacentX(), (double) ((float) enumdirection.getAdjacentY() + 0.1F), (double) enumdirection.getAdjacentZ(), b, a); - } - - if (velocity != null) { - ((T) launch.getBukkitEntity()).setVelocity(velocity); - } - - world.addEntity(launch); - return (T) launch.getBukkitEntity(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncDebugger.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncDebugger.java deleted file mode 100644 index c33213124..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncDebugger.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.bukkit.craftbukkit.scheduler; - -import org.bukkit.plugin.Plugin; - - -class CraftAsyncDebugger { - private CraftAsyncDebugger next = null; - private final int expiry; - private final Plugin plugin; - private final Class clazz; - - CraftAsyncDebugger(final int expiry, final Plugin plugin, final Class clazz) { - this.expiry = expiry; - this.plugin = plugin; - this.clazz = clazz; - - } - - final CraftAsyncDebugger getNextHead(final int time) { - CraftAsyncDebugger next, current = this; - while (time > current.expiry && (next = current.next) != null) { - current = next; - } - return current; - } - - final CraftAsyncDebugger setNext(final CraftAsyncDebugger next) { - return this.next = next; - } - - StringBuilder debugTo(final StringBuilder string) { - for (CraftAsyncDebugger next = this; next != null; next = next.next) { - string.append(next.plugin.getDescription().getName()).append(':').append(next.clazz.getName()).append('@').append(next.expiry).append(','); - } - return string; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java deleted file mode 100644 index 3c1992e21..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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.destroystokyo.paper.ServerSchedulerReportingWrapper; -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.bukkit.plugin.Plugin; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -public class CraftAsyncScheduler extends CraftScheduler { - - private final ThreadPoolExecutor executor = new ThreadPoolExecutor( - 4, Integer.MAX_VALUE,30L, TimeUnit.SECONDS, new SynchronousQueue<>(), - new ThreadFactoryBuilder().setNameFormat("Craft Scheduler Thread - %1$d").build()); - 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 - * @param runningTask - * @return - */ - static boolean isValid(CraftTask runningTask) { - return runningTask.getPeriod() >= CraftTask.NO_REPEATING; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java deleted file mode 100644 index 692aca048..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.bukkit.craftbukkit.scheduler; - -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import java.util.logging.Level; -import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitWorker; - -class CraftAsyncTask extends CraftTask { - - private final LinkedList workers = new LinkedList(); - private final Map runners; - - CraftAsyncTask(final Map runners, final Plugin plugin, final Object 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() == CraftTask.CANCEL) { - // Never continue running after cancelled. - // Checking this with the lock is important! - return; - } - workers.add( - new BukkitWorker() { - @Override - public Thread getThread() { - return thread; - } - - @Override - public int getTaskId() { - return CraftAsyncTask.this.getTaskId(); - } - - @Override - public Plugin getOwner() { - return CraftAsyncTask.this.getOwner(); - } - }); - } - Throwable thrown = null; - try { - super.run(); - } catch (final Throwable t) { - thrown = t; - getOwner().getLogger().log( - Level.WARNING, - 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; - } - - @Override - boolean cancel0() { - synchronized (workers) { - // Synchronizing here prevents race condition for a completing task - setPeriod(CraftTask.CANCEL); - if (workers.isEmpty()) { - runners.remove(getTaskId()); - } - } - return true; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java deleted file mode 100644 index 1e20385fd..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bukkit.craftbukkit.scheduler; - -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import org.bukkit.plugin.Plugin; - -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, CraftTask.NO_REPEATING); - this.callable = callable; - } - - @Override - public synchronized boolean cancel(final boolean mayInterruptIfRunning) { - if (getPeriod() != CraftTask.NO_REPEATING) { - return false; - } - setPeriod(CraftTask.CANCEL); - return true; - } - - @Override - public boolean isDone() { - final long period = this.getPeriod(); - return period != CraftTask.NO_REPEATING && period != CraftTask.PROCESS_FOR_FUTURE; - } - - @Override - public T get() throws CancellationException, InterruptedException, ExecutionException { - try { - return get(0, TimeUnit.MILLISECONDS); - } catch (final TimeoutException e) { - throw new Error(e); - } - } - - @Override - 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 == CraftTask.NO_REPEATING || period == CraftTask.PROCESS_FOR_FUTURE) { - this.wait(timeout); - period = this.getPeriod(); - if (period == CraftTask.NO_REPEATING || period == CraftTask.PROCESS_FOR_FUTURE) { - if (timeout == 0L) { - continue; - } - timeout += timestamp - (timestamp = System.currentTimeMillis()); - if (timeout > 0) { - continue; - } - throw new TimeoutException(); - } - } - if (period == CraftTask.CANCEL) { - throw new CancellationException(); - } - if (period == CraftTask.DONE_FOR_FUTURE) { - if (exception == null) { - return value; - } - throw new ExecutionException(exception); - } - throw new IllegalStateException("Expected " + CraftTask.NO_REPEATING + " to " + CraftTask.DONE_FOR_FUTURE + ", got " + period); - } - } - - @Override - public void run() { - synchronized (this) { - if (getPeriod() == CraftTask.CANCEL) { - return; - } - setPeriod(CraftTask.PROCESS_FOR_FUTURE); - } - try { - value = callable.call(); - } catch (final Exception e) { - exception = e; - } finally { - synchronized (this) { - setPeriod(CraftTask.DONE_FOR_FUTURE); - this.notifyAll(); - } - } - } - - @Override - synchronized boolean cancel0() { - if (getPeriod() != CraftTask.NO_REPEATING) { - return false; - } - setPeriod(CraftTask.CANCEL); - notifyAll(); - return true; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java deleted file mode 100644 index 5db848de1..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java +++ /dev/null @@ -1,619 +0,0 @@ -package org.bukkit.craftbukkit.scheduler; - -import co.aikar.timings.MinecraftTimings; // Paper -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.PriorityQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; -import java.util.logging.Level; -import com.destroystokyo.paper.ServerSchedulerReportingWrapper; -import com.destroystokyo.paper.event.server.ServerExceptionEvent; -import com.destroystokyo.paper.exception.ServerSchedulerException; -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; - -/** - * 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 #cancelTask(int)}
  • - *
  • {@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, {@link CraftTask#next} 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 - new Comparator() { - @Override - public int compare(final CraftTask o1, final CraftTask o2) { - int value = Long.compare(o1.getNextRun(), o2.getNextRun()); - - // If the tasks should run on the same tick they should be run FIFO - return value != 0 ? value : Integer.compare(o1.getTaskId(), o2.getTaskId()); - } - }); - /** - * 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 - //private final Executor executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Craft Scheduler Thread - %d").build()); // Paper - moved to AsyncScheduler - //private CraftAsyncDebugger debugHead = new CraftAsyncDebugger(-1, null, null) {@Override StringBuilder debugTo(StringBuilder string) {return string;}}; // Paper - //private CraftAsyncDebugger debugTail = debugHead; // Paper - private static final int RECENT_TICKS; - - static { - RECENT_TICKS = 30; - } - - - // 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 - @Override - public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable task) { - return this.scheduleSyncDelayedTask(plugin, task, 0L); - } - - @Override - public BukkitTask runTask(Plugin plugin, Runnable runnable) { - return runTaskLater(plugin, runnable, 0L); - } - - @Override - public void runTask(Plugin plugin, Consumer task) throws IllegalArgumentException { - runTaskLater(plugin, task, 0L); - } - - @Deprecated - @Override - public int scheduleAsyncDelayedTask(final Plugin plugin, final Runnable task) { - return this.scheduleAsyncDelayedTask(plugin, task, 0L); - } - - @Override - public BukkitTask runTaskAsynchronously(Plugin plugin, Runnable runnable) { - return runTaskLaterAsynchronously(plugin, runnable, 0L); - } - - @Override - public void runTaskAsynchronously(Plugin plugin, Consumer task) throws IllegalArgumentException { - runTaskLaterAsynchronously(plugin, task, 0L); - } - - @Override - public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable task, final long delay) { - return this.scheduleSyncRepeatingTask(plugin, task, delay, CraftTask.NO_REPEATING); - } - - @Override - public BukkitTask runTaskLater(Plugin plugin, Runnable runnable, long delay) { - return runTaskTimer(plugin, runnable, delay, CraftTask.NO_REPEATING); - } - - @Override - public void runTaskLater(Plugin plugin, Consumer task, long delay) throws IllegalArgumentException { - runTaskTimer(plugin, task, delay, CraftTask.NO_REPEATING); - } - - @Deprecated - @Override - public int scheduleAsyncDelayedTask(final Plugin plugin, final Runnable task, final long delay) { - return this.scheduleAsyncRepeatingTask(plugin, task, delay, CraftTask.NO_REPEATING); - } - - @Override - public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable runnable, long delay) { - return runTaskTimerAsynchronously(plugin, runnable, delay, CraftTask.NO_REPEATING); - } - - @Override - public void runTaskLaterAsynchronously(Plugin plugin, Consumer task, long delay) throws IllegalArgumentException { - runTaskTimerAsynchronously(plugin, task, delay, CraftTask.NO_REPEATING); - } - - @Override - public void runTaskTimerAsynchronously(Plugin plugin, Consumer task, long delay, long period) throws IllegalArgumentException { - runTaskTimerAsynchronously(plugin, (Object) task, delay, CraftTask.NO_REPEATING); - } - - @Override - public int scheduleSyncRepeatingTask(final Plugin plugin, final Runnable runnable, long delay, long period) { - return runTaskTimer(plugin, runnable, delay, period).getTaskId(); - } - - @Override - public BukkitTask runTaskTimer(Plugin plugin, Runnable runnable, long delay, long period) { - return runTaskTimer(plugin, (Object) runnable, delay, period); - } - - @Override - public void runTaskTimer(Plugin plugin, Consumer task, long delay, long period) throws IllegalArgumentException { - runTaskTimer(plugin, (Object) task, delay, period); - } - - public BukkitTask runTaskTimer(Plugin plugin, Object runnable, long delay, long period) { - validate(plugin, runnable); - if (delay < 0L) { - delay = 0; - } - if (period == CraftTask.ERROR) { - period = 1L; - } else if (period < CraftTask.NO_REPEATING) { - period = CraftTask.NO_REPEATING; - } - return handle(new CraftTask(plugin, runnable, nextId(), period), delay); - } - - @Deprecated - @Override - public int scheduleAsyncRepeatingTask(final Plugin plugin, final Runnable runnable, long delay, long period) { - return runTaskTimerAsynchronously(plugin, runnable, delay, period).getTaskId(); - } - - @Override - public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable runnable, long delay, long period) { - return runTaskTimerAsynchronously(plugin, (Object) runnable, delay, period); - } - - public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Object runnable, long delay, long period) { - validate(plugin, runnable); - if (delay < 0L) { - delay = 0; - } - if (period == CraftTask.ERROR) { - period = 1L; - } else if (period < CraftTask.NO_REPEATING) { - period = CraftTask.NO_REPEATING; - } - return handle(new CraftAsyncTask(this.asyncScheduler.runners, plugin, runnable, nextId(), period), delay); // Paper - } - - @Override - 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; - } - - @Override - 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() { - @Override - 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; - }}){{this.timings=co.aikar.timings.MinecraftTimings.getCancelTasksTimer();}}; // Paper - handle(task, 0L); - for (CraftTask taskPending = head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { - if (taskPending == task) { - return; - } - if (taskPending.getTaskId() == taskId) { - taskPending.cancel0(); - } - } - } - - @Override - 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() { - @Override - 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()); - } - } - } - } - }){{this.timings=co.aikar.timings.MinecraftTimings.getCancelTasksTimer(plugin);}}; // Paper - handle(task, 0L); - for (CraftTask taskPending = head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { - if (taskPending == task) { - break; - } - if (taskPending.getTaskId() != -1 && taskPending.getOwner().equals(plugin)) { - taskPending.cancel0(); - } - } - for (CraftTask runner : runners.values()) { - if (runner.getOwner().equals(plugin)) { - runner.cancel0(); - } - } - } - - @Override - 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(); - } - } - - @Override - 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() >= CraftTask.NO_REPEATING; // The task will run - } - } - CraftTask task = runners.get(taskId); - return task != null && task.getPeriod() >= CraftTask.NO_REPEATING; - } - - @Override - 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; - } - - @Override - 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() >= CraftTask.NO_REPEATING) { - pending.add(task); - } - } - - for (final CraftTask task : truePending) { - if (task.getPeriod() >= CraftTask.NO_REPEATING && !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() < CraftTask.NO_REPEATING) { - 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()); - } - } - MinecraftTimings.bukkitSchedulerFinishTimer.startTiming(); - pending.addAll(temp); - temp.clear(); - MinecraftTimings.bukkitSchedulerFinishTimer.stopTiming(); - //debugHead = debugHead.getNextHead(currentTick); // Paper - } - - protected 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 - // 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"); - Validate.isTrue(task instanceof Runnable || task instanceof Consumer || task instanceof Callable, "Task must be Runnable, Consumer, or Callable"); - if (!plugin.isEnabled()) { - throw new IllegalPluginAccessException("Plugin attempted to register task while disabled"); - } - } - - private int nextId() { - return ids.incrementAndGet(); - } - - void parsePending() { // Paper - if (!this.isAsyncScheduler) MinecraftTimings.bukkitSchedulerPendingTimer.startTiming(); // Paper - 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() >= CraftTask.NO_REPEATING) { - 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; - if (!this.isAsyncScheduler) MinecraftTimings.bukkitSchedulerPendingTimer.stopTiming(); // Paper - } - - private boolean isReady(final int currentTick) { - return !pending.isEmpty() && pending.peek().getNextRun() <= currentTick; - } - - @Override - public String toString() { - // Paper start - return ""; - /* - int debugTick = currentTick; - StringBuilder string = new StringBuilder("Recent tasks from ").append(debugTick - RECENT_TICKS).append('-').append(debugTick).append('{'); - debugHead.debugTo(string); - return string.append('}').toString(); - */ - // Paper end - } - - @Deprecated - @Override - public int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable task, long delay) { - throw new UnsupportedOperationException("Use BukkitRunnable#runTaskLater(Plugin, long)"); - } - - @Deprecated - @Override - public int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable task) { - throw new UnsupportedOperationException("Use BukkitRunnable#runTask(Plugin)"); - } - - @Deprecated - @Override - public int scheduleSyncRepeatingTask(Plugin plugin, BukkitRunnable task, long delay, long period) { - throw new UnsupportedOperationException("Use BukkitRunnable#runTaskTimer(Plugin, long, long)"); - } - - @Deprecated - @Override - public BukkitTask runTask(Plugin plugin, BukkitRunnable task) throws IllegalArgumentException { - throw new UnsupportedOperationException("Use BukkitRunnable#runTask(Plugin)"); - } - - @Deprecated - @Override - public BukkitTask runTaskAsynchronously(Plugin plugin, BukkitRunnable task) throws IllegalArgumentException { - throw new UnsupportedOperationException("Use BukkitRunnable#runTaskAsynchronously(Plugin)"); - } - - @Deprecated - @Override - public BukkitTask runTaskLater(Plugin plugin, BukkitRunnable task, long delay) throws IllegalArgumentException { - throw new UnsupportedOperationException("Use BukkitRunnable#runTaskLater(Plugin, long)"); - } - - @Deprecated - @Override - public BukkitTask runTaskLaterAsynchronously(Plugin plugin, BukkitRunnable task, long delay) throws IllegalArgumentException { - throw new UnsupportedOperationException("Use BukkitRunnable#runTaskLaterAsynchronously(Plugin, long)"); - } - - @Deprecated - @Override - public BukkitTask runTaskTimer(Plugin plugin, BukkitRunnable task, long delay, long period) throws IllegalArgumentException { - throw new UnsupportedOperationException("Use BukkitRunnable#runTaskTimer(Plugin, long, long)"); - } - - @Deprecated - @Override - public BukkitTask runTaskTimerAsynchronously(Plugin plugin, BukkitRunnable task, long delay, long period) throws IllegalArgumentException { - throw new UnsupportedOperationException("Use BukkitRunnable#runTaskTimerAsynchronously(Plugin, long, long)"); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java deleted file mode 100644 index 0d9a46680..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java +++ /dev/null @@ -1,139 +0,0 @@ -package org.bukkit.craftbukkit.scheduler; - -import java.util.function.Consumer; - -import co.aikar.timings.NullTimingHandler; -import org.bukkit.Bukkit; -import co.aikar.timings.MinecraftTimings; // Paper -import co.aikar.timings.Timing; // Paper -import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitTask; - - -public class CraftTask implements BukkitTask, Runnable { // Spigot - - private volatile CraftTask next = null; - public static final int ERROR = 0; - public static final int NO_REPEATING = -1; - public static final int CANCEL = -2; - public static final int PROCESS_FOR_FUTURE = -3; - public static final int DONE_FOR_FUTURE = -4; - /** - * -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 rTask; // Paper - public final Consumer cTask; // Paper - public Timing timings; // Paper - private final Plugin plugin; - private final int id; - - CraftTask() { - this(null, null, CraftTask.NO_REPEATING, CraftTask.NO_REPEATING); - } - - CraftTask(final Object task) { - this(null, task, CraftTask.NO_REPEATING, CraftTask.NO_REPEATING); - } - - CraftTask(final Plugin plugin, final Object task, final int id, final long period) { // Paper - this.plugin = plugin; - if (task instanceof Runnable) { - this.rTask = (Runnable) task; - this.cTask = null; - } else if (task instanceof Consumer) { - this.cTask = (Consumer) task; - this.rTask = null; - } else if (task == null) { - // Head or Future task - this.rTask = null; - this.cTask = null; - } else { - throw new AssertionError("Illegal task class " + task); - } - this.id = id; - this.period = period; - timings = task != null ? MinecraftTimings.getPluginTaskTimings(this, period) : NullTimingHandler.NULL; // Paper - } - - @Override - public final int getTaskId() { - return id; - } - - @Override - public final Plugin getOwner() { - return plugin; - } - - @Override - public boolean isSync() { - return true; - } - - @Override - public void run() { - try (Timing ignored = timings.startTiming()) { // Paper - if (rTask != null) { - rTask.run(); - } else { - cTask.accept(this); - } - } // Paper - } - - 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; - } - - public Class getTaskClass() { - return (rTask != null) ? rTask.getClass() : ((cTask != null) ? cTask.getClass() : null); - } - - @Override - public boolean isCancelled() { - return (period == CraftTask.CANCEL); - } - - @Override - 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(CraftTask.CANCEL); - return true; - } - -} diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java deleted file mode 100644 index 7cc904851..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.bukkit.craftbukkit.scoreboard; - -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import net.minecraft.server.IScoreboardCriteria; -import net.minecraft.server.ScoreboardObjective; - -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/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java deleted file mode 100644 index 5eaea24d2..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java +++ /dev/null @@ -1,163 +0,0 @@ -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.craftbukkit.util.CraftChatMessage; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.RenderType; -import org.bukkit.scoreboard.Score; - -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; - } - - @Override - public String getName() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return objective.getName(); - } - - @Override - public String getDisplayName() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return CraftChatMessage.fromComponent(objective.getDisplayName()); - } - - @Override - public void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(displayName, "Display name cannot be null"); - Validate.isTrue(displayName.length() <= 128, "Display name '" + displayName + "' is longer than the limit of 128 characters"); - CraftScoreboard scoreboard = checkState(); - - objective.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable - } - - @Override - public String getCriteria() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return criteria.bukkitName; - } - - @Override - public boolean isModifiable() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return !criteria.criteria.isReadOnly(); - } - - @Override - 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()); - } - } - - @Override - 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; - } - - @Override - public void setRenderType(RenderType renderType) throws IllegalStateException { - Validate.notNull(renderType, "RenderType cannot be null"); - CraftScoreboard scoreboard = checkState(); - - this.objective.setRenderType(CraftScoreboardTranslations.fromBukkitRender(renderType)); - } - - @Override - public RenderType getRenderType() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return CraftScoreboardTranslations.toBukkitRender(this.objective.getRenderType()); - } - - @Override - public Score getScore(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { - Validate.notNull(player, "Player cannot be null"); - CraftScoreboard scoreboard = checkState(); - - return new CraftScore(this, player.getName()); - } - - @Override - public Score getScore(String entry) throws IllegalArgumentException, IllegalStateException { - Validate.notNull(entry, "Entry cannot be null"); - Validate.isTrue(entry.length() <= 40, "Score '" + entry + "' is longer than the limit of 40 characters"); - CraftScoreboard scoreboard = checkState(); - - return new CraftScore(this, entry); - } - - @Override - public void unregister() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - scoreboard.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 !(this.objective != other.objective && (this.objective == null || !this.objective.equals(other.objective))); - } - - -} diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java deleted file mode 100644 index 41d22d223..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.bukkit.craftbukkit.scoreboard; - -import java.util.Map; -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; - -/** - * 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; - } - - @Override - public OfflinePlayer getPlayer() { - return Bukkit.getOfflinePlayer(entry); - } - - @Override - public String getEntry() { - return entry; - } - - @Override - public Objective getObjective() { - return objective; - } - - @Override - 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 - } - - @Override - public void setScore(int score) throws IllegalStateException { - objective.checkState().board.getPlayerScoreForObjective(entry, objective.getHandle()).setScore(score); - } - - @Override - public boolean isScoreSet() throws IllegalStateException { - Scoreboard board = objective.checkState().board; - - return board.getPlayers().contains(entry) && board.getPlayerObjectives(entry).containsKey(objective.getHandle()); - } - - @Override - public CraftScoreboard getScoreboard() { - return objective.getScoreboard(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java deleted file mode 100644 index e3036fe23..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java +++ /dev/null @@ -1,200 +0,0 @@ -package org.bukkit.craftbukkit.scoreboard; - -import com.google.common.base.Function; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import java.util.Collection; -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.craftbukkit.util.CraftChatMessage; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.RenderType; -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; - } - - @Override - public CraftObjective registerNewObjective(String name, String criteria) throws IllegalArgumentException { - return registerNewObjective(name, criteria, name); - } - - @Override - public CraftObjective registerNewObjective(String name, String criteria, String displayName) throws IllegalArgumentException { - return registerNewObjective(name, criteria, displayName, RenderType.INTEGER); - } - - @Override - public CraftObjective registerNewObjective(String name, String criteria, String displayName, RenderType renderType) throws IllegalArgumentException { - Validate.notNull(name, "Objective name cannot be null"); - Validate.notNull(criteria, "Criteria cannot be null"); - Validate.notNull(displayName, "Display name cannot be null"); - Validate.notNull(renderType, "RenderType cannot be null"); - Validate.isTrue(name.length() <= 16, "The name '" + name + "' is longer than the limit of 16 characters"); - Validate.isTrue(displayName.length() <= 128, "The display name '" + displayName + "' is longer than the limit of 128 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, CraftChatMessage.fromStringOrNull(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType)); - return new CraftObjective(this, objective); - } - - @Override - 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); - } - - @Override - public ImmutableSet getObjectivesByCriteria(String criteria) throws IllegalArgumentException { - Validate.notNull(criteria, "Criteria cannot be null"); - - ImmutableSet.Builder objectives = ImmutableSet.builder(); - for (ScoreboardObjective netObjective : (Collection) this.board.getObjectives()) { - CraftObjective objective = new CraftObjective(this, netObjective); - if (objective.getCriteria().equals(criteria)) { - objectives.add(objective); - } - } - return objectives.build(); - } - - @Override - public ImmutableSet getObjectives() { - return ImmutableSet.copyOf(Iterables.transform((Collection) this.board.getObjectives(), new Function() { - - @Override - public Objective apply(ScoreboardObjective input) { - return new CraftObjective(CraftScoreboard.this, input); - } - })); - } - - @Override - 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); - } - - @Override - public ImmutableSet getScores(OfflinePlayer player) throws IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); - - return getScores(player.getName()); - } - - @Override - public ImmutableSet getScores(String entry) throws IllegalArgumentException { - Validate.notNull(entry, "Entry cannot be null"); - - ImmutableSet.Builder scores = ImmutableSet.builder(); - for (ScoreboardObjective objective : (Collection) this.board.getObjectives()) { - scores.add(new CraftScore(new CraftObjective(this, objective), entry)); - } - return scores.build(); - } - - @Override - public void resetScores(OfflinePlayer player) throws IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); - - resetScores(player.getName()); - } - - @Override - public void resetScores(String entry) throws IllegalArgumentException { - Validate.notNull(entry, "Entry cannot be null"); - - for (ScoreboardObjective objective : (Collection) this.board.getObjectives()) { - board.resetPlayerScores(entry, objective); - } - } - - @Override - 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); - } - - @Override - 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); - } - - @Override - 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); - } - - @Override - public ImmutableSet getTeams() { - return ImmutableSet.copyOf(Iterables.transform((Collection) this.board.getTeams(), new Function() { - - @Override - public Team apply(ScoreboardTeam input) { - return new CraftTeam(CraftScoreboard.this, input); - } - })); - } - - @Override - 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)); - } - - @Override - public ImmutableSet getPlayers() { - ImmutableSet.Builder players = ImmutableSet.builder(); - for (Object playerName : board.getPlayers()) { - players.add(Bukkit.getOfflinePlayer(playerName.toString())); - } - return players.build(); - } - - @Override - public ImmutableSet getEntries() { - ImmutableSet.Builder entries = ImmutableSet.builder(); - for (Object entry : board.getPlayers()) { - entries.add(entry.toString()); - } - return entries.build(); - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java deleted file mode 100644 index d26d09d41..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.bukkit.craftbukkit.scoreboard; - -abstract class CraftScoreboardComponent { - private 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/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java deleted file mode 100644 index ca2be3060..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bukkit.craftbukkit.scoreboard; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.function.Consumer; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.IScoreboardCriteria; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.PacketPlayOutScoreboardObjective; -import net.minecraft.server.PacketPlayOutScoreboardTeam; -import net.minecraft.server.Scoreboard; -import net.minecraft.server.ScoreboardObjective; -import net.minecraft.server.ScoreboardScore; -import net.minecraft.server.ScoreboardServer; -import net.minecraft.server.ScoreboardTeam; -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; - -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); - } - - @Override - public CraftScoreboard getMainScoreboard() { - return mainScoreboard; - } - - @Override - 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 (CraftScoreboard) (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 (scoreboard == mainScoreboard) { - playerBoards.remove(player); - } else { - playerBoards.put(player, (CraftScoreboard) 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 - Iterator iterator = oldboard.getTeams().iterator(); - while (iterator.hasNext()) { - ScoreboardTeam scoreboardteam = (ScoreboardTeam) iterator.next(); - 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) { - playerBoards.remove(player); - } - - // CraftBukkit method - public void getScoreboardScores(IScoreboardCriteria criteria, String name, Consumer consumer) { - for (CraftScoreboard scoreboard : scoreboards) { - Scoreboard board = scoreboard.board; - board.getObjectivesForCriteria(criteria, name, (score) -> consumer.accept(score)); - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java deleted file mode 100644 index edd147fe6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.bukkit.craftbukkit.scoreboard; - -import com.google.common.collect.ImmutableBiMap; -import net.minecraft.server.IScoreboardCriteria; -import net.minecraft.server.Scoreboard; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.RenderType; - -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)); - } - - static RenderType toBukkitRender(IScoreboardCriteria.EnumScoreboardHealthDisplay display) { - return RenderType.valueOf(display.name()); - } - - static IScoreboardCriteria.EnumScoreboardHealthDisplay fromBukkitRender(RenderType render) { - return IScoreboardCriteria.EnumScoreboardHealthDisplay.valueOf(render.name()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java deleted file mode 100644 index bc92089ea..000000000 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java +++ /dev/null @@ -1,313 +0,0 @@ -package org.bukkit.craftbukkit.scoreboard; - -import com.google.common.collect.ImmutableSet; -import java.util.Set; -import net.minecraft.server.ScoreboardTeam; -import net.minecraft.server.ScoreboardTeamBase; -import net.minecraft.server.ScoreboardTeamBase.EnumNameTagVisibility; -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.bukkit.scoreboard.NameTagVisibility; -import org.bukkit.scoreboard.Team; - -final class CraftTeam extends CraftScoreboardComponent implements Team { - private final ScoreboardTeam team; - - CraftTeam(CraftScoreboard scoreboard, ScoreboardTeam team) { - super(scoreboard); - this.team = team; - } - - @Override - public String getName() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return team.getName(); - } - - @Override - public String getDisplayName() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return CraftChatMessage.fromComponent(team.getDisplayName()); - } - - @Override - public void setDisplayName(String displayName) throws IllegalStateException { - Validate.notNull(displayName, "Display name cannot be null"); - Validate.isTrue(displayName.length() <= 128, "Display name '" + displayName + "' is longer than the limit of 128 characters"); - CraftScoreboard scoreboard = checkState(); - - team.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable - } - - @Override - public String getPrefix() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return CraftChatMessage.fromComponent(team.getPrefix()); - } - - @Override - public void setPrefix(String prefix) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(prefix, "Prefix cannot be null"); - Validate.isTrue(prefix.length() <= 64, "Prefix '" + prefix + "' is longer than the limit of 64 characters"); - CraftScoreboard scoreboard = checkState(); - - team.setPrefix(CraftChatMessage.fromStringOrNull(prefix)); - } - - @Override - public String getSuffix() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return CraftChatMessage.fromComponent(team.getSuffix()); - } - - @Override - public void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(suffix, "Suffix cannot be null"); - Validate.isTrue(suffix.length() <= 64, "Suffix '" + suffix + "' is longer than the limit of 64 characters"); - CraftScoreboard scoreboard = checkState(); - - team.setSuffix(CraftChatMessage.fromStringOrNull(suffix)); - } - - @Override - public ChatColor getColor() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return CraftChatMessage.getColor(team.getColor()); - } - - @Override - public void setColor(ChatColor color) { - Validate.notNull(color, "Color cannot be null"); - CraftScoreboard scoreboard = checkState(); - - team.setColor(CraftChatMessage.getColor(color)); - } - - @Override - public boolean allowFriendlyFire() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return team.allowFriendlyFire(); - } - - @Override - public void setAllowFriendlyFire(boolean enabled) throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - team.setAllowFriendlyFire(enabled); - } - - @Override - public boolean canSeeFriendlyInvisibles() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return team.canSeeFriendlyInvisibles(); - } - - @Override - public void setCanSeeFriendlyInvisibles(boolean enabled) throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - team.setCanSeeFriendlyInvisibles(enabled); - } - - @Override - public NameTagVisibility getNameTagVisibility() throws IllegalArgumentException { - CraftScoreboard scoreboard = checkState(); - - return notchToBukkit(team.getNameTagVisibility()); - } - - @Override - public void setNameTagVisibility(NameTagVisibility visibility) throws IllegalArgumentException { - CraftScoreboard scoreboard = checkState(); - - team.setNameTagVisibility(bukkitToNotch(visibility)); - } - - @Override - public Set getPlayers() throws IllegalStateException { - CraftScoreboard scoreboard = 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 { - CraftScoreboard scoreboard = checkState(); - - ImmutableSet.Builder entries = ImmutableSet.builder(); - for (String playerName: team.getPlayerNameSet()){ - entries.add(playerName); - } - return entries.build(); - } - - @Override - public int getSize() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - return team.getPlayerNameSet().size(); - } - - @Override - public void addPlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); - addEntry(player.getName()); - } - - @Override - public void addEntry(String entry) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(entry, "Entry cannot be null"); - CraftScoreboard scoreboard = checkState(); - - scoreboard.board.addPlayerToTeam(entry, team); - } - - @Override - public boolean removePlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); - return removeEntry(player.getName()); - } - - @Override - 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; - } - - @Override - public boolean hasPlayer(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { - Validate.notNull(player, "OfflinePlayer cannot be null"); - return hasEntry(player.getName()); - } - - @Override - public boolean hasEntry(String entry) throws IllegalArgumentException, IllegalStateException { - Validate.notNull("Entry cannot be null"); - - CraftScoreboard scoreboard = checkState(); - - return team.getPlayerNameSet().contains(entry); - } - - @Override - public void unregister() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); - - scoreboard.board.removeTeam(team); - } - - @Override - public OptionStatus getOption(Option option) throws IllegalStateException { - checkState(); - - switch (option) { - case NAME_TAG_VISIBILITY: - return OptionStatus.values()[team.getNameTagVisibility().ordinal()]; - case DEATH_MESSAGE_VISIBILITY: - return OptionStatus.values()[team.getDeathMessageVisibility().ordinal()]; - case COLLISION_RULE: - return OptionStatus.values()[team.getCollisionRule().ordinal()]; - default: - throw new IllegalArgumentException("Unrecognised option " + option); - } - } - - @Override - public void setOption(Option option, OptionStatus status) throws IllegalStateException { - checkState(); - - switch (option) { - case NAME_TAG_VISIBILITY: - team.setNameTagVisibility(EnumNameTagVisibility.values()[status.ordinal()]); - break; - case DEATH_MESSAGE_VISIBILITY: - team.setDeathMessageVisibility(EnumNameTagVisibility.values()[status.ordinal()]); - break; - case COLLISION_RULE: - team.setCollisionRule(ScoreboardTeamBase.EnumTeamPush.values()[status.ordinal()]); - break; - default: - throw new IllegalArgumentException("Unrecognised option " + option); - } - } - - 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 !(this.team != other.team && (this.team == null || !this.team.equals(other.team))); - } - -} diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftBlockTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftBlockTag.java deleted file mode 100644 index 2fe308d91..000000000 --- a/src/main/java/org/bukkit/craftbukkit/tag/CraftBlockTag.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.craftbukkit.tag; - -import java.util.Collections; -import java.util.Set; -import java.util.stream.Collectors; -import net.minecraft.server.Block; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.TagsServer; -import org.bukkit.Material; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; - -public class CraftBlockTag extends CraftTag { - - public CraftBlockTag(TagsServer registry, MinecraftKey tag) { - super(registry, tag); - } - - @Override - public boolean isTagged(Material item) { - return getHandle().isTagged(CraftMagicNumbers.getBlock(item)); - } - - @Override - public Set getValues() { - return Collections.unmodifiableSet(getHandle().a().stream().map((block) -> CraftMagicNumbers.getMaterial(block)).collect(Collectors.toSet())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftItemTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftItemTag.java deleted file mode 100644 index 4a1a45257..000000000 --- a/src/main/java/org/bukkit/craftbukkit/tag/CraftItemTag.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.bukkit.craftbukkit.tag; - -import java.util.Collections; -import java.util.Set; -import java.util.stream.Collectors; -import net.minecraft.server.Item; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.TagsServer; -import org.bukkit.Material; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; - -public class CraftItemTag extends CraftTag { - - public CraftItemTag(TagsServer registry, MinecraftKey tag) { - super(registry, tag); - } - - @Override - public boolean isTagged(Material item) { - return getHandle().isTagged(CraftMagicNumbers.getItem(item)); - } - - @Override - public Set getValues() { - return Collections.unmodifiableSet(getHandle().a().stream().map((item) -> CraftMagicNumbers.getMaterial(item)).collect(Collectors.toSet())); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/tag/CraftTag.java b/src/main/java/org/bukkit/craftbukkit/tag/CraftTag.java deleted file mode 100644 index c08671e23..000000000 --- a/src/main/java/org/bukkit/craftbukkit/tag/CraftTag.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.bukkit.craftbukkit.tag; - -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.TagsServer; -import org.bukkit.Keyed; -import org.bukkit.NamespacedKey; -import org.bukkit.Tag; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; - -public abstract class CraftTag implements Tag { - - private final net.minecraft.server.TagsServer registry; - private final MinecraftKey tag; - // - private int version = -1; - private net.minecraft.server.Tag handle; - - public CraftTag(TagsServer registry, MinecraftKey tag) { - this.registry = registry; - this.tag = tag; - } - - protected net.minecraft.server.Tag getHandle() { - if (version != registry.version) { - handle = registry.b(tag); - version = registry.version; - } - - return handle; - } - - @Override - public NamespacedKey getKey() { - return CraftNamespacedKey.fromMinecraft(tag); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java b/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java deleted file mode 100644 index f66f8b323..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Set; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.Fluid; -import net.minecraft.server.IBlockData; -import net.minecraft.server.World; -import org.bukkit.block.BlockState; -import org.bukkit.craftbukkit.block.CraftBlockState; - -public class BlockStateListPopulator extends DummyGeneratorAccess { - private final World world; - private final LinkedHashMap list; - - public BlockStateListPopulator(World world) { - this(world, new LinkedHashMap<>()); - } - - public BlockStateListPopulator(World world, LinkedHashMap list) { - this.world = world; - this.list = list; - } - - @Override - public IBlockData getType(BlockPosition bp) { - CraftBlockState state = list.get(bp); - return (state != null) ? state.getHandle() : world.getType(bp); - } - - @Override - public Fluid getFluid(BlockPosition bp) { - CraftBlockState state = list.get(bp); - return (state != null) ? state.getHandle().p() : world.getFluid(bp); - } - - @Override - public boolean setTypeAndData(BlockPosition position, IBlockData data, int flag) { - // Paper start - // When a LinkedHashMap entry is overwritten, it keeps its old position. Removing the entry here before adding - // a new one ensures that the nether portal blocks are placed last and are not destroyed by physics. - list.remove(position); - // Paper end - CraftBlockState state = CraftBlockState.getBlockState(world, position, flag); - state.setData(data); - list.put(position, state); - return true; - } - - public void updateList() { - for (BlockState state : list.values()) { - state.update(true); - } - } - - public Set getBlocks() { - return list.keySet(); - } - - public List getList() { - return new ArrayList<>(list.values()); - } - - public World getWorld() { - return world; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/Commodore.java b/src/main/java/org/bukkit/craftbukkit/util/Commodore.java deleted file mode 100644 index 61f102355..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/Commodore.java +++ /dev/null @@ -1,456 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import com.google.common.io.ByteStreams; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.JarOutputStream; -import java.util.zip.ZipEntry; -import joptsimple.OptionParser; -import joptsimple.OptionSet; -import joptsimple.OptionSpec; -import org.bukkit.Material; -import org.bukkit.plugin.AuthorNagException; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.Handle; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - -import javax.annotation.Nonnull; - -/** - * This file is imported from Commodore. - * - * @author md_5 - */ -public class Commodore -{ - - private static final Set EVIL = new HashSet<>( Arrays.asList( - "org/bukkit/World (III)I getBlockTypeIdAt", - "org/bukkit/World (Lorg/bukkit/Location;)I getBlockTypeIdAt", - "org/bukkit/block/Block ()I getTypeId", - "org/bukkit/block/Block (I)Z setTypeId", - "org/bukkit/block/Block (IZ)Z setTypeId", - "org/bukkit/block/Block (IBZ)Z setTypeIdAndData", - "org/bukkit/block/Block (B)V setData", - "org/bukkit/block/Block (BZ)V setData", - "org/bukkit/inventory/ItemStack ()I getTypeId", - "org/bukkit/inventory/ItemStack (I)V setTypeId" - ) ); - - // Paper start - Plugin rewrites - private static final Map SEARCH_AND_REMOVE = initReplacementsMap(); - private static Map initReplacementsMap() - { - Map getAndRemove = new HashMap<>(); - // Be wary of maven shade's relocations - getAndRemove.put( "org/bukkit/".concat( "craftbukkit/libs/it/unimi/dsi/fastutil/" ), "org/bukkit/".concat( "craftbukkit/libs/" ) ); // Remap fastutil to our location - - if ( Boolean.getBoolean( "debug.rewriteForIde" ) ) - { - // unversion incoming calls for pre-relocate debug work - final String NMS_REVISION_PACKAGE = "v1_13_R2/"; - - getAndRemove.put( "net/minecraft/".concat( "server/" + NMS_REVISION_PACKAGE ), NMS_REVISION_PACKAGE ); - getAndRemove.put( "org/bukkit/".concat( "craftbukkit/" + NMS_REVISION_PACKAGE ), NMS_REVISION_PACKAGE ); - } - - return getAndRemove; - } - - @Nonnull - private static String getOriginalOrRewrite(@Nonnull String original) - { - String rewrite = null; - for ( Map.Entry entry : SEARCH_AND_REMOVE.entrySet() ) - { - if ( original.contains( entry.getKey() ) ) - { - rewrite = original.replace( entry.getValue(), "" ); - } - } - - return rewrite != null ? rewrite : original; - } - // Paper end - - public static void main(String[] args) - { - OptionParser parser = new OptionParser(); - OptionSpec inputFlag = parser.acceptsAll( Arrays.asList( "i", "input" ) ).withRequiredArg().ofType( File.class ).required(); - OptionSpec outputFlag = parser.acceptsAll( Arrays.asList( "o", "output" ) ).withRequiredArg().ofType( File.class ).required(); - - OptionSet options = parser.parse( args ); - - File input = options.valueOf( inputFlag ); - File output = options.valueOf( outputFlag ); - - if ( input.isDirectory() ) - { - if ( !output.isDirectory() ) - { - System.err.println( "If input directory specified, output directory required too" ); - return; - } - - for ( File in : input.listFiles() ) - { - if ( in.getName().endsWith( ".jar" ) ) - { - convert( in, new File( output, in.getName() ) ); - } - } - } else - { - convert( input, output ); - } - } - - private static void convert(File in, File out) - { - System.out.println( "Attempting to convert " + in + " to " + out ); - - try - { - try ( JarFile inJar = new JarFile( in, false ) ) - { - JarEntry entry = inJar.getJarEntry( ".commodore" ); - if ( entry != null ) - { - return; - } - - try ( JarOutputStream outJar = new JarOutputStream( new FileOutputStream( out ) ) ) - { - for ( Enumeration entries = inJar.entries(); entries.hasMoreElements(); ) - { - entry = entries.nextElement(); - - try ( InputStream is = inJar.getInputStream( entry ) ) - { - byte[] b = ByteStreams.toByteArray( is ); - - if ( entry.getName().endsWith( ".class" ) ) - { - b = convert( b, false ); - entry = new JarEntry( entry.getName() ); - } - - outJar.putNextEntry( entry ); - outJar.write( b ); - } - } - - outJar.putNextEntry( new ZipEntry( ".commodore" ) ); - } - } - } catch ( Exception ex ) - { - System.err.println( "Fatal error trying to convert " + in ); - ex.printStackTrace(); - } - } - - public static byte[] convert(byte[] b, final boolean modern) - { - ClassReader cr = new ClassReader( b ); - ClassWriter cw = new ClassWriter( cr, 0 ); - - cr.accept( new ClassVisitor( Opcodes.ASM7, cw ) - { - // Paper start - Rewrite plugins - @Override - public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) - { - desc = getOriginalOrRewrite( desc ); - if ( signature != null ) { - signature = getOriginalOrRewrite( signature ); - } - - return super.visitField( access, name, desc, signature, value) ; - } - // Paper end - - @Override - public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) - { - return new MethodVisitor( api, super.visitMethod( access, name, desc, signature, exceptions ) ) - { - // Paper start - Plugin rewrites - @Override - public void visitInvokeDynamicInsn(String name, String desc, Handle bootstrapMethodHandle, Object... bootstrapMethodArguments) - { - // Paper start - Rewrite plugins - name = getOriginalOrRewrite( name ); - if ( desc != null ) - { - desc = getOriginalOrRewrite( desc ); - } - // Paper end - - super.visitInvokeDynamicInsn( name, desc, bootstrapMethodHandle, bootstrapMethodArguments ); - } - - @Override - public void visitTypeInsn(int opcode, String type) - { - type = getOriginalOrRewrite( type ); - - super.visitTypeInsn( opcode, type ); - } - - @Override - public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { - for ( int i = 0; i < local.length; i++ ) - { - if ( !( local[i] instanceof String ) ) { continue; } - - local[i] = getOriginalOrRewrite( (String) local[i] ); - } - - for ( int i = 0; i < stack.length; i++ ) - { - if ( !( stack[i] instanceof String ) ) { continue; } - - stack[i] = getOriginalOrRewrite( (String) stack[i] ); - } - - super.visitFrame( type, nLocal, local, nStack, stack ); - } - - - - @Override - public void visitLocalVariable(String name, String descriptor, String signature, Label start, Label end, int index) - { - descriptor = getOriginalOrRewrite( descriptor ); - - super.visitLocalVariable( name, descriptor, signature, start, end, index ); - } - // Paper end - - - - @Override - public void visitFieldInsn(int opcode, String owner, String name, String desc) - { - // Paper start - Rewrite plugins - owner = getOriginalOrRewrite( owner ); - if ( desc != null ) - { - desc = getOriginalOrRewrite( desc ); - } - // Paper end - - if ( modern ) - { - if ( owner.equals( "org/bukkit/Material" ) ) - { - switch ( name ) - { - case "CACTUS_GREEN": - name = "GREEN_DYE"; - break; - case "DANDELION_YELLOW": - name = "YELLOW_DYE"; - break; - case "ROSE_RED": - name = "RED_DYE"; - break; - case "SIGN": - name = "OAK_SIGN"; - break; - case "WALL_SIGN": - name = "OAK_WALL_SIGN"; - break; - } - } - - super.visitFieldInsn( opcode, owner, name, desc ); - return; - } - - if ( owner.equals( "org/bukkit/Material" ) ) - { - try - { - Material.valueOf( "LEGACY_" + name ); - } catch ( IllegalArgumentException ex ) - { - throw new AuthorNagException( "No legacy enum constant for " + name + ". Did you forget to define api-version: 1.13 in your plugin.yml?" ); - } - - super.visitFieldInsn( opcode, owner, "LEGACY_" + name, desc ); - return; - } - - if ( owner.equals( "org/bukkit/Art" ) ) - { - switch ( name ) - { - case "BURNINGSKULL": - super.visitFieldInsn( opcode, owner, "BURNING_SKULL", desc ); - return; - case "DONKEYKONG": - super.visitFieldInsn( opcode, owner, "DONKEY_KONG", desc ); - return; - } - } - - if ( owner.equals( "org/bukkit/DyeColor" ) ) - { - switch ( name ) - { - case "SILVER": - super.visitFieldInsn( opcode, owner, "LIGHT_GRAY", desc ); - return; - } - } - - if ( owner.equals( "org/bukkit/Particle" ) ) - { - switch ( name ) - { - case "BLOCK_CRACK": - case "BLOCK_DUST": - case "FALLING_DUST": - super.visitFieldInsn( opcode, owner, "LEGACY_" + name, desc ); - return; - } - } - - super.visitFieldInsn( opcode, owner, name, desc ); - } - - @Override - public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) - { - // SPIGOT-4496 - if ( owner.equals( "org/bukkit/map/MapView" ) && name.equals( "getId" ) && desc.equals( "()S" ) ) - { - // Should be same size on stack so just call other method - super.visitMethodInsn( opcode, owner, name, "()I", itf ); - return; - } - // SPIGOT-4608 - if ( (owner.equals( "org/bukkit/Bukkit" ) || owner.equals( "org/bukkit/Server" ) ) && name.equals( "getMap" ) && desc.equals( "(S)Lorg/bukkit/map/MapView;" ) ) - { - // Should be same size on stack so just call other method - super.visitMethodInsn( opcode, owner, name, "(I)Lorg/bukkit/map/MapView;", itf ); - return; - } - - // Paper start - Rewrite plugins - owner = getOriginalOrRewrite( owner) ; - if (desc != null) - { - desc = getOriginalOrRewrite(desc); - } - // Paper end - - if ( modern ) - { - if ( owner.equals( "org/bukkit/Material" ) ) - { - switch ( name ) - { - case "values": - super.visitMethodInsn( opcode, "org/bukkit/craftbukkit/util/CraftLegacy", "modern_" + name, desc, itf ); - return; - case "ordinal": - super.visitMethodInsn( Opcodes.INVOKESTATIC, "org/bukkit/craftbukkit/util/CraftLegacy", "modern_" + name, "(Lorg/bukkit/Material;)I", false ); - return; - } - } - - super.visitMethodInsn( opcode, owner, name, desc, itf ); - return; - } - - if ( owner.equals( "org/bukkit/ChunkSnapshot" ) && name.equals( "getBlockData" ) && desc.equals( "(III)I" ) ) - { - super.visitMethodInsn( opcode, owner, "getData", desc, itf ); - return; - } - - Type retType = Type.getReturnType( desc ); - - if ( EVIL.contains( owner + " " + desc + " " + name ) - || ( owner.startsWith( "org/bukkit/block/" ) && ( desc + " " + name ).equals( "()I getTypeId" ) ) - || ( owner.startsWith( "org/bukkit/block/" ) && ( desc + " " + name ).equals( "(I)Z setTypeId" ) ) - || ( owner.startsWith( "org/bukkit/block/" ) && ( desc + " " + name ).equals( "()Lorg/bukkit/Material; getType" ) ) ) - { - Type[] args = Type.getArgumentTypes( desc ); - Type[] newArgs = new Type[ args.length + 1 ]; - newArgs[0] = Type.getObjectType( owner ); - System.arraycopy( args, 0, newArgs, 1, args.length ); - - super.visitMethodInsn( Opcodes.INVOKESTATIC, "org/bukkit/craftbukkit/util/CraftEvil", name, Type.getMethodDescriptor( retType, newArgs ), false ); - return; - } - - if ( owner.equals( "org/bukkit/DyeColor" ) ) - { - if ( name.equals( "valueOf" ) && desc.equals( "(Ljava/lang/String;)Lorg/bukkit/DyeColor;" ) ) - { - super.visitMethodInsn( opcode, owner, "legacyValueOf", desc, itf ); - return; - } - } - - if ( owner.equals( "org/bukkit/Material" ) ) - { - if ( name.equals( "getMaterial" ) && desc.equals( "(I)Lorg/bukkit/Material;" ) ) - { - super.visitMethodInsn( opcode, "org/bukkit/craftbukkit/util/CraftEvil", name, desc, itf ); - return; - } - - switch ( name ) - { - case "values": - case "valueOf": - case "getMaterial": - case "matchMaterial": - super.visitMethodInsn( opcode, "org/bukkit/craftbukkit/util/CraftLegacy", name, desc, itf ); - return; - case "ordinal": - super.visitMethodInsn( Opcodes.INVOKESTATIC, "org/bukkit/craftbukkit/util/CraftLegacy", "ordinal", "(Lorg/bukkit/Material;)I", false ); - return; - case "name": - case "toString": - super.visitMethodInsn( Opcodes.INVOKESTATIC, "org/bukkit/craftbukkit/util/CraftLegacy", name, "(Lorg/bukkit/Material;)Ljava/lang/String;", false ); - return; - } - } - - if ( retType.getSort() == Type.OBJECT && retType.getInternalName().equals( "org/bukkit/Material" ) && owner.startsWith( "org/bukkit" ) ) - { - super.visitMethodInsn( opcode, owner, name, desc, itf ); - super.visitMethodInsn( Opcodes.INVOKESTATIC, "org/bukkit/craftbukkit/util/CraftLegacy", "toLegacy", "(Lorg/bukkit/Material;)Lorg/bukkit/Material;", false ); - return; - } - - super.visitMethodInsn( opcode, owner, name, desc, itf ); - } - }; - } - }, 0 ); - - return cw.toByteArray(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java deleted file mode 100644 index e7a741724..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java +++ /dev/null @@ -1,276 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import net.minecraft.server.ChatClickable; -import net.minecraft.server.ChatClickable.EnumClickAction; -import net.minecraft.server.ChatComponentText; -import net.minecraft.server.ChatMessage; -import net.minecraft.server.ChatModifier; -import net.minecraft.server.EnumChatFormat; -import net.minecraft.server.IChatBaseComponent; -import org.bukkit.ChatColor; - -public final class CraftChatMessage { - - private static final Pattern LINK_PATTERN = Pattern.compile("((?:(?:https?):\\/\\/)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[" + String.valueOf(org.bukkit.ChatColor.COLOR_CHAR) + " \\n]|$))))"); - private static final Map formatMap; - - static { - Builder builder = ImmutableMap.builder(); - for (EnumChatFormat format : EnumChatFormat.values()) { - builder.put(Character.toLowerCase(format.toString().charAt(1)), format); - } - formatMap = builder.build(); - } - - public static EnumChatFormat getColor(ChatColor color) { - return formatMap.get(color.getChar()); - } - - public static ChatColor getColor(EnumChatFormat format) { - return ChatColor.getByChar(format.character); - } - - private static class StringMessage { - private static final Pattern INCREMENTAL_PATTERN = Pattern.compile("(" + String.valueOf(org.bukkit.ChatColor.COLOR_CHAR) + "[0-9a-fk-or])|(\\n)|((?:(?:https?):\\/\\/)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[" + String.valueOf(org.bukkit.ChatColor.COLOR_CHAR) + " \\n]|$))))", Pattern.CASE_INSENSITIVE); - - 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 = null; - 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(java.util.Locale.ENGLISH).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((ChatClickable) null); - } - currentIndex = matcher.end(groupId); - } - - if (currentIndex < message.length()) { - appendNewComponent(message.length()); - } - - output = list.toArray(new IChatBaseComponent[list.size()]); - } - - 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 wrapOrNull(String message) { - return (message == null || message.isEmpty()) ? null : new ChatComponentText(message); - } - - public static IChatBaseComponent wrapOrEmpty(String message) { - return (message == null) ? new ChatComponentText("") : new ChatComponentText(message); - } - - public static IChatBaseComponent fromStringOrNull(String message) { - return fromStringOrNull(message, false); - } - - public static IChatBaseComponent fromStringOrNull(String message, boolean keepNewlines) { - return (message == null || message.isEmpty()) ? null : fromString(message, keepNewlines)[0]; - } - - 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 toJSON(IChatBaseComponent component) { - return IChatBaseComponent.ChatSerializer.a(component); - } - - public static String fromComponent(IChatBaseComponent component, EnumChatFormat defaultColor) { - if (component == null) return ""; - StringBuilder out = new StringBuilder(); - - for (IChatBaseComponent c : (Iterable) 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()); - } - 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.getText(); - 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.getSiblings()); - 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.getSiblings(); - for (int i = 0; i < extras.size(); i++) { - IChatBaseComponent comp = extras.get(i); - if (comp.getChatModifier() != null && comp.getChatModifier().getClickEvent() == null) { - extras.set(i, fixComponent(comp, matcher)); - } - } - - if (component instanceof ChatMessage) { - Object[] subs = ((ChatMessage) component).getArgs(); - 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().getClickEvent() == 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/src/main/java/org/bukkit/craftbukkit/util/CraftDamageSource.java b/src/main/java/org/bukkit/craftbukkit/util/CraftDamageSource.java deleted file mode 100644 index a8e2b5e20..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftDamageSource.java +++ /dev/null @@ -1,31 +0,0 @@ -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/src/main/java/org/bukkit/craftbukkit/util/CraftEvil.java b/src/main/java/org/bukkit/craftbukkit/util/CraftEvil.java deleted file mode 100644 index 1580db836..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftEvil.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import com.google.common.base.Preconditions; -import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -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.block.CraftBlock; -import org.bukkit.craftbukkit.block.CraftBlockState; -import org.bukkit.inventory.ItemStack; - -/** - * @deprecated do not use for any reason - */ -@Deprecated -public class CraftEvil { - - private static final Int2ObjectMap byId = new Int2ObjectLinkedOpenHashMap<>(); - - static { - for (Material material : Material.values()) { - if (!material.isLegacy()) { - continue; - } - - Preconditions.checkState(!byId.containsKey(material.getId()), "Duplicate material ID for", material); - byId.put(material.getId(), material); - } - } - - public static int getBlockTypeIdAt(World world, int x, int y, int z) { - return getId(world.getBlockAt(x, y, z).getType()); - } - - public static int getBlockTypeIdAt(World world, Location location) { - return getId(world.getBlockAt(location).getType()); - } - - public static Material getType(Block block) { - return CraftLegacy.toLegacyMaterial(((CraftBlock) block).getNMS()); - } - - public static Material getType(BlockState block) { - return CraftLegacy.toLegacyMaterial(((CraftBlockState) block).getHandle()); - } - - public static int getTypeId(Block block) { - return getId(block.getType()); - } - - public static boolean setTypeId(Block block, int type) { - block.setType(getMaterial(type)); - return true; - } - - public static boolean setTypeId(Block block, int type, boolean applyPhysics) { - block.setType(getMaterial(type), applyPhysics); - return true; - } - - public static boolean setTypeIdAndData(Block block, int type, byte data, boolean applyPhysics) { - block.setType(getMaterial(type), applyPhysics); - setData(block, data); - return true; - } - - public static void setData(Block block, byte data) { - ((CraftBlock) block).setData(data); - } - - public static void setData(Block block, byte data, boolean applyPhysics) { - ((CraftBlock) block).setData(data, applyPhysics); - } - - public static int getTypeId(BlockState state) { - return getId(state.getType()); - } - - public static boolean setTypeId(BlockState state, int type) { - state.setType(getMaterial(type)); - return true; - } - - public static int getTypeId(ItemStack stack) { - return getId(stack.getType()); - } - - public static void setTypeId(ItemStack stack, int type) { - stack.setType(getMaterial(type)); - } - - public static Material getMaterial(int id) { - return byId.get(id); - } - - public static int getId(Material material) { - return CraftLegacy.toLegacy(material).getId(); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftIconCache.java b/src/main/java/org/bukkit/craftbukkit/util/CraftIconCache.java deleted file mode 100644 index 3d90b3426..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftIconCache.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import org.bukkit.util.CachedServerIcon; - -public class CraftIconCache implements CachedServerIcon { - public final String value; - - public String getData() { return value; } // Paper - public CraftIconCache(final String value) { - this.value = value; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftLegacy.java b/src/main/java/org/bukkit/craftbukkit/util/CraftLegacy.java deleted file mode 100644 index 4539a4a77..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftLegacy.java +++ /dev/null @@ -1,437 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import com.google.common.base.Preconditions; -import com.mojang.datafixers.Dynamic; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import net.minecraft.server.Block; -import net.minecraft.server.BlockStateList; -import net.minecraft.server.Blocks; -import net.minecraft.server.DataConverterFlattenData; -import net.minecraft.server.DataConverterMaterialId; -import net.minecraft.server.DataConverterRegistry; -import net.minecraft.server.DataConverterTypes; -import net.minecraft.server.DispenserRegistry; -import net.minecraft.server.DynamicOpsNBT; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IBlockState; -import net.minecraft.server.IRegistry; -import net.minecraft.server.Item; -import net.minecraft.server.Items; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagCompound; -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.bukkit.material.MaterialData; - -/** - * This class may seem unnecessarily slow and complicated/repetitive however it - * is able to handle a lot more edge cases and invertible transformations (many - * of which are not immediately obvious) than any other alternative. If you do - * make changes to this class please make sure to contribute them back - * https://hub.spigotmc.org/stash/projects/SPIGOT/repos/craftbukkit/browse so - * that all may benefit. - * - * @deprecated legacy use only - */ -@Deprecated -public class CraftLegacy { - - private static final Map SPAWN_EGGS = new HashMap<>(); - private static final Set whitelistedStates = new HashSet<>(Arrays.asList("explode", "check_decay", "decayable", "facing")); - private static final Map materialToItem = new HashMap<>(16384); - private static final Map itemToMaterial = new HashMap<>(1024); - private static final Map materialToData = new HashMap<>(4096); - private static final Map dataToMaterial = new HashMap<>(4096); - private static final Map materialToBlock = new HashMap<>(4096); - private static final Map blockToMaterial = new HashMap<>(1024); - - public static Material toLegacy(Material material) { - if (material == null || material.isLegacy()) { - return material; - } - - return toLegacyData(material).getItemType(); - } - - public static MaterialData toLegacyData(Material material) { - Preconditions.checkArgument(!material.isLegacy(), "toLegacy on legacy Material"); - MaterialData mappedData; - - if (material.isBlock()) { - Block block = CraftMagicNumbers.getBlock(material); - IBlockData blockData = block.getBlockData(); - - // Try exact match first - mappedData = dataToMaterial.get(blockData); - // Fallback to any block - if (mappedData == null) { - mappedData = blockToMaterial.get(block); - // Fallback to matching item - if (mappedData == null) { - mappedData = itemToMaterial.get(block.getItem()); - } - } - } else { - Item item = CraftMagicNumbers.getItem(material); - mappedData = itemToMaterial.get(item); - } - - return (mappedData == null) ? new MaterialData(Material.LEGACY_AIR) : mappedData; - } - - public static IBlockData fromLegacyData(Material material, Block block, byte data) { - Preconditions.checkArgument(material.isLegacy(), "fromLegacyData on modern Material"); - - MaterialData materialData = new MaterialData(material, data); - - // Try exact match first - IBlockData converted = materialToData.get(materialData); - if (converted != null) { - return converted; - } - - // Fallback to any block - Block convertedBlock = materialToBlock.get(materialData); - if (convertedBlock != null) { - return convertedBlock.getBlockData(); - } - - // Return existing block - return block.getBlockData(); - } - - public static Item fromLegacyData(Material material, Item item, short data) { - Preconditions.checkArgument(material.isLegacy(), "fromLegacyData on modern Material. Did you forget to define api-version: 1.13 in your plugin.yml?"); - - MaterialData materialData = new MaterialData(material, (byte) data); - - // First try matching item - Item convertedItem = materialToItem.get(materialData); - if (convertedItem != null) { - return convertedItem; - } - - // Fallback to matching block - if (material.isBlock()) { - // Try exact match first - IBlockData converted = materialToData.get(materialData); - if (converted != null) { - return converted.getBlock().getItem(); - } - - // Fallback to any block - Block convertedBlock = materialToBlock.get(materialData); - if (convertedBlock != null) { - return convertedBlock.getItem(); - } - } - - // Return existing item - return item; - } - - public static byte toLegacyData(IBlockData blockData) { - return toLegacy(blockData).getData(); - } - - public static Material toLegacyMaterial(IBlockData blockData) { - return toLegacy(blockData).getItemType(); - } - - public static MaterialData toLegacy(IBlockData blockData) { - MaterialData mappedData; - - // Try exact match first - mappedData = dataToMaterial.get(blockData); - // Fallback to any block - if (mappedData == null) { - mappedData = blockToMaterial.get(blockData.getBlock()); - } - - return (mappedData == null) ? new MaterialData(Material.LEGACY_AIR) : mappedData; - } - - public static Material fromLegacy(Material material) { - if (material == null || !material.isLegacy()) { - return material; - } - - return fromLegacy(new MaterialData(material)); - } - - public static Material fromLegacy(MaterialData materialData) { - return fromLegacy(materialData, false); - } - - public static Material fromLegacy(MaterialData materialData, boolean itemPriority) { - Material material = materialData.getItemType(); - if (material == null || !material.isLegacy()) { - return material; - } - - Material mappedData = null; - - // Try item first - if (itemPriority) { - Item item = materialToItem.get(materialData); - if (item != null) { - mappedData = CraftMagicNumbers.getMaterial(item); - } - } - - if (mappedData == null && material.isBlock()) { - // Try exact match first - IBlockData iblock = materialToData.get(materialData); - if (iblock != null) { - mappedData = CraftMagicNumbers.getMaterial(iblock.getBlock()); - } - - // Fallback to any block - if (mappedData == null) { - Block block = materialToBlock.get(materialData); - if (block != null) { - mappedData = CraftMagicNumbers.getMaterial(block); - } - } - } - - // Fallback to matching item - if (!itemPriority && mappedData == null) { - Item item = materialToItem.get(materialData); - if (item != null) { - mappedData = CraftMagicNumbers.getMaterial(item); - } - } - - return (mappedData == null) ? Material.AIR : mappedData; - } - - public static Material[] values() { - Material[] values = Material.values(); - return Arrays.copyOfRange(values, Material.LEGACY_AIR.ordinal(), values.length); - } - - public static Material valueOf(String name) { - return (name.startsWith(Material.LEGACY_PREFIX)) ? Material.valueOf(name) : Material.valueOf(Material.LEGACY_PREFIX + name); - } - - public static Material getMaterial(String name) { - return (name.startsWith(Material.LEGACY_PREFIX)) ? Material.getMaterial(name) : Material.getMaterial(Material.LEGACY_PREFIX + name); - } - - public static Material matchMaterial(String name) { - return (name.startsWith(Material.LEGACY_PREFIX)) ? Material.matchMaterial(name) : Material.matchMaterial(Material.LEGACY_PREFIX + name); - } - - public static int ordinal(Material material) { - Preconditions.checkArgument(material.isLegacy(), "ordinal on modern Material"); - - return material.ordinal() - Material.LEGACY_AIR.ordinal(); - } - - public static String name(Material material) { - return material.name().substring(Material.LEGACY_PREFIX.length()); - } - - public static String toString(Material material) { - return name(material); - } - - public static Material[] modern_values() { - Material[] values = Material.values(); - return Arrays.copyOfRange(values, 0, Material.LEGACY_AIR.ordinal()); - } - - public static int modern_ordinal(Material material) { - if (material.isLegacy()) { - // SPIGOT-4002: Fix for eclipse compiler manually compiling in default statements to lookupswitch - throw new NoSuchFieldError("Legacy field ordinal: " + material); - } - - return material.ordinal(); - } - - static { - SPAWN_EGGS.put((byte) 0, Material.PIG_SPAWN_EGG); // Will be fixed by updateMaterial if possible - - SPAWN_EGGS.put((byte) EntityType.BAT.getTypeId(), Material.BAT_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.BLAZE.getTypeId(), Material.BLAZE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.CAVE_SPIDER.getTypeId(), Material.CAVE_SPIDER_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.CHICKEN.getTypeId(), Material.CHICKEN_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.COD.getTypeId(), Material.COD_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.COW.getTypeId(), Material.COW_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.CREEPER.getTypeId(), Material.CREEPER_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.DOLPHIN.getTypeId(), Material.DOLPHIN_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.DONKEY.getTypeId(), Material.DONKEY_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.ELDER_GUARDIAN.getTypeId(), Material.ELDER_GUARDIAN_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.ENDERMAN.getTypeId(), Material.ENDERMAN_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.ENDERMITE.getTypeId(), Material.ENDERMITE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.EVOKER.getTypeId(), Material.EVOKER_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.GHAST.getTypeId(), Material.GHAST_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.GUARDIAN.getTypeId(), Material.GUARDIAN_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.HORSE.getTypeId(), Material.HORSE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.HUSK.getTypeId(), Material.HUSK_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.LLAMA.getTypeId(), Material.LLAMA_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.MAGMA_CUBE.getTypeId(), Material.MAGMA_CUBE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.MUSHROOM_COW.getTypeId(), Material.MOOSHROOM_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.MULE.getTypeId(), Material.MULE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.OCELOT.getTypeId(), Material.OCELOT_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.PARROT.getTypeId(), Material.PARROT_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.PIG.getTypeId(), Material.PIG_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.PHANTOM.getTypeId(), Material.PHANTOM_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.POLAR_BEAR.getTypeId(), Material.POLAR_BEAR_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.PUFFERFISH.getTypeId(), Material.PUFFERFISH_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.RABBIT.getTypeId(), Material.RABBIT_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SALMON.getTypeId(), Material.SALMON_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SHEEP.getTypeId(), Material.SHEEP_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SHULKER.getTypeId(), Material.SHULKER_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SILVERFISH.getTypeId(), Material.SILVERFISH_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SKELETON.getTypeId(), Material.SKELETON_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SKELETON_HORSE.getTypeId(), Material.SKELETON_HORSE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SLIME.getTypeId(), Material.SLIME_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SPIDER.getTypeId(), Material.SPIDER_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.SQUID.getTypeId(), Material.SQUID_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.STRAY.getTypeId(), Material.STRAY_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.TROPICAL_FISH.getTypeId(), Material.TROPICAL_FISH_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.TURTLE.getTypeId(), Material.TURTLE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.VEX.getTypeId(), Material.VEX_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.VILLAGER.getTypeId(), Material.VILLAGER_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.VINDICATOR.getTypeId(), Material.VINDICATOR_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.WITCH.getTypeId(), Material.WITCH_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.WITHER_SKELETON.getTypeId(), Material.WITHER_SKELETON_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.WOLF.getTypeId(), Material.WOLF_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.ZOMBIE.getTypeId(), Material.ZOMBIE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.ZOMBIE_HORSE.getTypeId(), Material.ZOMBIE_HORSE_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.PIG_ZOMBIE.getTypeId(), Material.ZOMBIE_PIGMAN_SPAWN_EGG); - SPAWN_EGGS.put((byte) EntityType.ZOMBIE_VILLAGER.getTypeId(), Material.ZOMBIE_VILLAGER_SPAWN_EGG); - - DispenserRegistry.init(); - - for (Material material : Material.values()) { - if (!material.isLegacy()) { - continue; - } - - // Handle blocks - if (material.isBlock()) { - for (byte data = 0; data < 16; data++) { - MaterialData matData = new MaterialData(material, data); - Dynamic blockTag = DataConverterFlattenData.b(material.getId() << 4 | data); - // TODO: better skull conversion, chests - if (blockTag.get("Name").asString("").contains("%%FILTER_ME%%")) { - continue; - } - - String name = blockTag.get("Name").asString(""); - // TODO: need to fix - if (name.equals("minecraft:portal")) { - name = "minecraft:nether_portal"; - } - - Block block = IRegistry.BLOCK.get(new MinecraftKey(name)); - if (block == null) { - continue; - } - IBlockData blockData = block.getBlockData(); - BlockStateList states = block.getStates(); - - Optional propMap = blockTag.getElement("Properties"); - if (propMap.isPresent()) { - NBTTagCompound properties = propMap.get(); - for (String dataKey : properties.getKeys()) { - IBlockState state = states.a(dataKey); - - if (state == null) { - if (whitelistedStates.contains(dataKey)) { - continue; - } - throw new IllegalStateException("No state for " + dataKey); - } - - Preconditions.checkState(!properties.getString(dataKey).isEmpty(), "Empty data string"); - Optional opt = state.b(properties.getString(dataKey)); - - blockData = blockData.set(state, (Comparable) opt.get()); - } - } - - if (block == Blocks.AIR) { - continue; - } - - materialToData.put(matData, blockData); - if (!dataToMaterial.containsKey(blockData)) { - dataToMaterial.put(blockData, matData); - } - - materialToBlock.put(matData, block); - if (!blockToMaterial.containsKey(block)) { - blockToMaterial.put(block, matData); - } - } - } - - // Handle items (and second fallback for blocks) - int maxData = material.getMaxDurability() == 0 ? 16 : 1; - // Manually do oldold spawn eggs - if (material == Material.LEGACY_MONSTER_EGG) { - maxData = 121; // Vilager + 1 - } - - for (byte data = 0; data < maxData; data++) { - // Manually skip invalid oldold spawn - if (material == Material.LEGACY_MONSTER_EGG /*&& data != 0 && EntityType.fromId(data) == null*/) { // Mojang broke 18w19b - continue; - } - // Skip non item stacks for now (18w19b) - if (DataConverterMaterialId.a(material.getId()) == null) { - continue; - } - - MaterialData matData = new MaterialData(material, data); - - NBTTagCompound stack = new NBTTagCompound(); - stack.setInt("id", material.getId()); - stack.setShort("Damage", data); - - Dynamic converted = DataConverterRegistry.a().update(DataConverterTypes.ITEM_STACK, new Dynamic(DynamicOpsNBT.a, stack), -1, CraftMagicNumbers.INSTANCE.getDataVersion()); - - String newId = converted.get("id").asString(""); - // Recover spawn eggs with invalid data - if (newId.equals("minecraft:spawn_egg")) { - newId = "minecraft:pig_spawn_egg"; - } - - // Preconditions.checkState(newId.contains("minecraft:"), "Unknown new material for " + matData); - Item newMaterial = IRegistry.ITEM.get(new MinecraftKey(newId)); - - if (newMaterial == Items.AIR) { - continue; - } - - materialToItem.put(matData, newMaterial); - if (!itemToMaterial.containsKey(newMaterial)) { - itemToMaterial.put(newMaterial, matData); - } - } - - for (Map.Entry entry : SPAWN_EGGS.entrySet()) { - MaterialData matData = new MaterialData(Material.LEGACY_MONSTER_EGG, entry.getKey()); - Item newMaterial = CraftMagicNumbers.getItem(entry.getValue()); - - materialToItem.put(matData, newMaterial); - itemToMaterial.put(newMaterial, matData); - } - } - } - - public static void main(String[] args) { - System.err.println(""); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java deleted file mode 100644 index 921c16dff..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java +++ /dev/null @@ -1,324 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import com.google.common.base.Charsets; -import com.google.common.base.Preconditions; -import com.google.common.collect.Maps; -import com.google.common.io.Files; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.datafixers.Dynamic; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.minecraft.server.AdvancementDataWorld; -import net.minecraft.server.Block; -import net.minecraft.server.ChatDeserializer; -import net.minecraft.server.DataConverterRegistry; -import net.minecraft.server.DataConverterTypes; -import net.minecraft.server.DynamicOpsNBT; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IRegistry; -import net.minecraft.server.Item; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.MojangsonParser; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.SharedConstants; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.UnsafeValues; -import org.bukkit.advancement.Advancement; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.bukkit.plugin.InvalidPluginException; -import org.bukkit.plugin.PluginDescriptionFile; - -@SuppressWarnings("deprecation") -public final class CraftMagicNumbers implements UnsafeValues { - public static final UnsafeValues INSTANCE = new CraftMagicNumbers(); - - private CraftMagicNumbers() {} - - public static IBlockData getBlock(MaterialData material) { - return getBlock(material.getItemType(), material.getData()); - } - - public static IBlockData getBlock(Material material, byte data) { - return CraftLegacy.fromLegacyData(CraftLegacy.toLegacy(material), getBlock(material), data); - } - - public static MaterialData getMaterial(IBlockData data) { - return CraftLegacy.toLegacy(getMaterial(data.getBlock())).getNewData(toLegacyData(data)); - } - - public static Item getItem(Material material, short data) { - if (material.isLegacy()) { - return CraftLegacy.fromLegacyData(CraftLegacy.toLegacy(material), getItem(material), data); - } - - return getItem(material); - } - - public static MaterialData getMaterialData(Item item) { - return CraftLegacy.toLegacyData(getMaterial(item)); - } - - // ======================================================================== - private static final Map BLOCK_MATERIAL = new HashMap<>(); - private static final Map ITEM_MATERIAL = new HashMap<>(); - private static final Map MATERIAL_ITEM = new HashMap<>(); - private static final Map MATERIAL_BLOCK = new HashMap<>(); - - static { - for (Block block : IRegistry.BLOCK) { - BLOCK_MATERIAL.put(block, Material.getMaterial(IRegistry.BLOCK.getKey(block).getKey().toUpperCase(Locale.ROOT))); - } - - for (Item item : IRegistry.ITEM) { - ITEM_MATERIAL.put(item, Material.getMaterial(IRegistry.ITEM.getKey(item).getKey().toUpperCase(Locale.ROOT))); - } - - for (Material material : Material.values()) { - MinecraftKey key = key(material); - IRegistry.ITEM.getOptional(key).ifPresent((item) -> { - MATERIAL_ITEM.put(material, item); - }); - IRegistry.BLOCK.getOptional(key).ifPresent((block) -> { - MATERIAL_BLOCK.put(material, block); - }); - } - } - - public static Material getMaterial(Block block) { - return BLOCK_MATERIAL.get(block); - } - - public static Material getMaterial(Item item) { - return ITEM_MATERIAL.getOrDefault(item, Material.AIR); - } - - public static Item getItem(Material material) { - return MATERIAL_ITEM.get(material); - } - - public static Block getBlock(Material material) { - return MATERIAL_BLOCK.get(material); - } - - public static MinecraftKey key(Material mat) { - if (mat.isLegacy()) { - mat = CraftLegacy.fromLegacy(mat); - } - - return CraftNamespacedKey.toMinecraft(mat.getKey()); - } - // ======================================================================== - - public static byte toLegacyData(IBlockData data) { - return CraftLegacy.toLegacyData(data); - } - - @Override - public Material toLegacy(Material material) { - return CraftLegacy.toLegacy(material); - } - - @Override - public Material fromLegacy(Material material) { - return CraftLegacy.fromLegacy(material); - } - - @Override - public Material fromLegacy(MaterialData material) { - return CraftLegacy.fromLegacy(material); - } - - @Override - public Material fromLegacy(MaterialData material, boolean itemPriority) { - return CraftLegacy.fromLegacy(material, itemPriority); - } - - @Override - public BlockData fromLegacy(Material material, byte data) { - return CraftBlockData.fromData(getBlock(material, data)); - } - - @Override - public Material getMaterial(String material, int version) { - Preconditions.checkArgument(version <= this.getDataVersion(), "Newer version! Server downgrades are not supported!"); - - // Fastpath up to date materials - if (version == this.getDataVersion()) { - return Material.getMaterial(material); - } - - NBTTagCompound stack = new NBTTagCompound(); - stack.setString("id", "minecraft:" + material.toLowerCase(Locale.ROOT)); - - Dynamic converted = DataConverterRegistry.a().update(DataConverterTypes.ITEM_STACK, new Dynamic<>(DynamicOpsNBT.a, stack), version, this.getDataVersion()); - String newId = converted.get("id").asString(""); - - return Material.matchMaterial(newId); - } - - /** - * This string should be changed if the NMS mappings do. - * - * It has no meaning and should only be used as an equality check. Plugins - * which are sensitive to the NMS mappings may read it and refuse to load if - * it cannot be found or is different to the expected value. - * - * Remember: NMS is not supported API and may break at any time for any - * reason irrespective of this. There is often supported API to do the same - * thing as many common NMS usages. If not, you are encouraged to open a - * feature and/or pull request for consideration, or use a well abstracted - * third-party API such as ProtocolLib. - * - * @return string - */ - public String getMappingsVersion() { - return "11ae498d9cf909730659b6357e7c2afa"; - } - - @Override - public int getDataVersion() { - return SharedConstants.a().getWorldVersion(); - } - - @Override - public ItemStack modifyItemStack(ItemStack stack, String arguments) { - net.minecraft.server.ItemStack nmsStack = CraftItemStack.asNMSCopy(stack); - - try { - nmsStack.setTag((NBTTagCompound) MojangsonParser.parse(arguments)); - } catch (CommandSyntaxException ex) { - Logger.getLogger(CraftMagicNumbers.class.getName()).log(Level.SEVERE, null, ex); - } - - stack.setItemMeta(CraftItemStack.getItemMeta(nmsStack)); - - return stack; - } - - @Override - public Advancement loadAdvancement(NamespacedKey key, String advancement) { - if (Bukkit.getAdvancement(key) != null) { - throw new IllegalArgumentException("Advancement " + key + " already exists."); - } - - net.minecraft.server.Advancement.SerializedAdvancement nms = (net.minecraft.server.Advancement.SerializedAdvancement) ChatDeserializer.a(AdvancementDataWorld.DESERIALIZER, advancement, net.minecraft.server.Advancement.SerializedAdvancement.class); - if (nms != null) { - MinecraftServer.getServer().getAdvancementData().REGISTRY.a(Maps.newHashMap(Collections.singletonMap(CraftNamespacedKey.toMinecraft(key), nms))); - Advancement bukkit = Bukkit.getAdvancement(key); - - if (bukkit != null) { - File file = new File(MinecraftServer.getServer().bukkitDataPackFolder, "data" + File.separator + key.getNamespace() + File.separator + "advancements" + File.separator + key.getKey() + ".json"); - file.getParentFile().mkdirs(); - - try { - Files.write(advancement, file, Charsets.UTF_8); - } catch (IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Error saving advancement " + key, ex); - } - - MinecraftServer.getServer().getPlayerList().reload(); - - return bukkit; - } - } - - return null; - } - - @Override - public boolean removeAdvancement(NamespacedKey key) { - File file = new File(MinecraftServer.getServer().bukkitDataPackFolder, "data" + File.separator + key.getNamespace() + File.separator + "advancements" + File.separator + key.getKey() + ".json"); - return file.delete(); - } - - private static final List SUPPORTED_API = Arrays.asList("1.13", "1.14"); - - @Override - public void checkSupported(PluginDescriptionFile pdf) throws InvalidPluginException { - String minimumVersion = MinecraftServer.getServer().server.minimumAPI; - int minimumIndex = SUPPORTED_API.indexOf(minimumVersion); - - if (pdf.getAPIVersion() != null) { - int pluginIndex = SUPPORTED_API.indexOf(pdf.getAPIVersion()); - - if (pluginIndex == -1) { - throw new InvalidPluginException("Unsupported API version " + pdf.getAPIVersion()); - } - - if (pluginIndex < minimumIndex) { - throw new InvalidPluginException("Plugin API version " + pdf.getAPIVersion() + " is lower than the minimum allowed version. Please update or replace it."); - } - } else { - if (minimumIndex == -1) { - Bukkit.getLogger().log(Level.WARNING, "Plugin " + pdf.getFullName() + " does not specify an api-version."); - } else { - throw new InvalidPluginException("Plugin API version " + pdf.getAPIVersion() + " is lower than the minimum allowed version. Please update or replace it."); - } - } - } - - public static boolean isLegacy(PluginDescriptionFile pdf) { - return pdf.getAPIVersion() == null; - } - - @Override - public byte[] processClass(PluginDescriptionFile pdf, String path, byte[] clazz) { - try { - clazz = Commodore.convert(clazz, !isLegacy(pdf)); - } catch (Exception ex) { - Bukkit.getLogger().log(Level.SEVERE, "Fatal error trying to convert " + pdf.getFullName() + ":" + path, ex); - } - - return clazz; - } - - // Paper start - @Override - public String getTimingsServerName() { - return com.destroystokyo.paper.PaperConfig.timingsServerName; - } - - @Override - public com.destroystokyo.paper.util.VersionFetcher getVersionFetcher() { - return new com.destroystokyo.paper.PaperVersionFetcher(); - } - // Paper end - - /** - * This helper class represents the different NBT Tags. - *

    - * These should match NBTBase#getTypeId - */ - public static class NBT { - - public static final int TAG_END = 0; - public static final int TAG_BYTE = 1; - public static final int TAG_SHORT = 2; - public static final int TAG_INT = 3; - public static final int TAG_LONG = 4; - public static final int TAG_FLOAT = 5; - public static final int TAG_DOUBLE = 6; - public static final int TAG_BYTE_ARRAY = 7; - public static final int TAG_STRING = 8; - public static final int TAG_LIST = 9; - public static final int TAG_COMPOUND = 10; - public static final int TAG_INT_ARRAY = 11; - public static final int TAG_ANY_NUMBER = 99; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftNBTTagConfigSerializer.java b/src/main/java/org/bukkit/craftbukkit/util/CraftNBTTagConfigSerializer.java deleted file mode 100644 index fd0b99b78..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftNBTTagConfigSerializer.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; -import net.minecraft.server.MojangsonParser; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTList; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NBTTagDouble; -import net.minecraft.server.NBTTagInt; -import net.minecraft.server.NBTTagList; -import net.minecraft.server.NBTTagString; - -public class CraftNBTTagConfigSerializer { - - private static final Pattern ARRAY = Pattern.compile("^\\[.*]"); - private static final Pattern INTEGER = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)?i", Pattern.CASE_INSENSITIVE); - private static final Pattern DOUBLE = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?d", Pattern.CASE_INSENSITIVE); - private static final MojangsonParser MOJANGSON_PARSER = new MojangsonParser(new StringReader("")); - - public static Object serialize(NBTBase base) { - if (base instanceof NBTTagCompound) { - Map innerMap = new HashMap<>(); - for (String key : ((NBTTagCompound) base).getKeys()) { - innerMap.put(key, serialize(((NBTTagCompound) base).get(key))); - } - - return innerMap; - } else if (base instanceof NBTTagList) { - List baseList = new ArrayList<>(); - for (int i = 0; i < ((NBTList) base).size(); i++) { - baseList.add(serialize((NBTBase) ((NBTList) base).get(i))); - } - - return baseList; - } else if (base instanceof NBTTagString) { - return base.asString(); - } else if (base instanceof NBTTagInt) { // No need to check for doubles, those are covered by the double itself - return base.toString() + "i"; - } - - return base.toString(); - } - - public static NBTBase deserialize(Object object) { - if (object instanceof Map) { - NBTTagCompound compound = new NBTTagCompound(); - for (Map.Entry entry : ((Map) object).entrySet()) { - compound.set(entry.getKey(), deserialize(entry.getValue())); - } - - return compound; - } else if (object instanceof List) { - List list = (List) object; - if (list.isEmpty()) { - return new NBTTagList(); // Default - } - - NBTTagList tagList = new NBTTagList(); - for (Object tag : list) { - tagList.add(deserialize(tag)); - } - - return tagList; - } else if (object instanceof String) { - String string = (String) object; - - if (ARRAY.matcher(string).matches()) { - try { - return new MojangsonParser(new StringReader(string)).parseArray(); - } catch (CommandSyntaxException e) { - throw new RuntimeException("Could not deserialize found list ", e); - } - } else if (INTEGER.matcher(string).matches()) { //Read integers on our own - return new NBTTagInt(Integer.parseInt(string.substring(0, string.length() - 1))); - } else if (DOUBLE.matcher(string).matches()) { - return new NBTTagDouble(Double.parseDouble(string.substring(0, string.length() - 1))); - } else { - NBTBase nbtBase = MOJANGSON_PARSER.parseLiteral(string); - - if (nbtBase instanceof NBTTagInt) { // If this returns an integer, it did not use our method from above - return new NBTTagString(nbtBase.asString()); // It then is a string that was falsely read as an int - } else if (nbtBase instanceof NBTTagDouble) { - return new NBTTagString(String.valueOf(((NBTTagDouble) nbtBase).asDouble())); // Doubles add "d" at the end - } else { - return nbtBase; - } - } - } - - throw new RuntimeException("Could not deserialize NBTBase"); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftNamespacedKey.java b/src/main/java/org/bukkit/craftbukkit/util/CraftNamespacedKey.java deleted file mode 100644 index b308b1901..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftNamespacedKey.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import net.minecraft.server.MinecraftKey; -import org.bukkit.NamespacedKey; - -public final class CraftNamespacedKey { - - public CraftNamespacedKey() { - } - - public static NamespacedKey fromStringOrNull(String string) { - if (string == null || string.isEmpty()) { - return null; - } - MinecraftKey minecraft = MinecraftKey.a(string); - return (minecraft == null) ? null : fromMinecraft(minecraft); - } - - public static NamespacedKey fromString(String string) { - return fromMinecraft(new MinecraftKey(string)); - } - - public static NamespacedKey fromMinecraft(MinecraftKey minecraft) { - return new NamespacedKey(minecraft.getNamespace(), minecraft.getKey()); - } - - public static MinecraftKey toMinecraft(NamespacedKey key) { - return new MinecraftKey(key.getNamespace(), key.getKey()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftRayTraceResult.java b/src/main/java/org/bukkit/craftbukkit/util/CraftRayTraceResult.java deleted file mode 100644 index 5c978a261..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftRayTraceResult.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import net.minecraft.server.BlockPosition; -import net.minecraft.server.MovingObjectPosition; -import net.minecraft.server.MovingObjectPosition.EnumMovingObjectType; -import net.minecraft.server.MovingObjectPositionBlock; -import net.minecraft.server.MovingObjectPositionEntity; -import net.minecraft.server.Vec3D; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.entity.Entity; -import org.bukkit.util.RayTraceResult; -import org.bukkit.util.Vector; - -public class CraftRayTraceResult { - - private CraftRayTraceResult() {} - - public static RayTraceResult fromNMS(World world, MovingObjectPosition nmsHitResult) { - if (nmsHitResult == null || nmsHitResult.getType() == EnumMovingObjectType.MISS) return null; - - Vec3D nmsHitPos = nmsHitResult.getPos(); - Vector hitPosition = new Vector(nmsHitPos.x, nmsHitPos.y, nmsHitPos.z); - BlockFace hitBlockFace = null; - - if (nmsHitResult.getType() == EnumMovingObjectType.ENTITY) { - Entity hitEntity = ((MovingObjectPositionEntity) nmsHitResult).getEntity().getBukkitEntity(); - return new RayTraceResult(hitPosition, hitEntity, null); - } - - Block hitBlock = null; - BlockPosition nmsBlockPos = null; - if (nmsHitResult.getType() == EnumMovingObjectType.BLOCK) { - MovingObjectPositionBlock blockHitResult = (MovingObjectPositionBlock) nmsHitResult; - hitBlockFace = CraftBlock.notchToBlockFace(blockHitResult.getDirection()); - nmsBlockPos = blockHitResult.getBlockPosition(); - } - if (nmsBlockPos != null && world != null) { - hitBlock = world.getBlockAt(nmsBlockPos.getX(), nmsBlockPos.getY(), nmsBlockPos.getZ()); - } - return new RayTraceResult(hitPosition, hitBlock, hitBlockFace); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftVector.java b/src/main/java/org/bukkit/craftbukkit/util/CraftVector.java deleted file mode 100644 index d47432739..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftVector.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.bukkit.craftbukkit.util; - -public final class CraftVector { - - private CraftVector() { - } - - public static org.bukkit.util.Vector toBukkit(net.minecraft.server.Vec3D nms) { - return new org.bukkit.util.Vector(nms.x, nms.y, nms.z); - } - - public static net.minecraft.server.Vec3D toNMS(org.bukkit.util.Vector bukkit) { - return new net.minecraft.server.Vec3D(bukkit.getX(), bukkit.getY(), bukkit.getZ()); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/DatFileFilter.java b/src/main/java/org/bukkit/craftbukkit/util/DatFileFilter.java deleted file mode 100644 index 66ff685d7..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/DatFileFilter.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import java.io.File; -import java.io.FilenameFilter; - -public class DatFileFilter implements FilenameFilter { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".dat"); - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java b/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java deleted file mode 100644 index 5bae026dc..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import java.util.List; -import java.util.Random; -import java.util.function.Predicate; -import net.minecraft.server.AxisAlignedBB; -import net.minecraft.server.BiomeBase; -import net.minecraft.server.Block; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.ChunkStatus; -import net.minecraft.server.DifficultyDamageScaler; -import net.minecraft.server.Entity; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.EnumSkyBlock; -import net.minecraft.server.Fluid; -import net.minecraft.server.FluidType; -import net.minecraft.server.GeneratorAccess; -import net.minecraft.server.HeightMap; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IChunkAccess; -import net.minecraft.server.IChunkProvider; -import net.minecraft.server.ParticleParam; -import net.minecraft.server.SoundCategory; -import net.minecraft.server.SoundEffect; -import net.minecraft.server.TickList; -import net.minecraft.server.TileEntity; -import net.minecraft.server.World; -import net.minecraft.server.WorldBorder; -import net.minecraft.server.WorldData; -import net.minecraft.server.WorldProvider; - -public class DummyGeneratorAccess implements GeneratorAccess { - - public static final GeneratorAccess INSTANCE = new DummyGeneratorAccess(); - - protected DummyGeneratorAccess() { - } - - @Override - public long getSeed() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public TickList getBlockTickList() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public TickList getFluidTickList() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public World getMinecraftWorld() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public WorldData getWorldData() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public DifficultyDamageScaler getDamageScaler(BlockPosition bp) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public IChunkProvider getChunkProvider() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Random getRandom() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void update(BlockPosition bp, Block block) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playSound(EntityHuman eh, BlockPosition bp, SoundEffect se, SoundCategory sc, float f, float f1) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void addParticle(ParticleParam pp, double d, double d1, double d2, double d3, double d4, double d5) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void a(EntityHuman eh, int i, BlockPosition bp, int i1) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getEntities(Entity entity, AxisAlignedBB aabb, Predicate prdct) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List a(Class type, AxisAlignedBB aabb, Predicate prdct) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getPlayers() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getLightLevel(BlockPosition bp, int i) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public IChunkAccess getChunkAt(int i, int i1, ChunkStatus cs, boolean bln) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public BlockPosition getHighestBlockYAt(HeightMap.Type type, BlockPosition bp) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int a(HeightMap.Type type, int i, int i1) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int c() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public WorldBorder getWorldBorder() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean e() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getSeaLevel() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public WorldProvider getWorldProvider() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public BiomeBase getBiome(BlockPosition bp) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getBrightness(EnumSkyBlock esb, BlockPosition bp) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public TileEntity getTileEntity(BlockPosition bp) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public IBlockData getType(BlockPosition bp) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Fluid getFluid(BlockPosition bp) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean a(BlockPosition bp, Predicate prdct) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean setTypeAndData(BlockPosition blockposition, IBlockData iblockdata, int i) { - return false; - } - - @Override - public boolean a(BlockPosition blockposition, boolean flag) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean b(BlockPosition blockposition, boolean flag) { - throw new UnsupportedOperationException("Not supported yet."); - } - - // Paper start - if loaded util - @javax.annotation.Nullable - @Override - public IChunkAccess getChunkIfLoadedImmediately(int x, int z) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public IBlockData getTypeIfLoaded(BlockPosition blockposition) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Fluid getFluidIfLoaded(BlockPosition blockposition) { - throw new UnsupportedOperationException("Not supported yet."); - } - // Paper end -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java b/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java deleted file mode 100644 index 100b8566d..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.ConsoleHandler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class ForwardLogHandler extends ConsoleHandler { - private 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/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java b/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java deleted file mode 100644 index c407d783b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java +++ /dev/null @@ -1,110 +0,0 @@ -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; - - @Override - public int size() { - return getReference().size(); - } - - @Override - public boolean isEmpty() { - return getReference().isEmpty(); - } - - @Override - public boolean contains(Object o) { - return getReference().contains(o); - } - - @Override - public Iterator iterator() { - return getReference().iterator(); - } - - @Override - public Object[] toArray() { - return getReference().toArray(); - } - - @Override - public T[] toArray(T[] a) { - return getReference().toArray(a); - } - - @Override - public boolean add(E o) { - return getReference().add(o); - } - - @Override - public boolean remove(Object o) { - return getReference().remove(o); - } - - @Override - public boolean containsAll(Collection c) { - return getReference().containsAll(c); - } - - @Override - public boolean addAll(Collection c) { - return getReference().addAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return getReference().retainAll(c); - } - - @Override - public boolean removeAll(Collection c) { - return getReference().removeAll(c); - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java b/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java deleted file mode 100644 index f847a9dd6..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import java.util.HashSet; -import java.util.List; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.MinecraftServer; -import org.bukkit.entity.Player; - -public class LazyPlayerSet extends LazyHashSet { - - private final MinecraftServer server; - - public LazyPlayerSet(MinecraftServer server) { - this.server = server; - } - - @Override - HashSet makeReference() { - if (reference != null) { - throw new IllegalStateException("Reference already created!"); - } - List players = server.getPlayerList().players; - HashSet reference = new HashSet(players.size()); - for (EntityPlayer player : players) { - reference.add(player.getBukkitEntity()); - } - return reference; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java b/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java deleted file mode 100644 index 449e99d1b..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import net.minecraft.server.MinecraftServer; - -public class ServerShutdownThread extends Thread { - private final MinecraftServer server; - - public ServerShutdownThread(MinecraftServer server) { - this.server = server; - } - - @Override - public void run() { - try { - org.spigotmc.AsyncCatcher.enabled = false; // Spigot - org.spigotmc.AsyncCatcher.shuttingDown = true; // Paper - server.close(); - } finally { - try { - net.minecrell.terminalconsole.TerminalConsoleAppender.close(); // Paper - Use TerminalConsoleAppender - } catch (Exception e) { - } - } - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java b/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java deleted file mode 100644 index 1aec70a1f..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java +++ /dev/null @@ -1,294 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.AbstractList; -import java.util.Arrays; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.RandomAccess; - -// 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); - } - - @Override - public E get(int index) { - rangeCheck(index); - - return (E) data[index]; - } - - public E unsafeGet(int index) { - return (E) data[index]; - } - - @Override - public E set(int index, E element) { - rangeCheck(index); - - E old = (E) data[index]; - data[index] = element; - return old; - } - - @Override - public boolean add(E element) { - growIfNeeded(); - data[size++] = element; - return true; - } - - @Override - public void add(int index, E element) { - growIfNeeded(); - System.arraycopy(data, index, data, index + 1, size - index); - data[index] = element; - size++; - } - - @Override - 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; - } - - @Override - public boolean remove(Object o) { - int index = indexOf(o); - if (index >= 0) { - remove(index); - return true; - } - - return false; - } - - @Override - public int indexOf(Object o) { - for (int i = 0; i < size; i++) { - if (o == data[i] || o.equals(data[i])) { - return i; - } - } - - return -1; - } - - @Override - public boolean contains(Object o) { - return indexOf(o) >= 0; - } - - @Override - 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 { - for (int i = 0; i < data.length; i++) { - data[i] = 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); - } - } - - @Override - public int size() { - return size; - } - - @Override - public boolean isEmpty() { - return size == 0; - } - - @Override - 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; - } - - @Override - 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; - } - - @Override - public boolean hasNext() { - valid = index != size; - return valid; - } - - @Override - 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]; - } - - @Override - 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/src/main/java/org/bukkit/craftbukkit/util/Versioning.java b/src/main/java/org/bukkit/craftbukkit/util/Versioning.java deleted file mode 100644 index 674096cab..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/Versioning.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Bukkit; - -public final class Versioning { - public static String getBukkitVersion() { - String result = "Unknown-Version"; - - InputStream stream = Bukkit.class.getClassLoader().getResourceAsStream("META-INF/maven/com.destroystokyo.paper/paper-api/pom.properties"); - Properties properties = new Properties(); - - if (stream != null) { - try { - properties.load(stream); - - result = properties.getProperty("version"); - } catch (IOException ex) { - Logger.getLogger(Versioning.class.getName()).log(Level.SEVERE, "Could not get Bukkit version!", ex); - } - } - - return result; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/Waitable.java b/src/main/java/org/bukkit/craftbukkit/util/Waitable.java deleted file mode 100644 index a7ec02287..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/Waitable.java +++ /dev/null @@ -1,47 +0,0 @@ -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; - - @Override - 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/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java b/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java deleted file mode 100644 index 166f4ee08..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java +++ /dev/null @@ -1,184 +0,0 @@ -package org.bukkit.craftbukkit.util; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.apache.commons.lang.Validate; - -public final class WeakCollection implements Collection { - static final Object NO_VALUE = new Object(); - private final Collection> collection; - - public WeakCollection() { - collection = new ArrayList>(); - } - - @Override - public boolean add(T value) { - Validate.notNull(value, "Cannot add null value"); - return collection.add(new WeakReference(value)); - } - - @Override - 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; - } - - @Override - public void clear() { - collection.clear(); - } - - @Override - public boolean contains(Object object) { - if (object == null) { - return false; - } - for (T compare : this) { - if (object.equals(compare)) { - return true; - } - } - return false; - } - - @Override - public boolean containsAll(Collection collection) { - return toCollection().containsAll(collection); - } - - @Override - public boolean isEmpty() { - return !iterator().hasNext(); - } - - @Override - public Iterator iterator() { - return new Iterator() { - Iterator> it = collection.iterator(); - Object value = NO_VALUE; - - @Override - public boolean hasNext() { - Object value = this.value; - if (value != null && value != NO_VALUE) { - return true; - } - - Iterator> it = this.it; - value = null; - - while (it.hasNext()) { - WeakReference ref = it.next(); - value = ref.get(); - if (value == null) { - it.remove(); - } else { - this.value = value; - return true; - } - } - return false; - } - - @Override - 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; - } - - @Override - public void remove() throws IllegalStateException { - if (value != NO_VALUE) { - throw new IllegalStateException("No last element"); - } - - value = null; - it.remove(); - } - }; - } - - @Override - 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; - } - - @Override - 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; - } - - @Override - 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; - } - - @Override - public int size() { - int s = 0; - for (T value : this) { - s++; - } - return s; - } - - @Override - public Object[] toArray() { - return this.toArray(new Object[0]); - } - - @Override - public T[] toArray(T[] array) { - return toCollection().toArray(array); - } - - private Collection toCollection() { - ArrayList collection = new ArrayList(); - for (T value : this) { - collection.add(value); - } - return collection; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java b/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java deleted file mode 100644 index d5f4ece06..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java +++ /dev/null @@ -1,40 +0,0 @@ -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 + "msg", "Allows the user to privately message another player", PermissionDefault.TRUE, commands); - DefaultPermissions.registerPermission(PREFIX + "help", "Allows the user to access Vanilla command help", 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); - DefaultPermissions.registerPermission(PREFIX + "trigger", "Allows the use of the trigger command", PermissionDefault.TRUE, commands); - - DefaultPermissions.registerPermission("minecraft.admin.command_feedback", "Receive command broadcasts when sendCommandFeedback is true", PermissionDefault.OP, commands); - - commands.recalculatePermissibles(); - return commands; - } -} diff --git a/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java b/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java deleted file mode 100644 index 574aee621..000000000 --- a/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java +++ /dev/null @@ -1,21 +0,0 @@ -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); - // Spigot start - DefaultPermissions.registerPermission(ROOT + ".nbt.place", "Gives the user the ability to place restricted blocks with NBT in creative", org.bukkit.permissions.PermissionDefault.OP, parent); - DefaultPermissions.registerPermission(ROOT + ".nbt.copy", "Gives the user the ability to copy NBT in creative", org.bukkit.permissions.PermissionDefault.TRUE, parent); - DefaultPermissions.registerPermission(ROOT + ".debugstick", "Gives the user the ability to use the debug stick creative", org.bukkit.permissions.PermissionDefault.OP, parent); - // Spigot end - parent.recalculatePermissibles(); - } -} diff --git a/src/main/java/org/spigotmc/ActivationRange.java b/src/main/java/org/spigotmc/ActivationRange.java deleted file mode 100644 index 92601c581..000000000 --- a/src/main/java/org/spigotmc/ActivationRange.java +++ /dev/null @@ -1,278 +0,0 @@ -package org.spigotmc; - -import java.util.Collection; -import java.util.List; -import net.minecraft.server.AxisAlignedBB; -import net.minecraft.server.Chunk; -import net.minecraft.server.Entity; -import net.minecraft.server.EntityAmbient; -import net.minecraft.server.EntityAnimal; -import net.minecraft.server.EntityArrow; -import net.minecraft.server.EntityComplexPart; -import net.minecraft.server.EntityCreature; -import net.minecraft.server.EntityCreeper; -import net.minecraft.server.EntityEnderCrystal; -import net.minecraft.server.EntityEnderDragon; -import net.minecraft.server.EntityFallingBlock; // Paper -import net.minecraft.server.EntityFireball; -import net.minecraft.server.EntityFireworks; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.EntityLightning; -import net.minecraft.server.EntityLiving; -import net.minecraft.server.EntityMonster; -import net.minecraft.server.EntityProjectile; -import net.minecraft.server.EntityRaider; -import net.minecraft.server.EntitySheep; -import net.minecraft.server.EntitySlice; -import net.minecraft.server.EntitySlime; -import net.minecraft.server.EntityTNTPrimed; -import net.minecraft.server.EntityThrownTrident; -import net.minecraft.server.EntityVillager; -import net.minecraft.server.EntityWither; -import net.minecraft.server.MathHelper; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.World; -import co.aikar.timings.MinecraftTimings; - -public class ActivationRange -{ - - public enum ActivationType - { - MONSTER, - ANIMAL, - RAIDER, - MISC; - - AxisAlignedBB boundingBox = new AxisAlignedBB( 0, 0, 0, 0, 0, 0 ); - } - - static AxisAlignedBB maxBB = new AxisAlignedBB( 0, 0, 0, 0, 0, 0 ); - - /** - * Initializes an entities type on construction to specify what group this - * entity is in for activation ranges. - * - * @param entity - * @return group id - */ - public static ActivationType initializeEntityActivationType(Entity entity) - { - if ( entity instanceof EntityRaider ) - { - return ActivationType.RAIDER; - } else if ( entity instanceof EntityMonster || entity instanceof EntitySlime ) - { - return ActivationType.MONSTER; - } else if ( entity instanceof EntityCreature || entity instanceof EntityAmbient ) - { - return ActivationType.ANIMAL; - } else - { - return ActivationType.MISC; - } - } - - /** - * These entities are excluded from Activation range checks. - * - * @param entity Entity to initialize - * @param config Spigot config to determine ranges - * @return boolean If it should always tick. - */ - public static boolean initializeEntityActivationState(Entity entity, SpigotWorldConfig config) - { - if ( ( entity.activationType == ActivationType.MISC && config.miscActivationRange == 0 ) - || ( entity.activationType == ActivationType.RAIDER && config.raiderActivationRange == 0 ) - || ( entity.activationType == ActivationType.ANIMAL && config.animalActivationRange == 0 ) - || ( entity.activationType == ActivationType.MONSTER && config.monsterActivationRange == 0 ) - || entity instanceof EntityHuman - || entity instanceof EntityProjectile - || entity instanceof EntityEnderDragon - || entity instanceof EntityComplexPart - || entity instanceof EntityWither - || entity instanceof EntityFireball - || entity instanceof EntityLightning - || entity instanceof EntityTNTPrimed - || entity instanceof EntityFallingBlock // Paper - Always tick falling blocks - || entity instanceof EntityEnderCrystal - || entity instanceof EntityFireworks - || entity instanceof EntityThrownTrident ) - { - return true; - } - - return false; - } - - /** - * 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) - { - MinecraftTimings.entityActivationCheckTimer.startTiming(); - final int miscActivationRange = world.spigotConfig.miscActivationRange; - final int raiderActivationRange = world.spigotConfig.raiderActivationRange; - final int animalActivationRange = world.spigotConfig.animalActivationRange; - final int monsterActivationRange = world.spigotConfig.monsterActivationRange; - - int maxRange = Math.max( monsterActivationRange, animalActivationRange ); - maxRange = Math.max( maxRange, raiderActivationRange ); - maxRange = Math.max( maxRange, miscActivationRange ); - maxRange = Math.min( ( world.spigotConfig.viewDistance << 4 ) - 8, maxRange ); - - for ( EntityHuman player : world.getPlayers() ) - { - - player.activatedTick = MinecraftServer.currentTick; - maxBB = player.getBoundingBox().grow( maxRange, 256, maxRange ); - ActivationType.MISC.boundingBox = player.getBoundingBox().grow( miscActivationRange, 256, miscActivationRange ); - ActivationType.RAIDER.boundingBox = player.getBoundingBox().grow( raiderActivationRange, 256, raiderActivationRange ); - ActivationType.ANIMAL.boundingBox = player.getBoundingBox().grow( animalActivationRange, 256, animalActivationRange ); - ActivationType.MONSTER.boundingBox = player.getBoundingBox().grow( monsterActivationRange, 256, monsterActivationRange ); - - int i = MathHelper.floor( maxBB.minX / 16.0D ); - int j = MathHelper.floor( maxBB.maxX / 16.0D ); - int k = MathHelper.floor( maxBB.minZ / 16.0D ); - int l = MathHelper.floor( maxBB.maxZ / 16.0D ); - - for ( int i1 = i; i1 <= j; ++i1 ) - { - for ( int j1 = k; j1 <= l; ++j1 ) - { - Chunk chunk = (Chunk) world.getChunkIfLoadedImmediately( i1, j1 ); - if ( chunk != null ) - { - activateChunkEntities( chunk ); - } - } - } - } - MinecraftTimings.entityActivationCheckTimer.stopTiming(); - } - - /** - * Checks for the activation state of all entities in this chunk. - * - * @param chunk - */ - private static void activateChunkEntities(Chunk chunk) - { - for ( List slice : chunk.entitySlices ) - { - for ( Entity entity : (Collection) slice ) - { - if ( MinecraftServer.currentTick > entity.activatedTick ) - { - if ( entity.defaultActivationState ) - { - entity.activatedTick = MinecraftServer.currentTick; - continue; - } - if ( entity.activationType.boundingBox.c( entity.getBoundingBox() ) ) - { - entity.activatedTick = MinecraftServer.currentTick; - } - } - } - } - } - - /** - * 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.passengers.isEmpty() || entity.isPassenger() ) - { - 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.size() > 0 ) - { - return true; - } - if ( entity instanceof EntityCreature && ( (EntityCreature) entity ).getGoalTarget() != null ) - { - return true; - } - if ( entity instanceof EntityVillager && ( (EntityVillager) entity ).canBreed() ) - { - 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; - } - } - if (entity instanceof EntityCreeper && ((EntityCreeper) entity).isIgnited()) { // isExplosive - return true; - } - } - 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.inChunk || entity instanceof EntityFireworks ) { - 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; - } - return isActive; - } -} diff --git a/src/main/java/org/spigotmc/AsyncCatcher.java b/src/main/java/org/spigotmc/AsyncCatcher.java deleted file mode 100644 index 9f7d2ef93..000000000 --- a/src/main/java/org/spigotmc/AsyncCatcher.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.spigotmc; - -import net.minecraft.server.MinecraftServer; - -public class AsyncCatcher -{ - - public static boolean enabled = true; - public static boolean shuttingDown = false; // Paper - - public static void catchOp(String reason) - { - if ( enabled && Thread.currentThread() != MinecraftServer.getServer().serverThread ) - { - throw new IllegalStateException( "Asynchronous " + reason + "!" ); - } - } -} diff --git a/src/main/java/org/spigotmc/LimitStream.java b/src/main/java/org/spigotmc/LimitStream.java deleted file mode 100644 index 8c32e8b62..000000000 --- a/src/main/java/org/spigotmc/LimitStream.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.spigotmc; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import net.minecraft.server.NBTReadLimiter; - -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 * 8 ); - return super.read( b ); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException - { - limit.a( len * 8 ); - return super.read( b, off, len ); - } -} diff --git a/src/main/java/org/spigotmc/Metrics.java b/src/main/java/org/spigotmc/Metrics.java deleted file mode 100644 index 05d2d3d52..000000000 --- a/src/main/java/org/spigotmc/Metrics.java +++ /dev/null @@ -1,645 +0,0 @@ -/* - * Copyright 2011-2013 Tyler Blair. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and contributors and should not be interpreted as representing official policies, - * either expressed or implied, of anybody else. - */ -package org.spigotmc; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.scheduler.BukkitTask; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import net.minecraft.server.MinecraftServer; - -/** - *

    The metrics class obtains data about a plugin and submits statistics about it to the metrics backend.

    - * Public methods provided by this class:

    - * - * Graph createGraph(String name);
    - * void addCustomData(BukkitMetrics.Plotter plotter);
    - * void start();
    - *
    - */ -public class Metrics { - - /** - * The current revision number - */ - private static final int REVISION = 6; - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "https://mcstats.spigotmc.org"; - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/report/%s"; - /** - * The separator to use for custom data. This MUST NOT change unless you are hosting your own version of metrics and - * want to change it. - */ - private static final String CUSTOM_DATA_SEPARATOR = "~~"; - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 10; - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - /** - * The default graph, used for addCustomData when you don't want a specific graph - */ - private final Graph defaultGraph = new Graph("Default"); - /** - * The plugin configuration file - */ - private final YamlConfiguration configuration; - /** - * The plugin configuration file - */ - private final File configurationFile; - /** - * Unique server id - */ - private final String guid; - /** - * Debug mode - */ - private final boolean debug; - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - /** - * The scheduled task - */ - private volatile Timer task = null; - - public Metrics() throws IOException { - // load the config - configurationFile = getConfigFile(); - configuration = YamlConfiguration.loadConfiguration(configurationFile); - - // add some defaults - configuration.addDefault("opt-out", false); - configuration.addDefault("guid", UUID.randomUUID().toString()); - configuration.addDefault("debug", false); - - // Do we need to create the file? - if (configuration.get("guid", null) == null) { - configuration.options().header("http://mcstats.org").copyDefaults(true); - configuration.save(configurationFile); - } - - // Load the guid then - guid = configuration.getString("guid"); - debug = configuration.getBoolean("debug", false); - } - - /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics - * website. Plotters can be added to the graph object returned. - * - * @param name The name of the graph - * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) { - if (name == null) { - throw new IllegalArgumentException("Graph name cannot be null"); - } - - // Construct the graph object - final Graph graph = new Graph(name); - - // Now we can add our graph - graphs.add(graph); - - // and return back - return graph; - } - - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend - * - * @param graph The name of the graph - */ - public void addGraph(final Graph graph) { - if (graph == null) { - throw new IllegalArgumentException("Graph cannot be null"); - } - - graphs.add(graph); - } - - /** - * Adds a custom data plotter to the default graph - * - * @param plotter The plotter to use to plot custom data - */ - public void addCustomData(final Plotter plotter) { - if (plotter == null) { - throw new IllegalArgumentException("Plotter cannot be null"); - } - - // Add the plotter to the graph o/ - defaultGraph.addPlotter(plotter); - - // Ensure the default graph is included in the submitted graphs - graphs.add(defaultGraph); - } - - /** - * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the - * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 - * ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() { - synchronized (optOutLock) { - // Did we opt out? - if (isOptOut()) { - return false; - } - - // Is metrics already running? - if (task != null) { - return true; - } - - // Begin hitting the server with glorious data - task = new Timer("Spigot Metrics Thread", true); - - task.scheduleAtFixedRate(new TimerTask() { - private boolean firstPost = true; - - public void run() { - try { - // This has to be synchronized or it can collide with the disable method. - synchronized (optOutLock) { - // Disable Task, if it is running and the server owner decided to opt-out - if (isOptOut() && task != null) { - task.cancel(); - task = null; - // Tell all plotters to stop gathering information. - for (Graph graph : graphs) { - graph.onOptOut(); - } - } - } - - // We use the inverse of firstPost because if it is the first time we are posting, - // it is not a interval ping, so it evaluates to FALSE - // Each time thereafter it will evaluate to TRUE, i.e PING! - postPlugin(!firstPost); - - // After the first post we set firstPost to false - // Each post thereafter will be a ping - firstPost = false; - } catch (IOException e) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, TimeUnit.MINUTES.toMillis(PING_INTERVAL)); - - return true; - } - } - - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() { - synchronized (optOutLock) { - try { - // Reload the metrics file - configuration.load(getConfigFile()); - } catch (IOException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } catch (InvalidConfigurationException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - return configuration.getBoolean("opt-out", false); - } - } - - /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. - * - * @throws java.io.IOException - */ - public void enable() throws IOException { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) { - // Check if the server owner has already set opt-out, if not, set it. - if (isOptOut()) { - configuration.set("opt-out", false); - configuration.save(configurationFile); - } - - // Enable Task, if it is not running - if (task == null) { - start(); - } - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - * @throws java.io.IOException - */ - public void disable() throws IOException { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) { - // Check if the server owner has already set opt-out, if not, set it. - if (!isOptOut()) { - configuration.set("opt-out", true); - configuration.save(configurationFile); - } - - // Disable Task, if it is running - if (task != null) { - task.cancel(); - task = null; - } - } - } - - /** - * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() { - // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - // File pluginsFolder = plugin.getDataFolder().getParentFile(); - - // return => base/plugins/PluginMetrics/config.yml - return new File(new File((File) MinecraftServer.getServer().options.valueOf("plugins"), "PluginMetrics"), "config.yml"); - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException { - // Server software specific section - String pluginName = "Spigot"; - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled - String pluginVersion = (Metrics.class.getPackage().getImplementationVersion() != null) ? Metrics.class.getPackage().getImplementationVersion() : "unknown"; - String serverVersion = Bukkit.getVersion(); - int playersOnline = Bukkit.getServer().getOnlinePlayers().size(); - - // END server software specific section -- all code below does not use any code outside of this class / Java - - // Construct the post data - final StringBuilder data = new StringBuilder(); - - // The plugin's description file containg all of the plugin data such as name, version, author, etc - data.append(encode("guid")).append('=').append(encode(guid)); - encodeDataPair(data, "version", pluginVersion); - encodeDataPair(data, "server", serverVersion); - encodeDataPair(data, "players", Integer.toString(playersOnline)); - encodeDataPair(data, "revision", String.valueOf(REVISION)); - - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } - - encodeDataPair(data, "osname", osname); - encodeDataPair(data, "osarch", osarch); - encodeDataPair(data, "osversion", osversion); - encodeDataPair(data, "cores", Integer.toString(coreCount)); - encodeDataPair(data, "online-mode", Boolean.toString(onlineMode)); - encodeDataPair(data, "java_version", java_version); - - // If we're pinging, append it - if (isPing) { - encodeDataPair(data, "ping", "true"); - } - - // Acquire a lock on the graphs, which lets us make the assumption we also lock everything - // inside of the graph (e.g plotters) - synchronized (graphs) { - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) { - final Graph graph = iter.next(); - - for (Plotter plotter : graph.getPlotters()) { - // The key name to send to the metrics server - // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top - // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME - final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); - - // The value to send, which for the foreseeable future is just the string - // value of plotter.getValue() - final String value = Integer.toString(plotter.getValue()); - - // Add it to the http post data :) - encodeDataPair(data, key, value); - } - } - } - - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(pluginName))); - - // Connect to the website - URLConnection connection; - - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } else { - connection = url.openConnection(); - } - - connection.setDoOutput(true); - - // Write the data - final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); - writer.write(data.toString()); - writer.flush(); - - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - final String response = reader.readLine(); - - // close resources - writer.close(); - reader.close(); - - if (response == null || response.startsWith("ERR")) { - throw new IOException(response); //Throw the exception - } else { - // Is this the first update this hour? - if (response.contains("OK This is your first update this hour")) { - synchronized (graphs) { - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) { - final Graph graph = iter.next(); - - for (Plotter plotter : graph.getPlotters()) { - plotter.reset(); - } - } - } - } - } - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } catch (Exception e) { - return false; - } - } - - /** - *

    Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first key/value pair - * MUST be included manually, e.g:

    - * - * StringBuffer data = new StringBuffer(); - * data.append(encode("guid")).append('=').append(encode(guid)); - * encodeDataPair(data, "version", description.getVersion()); - * - * - * @param buffer the stringbuilder to append the data pair onto - * @param key the key value - * @param value the value - */ - private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException { - buffer.append('&').append(encode(key)).append('=').append(encode(value)); - } - - /** - * Encode text as UTF-8 - * - * @param text the text to encode - * @return the encoded text, as UTF-8 - */ - private static String encode(final String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Represents a custom graph on the website - */ - public static class Graph { - - /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is - * rejected - */ - private final String name; - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet(); - - private Graph(final String name) { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) { - plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - public Set getPlotters() { - return Collections.unmodifiableSet(plotters); - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - @Override - public boolean equals(final Object object) { - if (!(object instanceof Graph)) { - return false; - } - - final Graph graph = (Graph) object; - return graph.name.equals(name); - } - - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() { - } - } - - /** - * Interface used to collect custom data for a plugin - */ - public abstract static class Plotter { - - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name the name of the plotter to use, which will show up on the website - */ - public Plotter(final String name) { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may - * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called - * from any thread so care should be taken when accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() { - return name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() { - } - - @Override - public int hashCode() { - return getColumnName().hashCode(); - } - - @Override - public boolean equals(final Object object) { - if (!(object instanceof Plotter)) { - return false; - } - - final Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); - } - } -} diff --git a/src/main/java/org/spigotmc/RestartCommand.java b/src/main/java/org/spigotmc/RestartCommand.java deleted file mode 100644 index aefea3a9a..000000000 --- a/src/main/java/org/spigotmc/RestartCommand.java +++ /dev/null @@ -1,179 +0,0 @@ -package org.spigotmc; - -import java.io.File; -import java.util.List; -import net.minecraft.server.EntityPlayer; -import net.minecraft.server.MinecraftServer; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -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().processQueue.add( new Runnable() - { - @Override - public void run() - { - restart(); - } - } ); - } - return true; - } - - public static void restart() - { - restart( SpigotConfig.restartScript ); - } - - private static void restart(final String restartScript) - { - AsyncCatcher.enabled = false; // Disable async catcher incase it interferes with us - org.spigotmc.AsyncCatcher.shuttingDown = true; // Paper - try - { - // Paper - extract method and cleanup - boolean isRestarting = addShutdownHook( restartScript ); - if ( isRestarting ) - { - System.out.println( "Attempting to restart with " + SpigotConfig.restartScript ); - } else - { - System.out.println( "Startup script '" + SpigotConfig.restartScript + "' does not exist! Stopping server." ); - } - // Stop the watchdog - WatchdogThread.doStop(); - - shutdownServer( isRestarting ); - // Paper end - } catch ( Exception ex ) - { - ex.printStackTrace(); - } - } - - // Paper start - sync copied from above with minor changes, async added - private static void shutdownServer(boolean isRestarting) - { - if ( MinecraftServer.getServer().isMainThread() ) - { - // Kick all players - for ( EntityPlayer p : com.google.common.collect.ImmutableList.copyOf( MinecraftServer.getServer().getPlayerList().players ) ) - { - p.playerConnection.disconnect(SpigotConfig.restartMessage); - } - // Give the socket a chance to send the packets - try - { - Thread.sleep( 100 ); - } catch ( InterruptedException ex ) - { - } - - closeSocket(); - - // Actually shutdown - try - { - MinecraftServer.getServer().close(); // calls stop() - } catch ( Throwable t ) - { - } - - // Actually stop the JVM - System.exit( 0 ); - - } else - { - // Mark the server to shutdown at the end of the tick - MinecraftServer.getServer().safeShutdown( false, isRestarting ); - - // wait 10 seconds to see if we're actually going to try shutdown - try - { - Thread.sleep( 10000 ); - } - catch (InterruptedException ignored) - { - } - - // Check if we've actually hit a state where the server is going to safely shutdown - // if we have, let the server stop as usual - if (MinecraftServer.getServer().isStopped()) return; - - // If the server hasn't stopped by now, assume worse case and kill - closeSocket(); - System.exit( 0 ); - } - } - // Paper end - - // Paper - Split from moved code - private static void closeSocket() - { - // 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 ex ) - { - } - } - // Paper end - - // Paper start - copied from above and modified to return if the hook registered - private static boolean addShutdownHook(String restartScript) - { - String[] split = restartScript.split( " " ); - if ( split.length > 0 && new File( split[0] ).isFile() ) - { - Thread shutdownHook = new Thread() - { - @Override - public void run() - { - try - { - String os = System.getProperty( "os.name" ).toLowerCase(java.util.Locale.ENGLISH); - if ( os.contains( "win" ) ) - { - Runtime.getRuntime().exec( "cmd /c start " + restartScript ); - } else - { - Runtime.getRuntime().exec( "sh " + restartScript ); - } - } catch ( Exception e ) - { - e.printStackTrace(); - } - } - }; - - shutdownHook.setDaemon( true ); - Runtime.getRuntime().addShutdownHook( shutdownHook ); - return true; - } else - { - return false; - } - } - // Paper end - -} diff --git a/src/main/java/org/spigotmc/SlackActivityAccountant.java b/src/main/java/org/spigotmc/SlackActivityAccountant.java deleted file mode 100644 index aabc7ad20..000000000 --- a/src/main/java/org/spigotmc/SlackActivityAccountant.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.spigotmc; - -/** - * Keeps track of the time spent doing main thread activities that can be spread across ticks, - * so that such work doesn't exceed the current tick's estimated available slack time. Each - * activity is allotted a proportion of the expected slack time according to its weight, versus the - * estimated total weight of all activities. - */ -public class SlackActivityAccountant { - private double prevTickSlackWeightReciprocal = 1 / MIN_SLACK_WEIGHT; - private static final double MIN_SLACK_WEIGHT = 1 / 65536.0; - private double averageTickNonSlackNanos = 0; - private static final double AVERAGING_FACTOR = 0.375; - - private long currentActivityStartNanos; - private static final long OFF = -1; - private long currentActivityEndNanos; - private double tickSlackWeight; - private long tickSlackNanos; - - private double getSlackFraction(double slackWeight) { - return Math.min(slackWeight * this.prevTickSlackWeightReciprocal, 1); - } - - private int getEstimatedSlackNanos() { - return (int) Math.max(net.minecraft.server.MinecraftServer.TICK_TIME - (long) this.averageTickNonSlackNanos, 0); - } - - public void tickStarted() { - this.currentActivityStartNanos = OFF; - this.tickSlackWeight = 0; - this.tickSlackNanos = 0; - } - - public void startActivity(double slackWeight) { - double slackFraction0 = getSlackFraction(this.tickSlackWeight); - this.tickSlackWeight += slackWeight; - double slackFraction1 = getSlackFraction(this.tickSlackWeight); - - long t = System.nanoTime(); - this.currentActivityStartNanos = t; - this.currentActivityEndNanos = t + ((int) ((slackFraction1 - slackFraction0) * this.getEstimatedSlackNanos())); - } - - private void endActivity(long endNanos) { - this.tickSlackNanos += endNanos - this.currentActivityStartNanos; - this.currentActivityStartNanos = OFF; - } - - public boolean activityTimeIsExhausted() { - if (this.currentActivityStartNanos == OFF) { - return true; - } - - long t = System.nanoTime(); - if (t <= this.currentActivityEndNanos) { - return false; - } else { - this.endActivity(this.currentActivityEndNanos); - return true; - } - } - - public void endActivity() { - if (this.currentActivityStartNanos == OFF) { - return; - } - - this.endActivity(Math.min(System.nanoTime(), this.currentActivityEndNanos)); - } - - public void tickEnded(long tickNanos) { - this.prevTickSlackWeightReciprocal = 1 / Math.max(this.tickSlackWeight, MIN_SLACK_WEIGHT); - - long tickNonSlackNanos = tickNanos - this.tickSlackNanos; - this.averageTickNonSlackNanos = this.averageTickNonSlackNanos * (1 - AVERAGING_FACTOR) + tickNonSlackNanos * AVERAGING_FACTOR; - } -} diff --git a/src/main/java/org/spigotmc/SpigotCommand.java b/src/main/java/org/spigotmc/SpigotCommand.java deleted file mode 100644 index d0be3c3b5..000000000 --- a/src/main/java/org/spigotmc/SpigotCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.spigotmc; - -import java.io.File; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.WorldServer; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -public class SpigotCommand extends Command { - - public SpigotCommand(String name) { - super(name); - this.description = "Spigot related commands"; - this.usageMessage = "/spigot reload"; - this.setPermission("bukkit.command.spigot"); - } - - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) { - if (!testPermission(sender)) return true; - - if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); - return false; - } - - if (args[0].equals("reload")) { - Command.broadcastCommandMessage(sender, ChatColor.RED + "Please note that this command is not supported and may cause issues."); - Command.broadcastCommandMessage(sender, ChatColor.RED + "If you encounter any issues please use the /stop command to restart your server."); - - MinecraftServer console = MinecraftServer.getServer(); - org.spigotmc.SpigotConfig.init((File) console.options.valueOf("spigot-settings")); - for (WorldServer world : console.getWorlds()) { - world.spigotConfig.init(); - } - console.server.reloadCount++; - - Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Reload complete."); - } - - return true; - } -} diff --git a/src/main/java/org/spigotmc/SpigotConfig.java b/src/main/java/org/spigotmc/SpigotConfig.java deleted file mode 100644 index 359a0c8af..000000000 --- a/src/main/java/org/spigotmc/SpigotConfig.java +++ /dev/null @@ -1,391 +0,0 @@ -package org.spigotmc; - -import com.google.common.base.Throwables; -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.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import net.minecraft.server.AttributeRanged; -import net.minecraft.server.GenericAttributes; -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.MinecraftServer; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; -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; - -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 ex ) - { - } 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(); - commands.put( "spigot", new SpigotCommand( "spigot" ) ); - - version = getInt( "config-version", 12 ); - set( "config-version", 12 ); - readConfig( SpigotConfig.class, null ); - } - - public static void registerCommands() - { - for ( Map.Entry entry : commands.entrySet() ) - { - MinecraftServer.getServer().server.getCommandMap().register( entry.getKey(), "Spigot", entry.getValue() ); - } - - /* // Paper - Replace with our own - if ( metrics == null ) - { - try - { - metrics = new Metrics(); - metrics.start(); - } catch ( IOException ex ) - { - Bukkit.getServer().getLogger().log( Level.SEVERE, "Could not start metrics service", ex ); - } - } - */ // Paper end - } - - 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 (List) 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; - public static boolean sendNamespaced; - 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 ); - sendNamespaced = getBoolean( "commands.send-namespaced", true ); - } - - 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" ); - } - 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 ); // Paper - moved to PaperConfig - } - - 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 ); - } - - private static void nettyThreads() - { - int count = getInt( "settings.netty-threads", 4 ); - System.setProperty( "io.netty.eventLoopThreads", Integer.toString( count ) ); - Bukkit.getLogger().log( Level.INFO, "Using {0} threads for Netty based IO", count ); - } - - public static boolean disableStatSaving; - public static Map forcedStats = new HashMap<>(); - 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 ) ) - { - try - { - MinecraftKey key = new MinecraftKey( name ); - if ( IRegistry.CUSTOM_STAT.get( key ) == null ) - { - Bukkit.getLogger().log(Level.WARNING, "Ignoring non existent stats.forced-stats " + name); - continue; - } - forcedStats.put( key, section.getInt( name ) ); - } catch (Exception ex) - { - Bukkit.getLogger().log(Level.WARNING, "Ignoring invalid stats.forced-stats " + name); - } - } - } - } - - private static void tpsCommand() - { - commands.put( "tps", new TicksPerSecondCommand( "tps" ) ); - } - - public static int playerSample; - private static void playerSample() - { - playerSample = Math.max( getInt( "settings.sample-count", 12 ), 0 ); // Paper - Avoid negative counts - Bukkit.getLogger().log( Level.INFO, "Server Ping Player Sample Count: {0}", playerSample ); // Paper - Use logger - } - - 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", Arrays.asList( new String[] - { - "/skill" - } ) ); - } - - public static boolean silentCommandBlocks; - private static void silentCommandBlocks() - { - silentCommandBlocks = getBoolean( "commands.silent-commandblock-console", false ); - } - - 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", false ); - } - - public static double movedWronglyThreshold; - private static void movedWronglyThreshold() - { - movedWronglyThreshold = getDouble( "settings.moved-wrongly-threshold", 0.0625D ); - } - - public static double movedTooQuicklyMultiplier; - private static void movedTooQuicklyMultiplier() - { - movedTooQuicklyMultiplier = getDouble( "settings.moved-too-quickly-multiplier", 10.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.MAX_HEALTH ).maximum = maxHealth; - movementSpeed = getDouble( "settings.attribute.movementSpeed.max", movementSpeed ); - ( (AttributeRanged) GenericAttributes.MOVEMENT_SPEED ).maximum = movementSpeed; - attackDamage = getDouble( "settings.attribute.attackDamage.max", attackDamage ); - ( (AttributeRanged) GenericAttributes.ATTACK_DAMAGE ).maximum = attackDamage; - } - - public static boolean debug; - private static void debug() - { - debug = getBoolean( "settings.debug", false ); - - if ( debug && !LogManager.getRootLogger().isTraceEnabled() ) - { - // Enable debug logging - LoggerContext ctx = (LoggerContext) LogManager.getContext( false ); - Configuration conf = ctx.getConfiguration(); - conf.getLoggerConfig( LogManager.ROOT_LOGGER_NAME ).setLevel( org.apache.logging.log4j.Level.ALL ); - ctx.updateLoggers( conf ); - } - - if ( LogManager.getRootLogger().isTraceEnabled() ) - { - Bukkit.getLogger().info( "Debug logging is enabled" ); - } else - { - Bukkit.getLogger().info( "Debug logging is disabled" ); - } - } - - public static boolean disableAdvancementSaving; - public static List disabledAdvancements; - private static void disabledAdvancements() { - disableAdvancementSaving = getBoolean("advancements.disable-saving", false); - disabledAdvancements = getList("advancements.disabled", Arrays.asList(new String[]{"minecraft:story/disabled"})); - } -} diff --git a/src/main/java/org/spigotmc/SpigotWorldConfig.java b/src/main/java/org/spigotmc/SpigotWorldConfig.java deleted file mode 100644 index 4feea10de..000000000 --- a/src/main/java/org/spigotmc/SpigotWorldConfig.java +++ /dev/null @@ -1,347 +0,0 @@ -package org.spigotmc; - -import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; - -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 ); - - log( "-------- World Settings For [" + worldName + "] --------" ); - 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 ); - } - - public boolean getBoolean(String path, boolean def) // Paper - private -> public - { - config.addDefault( "world-settings.default." + path, def ); - return config.getBoolean( "world-settings." + worldName + "." + path, config.getBoolean( "world-settings.default." + path ) ); - } - - public double getDouble(String path, double def) // Paper - private -> public - { - config.addDefault( "world-settings.default." + path, def ); - return config.getDouble( "world-settings." + worldName + "." + path, config.getDouble( "world-settings.default." + path ) ); - } - - public int getInt(String path) // Paper - private -> public - { - return config.getInt( "world-settings." + worldName + "." + path ); - } - - public int getInt(String path, int def) // Paper - private -> public - { - config.addDefault( "world-settings.default." + path, def ); - return config.getInt( "world-settings." + worldName + "." + path, config.getInt( "world-settings.default." + path ) ); - } - - public List getList(String path, T def) // Paper - private -> public - { - config.addDefault( "world-settings.default." + path, def ); - return (List) config.getList( "world-settings." + worldName + "." + path, config.getList( "world-settings.default." + path ) ); - } - - public String getString(String path, String def) // Paper - private -> public - { - config.addDefault( "world-settings.default." + path, def ); - return config.getString( "world-settings." + worldName + "." + path, config.getString( "world-settings.default." + path ) ); - } - - private Object get(String path, Object def) - { - config.addDefault( "world-settings.default." + path, def ); - return config.get( "world-settings." + worldName + "." + path, config.get( "world-settings.default." + path ) ); - } - - // Crop growth rates - public int cactusModifier; - public int caneModifier; - public int melonModifier; - public int mushroomModifier; - public int pumpkinModifier; - public int saplingModifier; - public int beetrootModifier; - public int carrotModifier; - public int potatoModifier; - public int wheatModifier; - public int wartModifier; - public int vineModifier; - public int cocoaModifier; - public int bambooModifier; - public int sweetBerryModifier; - public int kelpModifier; - private int getAndValidateGrowth(String crop) - { - int modifier = getInt( "growth." + crop.toLowerCase(java.util.Locale.ENGLISH) + "-modifier", 100 ); - if ( modifier == 0 ) - { - log( "Cannot set " + crop + " growth to zero, defaulting to 100" ); - modifier = 100; - } - log( crop + " Growth Modifier: " + modifier + "%" ); - - return modifier; - } - private void growthModifiers() - { - cactusModifier = getAndValidateGrowth( "Cactus" ); - caneModifier = getAndValidateGrowth( "Cane" ); - melonModifier = getAndValidateGrowth( "Melon" ); - mushroomModifier = getAndValidateGrowth( "Mushroom" ); - pumpkinModifier = getAndValidateGrowth( "Pumpkin" ); - saplingModifier = getAndValidateGrowth( "Sapling" ); - beetrootModifier = getAndValidateGrowth( "Beetroot" ); - carrotModifier = getAndValidateGrowth( "Carrot" ); - potatoModifier = getAndValidateGrowth( "Potato" ); - wheatModifier = getAndValidateGrowth( "Wheat" ); - wartModifier = getAndValidateGrowth( "NetherWart" ); - vineModifier = getAndValidateGrowth( "Vine" ); - cocoaModifier = getAndValidateGrowth( "Cocoa" ); - bambooModifier = getAndValidateGrowth( "Bamboo" ); - sweetBerryModifier = getAndValidateGrowth( "SweetBerry" ); - kelpModifier = getAndValidateGrowth( "Kelp" ); - } - - public double itemMerge; - private void itemMerge() - { - itemMerge = getDouble("merge-radius.item", 2.5 ); - log( "Item Merge Radius: " + itemMerge ); - } - - public double expMerge; - private void expMerge() - { - expMerge = getDouble("merge-radius.exp", 3.0 ); - log( "Experience Merge Radius: " + expMerge ); - } - - public int viewDistance; - private void viewDistance() - { - if ( SpigotConfig.version < 12 ) - { - set( "view-distance", null ); - } - - Object viewDistanceObject = get( "view-distance", "default" ); - viewDistance = ( viewDistanceObject ) instanceof Number ? ( (Number) viewDistanceObject ).intValue() : -1; - if ( viewDistance <= 0 ) - { - viewDistance = Bukkit.getViewDistance(); - } - - viewDistance = Math.max( Math.min( viewDistance, 32 ), 3 ); - log( "View Distance: " + viewDistance ); - } - - public byte mobSpawnRange; - private void mobSpawnRange() - { - mobSpawnRange = (byte) getInt( "mob-spawn-range", 8 ); // Paper - Vanilla - log( "Mob Spawn Range: " + mobSpawnRange ); - } - - public int itemDespawnRate; - private void itemDespawnRate() - { - itemDespawnRate = getInt( "item-despawn-rate", 6000 ); - log( "Item Despawn Rate: " + itemDespawnRate ); - } - - public int animalActivationRange = 32; - public int monsterActivationRange = 32; - public int raiderActivationRange = 48; - public int miscActivationRange = 16; - public boolean tickInactiveVillagers = true; - private void activationRange() - { - animalActivationRange = getInt( "entity-activation-range.animals", animalActivationRange ); - monsterActivationRange = getInt( "entity-activation-range.monsters", monsterActivationRange ); - raiderActivationRange = getInt( "entity-activation-range.raiders", raiderActivationRange ); - miscActivationRange = getInt( "entity-activation-range.misc", miscActivationRange ); - tickInactiveVillagers = getBoolean( "entity-activation-range.tick-inactive-villagers", tickInactiveVillagers ); - log( "Entity Activation Range: An " + animalActivationRange + " / Mo " + monsterActivationRange + " / Ra " + raiderActivationRange + " / Mi " + miscActivationRange + " / Tiv " + tickInactiveVillagers ); - } - - 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 ); - log( "Entity Tracking Range: Pl " + playerTrackingRange + " / An " + animalTrackingRange + " / Mo " + monsterTrackingRange + " / Mi " + miscTrackingRange + " / 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 ); - if ( SpigotConfig.version < 11 ) - { - set( "ticks-per.hopper-check", 1 ); - } - hopperCheck = getInt( "ticks-per.hopper-check", 1 ); - hopperAmount = getInt( "hopper-amount", 1 ); - log( "Hopper Transfer: " + hopperTransfer + " Hopper Check: " + hopperCheck + " Hopper Amount: " + hopperAmount ); - } - - public int arrowDespawnRate; - private void arrowDespawnRate() - { - arrowDespawnRate = getInt( "arrow-despawn-rate", 1200 ); - log( "Arrow Despawn Rate: " + arrowDespawnRate ); - } - - public boolean zombieAggressiveTowardsVillager; - private void zombieAggressiveTowardsVillager() - { - zombieAggressiveTowardsVillager = getBoolean( "zombie-aggressive-towards-villager", true ); - log( "Zombie Aggressive Towards Villager: " + zombieAggressiveTowardsVillager ); - } - - public boolean nerfSpawnerMobs; - private void nerfSpawnerMobs() - { - nerfSpawnerMobs = getBoolean( "nerf-spawner-mobs", false ); - log( "Nerfing mobs spawned from spawners: " + nerfSpawnerMobs ); - } - - public boolean enableZombiePigmenPortalSpawns; - private void enableZombiePigmenPortalSpawns() - { - enableZombiePigmenPortalSpawns = getBoolean( "enable-zombie-pigmen-portal-spawns", true ); - log( "Allow Zombie Pigmen to spawn from portal blocks: " + enableZombiePigmenPortalSpawns ); - } - - 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 desertSeed; - public int iglooSeed; - public int jungleSeed; - public int swampSeed; - public int monumentSeed; - public int oceanSeed; - public int outpostSeed; - public int shipwreckSeed; - public int slimeSeed; - private void initWorldGenSeeds() - { - villageSeed = getInt( "seed-village", 10387312 ); - desertSeed = getInt( "seed-desert", 14357617 ); - iglooSeed = getInt( "seed-igloo", 14357618 ); - jungleSeed = getInt( "seed-jungle", 14357619 ); - swampSeed = getInt( "seed-swamp", 14357620 ); - monumentSeed = getInt( "seed-monument", 10387313 ); - shipwreckSeed = getInt( "seed-shipwreck", 165745295 ); - oceanSeed = getInt( "seed-ocean", 14357621 ); - outpostSeed = getInt( "seed-outpost", 165745296 ); - slimeSeed = getInt( "seed-slime", 987234911 ); - log( "Custom Map Seeds: Village: " + villageSeed + " Desert: " + desertSeed + " Igloo: " + iglooSeed + " Jungle: " + jungleSeed + " Swamp: " + swampSeed + " Monument: " + monumentSeed + "Ocean: " + oceanSeed + " Shipwreck: " + shipwreckSeed + " Slime: " + slimeSeed ); - } - - public float jumpWalkExhaustion; - public float jumpSprintExhaustion; - public float combatExhaustion; - public float regenExhaustion; - public float swimMultiplier; - public float sprintMultiplier; - public float otherMultiplier; - private void initHunger() - { - if ( SpigotConfig.version < 10 ) - { - set( "hunger.walk-exhaustion", null ); - set( "hunger.sprint-exhaustion", null ); - set( "hunger.combat-exhaustion", 0.1 ); - set( "hunger.regen-exhaustion", 6.0 ); - } - - jumpWalkExhaustion = (float) getDouble( "hunger.jump-walk-exhaustion", 0.05 ); - jumpSprintExhaustion = (float) getDouble( "hunger.jump-sprint-exhaustion", 0.2 ); - combatExhaustion = (float) getDouble( "hunger.combat-exhaustion", 0.1 ); - regenExhaustion = (float) getDouble( "hunger.regen-exhaustion", 6.0 ); - swimMultiplier = (float) getDouble( "hunger.swim-multiplier", 0.01 ); - sprintMultiplier = (float) getDouble( "hunger.sprint-multiplier", 0.1 ); - otherMultiplier = (float) getDouble( "hunger.other-multiplier", 0.0 ); - } - - public int currentPrimedTnt = 0; - public int maxTntTicksPerTick; - private void maxTntPerTick() { - if ( SpigotConfig.version < 7 ) - { - set( "max-tnt-per-tick", 100 ); - } - maxTntTicksPerTick = getInt( "max-tnt-per-tick", 100 ); - log( "Max TNT Explosions: " + maxTntTicksPerTick ); - } - - public int hangingTickFrequency; - private void hangingTickFrequency() - { - hangingTickFrequency = getInt( "hanging-tick-frequency", 100 ); - } - - public int tileMaxTickTime; - public int entityMaxTickTime; - private void maxTickTimes() - { - tileMaxTickTime = getInt("max-tick-time.tile", 50); - entityMaxTickTime = getInt("max-tick-time.entity", 50); - log("Tile Max Tick Time: " + tileMaxTickTime + "ms Entity max Tick Time: " + entityMaxTickTime + "ms"); - } - - public double squidSpawnRangeMin; - private void squidSpawnRange() - { - squidSpawnRangeMin = getDouble("squid-spawn-range.min", 45.0D); - } -} diff --git a/src/main/java/org/spigotmc/TickLimiter.java b/src/main/java/org/spigotmc/TickLimiter.java deleted file mode 100644 index 23a39382b..000000000 --- a/src/main/java/org/spigotmc/TickLimiter.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.spigotmc; - -public class TickLimiter { - - private final int maxTime; - private long startTime; - - public TickLimiter(int maxtime) { - this.maxTime = maxtime; - } - - public void initTick() { - startTime = System.currentTimeMillis(); - } - - public boolean shouldContinue() { - long remaining = System.currentTimeMillis() - startTime; - return remaining < maxTime; - } -} diff --git a/src/main/java/org/spigotmc/TicksPerSecondCommand.java b/src/main/java/org/spigotmc/TicksPerSecondCommand.java deleted file mode 100644 index 6d21c3269..000000000 --- a/src/main/java/org/spigotmc/TicksPerSecondCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.spigotmc; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -public class TicksPerSecondCommand extends Command -{ - - public TicksPerSecondCommand(String name) - { - super( name ); - this.description = "Gets the current ticks per second for the server"; - this.usageMessage = "/tps"; - this.setPermission( "bukkit.command.tps" ); - } - - @Override - public boolean execute(CommandSender sender, String currentAlias, String[] args) - { - if ( !testPermission( sender ) ) - { - return true; - } - - // Paper start - Further improve tick handling - double[] tps = org.bukkit.Bukkit.getTPS(); - String[] tpsAvg = new String[tps.length]; - - for ( int i = 0; i < tps.length; i++) { - tpsAvg[i] = format( tps[i] ); - } - sender.sendMessage( ChatColor.GOLD + "TPS from last 1m, 5m, 15m: " + org.apache.commons.lang.StringUtils.join(tpsAvg, ", ")); - // Paper end - - return true; - } - - private static String format(double tps) // Paper - Made static - { - return ( ( tps > 18.0 ) ? ChatColor.GREEN : ( tps > 16.0 ) ? ChatColor.YELLOW : ChatColor.RED ).toString() - + ( ( tps > 20.0 ) ? "*" : "" ) + Math.min( Math.round( tps * 100.0 ) / 100.0, 20.0 ); - } -} diff --git a/src/main/java/org/spigotmc/TrackingRange.java b/src/main/java/org/spigotmc/TrackingRange.java deleted file mode 100644 index 6f8e6c1d0..000000000 --- a/src/main/java/org/spigotmc/TrackingRange.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.spigotmc; - -import net.minecraft.server.Entity; -import net.minecraft.server.EntityExperienceOrb; -import net.minecraft.server.EntityGhast; -import net.minecraft.server.EntityItem; -import net.minecraft.server.EntityItemFrame; -import net.minecraft.server.EntityPainting; -import net.minecraft.server.EntityPlayer; - -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 == ActivationRange.ActivationType.MONSTER || entity.activationType == ActivationRange.ActivationType.RAIDER ) - { - return config.monsterTrackingRange; - } else if ( entity instanceof EntityGhast ) - { - if ( config.monsterTrackingRange > config.monsterActivationRange ) - { - return config.monsterTrackingRange; - } else - { - return config.monsterActivationRange; - } - } else if ( entity.activationType == ActivationRange.ActivationType.ANIMAL ) - { - 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/src/main/java/org/spigotmc/ValidateUtils.java b/src/main/java/org/spigotmc/ValidateUtils.java deleted file mode 100644 index 58a953481..000000000 --- a/src/main/java/org/spigotmc/ValidateUtils.java +++ /dev/null @@ -1,14 +0,0 @@ -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/src/main/java/org/spigotmc/WatchdogThread.java b/src/main/java/org/spigotmc/WatchdogThread.java deleted file mode 100644 index 6ca0ebfde..000000000 --- a/src/main/java/org/spigotmc/WatchdogThread.java +++ /dev/null @@ -1,180 +0,0 @@ -package org.spigotmc; - -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; -import com.destroystokyo.paper.PaperConfig; -import com.destroystokyo.paper.io.chunk.ChunkTaskManager; // Paper -import net.minecraft.server.MinecraftServer; -import org.bukkit.Bukkit; - -public class WatchdogThread extends Thread -{ - - private static WatchdogThread instance; - private final long timeoutTime; - private final long earlyWarningEvery; // Paper - Timeout time for just printing a dump but not restarting - private final long earlyWarningDelay; // Paper - public static volatile boolean hasStarted; // Paper - private long lastEarlyWarning; // Paper - Keep track of short dump times to avoid spamming console with short dumps - 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; - earlyWarningEvery = Math.min(PaperConfig.watchdogPrintEarlyWarningEvery, timeoutTime); // Paper - earlyWarningDelay = Math.min(PaperConfig.watchdogPrintEarlyWarningDelay, timeoutTime); // Paper - } - - private static long monotonicMillis() - { - return System.nanoTime() / 1000000L; - } - - 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 = monotonicMillis(); - } - - public static void doStop() - { - if ( instance != null ) - { - instance.stopping = true; - } - } - - @Override - public void run() - { - while ( !stopping ) - { - // Paper start - Logger log = Bukkit.getServer().getLogger(); - long currentTime = monotonicMillis(); - if ( lastTick != 0 && currentTime > lastTick + earlyWarningEvery && !Boolean.getBoolean("disable.watchdog") ) - { - boolean isLongTimeout = currentTime > lastTick + timeoutTime; - // Don't spam early warning dumps - if ( !isLongTimeout && (earlyWarningEvery <= 0 || !hasStarted || currentTime < lastEarlyWarning + earlyWarningEvery || currentTime < lastTick + earlyWarningDelay)) continue; - lastEarlyWarning = currentTime; - if (isLongTimeout) { - // Paper end - log.log( Level.SEVERE, "------------------------------" ); - log.log( Level.SEVERE, "The server has stopped responding! This is (probably) not a Paper bug." ); // Paper - log.log( Level.SEVERE, "If you see a plugin in the Server thread dump below, then please report it to that author" ); - log.log( Level.SEVERE, "\t *Especially* if it looks like HTTP or MySQL operations are occurring" ); - log.log( Level.SEVERE, "If you see a world save or edit, then it means you did far more than your server can handle at once" ); - log.log( Level.SEVERE, "\t If this is the case, consider increasing timeout-time in spigot.yml but note that this will replace the crash with LARGE lag spikes" ); - log.log( Level.SEVERE, "If you are unsure or still think this is a Paper bug, please report this to https://github.com/PaperMC/Paper/issues" ); - 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() ); - ChunkTaskManager.dumpAllChunkLoadInfo(); // Paper - // - if ( net.minecraft.server.World.lastPhysicsProblem != null ) - { - 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.lastPhysicsProblem ); - } - // Paper start - Warn in watchdog if an excessive velocity was ever set - if ( org.bukkit.craftbukkit.CraftServer.excessiveVelEx != null ) - { - log.log( Level.SEVERE, "------------------------------" ); - log.log( Level.SEVERE, "During the run of the server, a plugin set an excessive velocity on an entity" ); - log.log( Level.SEVERE, "This may be the cause of the issue, or it may be entirely unrelated" ); - log.log( Level.SEVERE, org.bukkit.craftbukkit.CraftServer.excessiveVelEx.getMessage()); - for ( StackTraceElement stack : org.bukkit.craftbukkit.CraftServer.excessiveVelEx.getStackTrace() ) - { - log.log( Level.SEVERE, "\t\t" + stack ); - } - } - // Paper end - } else - { - log.log(Level.SEVERE, "--- DO NOT REPORT THIS TO PAPER - THIS IS NOT A BUG OR A CRASH - " + Bukkit.getServer().getVersion() + " ---"); - log.log(Level.SEVERE, "The server has not responded for " + (currentTime - lastTick) / 1000 + " seconds! Creating thread dump"); - } - // Paper end - Different message for short timeout - log.log( Level.SEVERE, "------------------------------" ); - log.log( Level.SEVERE, "Server thread dump (Look for plugins here before reporting to Paper!):" ); // Paper - log.log( Level.SEVERE, "The server is waiting on these chunks: " + ChunkTaskManager.getChunkWaitInfo() ); // Paper - async chunk debug - dumpThread( ManagementFactory.getThreadMXBean().getThreadInfo( MinecraftServer.getServer().serverThread.getId(), Integer.MAX_VALUE ), log ); - log.log( Level.SEVERE, "------------------------------" ); - // - // Paper start - Only print full dump on long timeouts - if ( isLongTimeout ) - { - log.log( Level.SEVERE, "Entire Thread Dump:" ); - ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads( true, true ); - for ( ThreadInfo thread : threads ) - { - dumpThread( thread, log ); - } - } else { - log.log(Level.SEVERE, "--- DO NOT REPORT THIS TO PAPER - THIS IS NOT A BUG OR A CRASH ---"); - } - - - log.log( Level.SEVERE, "------------------------------" ); - - if ( isLongTimeout ) - { - if ( restart ) - { - RestartCommand.restart(); - } - break; - } // Paper end - } - - try - { - sleep( 1000 ); // Paper - Reduce check time to every second instead of every ten seconds, more consistent and allows for short timeout - } 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/src/main/resources/configurations/bukkit.yml b/src/main/resources/configurations/bukkit.yml deleted file mode 100644 index 2ba4fe8e2..000000000 --- a/src/main/resources/configurations/bukkit.yml +++ /dev/null @@ -1,37 +0,0 @@ -# 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 -# https://www.spigotmc.org/go/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 https://www.spigotmc.org/go/irc ) -# Forums: https://www.spigotmc.org/ -# Bug tracker: https://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: 10 - water-animals: 15 - ambient: 15 -chunk-gc: - period-in-ticks: 600 - load-threshold: 0 -ticks-per: - animal-spawns: 400 - monster-spawns: 1 - autosave: 6000 -aliases: now-in-commands.yml diff --git a/src/main/resources/configurations/commands.yml b/src/main/resources/configurations/commands.yml deleted file mode 100644 index 0f45c397d..000000000 --- a/src/main/resources/configurations/commands.yml +++ /dev/null @@ -1,17 +0,0 @@ -# This is the commands configuration file for Bukkit. -# For documentation on how to make use of this file, check out the Bukkit Wiki at -# https://www.spigotmc.org/go/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 https://www.spigotmc.org/go/irc ) -# Forums: https://www.spigotmc.org/ -# Bug tracker: https://www.spigotmc.org/go/bugs - -command-block-overrides: [] -ignore-vanilla-permissions: false -aliases: - icanhasbukkit: - - "version $1-" diff --git a/src/main/resources/configurations/help.yml b/src/main/resources/configurations/help.yml deleted file mode 100644 index 15c3d0707..000000000 --- a/src/main/resources/configurations/help.yml +++ /dev/null @@ -1,55 +0,0 @@ -# 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/src/main/resources/log4j2.component.properties b/src/main/resources/log4j2.component.properties deleted file mode 100644 index ee7c90784..000000000 --- a/src/main/resources/log4j2.component.properties +++ /dev/null @@ -1 +0,0 @@ -Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml deleted file mode 100644 index 6711e6dff..000000000 --- a/src/main/resources/log4j2.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/test/java/org/bukkit/ArtTest.java b/src/test/java/org/bukkit/ArtTest.java deleted file mode 100644 index e6888dec5..000000000 --- a/src/test/java/org/bukkit/ArtTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.bukkit; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import net.minecraft.server.Paintings; - -import org.bukkit.craftbukkit.CraftArt; -import org.junit.Test; - -import com.google.common.collect.Lists; -import org.bukkit.support.AbstractTestingBase; - -public class ArtTest extends AbstractTestingBase { - private static final int UNIT_MULTIPLIER = 16; - - @Test - public void verifyMapping() { - List arts = Lists.newArrayList(Art.values()); - - for (MinecraftKey key : IRegistry.MOTIVE.keySet()) { - Paintings enumArt = IRegistry.MOTIVE.get(key); - String name = key.getKey(); - int width = enumArt.b() / UNIT_MULTIPLIER; - int height = enumArt.c() / UNIT_MULTIPLIER; - - Art subject = CraftArt.NotchToBukkit(enumArt); - - String message = String.format("org.bukkit.Art is missing '%s'", name); - assertNotNull(message, subject); - - assertThat(Art.getByName(name), is(subject)); - assertThat("Art." + subject + "'s width", subject.getBlockWidth(), is(width)); - assertThat("Art." + subject + "'s height", subject.getBlockHeight(), is(height)); - - arts.remove(subject); - } - - assertThat("org.bukkit.Art has too many arts", arts, is(Collections.EMPTY_LIST)); - } - - @Test - public void testCraftArtToNotch() { - Map cache = new HashMap<>(); - for (Art art : Art.values()) { - Paintings enumArt = CraftArt.BukkitToNotch(art); - assertNotNull(art.name(), enumArt); - assertThat(art.name(), cache.put(enumArt, art), is(nullValue())); - } - } - - @Test - public void testCraftArtToBukkit() { - Map cache = new EnumMap(Art.class); - for (Paintings enumArt : (Iterable) IRegistry.MOTIVE) { // Eclipse fail - Art art = CraftArt.NotchToBukkit(enumArt); - assertNotNull("Could not CraftArt.NotchToBukkit " + enumArt, art); - assertThat("Duplicate artwork " + enumArt, cache.put(art, enumArt), is(nullValue())); - } - } -} diff --git a/src/test/java/org/bukkit/BiomeTest.java b/src/test/java/org/bukkit/BiomeTest.java deleted file mode 100644 index 913c4cf3f..000000000 --- a/src/test/java/org/bukkit/BiomeTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bukkit; - -import net.minecraft.server.BiomeBase; -import net.minecraft.server.IRegistry; -import org.bukkit.block.Biome; -import org.bukkit.craftbukkit.block.CraftBlock; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Assert; -import org.junit.Test; - -public class BiomeTest extends AbstractTestingBase { - - @Test - public void testBukkitToMinecraft() { - for (Biome biome : Biome.values()) { - Assert.assertNotNull("No NMS mapping for " + biome, CraftBlock.biomeToBiomeBase(biome)); - } - } - - @Test - public void testMinecraftToBukkit() { - for (Object biome : IRegistry.BIOME) { - Assert.assertNotNull("No Bukkit mapping for " + biome, CraftBlock.biomeBaseToBiome((BiomeBase) biome)); - } - } -} diff --git a/src/test/java/org/bukkit/BlockDataConversionTest.java b/src/test/java/org/bukkit/BlockDataConversionTest.java deleted file mode 100644 index 46cc26b31..000000000 --- a/src/test/java/org/bukkit/BlockDataConversionTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.bukkit; - -import java.util.ArrayList; -import java.util.List; -import net.minecraft.server.Block; -import net.minecraft.server.IBlockData; -import net.minecraft.server.IRegistry; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -/** - * This test class ensures that all Blocks (as registered in IRegistry.BLOCK) - * can be converted into their CraftBlockData equivalent. - */ -@RunWith(Parameterized.class) -public class BlockDataConversionTest extends AbstractTestingBase { - - @Parameterized.Parameters(name = "{index}: {0}") - public static List args() { - List list = new ArrayList<>(); - for (Block block : (Iterable) IRegistry.BLOCK) { - list.add(new Object[]{block.getBlockData()}); - } - return list; - } - - @Parameterized.Parameter(0) public IBlockData data; - - @Test - public void testNotNull() { - Assert.assertNotNull(data); - Assert.assertNotNull(CraftBlockData.fromData(data)); - } -} diff --git a/src/test/java/org/bukkit/BlockDataTest.java b/src/test/java/org/bukkit/BlockDataTest.java deleted file mode 100644 index 11b600696..000000000 --- a/src/test/java/org/bukkit/BlockDataTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package org.bukkit; - -import net.minecraft.server.BlockCake; -import net.minecraft.server.BlockChest; -import net.minecraft.server.Blocks; -import net.minecraft.server.EnumDirection; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.Cake; -import org.bukkit.block.data.type.Chest; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.support.AbstractTestingBase; -import static org.hamcrest.Matchers.*; -import org.junit.Assert; -import org.junit.Test; - -public class BlockDataTest extends AbstractTestingBase { - - @Test - public void testParsing() { - BlockData cakeTest = CraftBlockData.fromData(Blocks.CAKE.getBlockData().set(BlockCake.BITES, 3)); - - BlockData materialString = CraftBlockData.newData(Material.CAKE, "[bites=3]"); - Assert.assertThat(materialString, is(cakeTest)); - - BlockData combined = CraftBlockData.newData(null, "cake[bites=3]"); - Assert.assertThat(combined, is(cakeTest)); - - BlockData combinedMinecraft = CraftBlockData.newData(null, "minecraft:cake[bites=3]"); - Assert.assertThat(combinedMinecraft, is(cakeTest)); - - BlockData inverted = CraftBlockData.newData(null, cakeTest.getAsString()); - Assert.assertThat(inverted, is(cakeTest)); - } - - @Test(expected = IllegalArgumentException.class) - public void testBadMaterial() { - CraftBlockData.newData(null, "invalid"); - } - - @Test(expected = IllegalArgumentException.class) - public void testBadSyntax() { - CraftBlockData.newData(null, "minecraft:cake[bites=3"); - } - - @Test(expected = IllegalArgumentException.class) - public void testDoubleMaterial() { - CraftBlockData.newData(Material.CAKE, "minecraft:cake[bites=3]"); - } - - @Test(expected = IllegalArgumentException.class) - public void testMistake() { - BlockData cakeTest = CraftBlockData.fromData(Blocks.CAKE.getBlockData().set(BlockCake.BITES, 3)); - - CraftBlockData.newData(Material.CAKE, cakeTest.toString()); - } - - @Test(expected = IllegalArgumentException.class) - public void testItem() { - CraftBlockData.newData(Material.DIAMOND_AXE, null); - } - - @Test(expected = IllegalArgumentException.class) - public void testItemParse() { - CraftBlockData.newData(null, "minecraft:diamond_axe"); - } - - @Test - public void testClone() { - Cake cakeTest = (Cake) CraftBlockData.fromData(Blocks.CAKE.getBlockData().set(BlockCake.BITES, 3)); - Cake clone = (Cake) cakeTest.clone(); - - Assert.assertFalse("Clone did not return new object", cakeTest == clone); - Assert.assertThat("Clone is not equal", clone, is(cakeTest)); - - clone.setBites(1); - Assert.assertThat("Clone is not actually clone", clone, is(not(cakeTest))); - } - - @Test - public void testMerge() { - Chest trueTarget = (Chest) CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=true]"); - Chest falseTarget = (Chest) CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=false]"); - Chest waterlogged = (Chest) CraftBlockData.newData(null, "minecraft:chest[waterlogged=true]"); - - BlockData candidate; - - Assert.assertFalse("Target and match are not yet equal", trueTarget.equals(waterlogged)); - candidate = trueTarget.merge(waterlogged); - Assert.assertTrue("Target and candidate are now equal", trueTarget.equals(candidate)); - - Assert.assertFalse("Target and match are not yet equal", falseTarget.equals(waterlogged)); - candidate = falseTarget.merge(waterlogged); - Assert.assertFalse("Target and candidate are still not equal", falseTarget.equals(candidate)); - } - - @Test - public void testMergeAny() { - Chest trueTarget = (Chest) CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=true]"); - Chest falseTarget = (Chest) CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=false]"); - Chest any = (Chest) CraftBlockData.newData(null, "minecraft:chest"); - - BlockData candidate; - - Assert.assertFalse("Target and match are not yet equal", trueTarget.equals(any)); - candidate = trueTarget.merge(any); - Assert.assertTrue("Target and candidate are now equal", trueTarget.equals(candidate)); - - Assert.assertFalse("Target and match are not yet equal", falseTarget.equals(any)); - candidate = falseTarget.merge(any); - Assert.assertTrue("Target and candidate are now equal", falseTarget.equals(candidate)); - } - - @Test(expected = IllegalArgumentException.class) - public void testCannotMerge1() { - Chest one = (Chest) CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=true]"); - Chest two = (Chest) CraftBlockData.fromData(Blocks.CHEST.getBlockData()); - - one.merge(two); - } - - @Test(expected = IllegalArgumentException.class) - public void testCannotMerge2() { - Chest one = (Chest) CraftBlockData.newData(null, "minecraft:chest[waterlogged=true]"); - Chest two = (Chest) CraftBlockData.newData(null, "minecraft:chest[waterlogged=true]"); - - one.merge(two); - - two.setFacing(BlockFace.NORTH); - one.merge(two); - } - - @Test(expected = IllegalArgumentException.class) - public void testCannotMerge3() { - Chest one = (Chest) CraftBlockData.newData(null, "minecraft:chest[waterlogged=true]"); - Chest two = (Chest) CraftBlockData.newData(null, "minecraft:trapped_chest[waterlogged=true]"); - - one.merge(two); - } - - @Test - public void testMatch() { - Assert.assertTrue(CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=true]").matches(CraftBlockData.newData(null, "minecraft:chest[waterlogged=true]"))); - Assert.assertFalse(CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=false]").matches(CraftBlockData.newData(null, "minecraft:chest[waterlogged=true]"))); - Assert.assertTrue(CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=true]").matches(CraftBlockData.newData(null, "minecraft:chest"))); - Assert.assertFalse(CraftBlockData.newData(null, "minecraft:trapped_chest[facing=east,waterlogged=false]").matches(CraftBlockData.newData(null, "minecraft:chest[waterlogged=true]"))); - Assert.assertTrue(CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=true]").matches(CraftBlockData.newData(null, "minecraft:chest[waterlogged=true,facing=east]"))); - - Chest one = (Chest) CraftBlockData.fromData(Blocks.CHEST.getBlockData().set(BlockChest.FACING, EnumDirection.EAST)); - Chest two = (Chest) CraftBlockData.newData(null, "minecraft:chest[waterlogged=false]"); - - Assert.assertTrue(one.matches(two)); - Assert.assertFalse(two.matches(one)); - } - - @Test - public void testGetAsString() { - String dataString = "minecraft:chest[facing=east,waterlogged=true]"; - BlockData data = CraftBlockData.newData(null, dataString); - - Assert.assertThat(data.getAsString(true), is(dataString)); - Assert.assertThat(data.getAsString(false), is("minecraft:chest[facing=east,type=single,waterlogged=true]")); - } - - @Test - public void testGetAsString2() { - Chest data = (Chest) CraftBlockData.fromData(Blocks.CHEST.getBlockData().set(BlockChest.FACING, EnumDirection.EAST)); - - Assert.assertThat(data.getAsString(true), is("minecraft:chest[facing=east,type=single,waterlogged=false]")); - Assert.assertThat(data.getAsString(false), is("minecraft:chest[facing=east,type=single,waterlogged=false]")); - } -} diff --git a/src/test/java/org/bukkit/ChatTest.java b/src/test/java/org/bukkit/ChatTest.java deleted file mode 100644 index 97467c26f..000000000 --- a/src/test/java/org/bukkit/ChatTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.bukkit; - -import net.minecraft.server.EnumChatFormat; -import net.minecraft.server.IChatBaseComponent; -import org.bukkit.craftbukkit.util.CraftChatMessage; -import org.junit.Assert; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class ChatTest { - - @Test - public void testColors() { - for (ChatColor color : ChatColor.values()) { - Assert.assertNotNull(CraftChatMessage.getColor(color)); - Assert.assertEquals(color, CraftChatMessage.getColor(CraftChatMessage.getColor(color))); - } - - for (EnumChatFormat format : EnumChatFormat.values()) { - Assert.assertNotNull(CraftChatMessage.getColor(format)); - Assert.assertEquals(format, CraftChatMessage.getColor(CraftChatMessage.getColor(format))); - } - } - - @Test - public void testURLJsonConversion() { - IChatBaseComponent[] components; - components = CraftChatMessage.fromString("https://spigotmc.org/test Test Message"); - assertEquals("{\"extra\":[{\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://spigotmc.org/test\"},\"text\":\"https://spigotmc.org/test\"},{\"text\":\" Test Message\"}],\"text\":\"\"}", - CraftChatMessage.toJSON(components[0])); - - components = CraftChatMessage.fromString("123 " + ChatColor.GOLD + "https://spigotmc.org " + ChatColor.BOLD + "test"); - assertEquals("{\"extra\":[{\"text\":\"123 \"},{\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://spigotmc.org\"},\"text\":\"https://spigotmc.org\"},{\"color\":\"gold\",\"text\":\" \"},{\"bold\":true,\"color\":\"gold\",\"text\":\"test\"}],\"text\":\"\"}", - CraftChatMessage.toJSON(components[0])); - - components = CraftChatMessage.fromString("multiCase http://SpigotMC.ORg/SpOngeBobMeEMeGoESHeRE"); - assertEquals("{\"extra\":[{\"text\":\"multiCase \"},{\"clickEvent\":{\"action\":\"open_url\",\"value\":\"http://SpigotMC.ORg/SpOngeBobMeEMeGoESHeRE\"},\"text\":\"http://SpigotMC.ORg/SpOngeBobMeEMeGoESHeRE\"}],\"text\":\"\"}", - CraftChatMessage.toJSON(components[0])); - } -} diff --git a/src/test/java/org/bukkit/DyeColorsTest.java b/src/test/java/org/bukkit/DyeColorsTest.java deleted file mode 100644 index 45a5caed2..000000000 --- a/src/test/java/org/bukkit/DyeColorsTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bukkit; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.server.EnumColor; - -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class DyeColorsTest extends AbstractTestingBase { - - @Parameters(name= "{index}: {0}") - public static List data() { - List list = new ArrayList(); - for (DyeColor dye : DyeColor.values()) { - list.add(new Object[] {dye}); - } - return list; - } - - @Parameter public DyeColor dye; - - @Test - public void checkColor() { - Color color = dye.getColor(); - float[] nmsColorArray = EnumColor.fromColorIndex(dye.getWoolData()).d(); - Color nmsColor = Color.fromRGB((int) (nmsColorArray[0] * 255), (int) (nmsColorArray[1] * 255), (int) (nmsColorArray[2] * 255)); - assertThat(color, is(nmsColor)); - } - - @Test - public void checkFireworkColor() { - Color color = dye.getFireworkColor(); - int nmsColor = EnumColor.fromColorIndex(dye.getWoolData()).f(); - assertThat(color, is(Color.fromRGB(nmsColor))); - } -} diff --git a/src/test/java/org/bukkit/EnchantmentTest.java b/src/test/java/org/bukkit/EnchantmentTest.java deleted file mode 100644 index e69283b1f..000000000 --- a/src/test/java/org/bukkit/EnchantmentTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bukkit; - -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Assert; -import org.junit.Test; - -public class EnchantmentTest extends AbstractTestingBase { - - @Test - public void verifyMapping() { - for (MinecraftKey key : IRegistry.ENCHANTMENT.keySet()) { - net.minecraft.server.Enchantment nms = IRegistry.ENCHANTMENT.get(key); - - Enchantment bukkitById = Enchantment.getByKey(CraftNamespacedKey.fromMinecraft(key)); - - Assert.assertFalse("Unknown enchant name for " + key, bukkitById.getName().startsWith("UNKNOWN")); - - Assert.assertNotNull("Unknown target for " + key, bukkitById.getItemTarget()); - } - } -} diff --git a/src/test/java/org/bukkit/GameRuleTest.java b/src/test/java/org/bukkit/GameRuleTest.java deleted file mode 100644 index e54f31e65..000000000 --- a/src/test/java/org/bukkit/GameRuleTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bukkit; - -import java.util.Map; -import java.util.TreeMap; -import net.minecraft.server.GameRules; -import net.minecraft.server.GameRules.GameRuleDefinition; - -import org.junit.Assert; -import org.junit.Test; - -import com.koloboke.collect.map.hash.HashObjObjMap; - -public class GameRuleTest { - - @Test - public void testBukkitRules() { - GameRule[] rules = GameRule.values(); - - for (GameRule rule : rules) { - GameRule registeredRule = GameRule.getByName(rule.getName()); - Assert.assertNotNull("Null GameRule", registeredRule); - Assert.assertEquals("Invalid GameRule equality", rule, registeredRule); - } - } - - @Test - public void testMinecraftRules() { - Map minecraftRules = GameRules.getGameRules(); // Paper - Optimize GameRules - - for (Map.Entry entry : minecraftRules.entrySet()) { - GameRule bukkitRule = GameRule.getByName(entry.getKey()); - - Assert.assertNotNull(bukkitRule); - Assert.assertEquals("Invalid GameRule Name", bukkitRule.getName(), entry.getKey()); - } - } - - @Test(expected = NullPointerException.class) - public void nullGameRuleName() { - GameRule.getByName(null); - } - - @Test - public void emptyGameRuleName() { - Assert.assertNull(GameRule.getByName("")); - } - - @Test - public void incorrectGameRuleName() { - Assert.assertNull(GameRule.getByName("doAnnounceAdvancements")); - Assert.assertNull(GameRule.getByName("sendCommandBlockFeedback")); - } - - @Test - public void invalidCasing() { - Assert.assertNull(GameRule.getByName("CommandBlockOutput")); - Assert.assertNull(GameRule.getByName("spAwnRadius")); - Assert.assertNull(GameRule.getByName("rand0mTickSpeEd")); - } -} diff --git a/src/test/java/org/bukkit/LegacyTest.java b/src/test/java/org/bukkit/LegacyTest.java deleted file mode 100644 index b441d40d9..000000000 --- a/src/test/java/org/bukkit/LegacyTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.bukkit; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; -import org.bukkit.craftbukkit.util.CraftLegacy; -import org.bukkit.material.MaterialData; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Assert; -import org.junit.Test; - -public class LegacyTest extends AbstractTestingBase { - - private final Set INVALIDATED_MATERIALS = new HashSet<>(Arrays.asList(Material.ACACIA_BUTTON, Material.ACACIA_PRESSURE_PLATE, Material.ACACIA_TRAPDOOR, Material.AIR, Material.ATTACHED_MELON_STEM, Material.ATTACHED_PUMPKIN_STEM, - Material.BIRCH_BUTTON, Material.BIRCH_PRESSURE_PLATE, Material.BIRCH_TRAPDOOR, Material.BLACK_WALL_BANNER, Material.BLUE_WALL_BANNER, Material.BROWN_WALL_BANNER, Material.BUBBLE_COLUMN, Material.CAVE_AIR, Material.CREEPER_WALL_HEAD, - Material.CYAN_WALL_BANNER, Material.DARK_OAK_BUTTON, Material.DARK_OAK_PRESSURE_PLATE, Material.DARK_OAK_TRAPDOOR, Material.DARK_PRISMARINE_SLAB, Material.DARK_PRISMARINE_STAIRS, Material.DEBUG_STICK, Material.DONKEY_SPAWN_EGG, - Material.DRAGON_WALL_HEAD, Material.DRIED_KELP, Material.DRIED_KELP_BLOCK, Material.ELDER_GUARDIAN_SPAWN_EGG, Material.EVOKER_SPAWN_EGG, Material.GRAY_WALL_BANNER, Material.GREEN_WALL_BANNER, Material.HUSK_SPAWN_EGG, - Material.JUNGLE_BUTTON, Material.JUNGLE_PRESSURE_PLATE, Material.JUNGLE_TRAPDOOR, Material.KELP, Material.KELP_PLANT, Material.LIGHT_BLUE_WALL_BANNER, Material.LIGHT_GRAY_WALL_BANNER, Material.LIME_WALL_BANNER, Material.LLAMA_SPAWN_EGG, - Material.MAGENTA_WALL_BANNER, Material.MULE_SPAWN_EGG, Material.ORANGE_WALL_BANNER, Material.PARROT_SPAWN_EGG, Material.PHANTOM_SPAWN_EGG, Material.PINK_WALL_BANNER, Material.PLAYER_WALL_HEAD, Material.POLAR_BEAR_SPAWN_EGG, - Material.POTTED_ACACIA_SAPLING, Material.POTTED_ALLIUM, Material.POTTED_AZURE_BLUET, Material.POTTED_BIRCH_SAPLING, Material.POTTED_BLUE_ORCHID, Material.POTTED_BROWN_MUSHROOM, Material.POTTED_DANDELION, Material.POTTED_DARK_OAK_SAPLING, - Material.POTTED_DEAD_BUSH, Material.POTTED_FERN, Material.POTTED_JUNGLE_SAPLING, Material.POTTED_OAK_SAPLING, Material.POTTED_ORANGE_TULIP, Material.POTTED_OXEYE_DAISY, Material.POTTED_PINK_TULIP, Material.POTTED_POPPY, - Material.POTTED_RED_MUSHROOM, Material.POTTED_RED_TULIP, Material.POTTED_SPRUCE_SAPLING, Material.POTTED_WHITE_TULIP, Material.PRISMARINE_BRICK_SLAB, Material.PRISMARINE_BRICK_STAIRS, Material.PRISMARINE_SLAB, Material.PRISMARINE_STAIRS, - Material.PUMPKIN, Material.PURPLE_WALL_BANNER, Material.RED_WALL_BANNER, Material.SEAGRASS, Material.SKELETON_HORSE_SPAWN_EGG, Material.SKELETON_WALL_SKULL, Material.SPRUCE_BUTTON, Material.SPRUCE_PRESSURE_PLATE, Material.SPRUCE_TRAPDOOR, - Material.STRAY_SPAWN_EGG, Material.STRIPPED_ACACIA_LOG, Material.STRIPPED_BIRCH_LOG, Material.STRIPPED_DARK_OAK_LOG, Material.STRIPPED_JUNGLE_LOG, Material.STRIPPED_OAK_LOG, Material.STRIPPED_SPRUCE_LOG, Material.TALL_SEAGRASS, - Material.TRIDENT, Material.TURTLE_EGG, Material.TURTLE_HELMET, Material.SCUTE, Material.TURTLE_SPAWN_EGG, Material.VEX_SPAWN_EGG, Material.VINDICATOR_SPAWN_EGG, Material.VOID_AIR, Material.WHITE_BED, - Material.WITHER_SKELETON_SPAWN_EGG, Material.WITHER_SKELETON_WALL_SKULL, Material.YELLOW_WALL_BANNER, Material.ZOMBIE_HORSE_SPAWN_EGG, Material.ZOMBIE_VILLAGER_SPAWN_EGG, Material.ZOMBIE_WALL_HEAD, - Material.COD_BUCKET, Material.COD_SPAWN_EGG, Material.PUFFERFISH_BUCKET, Material.PUFFERFISH_SPAWN_EGG, Material.SALMON_BUCKET, Material.SALMON_SPAWN_EGG, - Material.TROPICAL_FISH_BUCKET, Material.DROWNED_SPAWN_EGG, Material.SHULKER_BOX, Material.TROPICAL_FISH_SPAWN_EGG, - Material.BLUE_ICE, Material.BRAIN_CORAL, Material.BRAIN_CORAL_BLOCK, Material.BRAIN_CORAL_FAN, Material.BUBBLE_CORAL, Material.BUBBLE_CORAL_BLOCK, Material.BUBBLE_CORAL_FAN, Material.CONDUIT, Material.DEAD_BRAIN_CORAL_BLOCK, - Material.DEAD_BUBBLE_CORAL_BLOCK, Material.DEAD_FIRE_CORAL_BLOCK, Material.DEAD_HORN_CORAL_BLOCK, Material.DEAD_TUBE_CORAL_BLOCK, Material.DOLPHIN_SPAWN_EGG, Material.FIRE_CORAL, Material.FIRE_CORAL_BLOCK, Material.FIRE_CORAL_FAN, - Material.HEART_OF_THE_SEA, Material.HORN_CORAL, Material.HORN_CORAL_BLOCK, Material.HORN_CORAL_FAN, Material.NAUTILUS_SHELL, Material.PHANTOM_MEMBRANE, Material.SEA_PICKLE, Material.TUBE_CORAL, Material.TUBE_CORAL_BLOCK, - Material.TUBE_CORAL_FAN, Material.STRIPPED_ACACIA_WOOD, Material.STRIPPED_BIRCH_WOOD, Material.STRIPPED_DARK_OAK_WOOD, Material.STRIPPED_JUNGLE_WOOD, Material.STRIPPED_OAK_WOOD, Material.STRIPPED_SPRUCE_WOOD, - Material.ACACIA_WOOD, Material.BIRCH_WOOD, Material.DARK_OAK_WOOD, Material.JUNGLE_WOOD, Material.OAK_WOOD, Material.SPRUCE_WOOD, - Material.TUBE_CORAL_WALL_FAN, Material.BRAIN_CORAL_WALL_FAN, Material.BUBBLE_CORAL_WALL_FAN, Material.FIRE_CORAL_WALL_FAN, Material.HORN_CORAL_WALL_FAN, Material.DEAD_TUBE_CORAL_WALL_FAN, Material.DEAD_BRAIN_CORAL_WALL_FAN, - Material.DEAD_BUBBLE_CORAL_WALL_FAN, Material.DEAD_FIRE_CORAL_WALL_FAN, Material.DEAD_HORN_CORAL_WALL_FAN, Material.DEAD_TUBE_CORAL_FAN, Material.DEAD_BRAIN_CORAL_FAN, Material.DEAD_BUBBLE_CORAL_FAN, Material.DEAD_FIRE_CORAL_FAN, - Material.DEAD_HORN_CORAL_FAN, Material.DEAD_BRAIN_CORAL, Material.DEAD_BUBBLE_CORAL, Material.DEAD_FIRE_CORAL, Material.DEAD_HORN_CORAL, Material.DEAD_TUBE_CORAL, - // - Material.LEGACY_AIR, Material.LEGACY_DEAD_BUSH, Material.LEGACY_BURNING_FURNACE, Material.LEGACY_WALL_SIGN, Material.LEGACY_REDSTONE_TORCH_OFF, Material.LEGACY_SKULL, Material.LEGACY_REDSTONE_COMPARATOR_ON, Material.LEGACY_WALL_BANNER, Material.LEGACY_MONSTER_EGG)); - - private final Set INVERSION_FAILS = new HashSet<>(Arrays.asList(Material.LEGACY_DOUBLE_STEP, Material.LEGACY_GLOWING_REDSTONE_ORE, Material.LEGACY_DIODE_BLOCK_ON, Material.LEGACY_REDSTONE_LAMP_ON, Material.LEGACY_WOOD_DOUBLE_STEP, - Material.LEGACY_DAYLIGHT_DETECTOR_INVERTED, Material.LEGACY_DOUBLE_STONE_SLAB2, Material.LEGACY_PURPUR_DOUBLE_SLAB, Material.LEGACY_WHEAT, Material.LEGACY_SIGN, Material.LEGACY_WOOD_DOOR, Material.LEGACY_IRON_DOOR, Material.LEGACY_SUGAR_CANE, - Material.LEGACY_CAKE, Material.LEGACY_BED, Material.LEGACY_DIODE, Material.LEGACY_NETHER_STALK, Material.LEGACY_BREWING_STAND_ITEM, Material.LEGACY_CAULDRON_ITEM, Material.LEGACY_REDSTONE_COMPARATOR, Material.LEGACY_SPRUCE_DOOR_ITEM, - Material.LEGACY_BIRCH_DOOR_ITEM, Material.LEGACY_JUNGLE_DOOR_ITEM, Material.LEGACY_ACACIA_DOOR_ITEM, Material.LEGACY_DARK_OAK_DOOR_ITEM, Material.LEGACY_STATIONARY_LAVA, Material.LEGACY_STATIONARY_WATER)); - - @Test - public void toLegacyMaterial() { - for (Material material : Material.values()) { - if (!INVALIDATED_MATERIALS.contains(material) && !material.isLegacy()) { - MaterialData converted = CraftLegacy.toLegacyData(material); - - Assert.assertNotEquals("Could not toLegacy " + material, Material.LEGACY_AIR, converted.getItemType()); - - if (!INVALIDATED_MATERIALS.contains(converted.getItemType())) { - Assert.assertNotEquals("Could not fromLegacy(toLegacy) " + converted + "(" + material + ")", Material.AIR, CraftLegacy.fromLegacy(converted)); - } - if (!INVERSION_FAILS.contains(material)) { - Assert.assertEquals("Could not fromLegacy(toLegacy) " + converted + "(" + material + ")", material, CraftLegacy.fromLegacy(converted)); - } - } - } - - Assert.assertEquals("Could not toLegacy Air", Material.LEGACY_AIR, CraftLegacy.toLegacy(Material.AIR)); - } - - @Test - public void fromLegacyMaterial() { - for (Material material : Material.values()) { - if (!INVALIDATED_MATERIALS.contains(material) && material.isLegacy()) { - Material converted = CraftLegacy.fromLegacy(material); - Assert.assertNotEquals("Could not fromLegacy " + material, Material.AIR, converted); - - Assert.assertNotEquals("Could not toLegacy(fromLegacy) " + converted + "(" + material + ")", Material.AIR, CraftLegacy.toLegacy(converted)); - if (!INVERSION_FAILS.contains(material)) { - Assert.assertEquals("Could not toLegacy(fromLegacy) " + converted + "(" + material + ")", material, CraftLegacy.toLegacy(converted)); - } - } - } - - Assert.assertEquals("Could not fromLegacy Air", Material.AIR, CraftLegacy.fromLegacy(Material.LEGACY_AIR)); - } - - @Test - public void testRestricted() { - for (Material material : CraftLegacy.values()) { - Assert.assertTrue("Must iterate only legacy materials", material.isLegacy()); - } - - for (Material material : CraftLegacy.modern_values()) { - Assert.assertFalse("Must iterate only modern materials", material.isLegacy()); - } - } -} diff --git a/src/test/java/org/bukkit/LootTablesTest.java b/src/test/java/org/bukkit/LootTablesTest.java deleted file mode 100644 index 8d2cbb44c..000000000 --- a/src/test/java/org/bukkit/LootTablesTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit; - -import org.bukkit.loot.LootTable; -import org.bukkit.loot.LootTables; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Assert; -import org.junit.Test; - -public class LootTablesTest extends AbstractTestingBase { - - @Test - public void testLootTablesEnumExists() { - LootTables[] tables = LootTables.values(); - - for (LootTables table : tables) { - LootTable lootTable = Bukkit.getLootTable(table.getKey()); - - Assert.assertNotNull("Unknown LootTable " + table.getKey(), lootTable); - Assert.assertEquals(lootTable.getKey(), table.getKey()); - } - } -} diff --git a/src/test/java/org/bukkit/MaterialTest.java b/src/test/java/org/bukkit/MaterialTest.java deleted file mode 100644 index 8c9724478..000000000 --- a/src/test/java/org/bukkit/MaterialTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.util.Collections; -import java.util.Map; - -import net.minecraft.server.IRegistry; -import net.minecraft.server.Item; -import net.minecraft.server.MinecraftKey; - -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; - -import com.google.common.collect.Maps; -import java.util.Iterator; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; - -public class MaterialTest extends AbstractTestingBase { - - @Test - public void verifyMapping() { - Map materials = Maps.newHashMap(); - for (Material material : Material.values()) { - if (INVALIDATED_MATERIALS.contains(material)) { - continue; - } - - materials.put(CraftMagicNumbers.key(material), material); - } - - Iterator items = IRegistry.ITEM.iterator(); - - while (items.hasNext()) { - Item item = items.next(); - if (item == null) continue; - - MinecraftKey id = IRegistry.ITEM.getKey(item); - String name = item.getName(); - - Material material = materials.remove(id); - - assertThat("Missing " + name + "(" + id + ")", material, is(not(nullValue()))); - assertNotNull("No item mapping for " + name, CraftMagicNumbers.getMaterial(item)); - } - - assertThat(materials, is(Collections.EMPTY_MAP)); - } -} diff --git a/src/test/java/org/bukkit/NibbleArrayTest.java b/src/test/java/org/bukkit/NibbleArrayTest.java deleted file mode 100644 index 0131ff04a..000000000 --- a/src/test/java/org/bukkit/NibbleArrayTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bukkit; - -import java.util.Random; -import net.minecraft.server.NibbleArray; -import org.junit.Assert; -import org.junit.Test; - -public class NibbleArrayTest { - - private static final int NIBBLE_SIZE = 4096; - - @Test - public void testNibble() { - Random random = new Random(); - byte[] classic = new byte[NIBBLE_SIZE]; - NibbleArray nibble = new NibbleArray(); - - for (int i = 0; i < classic.length; i++) { - byte number = (byte) (random.nextInt() & 0xF); - - classic[i] = number; - nibble.a(i, number); - } - - for (int i = 0; i < classic.length; i++) { - Assert.assertEquals("Nibble array mismatch", classic[i], nibble.a(i)); - } - } -} diff --git a/src/test/java/org/bukkit/ParticleTest.java b/src/test/java/org/bukkit/ParticleTest.java deleted file mode 100644 index 26232c261..000000000 --- a/src/test/java/org/bukkit/ParticleTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit; - -import net.minecraft.server.IRegistry; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.CraftParticle; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Assert; -import org.junit.Test; - -public class ParticleTest extends AbstractTestingBase { - - @Test - public void verifyMapping() { - for (Particle bukkit : Particle.values()) { - Object data = null; - if (bukkit.getDataType().equals(ItemStack.class)) { - data = new ItemStack(Material.STONE); - } else if (bukkit.getDataType() == MaterialData.class) { - data = new MaterialData(Material.LEGACY_STONE); - } else if (bukkit.getDataType() == Particle.DustOptions.class) { - data = new Particle.DustOptions(Color.BLACK, 0); - } else if (bukkit.getDataType() == BlockData.class) { - data = CraftBlockData.newData(Material.STONE, ""); - } - - Assert.assertNotNull("Missing Bukkit->NMS particle mapping for " + bukkit, CraftParticle.toNMS(bukkit, data)); - } - for (net.minecraft.server.Particle nms : (Iterable>) IRegistry.PARTICLE_TYPE) { // Eclipse fail // Akarin - fixes eclipse - Assert.assertNotNull("Missing NMS->Bukkit particle mapping for " + nms, CraftParticle.toBukkit(nms)); - } - } -} diff --git a/src/test/java/org/bukkit/PerMaterialTest.java b/src/test/java/org/bukkit/PerMaterialTest.java deleted file mode 100644 index 7967c4c39..000000000 --- a/src/test/java/org/bukkit/PerMaterialTest.java +++ /dev/null @@ -1,239 +0,0 @@ -package org.bukkit; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.util.List; - -import net.minecraft.server.BlockFalling; -import net.minecraft.server.BlockFire; -import net.minecraft.server.Item; -import net.minecraft.server.ItemFood; -import net.minecraft.server.ItemRecord; -import net.minecraft.server.TileEntityFurnace; - -import org.bukkit.craftbukkit.inventory.CraftItemStack; -import org.bukkit.inventory.ItemStack; -import org.bukkit.support.AbstractTestingBase; -import org.bukkit.support.Util; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.collect.Lists; -import java.util.Map; -import net.minecraft.server.Block; -import net.minecraft.server.BlockPosition; -import net.minecraft.server.Blocks; -import net.minecraft.server.EntityHuman; -import net.minecraft.server.EnumDirection; -import net.minecraft.server.EnumHand; -import net.minecraft.server.IBlockData; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.enchantments.EnchantmentTarget; - -@RunWith(Parameterized.class) -public class PerMaterialTest extends AbstractTestingBase { - private static Map fireValues; - - @BeforeClass - public static void getFireValues() { - fireValues = Util.getInternalState(BlockFire.class, Blocks.FIRE, "flameChances"); - } - - @Parameters(name= "{index}: {0}") - public static List data() { - List list = Lists.newArrayList(); - for (Material material : Material.values()) { - if (!material.isLegacy()) { - list.add(new Object[] {material}); - } - } - return list; - } - - @Parameter public Material material; - - @Test - public void isBlock() { - if (material != Material.AIR && material != Material.CAVE_AIR && material != Material.VOID_AIR) { - assertThat(material.isBlock(), is(not(CraftMagicNumbers.getBlock(material) == null))); - } - } - - @Test - public void isSolid() { - if (material == Material.AIR) { - assertFalse(material.isSolid()); - } else if (material.isBlock()) { - assertThat(material.isSolid(), is(CraftMagicNumbers.getBlock(material).getBlockData().getMaterial().isSolid())); - } else { - assertFalse(material.isSolid()); - } - } - - @Test - public void isEdible() { - assertThat(material.isEdible(), is(CraftMagicNumbers.getItem(material) instanceof ItemFood)); - } - - @Test - public void isRecord() { - assertThat(material.isRecord(), is(CraftMagicNumbers.getItem(material) instanceof ItemRecord)); - } - - @Test - public void maxDurability() { - if (INVALIDATED_MATERIALS.contains(material)) return; - - if (material == Material.AIR) { - assertThat((int) material.getMaxDurability(), is(0)); - } else if (material.isBlock()){ - Item item = CraftMagicNumbers.getItem(material); - assertThat((int) material.getMaxDurability(), is(item.getMaxDurability())); - } - } - - @Test - public void maxStackSize() { - if (INVALIDATED_MATERIALS.contains(material)) return; - - final ItemStack bukkit = new ItemStack(material); - final CraftItemStack craft = CraftItemStack.asCraftCopy(bukkit); - if (material == Material.AIR) { - final int MAX_AIR_STACK = 0 /* Why can't I hold all of these AIR? */; - assertThat(material.getMaxStackSize(), is(MAX_AIR_STACK)); - assertThat(bukkit.getMaxStackSize(), is(MAX_AIR_STACK)); - assertThat(craft.getMaxStackSize(), is(MAX_AIR_STACK)); - } else { - assertThat(material.getMaxStackSize(), is(CraftMagicNumbers.getItem(material).getMaxStackSize())); - assertThat(bukkit.getMaxStackSize(), is(material.getMaxStackSize())); - assertThat(craft.getMaxStackSize(), is(material.getMaxStackSize())); - } - } - - @Test - public void isTransparent() { - if (material == Material.AIR) { - assertTrue(material.isTransparent()); - } else if (material.isBlock()) { - // assertThat(material.isTransparent(), is(not(CraftMagicNumbers.getBlock(material).getBlockData().getMaterial().blocksLight()))); // PAIL: not unit testable anymore (17w50a) - } else { - assertFalse(material.isTransparent()); - } - } - - @Test - public void isFlammable() { - if (material != Material.AIR && material.isBlock()) { - assertThat(material.isFlammable(), is(CraftMagicNumbers.getBlock(material).getBlockData().getMaterial().isBurnable())); - } else { - assertFalse(material.isFlammable()); - } - } - - @Test - public void isBurnable() { - if (material.isBlock()) { - Block block = CraftMagicNumbers.getBlock(material); - assertThat(material.isBurnable(), is(fireValues.containsKey(block) && fireValues.get(block) > 0)); - } else { - assertFalse(material.isBurnable()); - } - } - - @Test - public void isFuel() { - assertThat(material.isFuel(), is(TileEntityFurnace.isFuel(new net.minecraft.server.ItemStack(CraftMagicNumbers.getItem(material))))); - } - - @Test - public void isOccluding() { - if (material.isBlock()) { - assertThat(material.isOccluding(), is(CraftMagicNumbers.getBlock(material).isOccluding(CraftMagicNumbers.getBlock(material).getBlockData()))); - } else { - assertFalse(material.isOccluding()); - } - } - - @Test - public void hasGravity() { - if (material.isBlock()) { - assertThat(material.hasGravity(), is(CraftMagicNumbers.getBlock(material) instanceof BlockFalling)); - } else { - assertFalse(material.hasGravity()); - } - } - - @Test - public void usesDurability() { - if (!material.isBlock()) { - assertThat(EnchantmentTarget.BREAKABLE.includes(material), is(CraftMagicNumbers.getItem(material).usesDurability())); - } else { - assertFalse(EnchantmentTarget.BREAKABLE.includes(material)); - } - } - - @Test - public void testDurability() { - if (!material.isBlock()) { - assertThat(material.getMaxDurability(), is((short) CraftMagicNumbers.getItem(material).getMaxDurability())); - } else { - assertThat(material.getMaxDurability(), is((short) 0)); - } - } - - @Test - public void testBlock() { - if (material == Material.AIR) { - assertTrue(material.isBlock()); - } else { - assertThat(material.isBlock(), is(equalTo(CraftMagicNumbers.getBlock(material) != null))); - } - } - - @Test - public void testItem() { - if (material == Material.AIR) { - assertTrue(material.isItem()); - } else { - assertThat(material.isItem(), is(equalTo(CraftMagicNumbers.getItem(material) != null))); - } - } - - @Test - public void testInteractable() throws ReflectiveOperationException { - if (material.isBlock()) { - assertThat(material.isInteractable(), - is(!CraftMagicNumbers.getBlock(material).getClass() - .getMethod("interact", IBlockData.class, net.minecraft.server.World.class, BlockPosition.class, EntityHuman.class, EnumHand.class, EnumDirection.class, float.class, float.class, float.class) - .getDeclaringClass().equals(Block.class))); - } else { - assertFalse(material.isInteractable()); - } - } - - @Test - public void testBlockHardness() { - if (material.isBlock()) { - assertThat(material.getHardness(), is(CraftMagicNumbers.getBlock(material).strength)); - } - } - - @Test - public void testBlastResistance() { - if (material.isBlock()) { - assertThat(material.getBlastResistance(), is(CraftMagicNumbers.getBlock(material).getDurability())); - } - } - - @Test - public void testBlockDataCreation() { - if (material.isBlock()) { - assertNotNull(material.createBlockData()); - } - } -} diff --git a/src/test/java/org/bukkit/SoundTest.java b/src/test/java/org/bukkit/SoundTest.java deleted file mode 100644 index da8c3dcbb..000000000 --- a/src/test/java/org/bukkit/SoundTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.bukkit; - -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import org.bukkit.craftbukkit.CraftSound; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; - -public class SoundTest extends AbstractTestingBase { - - @Test - public void testGetSound() { - for (Sound sound : Sound.values()) { - assertThat(sound.name(), CraftSound.getSound(sound), is(not(nullValue()))); - } - } - - @Test - public void testReverse() { - for (MinecraftKey effect : IRegistry.SOUND_EVENT.keySet()) { - assertNotNull(effect + "", Sound.valueOf(effect.getKey().replace('.', '_').toUpperCase(java.util.Locale.ENGLISH))); - } - } - - @Test - public void testCategory() { - for (SoundCategory category : SoundCategory.values()) { - assertNotNull(category + "", net.minecraft.server.SoundCategory.valueOf(category.name())); - } - } - - @Test - public void testCategoryReverse() { - for (net.minecraft.server.SoundCategory category : net.minecraft.server.SoundCategory.values()) { - assertNotNull(category + "", SoundCategory.valueOf(category.name())); - } - } -} diff --git a/src/test/java/org/bukkit/StatisticsAndAchievementsTest.java b/src/test/java/org/bukkit/StatisticsAndAchievementsTest.java deleted file mode 100644 index 4edbc126c..000000000 --- a/src/test/java/org/bukkit/StatisticsAndAchievementsTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bukkit; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import net.minecraft.server.EntityTypes; -import net.minecraft.server.IRegistry; -import net.minecraft.server.StatisticWrapper; - -import org.bukkit.entity.EntityType; -import org.bukkit.craftbukkit.CraftStatistic; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; - -import com.google.common.collect.HashMultiset; - -public class StatisticsAndAchievementsTest extends AbstractTestingBase { - - @Test - @SuppressWarnings("unchecked") - public void verifyEntityMapping() throws Throwable { - for (Statistic statistic : Statistic.values()) { - if (statistic.getType() == Statistic.Type.ENTITY) { - for (EntityType entity : EntityType.values()) { - if (entity.getName() != null) { - assertNotNull(statistic + " missing for " + entity, CraftStatistic.getEntityStatistic(statistic, entity)); - } - } - } - } - } - - @Test - @SuppressWarnings("unchecked") - public void verifyStatisticMapping() throws Throwable { - HashMultiset statistics = HashMultiset.create(); - for (StatisticWrapper wrapper : (Iterable>) IRegistry.STATS) { // Eclipse fail - for (Object child : wrapper.a()) { - net.minecraft.server.Statistic statistic = wrapper.b(child); - String message = String.format("org.bukkit.Statistic is missing: '%s'", statistic); - - Statistic subject = CraftStatistic.getBukkitStatistic(statistic); - assertThat(message, subject, is(not(nullValue()))); - - if (wrapper.a() == IRegistry.BLOCK || wrapper.a() == IRegistry.ITEM) { - assertNotNull("Material type map missing for " + child, CraftStatistic.getMaterialFromStatistic(statistic)); - } else if (wrapper.a() == IRegistry.ENTITY_TYPE) { - assertNotNull("Entity type map missing for " + EntityTypes.getName((EntityTypes) child), CraftStatistic.getEntityTypeFromStatistic((net.minecraft.server.Statistic>) statistic)); - } - - statistics.add(subject); - } - } - - for (Statistic statistic : Statistic.values()) { - String message = String.format("org.bukkit.Statistic.%s does not have a corresponding minecraft statistic", statistic.name()); - assertThat(message, statistics.remove(statistic, statistics.count(statistic)), is(greaterThan(0))); - } - } -} diff --git a/src/test/java/org/bukkit/StructureTypeTest.java b/src/test/java/org/bukkit/StructureTypeTest.java deleted file mode 100644 index ad1c7a4d7..000000000 --- a/src/test/java/org/bukkit/StructureTypeTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit; - -import java.util.Map; -import net.minecraft.server.WorldGenFactory; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * This test makes sure that Bukkit always has Minecraft structure types up to - * date. - */ -public class StructureTypeTest extends AbstractTestingBase { - - private static Map structures; - - @BeforeClass - public static void setUp() { - structures = StructureType.getStructureTypes(); - } - - @Test - public void testMinecraftToBukkit() { - for (String key : WorldGenFactory.structureStartMap.keySet()) { - Assert.assertNotNull(structures.get(key)); - } - } - - @Test - public void testBukkit() { - for (Map.Entry entry : structures.entrySet()) { - Assert.assertNotNull(StructureType.getStructureTypes().get(entry.getKey())); - Assert.assertNotNull(StructureType.getStructureTypes().get(entry.getValue().getName())); - } - } - - @Test - public void testBukkitToMinecraft() { - for (Map.Entry entry : structures.entrySet()) { - Assert.assertNotNull(WorldGenFactory.structureStartMap.get(entry.getKey())); - Assert.assertNotNull(WorldGenFactory.structureStartMap.get(entry.getValue().getName())); - } - } -} diff --git a/src/test/java/org/bukkit/WorldTypeTest.java b/src/test/java/org/bukkit/WorldTypeTest.java deleted file mode 100644 index 4d35a1064..000000000 --- a/src/test/java/org/bukkit/WorldTypeTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bukkit; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import net.minecraft.server.WorldType; -import org.junit.Test; - -public class WorldTypeTest { - @Test - public void testTypes() { - for (WorldType type : WorldType.types) { - if (type == null) continue; - if (type == WorldType.DEBUG_ALL_BLOCK_STATES) continue; // Doesn't work anyway - - assertThat(type.name() + " has no Bukkit world", org.bukkit.WorldType.getByName(type.name()), is(not(nullValue()))); - } - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/generator/ChunkDataTest.java b/src/test/java/org/bukkit/craftbukkit/generator/ChunkDataTest.java deleted file mode 100644 index c5194e380..000000000 --- a/src/test/java/org/bukkit/craftbukkit/generator/ChunkDataTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.bukkit.craftbukkit.generator; - -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; -import static org.junit.Assert.*; - -public class ChunkDataTest extends AbstractTestingBase { - - private static final BlockData RED_WOOL = Material.RED_WOOL.createBlockData(); - private static final BlockData AIR = Material.AIR.createBlockData(); - - private boolean testSetBlock(CraftChunkData data, int x, int y, int z, BlockData type, BlockData expected) { - data.setBlock(x, y, z, type); - return expected.equals(data.getBlockData(x, y, z)) && expected.getMaterial().equals(data.getType(x, y, z)); - } - - private void testSetRegion(CraftChunkData data, int minx, int miny, int minz, int maxx, int maxy, int maxz, BlockData type) { - data.setRegion(minx, miny, minz, maxx, maxy, maxz, type); - for (int y = 0; y < data.getMaxHeight(); y++) { - for (int z = 0; z < 16; z++) { - for (int x = 0; x < 16; x++) { - boolean inRegion = miny <= y && y < maxy && minx <= x && x < maxx && minz <= z && z < maxz; - if (inRegion != type.equals(data.getBlockData(x, y, z))) { - throw new IllegalStateException( - "setRegion(" + minx + ", " + miny + ", " + minz + ", " + maxx + ", " + maxy + ", " + maxz + ", " + type + ")" - + "-> block at " + x + ", " + y + ", " + z + " is " + data.getBlockData(x, y, z)); - } - } - } - } - } - - @Test - public void testMaxHeight() { - CraftChunkData data = new CraftChunkData(128); - assertTrue("Could not set block above max height", testSetBlock(data, 0, 128, 0, RED_WOOL, AIR)); - assertTrue("Could set block below max height", testSetBlock(data, 0, 127, 0, RED_WOOL, RED_WOOL)); - } - - @Test - public void testBoundsCheckingSingle() { - CraftChunkData data = new CraftChunkData(256); - assertTrue("Can set block inside chunk bounds", testSetBlock(data, 0, 0, 0, RED_WOOL, RED_WOOL)); - assertTrue("Can set block inside chunk bounds", testSetBlock(data, 15, 255, 15, RED_WOOL, RED_WOOL)); - assertTrue("Can no set block outside chunk bounds", testSetBlock(data, -1, 0, 0, RED_WOOL, AIR)); - assertTrue("Can no set block outside chunk bounds", testSetBlock(data, 0, -1, 0, RED_WOOL, AIR)); - assertTrue("Can no set block outside chunk bounds", testSetBlock(data, 0, 0, -1, RED_WOOL, AIR)); - assertTrue("Can no set block outside chunk bounds", testSetBlock(data, 16, 0, 0, RED_WOOL, AIR)); - assertTrue("Can no set block outside chunk bounds", testSetBlock(data, 0, 256, 0, RED_WOOL, AIR)); - assertTrue("Can no set block outside chunk bounds", testSetBlock(data, 0, 0, 16, RED_WOOL, AIR)); - } - - @Test - public void testSetRegion() { - CraftChunkData data = new CraftChunkData(256); - testSetRegion(data, -100, 0, -100, 0, 256, 0, RED_WOOL); // exclusively outside - testSetRegion(data, 16, 256, 16, 0, 0, 0, RED_WOOL); // minimum >= maximum - testSetRegion(data, 0, 0, 0, 0, 0, 0, RED_WOOL); // minimum == maximum - testSetRegion(data, 0, 0, 0, 16, 16, 16, RED_WOOL); // Whole Chunk Section - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 8, 0, 16, 24, 16, RED_WOOL); // Start middle of this section, end middle of next - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 4, 0, 16, 12, 16, RED_WOOL); // Start in this section, end in this section - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 0, 0, 16, 16, 1, RED_WOOL); // Whole Chunk Section - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 8, 0, 16, 24, 1, RED_WOOL); // Start middle of this section, end middle of next - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 4, 0, 16, 12, 1, RED_WOOL); // Start in this section, end in this section - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 0, 0, 1, 16, 1, RED_WOOL); // Whole Chunk Section - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 8, 0, 1, 24, 1, RED_WOOL); // Start middle of this section, end middle of next - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 4, 0, 1, 12, 1, RED_WOOL); // Start in this section, end in this section - data.setRegion(0, 0, 0, 16, 256, 16, AIR); - testSetRegion(data, 0, 0, 0, 1, 1, 1, RED_WOOL); // Set single block. - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/CompositeSerialization.java b/src/test/java/org/bukkit/craftbukkit/inventory/CompositeSerialization.java deleted file mode 100644 index 2a0791bb9..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/CompositeSerialization.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.Material; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; - - -public class CompositeSerialization extends AbstractTestingBase { - - public YamlConfiguration getConfig() { - return new YamlConfiguration(); - } - - @Test - public void testSaveRestoreCompositeList() throws InvalidConfigurationException { - YamlConfiguration out = getConfig(); - - List stacks = new ArrayList(); - stacks.add(new ItemStack(Material.STONE)); - stacks.add(new ItemStack(Material.GRASS)); - stacks.add(new ItemStack(Material.DIRT)); - stacks.add(new ItemStack(Material.COBBLESTONE, 17)); - stacks.add(new ItemStack(Material.OAK_PLANKS, 63)); - stacks.add(new ItemStack(Material.OAK_SAPLING, 1, (short) 1)); - stacks.add(new ItemStack(Material.OAK_LEAVES, 32, (short) 2)); - - ItemStack item7 = new ItemStack(Material.IRON_SHOVEL); - item7.addUnsafeEnchantment(Enchantment.PROTECTION_FIRE, 1); - stacks.add(item7); - - ItemStack item8 = new ItemStack(Material.IRON_PICKAXE); - item8.addUnsafeEnchantment(Enchantment.PROTECTION_FALL, 2); - item8.addUnsafeEnchantment(Enchantment.PROTECTION_EXPLOSIONS, 1); - item8.addUnsafeEnchantment(Enchantment.PROTECTION_PROJECTILE, 5); - item8.addUnsafeEnchantment(Enchantment.OXYGEN, 4); - stacks.add(item8); - - out.set("composite-list.abc.def", stacks); - String yaml = out.saveToString(); - - YamlConfiguration in = new YamlConfiguration(); - in.loadFromString(yaml); - List raw = in.getList("composite-list.abc.def"); - - assertThat(stacks, hasSize(raw.size())); - - for (int i = 0; i < 9; i++) { - assertThat(String.valueOf(i), (Object) stacks.get(i), is((Object) raw.get(i))); - } - } -} - diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/FactoryItemMaterialTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/FactoryItemMaterialTest.java deleted file mode 100644 index 1e5c3ef2d..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/FactoryItemMaterialTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.lang.ArrayUtils; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemFactory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class FactoryItemMaterialTest extends AbstractTestingBase { - static final ItemFactory factory = CraftItemFactory.instance(); - static final StringBuilder buffer = new StringBuilder(); - static final Material[] materials; - - static { - Material[] local_materials = Material.values(); - List list = new ArrayList(local_materials.length); - for (Material material : local_materials) { - if (INVALIDATED_MATERIALS.contains(material)) { - continue; - } - - list.add(material); - } - materials = list.toArray(new Material[list.size()]); - } - - static String name(Enum from, Enum to) { - if (from.getClass() == to.getClass()) { - return buffer.delete(0, Integer.MAX_VALUE).append(from.getClass().getName()).append(' ').append(from.name()).append(" to ").append(to.name()).toString(); - } - return buffer.delete(0, Integer.MAX_VALUE).append(from.getClass().getName()).append('(').append(from.name()).append(") to ").append(to.getClass().getName()).append('(').append(to.name()).append(')').toString(); - } - - @Parameters(name="Material[{index}]:{0}") - public static List data() { - List list = new ArrayList(); - for (Material material : materials) { - list.add(new Object[] {material}); - } - return list; - } - - @Parameter(0) public Material material; - - @Test - public void itemStack() { - ItemStack bukkitStack = new ItemStack(material); - CraftItemStack craftStack = CraftItemStack.asCraftCopy(bukkitStack); - ItemMeta meta = factory.getItemMeta(material); - if (meta == null) { - assertThat(material, is(Material.AIR)); - } else { - assertTrue(factory.isApplicable(meta, bukkitStack)); - assertTrue(factory.isApplicable(meta, craftStack)); - } - } - - @Test - public void generalCase() { - CraftMetaItem meta = (CraftMetaItem) factory.getItemMeta(material); - if (meta == null) { - assertThat(material, is(Material.AIR)); - } else { - assertTrue(factory.isApplicable(meta, material)); - assertTrue(meta.applicableTo(material)); - - meta = meta.clone(); - assertTrue(factory.isApplicable(meta, material)); - assertTrue(meta.applicableTo(material)); - } - } - - @Test - public void asMetaFor() { - final CraftMetaItem baseMeta = (CraftMetaItem) factory.getItemMeta(material); - if (baseMeta == null) { - assertThat(material, is(Material.AIR)); - return; - } - - for (Material other : materials) { - final ItemStack bukkitStack = new ItemStack(other); - final CraftItemStack craftStack = CraftItemStack.asCraftCopy(bukkitStack); - final CraftMetaItem otherMeta = (CraftMetaItem) factory.asMetaFor(baseMeta, other); - - final String testName = name(material, other); - - if (otherMeta == null) { - assertThat(testName, other, is(Material.AIR)); - continue; - } - - assertTrue(testName, factory.isApplicable(otherMeta, craftStack)); - assertTrue(testName, factory.isApplicable(otherMeta, bukkitStack)); - assertTrue(testName, factory.isApplicable(otherMeta, other)); - assertTrue(testName, otherMeta.applicableTo(other)); - } - } - - @Test - public void blankEqualities() { - if (material == Material.AIR) { - return; - } - final CraftMetaItem baseMeta = (CraftMetaItem) factory.getItemMeta(material); - final CraftMetaItem baseMetaClone = baseMeta.clone(); - - final ItemStack baseMetaStack = new ItemStack(material); - baseMetaStack.setItemMeta(baseMeta); - - assertThat(baseMeta, is(not(sameInstance(baseMetaStack.getItemMeta())))); - - assertTrue(factory.equals(baseMeta, null)); - assertTrue(factory.equals(null, baseMeta)); - - assertTrue(factory.equals(baseMeta, baseMetaClone)); - assertTrue(factory.equals(baseMetaClone, baseMeta)); - - assertThat(baseMeta, is(not(sameInstance(baseMetaClone)))); - - assertThat(baseMeta, is(baseMetaClone)); - assertThat(baseMetaClone, is(baseMeta)); - - for (Material other : materials) { - final String testName = name(material, other); - - final CraftMetaItem otherMeta = (CraftMetaItem) factory.asMetaFor(baseMetaClone, other); - - if (otherMeta == null) { - assertThat(testName, other, is(Material.AIR)); - continue; - } - - assertTrue(testName, factory.equals(baseMeta, otherMeta)); - assertTrue(testName, factory.equals(otherMeta, baseMeta)); - - assertThat(testName, baseMeta, is(otherMeta)); - assertThat(testName, otherMeta, is(baseMeta)); - - assertThat(testName, baseMeta.hashCode(), is(otherMeta.hashCode())); - } - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/InventoryWrapperTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/InventoryWrapperTest.java deleted file mode 100644 index 9448c1882..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/InventoryWrapperTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import junit.framework.Assert; -import org.bukkit.Material; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.junit.Test; - -public class InventoryWrapperTest { - - @Test - public void test() { - Inventory raw = new CraftInventoryCustom(null, 9); - raw.addItem(new ItemStack(Material.STONE)); - - Assert.assertTrue(raw.contains(Material.STONE)); - - InventoryWrapper wrapper = new InventoryWrapper(raw); - CraftInventory proxy = new CraftInventory(wrapper); - - Assert.assertTrue(proxy.contains(Material.STONE)); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemFactoryTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemFactoryTest.java deleted file mode 100644 index 18f3e1ff6..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemFactoryTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.HashSet; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import net.minecraft.server.IAnimal; -import net.minecraft.server.IAttribute; - -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; - -public class ItemFactoryTest extends AbstractTestingBase { - - @Test - public void testKnownAttributes() throws Throwable { - final ZipInputStream nmsZipStream = new ZipInputStream(IAnimal.class/* Magic class that isn't imported! */.getProtectionDomain().getCodeSource().getLocation().openStream()); - final Collection names = new HashSet(); - for (ZipEntry clazzEntry; (clazzEntry = nmsZipStream.getNextEntry()) != null; ) { - final String entryName = clazzEntry.getName(); - if (!(entryName.endsWith(".class") && entryName.startsWith("net/minecraft/server/"))) { - continue; - } - - final Class clazz = Class.forName(entryName.substring(0, entryName.length() - ".class".length()).replace('/', '.')); - assertThat(entryName, clazz, is(not(nullValue()))); - for (final Field field : clazz.getDeclaredFields()) { - if (IAttribute.class.isAssignableFrom(field.getType()) && Modifier.isStatic(field.getModifiers())) { - field.setAccessible(true); - final String attributeName = ((IAttribute) field.get(null)).getName(); - assertThat("Logical error: duplicate name `" + attributeName + "' in " + clazz.getName(), names.add(attributeName), is(true)); - assertThat(clazz.getName(), CraftItemFactory.KNOWN_NBT_ATTRIBUTE_NAMES, hasItem(attributeName)); - } - } - } - - nmsZipStream.close(); - - assertThat("Extra values detected", CraftItemFactory.KNOWN_NBT_ATTRIBUTE_NAMES, is(names)); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaCloneTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaCloneTest.java deleted file mode 100644 index 834fb297b..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaCloneTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.lang.reflect.Method; -import org.bukkit.Material; -import org.junit.Test; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -public class ItemMetaCloneTest { - - @Test - public void testClone() throws Throwable { - for (Material material : ItemStackTest.COMPOUND_MATERIALS) { - Class clazz = CraftItemFactory.instance().getItemMeta(material).getClass(); - - Method clone = clazz.getDeclaredMethod("clone"); - assertNotNull("Class " + clazz + " does not override clone()", clone); - assertThat("Class " + clazz + " clone return type does not match", clone.getReturnType(), is(equalTo(clazz))); - } - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaCustomValueTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaCustomValueTest.java deleted file mode 100644 index fa303d1fa..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaCustomValueTest.java +++ /dev/null @@ -1,327 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.io.StringReader; -import java.lang.reflect.Array; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Map; -import java.util.UUID; -import net.minecraft.server.NBTBase; -import net.minecraft.server.NBTTagCompound; -import net.minecraft.server.NBTTagIntArray; -import net.minecraft.server.NBTTagList; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.craftbukkit.inventory.tags.CraftCustomItemTagContainer; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.tags.CustomItemTagContainer; -import org.bukkit.inventory.meta.tags.ItemTagAdapterContext; -import org.bukkit.inventory.meta.tags.ItemTagType; -import org.bukkit.support.AbstractTestingBase; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.Test; - -public class ItemMetaCustomValueTest extends AbstractTestingBase { - - private static NamespacedKey VALID_KEY; - - @Before - public void setup() { - VALID_KEY = new NamespacedKey("test", "validkey"); - } - - /* - Sets a test - */ - @Test(expected = IllegalArgumentException.class) - public void testSetNoAdapter() { - ItemMeta itemMeta = createNewItemMeta(); - itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, new PrimitiveTagType<>(boolean.class), true); - } - - /* - Contains a tag - */ - @Test(expected = IllegalArgumentException.class) - public void testHasNoAdapter() { - ItemMeta itemMeta = createNewItemMeta(); - itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, ItemTagType.INTEGER, 1); // We gotta set this so we at least try to compare it - itemMeta.getCustomTagContainer().hasCustomTag(VALID_KEY, new PrimitiveTagType<>(boolean.class)); - } - - /* - Getting a tag - */ - @Test(expected = IllegalArgumentException.class) - public void testGetNoAdapter() { - ItemMeta itemMeta = createNewItemMeta(); - itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, ItemTagType.INTEGER, 1); //We gotta set this so we at least try to compare it - itemMeta.getCustomTagContainer().getCustomTag(VALID_KEY, new PrimitiveTagType<>(boolean.class)); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetWrongType() { - ItemMeta itemMeta = createNewItemMeta(); - itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, ItemTagType.INTEGER, 1); - itemMeta.getCustomTagContainer().getCustomTag(VALID_KEY, ItemTagType.STRING); - } - - @Test - public void testDifferentNamespace() { - NamespacedKey namespacedKeyA = new NamespacedKey("plugin-a", "damage"); - NamespacedKey namespacedKeyB = new NamespacedKey("plugin-b", "damage"); - - ItemMeta meta = createNewItemMeta(); - meta.getCustomTagContainer().setCustomTag(namespacedKeyA, ItemTagType.LONG, 15L); - meta.getCustomTagContainer().setCustomTag(namespacedKeyB, ItemTagType.LONG, 160L); - - assertEquals(15L, (long) meta.getCustomTagContainer().getCustomTag(namespacedKeyA, ItemTagType.LONG)); - assertEquals(160L, (long) meta.getCustomTagContainer().getCustomTag(namespacedKeyB, ItemTagType.LONG)); - } - - private ItemMeta createNewItemMeta() { - return Bukkit.getItemFactory().getItemMeta(Material.DIAMOND_PICKAXE); - } - - private NamespacedKey requestKey(String keyName) { - return new NamespacedKey("test-plugin", keyName.toLowerCase()); - } - - /* - Removing a tag - */ - @Test - public void testNBTTagStoring() { - CraftMetaItem itemMeta = createComplexItemMeta(); - - NBTTagCompound compound = new NBTTagCompound(); - itemMeta.applyToItem(compound); - - assertEquals(itemMeta, new CraftMetaItem(compound)); - } - - @Test - public void testMapStoring() { - CraftMetaItem itemMeta = createComplexItemMeta(); - - Map serialize = itemMeta.serialize(); - assertEquals(itemMeta, new CraftMetaItem(serialize)); - } - - @Test - public void testYAMLStoring() { - ItemStack stack = new ItemStack(Material.DIAMOND); - CraftMetaItem meta = createComplexItemMeta(); - stack.setItemMeta(meta); - - YamlConfiguration configuration = new YamlConfiguration(); - configuration.set("testpath", stack); - - String configValue = configuration.saveToString(); - YamlConfiguration loadedConfig = YamlConfiguration.loadConfiguration(new StringReader(configValue)); - - assertEquals(stack, loadedConfig.getSerializable("testpath", ItemStack.class)); - assertNotEquals(new ItemStack(Material.DIAMOND), loadedConfig.getSerializable("testpath", ItemStack.class)); - } - - @Test - public void testCorrectType() { - ItemStack stack = new ItemStack(Material.DIAMOND); - CraftMetaItem meta = createComplexItemMeta(); - - meta.getCustomTagContainer().setCustomTag(requestKey("int"), ItemTagType.STRING, "1"); - meta.getCustomTagContainer().setCustomTag(requestKey("double"), ItemTagType.STRING, "1.33"); - stack.setItemMeta(meta); - - YamlConfiguration configuration = new YamlConfiguration(); - configuration.set("testpath", stack); - - String configValue = configuration.saveToString(); - YamlConfiguration loadedConfig = YamlConfiguration.loadConfiguration(new StringReader(configValue)); - ItemStack newStack = loadedConfig.getSerializable("testpath", ItemStack.class); - - assertTrue(newStack.getItemMeta().getCustomTagContainer().hasCustomTag(requestKey("int"), ItemTagType.STRING)); - assertEquals(newStack.getItemMeta().getCustomTagContainer().getCustomTag(requestKey("int"), ItemTagType.STRING), "1"); - - assertTrue(newStack.getItemMeta().getCustomTagContainer().hasCustomTag(requestKey("double"), ItemTagType.STRING)); - assertEquals(newStack.getItemMeta().getCustomTagContainer().getCustomTag(requestKey("double"), ItemTagType.STRING), "1.33"); - } - - private CraftMetaItem createComplexItemMeta() { - CraftMetaItem itemMeta = (CraftMetaItem) createNewItemMeta(); - itemMeta.setDisplayName("Item Display Name"); - - itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-long"), ItemTagType.LONG, 4L); //Add random primitive values - itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-byte-array"), ItemTagType.BYTE_ARRAY, new byte[]{ - 0, 1, 2, 10 - }); - itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-string"), ItemTagType.STRING, "Hello there world"); - itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-int"), ItemTagType.INTEGER, 3); - itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-double"), ItemTagType.DOUBLE, 3.123); - - CustomItemTagContainer innerContainer = itemMeta.getCustomTagContainer().getAdapterContext().newTagContainer(); //Add a inner container - innerContainer.setCustomTag(VALID_KEY, ItemTagType.LONG, 5L); - itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-inner-compound"), ItemTagType.TAG_CONTAINER, innerContainer); - - Map rawMap = ((CraftCustomItemTagContainer) itemMeta.getCustomTagContainer()).getRaw(); //Adds a tag list as well (even tho is has no API yet) - NBTTagList nbtList = new NBTTagList(); - nbtList.add(new NBTTagIntArray(Arrays.asList(1, 5, 3))); - nbtList.add(new NBTTagIntArray(Arrays.asList(42, 51))); - rawMap.put("nbttaglist", nbtList); - return itemMeta; - } - - /* - Test complex object storage - */ - @Test - public void storeUUIDOnItemTest() { - ItemMeta itemMeta = createNewItemMeta(); - UUIDItemTagType uuidItemTagType = new UUIDItemTagType(); - UUID uuid = UUID.fromString("434eea72-22a6-4c61-b5ef-945874a5c478"); - - itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, uuidItemTagType, uuid); - assertTrue(itemMeta.getCustomTagContainer().hasCustomTag(VALID_KEY, uuidItemTagType)); - assertEquals(uuid, itemMeta.getCustomTagContainer().getCustomTag(VALID_KEY, uuidItemTagType)); - } - - @Test - public void encapsulatedContainers() { - NamespacedKey innerKey = new NamespacedKey("plugin-a", "inner"); - - ItemMeta meta = createNewItemMeta(); - ItemTagAdapterContext context = meta.getCustomTagContainer().getAdapterContext(); - - CustomItemTagContainer thirdContainer = context.newTagContainer(); - thirdContainer.setCustomTag(VALID_KEY, ItemTagType.LONG, 3L); - - CustomItemTagContainer secondContainer = context.newTagContainer(); - secondContainer.setCustomTag(VALID_KEY, ItemTagType.LONG, 2L); - secondContainer.setCustomTag(innerKey, ItemTagType.TAG_CONTAINER, thirdContainer); - - meta.getCustomTagContainer().setCustomTag(VALID_KEY, ItemTagType.LONG, 1L); - meta.getCustomTagContainer().setCustomTag(innerKey, ItemTagType.TAG_CONTAINER, secondContainer); - - assertEquals(3L, meta.getCustomTagContainer() - .getCustomTag(innerKey, ItemTagType.TAG_CONTAINER) - .getCustomTag(innerKey, ItemTagType.TAG_CONTAINER) - .getCustomTag(VALID_KEY, ItemTagType.LONG).longValue()); - - assertEquals(2L, meta.getCustomTagContainer() - .getCustomTag(innerKey, ItemTagType.TAG_CONTAINER) - .getCustomTag(VALID_KEY, ItemTagType.LONG).longValue()); - - assertEquals(1L, meta.getCustomTagContainer() - .getCustomTag(VALID_KEY, ItemTagType.LONG).longValue()); - } - - class UUIDItemTagType implements ItemTagType { - - @Override - public Class getPrimitiveType() { - return byte[].class; - } - - @Override - public Class getComplexType() { - return UUID.class; - } - - @Override - public byte[] toPrimitive(UUID complex, ItemTagAdapterContext context) { - ByteBuffer bb = ByteBuffer.wrap(new byte[16]); - bb.putLong(complex.getMostSignificantBits()); - bb.putLong(complex.getLeastSignificantBits()); - return bb.array(); - } - - @Override - public UUID fromPrimitive(byte[] primitive, ItemTagAdapterContext context) { - ByteBuffer bb = ByteBuffer.wrap(primitive); - long firstLong = bb.getLong(); - long secondLong = bb.getLong(); - return new UUID(firstLong, secondLong); - } - } - - @Test - public void testPrimitiveCustomTags() { - ItemMeta itemMeta = createNewItemMeta(); - - testPrimitiveCustomTag(itemMeta, ItemTagType.BYTE, (byte) 1); - testPrimitiveCustomTag(itemMeta, ItemTagType.SHORT, (short) 1); - testPrimitiveCustomTag(itemMeta, ItemTagType.INTEGER, 1); - testPrimitiveCustomTag(itemMeta, ItemTagType.LONG, 1L); - testPrimitiveCustomTag(itemMeta, ItemTagType.FLOAT, 1.34F); - testPrimitiveCustomTag(itemMeta, ItemTagType.DOUBLE, 151.123); - - testPrimitiveCustomTag(itemMeta, ItemTagType.STRING, "test"); - - testPrimitiveCustomTag(itemMeta, ItemTagType.BYTE_ARRAY, new byte[]{ - 1, 4, 2, Byte.MAX_VALUE - }); - testPrimitiveCustomTag(itemMeta, ItemTagType.INTEGER_ARRAY, new int[]{ - 1, 4, 2, Integer.MAX_VALUE - }); - testPrimitiveCustomTag(itemMeta, ItemTagType.LONG_ARRAY, new long[]{ - 1L, 4L, 2L, Long.MAX_VALUE - }); - } - - private void testPrimitiveCustomTag(ItemMeta meta, ItemTagType type, Z value) { - NamespacedKey tagKey = new NamespacedKey("test", String.valueOf(type.hashCode())); - - meta.getCustomTagContainer().setCustomTag(tagKey, type, value); - assertTrue(meta.getCustomTagContainer().hasCustomTag(tagKey, type)); - - Z foundValue = meta.getCustomTagContainer().getCustomTag(tagKey, type); - if (foundValue.getClass().isArray()) { // Compare arrays using reflection access - int length = Array.getLength(foundValue); - int originalLength = Array.getLength(value); - for (int i = 0; i < length && i < originalLength; i++) { - assertEquals(Array.get(value, i), Array.get(foundValue, i)); - } - } else { - assertEquals(foundValue, value); - } - - meta.getCustomTagContainer().removeCustomTag(tagKey); - assertFalse(meta.getCustomTagContainer().hasCustomTag(tagKey, type)); - } - - class PrimitiveTagType implements ItemTagType { - - private final Class primitiveType; - - PrimitiveTagType(Class primitiveType) { - this.primitiveType = primitiveType; - } - - @Override - public Class getPrimitiveType() { - return primitiveType; - } - - @Override - public Class getComplexType() { - return primitiveType; - } - - @Override - public T toPrimitive(T complex, ItemTagAdapterContext context) { - return complex; - } - - @Override - public T fromPrimitive(T primitive, ItemTagAdapterContext context) { - return primitive; - } - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaImplementationOverrideTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaImplementationOverrideTest.java deleted file mode 100644 index f1b4ec0da..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaImplementationOverrideTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Callable; - -import org.bukkit.Material; -import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.Overridden; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class ItemMetaImplementationOverrideTest { - static final Class parent = CraftMetaItem.class; - - @Parameters(name="[{index}]:{1}") - public static List data() { - final List testData = new ArrayList(); - List> classes = new ArrayList>(); - - for (Material material : ItemStackTest.COMPOUND_MATERIALS) { - Class clazz = CraftItemFactory.instance().getItemMeta(material).getClass().asSubclass(parent); - if (clazz != parent) { - classes.add(clazz); - } - } - - List list = new ArrayList(); - - for (Method method: parent.getDeclaredMethods()) { - if (method.isAnnotationPresent(Overridden.class)) { - list.add(method); - } - } - - for (final Class clazz : classes) { - for (final Method method : list) { - testData.add( - new Object[] { - new Callable() { - public Method call() throws Exception { - return clazz.getDeclaredMethod(method.getName(), method.getParameterTypes()); - } - }, - clazz.getSimpleName() + " contains " + method.getName() - } - ); - } - - testData.add( - new Object[] { - new Callable() { - public DelegateDeserialization call() throws Exception { - return clazz.getAnnotation(DelegateDeserialization.class); - } - }, - clazz.getSimpleName() + " contains annotation " + DelegateDeserialization.class - } - ); - } - - return testData; - } - - @Parameter(0) public Callable test; - @Parameter(1) public String name; - - @Test - public void testClass() throws Throwable { - assertThat(name, test.call(), is(not(nullValue()))); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaTest.java deleted file mode 100644 index 7455461f1..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemMetaTest.java +++ /dev/null @@ -1,423 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; // Paper -import java.util.List; -import java.util.UUID; - -import com.destroystokyo.paper.inventory.meta.ArmorStandMeta; // Paper -import net.minecraft.server.Block; -import net.minecraft.server.IRegistry; -import net.minecraft.server.ITileEntity; -import net.minecraft.server.Item; -import net.minecraft.server.ItemBlock; -import net.minecraft.server.ItemBlockWallable; -import net.minecraft.server.NBTTagInt; - -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.DyeColor; -import org.bukkit.FireworkEffect; -import org.bukkit.Material; -import org.bukkit.FireworkEffect.Type; -import org.bukkit.NamespacedKey; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.block.banner.Pattern; -import org.bukkit.block.banner.PatternType; -import org.bukkit.craftbukkit.inventory.ItemStackTest.StackProvider; -import org.bukkit.craftbukkit.inventory.ItemStackTest.StackWrapper; -import org.bukkit.craftbukkit.inventory.ItemStackTest.BukkitWrapper; -import org.bukkit.craftbukkit.inventory.ItemStackTest.CraftWrapper; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.TropicalFish; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BannerMeta; -import org.bukkit.inventory.meta.BlockStateMeta; -import org.bukkit.inventory.meta.BookMeta; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.bukkit.inventory.meta.FireworkEffectMeta; -import org.bukkit.inventory.meta.FireworkMeta; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.KnowledgeBookMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.MapMeta; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.inventory.meta.SpawnEggMeta; -import org.bukkit.inventory.meta.TropicalFishBucketMeta; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionType; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; - -public class ItemMetaTest extends AbstractTestingBase { - - static final int MAX_FIREWORK_POWER = 127; // Please update ItemStackFireworkTest if/when this gets changed. - - @Test(expected=IllegalArgumentException.class) - public void testPowerLimitExact() { - newFireworkMeta().setPower(MAX_FIREWORK_POWER + 1); - } - - @Test(expected=IllegalArgumentException.class) - public void testPowerLimitMax() { - newFireworkMeta().setPower(Integer.MAX_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testPowerLimitMin() { - newFireworkMeta().setPower(Integer.MIN_VALUE); - } - - @Test(expected=IllegalArgumentException.class) - public void testPowerLimitNegative() { - newFireworkMeta().setPower(-1); - } - - @Test - public void testPowers() { - for (int i = 0; i <= MAX_FIREWORK_POWER; i++) { - FireworkMeta firework = newFireworkMeta(); - firework.setPower(i); - assertThat(String.valueOf(i), firework.getPower(), is(i)); - } - } - - @Test - public void testConflictingEnchantment() { - ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(Material.DIAMOND_PICKAXE); - assertThat(itemMeta.hasConflictingEnchant(Enchantment.DURABILITY), is(false)); - - itemMeta.addEnchant(Enchantment.SILK_TOUCH, 1, false); - assertThat(itemMeta.hasConflictingEnchant(Enchantment.DURABILITY), is(false)); - assertThat(itemMeta.hasConflictingEnchant(Enchantment.LOOT_BONUS_BLOCKS), is(true)); - assertThat(itemMeta.hasConflictingEnchant(null), is(false)); - } - - @Test - public void testConflictingStoredEnchantment() { - EnchantmentStorageMeta itemMeta = (EnchantmentStorageMeta) Bukkit.getItemFactory().getItemMeta(Material.ENCHANTED_BOOK); - assertThat(itemMeta.hasConflictingStoredEnchant(Enchantment.DURABILITY), is(false)); - - itemMeta.addStoredEnchant(Enchantment.SILK_TOUCH, 1, false); - assertThat(itemMeta.hasConflictingStoredEnchant(Enchantment.DURABILITY), is(false)); - assertThat(itemMeta.hasConflictingStoredEnchant(Enchantment.LOOT_BONUS_BLOCKS), is(true)); - assertThat(itemMeta.hasConflictingStoredEnchant(null), is(false)); - } - - @Test - public void testConflictingEnchantments() { - ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(Material.DIAMOND_PICKAXE); - itemMeta.addEnchant(Enchantment.DURABILITY, 6, true); - itemMeta.addEnchant(Enchantment.DIG_SPEED, 6, true); - assertThat(itemMeta.hasConflictingEnchant(Enchantment.LOOT_BONUS_BLOCKS), is(false)); - - itemMeta.addEnchant(Enchantment.SILK_TOUCH, 1, false); - assertThat(itemMeta.hasConflictingEnchant(Enchantment.LOOT_BONUS_BLOCKS), is(true)); - assertThat(itemMeta.hasConflictingEnchant(null), is(false)); - } - - @Test - public void testConflictingStoredEnchantments() { - EnchantmentStorageMeta itemMeta = (EnchantmentStorageMeta) Bukkit.getItemFactory().getItemMeta(Material.ENCHANTED_BOOK); - itemMeta.addStoredEnchant(Enchantment.DURABILITY, 6, true); - itemMeta.addStoredEnchant(Enchantment.DIG_SPEED, 6, true); - assertThat(itemMeta.hasConflictingStoredEnchant(Enchantment.LOOT_BONUS_BLOCKS), is(false)); - - itemMeta.addStoredEnchant(Enchantment.SILK_TOUCH, 1, false); - assertThat(itemMeta.hasConflictingStoredEnchant(Enchantment.LOOT_BONUS_BLOCKS), is(true)); - assertThat(itemMeta.hasConflictingStoredEnchant(null), is(false)); - } - - private static FireworkMeta newFireworkMeta() { - return ((FireworkMeta) Bukkit.getItemFactory().getItemMeta(Material.FIREWORK_ROCKET)); - } - - @Test - public void testCrazyEquality() { - CraftItemStack craft = CraftItemStack.asCraftCopy(new ItemStack(Material.STONE)); - craft.setItemMeta(craft.getItemMeta()); - ItemStack bukkit = new ItemStack(craft); - assertThat(craft, is(bukkit)); - assertThat(bukkit, is((ItemStack) craft)); - } - - @Test - public void testTaggedButNotMeta() { - CraftItemStack craft = CraftItemStack.asCraftCopy(new ItemStack(Material.SHEARS)); - craft.handle.setDamage(0); - - assertThat("Should have NBT tag", CraftItemStack.hasItemMeta(craft.handle), is(true)); - assertThat("NBT Tag should contain Damage", craft.handle.getTag().get("Damage"), instanceOf(NBTTagInt.class)); - assertThat("But we should not have meta", craft.hasItemMeta(), is(false)); - - ItemStack pureBukkit = new ItemStack(Material.SHEARS); - assertThat("Bukkit and craft stacks should be similar", craft.isSimilar(pureBukkit), is(true)); - assertThat("Bukkit and craft stacks should be equal", craft.equals(pureBukkit), is(true)); - // Paper start - test additional ItemMeta damage cases - ItemStack clone = CraftItemStack.asBukkitCopy(CraftItemStack.asNMSCopy(craft)); - assertThat("Bukkit and craft stacks should be similar", craft.isSimilar(clone), is(true)); - assertThat("Bukkit and craft stacks should be equal", craft.equals(clone), is(true)); - - pureBukkit = new ItemStack(Material.DIAMOND_SWORD); - pureBukkit.setDurability((short) 2); - net.minecraft.server.ItemStack nms = CraftItemStack.asNMSCopy(pureBukkit); - ItemStack other = CraftItemStack.asBukkitCopy(nms); - - assertThat("Bukkit and NMS ItemStack copies should be similar", pureBukkit.isSimilar(other), is(true)); - assertThat("Bukkit and NMS ItemStack copies should be equal", pureBukkit.equals(other), is(true)); - } - - private void testItemMeta(ItemStack stack) { - assertThat("Should not have ItemMeta", stack.hasItemMeta(), is(false)); - - stack.setDurability((short) 0); - assertThat("ItemStack with zero durability should not have ItemMeta", stack.hasItemMeta(), is(false)); - - stack.setDurability((short) 2); - assertThat("ItemStack with non-zero durability should have ItemMeta", stack.hasItemMeta(), is(true)); - - stack.setLore(Collections.singletonList("Lore")); - assertThat("ItemStack with lore and durability should have ItemMeta", stack.hasItemMeta(), is(true)); - - stack.setDurability((short) 0); - assertThat("ItemStack with lore should have ItemMeta", stack.hasItemMeta(), is(true)); - - stack.setLore(null); - } - - @Test - public void testHasItemMeta() { - ItemStack itemStack = new ItemStack(Material.SHEARS); - - testItemMeta(itemStack); - testItemMeta(CraftItemStack.asCraftCopy(itemStack)); - } - // Paper end - - @Test - public void testBlockStateMeta() { - List queue = new ArrayList<>(); - - for (Item item : (Iterable) IRegistry.ITEM) { // Eclipse fail - if (item instanceof ItemBlock) { - queue.add(((ItemBlock) item).getBlock()); - } - if (item instanceof ItemBlockWallable) { - queue.add(((ItemBlockWallable) item).wallBlock); - } - } - - for (Block block : queue) { - if (block != null) { - ItemStack stack = CraftItemStack.asNewCraftStack(Item.getItemOf(block)); - - // Command blocks aren't unit testable atm - if (stack.getType() == Material.COMMAND_BLOCK || stack.getType() == Material.CHAIN_COMMAND_BLOCK || stack.getType() == Material.REPEATING_COMMAND_BLOCK) { - return; - } - - ItemMeta meta = stack.getItemMeta(); - if (block instanceof ITileEntity) { - assertTrue(stack + " has meta of type " + meta + " expected BlockStateMeta", meta instanceof BlockStateMeta); - - BlockStateMeta blockState = (BlockStateMeta) meta; - assertNotNull(stack + " has null block state", blockState.getBlockState()); - - blockState.setBlockState(blockState.getBlockState()); - } else { - assertTrue(stack + " has unexpected meta of type BlockStateMeta (but is not a tile)", !(meta instanceof BlockStateMeta)); - } - } - } - } - - @Test - public void testEachExtraData() { - final List providers = Arrays.asList( - new StackProvider(Material.WRITABLE_BOOK) { - @Override ItemStack operate(final ItemStack cleanStack) { - final BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setAuthor("Some author"); - meta.setPages("Page 1", "Page 2"); - meta.setTitle("A title"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new StackProvider(Material.WRITTEN_BOOK) { - @Override ItemStack operate(final ItemStack cleanStack) { - final BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setAuthor("Some author"); - meta.setPages("Page 1", "Page 2"); - meta.setTitle("A title"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - /* Skulls rely on a running server instance - new StackProvider(Material.SKULL_ITEM) { - @Override ItemStack operate(final ItemStack cleanStack) { - final SkullMeta meta = (SkullMeta) cleanStack.getItemMeta(); - meta.setOwner("Notch"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - */ - new StackProvider(Material.FILLED_MAP) { - @Override ItemStack operate(final ItemStack cleanStack) { - final MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - meta.setScaling(true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new StackProvider(Material.LEATHER_BOOTS) { - @Override ItemStack operate(final ItemStack cleanStack) { - final LeatherArmorMeta meta = (LeatherArmorMeta) cleanStack.getItemMeta(); - meta.setColor(Color.FUCHSIA); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new StackProvider(Material.POTION) { - @Override ItemStack operate(final ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.setBasePotionData(new PotionData(PotionType.UNCRAFTABLE, false, false)); - meta.addCustomEffect(PotionEffectType.CONFUSION.createEffect(1, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new StackProvider(Material.FIREWORK_ROCKET) { - @Override ItemStack operate(final ItemStack cleanStack) { - final FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.GREEN).withFade(Color.OLIVE).with(Type.BALL_LARGE).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new StackProvider(Material.ENCHANTED_BOOK) { - @Override ItemStack operate(final ItemStack cleanStack) { - final EnchantmentStorageMeta meta = (EnchantmentStorageMeta) cleanStack.getItemMeta(); - meta.addStoredEnchant(Enchantment.ARROW_FIRE, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new StackProvider(Material.FIREWORK_STAR) { - @Override ItemStack operate(final ItemStack cleanStack) { - final FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.MAROON, Color.BLACK).with(Type.CREEPER).withFlicker().build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new StackProvider(Material.WHITE_BANNER) { - @Override ItemStack operate(ItemStack cleanStack) { - final BannerMeta meta = (BannerMeta) cleanStack.getItemMeta(); - meta.setBaseColor(DyeColor.CYAN); - meta.addPattern(new Pattern(DyeColor.WHITE, PatternType.BRICKS)); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - /* No distinguishing features, add back with virtual entity API - new StackProvider(Material.ZOMBIE_SPAWN_EGG) { - @Override ItemStack operate(ItemStack cleanStack) { - final SpawnEggMeta meta = (SpawnEggMeta) cleanStack.getItemMeta(); - meta.setSpawnedType(EntityType.ZOMBIE); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - */ - new StackProvider(Material.KNOWLEDGE_BOOK) { - @Override ItemStack operate(ItemStack cleanStack) { - final KnowledgeBookMeta meta = (KnowledgeBookMeta) cleanStack.getItemMeta(); - meta.addRecipe(new NamespacedKey("minecraft", "test"), new NamespacedKey("plugin", "test")); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new StackProvider(Material.TROPICAL_FISH_BUCKET) { - @Override ItemStack operate(ItemStack cleanStack) { - final TropicalFishBucketMeta meta = (TropicalFishBucketMeta) cleanStack.getItemMeta(); - meta.setBodyColor(DyeColor.ORANGE); - meta.setPatternColor(DyeColor.BLACK); - meta.setPattern(TropicalFish.Pattern.DASHER); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - // Paper start - new StackProvider(Material.ARMOR_STAND) { - @Override - ItemStack operate(ItemStack cleanStack) { - final ArmorStandMeta meta = (ArmorStandMeta) cleanStack.getItemMeta(); - meta.setInvisible(true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - } - // paper end - ); - - assertThat("Forgotten test?", providers, hasSize(ItemStackTest.COMPOUND_MATERIALS.length - 4/* Normal item meta, skulls, eggs and tile entities */)); - - for (final StackProvider provider : providers) { - downCastTest(new BukkitWrapper(provider)); - downCastTest(new CraftWrapper(provider)); - } - } - - @Test - public void testAttributeModifiers() { - UUID sameUUID = UUID.randomUUID(); - ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(Material.DIAMOND_PICKAXE); - itemMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, new AttributeModifier(sameUUID, "Test Modifier", 10, AttributeModifier.Operation.ADD_NUMBER)); - - ItemMeta equalMeta = Bukkit.getItemFactory().getItemMeta(Material.DIAMOND_PICKAXE); - equalMeta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, new AttributeModifier(sameUUID, "Test Modifier", 10, AttributeModifier.Operation.ADD_NUMBER)); - - assertThat(itemMeta.equals(equalMeta), is(true)); - - ItemMeta itemMeta2 = Bukkit.getItemFactory().getItemMeta(Material.DIAMOND_PICKAXE); - itemMeta2.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, new AttributeModifier(sameUUID, "Test Modifier", 10, AttributeModifier.Operation.ADD_NUMBER)); - - ItemMeta notEqualMeta2 = Bukkit.getItemFactory().getItemMeta(Material.DIAMOND_PICKAXE); - notEqualMeta2.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, new AttributeModifier(sameUUID, "Test Modifier", 11, AttributeModifier.Operation.ADD_NUMBER)); - - assertThat(itemMeta2.equals(notEqualMeta2), is(false)); - } - - private void downCastTest(final StackWrapper provider) { - final String name = provider.toString(); - final ItemStack blank = new ItemStack(Material.STONE); - final ItemStack craftBlank = CraftItemStack.asCraftCopy(blank); - - downCastTest(name, provider.stack(), blank); - blank.setItemMeta(blank.getItemMeta()); - downCastTest(name, provider.stack(), blank); - - downCastTest(name, provider.stack(), craftBlank); - craftBlank.setItemMeta(craftBlank.getItemMeta()); - downCastTest(name, provider.stack(), craftBlank); - } - - private void downCastTest(final String name, final ItemStack stack, final ItemStack blank) { - assertThat(name, stack, is(not(blank))); - assertThat(name, stack.getItemMeta(), is(not(blank.getItemMeta()))); - - stack.setType(Material.STONE); - - assertThat(name, stack, is(blank)); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackBookTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackBookTest.java deleted file mode 100644 index c16c5611d..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackBookTest.java +++ /dev/null @@ -1,213 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BookMeta; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackBookTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.WRITTEN_BOOK, Material.WRITABLE_BOOK); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - Long.parseLong("1110", 2), - ItemStackLoreEnchantmentTest.operators(), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.addPage("Page 1", "Page 2"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Pages vs. Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.addPage("Page 1", "Page 2"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - cleanStack.setItemMeta(cleanStack.getItemMeta()); - return cleanStack; - } - }, - "Pages vs. blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.addPage("Page 1", "Page 2"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.addPage("Page 2", "Page 1"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Pages switched" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.addPage("Page 1", "Page 2"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.addPage("Page 1"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Pages short" - } - ), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setAuthor("AnAuthor"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Author vs. Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setAuthor("AnAuthor"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - cleanStack.setItemMeta(cleanStack.getItemMeta()); - return cleanStack; - } - }, - "Author vs. blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setAuthor("AnAuthor"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setAuthor("AnotherAuthor"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Authors" - } - ), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setTitle("Some title"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Title vs. Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setTitle("Some title"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - cleanStack.setItemMeta(cleanStack.getItemMeta()); - return cleanStack; - } - }, - "title vs. blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setTitle("Some title"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - BookMeta meta = (BookMeta) cleanStack.getItemMeta(); - meta.setTitle("Different title"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Titles" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackEnchantStorageTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackEnchantStorageTest.java deleted file mode 100644 index a0499b8ad..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackEnchantStorageTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackEnchantStorageTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.ENCHANTED_BOOK); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - Long.parseLong("10", 2), - ItemStackLoreEnchantmentTest.operators(), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) cleanStack.getItemMeta(); - meta.addStoredEnchant(Enchantment.DURABILITY, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Enchantable vs Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) cleanStack.getItemMeta(); - meta.addStoredEnchant(Enchantment.KNOCKBACK, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Enchantable vs Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) cleanStack.getItemMeta(); - meta.addStoredEnchant(Enchantment.DAMAGE_UNDEAD, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) cleanStack.getItemMeta(); - meta.addStoredEnchant(Enchantment.DAMAGE_UNDEAD, 1, true); - meta.addStoredEnchant(Enchantment.FIRE_ASPECT, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Enchantable vs More" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) cleanStack.getItemMeta(); - meta.addStoredEnchant(Enchantment.PROTECTION_FIRE, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) cleanStack.getItemMeta(); - meta.addEnchant(Enchantment.PROTECTION_FIRE, 2, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Enchantable vs Other" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackFireworkChargeTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackFireworkChargeTest.java deleted file mode 100644 index fbfce58c5..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackFireworkChargeTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Color; -import org.bukkit.FireworkEffect; -import org.bukkit.FireworkEffect.Type; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.FireworkEffectMeta; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackFireworkChargeTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.FIREWORK_STAR); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - Long.parseLong("10", 2), - ItemStackLoreEnchantmentTest.operators(), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.WHITE).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.BLACK).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Effect Color 1 vs. Effect Color 2" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.WHITE).with(Type.CREEPER).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.WHITE).with(Type.BURST).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Effect type 1 vs. Effect type 2" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.WHITE).withFade(Color.BLUE).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.WHITE).withFade(Color.RED).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Effect fade 1 vs. Effect fade 2" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.WHITE).withFlicker().build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Effect vs. Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkEffectMeta meta = (FireworkEffectMeta) cleanStack.getItemMeta(); - meta.setEffect(FireworkEffect.builder().withColor(Color.WHITE).withTrail().build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Effect vs. None" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackFireworkTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackFireworkTest.java deleted file mode 100644 index 55e6629bc..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackFireworkTest.java +++ /dev/null @@ -1,184 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Color; -import org.bukkit.FireworkEffect; -import org.bukkit.Material; -import org.bukkit.FireworkEffect.Type; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.FireworkMeta; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackFireworkTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.FIREWORK_ROCKET); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - Long.parseLong("110", 2), - ItemStackLoreEnchantmentTest.operators(), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.WHITE).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.BLACK).build()); - meta.addEffect(FireworkEffect.builder().withColor(Color.GREEN).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Effect Color 1 vs. Effect Color 2" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.WHITE).with(Type.CREEPER).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.WHITE).with(Type.BURST).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Effect type 1 vs. Effect type 2" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.WHITE).withFade(Color.BLUE).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.WHITE).withFade(Color.RED).build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Effect fade 1 vs. Effect fade 2" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.WHITE).withFlicker().build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Effect vs. Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.addEffect(FireworkEffect.builder().withColor(Color.WHITE).withTrail().build()); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Effect vs. None" - } - ), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.setPower(127); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.setPower(100); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Height vs. Other" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.setPower(42); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Height vs. Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - FireworkMeta meta = (FireworkMeta) cleanStack.getItemMeta(); - meta.setPower(10); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Height vs. None" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackLeatherTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackLeatherTest.java deleted file mode 100644 index 6d68e1f46..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackLeatherTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.LeatherArmorMeta; - -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackLeatherTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.LEATHER_BOOTS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET, Material.LEATHER_LEGGINGS); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - Long.parseLong("10", 2), - ItemStackLoreEnchantmentTest.operators(), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - LeatherArmorMeta meta = (LeatherArmorMeta) cleanStack.getItemMeta(); - meta.setColor(Color.FUCHSIA); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Color vs Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - LeatherArmorMeta meta = (LeatherArmorMeta) cleanStack.getItemMeta(); - meta.setColor(Color.GRAY); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - LeatherArmorMeta meta = (LeatherArmorMeta) cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Color vs Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - LeatherArmorMeta meta = (LeatherArmorMeta) cleanStack.getItemMeta(); - meta.setColor(Color.MAROON); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - LeatherArmorMeta meta = (LeatherArmorMeta) cleanStack.getItemMeta(); - meta.setColor(Color.ORANGE); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Color vs Other" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackLoreEnchantmentTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackLoreEnchantmentTest.java deleted file mode 100644 index 32a9184fd..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackLoreEnchantmentTest.java +++ /dev/null @@ -1,297 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.Repairable; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackLoreEnchantmentTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, ItemStackTest.COMPOUND_MATERIALS); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - ~0l, - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.setLore(Arrays.asList("First Lore", "Second Lore")); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Lore vs Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.setLore(Arrays.asList("Some lore")); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Lore vs Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.setLore(Arrays.asList("Some more lore", "Another lore")); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.setLore(Arrays.asList("Some more lore")); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Lore vs Other" - } - ), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.setDisplayName("TestItemName"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Name vs Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.setDisplayName("AnotherItemName"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Name vs Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.setDisplayName("The original ItemName"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.setDisplayName("The other name"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Name vs Other" - } - ), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - cleanStack.addUnsafeEnchantment(Enchantment.DIG_SPEED, 2); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "EnchantStack vs Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - cleanStack.addUnsafeEnchantment(Enchantment.OXYGEN, 1); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "EnchantStack vs Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - cleanStack.addUnsafeEnchantment(Enchantment.ARROW_DAMAGE, 1); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - cleanStack.addUnsafeEnchantment(Enchantment.ARROW_FIRE, 1); - return cleanStack; - } - }, - "EnchantStack vs OtherEnchantStack" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.addEnchant(Enchantment.DURABILITY, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Enchant vs Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.addEnchant(Enchantment.KNOCKBACK, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Enchant vs Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.addEnchant(Enchantment.PROTECTION_FIRE, 1, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - meta.addEnchant(Enchantment.PROTECTION_FIRE, 2, true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Enchant vs Other" - } - ), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - ((Repairable) meta).setRepairCost(42); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Repair vs Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - ((Repairable) meta).setRepairCost(36); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Repair vs Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - ((Repairable) meta).setRepairCost(89); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - ItemMeta meta = cleanStack.getItemMeta(); - ((Repairable) meta).setRepairCost(88); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Repair vs Other" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackMapTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackMapTest.java deleted file mode 100644 index c13f6d579..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackMapTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.MapMeta; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackMapTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.FILLED_MAP); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - Long.parseLong("10", 2), - ItemStackLoreEnchantmentTest.operators(), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - meta.setScaling(true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - meta.setScaling(false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Scale vs. Unscale" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - meta.setScaling(true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Scale vs. Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - meta.setScaling(false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Unscale vs. Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - meta.setScaling(true); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Scale vs. None" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - MapMeta meta = (MapMeta) cleanStack.getItemMeta(); - meta.setScaling(false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Unscale vs. None" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackPotionsTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackPotionsTest.java deleted file mode 100644 index c1f9fb745..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackPotionsTest.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionEffectType; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackPotionsTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.POTION); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - Long.parseLong("10", 2), - ItemStackLoreEnchantmentTest.operators(), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.CONFUSION.createEffect(1, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Potion vs Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.HARM.createEffect(2, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Potion vs Blank" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.SLOW_DIGGING.createEffect(1, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.FAST_DIGGING.createEffect(1, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Potion vs Harder" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.JUMP.createEffect(1, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.JUMP.createEffect(1, 1), false); - meta.addCustomEffect(PotionEffectType.REGENERATION.createEffect(1, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Potion vs Better" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.SPEED.createEffect(10, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.SPEED.createEffect(5, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Potion vs Faster" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.INCREASE_DAMAGE.createEffect(1, 1), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - final PotionMeta meta = (PotionMeta) cleanStack.getItemMeta(); - meta.addCustomEffect(PotionEffectType.INCREASE_DAMAGE.createEffect(1, 2), false); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Potion vs Stronger" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackSkullTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackSkullTest.java deleted file mode 100644 index 1561bf885..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackSkullTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import java.util.Arrays; -import java.util.List; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.SkullMeta; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import com.google.common.base.Joiner; - -@RunWith(Parameterized.class) -public class ItemStackSkullTest extends ItemStackTest { - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.PLAYER_HEAD); - } - - @SuppressWarnings("unchecked") - static List operators() { - return CompoundOperator.compound( - Joiner.on('+'), - NAME_PARAMETER, - Long.parseLong("10", 2), - ItemStackLoreEnchantmentTest.operators(), - Arrays.asList( - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - SkullMeta meta = (SkullMeta) cleanStack.getItemMeta(); - meta.setOwner("Notch"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - SkullMeta meta = (SkullMeta) cleanStack.getItemMeta(); - meta.setOwner("Dinnerbone"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Name 1 vs. Name 2" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - SkullMeta meta = (SkullMeta) cleanStack.getItemMeta(); - meta.setOwner("Notch"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - SkullMeta meta = (SkullMeta) cleanStack.getItemMeta(); - meta.setOwner(null); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - "Name vs. Null" - }, - new Object[] { - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - SkullMeta meta = (SkullMeta) cleanStack.getItemMeta(); - meta.setOwner("Notch"); - cleanStack.setItemMeta(meta); - return cleanStack; - } - }, - new Operator() { - public ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - }, - "Name vs. None" - } - ) - ); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackTest.java deleted file mode 100644 index 6140edeec..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/ItemStackTest.java +++ /dev/null @@ -1,493 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.bukkit.support.Matchers.sameHash; -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.bukkit.Material; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.inventory.ItemFactory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.support.AbstractTestingBase; -import org.bukkit.util.io.BukkitObjectInputStream; -import org.bukkit.util.io.BukkitObjectOutputStream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; - -import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableList; - -@RunWith(Parameterized.class) -public class ItemStackTest extends AbstractTestingBase { - static abstract class StackProvider { - final Material material; - - StackProvider(Material material) { - this.material = material; - } - - ItemStack bukkit() { - return operate(cleanStack(material, false)); - } - - ItemStack craft() { - return operate(cleanStack(material, true)); - } - - abstract ItemStack operate(ItemStack cleanStack); - - static ItemStack cleanStack(Material material, boolean craft) { - final ItemStack stack = new ItemStack(material); - return craft ? CraftItemStack.asCraftCopy(stack) : stack; - } - - @Override - public String toString() { - return material.toString(); - } - - /** - * For each item in parameterList, it will apply nameFormat at nameIndex. - * For each item in parameterList for each item in materials, it will create a stack provider at each array index that contains an Operator. - * - * @param parameterList - * @param nameFormat - * @param nameIndex - * @param materials - * @return - */ - static List compound(final List parameterList, final String nameFormat, final int nameIndex, final Material...materials) { - final List out = new ArrayList(); - for (Object[] params : parameterList) { - final int len = params.length; - for (final Material material : materials) { - final Object[] paramsOut = params.clone(); - for (int i = 0; i < len; i++) { - final Object param = paramsOut[i]; - if (param instanceof Operator) { - final Operator operator = (Operator) param; - paramsOut[i] = new StackProvider(material) { - @Override - ItemStack operate(ItemStack cleanStack) { - return operator.operate(cleanStack); - } - }; - } - } - paramsOut[nameIndex] = String.format(nameFormat, paramsOut[nameIndex], material); - out.add(paramsOut); - } - } - return out; - } - } - - interface Operator { - ItemStack operate(ItemStack cleanStack); - } - - static class CompoundOperator implements Operator { - static class RecursiveContainer { - final Joiner joiner; - final Object[] strings; - final int nameParameter; - final List stack; - final List out; - final List[] lists; - - RecursiveContainer(Joiner joiner, Object[] strings, int nameParameter, List stack, List out, List[] lists) { - this.joiner = joiner; - this.strings = strings; - this.nameParameter = nameParameter; - this.stack = stack; - this.out = out; - this.lists = lists; - } - } - final Operator[] operators; - - CompoundOperator(Operator...operators) { - this.operators = operators; - } - - public ItemStack operate(ItemStack cleanStack) { - for (Operator operator : operators) { - operator.operate(cleanStack); - } - return cleanStack; - } - - @Override - public String toString() { - return Arrays.toString(operators); - } - - - /** - * This combines different tests into one large collection, combining no two tests from the same list. - * @param joiner used to join names - * @param nameParameter index of the name parameter - * @param singletonBitmask a list of bits representing the 'singletons' located in your originalLists. Lowest order bits represent the first items in originalLists. - * Singletons are exponentially linked with each other, such that, - * the output will contain every unique subset of only items from the singletons, - * as well as every unique subset that contains at least one item from each non-singleton. - * @param originalLists - * @return - */ - static List compound(final Joiner joiner, final int nameParameter, final long singletonBitmask, final List...originalLists) { - - final List out = new ArrayList(); - final List> singletons = new ArrayList>(); - final List> notSingletons = new ArrayList>(); - - { // Separate and prime the 'singletons' - int i = 0; - for (List list : originalLists) { - (((singletonBitmask >>> i++) & 0x1) == 0x1 ? singletons : notSingletons).add(list); - } - } - - for (final List primarySingleton : singletons) { - // Iterate over our singletons, to multiply the 'out' each time - for (final Object[] entry : out.toArray(EMPTY_ARRAY)) { - // Iterate over a snapshot of 'out' to prevent CMEs / infinite iteration - final int len = entry.length; - for (final Object[] singleton : primarySingleton) { - // Iterate over each item in our singleton for the current 'out' entry - final Object[] toOut = entry.clone(); - for (int i = 0; i < len; i++) { - // Iterate over each parameter - if (i == nameParameter) { - toOut[i] = joiner.join(toOut[i], singleton[i]); - } else if (toOut[i] instanceof Operator) { - final Operator op1 = (Operator) toOut[i]; - final Operator op2 = (Operator) singleton[i]; - toOut[i] = new Operator() { - public ItemStack operate(final ItemStack cleanStack) { - return op2.operate(op1.operate(cleanStack)); - } - }; - } - } - out.add(toOut); - } - } - out.addAll(primarySingleton); - } - - @SuppressWarnings("unchecked") - final List[] lists = new List[notSingletons.size() + 1]; - notSingletons.toArray(lists); - lists[lists.length - 1] = out; - - final RecursiveContainer methodParams = new RecursiveContainer(joiner, new Object[lists.length], nameParameter, new ArrayList(lists.length), new ArrayList(), lists); - - recursivelyCompound(methodParams, 0); - methodParams.out.addAll(out); - - return methodParams.out; - } - - private static void recursivelyCompound(final RecursiveContainer methodParams, final int level) { - final List stack = methodParams.stack; - - if (level == methodParams.lists.length) { - final Object[] firstParams = stack.get(0); - final int len = firstParams.length; - final int stackSize = stack.size(); - final Object[] params = new Object[len]; - - for (int i = 0; i < len; i++) { - final Object firstParam = firstParams[i]; - - if (firstParam instanceof Operator) { - final Operator[] operators = new Operator[stackSize]; - for (int j = 0; j < stackSize; j++) { - operators[j] = (Operator) stack.get(j)[i]; - } - - params[i] = new CompoundOperator(operators); - } else if (i == methodParams.nameParameter) { - final Object[] strings = methodParams.strings; - for (int j = 0; j < stackSize; j++) { - strings[j] = stack.get(j)[i]; - } - - params[i] = methodParams.joiner.join(strings); - } else { - params[i] = firstParam; - } - } - - methodParams.out.add(params); - } else { - final int marker = stack.size(); - - for (final Object[] params : methodParams.lists[level]) { - stack.add(params); - recursivelyCompound(methodParams, level + 1); - stack.remove(marker); - } - } - } - } - - interface StackWrapper { - ItemStack stack(); - } - - static class CraftWrapper implements StackWrapper { - final StackProvider provider; - - CraftWrapper(StackProvider provider) { - this.provider = provider; - } - - public ItemStack stack() { - return provider.craft(); - } - - @Override - public String toString() { - return "Craft " + provider; - } - } - - static class BukkitWrapper implements StackWrapper { - final StackProvider provider; - - BukkitWrapper(StackProvider provider) { - this.provider = provider; - } - - public ItemStack stack() { - return provider.bukkit(); - } - - @Override - public String toString() { - return "Bukkit " + provider; - } - } - - static class NoOpProvider extends StackProvider { - - NoOpProvider(Material material) { - super(material); - } - - @Override - ItemStack operate(ItemStack cleanStack) { - return cleanStack; - } - - @Override - public String toString() { - return "NoOp " + super.toString(); - } - } - - @Parameters(name="[{index}]:{" + NAME_PARAMETER + "}") - public static List data() { - return ImmutableList.of(); // TODO, test basic durability issues - } - - static final Object[][] EMPTY_ARRAY = new Object[0][]; - /** - * Materials that generate unique item meta types. - */ - static final Material[] COMPOUND_MATERIALS; - static final int NAME_PARAMETER = 2; - static { - final ItemFactory factory = CraftItemFactory.instance(); - final Map, Material> possibleMaterials = new HashMap, Material>(); - ItemMeta meta; - for (final Material material : Material.values()) { - meta = factory.getItemMeta(material); - if (meta == null || possibleMaterials.containsKey(meta.getClass())) - continue; - possibleMaterials.put(meta.getClass(), material); - - } - COMPOUND_MATERIALS = possibleMaterials.values().toArray(new Material[possibleMaterials.size()]); - } - - @Parameter(0) public StackProvider provider; - @Parameter(1) public StackProvider unequalProvider; - @Parameter(NAME_PARAMETER) public String name; - - @Test - public void testBukkitInequality() { - final StackWrapper bukkitWrapper = new CraftWrapper(provider); - testInequality(bukkitWrapper, new BukkitWrapper(unequalProvider)); - testInequality(bukkitWrapper, new BukkitWrapper(new NoOpProvider(provider.material))); - } - - @Test - public void testCraftInequality() { - final StackWrapper craftWrapper = new CraftWrapper(provider); - testInequality(craftWrapper, new CraftWrapper(unequalProvider)); - testInequality(craftWrapper, new CraftWrapper(new NoOpProvider(provider.material))); - } - - @Test - public void testMixedInequality() { - final StackWrapper craftWrapper = new CraftWrapper(provider); - testInequality(craftWrapper, new BukkitWrapper(unequalProvider)); - testInequality(craftWrapper, new BukkitWrapper(new NoOpProvider(provider.material))); - - final StackWrapper bukkitWrapper = new CraftWrapper(provider); - testInequality(bukkitWrapper, new CraftWrapper(unequalProvider)); - testInequality(bukkitWrapper, new CraftWrapper(new NoOpProvider(provider.material))); - } - - static void testInequality(StackWrapper provider, StackWrapper unequalProvider) { - final ItemStack stack = provider.stack(); - final ItemStack stack2 = provider.stack(); - assertThat(stack, allOf(equalTo(stack), sameHash(stack))); - assertThat(stack, is(not(sameInstance(stack2)))); - assertThat(stack, allOf(equalTo(stack2), sameHash(stack2))); - - final ItemStack unequalStack = unequalProvider.stack(); - final ItemStack unequalStack2 = unequalProvider.stack(); - assertThat(unequalStack, allOf(equalTo(unequalStack), sameHash(unequalStack))); - assertThat(unequalStack, is(not(sameInstance(unequalStack2)))); - assertThat(unequalStack, allOf(equalTo(unequalStack2), sameHash(unequalStack2))); - - assertThat(stack, is(not(unequalStack))); - assertThat(unequalStack, is(not(stack))); - - final ItemStack newStack = new ItemStack(stack2); - assertThat(newStack, allOf(equalTo(stack), sameHash(stack))); - assertThat(newStack, is(not(unequalStack))); - assertThat(newStack.getItemMeta(), allOf(equalTo(stack.getItemMeta()), sameHash(stack.getItemMeta()))); - assertThat(newStack.getItemMeta(), is(not(unequalStack.getItemMeta()))); - - final ItemStack craftStack = CraftItemStack.asCraftCopy(stack2); - assertThat(craftStack, allOf(equalTo(stack), sameHash(stack))); - assertThat(craftStack, is(not(unequalStack))); - assertThat(craftStack.getItemMeta(), allOf(equalTo(stack.getItemMeta()), sameHash(stack.getItemMeta()))); - assertThat(craftStack.getItemMeta(), is(not(unequalStack.getItemMeta()))); - - final ItemStack newUnequalStack = new ItemStack(unequalStack2); - assertThat(newUnequalStack, allOf(equalTo(unequalStack), sameHash(unequalStack))); - assertThat(newUnequalStack, is(not(stack))); - assertThat(newUnequalStack.getItemMeta(), allOf(equalTo(unequalStack.getItemMeta()), sameHash(unequalStack.getItemMeta()))); - assertThat(newUnequalStack.getItemMeta(), is(not(stack.getItemMeta()))); - - final ItemStack newUnequalCraftStack = CraftItemStack.asCraftCopy(unequalStack2); - assertThat(newUnequalCraftStack, allOf(equalTo(unequalStack), sameHash(unequalStack))); - assertThat(newUnequalCraftStack, is(not(stack))); - assertThat(newUnequalCraftStack.getItemMeta(), allOf(equalTo(unequalStack.getItemMeta()), sameHash(unequalStack.getItemMeta()))); - assertThat(newUnequalCraftStack.getItemMeta(), is(not(stack.getItemMeta()))); - } - - @Test - public void testBukkitYamlDeserialize() throws Throwable { - testYamlDeserialize(new BukkitWrapper(provider), new BukkitWrapper(unequalProvider)); - } - - @Test - public void testCraftYamlDeserialize() throws Throwable { - testYamlDeserialize(new CraftWrapper(provider), new CraftWrapper(unequalProvider)); - } - - @Test - public void testBukkitStreamDeserialize() throws Throwable { - testStreamDeserialize(new BukkitWrapper(provider), new BukkitWrapper(unequalProvider)); - } - - @Test - public void testCraftStreamDeserialize() throws Throwable { - testStreamDeserialize(new CraftWrapper(provider), new CraftWrapper(unequalProvider)); - } - - static void testStreamDeserialize(StackWrapper provider, StackWrapper unequalProvider) throws Throwable { - final ItemStack stack = provider.stack(); - final ItemStack unequalStack = unequalProvider.stack(); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream oos = null; - try { - oos = new BukkitObjectOutputStream(out); - - oos.writeObject(stack); - oos.writeObject(unequalStack); - } finally { - if (oos != null) { - try { - oos.close(); - } catch (IOException ex) { - } - } - } - - final String data = new String(Base64Coder.encode(out.toByteArray())); - - ObjectInputStream ois = null; - - final ItemStack readFirst; - final ItemStack readSecond; - - try { - ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); - ois = new BukkitObjectInputStream(in); - - readFirst = (ItemStack) ois.readObject(); - readSecond = (ItemStack) ois.readObject(); - } finally { - if (ois != null) { - try { - ois.close(); - } catch (IOException ex) { - } - } - } - - testEqualities(data, readFirst, readSecond, stack, unequalStack); - } - - static void testYamlDeserialize(StackWrapper provider, StackWrapper unequalProvider) { - final ItemStack stack = provider.stack(); - final ItemStack unequalStack = unequalProvider.stack(); - final YamlConfiguration configOut = new YamlConfiguration(); - - configOut.set("provider", stack); - configOut.set("unequal", unequalStack); - - final String out = '\n' + configOut.saveToString(); - final YamlConfiguration configIn = new YamlConfiguration(); - - try { - configIn.loadFromString(out); - } catch (InvalidConfigurationException ex) { - throw new RuntimeException(out, ex); - } - - testEqualities(out, configIn.getItemStack("provider"), configIn.getItemStack("unequal"), stack, unequalStack); - } - - static void testEqualities(String information, ItemStack primaryRead, ItemStack unequalRead, ItemStack primaryOriginal, ItemStack unequalOriginal) { - assertThat(information, primaryRead, allOf(equalTo(primaryOriginal), sameHash(primaryOriginal))); - assertThat(information, unequalRead, allOf(equalTo(unequalOriginal), sameHash(unequalOriginal))); - assertThat(information, primaryRead, is(not(unequalOriginal))); - assertThat(information, primaryRead, is(not(unequalRead))); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/NMSCraftItemStackTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/NMSCraftItemStackTest.java deleted file mode 100644 index 5a43fd867..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/NMSCraftItemStackTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -import net.minecraft.server.Enchantments; - -import org.bukkit.inventory.ItemStack; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; - -public class NMSCraftItemStackTest extends AbstractTestingBase { - - @Test - public void testCloneEnchantedItem() throws Exception { - net.minecraft.server.ItemStack nmsItemStack = new net.minecraft.server.ItemStack(net.minecraft.server.Items.POTION); - nmsItemStack.addEnchantment(Enchantments.DAMAGE_ALL, 1); - ItemStack itemStack = CraftItemStack.asCraftMirror(nmsItemStack); - ItemStack clone = itemStack.clone(); - assertThat(clone.getType(), is(itemStack.getType())); - assertThat(clone.getAmount(), is(itemStack.getAmount())); - assertThat(clone.getDurability(), is(itemStack.getDurability())); - assertThat(clone.getEnchantments(), is(itemStack.getEnchantments())); - assertThat(clone.getData(), is(itemStack.getData())); - assertThat(clone, is(itemStack)); - } - - @Test - public void testCloneNullItem() throws Exception { - net.minecraft.server.ItemStack nmsItemStack = null; - ItemStack itemStack = CraftItemStack.asCraftMirror(nmsItemStack); - ItemStack clone = itemStack.clone(); - assertThat(clone, is(itemStack)); - } -} diff --git a/src/test/java/org/bukkit/craftbukkit/inventory/PlayerInventoryTest.java b/src/test/java/org/bukkit/craftbukkit/inventory/PlayerInventoryTest.java deleted file mode 100644 index fc0da1a9b..000000000 --- a/src/test/java/org/bukkit/craftbukkit/inventory/PlayerInventoryTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bukkit.craftbukkit.inventory; - -import net.minecraft.server.ItemStack; -import net.minecraft.server.Items; -import net.minecraft.server.PlayerInventory; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; -import static org.junit.Assert.*; - -public class PlayerInventoryTest extends AbstractTestingBase { - - @Test - public void testCanHold() throws Exception { - ItemStack itemStackApple = new ItemStack(Items.APPLE); - ItemStack itemStack1Coal = new ItemStack(Items.COAL); - ItemStack itemStack32Coal = new ItemStack(Items.COAL, 32); - ItemStack itemStack63Coal = new ItemStack(Items.COAL, 63); - ItemStack itemStack64Coal = new ItemStack(Items.COAL, 64); - - // keep one slot empty - PlayerInventory inventory = new PlayerInventory(null); - for (int i = 0; i < inventory.items.size() - 1; i++) { - inventory.setItem(i, itemStackApple); - } - - // one slot empty - assertEquals(1, inventory.canHold(itemStack1Coal)); - assertEquals(32, inventory.canHold(itemStack32Coal)); - assertEquals(64, inventory.canHold(itemStack64Coal)); - - // no free space with a stack of the item to check in the inventory - inventory.setItem(inventory.items.size() - 1, itemStack64Coal); - - assertEquals(0, inventory.canHold(itemStack1Coal)); - assertEquals(0, inventory.canHold(itemStack32Coal)); - assertEquals(0, inventory.canHold(itemStack64Coal)); - - // no free space without a stack of the item to check in the inventory - inventory.setItem(inventory.items.size() - 1, itemStackApple); - - assertEquals(0, inventory.canHold(itemStack1Coal)); - assertEquals(0, inventory.canHold(itemStack32Coal)); - assertEquals(0, inventory.canHold(itemStack64Coal)); - - // free space for 32 items in one slot - inventory.setItem(inventory.items.size() - 1, itemStack32Coal); - - assertEquals(1, inventory.canHold(itemStack1Coal)); - assertEquals(32, inventory.canHold(itemStack32Coal)); - assertEquals(32, inventory.canHold(itemStack64Coal)); - - // free space for 1 item in two slots - inventory.setItem(inventory.items.size() - 1, itemStack63Coal); - inventory.setItem(inventory.items.size() - 2, itemStack63Coal); - - assertEquals(1, inventory.canHold(itemStack1Coal)); - assertEquals(2, inventory.canHold(itemStack32Coal)); - assertEquals(2, inventory.canHold(itemStack64Coal)); - } -} diff --git a/src/test/java/org/bukkit/entity/EnderDragonPhaseTest.java b/src/test/java/org/bukkit/entity/EnderDragonPhaseTest.java deleted file mode 100644 index 7e8d5a0e5..000000000 --- a/src/test/java/org/bukkit/entity/EnderDragonPhaseTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bukkit.entity; - -import net.minecraft.server.DragonControllerPhase; -import org.bukkit.craftbukkit.entity.CraftEnderDragon; -import org.junit.Assert; -import org.junit.Test; - -import static junit.framework.TestCase.assertNotNull; - -public class EnderDragonPhaseTest { - - @Test - public void testNotNull() { - for (EnderDragon.Phase phase : EnderDragon.Phase.values()) { - DragonControllerPhase dragonControllerPhase = CraftEnderDragon.getMinecraftPhase(phase); - assertNotNull(phase.name(), dragonControllerPhase); - assertNotNull(phase.name(), CraftEnderDragon.getBukkitPhase(dragonControllerPhase)); - } - } - - @Test - public void testBukkitToMinecraft() { - Assert.assertEquals("CIRCLING", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.CIRCLING), DragonControllerPhase.HOLDING_PATTERN); - Assert.assertEquals("STRAFING", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.STRAFING), DragonControllerPhase.STRAFE_PLAYER); - Assert.assertEquals("FLY_TO_PORTAL", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.FLY_TO_PORTAL), DragonControllerPhase.LANDING_APPROACH); - Assert.assertEquals("LAND_ON_PORTAL", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.LAND_ON_PORTAL), DragonControllerPhase.LANDING); - Assert.assertEquals("LEAVE_PORTAL", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.LEAVE_PORTAL), DragonControllerPhase.TAKEOFF); - Assert.assertEquals("BREATH_ATTACK", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.BREATH_ATTACK), DragonControllerPhase.SITTING_FLAMING); - Assert.assertEquals("SEARCH_FOR_BREATH_ATTACK_TARGET", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET), DragonControllerPhase.SITTING_SCANNING); - Assert.assertEquals("ROAR_BEFORE_ATTACK", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.ROAR_BEFORE_ATTACK), DragonControllerPhase.SITTING_ATTACKING); - Assert.assertEquals("CHARGE_PLAYER", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.CHARGE_PLAYER), DragonControllerPhase.CHARGING_PLAYER); - Assert.assertEquals("DYING", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.DYING), DragonControllerPhase.DYING); - Assert.assertEquals("HOVER", CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.HOVER), DragonControllerPhase.HOVER); - } - - @Test - public void testMinecraftToBukkit() { - Assert.assertEquals("CIRCLING", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.HOLDING_PATTERN), EnderDragon.Phase.CIRCLING); - Assert.assertEquals("STRAFING", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.STRAFE_PLAYER), EnderDragon.Phase.STRAFING); - Assert.assertEquals("FLY_TO_PORTAL", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.LANDING_APPROACH), EnderDragon.Phase.FLY_TO_PORTAL); - Assert.assertEquals("LAND_ON_PORTAL", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.LANDING), EnderDragon.Phase.LAND_ON_PORTAL); - Assert.assertEquals("LEAVE_PORTAL", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.TAKEOFF), EnderDragon.Phase.LEAVE_PORTAL); - Assert.assertEquals("BREATH_ATTACK", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.SITTING_FLAMING), EnderDragon.Phase.BREATH_ATTACK); - Assert.assertEquals("SEARCH_FOR_BREATH_ATTACK_TARGET", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.SITTING_SCANNING), EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET); - Assert.assertEquals("ROAR_BEFORE_ATTACK", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.SITTING_ATTACKING), EnderDragon.Phase.ROAR_BEFORE_ATTACK); - Assert.assertEquals("CHARGE_PLAYER", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.CHARGING_PLAYER), EnderDragon.Phase.CHARGE_PLAYER); - Assert.assertEquals("DYING", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.DYING), EnderDragon.Phase.DYING); - Assert.assertEquals("HOVER", CraftEnderDragon.getBukkitPhase(DragonControllerPhase.HOVER), EnderDragon.Phase.HOVER); - } -} diff --git a/src/test/java/org/bukkit/entity/EntityTypesTest.java b/src/test/java/org/bukkit/entity/EntityTypesTest.java deleted file mode 100644 index 465bc9735..000000000 --- a/src/test/java/org/bukkit/entity/EntityTypesTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit.entity; - -import java.util.Arrays; -import java.util.Set; -import java.util.stream.Collectors; -import net.minecraft.server.EntityTypes; -import net.minecraft.server.IRegistry; -import net.minecraft.server.MinecraftKey; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Assert; -import org.junit.Test; - -public class EntityTypesTest extends AbstractTestingBase { - - @Test - public void testMaps() { - Set allBukkit = Arrays.stream(EntityType.values()).filter((b) -> b.getName() != null).collect(Collectors.toSet()); - - for (Object o : IRegistry.ENTITY_TYPE) { - EntityTypes nms = (EntityTypes) o; // Eclipse fail - MinecraftKey key = EntityTypes.getName(nms); - - EntityType bukkit = EntityType.fromName(key.getKey()); - Assert.assertNotNull("Missing nms->bukkit " + key, bukkit); - - Assert.assertTrue("Duplicate entity nms->" + bukkit, allBukkit.remove(bukkit)); - } - - Assert.assertTrue("Unmapped bukkit entities " + allBukkit, allBukkit.isEmpty()); - } -} diff --git a/src/test/java/org/bukkit/entity/TropicalFishTest.java b/src/test/java/org/bukkit/entity/TropicalFishTest.java deleted file mode 100644 index b65dc340a..000000000 --- a/src/test/java/org/bukkit/entity/TropicalFishTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.bukkit.entity; - -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; -import org.bukkit.DyeColor; -import org.bukkit.craftbukkit.entity.CraftTropicalFish; -import org.bukkit.entity.TropicalFish.Pattern; - -import org.junit.Test; - -public class TropicalFishTest { - - @Test - public void testVariants() { - testVariant(65536, DyeColor.ORANGE, DyeColor.WHITE, Pattern.KOB); - testVariant(917504, DyeColor.RED, DyeColor.WHITE, Pattern.KOB); - testVariant(918273, DyeColor.RED, DyeColor.WHITE, Pattern.BLOCKFISH); - testVariant(918529, DyeColor.RED, DyeColor.WHITE, Pattern.BETTY); - testVariant(16778497, DyeColor.WHITE, DyeColor.ORANGE, Pattern.CLAYFISH); - testVariant(50660352, DyeColor.LIME, DyeColor.LIGHT_BLUE, Pattern.BRINELY); - testVariant(50726144, DyeColor.PINK, DyeColor.LIGHT_BLUE, Pattern.SPOTTY); - testVariant(50790656, DyeColor.GRAY, DyeColor.LIGHT_BLUE, Pattern.SUNSTREAK); - testVariant(67108865, DyeColor.WHITE, DyeColor.YELLOW, Pattern.FLOPPER); - testVariant(67110144, DyeColor.WHITE, DyeColor.YELLOW, Pattern.SPOTTY); - testVariant(67371265, DyeColor.YELLOW, DyeColor.YELLOW, Pattern.STRIPEY); - testVariant(67764993, DyeColor.PURPLE, DyeColor.YELLOW, Pattern.BLOCKFISH); - testVariant(101253888, DyeColor.CYAN, DyeColor.PINK, Pattern.DASHER); - testVariant(117441025, DyeColor.WHITE, DyeColor.GRAY, Pattern.GLITTER); - testVariant(117441280, DyeColor.WHITE, DyeColor.GRAY, Pattern.DASHER); - testVariant(117441536, DyeColor.WHITE, DyeColor.GRAY, Pattern.BRINELY); - testVariant(117506305, DyeColor.ORANGE, DyeColor.GRAY, Pattern.STRIPEY); - testVariant(117899265, DyeColor.GRAY, DyeColor.GRAY, Pattern.FLOPPER); - testVariant(118161664, DyeColor.BLUE, DyeColor.GRAY, Pattern.SUNSTREAK); - testVariant(134217984, DyeColor.WHITE, DyeColor.LIGHT_GRAY, Pattern.SUNSTREAK); - testVariant(234882305, DyeColor.WHITE, DyeColor.RED, Pattern.CLAYFISH); - testVariant(235340288, DyeColor.GRAY, DyeColor.RED, Pattern.SNOOPER); - } - - private void testVariant(int variant, DyeColor bodyColor, DyeColor patternColor, Pattern pattern) { - assertThat("variant write", CraftTropicalFish.getData(patternColor, bodyColor, pattern), is(variant)); - assertThat("pattern colour read", CraftTropicalFish.getPatternColor(variant), is(patternColor)); - assertThat("body colour read", CraftTropicalFish.getBodyColor(variant), is(bodyColor)); - assertThat("pattern read", CraftTropicalFish.getPattern(variant), is(pattern)); - } -} diff --git a/src/test/java/org/bukkit/map/MapTest.java b/src/test/java/org/bukkit/map/MapTest.java deleted file mode 100644 index 2dde26d3f..000000000 --- a/src/test/java/org/bukkit/map/MapTest.java +++ /dev/null @@ -1,62 +0,0 @@ - -package org.bukkit.map; - -import java.awt.Color; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.minecraft.server.MaterialMapColor; -import org.junit.Assert; -import org.junit.Test; - -public class MapTest { - - private static final Logger logger = Logger.getLogger("MapTest"); - - private static final int[] modifiers = {180, 220, 255, 135}; - - @Test - public void testColors() { - MaterialMapColor[] nmsColors = MaterialMapColor.a; - Color[] bukkitColors = MapPalette.colors; - - boolean fail = false; - for (int i = 0; i < nmsColors.length; i++) { - if (nmsColors[i] == null) { - break; - } - int rgb = nmsColors[i].rgb; - - int r = (rgb >> 16) & 0xFF; - int g = (rgb >> 8) & 0xFF; - int b = rgb & 0xFF; - - if (i + 1 > bukkitColors.length / 4) { - for (int modi : modifiers) { - int mr = (r * modi) / 255; - int mg = (g * modi) / 255; - int mb = (b * modi) / 255; - logger.log(Level.WARNING, "Missing color: c({0}, {1}, {2})", new Object[]{mr, mg, mb}); - } - fail = true; - } else { - for (int j = 0; j < modifiers.length; j++) { - int modi = modifiers[j]; - Color bukkit = bukkitColors[i * 4 + j]; - int mr = (r * modi) / 255; - int mg = (g * modi) / 255; - int mb = (b * modi) / 255; - - if (bukkit.getRed() != mr || bukkit.getGreen() != mg || bukkit.getBlue() != mb) { - logger.log(Level.WARNING, "Incorrect color: {6} {7} c({0}, {1}, {2}) != c({3}, {4}, {5})", new Object[]{ - bukkit.getRed(), bukkit.getGreen(), bukkit.getBlue(), - mr, mg, mb, - i, j - }); - fail = true; - } - } - } - } - Assert.assertFalse(fail); - } -} diff --git a/src/test/java/org/bukkit/potion/PotionTest.java b/src/test/java/org/bukkit/potion/PotionTest.java deleted file mode 100644 index f6c23ebba..000000000 --- a/src/test/java/org/bukkit/potion/PotionTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bukkit.potion; - -import static org.junit.Assert.*; - -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import net.minecraft.server.IRegistry; - -import net.minecraft.server.MobEffect; -import net.minecraft.server.MobEffectList; -import net.minecraft.server.PotionRegistry; -import org.bukkit.support.AbstractTestingBase; -import org.junit.Test; - -public class PotionTest extends AbstractTestingBase { - @Test - public void testEffectCompleteness() throws Throwable { - Map effects = new EnumMap(PotionType.class); - for (Object reg : IRegistry.POTION) { - List eff = ((PotionRegistry)reg).a(); - if (eff.size() != 1) continue; - int id = MobEffectList.getId(eff.get(0).getMobEffect()); - PotionEffectType type = PotionEffectType.getById(id); - assertNotNull(String.valueOf(id), PotionEffectType.getById(id)); - - PotionType enumType = PotionType.getByEffect(type); - assertNotNull(type.getName(), enumType); - - effects.put(enumType, enumType.name()); - } - - assertEquals(effects.entrySet().size(), PotionType.values().length - /* PotionTypes with no/shared Effects */ 6); - } -} diff --git a/src/test/java/org/bukkit/support/AbstractTestingBase.java b/src/test/java/org/bukkit/support/AbstractTestingBase.java deleted file mode 100644 index 53cbb525e..000000000 --- a/src/test/java/org/bukkit/support/AbstractTestingBase.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bukkit.support; - -import com.google.common.collect.ImmutableList; -import java.util.Collections; -import java.util.List; -import net.minecraft.server.DispenserRegistry; -import net.minecraft.server.EnumResourcePackType; -import net.minecraft.server.LootTableRegistry; -import net.minecraft.server.ResourceManager; -import net.minecraft.server.ResourcePackVanilla; -import net.minecraft.server.TagRegistry; -import org.bukkit.Material; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.junit.Assert; - -/** - * If you are getting: java.lang.ExceptionInInitializerError - * at net.minecraft.server.StatisticList.(SourceFile:58) - * at net.minecraft.server.Item.(SourceFile:252) - * at net.minecraft.server.Block.(Block.java:577) - * - * extend this class to solve it. - */ -public abstract class AbstractTestingBase { - // Materials that only exist in block form (or are legacy) - public static final List INVALIDATED_MATERIALS; - - public static final LootTableRegistry LOOT_TABLE_REGISTRY; - public static final TagRegistry TAG_REGISTRY; - - static { - DispenserRegistry.c(); - // Set up resource manager - ResourceManager resourceManager = new ResourceManager(EnumResourcePackType.SERVER_DATA); - // add tags and loot tables for unit tests - resourceManager.a(TAG_REGISTRY = new TagRegistry()); - resourceManager.a(LOOT_TABLE_REGISTRY = new LootTableRegistry()); - // Register vanilla pack - resourceManager.a(Collections.singletonList(new ResourcePackVanilla("minecraft"))); - - DummyServer.setup(); - DummyEnchantments.setup(); - - ImmutableList.Builder builder = ImmutableList.builder(); - for (Material m : Material.values()) { - if (m.isLegacy() || CraftMagicNumbers.getItem(m) == null) { - builder.add(m); - } - } - INVALIDATED_MATERIALS = builder.build(); - Assert.assertEquals("Expected 543 invalidated materials (got " + INVALIDATED_MATERIALS.size() + ")", 543, INVALIDATED_MATERIALS.size()); - } -} diff --git a/src/test/java/org/bukkit/support/DummyEnchantments.java b/src/test/java/org/bukkit/support/DummyEnchantments.java deleted file mode 100644 index f3cc27e71..000000000 --- a/src/test/java/org/bukkit/support/DummyEnchantments.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bukkit.support; - -import net.minecraft.server.Enchantments; - -public class DummyEnchantments { - static { - Enchantments.DAMAGE_ALL.getClass(); - org.bukkit.enchantments.Enchantment.stopAcceptingRegistrations(); - } - - public static void setup() {} -} diff --git a/src/test/java/org/bukkit/support/DummyServer.java b/src/test/java/org/bukkit/support/DummyServer.java deleted file mode 100644 index 3c489b6cc..000000000 --- a/src/test/java/org/bukkit/support/DummyServer.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.bukkit.support; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.HashMap; -import java.util.logging.Logger; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.Server; -import org.bukkit.craftbukkit.CraftLootTable; -import org.bukkit.craftbukkit.block.data.CraftBlockData; -import org.bukkit.craftbukkit.inventory.CraftItemFactory; -import org.bukkit.craftbukkit.util.CraftMagicNumbers; -import org.bukkit.craftbukkit.util.CraftNamespacedKey; -import org.bukkit.craftbukkit.util.Versioning; - -public class DummyServer implements InvocationHandler { - private static interface MethodHandler { - Object handle(DummyServer server, Object[] args); - } - private static final HashMap methods = new HashMap(); - static { - try { - methods.put( - Server.class.getMethod("getItemFactory"), - new MethodHandler() { - public Object handle(DummyServer server, Object[] args) { - return CraftItemFactory.instance(); - } - } - ); - methods.put( - Server.class.getMethod("getName"), - new MethodHandler() { - public Object handle(DummyServer server, Object[] args) { - return DummyServer.class.getName(); - } - } - ); - methods.put( - Server.class.getMethod("getVersion"), - new MethodHandler() { - public Object handle(DummyServer server, Object[] args) { - return DummyServer.class.getPackage().getImplementationVersion(); - } - } - ); - methods.put( - Server.class.getMethod("getBukkitVersion"), - new MethodHandler() { - public Object handle(DummyServer server, Object[] args) { - return Versioning.getBukkitVersion(); - } - } - ); - methods.put( - Server.class.getMethod("getLogger"), - new MethodHandler() { - final Logger logger = Logger.getLogger(DummyServer.class.getCanonicalName()); - public Object handle(DummyServer server, Object[] args) { - return logger; - } - } - ); - methods.put( - Server.class.getMethod("getUnsafe"), - new MethodHandler() { - public Object handle(DummyServer server, Object[] args) { - return CraftMagicNumbers.INSTANCE; - } - } - ); - methods.put( - Server.class.getMethod("createBlockData", Material.class), - new MethodHandler() { - final Logger logger = Logger.getLogger(DummyServer.class.getCanonicalName()); - public Object handle(DummyServer server, Object[] args) { - return CraftBlockData.newData((Material) args[0], null); - } - } - ); - methods.put(Server.class.getMethod("getLootTable", NamespacedKey.class), - new MethodHandler() { - @Override - public Object handle(DummyServer server, Object[] args) { - NamespacedKey key = (NamespacedKey) args[0]; - return new CraftLootTable(key, AbstractTestingBase.LOOT_TABLE_REGISTRY.getLootTable(CraftNamespacedKey.toMinecraft(key))); - } - } - ); - Bukkit.setServer(Proxy.getProxyClass(Server.class.getClassLoader(), Server.class).asSubclass(Server.class).getConstructor(InvocationHandler.class).newInstance(new DummyServer())); - } catch (Throwable t) { - throw new Error(t); - } - } - - public static void setup() {} - - private DummyServer() {}; - - public Object invoke(Object proxy, Method method, Object[] args) { - MethodHandler handler = methods.get(method); - if (handler != null) { - return handler.handle(this, args); - } - throw new UnsupportedOperationException(String.valueOf(method)); - } -} diff --git a/src/test/java/org/bukkit/support/Matchers.java b/src/test/java/org/bukkit/support/Matchers.java deleted file mode 100644 index b190c6736..000000000 --- a/src/test/java/org/bukkit/support/Matchers.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.bukkit.support; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; - -public final class Matchers { - - private Matchers() {} - - public static Matcher sameHash(T value) { - return new SameHash(value); - } - - static class SameHash extends BaseMatcher { - private final int expected; - - SameHash(T object) { - expected = object.hashCode(); - } - - public boolean matches(Object item) { - return item.hashCode() == expected; - } - - public void describeTo(Description description) { - description.appendValue(expected); - } - } -} diff --git a/src/test/java/org/bukkit/support/Util.java b/src/test/java/org/bukkit/support/Util.java deleted file mode 100644 index 2f24d9a40..000000000 --- a/src/test/java/org/bukkit/support/Util.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.bukkit.support; - -import java.lang.reflect.Field; - -public class Util { - /* - public static T getInternalState(Object object, String fieldName) { - return getInternalState(object.getClass(), object, fieldName); - } - */ - - @SuppressWarnings("unchecked") - public static T getInternalState(Class clazz, Object object, String fieldName) { - Field field; - try { - field = clazz.getDeclaredField(fieldName); - } catch (SecurityException e) { - throw new RuntimeException("Not allowed to access " + clazz, e); - } catch (NoSuchFieldException e) { - throw new RuntimeException("Unable to find field " + fieldName, e); - } - - field.setAccessible(true); - try { - return (T) field.get(object); - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } - throw new RuntimeException("Unable to get internal value"); - } -}